text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { getEle } from "../../utility/dom/getEle"; import { getAllEle } from "../../utility/dom/getAllEle"; import { setCss } from "../../utility/dom/setCss"; import { addClass } from "../../utility/dom/addClass"; import { getAttr } from "../../utility/dom/getAttr"; import { removeClass } from "../../utility/dom/removeClass"; export interface ITabConfigProps { container?: string; dataSource?: ITabDataSource[]; type?: ITabTypeEffect; mouse?: ITabMouseEffect; defaultActiveKey?: number; tabBarGap?: number; tabBarStyle?: ITabBarStyle; tabBarLineStyle?: ITabBarLineStyle; animated?: boolean; onChange?: (activeKey: number | string) => void; onTabClick?: () => void; } export interface ITabDataSource { tabPaneTitle: { icon?: string, text?: string, }, tabPaneContent: { text?: string, }, }; export interface ITabBarStyle { 'background-color'?: string; color?: string; 'font-size'?: number; 'font-family'?: string; backgroundColorActive?: string; colorActive?: string; } export interface ITabBarLineStyle { 'background-color'?: string; height?: number; } export type ITabTypeEffect = 'line' | 'card'; export type ITabMouseEffect = 'mouseenter' | 'click'; export class Tab { public static defaultConfig = { container: 'body', dataSource: [ { tabPaneTitle: { text: '面板一', icon: '😂', }, tabPaneContent: { text: '内容区块一', }, }, { tabPaneTitle: { text: '面板二', icon: '😘', }, tabPaneContent: { text: '内容区块二', }, }, { tabPaneTitle: { text: '面板三', icon: '😍', }, tabPaneContent: { text: '内容区块三', }, } ], type: 'line', mouse: 'mouseenter', defaultActiveKey: 1, tabBarGap: 8, tabBarStyle: { 'background-color': '#fafafa', color: '#5a5a5a', 'font-size': 14, backgroundColorActive: '#fff', colorActive: '#1890ff', }, tabBarLineStyle: { 'background-color': '#1890ff', height: 3, }, animated: true, onTabClick: () => void 0, onChange: (_activeKey: string | number) => void 0, } public constructor( config: ITabConfigProps, ) { this.__init(config); } private __init( config: ITabConfigProps, ): void { this.__initSettings(config); this.render(); } /** * 初始化配置项 * @param config 配置项 */ private __initSettings( config: ITabConfigProps, ): void { const { defaultConfig } = Tab; for (const key in config) { if (config.hasOwnProperty(key)) { const value = Reflect.get(config, key); Reflect.set(defaultConfig, key, value); } } } private render(): void { this.handleMount(); this.handleSetStyle(); this.handleMouse(); } /** * 挂载 */ private handleMount(): void { const { container, } = Tab.defaultConfig; const oContainer = getEle(container); if (oContainer) { const oTempDiv = document.createElement('div'); oTempDiv.innerHTML = this.handleCreateDOMTree(); oContainer.appendChild(oTempDiv); } else { throw new TypeError('Invalid container you have passed!'); } } /** * 初始化样式 */ private handleSetStyle(): void { const { tabBarGap, dataSource, tabBarStyle, tabBarLineStyle, container, } = Tab.defaultConfig; const oIconBoxArr = getAllEle('.yyg-nav-item-icon') as any; const oNavItem = getEle('.yyg-nav-item') as HTMLLIElement; let oStyle = getEle('style'); if (!oStyle) { const oHead = getEle('head') as HTMLHeadElement; oStyle = document.createElement('style'); oHead.appendChild(oStyle); } dataSource.forEach((item: ITabDataSource, index: number) => { if (item.tabPaneTitle.icon) { oIconBoxArr[index].innerHTML = item.tabPaneTitle.icon; setCss(oIconBoxArr[index], { flex: .6, 'text-align': 'right', }); } else { setCss(oIconBoxArr[index], { display: 'none', }); } }); oStyle.innerText += ` ${container} ul, li, p, h1, h2, h3 { margin: 0; padding: 0; } ${container} ul { list-style-type: none; } ${container} .yyg-tabs-wrapper { width: 100%; height: 100%; } ${container} .yyg-tabs-main { box-sizing: border-box; padding: 10px 0; } ${container} .yyg-tabs-main-bar { } ${container} .yyg-bar-nav-container { box-sizing: border-box; height: 50px; border-bottom: 1px solid #ccc; line-height: 47px; } ${container} .yyg-nav-list-box { display: flex; } ${container} .yyg-nav-item { flex: 1; display: flex; margin-right: ${tabBarGap}px; text-align: center; color: ${tabBarStyle['color'] || '#5a5a5a'}; font-size: ${tabBarStyle['font-size'] || 14}px; cursor: pointer; user-select: none; transition: all .3s ease-in; } /* bar-item */ ${container} .yyg-nav-item-icon { flex: ${0}; font-size: 12px; } .yyg-nav-item-text { flex: 1; } ${container} .yyg-nav-line-box { width: ${oNavItem.clientWidth / dataSource.length - tabBarGap}px; height: ${tabBarLineStyle['height'] || 3}px; background-color: ${tabBarLineStyle['background-color'] || '#1890ff'}; transition: all .3s ease-in; } /* 内容框 */ ${container} .yyg-tabs-main-bar { } ${container} .yyg-content-tabpane-container { overflow: hidden; box-sizing: border-box; padding: 5px 0; } ${container} .yyg-tabpane-list { width: ${dataSource.length * 100}%; } ${container} .yyg-tabpane-item { float: left; width: ${100 / dataSource.length}%; } /* type */ ${container} .yyg-nav-item-line { } ${container} .yyg-nav-item-card { border: 1px solid #e8e8e8; border-bottom: 0; border-radius: 4px 4px 0 0; background-color: ${tabBarStyle['background-color'] || '#fafafa'}; } /* 活动样式类 */ ${container} .yyg-nav-item-card-active { background-color: ${tabBarStyle['backgroundColorActive'] || '#fff'}; color: ${tabBarStyle['colorActive'] || '#1890ff'}; } ${container} .yyg-nav-item-line-active { color: ${tabBarStyle['colorActive'] || '#1890ff'}; } /* animated */ ${container} .yyg-tabpane-list-animated { transition: all .2s ease-in-out; } `; } /** * 鼠标配置项相关 */ private handleMouse(): void { const { mouse, tabBarGap, type, defaultActiveKey, animated, onTabClick, onChange, } = Tab.defaultConfig; const paneList = getEle('.yyg-tabpane-list') as HTMLUListElement; // TODO: 解决滚动距离bug, 使用`paneList`父级宽度 const paneListParent = getEle('.yyg-content-tabpane-container') as HTMLDivElement; const barItems = getAllEle('.yyg-nav-item') as NodeListOf<HTMLLIElement>; const lineBox = getEle('.yyg-nav-line-box'); // TODO: 判断不同type不同active样式 const whichTypeActiveClass: string = type === 'line' ? 'yyg-nav-item-line-active' : 'yyg-nav-item-card-active'; // TODO: 是否具有动画效果 const whichAnimatedClass: string = animated ? 'yyg-tabpane-list-animated' : 'yyg-tabpane-list-noanimated'; lineBox && setCss(lineBox, { transform: `translateX(${ lineBox.clientWidth * (defaultActiveKey - 1) + tabBarGap * (defaultActiveKey - 1) }px)`, }); addClass( barItems[defaultActiveKey - 1], whichTypeActiveClass ) setCss(paneList, { transform: `translateX(${-(defaultActiveKey - 1) * paneListParent.clientWidth}px)`, }) addClass(paneList, whichAnimatedClass); barItems.forEach((item: HTMLLIElement, index: number) => { item.addEventListener(mouse, () => { // 钩子 onTabClick && onTabClick(); onChange && onChange( getAttr(item, 'data-id') as string, ); barItems.forEach((ite: HTMLLIElement) => { removeClass(ite, whichTypeActiveClass); }) lineBox && setCss(lineBox, { transform: `translateX(${ lineBox.clientWidth * index + tabBarGap * index }px)`, }); addClass(item, whichTypeActiveClass) setCss(paneList, { transform: `translateX(${-index * paneListParent.clientWidth}px)`, }); }); }); } private handleCreateDOMTree(): string { const { dataSource, type, } = Tab.defaultConfig; let navStr: string = ''; let contentStr: string = ''; if (dataSource.length !== 0) { dataSource.forEach((item: ITabDataSource, index: number) => { navStr += ` <li class="yyg-nav-item ${ type === 'line' ? 'yyg-nav-item-line' : 'yyg-nav-item-card' }" data-id=${index + 1}> <div class="yyg-nav-item-icon"> ${item.tabPaneTitle.icon} </div> <div class="yyg-nav-item-text"> ${item.tabPaneTitle.text} </div> </li> `; contentStr += ` <li class="yyg-tabpane-item" data-id=${index + 1}> <div class="yyg-tabpane-item-content"> ${item.tabPaneContent.text} </div> </li> `; }); } const navBottomLineStr: string = ` <div class="yyg-nav-line-box"> <span class="yyg-nav-line"></span> </div> `; const html: string = ` <div class="yyg-tabs-wrapper"> <div class="yyg-tabs-main"> <!-- 导航容器 --> <div class="yyg-tabs-main-bar"> <div class="yyg-bar-nav-container"> <ul class="yyg-nav-list-box"> ${navStr} </ul> ${type === 'line' ? navBottomLineStr : ''} </div> </div> <!-- 内容容器 --> <div class="yyg-tabs-main-content"> <div class="yyg-content-tabpane-container"> <ul class="yyg-tabpane-list"> ${contentStr} </ul> </div> </div> </div> </div> `; return html; } }
the_stack
import { Injectable } from '@angular/core'; import { CoreSyncBaseProvider } from '@classes/base-sync'; import { CoreComments, CoreCommentsProvider } from './comments'; import { CoreEvents } from '@singletons/events'; import { makeSingleton, Translate } from '@singletons'; import { CoreCommentsOffline } from './comments-offline'; import { CoreSites } from '@services/sites'; import { CoreApp } from '@services/app'; import { CoreUtils } from '@services/utils/utils'; import { CoreNetworkError } from '@classes/errors/network-error'; import { CoreCommentsDBRecord, CoreCommentsDeletedDBRecord } from './database/comments'; /** * Service to sync omments. */ @Injectable( { providedIn: 'root' }) export class CoreCommentsSyncProvider extends CoreSyncBaseProvider<CoreCommentsSyncResult> { static readonly AUTO_SYNCED = 'core_comments_autom_synced'; constructor() { super('CoreCommentsSync'); } /** * Try to synchronize all the comments in a certain site or in all sites. * * @param siteId Site ID to sync. If not defined, sync all sites. * @param force Wether to force sync not depending on last execution. * @return Promise resolved if sync is successful, rejected if sync fails. */ syncAllComments(siteId?: string, force?: boolean): Promise<void> { return this.syncOnSites('all comments', this.syncAllCommentsFunc.bind(this, !!force), siteId); } /** * Synchronize all the comments in a certain site * * @param force Wether to force sync not depending on last execution. * @param siteId Site ID to sync. * @return Promise resolved if sync is successful, rejected if sync fails. */ private async syncAllCommentsFunc(force: boolean, siteId: string): Promise<void> { const comments = await CoreCommentsOffline.getAllComments(siteId); const commentsUnique: { [syncId: string]: (CoreCommentsDBRecord | CoreCommentsDeletedDBRecord) } = {}; // Get Unique array. comments.forEach((comment) => { const syncId = this.getSyncId( comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, ); commentsUnique[syncId] = comment; }); // Sync all courses. const promises = Object.keys(commentsUnique).map(async (key) => { const comment = commentsUnique[key]; const result = await (force ? this.syncComments( comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, siteId, ) : this.syncCommentsIfNeeded( comment.contextlevel, comment.instanceid, comment.component, comment.itemid, comment.area, siteId, )); if (typeof result != 'undefined') { // Sync successful, send event. CoreEvents.trigger(CoreCommentsSyncProvider.AUTO_SYNCED, { contextLevel: comment.contextlevel, instanceId: comment.instanceid, componentName: comment.component, itemId: comment.itemid, area: comment.area, warnings: result.warnings, }, siteId); } }); await Promise.all(promises); } /** * Sync course comments only if a certain time has passed since the last time. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the comments are synced or if they don't need to be synced. */ private async syncCommentsIfNeeded( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<CoreCommentsSyncResult | undefined> { const syncId = this.getSyncId(contextLevel, instanceId, component, itemId, area); const needed = await this.isSyncNeeded(syncId, siteId); if (needed) { return this.syncComments(contextLevel, instanceId, component, itemId, area, siteId); } } /** * Synchronize comments in a particular area. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if sync is successful, rejected otherwise. */ syncComments( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId?: string, ): Promise<CoreCommentsSyncResult> { siteId = siteId || CoreSites.getCurrentSiteId(); const syncId = this.getSyncId(contextLevel, instanceId, component, itemId, area); if (this.isSyncing(syncId, siteId)) { // There's already a sync ongoing for comments, return the promise. return this.getOngoingSync(syncId, siteId)!; } this.logger.debug('Try to sync comments ' + syncId + ' in site ' + siteId); const syncPromise = this.performSyncComments(contextLevel, instanceId, component, itemId, area, siteId); return this.addOngoingSync(syncId, syncPromise, siteId); } /** * Performs the syncronization of comments in a particular area. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if sync is successful, rejected otherwise. */ private async performSyncComments( contextLevel: string, instanceId: number, component: string, itemId: number, area: string = '', siteId: string, ): Promise<CoreCommentsSyncResult> { const result: CoreCommentsSyncResult = { warnings: [], updated: false, }; // Get offline comments to be sent. const comments = await CoreCommentsOffline.getComments(contextLevel, instanceId, component, itemId, area, siteId); if (!comments.length) { // Nothing to sync. return result; } if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } const errors: string[] = []; const promises: Promise<void>[] = []; const deleteCommentIds: number[] = []; let countChange = 0; comments.forEach((comment) => { if ('deleted' in comment) { deleteCommentIds.push(comment.commentid); } else { promises.push(CoreComments.addCommentOnline( comment.content, contextLevel, instanceId, component, itemId, area, siteId, ).then(() => { countChange++; return CoreCommentsOffline.removeComment(contextLevel, instanceId, component, itemId, area, siteId); })); } }); if (deleteCommentIds.length > 0) { promises.push(CoreComments.deleteCommentsOnline( deleteCommentIds, contextLevel, instanceId, component, itemId, area, siteId, ).then(() => { countChange--; return CoreCommentsOffline.removeDeletedComments( contextLevel, instanceId, component, itemId, area, siteId, ); })); } // Send the comments. try { await Promise.all(promises); result.updated = true; CoreEvents.trigger(CoreCommentsProvider.COMMENTS_COUNT_CHANGED_EVENT, { contextLevel: contextLevel, instanceId: instanceId, component, itemId: itemId, area: area, countChange: countChange, }, CoreSites.getCurrentSiteId()); // Fetch the comments from server to be sure they're up to date. await CoreUtils.ignoreErrors( CoreComments.invalidateCommentsData(contextLevel, instanceId, component, itemId, area, siteId), ); await CoreUtils.ignoreErrors( CoreComments.getComments(contextLevel, instanceId, component, itemId, area, 0, siteId), ); } catch (error) { if (CoreUtils.isWebServiceError(error)) { // It's a WebService error, this means the user cannot send comments. errors.push(error.message); } else { // Not a WebService error, reject the synchronization to try again. throw error; } } if (errors && errors.length) { errors.forEach((error) => { result.warnings.push(Translate.instant('core.comments.warningcommentsnotsent', { error: error, })); }); } // All done, return the warnings. return result; } /** * Get the ID of a comments sync. * * @param contextLevel Contextlevel system, course, user... * @param instanceId The Instance id of item associated with the context level. * @param component Component name. * @param itemId Associated id. * @param area String comment area. Default empty. * @return Sync ID. */ protected getSyncId(contextLevel: string, instanceId: number, component: string, itemId: number, area: string = ''): string { return contextLevel + '#' + instanceId + '#' + component + '#' + itemId + '#' + area; } } export const CoreCommentsSync = makeSingleton(CoreCommentsSyncProvider); export type CoreCommentsSyncResult = { warnings: string[]; // List of warnings. updated: boolean; // Whether some data was sent to the server or offline data was updated. }; /** * Data passed to AUTO_SYNCED event. */ export type CoreCommentsSyncAutoSyncData = { contextLevel: string; instanceId: number; componentName: string; itemId: number; area: string; warnings: string[]; };
the_stack
import { randomBytes } from 'crypto'; import { validator } from '@liskhq/lisk-validator'; import { codec } from '@liskhq/lisk-codec'; import { getRandomBytes, hash } from '@liskhq/lisk-cryptography'; import { Transaction, transactionSchema } from '@liskhq/lisk-chain'; import { RegisterAsset } from '../../../../src/modules/keys/register_asset'; import * as fixtures from './fixtures.json'; import { keysSchema } from '../../../../src/modules/keys/schemas'; import * as testing from '../../../../src/testing'; import { KeysModule, TokenModule } from '../../../../src'; describe('register asset', () => { let decodedMultiSignature: any; let validTestTransaction: any; let multisignatureSender: any; let convertedAccount: any; let stateStore: any; let storeAccountGetStub: jest.SpyInstance; let storeAccountSetStub: jest.SpyInstance; let registerAsset: RegisterAsset; const defaultTestCase = fixtures.testCases[0]; beforeEach(() => { registerAsset = new RegisterAsset(); const buffer = Buffer.from(defaultTestCase.output.transaction, 'hex'); const id = hash(buffer); const decodedBaseTransaction = codec.decode<Transaction>(transactionSchema, buffer); const decodedAsset = codec.decode<any>(registerAsset.schema, decodedBaseTransaction.asset); decodedMultiSignature = { ...decodedBaseTransaction, asset: decodedAsset, id, }; validTestTransaction = new Transaction(decodedMultiSignature); multisignatureSender = testing.fixtures.createDefaultAccount([KeysModule, TokenModule], { address: Buffer.from(defaultTestCase.input.account.address, 'hex'), token: { balance: BigInt('94378900000') }, }); convertedAccount = testing.fixtures.createDefaultAccount([KeysModule, TokenModule], { address: Buffer.from(defaultTestCase.input.account.address, 'hex'), token: { balance: BigInt('94378900000') }, keys: { ...validTestTransaction.asset, }, }); stateStore = new testing.mocks.StateStoreMock({ accounts: [multisignatureSender], }); storeAccountGetStub = jest.spyOn(stateStore.account, 'get'); storeAccountSetStub = jest.spyOn(stateStore.account, 'set'); }); describe('validateSchema', () => { it('should fail validation if asset has numberOfSignatures > 64', () => { const asset = { numberOfSignatures: 100, mandatoryKeys: [getRandomBytes(32)], optionalKeys: [getRandomBytes(32)], } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must be <= 64'); }); it('should fail validation if asset has numberOfSignatures < 1', () => { const asset = { numberOfSignatures: 0, mandatoryKeys: [getRandomBytes(32)], optionalKeys: [getRandomBytes(32)], } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must be >= 1'); }); it('should fail validation if asset has more than 64 mandatory keys', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), optionalKeys: [], } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must NOT have more than 64 items'); }); it('should fail validation if asset mandatory keys contains items with length bigger than 32', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [...Array(1).keys()].map(() => getRandomBytes(64)), optionalKeys: [], } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('maxLength exceeded'); }); it('should fail validation if asset mandatory keys contains items with length smaller than 32', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [...Array(1).keys()].map(() => getRandomBytes(10)), optionalKeys: [], } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('minLength not satisfied'); }); it('should fail validation if asset optional keys contains items with length bigger than 32', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [], optionalKeys: [...Array(1).keys()].map(() => getRandomBytes(64)), } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('maxLength exceeded'); }); it('should fail validation if asset optional keys contains items with length smaller than 32', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [], optionalKeys: [...Array(1).keys()].map(() => getRandomBytes(31)), } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('minLength not satisfied'); }); it('should fail validation if asset has more than 64 optional keys', () => { const asset = { numberOfSignatures: 2, mandatoryKeys: [], optionalKeys: [...Array(65).keys()].map(() => getRandomBytes(32)), } as any; const errors = validator.validate(keysSchema, asset); expect(errors).toHaveLength(1); expect(errors[0].message).toInclude('must NOT have more than 64 items'); }); }); describe('validate', () => { it('should not throw errors for valid asset', () => { const context = testing.createValidateAssetContext({ asset: validTestTransaction.asset, transaction: validTestTransaction, }); expect(() => registerAsset.validate(context)).not.toThrow(); }); it('should throw error when there are duplicated mandatory keys', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, mandatoryKeys: [ ...decodedMultiSignature.asset.mandatoryKeys, decodedMultiSignature.asset.mandatoryKeys[1], ], }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'MandatoryKeys contains duplicate public keys.', ); }); it('should throw error when there are duplicated optional keys', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, optionalKeys: [ ...decodedMultiSignature.asset.optionalKeys, decodedMultiSignature.asset.optionalKeys[1], ], }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'OptionalKeys contains duplicate public keys.', ); }); it('should throw error when numberOfSignatures is bigger than the count of all keys', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, numberOfSignatures: 5, }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'The numberOfSignatures is bigger than the count of Mandatory and Optional keys.', ); }); it('should throw error when numberOfSignatures is smaller than mandatory key count', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, numberOfSignatures: 1, }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'The numberOfSignatures needs to be equal or bigger than the number of Mandatory keys.', ); }); it('should throw error when mandatory and optional key sets are not disjointed', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, numberOfSignatures: 2, mandatoryKeys: [ Buffer.from('48e041ae61a32777c899c1f1b0a9588bdfe939030613277a39556518cc66d371', 'hex'), Buffer.from('483077a8b23208f2fd85dacec0fbb0b590befea0a1fcd76a5b43f33063aaa180', 'hex'), ], optionalKeys: [ Buffer.from('483077a8b23208f2fd85dacec0fbb0b590befea0a1fcd76a5b43f33063aaa180', 'hex'), ], }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'Invalid combination of Mandatory and Optional keys. Repeated keys across Mandatory and Optional were found.', ); }); it('should throw error when mandatory keys set is not sorted', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, numberOfSignatures: 2, mandatoryKeys: [ Buffer.from('48e041ae61a32777c899c1f1b0a9588bdfe939030613277a39556518cc66d371', 'hex'), Buffer.from('483077a8b23208f2fd85dacec0fbb0b590befea0a1fcd76a5b43f33063aaa180', 'hex'), ], }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'Mandatory keys should be sorted lexicographically.', ); }); it('should throw error when optional keys set is not sorted', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, numberOfSignatures: 2, optionalKeys: [ Buffer.from('48e041ae61a32777c899c1f1b0a9588bdfe939030613277a39556518cc66d371', 'hex'), Buffer.from('483077a8b23208f2fd85dacec0fbb0b590befea0a1fcd76a5b43f33063aaa180', 'hex'), ], }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'Optional keys should be sorted lexicographically.', ); }); it('should throw error when the number of optional and mandatory keys is more than 64', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, optionalKeys: [...Array(65).keys()].map(() => randomBytes(64)), mandatoryKeys: [...Array(65).keys()].map(() => randomBytes(64)), }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'The count of Mandatory and Optional keys should be between 1 and 64.', ); }); it('should throw error when the number of optional and mandatory keys is less than 1', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, optionalKeys: [], mandatoryKeys: [], numberOfSignatures: 0, }, }; const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'The count of Mandatory and Optional keys should be between 1 and 64.', ); }); it('should return error when number of mandatory, optional and sender keys do not match the number of signatures', () => { const invalidTransaction = { ...decodedMultiSignature, asset: { ...decodedMultiSignature.asset, }, signatures: [...decodedMultiSignature.signatures], }; invalidTransaction.signatures.pop(); const context = testing.createValidateAssetContext({ asset: invalidTransaction.asset, transaction: invalidTransaction, }); expect(() => registerAsset.validate(context)).toThrow( 'The number of mandatory, optional and sender keys should match the number of signatures', ); }); }); describe('apply', () => { it('should not throw when registering for first time', () => { const context = testing.createApplyAssetContext({ stateStore, asset: validTestTransaction.asset, transaction: validTestTransaction, }); expect(async () => registerAsset.apply(context)).not.toThrow(); }); it('should call state store get() with senderAddress and set() with address and updated account', async () => { const context = testing.createApplyAssetContext({ stateStore, asset: validTestTransaction.asset, transaction: validTestTransaction, }); await registerAsset.apply(context); expect(storeAccountGetStub).toHaveBeenCalledWith(validTestTransaction.senderAddress); expect(storeAccountSetStub).toHaveBeenCalledWith( multisignatureSender.address, convertedAccount, ); }); it('should throw error when account is already multisignature', async () => { const context = testing.createApplyAssetContext({ stateStore, asset: validTestTransaction.asset, transaction: validTestTransaction, }); storeAccountGetStub.mockReturnValue(convertedAccount); return expect(registerAsset.apply(context)).rejects.toStrictEqual( new Error('Register multisignature only allowed once per account.'), ); }); }); });
the_stack
import {launch, Request, SetCookie} from "puppeteer"; import * as url from "url"; import * as http from "http"; import {IncomingMessage} from "http"; import * as https from "https"; import * as HttpProxyAgent from 'http-proxy-agent'; import * as HttpsProxyAgent from 'https-proxy-agent'; import * as stream from "stream"; import * as util from "util"; import * as zlib from "zlib"; import {logger} from "../.."; // https://stackoverflow.com/questions/21491567/how-to-implement-a-writable-stream function BufferStream() { this.chunks = []; stream.Writable.call(this); } util.inherits(BufferStream, stream.Writable); BufferStream.prototype._write = function (chunk, encoding, done) { this.chunks.push(chunk); done(); }; BufferStream.prototype.toBuffer = function (): Buffer { return Buffer.concat(this.chunks); }; (async () => { const browser = await launch({ headless: false, devtools: true, // args: [ '--proxy-server=127.0.0.1:3000' ] }); const page = await browser.newPage(); await page.setViewport({width: 1920, height: 1080}); await page.setRequestInterception(true); page.on("request", async (req: Request) => { if (req["_interceptionHandled"]) { logger.warn(`request(${req.url()}) handled`); return; } else if (req.url().startsWith("http")) { if (!req.isNavigationRequest()) { const responseCache = await page.evaluate(url => { const cache = localStorage.getItem(url); if (cache) { if (parseInt(cache.substring(0, cache.indexOf("\n"))) <= new Date().getTime()) { // 已过期 localStorage.removeItem(url); } else { return cache; } } }, req.url()).catch(err => {}); if (responseCache) { let [expires, statusCodeStr, bodyBase64] = responseCache.split("\n"); const statusCode = +statusCodeStr; const body = Buffer.from(bodyBase64, "base64"); return req.respond({ status: statusCode, headers: { cache: "from-local-storage" }, body: body }); } } const options = url.parse(req.url()); options["method"] = req.method(); options["headers"] = req.headers() || {}; // 解决一些请求(例如 https://www.google.com/)响应头既不包含 content-length,又不包含 transfer-encoding:chunked 的情况 // 支持 br 的node版本较高,所以这里不启用br options["headers"]["accept-encoding"] = "identity, gzip, deflate"; const resHandler = (proxyRes: IncomingMessage) => { let pipes: stream = proxyRes; const contentEncodings = (proxyRes.headers["content-encoding"] || "").split(/, ?/).filter(item => item != "").reverse(); for (let contentEncoding of contentEncodings) { switch (contentEncoding) { case "gzip": pipes = pipes.pipe(zlib.createGunzip()); break; // case "br": // pipes = pipes.pipe(zlib.createBrotliDecompress()); // break; case "deflate": pipes = pipes.pipe(zlib.createInflate()); break; } } const bodyStream = new BufferStream(); const onBodyEnd = () => { const statusCode = proxyRes.statusCode; const headers = proxyRes.headers; for (let name in headers) { const value = headers[name]; if (name == "set-cookie") { if (value.length == 0) { headers[name] = ("" + value[0]) as any; } else { const setCookies: SetCookie[] = []; for (let item of value) { const setCookie: SetCookie = { name: null, value: null }; item.split("; ").forEach((keyVal, keyValI) => { const eqI = keyVal.indexOf("="); let key; let value; if (eqI > -1) { key = keyVal.substring(0, eqI); value = keyVal.substring(eqI + 1); } else { key = keyVal; value = ""; } const lowerKey = key.toLowerCase(); if (keyValI == 0) { setCookie.name = key; setCookie.value = value; } else if (lowerKey == "expires") { const expires = new Date(value).getTime(); if (!isNaN(expires)) { setCookie.expires = +(expires / 1000).toFixed(0); } } else if (lowerKey == "max-age") { const expires = +value; if (!isNaN(expires)) { setCookie.expires = expires; } } else if (lowerKey == "path" || key == "domain") { setCookie[lowerKey] = value; } else if (lowerKey == "samesite") { setCookie.httpOnly = true; } else if (lowerKey == "httponly") { setCookie.httpOnly = true; } else if (lowerKey == "secure") { setCookie.secure = true; } }); setCookies.push(setCookie); } page.setCookie(...setCookies).catch(err => {}); delete headers[name]; } } else if (typeof value != "string") { if (value instanceof Array) { headers[name] = JSON.stringify(value); } else { headers[name] = "" + value; } } } const body = bodyStream.toBuffer(); req.respond({ status: statusCode, headers: headers as any, body: body }).catch(err => {}); // 如果有 Expires ,则保存缓存 const expires = new Date(headers.expires).getTime(); if (expires > new Date().getTime()) { const bodyBase64 = body.toString("base64"); const responseCache = `${expires}\n${statusCode}\n${bodyBase64}`; page.evaluate((url, responseCache) => { localStorage.setItem(url, responseCache); }, req.url(), responseCache).catch(err => {}); } proxyRes.destroy(); }; let contentLength = +proxyRes.headers["content-length"]; isNaN(contentLength) && (contentLength = -1); if (contentLength == 0) { onBodyEnd(); } else { if (contentLength > 0) { let receiveLen = 0; proxyRes.on("data", chunk => { receiveLen += chunk.length; if (receiveLen >= contentLength) { setTimeout(() => { proxyRes.emit("close"); }, 0); } }); } else { // transfer-encoding:chunked // const transferEncoding = proxyRes.headers["transfer-encoding"]; // transferEncoding == null; } pipes.pipe(bodyStream); pipes.once("close", onBodyEnd); } }; const proxy = "http://127.0.0.1:2007"; let proxyReq; if (options.protocol == "http:") { options["agent"] = new HttpProxyAgent(proxy); proxyReq = http.request(options, resHandler); } else { options["agent"] = new HttpsProxyAgent(proxy); proxyReq = https.request(options, resHandler); } const postData = req.postData(); if (postData) { proxyReq.write(postData); } proxyReq.end(); } else { req.continue().catch(err => {}); } }); await page.goto("https://www.bilibili.com/"); // await page.goto("https://www.google.com/"); console.log(); })();
the_stack
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Rx'; declare var plugins: any; declare var document: any; @Injectable() export class JPushService { private jPushPlugin: any; warnText: string = '没有找到 jPushPlugin 对象 \n也许你是在浏览器环境下运行或者没有正确安装插件; \n如果没有在Platform 的 ready 方法中调用,也会出现这样的情况。\n了解:http://ionicframework.com/docs/v2/api/platform/Platform/'; constructor() { this.initJPushPlugin() } wrapEventObservable(event: string): Observable<any> { return new Observable((observer: any) => { document.addEventListener(event, observer.next.bind(observer), false); return () => document.removeEventListener(event, observer.next.bind(observer), false); }); } initJPushPlugin() { if ((<any>window).plugins && (<any>window).plugins.jPushPlugin) { this.jPushPlugin = (<any>window).plugins.jPushPlugin } else if ((<any>window).JPush) { this.jPushPlugin = (<any>window).JPush } else { this.jPushPlugin = null } } setDebugMode(debug: boolean) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setDebugMode(debug); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } startJPushSDK() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.startJPushSDK(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } init() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.init(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } stopPush() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.stopPush(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } resumePush() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.resumePush(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } getRegistrationID() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.getRegistrationID((id: any) => { if (id) { resolve(id) } else { reject('获取ID失败') } }) } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } getUserNotificationSettings() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.getUserNotificationSettings((result: any) => { if (result === 0) { reject(result) } else { resolve(result) } }) } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } setLatestNotificationNum(num = 5) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setLatestNotificationNum(num); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } isPushStopped() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.isPushStopped((result: any) => { resolve(result) }) } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param tags * @param alias * @returns {Promise<T>} */ setTagsWithAlias(tags: Array<any>, alias: string) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setTagsWithAlias(tags, alias); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param data * @returns {Promise<T>} */ setTags(data: string[] | { sequence: number; tags: string[] }) { this.initJPushPlugin(); if (Array.isArray(data)) { return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setTags(data); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } else if (typeof data === 'object') { return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setTags( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } } addTags(data: { sequence: number; tags: string[] }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.addTags( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } deleteTags(data: { sequence: number; tags: string[] }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.deleteTags( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } cleanTags(data: { sequence: number }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.cleanTags( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } getAllTags(data: { sequence: number }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.getAllTags( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } checkTagBindState(data: { sequence: number, tag: string }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.checkTagBindState( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param alias * @returns {Promise<T>} */ setAlias(alias: string | { sequence: number; alias: string }) { this.initJPushPlugin(); if (typeof alias === 'string') { return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setAlias(alias); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } else if (typeof alias === 'object') { return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setAlias( alias, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } } deleteAlias(data: { sequence: number }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.deleteAlias( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } getAlias(data: { sequence: number }) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.getAlias( data, (res: any) => resolve(res), (error: any) => reject(error) ); } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param value * @returns {Promise<T>} */ setBadge(value: number) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setBadge(value); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } reSetBadge() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.reSetBadge(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } clearAllLocalNotifications() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.clearAllLocalNotifications(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param value * @returns {Promise<T>} */ setApplicationIconBadgeNumber(value: number) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setApplicationIconBadgeNumber(value); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } getApplicationIconBadgeNumber() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.getApplicationIconBadgeNumber((num: any) => { resolve(num) }) } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } setPushTime(days: number | null[], startHour: number, endHour: number) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setPushTime(days, startHour, endHour); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } setSilenceTime(startHour: number, startMinute: number, endHour: number, endMinute: number) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.setSilenceTime(startHour, startMinute, endHour, endMinute); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @param id * @returns {Promise<T>} */ clearNotificationById(id: number) { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.clearNotificationById(id); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } clearAllNotification() { this.initJPushPlugin(); return new Promise((resolve, reject) => { if (this.jPushPlugin) { this.jPushPlugin.clearAllNotification(); resolve('ok') } else { console.warn(this.warnText); reject('没有找到 jPushPlugin'); } }) } /** * * @returns {Observable<any>} */ openNotification() { return this.wrapEventObservable('jpush.openNotification'); } /** * * @returns {Observable<any>} */ receiveNotification() { return this.wrapEventObservable('jpush.receiveNotification'); } /** * * @returns {Observable<any>} */ receiveMessage() { return this.wrapEventObservable('jpush.receiveMessage'); } backgroundNotification() { return this.wrapEventObservable('jpush.backgroundNotification'); } receiveRegistrationId() { return this.wrapEventObservable('jpush.receiveRegistrationId'); } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [sso-directory](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsssodirectory.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class SsoDirectory extends PolicyStatement { public servicePrefix = 'sso-directory'; /** * Statement provider for service [sso-directory](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsssodirectory.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to add a member to a group in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toAddMemberToGroup() { return this.to('AddMemberToGroup'); } /** * Grants permission to complete the creation process of a virtual MFA device * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCompleteVirtualMfaDeviceRegistration() { return this.to('CompleteVirtualMfaDeviceRegistration'); } /** * Grants permission to complete the registration process of a WebAuthn device * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCompleteWebAuthnDeviceRegistration() { return this.to('CompleteWebAuthnDeviceRegistration'); } /** * Grants permission to create an alias for the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateAlias() { return this.to('CreateAlias'); } /** * Grants permission to create a bearer token for a given provisioning tenant * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateBearerToken() { return this.to('CreateBearerToken'); } /** * Grants permission to create an External Identity Provider configuration for the directory * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateExternalIdPConfigurationForDirectory() { return this.to('CreateExternalIdPConfigurationForDirectory'); } /** * Grants permission to create a group in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateGroup() { return this.to('CreateGroup'); } /** * Grants permission to create a provisioning tenant for a given directory * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateProvisioningTenant() { return this.to('CreateProvisioningTenant'); } /** * Grants permission to create a user in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toCreateUser() { return this.to('CreateUser'); } /** * Grants permission to delete a bearer token * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteBearerToken() { return this.to('DeleteBearerToken'); } /** * Grants permission to delete the given external IdP certificate * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteExternalIdPCertificate() { return this.to('DeleteExternalIdPCertificate'); } /** * Grants permission to delete an External Identity Provider configuration associated with the directory * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteExternalIdPConfigurationForDirectory() { return this.to('DeleteExternalIdPConfigurationForDirectory'); } /** * Grants permission to delete a group from the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteGroup() { return this.to('DeleteGroup'); } /** * Grants permission to delete a MFA device by device name for a given user * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteMfaDeviceForUser() { return this.to('DeleteMfaDeviceForUser'); } /** * Grants permission to delete the provisioning tenant * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteProvisioningTenant() { return this.to('DeleteProvisioningTenant'); } /** * Grants permission to delete a user from the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDeleteUser() { return this.to('DeleteUser'); } /** * Grants permission to retrieve information about the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeDirectory() { return this.to('DescribeDirectory'); } /** * Grants permission to query the group data, not including user and group members * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeGroup() { return this.to('DescribeGroup'); } /** * Grants permission to retrieve information about groups from the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeGroups() { return this.to('DescribeGroups'); } /** * Grants permission to describes the provisioning tenant * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeProvisioningTenant() { return this.to('DescribeProvisioningTenant'); } /** * Grants permission to retrieve information about a user from the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeUser() { return this.to('DescribeUser'); } /** * Grants permission to describe user with a valid unique attribute represented for the user * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeUserByUniqueAttribute() { return this.to('DescribeUserByUniqueAttribute'); } /** * Grants permission to retrieve information about user from the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDescribeUsers() { return this.to('DescribeUsers'); } /** * Grants permission to disable authentication of end users with an External Identity Provider * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDisableExternalIdPConfigurationForDirectory() { return this.to('DisableExternalIdPConfigurationForDirectory'); } /** * Grants permission to deactivate a user in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toDisableUser() { return this.to('DisableUser'); } /** * Grants permission to enable authentication of end users with an External Identity Provider * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toEnableExternalIdPConfigurationForDirectory() { return this.to('EnableExternalIdPConfigurationForDirectory'); } /** * Grants permission to activate user in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toEnableUser() { return this.to('EnableUser'); } /** * Grants permission to retrieve the AWS SSO Service Provider configurations for the directory * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toGetAWSSPConfigurationForDirectory() { return this.to('GetAWSSPConfigurationForDirectory'); } /** * (Deprecated) Grants permission to get UserPool Info * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toGetUserPoolInfo() { return this.to('GetUserPoolInfo'); } /** * Grants permission to import the IdP certificate used for verifying external IdP responses * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toImportExternalIdPCertificate() { return this.to('ImportExternalIdPCertificate'); } /** * Grants permission to check if a member is a part of the group in the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toIsMemberInGroup() { return this.to('IsMemberInGroup'); } /** * Grants permission to list bearer tokens for a given provisioning tenant * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListBearerTokens() { return this.to('ListBearerTokens'); } /** * Grants permission to list the external IdP certificates of a given directory and IdP * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListExternalIdPCertificates() { return this.to('ListExternalIdPCertificates'); } /** * Grants permission to list all the External Identity Provider configurations created for the directory * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListExternalIdPConfigurationsForDirectory() { return this.to('ListExternalIdPConfigurationsForDirectory'); } /** * Grants permission to list groups of the target member * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListGroupsForMember() { return this.to('ListGroupsForMember'); } /** * Grants permission to list groups for a user from the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListGroupsForUser() { return this.to('ListGroupsForUser'); } /** * Grants permission to retrieve all members that are part of a group in the directory that AWS SSO provides by default * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListMembersInGroup() { return this.to('ListMembersInGroup'); } /** * Grants permission to list all active MFA devices and their MFA device metadata for a user * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListMfaDevicesForUser() { return this.to('ListMfaDevicesForUser'); } /** * Grants permission to list provisioning tenants for a given directory * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toListProvisioningTenants() { return this.to('ListProvisioningTenants'); } /** * Grants permission to remove a member that is part of a group in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toRemoveMemberFromGroup() { return this.to('RemoveMemberFromGroup'); } /** * Grants permission to search for groups within the associated directory * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toSearchGroups() { return this.to('SearchGroups'); } /** * Grants permission to search for users within the associated directory * * Access Level: Read * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toSearchUsers() { return this.to('SearchUsers'); } /** * Grants permission to begin the creation process of virtual mfa device * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toStartVirtualMfaDeviceRegistration() { return this.to('StartVirtualMfaDeviceRegistration'); } /** * Grants permission to begin the registration process of a WebAuthn device * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toStartWebAuthnDeviceRegistration() { return this.to('StartWebAuthnDeviceRegistration'); } /** * Grants permission to update an External Identity Provider configuration associated with the directory * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateExternalIdPConfigurationForDirectory() { return this.to('UpdateExternalIdPConfigurationForDirectory'); } /** * Grants permission to update information about a group in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateGroup() { return this.to('UpdateGroup'); } /** * Grants permission to update group display name update group display name response * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateGroupDisplayName() { return this.to('UpdateGroupDisplayName'); } /** * Grants permission to update MFA device information * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateMfaDeviceForUser() { return this.to('UpdateMfaDeviceForUser'); } /** * Grants permission to update a password by sending password reset link via email or generating one time password for a user in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdatePassword() { return this.to('UpdatePassword'); } /** * Grants permission to update user information in the directory that AWS SSO provides by default * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateUser() { return this.to('UpdateUser'); } /** * Grants permission to update user name update user name response * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toUpdateUserName() { return this.to('UpdateUserName'); } /** * Grants permission to verify an email address of an User * * Access Level: Write * * https://docs.aws.amazon.com/singlesignon/latest/userguide/iam-auth-access-using-id-policies.html#policyexample */ public toVerifyEmail() { return this.to('VerifyEmail'); } protected accessLevelList: AccessLevelList = { "Write": [ "AddMemberToGroup", "CompleteVirtualMfaDeviceRegistration", "CompleteWebAuthnDeviceRegistration", "CreateAlias", "CreateBearerToken", "CreateExternalIdPConfigurationForDirectory", "CreateGroup", "CreateProvisioningTenant", "CreateUser", "DeleteBearerToken", "DeleteExternalIdPCertificate", "DeleteExternalIdPConfigurationForDirectory", "DeleteGroup", "DeleteMfaDeviceForUser", "DeleteProvisioningTenant", "DeleteUser", "DisableExternalIdPConfigurationForDirectory", "DisableUser", "EnableExternalIdPConfigurationForDirectory", "EnableUser", "ImportExternalIdPCertificate", "RemoveMemberFromGroup", "StartVirtualMfaDeviceRegistration", "StartWebAuthnDeviceRegistration", "UpdateExternalIdPConfigurationForDirectory", "UpdateGroup", "UpdateGroupDisplayName", "UpdateMfaDeviceForUser", "UpdatePassword", "UpdateUser", "UpdateUserName", "VerifyEmail" ], "Read": [ "DescribeDirectory", "DescribeGroup", "DescribeGroups", "DescribeProvisioningTenant", "DescribeUser", "DescribeUserByUniqueAttribute", "DescribeUsers", "GetAWSSPConfigurationForDirectory", "GetUserPoolInfo", "IsMemberInGroup", "ListBearerTokens", "ListExternalIdPCertificates", "ListExternalIdPConfigurationsForDirectory", "ListGroupsForMember", "ListGroupsForUser", "ListMembersInGroup", "ListMfaDevicesForUser", "ListProvisioningTenants", "SearchGroups", "SearchUsers" ] }; }
the_stack
import { CommonModule } from '@angular/common'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, fakeAsync, inject, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserModule, By } from '@angular/platform-browser'; import { Router } from '@angular/router'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { Observable, of as observableOf } from 'rxjs'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model'; import { RemoteData } from '../../core/data/remote-data'; import { RequestService } from '../../core/data/request.service'; import { EPersonDataService } from '../../core/eperson/eperson-data.service'; import { GroupDataService } from '../../core/eperson/group-data.service'; import { EPerson } from '../../core/eperson/models/eperson.model'; import { Group } from '../../core/eperson/models/group.model'; import { RouteService } from '../../core/services/route.service'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { PageInfo } from '../../core/shared/page-info.model'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { GroupMock, GroupMock2 } from '../../shared/testing/group-mock'; import { GroupsRegistryComponent } from './groups-registry.component'; import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { TranslateLoaderMock } from '../../shared/testing/translate-loader.mock'; import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub'; import { routeServiceStub } from '../../shared/testing/route-service.stub'; import { RouterMock } from '../../shared/mocks/router.mock'; import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; describe('GroupRegistryComponent', () => { let component: GroupsRegistryComponent; let fixture: ComponentFixture<GroupsRegistryComponent>; let ePersonDataServiceStub: any; let groupsDataServiceStub: any; let dsoDataServiceStub: any; let authorizationService: AuthorizationDataService; let mockGroups; let mockEPeople; let paginationService; /** * Set authorizationService.isAuthorized to return the following values. * @param isAdmin whether or not the current user is an admin. * @param canManageGroup whether or not the current user can manage all groups. */ const setIsAuthorized = (isAdmin: boolean, canManageGroup: boolean) => { (authorizationService as any).isAuthorized.and.callFake((featureId?: FeatureID) => { switch (featureId) { case FeatureID.AdministratorOf: return observableOf(isAdmin); case FeatureID.CanManageGroup: return observableOf(canManageGroup); case FeatureID.CanDelete: return observableOf(true); default: throw new Error(`setIsAuthorized: this fake implementation does not support ${featureId}.`); } }); }; beforeEach(waitForAsync(() => { mockGroups = [GroupMock, GroupMock2]; mockEPeople = [EPersonMock, EPersonMock2]; ePersonDataServiceStub = { findAllByHref(href: string): Observable<RemoteData<PaginatedList<EPerson>>> { switch (href) { case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid2/epersons': return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 0, totalPages: 0, currentPage: 1 }), [])); case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid/epersons': return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 1, totalPages: 1, currentPage: 1 }), [EPersonMock])); default: return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 0, totalPages: 0, currentPage: 1 }), [])); } } }; groupsDataServiceStub = { allGroups: mockGroups, findAllByHref(href: string): Observable<RemoteData<PaginatedList<Group>>> { switch (href) { case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid2/groups': return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 0, totalPages: 0, currentPage: 1 }), [])); case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid/groups': return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 1, totalPages: 1, currentPage: 1 }), [GroupMock2])); default: return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: 1, totalElements: 0, totalPages: 0, currentPage: 1 }), [])); } }, getGroupEditPageRouterLink(group: Group): string { return '/access-control/groups/' + group.id; }, getGroupRegistryRouterLink(): string { return '/access-control/groups'; }, searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> { if (query === '') { return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: this.allGroups.length, totalElements: this.allGroups.length, totalPages: 1, currentPage: 1 }), this.allGroups)); } const result = this.allGroups.find((group: Group) => { return (group.id.includes(query)); }); return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({ elementsPerPage: [result].length, totalElements: [result].length, totalPages: 1, currentPage: 1 }), [result])); } }; dsoDataServiceStub = { findByHref(href: string): Observable<RemoteData<DSpaceObject>> { return createSuccessfulRemoteDataObject$(undefined); } }; authorizationService = jasmine.createSpyObj('authorizationService', ['isAuthorized']); setIsAuthorized(true, true); paginationService = new PaginationServiceStub(); TestBed.configureTestingModule({ imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: TranslateLoaderMock } }), ], declarations: [GroupsRegistryComponent], providers: [GroupsRegistryComponent, { provide: EPersonDataService, useValue: ePersonDataServiceStub }, { provide: GroupDataService, useValue: groupsDataServiceStub }, { provide: DSpaceObjectDataService, useValue: dsoDataServiceStub }, { provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: RouteService, useValue: routeServiceStub }, { provide: Router, useValue: new RouterMock() }, { provide: AuthorizationDataService, useValue: authorizationService }, { provide: PaginationService, useValue: paginationService }, { provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) } ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(GroupsRegistryComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create GroupRegistryComponent', inject([GroupsRegistryComponent], (comp: GroupsRegistryComponent) => { expect(comp).toBeDefined(); })); it('should display list of groups', () => { const groupIdsFound = fixture.debugElement.queryAll(By.css('#groups tr td:first-child')); expect(groupIdsFound.length).toEqual(2); mockGroups.map((group: Group) => { expect(groupIdsFound.find((foundEl) => { return (foundEl.nativeElement.textContent.trim() === group.uuid); })).toBeTruthy(); }); }); it('should display community/collection name if present', () => { const collectionNamesFound = fixture.debugElement.queryAll(By.css('#groups tr td:nth-child(3)')); expect(collectionNamesFound.length).toEqual(2); expect(collectionNamesFound[0].nativeElement.textContent).toEqual(''); expect(collectionNamesFound[1].nativeElement.textContent).toEqual('testgroupid2objectName'); }); describe('edit buttons', () => { describe('when the user is a general admin', () => { beforeEach(fakeAsync(() => { // NOTE: setting canManageGroup to false should not matter, since isAdmin takes priority setIsAuthorized(true, false); // force rerender after setup changes component.search({ query: '' }); tick(); fixture.detectChanges(); })); it('should be active', () => { const editButtonsFound = fixture.debugElement.queryAll(By.css('#groups tr td:nth-child(5) button.btn-edit')); expect(editButtonsFound.length).toEqual(2); editButtonsFound.forEach((editButtonFound) => { expect(editButtonFound.nativeElement.disabled).toBeFalse(); }); }); it('should not check the canManageGroup permissions', () => { expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith( FeatureID.CanManageGroup, mockGroups[0].self ); expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith( FeatureID.CanManageGroup, mockGroups[0].self, undefined // treated differently ); expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith( FeatureID.CanManageGroup, mockGroups[1].self ); expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith( FeatureID.CanManageGroup, mockGroups[1].self, undefined // treated differently ); }); }); describe('when the user can edit the groups', () => { beforeEach(fakeAsync(() => { setIsAuthorized(false, true); // force rerender after setup changes component.search({ query: '' }); tick(); fixture.detectChanges(); })); it('should be active', () => { const editButtonsFound = fixture.debugElement.queryAll(By.css('#groups tr td:nth-child(5) button.btn-edit')); expect(editButtonsFound.length).toEqual(2); editButtonsFound.forEach((editButtonFound) => { expect(editButtonFound.nativeElement.disabled).toBeFalse(); }); }); }); describe('when the user can not edit the groups', () => { beforeEach(fakeAsync(() => { setIsAuthorized(false, false); // force rerender after setup changes component.search({ query: '' }); tick(); fixture.detectChanges(); })); it('should not be active', () => { const editButtonsFound = fixture.debugElement.queryAll(By.css('#groups tr td:nth-child(5) button.btn-edit')); expect(editButtonsFound.length).toEqual(2); editButtonsFound.forEach((editButtonFound) => { expect(editButtonFound.nativeElement.disabled).toBeTrue(); }); }); }); }); describe('search', () => { describe('when searching with query', () => { let groupIdsFound; beforeEach(fakeAsync(() => { component.search({ query: GroupMock2.id }); tick(); fixture.detectChanges(); groupIdsFound = fixture.debugElement.queryAll(By.css('#groups tr td:first-child')); })); it('should display search result', () => { expect(groupIdsFound.length).toEqual(1); expect(groupIdsFound.find((foundEl) => { return (foundEl.nativeElement.textContent.trim() === GroupMock2.uuid); })).toBeTruthy(); }); }); }); });
the_stack
import { BSTNode } from 'core/node' import { eq, lt, gt, neq } from 'core/utils2' /** * @二叉搜索树(BST):是二叉树的一种,但是它只允许你在左侧节点存储(比父节点)小的值, 在右侧节点存储(比父节点)大(或者等于)的值。 */ export default class BinarySearchTree<T> { protected root: BSTNode<T> constructor() {} // 广度优先遍历的核心实现 private breadthFirstSearchNode( node: BSTNode<T>, callback: (key: T) => void, ): void { const queue: BSTNode<T>[] = [node] while (queue.length) { const head: BSTNode<T> = queue.shift() callback(head.key) if (head.left) { queue.push(head.left) } if (head.right) { queue.push(head.right) } } } // 广度优先遍历方式遍历所有节点。 breadthFirstSearch(callback: (key: T) => void): void { this.breadthFirstSearchNode(this.root, callback) } // 深度优先遍历的核心实现 private depthFirstSearchNode( node: BSTNode<T>, callback: (key: T) => void, ): void { const stack: BSTNode<T>[] = [node] while (stack.length) { const tail: BSTNode<T> = stack.pop() callback(tail.key) if (tail.right) { stack.push(tail.right) } if (tail.left) { stack.push(tail.left) } } } // 深度优先遍历方式遍历所有节点。 depthFirstSearch(callback: (key: T) => void): void { this.depthFirstSearchNode(this.root, callback) } // 递归插入节点 protected recursionInsertNode(node: BSTNode<T>, key: T): void { // 将节点加在非根节点的其他位置,找到新节点应该插入的正确位置 if (lt(key, node.key)) { if (!node.left) { node.left = new BSTNode<T>(key) } else { this.recursionInsertNode(node.left, key) } } else { if (!node.right) { node.right = new BSTNode<T>(key) } else { this.recursionInsertNode(node.right, key) } } } // 遍历插入节点 protected loopInsertNode(node: BSTNode<T>, key: T): void { const newNode: BSTNode<T> = new BSTNode<T>(key) if (!this.root) { node = newNode return } let current: BSTNode<T> = node let parent: BSTNode<T> while (current) { parent = current if (lt(key, parent.key)) { current = current.left if (!current) { parent.left = newNode } } else { current = current.right if (!current) { parent.right = newNode return } } } } // 向树中插入一个新的键。 insert(key: T): BinarySearchTree<T> { if (!this.root) { this.root = new BSTNode<T>(key) } else { // this.recursionInsertNode(this.root, key) this.loopInsertNode(this.root, key) } return this } // 递归查找节点 private recursionSearchNode(node: BSTNode<T>, key: T): boolean { if (!node) { return false } if (lt(key, node.key)) { return this.recursionSearchNode(node.left, key) } else if (gt(key, node.key)) { return this.recursionSearchNode(node.right, key) } // 当键值等于当前节点时,返回true return true } // 循环查找节点 private loopSearchNode(node: BSTNode<T>, key: T): boolean { const queue: BSTNode<T>[] = [node] while (queue.length) { const head = queue.shift() if (eq(key, head.key)) { return true } if (head.left) { queue.push(head.left) } if (head.right) { queue.push(head.right) } } return false } // 在树中查找一个键,如果节点存在,则返回true;如果不存在,则返回false。 search(key: T): boolean { // return this.recursionSearchNode(this.root, key) return this.loopSearchNode(this.root, key) } // 中序遍历的递归实现 private recursionInOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { if (node) { this.recursionInOrderTraverseNode(node.left, callback) callback(node.key) this.recursionInOrderTraverseNode(node.right, callback) } } // 中序遍历的循环实现 private loopInOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { const stack: BSTNode<T>[] = [] let current: BSTNode<T> = node while (current || stack.length) { while (current) { stack.push(current) current = current.left } current = stack.pop() callback(current.key) current = current.right } } // 通过中序遍历方式遍历所有节点。 中序遍历是一种以上行顺序访问BST所有节点的遍历方式,也就是以从最小到最大的顺序访问所有节点。中序遍历的一种应用就是对树进行排序操作。 inOrderTraverse(callback: (key: T) => void): void { // this.recursionInOrderTraverseNode(this.root, callback) this.loopInOrderTraverseNode(this.root, callback) } // 前序遍历的递归实现 private recursionPreOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { if (node) { callback(node.key) this.recursionPreOrderTraverseNode(node.left, callback) this.recursionPreOrderTraverseNode(node.right, callback) } } // 前序遍历的循环实现 private loopPreOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { const stack: BSTNode<T>[] = [] let current: BSTNode<T> = node while (current || stack.length) { while (current) { stack.push(current) callback(current.key) current = current.left } current = stack.pop() current = current.right } } // 通过前序遍历方式遍历所有节点。 preOrderTraverse(callback: (key: T) => void): void { // this.recursionPreOrderTraverseNode(this.root, callback) this.loopPreOrderTraverseNode(this.root, callback) } // 后序遍历的递归实现 private recursionPostOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { if (node) { this.recursionPostOrderTraverseNode(node.left, callback) this.recursionPostOrderTraverseNode(node.right, callback) callback(node.key) } } // 前序遍历的循环实现 private loopPostOrderTraverseNode( node: BSTNode<T>, callback: (key: T) => void, ): void { const stack: BSTNode<T>[] = [] let prev: BSTNode<T> let current: BSTNode<T> = node while (current || stack.length) { while (current) { stack.push(current) current = current.left } current = stack[stack.length - 1] if (!current.right || eq(current.right, prev)) { current = stack.pop() callback(current.key) prev = current current = null } else { current = current.right } } } // 通过后序遍历方式遍历所有节点。 postOrderTraverse(callback: (key: T) => void): void { // this.recursionPostOrderTraverseNode(this.root, callback) this.loopPostOrderTraverseNode(this.root, callback) } // 获取最小的值/键。 protected minNode(node: BSTNode<T>): BSTNode<T> { let current: BSTNode<T> = node while (current && current.left) { current = current.left } return current } min(): BSTNode<T> { // 返回树中最小的值/键。 return this.minNode(this.root) } // 获取最大的值/键。 protected maxNode(node: BSTNode<T>): BSTNode<T> { let current: BSTNode<T> = node while (current && current.right) { current = current.right } return current } // 返回树中最大的值/键。 max(): BSTNode<T> { return this.maxNode(this.root) } // 递归删除节点 // 当key === node.item时 // 有三种情况 // 1 - 一个叶子节点 // 2 - 一个节点只有一个子节点 // 3 - 一个节点有两个字节点 protected recursionRemoveNode(node: BSTNode<T>, key: T): BSTNode<T> { if (!node) { return null } if (lt(key, node.key)) { // 要删除的节点在左子树 node.left = this.recursionRemoveNode(node.left, key) } else if (gt(key, node.key)) { // 要删除的节点在右子树 node.right = this.recursionRemoveNode(node.right, key) } else { // 键等于node.key // node是要被删除的节点 // 第一种情况——一个叶节点 if (!node.left && !node.right) { node = null } else if (!node.left && node.right) { // 第二种情况——一个只有一个子节点的节点 node = node.right } else if (node.left && !node.right) { // 第二种情况——一个只有一个子节点的节点 node = node.left } else { // 第三种情况——一个有两个子节点的节点 // node有两个子节点,则获取其最小的节点(后序节点) const inOrderNode: BSTNode<T> = this.minNode(node.right) node.key = inOrderNode.key node.right = this.recursionRemoveNode( node.right, inOrderNode.key, ) } } return node } // 暴力重建法 protected rebuildRemoveNode(node: BSTNode<T>, key: T): BSTNode<T> { if (!node) { return null } const newTree: BinarySearchTree<T> = new BinarySearchTree() this.breadthFirstSearch((nKey: T): void => { if (neq(nKey, key)) { newTree.insert(nKey) } }) return newTree.getRoot() } // 循环删除节点的核心 // 合并左子节点和右子节点 protected mergeChild(node: BSTNode<T>): BSTNode<T> { if (!node.left && !node.right) { return null } if (!node.left && node.right) { return node.right } if (node.left && !node.right) { return node.left } let current: BSTNode<T> = node.right while (current.left) { current = current.left } current.left = node.left return node.right } // 循环删除节点 protected loopRemoveNode(node: BSTNode<T>, key: T): BSTNode<T> { if (!node) { return null } if (eq(key, node.key)) { return this.mergeChild(node) } let current: BSTNode<T> = node let parent: BSTNode<T> let keyword: 'left' | 'right' while (current && neq(current.key, key)) { parent = current keyword = gt(current.key, key) ? 'left' : 'right' current = current[keyword] } if (!current) { return node } parent[keyword] = this.mergeChild(current) return node } // 从树中移除某个键。 remove(key: T): BinarySearchTree<T> { // this.root = this.recursionRemoveNode(this.root, key) // this.root = this.rebuildRemoveNode(this.root, key) this.root = this.loopRemoveNode(this.root, key) return this } getRoot(): BSTNode<T> { return this.root } print(): void { console.log(this.toArray()) } toArray(): T[] { const list: T[] = [] this.breadthFirstSearch((key: T) => { list.push(key) }) return list } }
the_stack
"use strict"; import { exec } from "child_process"; import { Gzip, createGzip } from "zlib"; import { Readable, Writable } from "stream"; import { Stats, access, constants, createReadStream, createWriteStream } from "fs"; import { FileHandle, mkdir, open, readFile, rename, stat, unlink, writeFile } from "fs/promises"; import { sep } from "path"; import { TextDecoder } from "util"; async function exists(filename: string): Promise<boolean> { return new Promise(resolve => access(filename, constants.F_OK, error => resolve(! error))); } export class RotatingFileStreamError extends Error { public code = "RFS-TOO-MANY"; constructor() { super("Too many destination file attempts"); } } export type Compressor = (source: string, dest: string) => string; export type Generator = (time: number | Date, index?: number) => string; interface RotatingFileStreamEvents { // Inehrited from Writable close: () => void; drain: () => void; error: (err: Error) => void; finish: () => void; pipe: (src: Readable) => void; unpipe: (src: Readable) => void; // RotatingFileStream defined external: (stdout: string, stderr: string) => void; history: () => void; open: (filename: string) => void; removed: (filename: string, number: boolean) => void; rotation: () => void; rotated: (filename: string) => void; warning: (error: Error) => void; } export declare interface RotatingFileStream extends Writable { addListener<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; emit<Event extends keyof RotatingFileStreamEvents>(event: Event, ...args: Parameters<RotatingFileStreamEvents[Event]>): boolean; on<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; once<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; prependListener<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; prependOnceListener<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; removeListener<Event extends keyof RotatingFileStreamEvents>(event: Event, listener: RotatingFileStreamEvents[Event]): this; } export interface Options { compress?: boolean | string | Compressor; encoding?: BufferEncoding; history?: string; immutable?: boolean; initialRotation?: boolean; interval?: string; intervalBoundary?: boolean; maxFiles?: number; maxSize?: string; mode?: number; omitExtension?: boolean; path?: string; rotate?: number; size?: string; teeToStdout?: boolean; } interface Opts { compress?: string | Compressor; encoding?: BufferEncoding; history?: string; immutable?: boolean; initialRotation?: boolean; interval?: { num: number; unit: string }; intervalBoundary?: boolean; maxFiles?: number; maxSize?: number; mode?: number; omitExtension?: boolean; path?: string; rotate?: number; size?: number; teeToStdout?: boolean; } type Callback = (error?: Error) => void; interface Chunk { chunk: Buffer; encoding: BufferEncoding; } interface History { name: string; size: number; time: number; } export class RotatingFileStream extends Writable { private createGzip: () => Gzip; private exec: typeof exec; private file: FileHandle | undefined; private filename: string; private finished: boolean; private fsCreateReadStream: typeof createReadStream; private fsCreateWriteStream: typeof createWriteStream; private fsOpen: typeof open; private fsReadFile: typeof readFile; private fsStat: typeof stat; private generator: Generator; private initPromise: Promise<void> | null; private last: string; private maxTimeout: number; private next: number; private options: Opts; private prev: number; private rotation: Date; private size: number; private stdout: typeof process.stdout; private timeout: NodeJS.Timeout; private timeoutPromise: Promise<void> | null; constructor(generator: Generator, options: Opts) { const { encoding, history, maxFiles, maxSize, path } = options; super({ decodeStrings: true, defaultEncoding: encoding }); this.createGzip = createGzip; this.exec = exec; this.filename = path + generator(null); this.fsCreateReadStream = createReadStream; this.fsCreateWriteStream = createWriteStream; this.fsOpen = open; this.fsReadFile = readFile; this.fsStat = stat; this.generator = generator; this.maxTimeout = 2147483640; this.options = options; this.stdout = process.stdout; if(maxFiles || maxSize) options.history = path + (history ? history : this.generator(null) + ".txt"); this.on("close", () => (this.finished ? null : this.emit("finish"))); this.on("finish", () => (this.finished = this.clear())); // In v15 was introduced the _constructor method to delay any _write(), _final() and _destroy() calls // Untill v16 will be not deprecated we still need this.initPromise // https://nodejs.org/api/stream.html#stream_writable_construct_callback (async () => { try { this.initPromise = this.init(); await this.initPromise; delete this.initPromise; } catch(e) {} })(); } _destroy(error: Error, callback: Callback): void { this.refinal(error, callback); } _final(callback: Callback): void { this.refinal(undefined, callback); } _write(chunk: Buffer, encoding: BufferEncoding, callback: Callback): void { this.rewrite([{ chunk, encoding }], 0, callback); } _writev(chunks: Chunk[], callback: Callback): void { this.rewrite(chunks, 0, callback); } private async refinal(error: Error | undefined, callback: Callback): Promise<void> { try { this.clear(); if(this.initPromise) await this.initPromise; if(this.timeoutPromise) await this.timeoutPromise; await this.reclose(); } catch(e) { return callback(error || e); } callback(error); } private async rewrite(chunks: Chunk[], index: number, callback: Callback): Promise<void> { const { size, teeToStdout } = this.options; try { if(this.initPromise) await this.initPromise; if(this.timeoutPromise) await this.timeoutPromise; for(let i = 0; i < chunks.length; ++i) { const { chunk } = chunks[i]; this.size += chunk.length; await this.file.write(chunk); if(teeToStdout && ! this.stdout.destroyed) this.stdout.write(chunk); if(size && this.size >= size) await this.rotate(); } } catch(e) { return callback(e); } callback(); } private async init(): Promise<void> { const { immutable, initialRotation, interval, size } = this.options; // In v15 was introduced the _constructor method to delay any _write(), _final() and _destroy() calls // Once v16 will be deprecated we can restore only following line // if(immutable) return this.immutate(true); if(immutable) return new Promise<void>((resolve, reject) => process.nextTick(() => this.immutate(true).then(resolve).catch(reject))); let stats: Stats; try { stats = await stat(this.filename); } catch(e) { if(e.code !== "ENOENT") throw e; return this.reopen(0); } if(! stats.isFile()) throw new Error(`Can't write on: ${this.filename} (it is not a file)`); if(initialRotation) { this.intervalBounds(this.now()); const prev = this.prev; this.intervalBounds(new Date(stats.mtime.getTime())); if(prev !== this.prev) return this.rotate(); } this.size = stats.size; if(! size || stats.size < size) return this.reopen(stats.size); if(interval) this.intervalBounds(this.now()); return this.rotate(); } private async makePath(name: string): Promise<string> { return mkdir(name.split(sep).slice(0, -1).join(sep), { recursive: true }); } private async reopen(size: number): Promise<void> { let file: FileHandle; try { file = await open(this.filename, "a", this.options.mode); } catch(e) { if(e.code !== "ENOENT") throw e; await this.makePath(this.filename); file = await open(this.filename, "a", this.options.mode); } this.file = file; this.size = size; this.interval(); this.emit("open", this.filename); } private async reclose(): Promise<void> { const { file } = this; if(! file) return; delete this.file; return file.close(); } private now(): Date { return new Date(); } private async rotate(): Promise<void> { const { immutable, rotate } = this.options; this.size = 0; this.rotation = this.now(); this.clear(); this.emit("rotation"); await this.reclose(); if(rotate) return this.classical(); if(immutable) return this.immutate(false); return this.move(); } private async findName(): Promise<string> { const { interval, path, intervalBoundary } = this.options; for(let index = 1; index < 1000; ++index) { const filename = path + this.generator(interval && intervalBoundary ? new Date(this.prev) : this.rotation, index); if(! (await exists(filename))) return filename; } throw new RotatingFileStreamError(); } private async move(): Promise<void> { const { compress } = this.options; const filename = await this.findName(); await this.touch(filename); if(compress) await this.compress(filename); else await rename(this.filename, filename); return this.rotated(filename); } private async touch(filename: string): Promise<void> { let file: FileHandle; try { file = await this.fsOpen(filename, "a"); } catch(e) { if(e.code !== "ENOENT") throw e; await this.makePath(filename); file = await open(filename, "a"); } await file.close(); return unlink(filename); } private async classical(): Promise<void> { const { compress, path, rotate } = this.options; let rotatedName = ""; for(let count = rotate; count > 0; --count) { const currName = path + this.generator(count); const prevName = count === 1 ? this.filename : path + this.generator(count - 1); if(! (await exists(prevName))) continue; if(! rotatedName) rotatedName = currName; if(count === 1 && compress) await this.compress(currName); else { try { await rename(prevName, currName); } catch(e) { if(e.code !== "ENOENT") throw e; await this.makePath(currName); await rename(prevName, currName); } } } return this.rotated(rotatedName); } private clear(): boolean { if(this.timeout) { clearTimeout(this.timeout); this.timeout = null; } return true; } private intervalBoundsBig(now: Date): void { const year = now.getFullYear(); let month = now.getMonth(); let day = now.getDate(); let hours = now.getHours(); const { num, unit } = this.options.interval; if(unit === "M") { day = 1; hours = 0; } else if(unit === "d") hours = 0; else hours = parseInt((hours / num) as unknown as string, 10) * num; this.prev = new Date(year, month, day, hours, 0, 0, 0).getTime(); if(unit === "M") month += num; else if(unit === "d") day += num; else hours += num; this.next = new Date(year, month, day, hours, 0, 0, 0).getTime(); } private intervalBounds(now: Date): Date { const unit = this.options.interval.unit; if(unit === "M" || unit === "d" || unit === "h") this.intervalBoundsBig(now); else { let period = 1000 * this.options.interval.num; if(unit === "m") period *= 60; this.prev = parseInt((now.getTime() / period) as unknown as string, 10) * period; this.next = this.prev + period; } return new Date(this.prev); } private interval(): void { if(! this.options.interval) return; this.intervalBounds(this.now()); const set = async (): Promise<void> => { const time = this.next - this.now().getTime(); if(time <= 0) { try { this.timeoutPromise = this.rotate(); await this.timeoutPromise; delete this.timeoutPromise; } catch(e) {} } else { this.timeout = setTimeout(set, time > this.maxTimeout ? this.maxTimeout : time); this.timeout.unref(); } }; set(); } private async compress(filename: string): Promise<void> { const { compress } = this.options; if(typeof compress === "function") { await new Promise<void>((resolve, reject) => { this.exec(compress(this.filename, filename), (error, stdout, stderr) => { this.emit("external", stdout, stderr); error ? reject(error) : resolve(); }); }); } else await this.gzip(filename); return unlink(this.filename); } private async gzip(filename: string): Promise<void> { const { mode } = this.options; const options = mode ? { mode } : {}; const inp = this.fsCreateReadStream(this.filename, {}); const out = this.fsCreateWriteStream(filename, options); const zip = this.createGzip(); return new Promise((resolve, reject) => { [inp, out, zip].map(stream => stream.once("error", reject)); out.once("finish", resolve); inp.pipe(zip).pipe(out); }); } private async rotated(filename: string): Promise<void> { const { maxFiles, maxSize } = this.options; if(maxFiles || maxSize) await this.history(filename); this.emit("rotated", filename); return this.reopen(0); } private async history(filename: string): Promise<void> { const { history, maxFiles, maxSize } = this.options; const res: History[] = []; let files = [filename]; try { const content = await this.fsReadFile(history, "utf8"); files = [...content.toString().split("\n"), filename]; } catch(e) { if(e.code !== "ENOENT") throw e; } for(const file of files) { if(file) { try { const stats = await this.fsStat(file); if(stats.isFile()) { res.push({ name: file, size: stats.size, time: stats.ctime.getTime() }); } else this.emit("warning", new Error(`File '${file}' contained in history is not a regular file`)); } catch(e) { if(e.code !== "ENOENT") throw e; } } } res.sort((a, b) => a.time - b.time); if(maxFiles) { while(res.length > maxFiles) { const file = res.shift(); await unlink(file.name); this.emit("removed", file.name, true); } } if(maxSize) { while(res.reduce((size, file) => size + file.size, 0) > maxSize) { const file = res.shift(); await unlink(file.name); this.emit("removed", file.name, false); } } await writeFile(history, res.map(e => e.name).join("\n") + "\n", "utf-8"); this.emit("history"); } private async immutate(first: boolean): Promise<void> { const { size } = this.options; const now = this.now(); for(let index = 1; index < 1000; ++index) { let fileSize = 0; let stats: Stats = undefined; this.filename = this.options.path + this.generator(now, index); try { stats = await this.fsStat(this.filename); } catch(e) { if(e.code !== "ENOENT") throw e; } if(stats) { fileSize = stats.size; if(! stats.isFile()) throw new Error(`Can't write on: '${this.filename}' (it is not a file)`); if(size && fileSize >= size) continue; } if(first) { this.last = this.filename; return this.reopen(fileSize); } await this.rotated(this.last); this.last = this.filename; return; } throw new RotatingFileStreamError(); } } function buildNumberCheck(field: string): (type: string, options: Options, value: string) => void { return (type: string, options: Options, value: string): void => { const converted: number = parseInt(value, 10); if(type !== "number" || (converted as unknown) !== value || converted <= 0) throw new Error(`'${field}' option must be a positive integer number`); }; } function buildStringCheck(field: string, check: (value: string) => any) { return (type: string, options: Options, value: string): void => { if(type !== "string") throw new Error(`Don't know how to handle 'options.${field}' type: ${type}`); options[field] = check(value); }; } function checkMeasure(value: string, what: string, units: any): any { const ret: any = {}; ret.num = parseInt(value, 10); if(isNaN(ret.num)) throw new Error(`Unknown 'options.${what}' format: ${value}`); if(ret.num <= 0) throw new Error(`A positive integer number is expected for 'options.${what}'`); ret.unit = value.replace(/^[ 0]*/g, "").substr((ret.num + "").length, 1); if(ret.unit.length === 0) throw new Error(`Missing unit for 'options.${what}'`); if(! units[ret.unit]) throw new Error(`Unknown 'options.${what}' unit: ${ret.unit}`); return ret; } const intervalUnits: any = { M: true, d: true, h: true, m: true, s: true }; function checkIntervalUnit(ret: any, unit: string, amount: number): void { if(parseInt((amount / ret.num) as unknown as string, 10) * ret.num !== amount) throw new Error(`An integer divider of ${amount} is expected as ${unit} for 'options.interval'`); } function checkInterval(value: string): any { const ret = checkMeasure(value, "interval", intervalUnits); switch(ret.unit) { case "h": checkIntervalUnit(ret, "hours", 24); break; case "m": checkIntervalUnit(ret, "minutes", 60); break; case "s": checkIntervalUnit(ret, "seconds", 60); break; } return ret; } const sizeUnits: any = { B: true, G: true, K: true, M: true }; function checkSize(value: string): any { const ret = checkMeasure(value, "size", sizeUnits); if(ret.unit === "K") return ret.num * 1024; if(ret.unit === "M") return ret.num * 1048576; if(ret.unit === "G") return ret.num * 1073741824; return ret.num; } const checks: any = { encoding: (type: string, options: Opts, value: string): any => new TextDecoder(value), immutable: (): void => {}, initialRotation: (): void => {}, interval: buildStringCheck("interval", checkInterval), intervalBoundary: (): void => {}, maxFiles: buildNumberCheck("maxFiles"), maxSize: buildStringCheck("maxSize", checkSize), mode: (): void => {}, omitExtension: (): void => {}, rotate: buildNumberCheck("rotate"), size: buildStringCheck("size", checkSize), teeToStdout: (): void => {}, compress: (type: string, options: Opts, value: boolean | string | Compressor): any => { if(! value) throw new Error("A value for 'options.compress' must be specified"); if(type === "boolean") return (options.compress = (source: string, dest: string): string => `cat ${source} | gzip -c9 > ${dest}`); if(type === "function") return; if(type !== "string") throw new Error(`Don't know how to handle 'options.compress' type: ${type}`); if((value as unknown as string) !== "gzip") throw new Error(`Don't know how to handle compression method: ${value}`); }, history: (type: string): void => { if(type !== "string") throw new Error(`Don't know how to handle 'options.history' type: ${type}`); }, path: (type: string, options: Opts, value: string): void => { if(type !== "string") throw new Error(`Don't know how to handle 'options.path' type: ${type}`); if(value[value.length - 1] !== sep) options.path = value + sep; } }; function checkOpts(options: Options): Opts { const ret: Opts = {}; for(const opt in options) { const value = options[opt]; const type = typeof value; if(! (opt in checks)) throw new Error(`Unknown option: ${opt}`); ret[opt] = options[opt]; checks[opt](type, ret, value); } if(! ret.path) ret.path = ""; if(! ret.interval) { delete ret.immutable; delete ret.initialRotation; delete ret.intervalBoundary; } if(ret.rotate) { delete ret.history; delete ret.immutable; delete ret.maxFiles; delete ret.maxSize; delete ret.intervalBoundary; } if(ret.immutable) delete ret.compress; if(! ret.intervalBoundary) delete ret.initialRotation; return ret; } function createClassical(filename: string, compress: boolean, omitExtension: boolean): Generator { return (index: number): string => (index ? `${filename}.${index}${compress && ! omitExtension ? ".gz" : ""}` : filename); } function createGenerator(filename: string, compress: boolean, omitExtension: boolean): Generator { const pad = (num: number): string => (num > 9 ? "" : "0") + num; return (time: Date, index?: number): string => { if(! time) return filename as unknown as string; const month = time.getFullYear() + "" + pad(time.getMonth() + 1); const day = pad(time.getDate()); const hour = pad(time.getHours()); const minute = pad(time.getMinutes()); return month + day + "-" + hour + minute + "-" + pad(index) + "-" + filename + (compress && ! omitExtension ? ".gz" : ""); }; } export function createStream(filename: string | Generator, options?: Options): RotatingFileStream { if(typeof options === "undefined") options = {}; else if(typeof options !== "object") throw new Error(`The "options" argument must be of type object. Received type ${typeof options}`); const opts = checkOpts(options); const { compress, omitExtension } = opts; let generator: Generator; if(typeof filename === "string") generator = options.rotate ? createClassical(filename, compress !== undefined, omitExtension) : createGenerator(filename, compress !== undefined, omitExtension); else if(typeof filename === "function") generator = filename; else throw new Error(`The "filename" argument must be one of type string or function. Received type ${typeof filename}`); return new RotatingFileStream(generator, opts); }
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "Operation_display", type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } } } } }; export const Operation: msRest.CompositeMapper = { serializedName: "Operation", type: { name: "Composite", className: "Operation", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, display: { readOnly: true, serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } } } } }; export const ConnectedClusterIdentity: msRest.CompositeMapper = { serializedName: "ConnectedClusterIdentity", type: { name: "Composite", className: "ConnectedClusterIdentity", modelProperties: { principalId: { readOnly: true, serializedName: "principalId", type: { name: "String" } }, tenantId: { readOnly: true, serializedName: "tenantId", type: { name: "String" } }, type: { required: true, serializedName: "type", defaultValue: 'SystemAssigned', type: { name: "Enum", allowedValues: [ "None", "SystemAssigned" ] } } } } }; export const SystemData: msRest.CompositeMapper = { serializedName: "SystemData", type: { name: "Composite", className: "SystemData", modelProperties: { createdBy: { serializedName: "createdBy", type: { name: "String" } }, createdByType: { serializedName: "createdByType", type: { name: "String" } }, createdAt: { serializedName: "createdAt", type: { name: "DateTime" } }, lastModifiedBy: { serializedName: "lastModifiedBy", type: { name: "String" } }, lastModifiedByType: { serializedName: "lastModifiedByType", type: { name: "String" } }, lastModifiedAt: { serializedName: "lastModifiedAt", type: { name: "DateTime" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { required: true, serializedName: "location", type: { name: "String" } } } } }; export const ConnectedCluster: msRest.CompositeMapper = { serializedName: "ConnectedCluster", type: { name: "Composite", className: "ConnectedCluster", modelProperties: { ...TrackedResource.type.modelProperties, identity: { required: true, serializedName: "identity", type: { name: "Composite", className: "ConnectedClusterIdentity" } }, agentPublicKeyCertificate: { required: true, serializedName: "properties.agentPublicKeyCertificate", type: { name: "String" } }, kubernetesVersion: { readOnly: true, serializedName: "properties.kubernetesVersion", type: { name: "String" } }, totalNodeCount: { readOnly: true, serializedName: "properties.totalNodeCount", type: { name: "Number" } }, totalCoreCount: { readOnly: true, serializedName: "properties.totalCoreCount", type: { name: "Number" } }, agentVersion: { readOnly: true, serializedName: "properties.agentVersion", type: { name: "String" } }, provisioningState: { serializedName: "properties.provisioningState", type: { name: "String" } }, distribution: { serializedName: "properties.distribution", type: { name: "String" } }, infrastructure: { serializedName: "properties.infrastructure", type: { name: "String" } }, offering: { readOnly: true, serializedName: "properties.offering", type: { name: "String" } }, managedIdentityCertificateExpirationTime: { readOnly: true, serializedName: "properties.managedIdentityCertificateExpirationTime", type: { name: "DateTime" } }, lastConnectivityTime: { readOnly: true, serializedName: "properties.lastConnectivityTime", type: { name: "DateTime" } }, connectivityStatus: { readOnly: true, serializedName: "properties.connectivityStatus", type: { name: "String" } }, systemData: { readOnly: true, serializedName: "systemData", type: { name: "Composite", className: "SystemData" } } } } }; export const ConnectedClusterPatch: msRest.CompositeMapper = { serializedName: "ConnectedClusterPatch", type: { name: "Composite", className: "ConnectedClusterPatch", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, properties: { serializedName: "properties", type: { name: "Object" } } } } }; export const ProxyResource: msRest.CompositeMapper = { serializedName: "ProxyResource", type: { name: "Composite", className: "ProxyResource", modelProperties: { ...Resource.type.modelProperties } } }; export const AzureEntityResource: msRest.CompositeMapper = { serializedName: "AzureEntityResource", type: { name: "Composite", className: "AzureEntityResource", modelProperties: { ...Resource.type.modelProperties, etag: { readOnly: true, serializedName: "etag", type: { name: "String" } } } } }; export const ErrorAdditionalInfo: msRest.CompositeMapper = { serializedName: "ErrorAdditionalInfo", type: { name: "Composite", className: "ErrorAdditionalInfo", modelProperties: { type: { readOnly: true, serializedName: "type", type: { name: "String" } }, info: { readOnly: true, serializedName: "info", type: { name: "Object" } } } } }; export const ErrorDetail: msRest.CompositeMapper = { serializedName: "ErrorDetail", type: { name: "Composite", className: "ErrorDetail", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorDetail" } } } }, additionalInfo: { readOnly: true, serializedName: "additionalInfo", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorAdditionalInfo" } } } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "ErrorDetail" } } } } }; export const ConnectedClusterList: msRest.CompositeMapper = { serializedName: "ConnectedClusterList", type: { name: "Composite", className: "ConnectedClusterList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "ConnectedCluster" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const OperationList: msRest.CompositeMapper = { serializedName: "OperationList", type: { name: "Composite", className: "OperationList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import { EOL } from "os"; import {} from "vscode" import type { TextDocument, WorkspaceFolder, TextLine, Position, Range, StatusBarItem, Extension, TreeDataProvider, Command, TreeItemCollapsibleState } from "vscode" import { URI } from 'vscode-uri' // adapted from https://github.com/rokucommunity/vscode-brightscript-language/blob/master/src/mockVscode.spec.ts export let vscodeMock = { CompletionItem: class { }, CodeLens: class { }, StatusBarAlignment: { Left: 1, Right: 2 }, StatusBarItem: { alignment: { Left: 1, Right: 2 }, priority: 0, text: "", tooltip: "", color: "", command: "", show: ()=>{}, hide: ()=>{}, dispose: ()=>{} }, extensions: { getExtension: function(extensionId: string): Extension<any> | undefined { return { id: "", /** * The absolute file path of the directory containing this extension. */ extensionPath: "", /** * `true` if the extension has been activated. */ isActive: true, /** * The parsed contents of the extension's package.json. */ packageJSON: { "version": "0.0.0" }, extensionKind: null, exports: null, activate: ()=>{return new Promise(()=>{})} } }, all: [], onDidChange: null, }, debug: { registerDebugConfigurationProvider: () => { }, onDidStartDebugSession: () => { }, onDidReceiveDebugSessionCustomEvent: () => { }, }, languages: { registerDefinitionProvider: () => { }, registerDocumentSymbolProvider: () => { }, registerWorkspaceSymbolProvider: () => { }, registerDocumentRangeFormattingEditProvider: () => { }, registerSignatureHelpProvider: () => { }, registerReferenceProvider: () => { }, registerDocumentLinkProvider: () => { }, registerCompletionItemProvider: () => { }, createDiagnosticCollection: () => { return { clear: () => { } }; } }, subscriptions: [], commands: { registerCommand: () => { }, executeCommand: () => { } }, context: { subscriptions: [], asAbsolutePath: function() { } }, workspace: { workspaceFolders: [<WorkspaceFolder>{ uri: URI.parse(""), name: "foo", index: 0 }], createFileSystemWatcher: () => { return { onDidCreate: () => { }, onDidChange: () => { }, onDidDelete: () => { } }; }, getConfiguration: function() { return { get: function(section?: string, resource?: any) { if(section == "enableTelemetry") return false if(section == "pyGuiLibraries") return [] } }; }, onDidChangeConfiguration: () => { return { "dispose": ()=>{} } }, onDidChangeWorkspaceFolders: () => { }, findFiles: (include, exclude) => { return []; }, registerTextDocumentContentProvider: () => { }, onDidChangeTextDocument: () => { }, onDidCloseTextDocument: () => { }, openTextDocument: (content: string)=>new Promise(()=><TextDocument>{}) }, window: { createOutputChannel: function() { return { show: () => { }, clear: () => { }, appendLine: () => { } }; }, registerTreeDataProvider: function(viewId: string, treeDataProvider: TreeDataProvider<any>) { }, showErrorMessage: function(message: string) { }, activeTextEditor: { document: undefined, setDecorations(decorationType, rangesOrOptions){} }, onDidChangeTextEditorSelection: () => { }, createTextEditorDecorationType: function(){}, showTextDocument: function(doc){ return new Promise(()=>doc) }, createStatusBarItem: function(alignment?: number, priority?: number):StatusBarItem{ return { alignment: 0, priority: 0, text: "", tooltip: "", color: "", command: "", show: ()=>{}, hide: ()=>{}, dispose: ()=>{} } } }, CompletionItemKind: { Function: 2 }, Disposable: class { public static from() { } }, EventEmitter: class { public fire() { } public event() { } }, DeclarationProvider: class { public onDidChange = () => { } public onDidDelete = () => { } public onDidReset = () => { } public sync = () => { } }, OutputChannel: class { public clear() { } public appendLine() { } public show() { } }, DebugCollection: class { public clear() { } public set() { } }, Position: class { constructor(line, character) { this.line = line; this.character = character; } private line: number; private character: number; }, ParameterInformation: class { constructor(label: string, documentation?: string | any) { this.label = label; this.documentation = documentation; } private label: string; private documentation: string | any | undefined; }, SignatureHelp: class { constructor() { this.signatures = []; } private signatures: any[]; private activeParameter: number; private activeSignature: number; }, SignatureInformation: class { constructor(label: string, documentation?: string | any) { this.label = label; this.documentation = documentation; } private label: string; private documentation: string | any | undefined; }, Range: class { constructor(private startLine: number, private startCharacter: number, private endLine: number, private endCharacter: number) { this.start = <Position>{ line:startLine, character: startCharacter } this.end = <Position>{ line:endLine, character: endCharacter } } readonly start: Position readonly end: Position public isEmpty: boolean public isSingleLine: boolean }, SymbolKind: { File: 0, Module: 1, Namespace: 2, Package: 3, Class: 4, Method: 5, Property: 6, Field: 7, Constructor: 8, Enum: 9, Interface: 10, Function: 11, Variable: 12, Constant: 13, String: 14, Number: 15, Boolean: 16, Array: 17, Object: 18, Key: 19, Null: 20, EnumMember: 21, Struct: 22, Event: 23, Operator: 24, TypeParameter: 25 }, TextDocument: class { constructor(fileName: string, private text: string) { this.fileName = fileName; this.lineCount = text.split(EOL).length } readonly uri: URI; readonly isUntitled: boolean; readonly languageId: string; readonly version: number; readonly isDirty: boolean; readonly isClosed: boolean; readonly lineCount: number; public fileName: string; public eol: 1 | 2 = 1; public getText() { return this.text; } save(): Thenable<boolean> {return new Promise(()=>{});}; public getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined { return undefined}; public lineAt(line: number): TextLine { const splitText = this.text.split(EOL) return { lineNumber: line, text: splitText[line], range: <Range>{ start: <Position>{ line: line, }, end: <Position>{ line: line }, isEmpty: Boolean(this.text), isSingleLine: true }, rangeIncludingLineBreak: null, firstNonWhitespaceCharacterIndex: null, isEmptyOrWhitespace: null } }; public offsetAt(position: Position): number {return -1}; public positionAt(offset: number): Position {return null}; }, TreeItem: class { constructor(label: string, collapsibleState?: TreeItemCollapsibleState) { this.label = label; this.collapsibleState = collapsibleState; } public readonly label: string; public readonly iconPath?: string | URI | { light: string | URI; dark: string | URI }; public readonly command?: Command; public readonly collapsibleState?: TreeItemCollapsibleState; public readonly contextValue?: string; }, DocumentLink: class { constructor(range: Range, uri: string) { this.range = range; this.uri = uri; } private range: any; private uri: string; }, MarkdownString: class { constructor(value: string = null) { this.value = value; } private value: string; }, Uri: URI.parse(""), SnippetString: class { constructor(value: string = null) { this.value = value; } private value: string; }, };
the_stack
import { PathInfo } from "acebase-core"; import { IPCPeer } from "./ipc"; const SECOND = 1000; const MINUTE = 60000; const DEBUG_MODE = false; const LOCK_TIMEOUT_MS = DEBUG_MODE ? 15 * MINUTE : 90 * SECOND; type NodeKey = string|number; export abstract class NodeLockIntention { /** * The intention to read a single node for reflection purposes (eg enumerating its children). * While lock is granted, this prevents others to write to this node */ static ReadInfo() { return new ReadInfoIntention(); } /** * The intention to read the value of a node and its children, optionally filtered to include or exclude specific child keys/paths * While lock is granted, this prevents others to write to this node and its (optionally filtered) child paths * @param filter */ static ReadValue(filter?: { include?: NodeKey[], exclude?: NodeKey[], child_objects?: boolean } ) { return new ReadValueIntention(filter); } /** * The intention to update specific child values of a node. * While lock is granted, this prevents others to read or write to this node and specified child keys * @param keys The child keys that will be updated */ static UpdateNode(keys: NodeKey[]) { return new UpdateNodeIntention(keys); } /** * The intention to overwrite a node's value. * While lock is granted, this prevents others to read or write to this node and its descendants */ static OverwriteNode() { return new OverwriteNodeIntention(); } } class ReadInfoIntention extends NodeLockIntention {} class ReadValueIntention extends NodeLockIntention { constructor(public filter?: { include?: NodeKey[], exclude?: NodeKey[], child_objects?: boolean }) { super(); } } class UpdateNodeIntention extends NodeLockIntention { constructor(public keys: NodeKey[]) { super(); } } class OverwriteNodeIntention extends NodeLockIntention {} interface INodeLockRequest { tid: TransactionID path: string pathInfo?: PathInfo intention: NodeLockIntention } interface IQueuedLockRequest { queued: number lock: NodeLockInfo // resolve: () => void // reject: (err: Error) => void grant: () => void } type TransactionID = number; // Change to string later? type LockID = number; // Change to string later, use ID.generate() enum NodeLockState { pending, locked, released, expired } export class NodeLockInfo { /** Generated lock ID */ readonly id: LockID; /** Transaction this lock is part of */ readonly tid: TransactionID /** path of the lock */ readonly path: string /** pathInfo */ readonly pathInfo: PathInfo /** the intention the lock was requested with */ readonly intention: NodeLockIntention /** current state of the lock. Cycle: pending -> locked -> released or expired */ state: NodeLockState; /** lock request timestamp */ requested: number; /** timestamp the lock was granted */ granted?: number; /** lock expiry timestamp */ expires: number; /** lock release timestamp */ released?: number; constructor(id: LockID, tid: TransactionID, path: string, intention: NodeLockIntention) { this.id = id; this.tid = tid; this.path = path; this.pathInfo = PathInfo.get(path); this.intention = intention; this.state = NodeLockState.pending; } } interface ITransactionManager { /** * Creates a transaction that handles lock requests */ createTransaction(): Promise<Transaction> /** * If a transaction is unable to determine if access can be granted by itself based upon the locks it currently holds, it will * have to forward the request to the TransactionManager that is able to check other transactions. * @param request request details */ requestLock(request: INodeLockRequest): Promise<NodeLockInfo> // releaseTransaction(tid: TransactionID): Promise<void> releaseLock(id: LockID): Promise<void> } export class TransactionManager implements ITransactionManager { private lastTid:TransactionID = 0; private lastLid:LockID = 0; private queue:IQueuedLockRequest[] = []; private locks:NodeLockInfo[] = []; private blacklisted: TransactionID[] = []; constructor() { } async createTransaction(): Promise<Transaction> { const tid = ++this.lastTid; const transaction = new Transaction(this, tid); // this.transactions.push(transaction); return transaction; } async requestLock(request: INodeLockRequest): Promise<NodeLockInfo> { if (this.blacklisted.includes(request.tid)) { throw new Error(`Transaction ${request.tid} not allowed to continue because one or more locks timed out`); } const lock = new NodeLockInfo(++this.lastLid, request.tid, request.path, request.intention); lock.requested = Date.now(); const grantLock = () => { lock.state = NodeLockState.locked; lock.granted = Date.now(); lock.expires = lock.granted + LOCK_TIMEOUT_MS this.locks.push(lock); } // Check locks held by other transactions for conflicts, then grant lock or queue. const allow = this.allowLock(request); if (allow.ok) { grantLock(); } else { // Queue let resolve, reject; const promise = new Promise((rs, rj) => { resolve = rs; reject = rj; }); const queuedRequest = { lock, queued: Date.now(), grant() { const i = this.queue.indexOf(this); this.queue.splice(i, 1); grantLock(); resolve(); } }; this.queue.push(queuedRequest); // Create timeout let timeoutsFired = 0; const timeoutHandler = () => { timeoutsFired++; const lock = queuedRequest.lock, tid = lock.tid, blacklisted = this.blacklisted.includes(tid), terminate = timeoutsFired === 3 || blacklisted; console.warn(`${request.intention.constructor.name} lock on "/${request.path}" is taking a long time [${timeoutsFired}]${terminate ? '. terminating.' : ''} (id ${lock.id}, tid ${lock.tid})`); if (terminate) { const i = this.queue.indexOf(queuedRequest); this.queue.splice(i, 1); !blacklisted && this.blacklisted.push(tid); return reject(new Error(`Lock timeout`)); } timeout = setTimeout(timeoutHandler, LOCK_TIMEOUT_MS / 3); }; let timeout = setTimeout(timeoutHandler, LOCK_TIMEOUT_MS / 3); // Wait until we get lock await promise; // Disable timeout clearTimeout(timeout); } return lock; } async releaseLock(id: LockID) { const index = this.locks.findIndex(l => l.id === id); if (index < 0) { throw new Error(`Lock ${id} not found`); } this.locks.splice(index, 1); this.processQueue(); } private processQueue() { this.queue.forEach((item, i, queue) => { const allow = this.allowLock(item.lock); if (allow) { item.grant(); // item will be removed from the queue by grant callback } }); } private allowLock(request: INodeLockRequest|NodeLockInfo) { // Get current granted locks in other transactions const otherLocks = this.locks.filter(lock => lock.tid !== request.tid && lock.state === NodeLockState.locked); // Find clashing lock const conflict = otherLocks.find(lock => this.conflicts(request, lock)); return { ok: !conflict, conflict }; } public testConflict(lock: { path: string, intention: NodeLockIntention}, request: { path: string, intention: NodeLockIntention }) { const lockInfo = new NodeLockInfo(1, 1, lock.path, lock.intention); const lockRequest: INodeLockRequest = { tid: 2, path: request.path, intention: request.intention }; const conflict = this.conflicts(lockRequest, lockInfo); // Also test reverse outcome: const revLockInfo = new NodeLockInfo(1, 1, request.path, request.intention); const revLockRequest: INodeLockRequest = { tid: 2, path: lock.path, intention: lock.intention }; const reverse = this.conflicts(revLockRequest, revLockInfo); return [ conflict, reverse ]; } private conflictsLegacy(request: INodeLockRequest, lock: NodeLockInfo) { // The legacy locking allowed 1 simultanious write, and denies writes while reading. // So, a requested write lock always conflicts with any other granted lock return request.intention instanceof OverwriteNodeIntention || request.intention instanceof UpdateNodeIntention; } private conflicts(request: INodeLockRequest, lock: NodeLockInfo) { // Returns true if the request lock conflicts with given existing lock if (!request.pathInfo) { request.pathInfo = PathInfo.get(request.path); } const requestPath = request.pathInfo; const lockPath = lock.pathInfo; if (request.intention instanceof ReadInfoIntention) { // Requested lock is to read info for a specific node and/or its children for reflection purposes if (lock.intention instanceof OverwriteNodeIntention) { // overwrite lock on "users/ewout/address" // deny info requests for "users/ewout" // deny info requests for "users/ewout/address(/*)" return requestPath.isParentOf(lockPath) || lock.path === request.path || requestPath.isDescendantOf(lockPath); } else if (lock.intention instanceof UpdateNodeIntention) { // update lock on "users/ewout/address" (keys "street", "nr"): // deny info requests for "users/ewout/address", "users/ewout/address/street(/*)", "users/ewout/address/nr(/*)" // allow info requests for all else, eg "users/ewout/address/city" return request.path === lock.path || (requestPath.isDescendantOf(lockPath) && lock.intention.keys.some(key => requestPath.isOnTrailOf(lockPath.child(key)))); } // Other lock is read lock, allowed return false; } else if (request.intention instanceof ReadValueIntention) { // Requested lock is to read the value of a specific node, optionally filtering the children if (lock.intention instanceof ReadValueIntention || lock.intention instanceof ReadInfoIntention) { // existing lock is for reading. No conflict return false; } const checkPath = (checkPath:PathInfo) => { if (lock.intention instanceof UpdateNodeIntention) { // update lock on "users/ewout/address" (keys "street", "nr"): // deny value request for paths "", "users", "users/ewout", "users/ewout/address", "users/ewout/address", "users/ewout/address/street(/*)", "users/ewout/address/nr(/*)" // allow value requests for all else return checkPath.isOnTrailOf(lockPath) || lock.intention.keys.some(key => checkPath.isOnTrailOf(lockPath.child(key))); } else if (lock.intention instanceof OverwriteNodeIntention) { // overwrite lock on "users/ewout/address": // deny value request for anything on that trail return checkPath.isOnTrailOf(lockPath); } return false; }; let conflict = checkPath(requestPath); if (!request.intention.filter) { // Requested lock is unfiltered - all data will be read } if (conflict && request.intention.filter && !requestPath.isDescendantOf(lockPath)) { // Requested lock is filtered - only selected data will be read conflict = false; if (request.intention.filter.include instanceof Array) { // The intention has an include filter to read only specified child keys/paths conflict = requestPath.equals(lockPath) || request.intention.filter.include.some(key => checkPath(requestPath.child(key))); } if (!conflict && request.intention.filter.exclude instanceof Array) { // request intention excludes 1 or more child keys/paths. If the lock is not on any of the excluded children, it is a conflict conflict = requestPath.equals(lockPath) || !request.intention.filter.exclude.some(key => checkPath(requestPath.child(key))); } if (!conflict && request.intention.filter.child_objects === false) { // child objects will not be loaded, so if the lock is writing to requestPath/obj/... that is no problem. const allow = lockPath.isDescendantOf(requestPath.child('*')) || (lock.intention instanceof UpdateNodeIntention && lockPath.equals(requestPath.child('*'))); conflict = !allow; } } return conflict; } else if (request.intention instanceof OverwriteNodeIntention) { // Requested lock is to overwrite a specific node if (lock.intention instanceof UpdateNodeIntention) { // update of "users/ewout/address" (keys "street", "nr"): // deny overwrites on "", "users", "users/ewout", "users/ewout/address", "users/ewout/address/street(/*)", "users/ewout/address/nr(/*)" // allow overwrite on "users/ewout/address/city" return requestPath.equals(lockPath) || requestPath.isAncestorOf(lockPath) || lock.intention.keys.some(key => requestPath.equals(lockPath.child(key)) || requestPath.isAncestorOf(lockPath.child(key))); } else if (lock.intention instanceof ReadInfoIntention) { // read info of "users/ewout/address" // deny overwrites on "", "users", "users/ewout", "users/ewout/address(/*)" // allow overwrites on "users/ewout/address/*/*" return requestPath.equals(lockPath) || requestPath.isAncestorOf(lockPath) || requestPath.isChildOf(lockPath); } else if (lock.intention instanceof ReadValueIntention) { // lock is read value of "users/ewout/address" // deny requested overwrites on "", "users", "users/ewout", "users/ewout/address(/*)" // BUT: // allow requested overwrite on "users/ewout/address/nr" if read does NOT have "nr" in filter.include // allow requested overwrite on "users/ewout/address/collection/key" if read does NOT have "collection", "collection/*" or "*/key" etc in filter.include // allow requested overwrite on "users/ewout/address/street" if read has "street" in filter.exclude // allow requested overwrite on "users/ewout/address/*/*" if read filter.child_objects === false let conflict = requestPath.isOnTrailOf(lockPath); if (conflict && lock.intention.filter && requestPath.isDescendantOf(lockPath)) { conflict = false; if (lock.intention.filter.include instanceof Array) { conflict = lock.intention.filter.include.some(key => { // read lock on "users/ewout/address", include ["street", "nr"] // conflict if overwrite request equals or is descendant of "users/ewout/address/street" or "users/ewout/address/nr" const childLockPath = lockPath.child(key); return requestPath.equals(childLockPath) || requestPath.isDescendantOf(childLockPath) }); } if (!conflict && lock.intention.filter.exclude instanceof Array) { conflict = !lock.intention.filter.exclude.some(key => { // read lock on "users/ewout/address", exclude ["street", "nr"] // conflict if overwrite request equals or is descendant of "users/ewout/address/street" or "users/ewout/address/nr" const childLockPath = lockPath.child(key); return requestPath.equals(childLockPath) || requestPath.isDescendantOf(childLockPath) }); } if (!conflict && lock.intention.filter.child_objects === false) { // read lock on "users/ewout", no child_objects // conflict if overwrite request is a child of "users/ewout", eg "users/ewout/address" conflict = requestPath.isChildOf(lockPath); } } return conflict; } else if (lock.intention instanceof OverwriteNodeIntention) { // overwrite of "users/ewout/address" // deny overwrites on "", "users", "users/ewout", "users/ewout/address(/*)" return requestPath.isOnTrailOf(lockPath); } } else if (request.intention instanceof UpdateNodeIntention) { // Requested lock is to update a specific node if (lock.intention instanceof UpdateNodeIntention) { // update of "users/ewout/address" (keys "street", "nr"): // deny updates on "" (key "users"), "users" (key "ewout"), "users/ewout" (key "address"), "users/ewout/address" (keys "street", "nr") const lockedPaths = lock.intention.keys.map(key => lockPath.child(key)); // eg: ["users/ewout/address/street", "users/ewout/address/nr"] const overwritePaths = request.intention.keys.map(key => requestPath.child(key)); // eg: ["users/ewout/address/city" (allow), "users/ewout/address/street" (deny)] // or: ["users/ewout" (deny)] return lockedPaths.some(lockPath => overwritePaths.some(overwritePath => overwritePath.isOnTrailOf(lockPath))); } else if (lock.intention instanceof OverwriteNodeIntention) { // overwrite of "users/ewout/address" // deny updates on "" (key "users"), "users" (key "ewout"), "users/ewout" (key "address"), "users/ewout/address(/*)" (any key) const overwritePaths = request.intention.keys.map(key => requestPath.child(key)); // eg: ["users/ewout/address/city" (deny), "users/ewout/address/street" (deny)] // or: ["users/ewout/last_login" (allow), "users/ewout/address" (deny)] // or: "users/ewout" (deny) return overwritePaths.some(path => path.isOnTrailOf(lockPath)); } else if (lock.intention instanceof ReadInfoIntention) { // read info of "users/ewout/address": // deny updates on "" (key "users"), "users" (key "ewout"), "users/ewout" (key "address"), "users/ewout/address" (any key) // allow updates on "users/ewout/address/*/*" const overwritePaths = request.intention.keys.map(key => requestPath.child(key)); return overwritePaths.some(path => path.equals(lockPath) || path.isAncestorOf(lockPath) || path.isChildOf(lockPath)); } else if (lock.intention instanceof ReadValueIntention) { // read value lock on "users/ewout/address": // when unfiltered: // deny requested updates on "" (key "users"), "users" (key "ewout"), "users/ewout" (key "address"), "users/ewout/address(/*)" (any key) const overwritePaths = request.intention.keys.map(key => requestPath.child(key)); // eg: ["users/ewout/address/city" (deny), "users/ewout/address/street" (deny)] // or: ["users/ewout/last_login" (allow), "users/ewout/address" (deny)] // or: ["users/ewout"] (deny) let conflict = overwritePaths.some(path => path.isOnTrailOf(lockPath)); if (conflict && lock.intention.filter && !requestPath.isAncestorOf(lockPath)) { conflict = false; if (lock.intention.filter.include instanceof Array) { // include ["street", "nr"]: // deny writes on "users/ewout/address/street" and "users/ewout/address/nr" const readPaths = lock.intention.filter.include.map(key => lockPath.child(key)); conflict = overwritePaths.some(writePath => readPaths.some(readPath => writePath.isOnTrailOf(readPath))); } if (!conflict && lock.intention.filter.exclude instanceof Array) { // exclude ["street", "nr"]: // deny writes on "users/ewout/address/(not street or nr)" const unreadPaths = lock.intention.filter.include.map(key => lockPath.child(key)); conflict = !overwritePaths.every(writePath => unreadPaths.some(readPath => writePath.isOnTrailOf(readPath))); } if (!conflict && lock.intention.filter.child_objects === false) { // deny writes on direct children of lockPath conflict = !overwritePaths.every(writePath => lockPath.child('*').isAncestorOf(writePath)); } } return conflict; } } return false; // Should not be able to get here? } } export class IPCTransactionManager extends TransactionManager { constructor (private ipc: IPCPeer) { super(); this.init(); } private init() { if (!this.ipc.isMaster) { return; } this.ipc.on('request', async (request: any) => { try { if (request.type === 'transaction.create') { const transaction = await this.createTransaction(); const tx = { id: transaction.id }; this.ipc.replyRequest(request, { ok: true, transaction }); } else if (request.type === 'transaction.lock') { const lock = await this.requestLock(request.lock); this.ipc.replyRequest(request, { ok: true, lock }); } else if (request.type === 'transaction.release') { await this.releaseLock(request.id); this.ipc.replyRequest(request, { ok: true }); } } catch(err) { this.ipc.replyRequest(request, { ok: false, error: err.message }); } }) } async createTransaction() : Promise<Transaction> { if (this.ipc.isMaster) { return super.createTransaction(); } else { const result = await this.ipc.sendRequest({ type: 'transaction.create' }); if (!result.ok) { throw new Error(result.error); } const transaction = new Transaction(this, result.transaction.id); return transaction; } } async requestLock(request: INodeLockRequest): Promise<NodeLockInfo> { if (this.ipc.isMaster) { return super.requestLock(request); } const result = await this.ipc.sendRequest({ type: 'transaction.lock', lock: request }); if (!result.ok) { throw new Error(result.error); } return result.lock as NodeLockInfo; } async releaseLock(id: LockID) { if (this.ipc.isMaster) { return super.releaseLock(id); } const result = await this.ipc.sendRequest({ type: 'transaction.release', id }); if (!result.ok) { throw new Error(result.error); } } } export class NodeLock extends NodeLockInfo { constructor(private transaction: Transaction, lockInfo: NodeLockInfo) { super(lockInfo.id, transaction.id, lockInfo.path, lockInfo.intention); } async release() { return this.transaction.manager.releaseLock(this.id); } } export class Transaction { readonly id: TransactionID; readonly locks: NodeLockInfo[]; constructor(public manager: ITransactionManager, id: TransactionID) { this.id = id; this.locks = []; } async lock(path: string, intention: NodeLockIntention): Promise<NodeLock> { const lockInfo = await this.manager.requestLock({ tid: this.id, path, intention }); this.locks.push(lockInfo); return new NodeLock(this, lockInfo); } }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>Specifies whether to get notified for alarm state changes.</p> */ export interface AcknowledgeFlow { /** * <p>The value must be <code>TRUE</code> or <code>FALSE</code>. If <code>TRUE</code>, you * receive a notification when the alarm state changes. You must choose to acknowledge the * notification before the alarm state can return to <code>NORMAL</code>. If <code>FALSE</code>, * you won't receive notifications. The alarm automatically changes to the <code>NORMAL</code> * state when the input property value returns to the specified range.</p> */ enabled: boolean | undefined; } export namespace AcknowledgeFlow { /** * @internal */ export const filterSensitiveLog = (obj: AcknowledgeFlow): any => ({ ...obj, }); } /** * <p>Information needed to clear the timer.</p> */ export interface ClearTimerAction { /** * <p>The name of the timer to clear.</p> */ timerName: string | undefined; } export namespace ClearTimerAction { /** * @internal */ export const filterSensitiveLog = (obj: ClearTimerAction): any => ({ ...obj, }); } export enum PayloadType { JSON = "JSON", STRING = "STRING", } /** * <p>Information needed to configure the payload.</p> * <p>By default, AWS IoT Events generates a standard payload in JSON for any action. This action payload * contains all attribute-value pairs that have the information about the detector model instance * and the event triggered the action. To configure the action payload, you can use * <code>contentExpression</code>.</p> */ export interface Payload { /** * <p>The content of the payload. You can use a string expression that includes quoted strings * (<code>'<string>'</code>), variables (<code>$variable.<variable-name></code>), * input values (<code>$input.<input-name>.<path-to-datum></code>), string * concatenations, and quoted strings that contain <code>${}</code> as the content. The * recommended maximum size of a content expression is 1 KB.</p> */ contentExpression: string | undefined; /** * <p>The value of the payload type can be either <code>STRING</code> or * <code>JSON</code>.</p> */ type: PayloadType | string | undefined; } export namespace Payload { /** * @internal */ export const filterSensitiveLog = (obj: Payload): any => ({ ...obj, }); } /** * <p>Defines an action to write to the Amazon DynamoDB table that you created. The standard action * payload contains all the information about the detector model instance and the event that * triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. One column of the * DynamoDB table receives all attribute-value pairs in the payload that you specify.</p> * <p>You must use expressions for all parameters in <code>DynamoDBAction</code>. The expressions * accept literals, operators, functions, references, and substitution templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>hashKeyType</code> parameter can be <code>'STRING'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>hashKeyField</code> parameter can be * <code>$input.GreenhouseInput.name</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>hashKeyValue</code> parameter uses a * substitution template. </p> * <p> * <code>'${$input.GreenhouseInput.temperature * 6 / 5 + 32} in Fahrenheit'</code> * </p> * </li> * <li> * <p>For a string concatenation, you must use <code>+</code>. A string concatenation can * also contain a combination of literals, operators, functions, references, and substitution * templates.</p> * <p>In the following example, the value for the <code>tableName</code> parameter uses a * string concatenation. </p> * <p> * <code>'GreenhouseTemperatureTable ' + $input.GreenhouseInput.date</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>If the defined payload type is a string, <code>DynamoDBAction</code> writes non-JSON data to * the DynamoDB table as binary data. The DynamoDB console displays the data as Base64-encoded text. * The value for the <code>payloadField</code> parameter is * <code><payload-field>_raw</code>.</p> */ export interface DynamoDBAction { /** * <p>The data type for the hash key (also called the partition key). You can specify the * following values:</p> * <ul> * <li> * <p> * <code>'STRING'</code> - The hash key is a string.</p> * </li> * <li> * <p> * <code>'NUMBER'</code> - The hash key is a number.</p> * </li> * </ul> * <p>If you don't specify <code>hashKeyType</code>, the default value is * <code>'STRING'</code>.</p> */ hashKeyType?: string; /** * <p>The name of the hash key (also called the partition key). The <code>hashKeyField</code> * value must match the partition key of the target DynamoDB table.</p> */ hashKeyField: string | undefined; /** * <p>The value of the hash key (also called the partition key).</p> */ hashKeyValue: string | undefined; /** * <p>The data type for the range key (also called the sort key), You can specify the following * values:</p> * <ul> * <li> * <p> * <code>'STRING'</code> - The range key is a string.</p> * </li> * <li> * <p> * <code>'NUMBER'</code> - The range key is number.</p> * </li> * </ul> * <p>If you don't specify <code>rangeKeyField</code>, the default value is * <code>'STRING'</code>.</p> */ rangeKeyType?: string; /** * <p>The name of the range key (also called the sort key). The <code>rangeKeyField</code> value * must match the sort key of the target DynamoDB table. </p> */ rangeKeyField?: string; /** * <p>The value of the range key (also called the sort key).</p> */ rangeKeyValue?: string; /** * <p>The type of operation to perform. You can specify the following values: </p> * <ul> * <li> * <p> * <code>'INSERT'</code> - Insert data as a new item into the DynamoDB table. This item uses * the specified hash key as a partition key. If you specified a range key, the item uses the * range key as a sort key.</p> * </li> * <li> * <p> * <code>'UPDATE'</code> - Update an existing item of the DynamoDB table with new data. This * item's partition key must match the specified hash key. If you specified a range key, the * range key must match the item's sort key.</p> * </li> * <li> * <p> * <code>'DELETE'</code> - Delete an existing item of the DynamoDB table. This item's * partition key must match the specified hash key. If you specified a range key, the range * key must match the item's sort key.</p> * </li> * </ul> * <p>If you don't specify this parameter, AWS IoT Events triggers the <code>'INSERT'</code> * operation.</p> */ operation?: string; /** * <p>The name of the DynamoDB column that receives the action payload.</p> * <p>If you don't specify this parameter, the name of the DynamoDB column is * <code>payload</code>.</p> */ payloadField?: string; /** * <p>The name of the DynamoDB table. The <code>tableName</code> value must match the table name of * the target DynamoDB table. </p> */ tableName: string | undefined; /** * <p>Information needed to configure the payload.</p> * <p>By default, AWS IoT Events generates a standard payload in JSON for any action. This action payload * contains all attribute-value pairs that have the information about the detector model instance * and the event triggered the action. To configure the action payload, you can use * <code>contentExpression</code>.</p> */ payload?: Payload; } export namespace DynamoDBAction { /** * @internal */ export const filterSensitiveLog = (obj: DynamoDBAction): any => ({ ...obj, }); } /** * <p>Defines an action to write to the Amazon DynamoDB table that you created. The default action * payload contains all the information about the detector model instance and the event that * triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. A separate column of * the DynamoDB table receives one attribute-value pair in the payload that you specify.</p> * <p>You must use expressions for all parameters in <code>DynamoDBv2Action</code>. The expressions * accept literals, operators, functions, references, and substitution templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>tableName</code> parameter can be * <code>'GreenhouseTemperatureTable'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>tableName</code> parameter can be * <code>$variable.ddbtableName</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>contentExpression</code> parameter * in <code>Payload</code> uses a substitution template. </p> * <p> * <code>'{\"sensorID\": \"${$input.GreenhouseInput.sensor_id}\", \"temperature\": * \"${$input.GreenhouseInput.temperature * 9 / 5 + 32}\"}'</code> * </p> * </li> * <li> * <p>For a string concatenation, you must use <code>+</code>. A string concatenation can * also contain a combination of literals, operators, functions, references, and substitution * templates.</p> * <p>In the following example, the value for the <code>tableName</code> parameter uses a * string concatenation. </p> * <p> * <code>'GreenhouseTemperatureTable ' + $input.GreenhouseInput.date</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>The value for the <code>type</code> parameter in <code>Payload</code> must be * <code>JSON</code>.</p> */ export interface DynamoDBv2Action { /** * <p>The name of the DynamoDB table.</p> */ tableName: string | undefined; /** * <p>Information needed to configure the payload.</p> * <p>By default, AWS IoT Events generates a standard payload in JSON for any action. This action payload * contains all attribute-value pairs that have the information about the detector model instance * and the event triggered the action. To configure the action payload, you can use * <code>contentExpression</code>.</p> */ payload?: Payload; } export namespace DynamoDBv2Action { /** * @internal */ export const filterSensitiveLog = (obj: DynamoDBv2Action): any => ({ ...obj, }); } /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon Kinesis Data Firehose delivery stream.</p> */ export interface FirehoseAction { /** * <p>The name of the Kinesis Data Firehose delivery stream where the data is written.</p> */ deliveryStreamName: string | undefined; /** * <p>A character separator that is used to separate records written to the Kinesis Data * Firehose delivery stream. Valid values are: '\n' (newline), '\t' (tab), '\r\n' (Windows * newline), ',' (comma).</p> */ separator?: string; /** * <p>You can configure the action payload when you send a message to an Amazon Kinesis Data Firehose delivery * stream.</p> */ payload?: Payload; } export namespace FirehoseAction { /** * @internal */ export const filterSensitiveLog = (obj: FirehoseAction): any => ({ ...obj, }); } /** * <p>Sends an AWS IoT Events input, passing in information about the detector model instance and the * event that triggered the action.</p> */ export interface IotEventsAction { /** * <p>The name of the AWS IoT Events input where the data is sent.</p> */ inputName: string | undefined; /** * <p>You can configure the action payload when you send a message to an AWS IoT Events input.</p> */ payload?: Payload; } export namespace IotEventsAction { /** * @internal */ export const filterSensitiveLog = (obj: IotEventsAction): any => ({ ...obj, }); } /** * <p>A structure that contains timestamp information. For more information, see <a href="https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_TimeInNanos.html">TimeInNanos</a> in the <i>AWS IoT SiteWise API Reference</i>.</p> * <p>You must use expressions for all parameters in <code>AssetPropertyTimestamp</code>. The * expressions accept literals, operators, functions, references, and substitution * templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>timeInSeconds</code> parameter can be <code>'1586400675'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>offsetInNanos</code> parameter can be * <code>$variable.time</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>timeInSeconds</code> parameter uses * a substitution template.</p> * <p> * <code>'${$input.TemperatureInput.sensorData.timestamp / 1000}'</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> */ export interface AssetPropertyTimestamp { /** * <p>The timestamp, in seconds, in the Unix epoch format. The valid range is between * 1-31556889864403199.</p> */ timeInSeconds: string | undefined; /** * <p>The nanosecond offset converted from <code>timeInSeconds</code>. The valid range is * between 0-999999999.</p> */ offsetInNanos?: string; } export namespace AssetPropertyTimestamp { /** * @internal */ export const filterSensitiveLog = (obj: AssetPropertyTimestamp): any => ({ ...obj, }); } /** * <p>A structure that contains an asset property value. For more information, see <a href="https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_Variant.html">Variant</a> * in the <i>AWS IoT SiteWise API Reference</i>.</p> * <p>You must use expressions for all parameters in <code>AssetPropertyVariant</code>. The * expressions accept literals, operators, functions, references, and substitution * templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>integerValue</code> parameter can be <code>'100'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or parameters. For example, the * value for the <code>booleanValue</code> parameter can be * <code>$variable.offline</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates. </p> * <p>In the following example, the value for the <code>doubleValue</code> parameter uses a * substitution template. </p> * <p> * <code>'${$input.TemperatureInput.sensorData.temperature * 6 / 5 + 32}'</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>You must specify one of the following value types, depending on the <code>dataType</code> * of the specified asset property. For more information, see <a href="https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_AssetProperty.html">AssetProperty</a> in the * <i>AWS IoT SiteWise API Reference</i>.</p> */ export interface AssetPropertyVariant { /** * <p>The asset property value is a string. You must use an expression, and the evaluated result * should be a string.</p> */ stringValue?: string; /** * <p>The asset property value is an integer. You must use an expression, and the evaluated * result should be an integer.</p> */ integerValue?: string; /** * <p>The asset property value is a double. You must use an expression, and the evaluated result * should be a double.</p> */ doubleValue?: string; /** * <p>The asset property value is a Boolean value that must be <code>'TRUE'</code> or * <code>'FALSE'</code>. You must use an expression, and the evaluated result should be a * Boolean value.</p> */ booleanValue?: string; } export namespace AssetPropertyVariant { /** * @internal */ export const filterSensitiveLog = (obj: AssetPropertyVariant): any => ({ ...obj, }); } /** * <p>A structure that contains value information. For more information, see <a href="https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_AssetPropertyValue.html">AssetPropertyValue</a> in the <i>AWS IoT SiteWise API Reference</i>.</p> * <p>You must use expressions for all parameters in <code>AssetPropertyValue</code>. The * expressions accept literals, operators, functions, references, and substitution * templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>quality</code> parameter can be <code>'GOOD'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>quality</code> parameter can be * <code>$input.TemperatureInput.sensorData.quality</code>.</p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> */ export interface AssetPropertyValue { /** * <p>The value to send to an asset property.</p> */ value?: AssetPropertyVariant; /** * <p>The timestamp associated with the asset property value. The default is the current event * time.</p> */ timestamp?: AssetPropertyTimestamp; /** * <p>The quality of the asset property value. The value must be <code>'GOOD'</code>, * <code>'BAD'</code>, or <code>'UNCERTAIN'</code>.</p> */ quality?: string; } export namespace AssetPropertyValue { /** * @internal */ export const filterSensitiveLog = (obj: AssetPropertyValue): any => ({ ...obj, }); } /** * <p>Sends information about the detector model instance and the event that triggered the * action to a specified asset property in AWS IoT SiteWise.</p> * <p>You must use expressions for all parameters in <code>IotSiteWiseAction</code>. The * expressions accept literals, operators, functions, references, and substitutions * templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>propertyAlias</code> parameter can be * <code>'/company/windfarm/3/turbine/7/temperature'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>assetId</code> parameter can be * <code>$input.TurbineInput.assetId1</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>propertyAlias</code> parameter uses * a substitution template. </p> * <p> * <code>'company/windfarm/${$input.TemperatureInput.sensorData.windfarmID}/turbine/ * ${$input.TemperatureInput.sensorData.turbineID}/temperature'</code> * </p> * </li> * </ul> * <p>You must specify either <code>propertyAlias</code> or both <code>assetId</code> and * <code>propertyId</code> to identify the target asset property in AWS IoT SiteWise.</p> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> */ export interface IotSiteWiseAction { /** * <p>A unique identifier for this entry. You can use the entry ID to track which data entry * causes an error in case of failure. The default is a new unique identifier.</p> */ entryId?: string; /** * <p>The ID of the asset that has the specified property.</p> */ assetId?: string; /** * <p>The ID of the asset property.</p> */ propertyId?: string; /** * <p>The alias of the asset property.</p> */ propertyAlias?: string; /** * <p>The value to send to the asset property. This value contains timestamp, quality, and value * (TQV) information. </p> */ propertyValue?: AssetPropertyValue; } export namespace IotSiteWiseAction { /** * @internal */ export const filterSensitiveLog = (obj: IotSiteWiseAction): any => ({ ...obj, }); } /** * <p>Information required to publish the MQTT message through the AWS IoT message broker.</p> */ export interface IotTopicPublishAction { /** * <p>The MQTT topic of the message. You can use a string expression that includes variables * (<code>$variable.<variable-name></code>) and input values * (<code>$input.<input-name>.<path-to-datum></code>) as the topic string.</p> */ mqttTopic: string | undefined; /** * <p>You can configure the action payload when you publish a message to an AWS IoT Core * topic.</p> */ payload?: Payload; } export namespace IotTopicPublishAction { /** * @internal */ export const filterSensitiveLog = (obj: IotTopicPublishAction): any => ({ ...obj, }); } /** * <p>Calls a Lambda function, passing in information about the detector model instance and the * event that triggered the action.</p> */ export interface LambdaAction { /** * <p>The ARN of the Lambda function that is executed.</p> */ functionArn: string | undefined; /** * <p>You can configure the action payload when you send a message to a Lambda function.</p> */ payload?: Payload; } export namespace LambdaAction { /** * @internal */ export const filterSensitiveLog = (obj: LambdaAction): any => ({ ...obj, }); } /** * <p>Information required to reset the timer. The timer is reset to the previously evaluated * result of the duration. The duration expression isn't reevaluated when you reset the * timer.</p> */ export interface ResetTimerAction { /** * <p>The name of the timer to reset.</p> */ timerName: string | undefined; } export namespace ResetTimerAction { /** * @internal */ export const filterSensitiveLog = (obj: ResetTimerAction): any => ({ ...obj, }); } /** * <p>Information needed to set the timer.</p> */ export interface SetTimerAction { /** * <p>The name of the timer.</p> */ timerName: string | undefined; /** * @deprecated * * <p>The number of seconds until the timer expires. The minimum value is 60 seconds to ensure * accuracy. The maximum value is 31622400 seconds. </p> */ seconds?: number; /** * <p>The duration of the timer, in seconds. You can use a string expression that includes * numbers, variables (<code>$variable.<variable-name></code>), and input values * (<code>$input.<input-name>.<path-to-datum></code>) as the duration. The range of * the duration is 1-31622400 seconds. To ensure accuracy, the minimum duration is 60 seconds. * The evaluated result of the duration is rounded down to the nearest whole number. </p> */ durationExpression?: string; } export namespace SetTimerAction { /** * @internal */ export const filterSensitiveLog = (obj: SetTimerAction): any => ({ ...obj, }); } /** * <p>Information about the variable and its new value.</p> */ export interface SetVariableAction { /** * <p>The name of the variable.</p> */ variableName: string | undefined; /** * <p>The new value of the variable.</p> */ value: string | undefined; } export namespace SetVariableAction { /** * @internal */ export const filterSensitiveLog = (obj: SetVariableAction): any => ({ ...obj, }); } /** * <p>Information required to publish the Amazon SNS message.</p> */ export interface SNSTopicPublishAction { /** * <p>The ARN of the Amazon SNS target where the message is sent.</p> */ targetArn: string | undefined; /** * <p>You can configure the action payload when you send a message as an Amazon SNS push * notification.</p> */ payload?: Payload; } export namespace SNSTopicPublishAction { /** * @internal */ export const filterSensitiveLog = (obj: SNSTopicPublishAction): any => ({ ...obj, }); } /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon SQS queue.</p> */ export interface SqsAction { /** * <p>The URL of the SQS queue where the data is written.</p> */ queueUrl: string | undefined; /** * <p>Set this to TRUE if you want the data to be base-64 encoded before it is written to the * queue. Otherwise, set this to FALSE.</p> */ useBase64?: boolean; /** * <p>You can configure the action payload when you send a message to an Amazon SQS * queue.</p> */ payload?: Payload; } export namespace SqsAction { /** * @internal */ export const filterSensitiveLog = (obj: SqsAction): any => ({ ...obj, }); } /** * <p>An action to be performed when the <code>condition</code> is TRUE.</p> */ export interface Action { /** * <p>Sets a variable to a specified value.</p> */ setVariable?: SetVariableAction; /** * <p>Sends an Amazon SNS message.</p> */ sns?: SNSTopicPublishAction; /** * <p>Publishes an MQTT message with the given topic to the AWS IoT message broker.</p> */ iotTopicPublish?: IotTopicPublishAction; /** * <p>Information needed to set the timer.</p> */ setTimer?: SetTimerAction; /** * <p>Information needed to clear the timer.</p> */ clearTimer?: ClearTimerAction; /** * <p>Information needed to reset the timer.</p> */ resetTimer?: ResetTimerAction; /** * <p>Calls a Lambda function, passing in information about the detector model instance and the * event that triggered the action.</p> */ lambda?: LambdaAction; /** * <p>Sends AWS IoT Events input, which passes information about the detector model instance and the * event that triggered the action.</p> */ iotEvents?: IotEventsAction; /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon SQS queue.</p> */ sqs?: SqsAction; /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon Kinesis Data Firehose delivery stream.</p> */ firehose?: FirehoseAction; /** * <p>Writes to the DynamoDB table that you created. The default action payload contains all * attribute-value pairs that have the information about the detector model instance and the * event that triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. One column of the * DynamoDB table receives all attribute-value pairs in the payload that you specify. For more * information, see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-event-actions.html">Actions</a> in * <i>AWS IoT Events Developer Guide</i>.</p> */ dynamoDB?: DynamoDBAction; /** * <p>Writes to the DynamoDB table that you created. The default action payload contains all * attribute-value pairs that have the information about the detector model instance and the * event that triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. A separate column of * the DynamoDB table receives one attribute-value pair in the payload that you specify. For more * information, see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-event-actions.html">Actions</a> in * <i>AWS IoT Events Developer Guide</i>.</p> */ dynamoDBv2?: DynamoDBv2Action; /** * <p>Sends information about the detector model instance and the event that triggered the * action to an asset property in AWS IoT SiteWise .</p> */ iotSiteWise?: IotSiteWiseAction; } export namespace Action { /** * @internal */ export const filterSensitiveLog = (obj: Action): any => ({ ...obj, }); } /** * <p>Specifies one of the following actions to receive notifications when the alarm state * changes.</p> */ export interface AlarmAction { /** * <p>Information required to publish the Amazon SNS message.</p> */ sns?: SNSTopicPublishAction; /** * <p>Information required to publish the MQTT message through the AWS IoT message broker.</p> */ iotTopicPublish?: IotTopicPublishAction; /** * <p>Calls a Lambda function, passing in information about the detector model instance and the * event that triggered the action.</p> */ lambda?: LambdaAction; /** * <p>Sends an AWS IoT Events input, passing in information about the detector model instance and the * event that triggered the action.</p> */ iotEvents?: IotEventsAction; /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon SQS queue.</p> */ sqs?: SqsAction; /** * <p>Sends information about the detector model instance and the event that triggered the * action to an Amazon Kinesis Data Firehose delivery stream.</p> */ firehose?: FirehoseAction; /** * <p>Defines an action to write to the Amazon DynamoDB table that you created. The standard action * payload contains all the information about the detector model instance and the event that * triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. One column of the * DynamoDB table receives all attribute-value pairs in the payload that you specify.</p> * <p>You must use expressions for all parameters in <code>DynamoDBAction</code>. The expressions * accept literals, operators, functions, references, and substitution templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>hashKeyType</code> parameter can be <code>'STRING'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>hashKeyField</code> parameter can be * <code>$input.GreenhouseInput.name</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>hashKeyValue</code> parameter uses a * substitution template. </p> * <p> * <code>'${$input.GreenhouseInput.temperature * 6 / 5 + 32} in Fahrenheit'</code> * </p> * </li> * <li> * <p>For a string concatenation, you must use <code>+</code>. A string concatenation can * also contain a combination of literals, operators, functions, references, and substitution * templates.</p> * <p>In the following example, the value for the <code>tableName</code> parameter uses a * string concatenation. </p> * <p> * <code>'GreenhouseTemperatureTable ' + $input.GreenhouseInput.date</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>If the defined payload type is a string, <code>DynamoDBAction</code> writes non-JSON data to * the DynamoDB table as binary data. The DynamoDB console displays the data as Base64-encoded text. * The value for the <code>payloadField</code> parameter is * <code><payload-field>_raw</code>.</p> */ dynamoDB?: DynamoDBAction; /** * <p>Defines an action to write to the Amazon DynamoDB table that you created. The default action * payload contains all the information about the detector model instance and the event that * triggered the action. You can customize the <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Payload.html">payload</a>. A separate column of * the DynamoDB table receives one attribute-value pair in the payload that you specify.</p> * <p>You must use expressions for all parameters in <code>DynamoDBv2Action</code>. The expressions * accept literals, operators, functions, references, and substitution templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>tableName</code> parameter can be * <code>'GreenhouseTemperatureTable'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>tableName</code> parameter can be * <code>$variable.ddbtableName</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>contentExpression</code> parameter * in <code>Payload</code> uses a substitution template. </p> * <p> * <code>'{\"sensorID\": \"${$input.GreenhouseInput.sensor_id}\", \"temperature\": * \"${$input.GreenhouseInput.temperature * 9 / 5 + 32}\"}'</code> * </p> * </li> * <li> * <p>For a string concatenation, you must use <code>+</code>. A string concatenation can * also contain a combination of literals, operators, functions, references, and substitution * templates.</p> * <p>In the following example, the value for the <code>tableName</code> parameter uses a * string concatenation. </p> * <p> * <code>'GreenhouseTemperatureTable ' + $input.GreenhouseInput.date</code> * </p> * </li> * </ul> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>The value for the <code>type</code> parameter in <code>Payload</code> must be * <code>JSON</code>.</p> */ dynamoDBv2?: DynamoDBv2Action; /** * <p>Sends information about the detector model instance and the event that triggered the * action to a specified asset property in AWS IoT SiteWise.</p> * <p>You must use expressions for all parameters in <code>IotSiteWiseAction</code>. The * expressions accept literals, operators, functions, references, and substitutions * templates.</p> * <p class="title"> * <b>Examples</b> * </p> * <ul> * <li> * <p>For literal values, the expressions must contain single quotes. For example, the value * for the <code>propertyAlias</code> parameter can be * <code>'/company/windfarm/3/turbine/7/temperature'</code>.</p> * </li> * <li> * <p>For references, you must specify either variables or input values. For example, the * value for the <code>assetId</code> parameter can be * <code>$input.TurbineInput.assetId1</code>.</p> * </li> * <li> * <p>For a substitution template, you must use <code>${}</code>, and the template must be * in single quotes. A substitution template can also contain a combination of literals, * operators, functions, references, and substitution templates.</p> * <p>In the following example, the value for the <code>propertyAlias</code> parameter uses * a substitution template. </p> * <p> * <code>'company/windfarm/${$input.TemperatureInput.sensorData.windfarmID}/turbine/ * ${$input.TemperatureInput.sensorData.turbineID}/temperature'</code> * </p> * </li> * </ul> * <p>You must specify either <code>propertyAlias</code> or both <code>assetId</code> and * <code>propertyId</code> to identify the target asset property in AWS IoT SiteWise.</p> * <p>For more information, * see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-expressions.html">Expressions</a> * in the <i>AWS IoT Events Developer Guide</i>.</p> */ iotSiteWise?: IotSiteWiseAction; } export namespace AlarmAction { /** * @internal */ export const filterSensitiveLog = (obj: AlarmAction): any => ({ ...obj, }); } /** * <p>Specifies the default alarm state. * The configuration applies to all alarms that were created based on this alarm model.</p> */ export interface InitializationConfiguration { /** * <p>The value must be <code>TRUE</code> or <code>FALSE</code>. If <code>FALSE</code>, all * alarm instances created based on the alarm model are activated. The default value is * <code>TRUE</code>.</p> */ disabledOnInitialization: boolean | undefined; } export namespace InitializationConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: InitializationConfiguration): any => ({ ...obj, }); } /** * <p>Contains the configuration information of alarm state changes.</p> */ export interface AlarmCapabilities { /** * <p>Specifies the default alarm state. * The configuration applies to all alarms that were created based on this alarm model.</p> */ initializationConfiguration?: InitializationConfiguration; /** * <p>Specifies whether to get notified for alarm state changes.</p> */ acknowledgeFlow?: AcknowledgeFlow; } export namespace AlarmCapabilities { /** * @internal */ export const filterSensitiveLog = (obj: AlarmCapabilities): any => ({ ...obj, }); } /** * <p>Contains information about one or more alarm actions.</p> */ export interface AlarmEventActions { /** * <p>Specifies one or more supported actions to receive notifications when the alarm state * changes.</p> */ alarmActions?: AlarmAction[]; } export namespace AlarmEventActions { /** * @internal */ export const filterSensitiveLog = (obj: AlarmEventActions): any => ({ ...obj, }); } /** * <p>Contains a summary of an alarm model.</p> */ export interface AlarmModelSummary { /** * <p>The time the alarm model was created, in the Unix epoch format.</p> */ creationTime?: Date; /** * <p>The description of the alarm model.</p> */ alarmModelDescription?: string; /** * <p>The name of the alarm model.</p> */ alarmModelName?: string; } export namespace AlarmModelSummary { /** * @internal */ export const filterSensitiveLog = (obj: AlarmModelSummary): any => ({ ...obj, }); } export enum AlarmModelVersionStatus { ACTIVATING = "ACTIVATING", ACTIVE = "ACTIVE", FAILED = "FAILED", INACTIVE = "INACTIVE", } /** * <p>Contains a summary of an alarm model version.</p> */ export interface AlarmModelVersionSummary { /** * <p>The name of the alarm model.</p> */ alarmModelName?: string; /** * <p>The ARN of the alarm model. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ alarmModelArn?: string; /** * <p>The version of the alarm model.</p> */ alarmModelVersion?: string; /** * <p>The ARN of the IAM role that allows the alarm to perform actions and access AWS resources. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ roleArn?: string; /** * <p>The time the alarm model was created, in the Unix epoch format.</p> */ creationTime?: Date; /** * <p>The time the alarm model was last updated, in the Unix epoch format.</p> */ lastUpdateTime?: Date; /** * <p>The status of the alarm model. The status can be one of the following values:</p> * <ul> * <li> * <p> * <code>ACTIVE</code> - The alarm model is active and it's ready to evaluate data.</p> * </li> * <li> * <p> * <code>ACTIVATING</code> - AWS IoT Events is activating your alarm model. * Activating an alarm model can take up to a few minutes.</p> * </li> * <li> * <p> * <code>INACTIVE</code> - The alarm model is inactive, so it isn't ready to evaluate data. * Check your alarm model information and update the alarm model.</p> * </li> * <li> * <p> * <code>FAILED</code> - You couldn't create or update the alarm model. Check your alarm model information * and try again.</p> * </li> * </ul> */ status?: AlarmModelVersionStatus | string; /** * <p> * Contains information about the status of the alarm model version. * </p> */ statusMessage?: string; } export namespace AlarmModelVersionSummary { /** * @internal */ export const filterSensitiveLog = (obj: AlarmModelVersionSummary): any => ({ ...obj, }); } /** * <p>Specifies an AWS Lambda function to manage alarm notifications. * You can create one or use the <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/lambda-support.html">AWS Lambda function provided by AWS IoT Events</a>.</p> */ export interface NotificationTargetActions { /** * <p>Calls a Lambda function, passing in information about the detector model instance and the * event that triggered the action.</p> */ lambdaAction?: LambdaAction; } export namespace NotificationTargetActions { /** * @internal */ export const filterSensitiveLog = (obj: NotificationTargetActions): any => ({ ...obj, }); } /** * <p>Contains the subject and message of an email.</p> */ export interface EmailContent { /** * <p>The subject of the email.</p> */ subject?: string; /** * <p>The message that you want to send. The message can be up to 200 characters.</p> */ additionalMessage?: string; } export namespace EmailContent { /** * @internal */ export const filterSensitiveLog = (obj: EmailContent): any => ({ ...obj, }); } /** * <p>Contains information about your identity source in AWS Single Sign-On. For more information, see * the <a href="https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html">AWS Single Sign-On * User Guide</a>.</p> */ export interface SSOIdentity { /** * <p>The ID of the AWS SSO identity store.</p> */ identityStoreId: string | undefined; /** * <p>The user ID.</p> */ userId?: string; } export namespace SSOIdentity { /** * @internal */ export const filterSensitiveLog = (obj: SSOIdentity): any => ({ ...obj, }); } /** * <p>The information that identifies the recipient.</p> */ export interface RecipientDetail { /** * <p>The AWS Single Sign-On (AWS SSO) authentication information.</p> */ ssoIdentity?: SSOIdentity; } export namespace RecipientDetail { /** * @internal */ export const filterSensitiveLog = (obj: RecipientDetail): any => ({ ...obj, }); } /** * <p>Contains the information of one or more recipients who receive the emails.</p> * <important> * <p>You must <a href="https://docs.aws.amazon.com/singlesignon/latest/userguide/addusers.html">add the users that receive emails to your AWS SSO store</a>.</p> * </important> */ export interface EmailRecipients { /** * <p>Specifies one or more recipients who receive the email.</p> */ to?: RecipientDetail[]; } export namespace EmailRecipients { /** * @internal */ export const filterSensitiveLog = (obj: EmailRecipients): any => ({ ...obj, }); } /** * <p>Contains the configuration information of email notifications.</p> */ export interface EmailConfiguration { /** * <p>The email address that sends emails.</p> * <important> * <p>If you use the AWS IoT Events managed AWS Lambda function to manage your emails, you must <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses.html">verify * the email address that sends emails in Amazon SES</a>.</p> * </important> */ from: string | undefined; /** * <p>Contains the subject and message of an email.</p> */ content?: EmailContent; /** * <p>Contains the information of one or more recipients who receive the emails.</p> * <important> * <p>You must <a href="https://docs.aws.amazon.com/singlesignon/latest/userguide/addusers.html">add the users that receive emails to your AWS SSO store</a>.</p> * </important> */ recipients: EmailRecipients | undefined; } export namespace EmailConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: EmailConfiguration): any => ({ ...obj, }); } /** * <p>Contains the configuration information of SMS notifications.</p> */ export interface SMSConfiguration { /** * <p>The sender ID.</p> */ senderId?: string; /** * <p>The message that you want to send. The message can be up to 200 characters.</p> */ additionalMessage?: string; /** * <p>Specifies one or more recipients who receive the message.</p> * <important> * <p>You must <a href="https://docs.aws.amazon.com/singlesignon/latest/userguide/addusers.html">add the users that receive SMS messages to your AWS SSO store</a>.</p> * </important> */ recipients: RecipientDetail[] | undefined; } export namespace SMSConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: SMSConfiguration): any => ({ ...obj, }); } /** * <p>Contains the notification settings of an alarm model. * The settings apply to all alarms that were created based on this alarm model.</p> */ export interface NotificationAction { /** * <p>Specifies an AWS Lambda function to manage alarm notifications. * You can create one or use the <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/lambda-support.html">AWS Lambda function provided by AWS IoT Events</a>.</p> */ action: NotificationTargetActions | undefined; /** * <p>Contains the configuration information of SMS notifications.</p> */ smsConfigurations?: SMSConfiguration[]; /** * <p>Contains the configuration information of email notifications.</p> */ emailConfigurations?: EmailConfiguration[]; } export namespace NotificationAction { /** * @internal */ export const filterSensitiveLog = (obj: NotificationAction): any => ({ ...obj, }); } /** * <p>Contains information about one or more notification actions.</p> */ export interface AlarmNotification { /** * <p>Contains the notification settings of an alarm model. * The settings apply to all alarms that were created based on this alarm model.</p> */ notificationActions?: NotificationAction[]; } export namespace AlarmNotification { /** * @internal */ export const filterSensitiveLog = (obj: AlarmNotification): any => ({ ...obj, }); } export enum ComparisonOperator { EQUAL = "EQUAL", GREATER = "GREATER", GREATER_OR_EQUAL = "GREATER_OR_EQUAL", LESS = "LESS", LESS_OR_EQUAL = "LESS_OR_EQUAL", NOT_EQUAL = "NOT_EQUAL", } /** * <p>A rule that compares an input property value to a threshold value with a comparison operator.</p> */ export interface SimpleRule { /** * <p>The value on the left side of the comparison operator. You can specify an AWS IoT Events input * attribute as an input property.</p> */ inputProperty: string | undefined; /** * <p>The comparison operator.</p> */ comparisonOperator: ComparisonOperator | string | undefined; /** * <p>The value on the right side of the comparison operator. You can enter a number or specify * an AWS IoT Events input attribute.</p> */ threshold: string | undefined; } export namespace SimpleRule { /** * @internal */ export const filterSensitiveLog = (obj: SimpleRule): any => ({ ...obj, }); } /** * <p>Defines when your alarm is invoked.</p> */ export interface AlarmRule { /** * <p>A rule that compares an input property value to a threshold value with a comparison operator.</p> */ simpleRule?: SimpleRule; } export namespace AlarmRule { /** * @internal */ export const filterSensitiveLog = (obj: AlarmRule): any => ({ ...obj, }); } export enum AnalysisResultLevel { ERROR = "ERROR", INFO = "INFO", WARNING = "WARNING", } /** * <p>Contains information that you can use to locate the field in your detector model that the * analysis result references.</p> */ export interface AnalysisResultLocation { /** * <p>A <a href="https://github.com/json-path/JsonPath">JsonPath</a> expression that * identifies the error field in your detector model.</p> */ path?: string; } export namespace AnalysisResultLocation { /** * @internal */ export const filterSensitiveLog = (obj: AnalysisResultLocation): any => ({ ...obj, }); } /** * <p>Contains the result of the analysis.</p> */ export interface AnalysisResult { /** * <p>The type of the analysis result. Analyses fall into the following types based on the * validators used to generate the analysis result:</p> * <ul> * <li> * <p> * <code>supported-actions</code> - You must specify AWS IoT Events supported actions that work * with other AWS services in a supported AWS Region.</p> * </li> * <li> * <p> * <code>service-limits</code> - Resources or API operations can't exceed service * quotas (also known as limits). Update your detector model or request a quota * increase.</p> * </li> * <li> * <p> * <code>structure</code> - The detector model must follow a structure that AWS IoT Events * supports. </p> * </li> * <li> * <p> * <code>expression-syntax</code> - Your expression must follow the required * syntax.</p> * </li> * <li> * <p> * <code>data-type</code> - Data types referenced in the detector model must be * compatible.</p> * </li> * <li> * <p> * <code>referenced-data</code> - You must define the data referenced in your detector * model before you can use the data.</p> * </li> * <li> * <p> * <code>referenced-resource</code> - Resources that the detector model uses must be * available.</p> * </li> * </ul> * <p>For more information, see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-analyze-api.html">Running detector model * analyses</a> in the <i>AWS IoT Events Developer Guide</i>.</p> */ type?: string; /** * <p>The severity level of the analysis result. Based on the severity level, analysis results * fall into three general categories:</p> * <ul> * <li> * <p> * <code>INFO</code> - An information result tells you about a significant field in your * detector model. This type of result usually doesn't require immediate action.</p> * </li> * <li> * <p> * <code>WARNING</code> - A warning result draws special attention to fields that might cause issues for your detector model. * We recommend that you review warnings and take necessary actions * before you use your detector model in production environments. Otherwise, the detector * model might not work as expected.</p> * </li> * <li> * <p> * <code>ERROR</code> - An error result notifies you about a problem found in your * detector model. You must fix all errors before you can publish your detector model.</p> * </li> * </ul> */ level?: AnalysisResultLevel | string; /** * <p>Contains additional information about the analysis result.</p> */ message?: string; /** * <p>Contains one or more locations that you can use to locate the fields in your detector * model that the analysis result references.</p> */ locations?: AnalysisResultLocation[]; } export namespace AnalysisResult { /** * @internal */ export const filterSensitiveLog = (obj: AnalysisResult): any => ({ ...obj, }); } export enum AnalysisStatus { COMPLETE = "COMPLETE", FAILED = "FAILED", RUNNING = "RUNNING", } /** * <p>The attributes from the JSON payload that are made available by the input. Inputs are * derived from messages sent to the AWS IoT Events system using <code>BatchPutMessage</code>. Each such * message contains a JSON payload. Those attributes (and their paired values) specified here are * available for use in the <code>condition</code> expressions used by detectors. </p> */ export interface Attribute { /** * <p>An expression that specifies an attribute-value pair in a JSON structure. Use this to * specify an attribute from the JSON payload that is made available by the input. Inputs are * derived from messages sent to AWS IoT Events (<code>BatchPutMessage</code>). Each such message contains * a JSON payload. The attribute (and its paired value) specified here are available for use in * the <code>condition</code> expressions used by detectors. </p> * <p>Syntax: <code><field-name>.<field-name>...</code> * </p> */ jsonPath: string | undefined; } export namespace Attribute { /** * @internal */ export const filterSensitiveLog = (obj: Attribute): any => ({ ...obj, }); } /** * <p>Metadata that can be used to manage the resource.</p> */ export interface Tag { /** * <p>The tag's key.</p> */ key: string | undefined; /** * <p>The tag's value.</p> */ value: string | undefined; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } export interface CreateAlarmModelRequest { /** * <p>A unique name that helps you identify the alarm model. You can't change this name after * you create the alarm model.</p> */ alarmModelName: string | undefined; /** * <p>A description that tells you what the alarm model detects.</p> */ alarmModelDescription?: string; /** * <p>The ARN of the IAM role that allows the alarm to perform actions and access AWS resources. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ roleArn: string | undefined; /** * <p>A list of key-value pairs that contain metadata for the alarm model. The tags help you * manage the alarm model. For more information, see <a href="https://docs.aws.amazon.com/iotevents/latest/developerguide/tagging-iotevents.html">Tagging your AWS IoT Events * resources</a> in the <i>AWS IoT Events Developer Guide</i>.</p> * <p>You can create up to 50 tags for one alarm model.</p> */ tags?: Tag[]; /** * <p>An input attribute used as a key to create an alarm. * AWS IoT Events routes <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Input.html">inputs</a> * associated with this key to the alarm.</p> */ key?: string; /** * <p>A non-negative integer that reflects the severity level of the alarm.</p> */ severity?: number; /** * <p>Defines when your alarm is invoked.</p> */ alarmRule: AlarmRule | undefined; /** * <p>Contains information about one or more notification actions.</p> */ alarmNotification?: AlarmNotification; /** * <p>Contains information about one or more alarm actions.</p> */ alarmEventActions?: AlarmEventActions; /** * <p>Contains the configuration information of alarm state changes.</p> */ alarmCapabilities?: AlarmCapabilities; } export namespace CreateAlarmModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateAlarmModelRequest): any => ({ ...obj, }); } export interface CreateAlarmModelResponse { /** * <p>The time the alarm model was created, in the Unix epoch format.</p> */ creationTime?: Date; /** * <p>The ARN of the alarm model. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ alarmModelArn?: string; /** * <p>The version of the alarm model.</p> */ alarmModelVersion?: string; /** * <p>The time the alarm model was last updated, in the Unix epoch format.</p> */ lastUpdateTime?: Date; /** * <p>The status of the alarm model. The status can be one of the following values:</p> * <ul> * <li> * <p> * <code>ACTIVE</code> - The alarm model is active and it's ready to evaluate data.</p> * </li> * <li> * <p> * <code>ACTIVATING</code> - AWS IoT Events is activating your alarm model. * Activating an alarm model can take up to a few minutes.</p> * </li> * <li> * <p> * <code>INACTIVE</code> - The alarm model is inactive, so it isn't ready to evaluate data. * Check your alarm model information and update the alarm model.</p> * </li> * <li> * <p> * <code>FAILED</code> - You couldn't create or update the alarm model. Check your alarm model information * and try again.</p> * </li> * </ul> */ status?: AlarmModelVersionStatus | string; } export namespace CreateAlarmModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateAlarmModelResponse): any => ({ ...obj, }); } /** * <p>An internal failure occurred.</p> */ export interface InternalFailureException extends __SmithyException, $MetadataBearer { name: "InternalFailureException"; $fault: "server"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace InternalFailureException { /** * @internal */ export const filterSensitiveLog = (obj: InternalFailureException): any => ({ ...obj, }); } /** * <p>The request was invalid.</p> */ export interface InvalidRequestException extends __SmithyException, $MetadataBearer { name: "InvalidRequestException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace InvalidRequestException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidRequestException): any => ({ ...obj, }); } /** * <p>A limit was exceeded.</p> */ export interface LimitExceededException extends __SmithyException, $MetadataBearer { name: "LimitExceededException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace LimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: LimitExceededException): any => ({ ...obj, }); } /** * <p>The resource already exists.</p> */ export interface ResourceAlreadyExistsException extends __SmithyException, $MetadataBearer { name: "ResourceAlreadyExistsException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; /** * <p>The ID of the resource.</p> */ resourceId?: string; /** * <p>The ARN of the resource.</p> */ resourceArn?: string; } export namespace ResourceAlreadyExistsException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceAlreadyExistsException): any => ({ ...obj, }); } /** * <p>The resource is in use.</p> */ export interface ResourceInUseException extends __SmithyException, $MetadataBearer { name: "ResourceInUseException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ResourceInUseException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceInUseException): any => ({ ...obj, }); } /** * <p>The service is currently unavailable.</p> */ export interface ServiceUnavailableException extends __SmithyException, $MetadataBearer { name: "ServiceUnavailableException"; $fault: "server"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ServiceUnavailableException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceUnavailableException): any => ({ ...obj, }); } /** * <p>The request could not be completed due to throttling.</p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * <p>Specifies the <code>actions</code> to be performed when the <code>condition</code> * evaluates to TRUE.</p> */ export interface Event { /** * <p>The name of the event.</p> */ eventName: string | undefined; /** * <p>Optional. The Boolean expression that, when TRUE, causes the <code>actions</code> to be * performed. If not present, the actions are performed (=TRUE). If the expression result is not * a Boolean value, the actions are not performed (=FALSE).</p> */ condition?: string; /** * <p>The actions to be performed.</p> */ actions?: Action[]; } export namespace Event { /** * @internal */ export const filterSensitiveLog = (obj: Event): any => ({ ...obj, }); } /** * <p>When entering this state, perform these <code>actions</code> if the <code>condition</code> * is TRUE.</p> */ export interface OnEnterLifecycle { /** * <p>Specifies the actions that are performed when the state is entered and the * <code>condition</code> is <code>TRUE</code>.</p> */ events?: Event[]; } export namespace OnEnterLifecycle { /** * @internal */ export const filterSensitiveLog = (obj: OnEnterLifecycle): any => ({ ...obj, }); } /** * <p>When exiting this state, perform these <code>actions</code> if the specified * <code>condition</code> is <code>TRUE</code>.</p> */ export interface OnExitLifecycle { /** * <p>Specifies the <code>actions</code> that are performed when the state is exited and the * <code>condition</code> is <code>TRUE</code>.</p> */ events?: Event[]; } export namespace OnExitLifecycle { /** * @internal */ export const filterSensitiveLog = (obj: OnExitLifecycle): any => ({ ...obj, }); } /** * <p>Specifies the actions performed and the next state entered when a <code>condition</code> * evaluates to TRUE.</p> */ export interface TransitionEvent { /** * <p>The name of the transition event.</p> */ eventName: string | undefined; /** * <p>Required. A Boolean expression that when TRUE causes the actions to be performed and the * <code>nextState</code> to be entered.</p> */ condition: string | undefined; /** * <p>The actions to be performed.</p> */ actions?: Action[]; /** * <p>The next state to enter.</p> */ nextState: string | undefined; } export namespace TransitionEvent { /** * @internal */ export const filterSensitiveLog = (obj: TransitionEvent): any => ({ ...obj, }); } /** * <p>Specifies the actions performed when the <code>condition</code> evaluates to TRUE.</p> */ export interface OnInputLifecycle { /** * <p>Specifies the actions performed when the <code>condition</code> evaluates to TRUE.</p> */ events?: Event[]; /** * <p>Specifies the actions performed, and the next state entered, when a <code>condition</code> * evaluates to TRUE.</p> */ transitionEvents?: TransitionEvent[]; } export namespace OnInputLifecycle { /** * @internal */ export const filterSensitiveLog = (obj: OnInputLifecycle): any => ({ ...obj, }); } /** * <p>Information that defines a state of a detector.</p> */ export interface State { /** * <p>The name of the state.</p> */ stateName: string | undefined; /** * <p>When an input is received and the <code>condition</code> is TRUE, perform the specified * <code>actions</code>.</p> */ onInput?: OnInputLifecycle; /** * <p>When entering this state, perform these <code>actions</code> if the <code>condition</code> * is TRUE.</p> */ onEnter?: OnEnterLifecycle; /** * <p>When exiting this state, perform these <code>actions</code> if the specified * <code>condition</code> is <code>TRUE</code>.</p> */ onExit?: OnExitLifecycle; } export namespace State { /** * @internal */ export const filterSensitiveLog = (obj: State): any => ({ ...obj, }); } /** * <p>Information that defines how a detector operates.</p> */ export interface DetectorModelDefinition { /** * <p>Information about the states of the detector.</p> */ states: State[] | undefined; /** * <p>The state that is entered at the creation of each detector (instance).</p> */ initialStateName: string | undefined; } export namespace DetectorModelDefinition { /** * @internal */ export const filterSensitiveLog = (obj: DetectorModelDefinition): any => ({ ...obj, }); } export enum EvaluationMethod { BATCH = "BATCH", SERIAL = "SERIAL", } export interface CreateDetectorModelRequest { /** * <p>The name of the detector model.</p> */ detectorModelName: string | undefined; /** * <p>Information that defines how the detectors operate.</p> */ detectorModelDefinition: DetectorModelDefinition | undefined; /** * <p>A brief description of the detector model.</p> */ detectorModelDescription?: string; /** * <p>The input attribute key used to identify a device or system to create a detector (an * instance of the detector model) and then to route each input received to the appropriate * detector (instance). This parameter uses a JSON-path expression in the message payload of each * input to specify the attribute-value pair that is used to identify the device associated with * the input.</p> */ key?: string; /** * <p>The ARN of the role that grants permission to AWS IoT Events to perform its operations.</p> */ roleArn: string | undefined; /** * <p>Metadata that can be used to manage the detector model.</p> */ tags?: Tag[]; /** * <p>Information about the order in which events are evaluated and how actions are executed. * </p> */ evaluationMethod?: EvaluationMethod | string; } export namespace CreateDetectorModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateDetectorModelRequest): any => ({ ...obj, }); } export enum DetectorModelVersionStatus { ACTIVATING = "ACTIVATING", ACTIVE = "ACTIVE", DEPRECATED = "DEPRECATED", DRAFT = "DRAFT", FAILED = "FAILED", INACTIVE = "INACTIVE", PAUSED = "PAUSED", } /** * <p>Information about how the detector model is configured.</p> */ export interface DetectorModelConfiguration { /** * <p>The name of the detector model.</p> */ detectorModelName?: string; /** * <p>The version of the detector model.</p> */ detectorModelVersion?: string; /** * <p>A brief description of the detector model.</p> */ detectorModelDescription?: string; /** * <p>The ARN of the detector model.</p> */ detectorModelArn?: string; /** * <p>The ARN of the role that grants permission to AWS IoT Events to perform its operations.</p> */ roleArn?: string; /** * <p>The time the detector model was created.</p> */ creationTime?: Date; /** * <p>The time the detector model was last updated.</p> */ lastUpdateTime?: Date; /** * <p>The status of the detector model.</p> */ status?: DetectorModelVersionStatus | string; /** * <p>The value used to identify a detector instance. When a device or system sends input, a new * detector instance with a unique key value is created. AWS IoT Events can continue to route input to its * corresponding detector instance based on this identifying information. </p> * <p>This parameter uses a JSON-path expression to select the attribute-value pair in the * message payload that is used for identification. To route the message to the correct detector * instance, the device must send a message payload that contains the same * attribute-value.</p> */ key?: string; /** * <p>Information about the order in which events are evaluated and how actions are executed. * </p> */ evaluationMethod?: EvaluationMethod | string; } export namespace DetectorModelConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: DetectorModelConfiguration): any => ({ ...obj, }); } export interface CreateDetectorModelResponse { /** * <p>Information about how the detector model is configured.</p> */ detectorModelConfiguration?: DetectorModelConfiguration; } export namespace CreateDetectorModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateDetectorModelResponse): any => ({ ...obj, }); } /** * <p>The definition of the input.</p> */ export interface InputDefinition { /** * <p>The attributes from the JSON payload that are made available by the input. Inputs are * derived from messages sent to the AWS IoT Events system using <code>BatchPutMessage</code>. Each such * message contains a JSON payload, and those attributes (and their paired values) specified here * are available for use in the <code>condition</code> expressions used by detectors that monitor * this input. </p> */ attributes: Attribute[] | undefined; } export namespace InputDefinition { /** * @internal */ export const filterSensitiveLog = (obj: InputDefinition): any => ({ ...obj, }); } export interface CreateInputRequest { /** * <p>The name you want to give to the input.</p> */ inputName: string | undefined; /** * <p>A brief description of the input.</p> */ inputDescription?: string; /** * <p>The definition of the input.</p> */ inputDefinition: InputDefinition | undefined; /** * <p>Metadata that can be used to manage the input.</p> */ tags?: Tag[]; } export namespace CreateInputRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateInputRequest): any => ({ ...obj, }); } export enum InputStatus { ACTIVE = "ACTIVE", CREATING = "CREATING", DELETING = "DELETING", UPDATING = "UPDATING", } /** * <p>Information about the configuration of an input.</p> */ export interface InputConfiguration { /** * <p>The name of the input.</p> */ inputName: string | undefined; /** * <p>A brief description of the input.</p> */ inputDescription?: string; /** * <p>The ARN of the input.</p> */ inputArn: string | undefined; /** * <p>The time the input was created.</p> */ creationTime: Date | undefined; /** * <p>The last time the input was updated.</p> */ lastUpdateTime: Date | undefined; /** * <p>The status of the input.</p> */ status: InputStatus | string | undefined; } export namespace InputConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: InputConfiguration): any => ({ ...obj, }); } export interface CreateInputResponse { /** * <p>Information about the configuration of the input.</p> */ inputConfiguration?: InputConfiguration; } export namespace CreateInputResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateInputResponse): any => ({ ...obj, }); } export interface DeleteAlarmModelRequest { /** * <p>The name of the alarm model.</p> */ alarmModelName: string | undefined; } export namespace DeleteAlarmModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteAlarmModelRequest): any => ({ ...obj, }); } export interface DeleteAlarmModelResponse {} export namespace DeleteAlarmModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteAlarmModelResponse): any => ({ ...obj, }); } /** * <p>The resource was not found.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface DeleteDetectorModelRequest { /** * <p>The name of the detector model to be deleted.</p> */ detectorModelName: string | undefined; } export namespace DeleteDetectorModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDetectorModelRequest): any => ({ ...obj, }); } export interface DeleteDetectorModelResponse {} export namespace DeleteDetectorModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteDetectorModelResponse): any => ({ ...obj, }); } export interface DeleteInputRequest { /** * <p>The name of the input to delete.</p> */ inputName: string | undefined; } export namespace DeleteInputRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteInputRequest): any => ({ ...obj, }); } export interface DeleteInputResponse {} export namespace DeleteInputResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteInputResponse): any => ({ ...obj, }); } export interface DescribeAlarmModelRequest { /** * <p>The name of the alarm model.</p> */ alarmModelName: string | undefined; /** * <p>The version of the alarm model.</p> */ alarmModelVersion?: string; } export namespace DescribeAlarmModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAlarmModelRequest): any => ({ ...obj, }); } export interface DescribeAlarmModelResponse { /** * <p>The time the alarm model was created, in the Unix epoch format.</p> */ creationTime?: Date; /** * <p>The ARN of the alarm model. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ alarmModelArn?: string; /** * <p>The version of the alarm model.</p> */ alarmModelVersion?: string; /** * <p>The time the alarm model was last updated, in the Unix epoch format.</p> */ lastUpdateTime?: Date; /** * <p>The status of the alarm model. The status can be one of the following values:</p> * <ul> * <li> * <p> * <code>ACTIVE</code> - The alarm model is active and it's ready to evaluate data.</p> * </li> * <li> * <p> * <code>ACTIVATING</code> - AWS IoT Events is activating your alarm model. * Activating an alarm model can take up to a few minutes.</p> * </li> * <li> * <p> * <code>INACTIVE</code> - The alarm model is inactive, so it isn't ready to evaluate data. * Check your alarm model information and update the alarm model.</p> * </li> * <li> * <p> * <code>FAILED</code> - You couldn't create or update the alarm model. Check your alarm model information * and try again.</p> * </li> * </ul> */ status?: AlarmModelVersionStatus | string; /** * <p> * Contains information about the status of the alarm model. * </p> */ statusMessage?: string; /** * <p>The name of the alarm model.</p> */ alarmModelName?: string; /** * <p>The description of the alarm model.</p> */ alarmModelDescription?: string; /** * <p>The ARN of the IAM role that allows the alarm to perform actions and access AWS resources. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ roleArn?: string; /** * <p>An input attribute used as a key to create an alarm. * AWS IoT Events routes <a href="https://docs.aws.amazon.com/iotevents/latest/apireference/API_Input.html">inputs</a> * associated with this key to the alarm.</p> */ key?: string; /** * <p>A non-negative integer that reflects the severity level of the alarm.</p> */ severity?: number; /** * <p>Defines when your alarm is invoked.</p> */ alarmRule?: AlarmRule; /** * <p>Contains information about one or more notification actions.</p> */ alarmNotification?: AlarmNotification; /** * <p>Contains information about one or more alarm actions.</p> */ alarmEventActions?: AlarmEventActions; /** * <p>Contains the configuration information of alarm state changes.</p> */ alarmCapabilities?: AlarmCapabilities; } export namespace DescribeAlarmModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeAlarmModelResponse): any => ({ ...obj, }); } export interface DescribeDetectorModelRequest { /** * <p>The name of the detector model.</p> */ detectorModelName: string | undefined; /** * <p>The version of the detector model.</p> */ detectorModelVersion?: string; } export namespace DescribeDetectorModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectorModelRequest): any => ({ ...obj, }); } /** * <p>Information about the detector model.</p> */ export interface DetectorModel { /** * <p>Information that defines how a detector operates.</p> */ detectorModelDefinition?: DetectorModelDefinition; /** * <p>Information about how the detector is configured.</p> */ detectorModelConfiguration?: DetectorModelConfiguration; } export namespace DetectorModel { /** * @internal */ export const filterSensitiveLog = (obj: DetectorModel): any => ({ ...obj, }); } export interface DescribeDetectorModelResponse { /** * <p>Information about the detector model.</p> */ detectorModel?: DetectorModel; } export namespace DescribeDetectorModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectorModelResponse): any => ({ ...obj, }); } export interface DescribeDetectorModelAnalysisRequest { /** * <p>The ID of the analysis result that you want to retrieve.</p> */ analysisId: string | undefined; } export namespace DescribeDetectorModelAnalysisRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectorModelAnalysisRequest): any => ({ ...obj, }); } export interface DescribeDetectorModelAnalysisResponse { /** * <p>The status of the analysis activity. The status can be one of the following values:</p> * <ul> * <li> * <p> * <code>RUNNING</code> - AWS IoT Events is analyzing your detector model. This process can take * several minutes to complete.</p> * </li> * <li> * <p> * <code>COMPLETE</code> - AWS IoT Events finished analyzing your detector model.</p> * </li> * <li> * <p> * <code>FAILED</code> - AWS IoT Events couldn't analyze your detector model. Try again * later.</p> * </li> * </ul> */ status?: AnalysisStatus | string; } export namespace DescribeDetectorModelAnalysisResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeDetectorModelAnalysisResponse): any => ({ ...obj, }); } export interface DescribeInputRequest { /** * <p>The name of the input.</p> */ inputName: string | undefined; } export namespace DescribeInputRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeInputRequest): any => ({ ...obj, }); } /** * <p>Information about the input.</p> */ export interface Input { /** * <p>Information about the configuration of an input.</p> */ inputConfiguration?: InputConfiguration; /** * <p>The definition of the input.</p> */ inputDefinition?: InputDefinition; } export namespace Input { /** * @internal */ export const filterSensitiveLog = (obj: Input): any => ({ ...obj, }); } export interface DescribeInputResponse { /** * <p>Information about the input.</p> */ input?: Input; } export namespace DescribeInputResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeInputResponse): any => ({ ...obj, }); } export interface DescribeLoggingOptionsRequest {} export namespace DescribeLoggingOptionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeLoggingOptionsRequest): any => ({ ...obj, }); } /** * <p>The detector model and the specific detectors (instances) for which the logging level is * given.</p> */ export interface DetectorDebugOption { /** * <p>The name of the detector model.</p> */ detectorModelName: string | undefined; /** * <p>The value of the input attribute key used to create the detector (the instance of the * detector model).</p> */ keyValue?: string; } export namespace DetectorDebugOption { /** * @internal */ export const filterSensitiveLog = (obj: DetectorDebugOption): any => ({ ...obj, }); } export enum LoggingLevel { DEBUG = "DEBUG", ERROR = "ERROR", INFO = "INFO", } /** * <p>The values of the AWS IoT Events logging options.</p> */ export interface LoggingOptions { /** * <p>The ARN of the role that grants permission to AWS IoT Events to perform logging.</p> */ roleArn: string | undefined; /** * <p>The logging level.</p> */ level: LoggingLevel | string | undefined; /** * <p>If TRUE, logging is enabled for AWS IoT Events.</p> */ enabled: boolean | undefined; /** * <p>Information that identifies those detector models and their detectors (instances) for * which the logging level is given.</p> */ detectorDebugOptions?: DetectorDebugOption[]; } export namespace LoggingOptions { /** * @internal */ export const filterSensitiveLog = (obj: LoggingOptions): any => ({ ...obj, }); } export interface DescribeLoggingOptionsResponse { /** * <p>The current settings of the AWS IoT Events logging options.</p> */ loggingOptions?: LoggingOptions; } export namespace DescribeLoggingOptionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeLoggingOptionsResponse): any => ({ ...obj, }); } /** * <p>The requested operation is not supported.</p> */ export interface UnsupportedOperationException extends __SmithyException, $MetadataBearer { name: "UnsupportedOperationException"; $fault: "server"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace UnsupportedOperationException { /** * @internal */ export const filterSensitiveLog = (obj: UnsupportedOperationException): any => ({ ...obj, }); } /** * <p>Information about the detector model.</p> */ export interface DetectorModelSummary { /** * <p>The name of the detector model.</p> */ detectorModelName?: string; /** * <p>A brief description of the detector model.</p> */ detectorModelDescription?: string; /** * <p>The time the detector model was created.</p> */ creationTime?: Date; } export namespace DetectorModelSummary { /** * @internal */ export const filterSensitiveLog = (obj: DetectorModelSummary): any => ({ ...obj, }); } /** * <p>Information about the detector model version.</p> */ export interface DetectorModelVersionSummary { /** * <p>The name of the detector model.</p> */ detectorModelName?: string; /** * <p>The ID of the detector model version.</p> */ detectorModelVersion?: string; /** * <p>The ARN of the detector model version.</p> */ detectorModelArn?: string; /** * <p>The ARN of the role that grants the detector model permission to perform its tasks.</p> */ roleArn?: string; /** * <p>The time the detector model version was created.</p> */ creationTime?: Date; /** * <p>The last time the detector model version was updated.</p> */ lastUpdateTime?: Date; /** * <p>The status of the detector model version.</p> */ status?: DetectorModelVersionStatus | string; /** * <p>Information about the order in which events are evaluated and how actions are executed. * </p> */ evaluationMethod?: EvaluationMethod | string; } export namespace DetectorModelVersionSummary { /** * @internal */ export const filterSensitiveLog = (obj: DetectorModelVersionSummary): any => ({ ...obj, }); } export interface GetDetectorModelAnalysisResultsRequest { /** * <p>The ID of the analysis result that you want to retrieve.</p> */ analysisId: string | undefined; /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace GetDetectorModelAnalysisResultsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetDetectorModelAnalysisResultsRequest): any => ({ ...obj, }); } export interface GetDetectorModelAnalysisResultsResponse { /** * <p>Contains information about one or more analysis results.</p> */ analysisResults?: AnalysisResult[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace GetDetectorModelAnalysisResultsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetDetectorModelAnalysisResultsResponse): any => ({ ...obj, }); } /** * <p> * The identifier of the input routed to AWS IoT Events. * </p> */ export interface IotEventsInputIdentifier { /** * <p> * The name of the input routed to AWS IoT Events. * </p> */ inputName: string | undefined; } export namespace IotEventsInputIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: IotEventsInputIdentifier): any => ({ ...obj, }); } /** * <p> * The asset model property identifer of the input routed from AWS IoT SiteWise. * </p> */ export interface IotSiteWiseAssetModelPropertyIdentifier { /** * <p> * The ID of the AWS IoT SiteWise asset model. * </p> */ assetModelId: string | undefined; /** * <p> * The ID of the AWS IoT SiteWise asset property. * </p> */ propertyId: string | undefined; } export namespace IotSiteWiseAssetModelPropertyIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: IotSiteWiseAssetModelPropertyIdentifier): any => ({ ...obj, }); } /** * <p> * The identifer of the input routed from AWS IoT SiteWise. * </p> */ export interface IotSiteWiseInputIdentifier { /** * <p> * The identifier of the AWS IoT SiteWise asset model property. * </p> */ iotSiteWiseAssetModelPropertyIdentifier?: IotSiteWiseAssetModelPropertyIdentifier; } export namespace IotSiteWiseInputIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: IotSiteWiseInputIdentifier): any => ({ ...obj, }); } /** * <p> * The identifer of the input. * </p> */ export interface InputIdentifier { /** * <p> * The identifier of the input routed to AWS IoT Events. * </p> */ iotEventsInputIdentifier?: IotEventsInputIdentifier; /** * <p> * The identifer of the input routed from AWS IoT SiteWise. * </p> */ iotSiteWiseInputIdentifier?: IotSiteWiseInputIdentifier; } export namespace InputIdentifier { /** * @internal */ export const filterSensitiveLog = (obj: InputIdentifier): any => ({ ...obj, }); } /** * <p>Information about the input.</p> */ export interface InputSummary { /** * <p>The name of the input.</p> */ inputName?: string; /** * <p>A brief description of the input.</p> */ inputDescription?: string; /** * <p>The ARN of the input.</p> */ inputArn?: string; /** * <p>The time the input was created.</p> */ creationTime?: Date; /** * <p>The last time the input was updated.</p> */ lastUpdateTime?: Date; /** * <p>The status of the input.</p> */ status?: InputStatus | string; } export namespace InputSummary { /** * @internal */ export const filterSensitiveLog = (obj: InputSummary): any => ({ ...obj, }); } export interface ListAlarmModelsRequest { /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace ListAlarmModelsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAlarmModelsRequest): any => ({ ...obj, }); } export interface ListAlarmModelsResponse { /** * <p>A list that summarizes each alarm model.</p> */ alarmModelSummaries?: AlarmModelSummary[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace ListAlarmModelsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAlarmModelsResponse): any => ({ ...obj, }); } export interface ListAlarmModelVersionsRequest { /** * <p>The name of the alarm model.</p> */ alarmModelName: string | undefined; /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace ListAlarmModelVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListAlarmModelVersionsRequest): any => ({ ...obj, }); } export interface ListAlarmModelVersionsResponse { /** * <p>A list that summarizes each alarm model version.</p> */ alarmModelVersionSummaries?: AlarmModelVersionSummary[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace ListAlarmModelVersionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListAlarmModelVersionsResponse): any => ({ ...obj, }); } export interface ListDetectorModelsRequest { /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace ListDetectorModelsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectorModelsRequest): any => ({ ...obj, }); } export interface ListDetectorModelsResponse { /** * <p>Summary information about the detector models.</p> */ detectorModelSummaries?: DetectorModelSummary[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace ListDetectorModelsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectorModelsResponse): any => ({ ...obj, }); } export interface ListDetectorModelVersionsRequest { /** * <p>The name of the detector model whose versions are returned.</p> */ detectorModelName: string | undefined; /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace ListDetectorModelVersionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectorModelVersionsRequest): any => ({ ...obj, }); } export interface ListDetectorModelVersionsResponse { /** * <p>Summary information about the detector model versions.</p> */ detectorModelVersionSummaries?: DetectorModelVersionSummary[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace ListDetectorModelVersionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListDetectorModelVersionsResponse): any => ({ ...obj, }); } export interface ListInputRoutingsRequest { /** * <p> * The identifer of the routed input. * </p> */ inputIdentifier: InputIdentifier | undefined; /** * <p> * The maximum number of results to be returned per request. * </p> */ maxResults?: number; /** * <p> * The token that you can use to return the next set of results. * </p> */ nextToken?: string; } export namespace ListInputRoutingsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListInputRoutingsRequest): any => ({ ...obj, }); } /** * <p> * Contains information about the routed resource. * </p> */ export interface RoutedResource { /** * <p> * The name of the routed resource. * </p> */ name?: string; /** * <p> * The ARN of the routed resource. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>. * </p> */ arn?: string; } export namespace RoutedResource { /** * @internal */ export const filterSensitiveLog = (obj: RoutedResource): any => ({ ...obj, }); } export interface ListInputRoutingsResponse { /** * <p> * Summary information about the routed resources. * </p> */ routedResources?: RoutedResource[]; /** * <p> * The token that you can use to return the next set of results, * or <code>null</code> if there are no more results. * </p> */ nextToken?: string; } export namespace ListInputRoutingsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListInputRoutingsResponse): any => ({ ...obj, }); } export interface ListInputsRequest { /** * <p>The token that you can use to return the next set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to be returned per request.</p> */ maxResults?: number; } export namespace ListInputsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListInputsRequest): any => ({ ...obj, }); } export interface ListInputsResponse { /** * <p>Summary information about the inputs.</p> */ inputSummaries?: InputSummary[]; /** * <p>The token that you can use to return the next set of results, * or <code>null</code> if there are no more results.</p> */ nextToken?: string; } export namespace ListInputsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListInputsResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The ARN of the resource.</p> */ resourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The list of tags assigned to the resource.</p> */ tags?: Tag[]; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface PutLoggingOptionsRequest { /** * <p>The new values of the AWS IoT Events logging options.</p> */ loggingOptions: LoggingOptions | undefined; } export namespace PutLoggingOptionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: PutLoggingOptionsRequest): any => ({ ...obj, }); } export interface StartDetectorModelAnalysisRequest { /** * <p>Information that defines how a detector operates.</p> */ detectorModelDefinition: DetectorModelDefinition | undefined; } export namespace StartDetectorModelAnalysisRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartDetectorModelAnalysisRequest): any => ({ ...obj, }); } export interface StartDetectorModelAnalysisResponse { /** * <p>The ID that you can use to retrieve the analysis result.</p> */ analysisId?: string; } export namespace StartDetectorModelAnalysisResponse { /** * @internal */ export const filterSensitiveLog = (obj: StartDetectorModelAnalysisResponse): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p>The ARN of the resource.</p> */ resourceArn: string | undefined; /** * <p>The new or modified tags for the resource.</p> */ tags: Tag[] | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The ARN of the resource.</p> */ resourceArn: string | undefined; /** * <p>A list of the keys of the tags to be removed from the resource.</p> */ tagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); } export interface UpdateAlarmModelRequest { /** * <p>The name of the alarm model.</p> */ alarmModelName: string | undefined; /** * <p>The description of the alarm model.</p> */ alarmModelDescription?: string; /** * <p>The ARN of the IAM role that allows the alarm to perform actions and access AWS resources. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ roleArn: string | undefined; /** * <p>A non-negative integer that reflects the severity level of the alarm.</p> */ severity?: number; /** * <p>Defines when your alarm is invoked.</p> */ alarmRule: AlarmRule | undefined; /** * <p>Contains information about one or more notification actions.</p> */ alarmNotification?: AlarmNotification; /** * <p>Contains information about one or more alarm actions.</p> */ alarmEventActions?: AlarmEventActions; /** * <p>Contains the configuration information of alarm state changes.</p> */ alarmCapabilities?: AlarmCapabilities; } export namespace UpdateAlarmModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateAlarmModelRequest): any => ({ ...obj, }); } export interface UpdateAlarmModelResponse { /** * <p>The time the alarm model was created, in the Unix epoch format.</p> */ creationTime?: Date; /** * <p>The ARN of the alarm model. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon Resource Names (ARNs)</a> in the <i>AWS General Reference</i>.</p> */ alarmModelArn?: string; /** * <p>The version of the alarm model.</p> */ alarmModelVersion?: string; /** * <p>The time the alarm model was last updated, in the Unix epoch format.</p> */ lastUpdateTime?: Date; /** * <p>The status of the alarm model. The status can be one of the following values:</p> * <ul> * <li> * <p> * <code>ACTIVE</code> - The alarm model is active and it's ready to evaluate data.</p> * </li> * <li> * <p> * <code>ACTIVATING</code> - AWS IoT Events is activating your alarm model. * Activating an alarm model can take up to a few minutes.</p> * </li> * <li> * <p> * <code>INACTIVE</code> - The alarm model is inactive, so it isn't ready to evaluate data. * Check your alarm model information and update the alarm model.</p> * </li> * <li> * <p> * <code>FAILED</code> - You couldn't create or update the alarm model. Check your alarm model information * and try again.</p> * </li> * </ul> */ status?: AlarmModelVersionStatus | string; } export namespace UpdateAlarmModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateAlarmModelResponse): any => ({ ...obj, }); } export interface UpdateDetectorModelRequest { /** * <p>The name of the detector model that is updated.</p> */ detectorModelName: string | undefined; /** * <p>Information that defines how a detector operates.</p> */ detectorModelDefinition: DetectorModelDefinition | undefined; /** * <p>A brief description of the detector model.</p> */ detectorModelDescription?: string; /** * <p>The ARN of the role that grants permission to AWS IoT Events to perform its operations.</p> */ roleArn: string | undefined; /** * <p>Information about the order in which events are evaluated and how actions are executed. * </p> */ evaluationMethod?: EvaluationMethod | string; } export namespace UpdateDetectorModelRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateDetectorModelRequest): any => ({ ...obj, }); } export interface UpdateDetectorModelResponse { /** * <p>Information about how the detector model is configured.</p> */ detectorModelConfiguration?: DetectorModelConfiguration; } export namespace UpdateDetectorModelResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateDetectorModelResponse): any => ({ ...obj, }); } export interface UpdateInputRequest { /** * <p>The name of the input you want to update.</p> */ inputName: string | undefined; /** * <p>A brief description of the input.</p> */ inputDescription?: string; /** * <p>The definition of the input.</p> */ inputDefinition: InputDefinition | undefined; } export namespace UpdateInputRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateInputRequest): any => ({ ...obj, }); } export interface UpdateInputResponse { /** * <p>Information about the configuration of the input.</p> */ inputConfiguration?: InputConfiguration; } export namespace UpdateInputResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateInputResponse): any => ({ ...obj, }); }
the_stack
"use strict"; import { assert } from "chai"; import * as path from "path"; import { Strings } from "../../../src/helpers/strings"; import { Undo } from "../../../src/tfvc/commands/undo"; import { TfvcError } from "../../../src/tfvc/tfvcerror"; import { IExecutionResult } from "../../../src/tfvc/interfaces"; import { TeamServerContext } from "../../../src/contexts/servercontext"; import { CredentialInfo } from "../../../src/info/credentialinfo"; import { RepositoryInfo } from "../../../src/info/repositoryinfo"; describe("Tfvc-UndoCommand", function() { const serverUrl: string = "http://server:8080/tfs"; const repoUrl: string = "http://server:8080/tfs/collection1/_git/repo1"; const collectionUrl: string = "http://server:8080/tfs/collection1"; const user: string = "user1"; const pass: string = "pass1"; let context: TeamServerContext; beforeEach(function() { context = new TeamServerContext(repoUrl); context.CredentialInfo = new CredentialInfo(user, pass); context.RepoInfo = new RepositoryInfo({ serverUrl: serverUrl, collection: { name: "collection1", id: "" }, repository: { remoteUrl: repoUrl, id: "", name: "", project: { name: "project1" } } }); }); //new Undo(this._serverContext, itemPaths)); it("should verify constructor - windows", function() { const localPaths: string[] = ["c:\\repos\\Tfvc.L2VSCodeExtension.RC\\README.md"]; new Undo(undefined, localPaths); }); it("should verify constructor - mac/linux", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; new Undo(undefined, localPaths); }); it("should verify constructor with context", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; new Undo(context, localPaths); }); it("should verify constructor - undefined args", function() { assert.throws(() => new Undo(undefined, undefined), TfvcError, /Argument is required/); }); it("should verify GetOptions", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(context, localPaths); assert.deepEqual(cmd.GetOptions(), {}); }); it("should verify GetExeOptions", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(context, localPaths); assert.deepEqual(cmd.GetExeOptions(), {}); }); it("should verify arguments", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(undefined, localPaths); assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "undo -noprompt " + localPaths[0]); }); it("should verify arguments with context", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(context, localPaths); assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "undo -noprompt -collection:" + collectionUrl + " ******** " + localPaths[0]); }); it("should verify UndoAll arguments", function() { const localPaths: string[] = ["*"]; const cmd: Undo = new Undo(undefined, localPaths); assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "undo -noprompt . -recursive"); }); it("should verify UndoAll arguments with context", function() { const localPaths: string[] = ["*"]; const cmd: Undo = new Undo(context, localPaths); assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "undo -noprompt -collection:" + collectionUrl + " ******** . -recursive"); }); it("should verify GetExeArguments", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(undefined, localPaths); assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "undo -noprompt " + localPaths[0]); }); it("should verify GetExeArguments with context", function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(context, localPaths); assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "undo -noprompt -collection:" + collectionUrl + " ******** " + localPaths[0]); }); it("should verify GetExeArguments UndoAll arguments", function() { const localPaths: string[] = ["*"]; const cmd: Undo = new Undo(undefined, localPaths); assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "undo -noprompt . -recursive"); }); it("should verify GetExeArguments UndoAll arguments with context", function() { const localPaths: string[] = ["*"]; const cmd: Undo = new Undo(context, localPaths); assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "undo -noprompt -collection:" + collectionUrl + " ******** . -recursive"); }); it("should verify parse output - no output", async function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 0); }); it("should verify parse output - single file edit - no errors", async function() { const localPaths: string[] = ["README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing edit: README.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); it("should verify parse output - single file add - no errors", async function() { const localPaths: string[] = ["README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing add: README.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); it("should verify parse output - multiple file add - no errors", async function() { const localPaths: string[] = ["README.md", "README2.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing add: README.md\n" + "Undoing add: README2.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 2); assert.equal(filesUndone[0], "README.md"); assert.equal(filesUndone[1], "README2.md"); }); it("should verify parse output - single folder+file edit - no errors", async function() { const localPaths: string[] = [path.join("folder1", "file1.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "folder1:\n" + "Undoing edit: file1.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse output - single subfolder+file add - no errors", async function() { const localPaths: string[] = [path.join("folder1", "folder2", "file2.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: path.join("folder1", "folder2") + ":\n" + "Undoing edit: file2.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse output - single folder+file edit - spaces - no errors", async function() { const localPaths: string[] = [path.join("fold er1", "file1.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "fold er1:\n" + "Undoing edit: file1.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse output - single subfolder+file add - spaces - no errors", async function() { const localPaths: string[] = [path.join("fold er1", "fol der2", "file2.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: path.join("fold er1", "fol der2") + ":\n" + "Undoing edit: file2.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); //If we have at least 1 file undone but at least 1 with no pending changes, exit code is 1 //Proceed normally but ignore the files that have no pending changes. it("should verify parse output - multiple files - several no pending changes", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = ["README.md"].concat(noChangesPaths); const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 1, stdout: "Undoing add: README.md\n" + "No pending changes were found for " + noChangesPaths[0] + "\n" + "No pending changes were found for " + noChangesPaths[1] + "\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); //If all files have no pending changes, exit code is 100 but we don't want to fail it("should verify parse output - multiple files - all no pending changes", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = noChangesPaths; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 100, stdout: "" + "No pending changes were found for " + noChangesPaths[0] + "\n" + "No pending changes were found for " + noChangesPaths[1] + "\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseOutput(executionResult); assert.isDefined(filesUndone); assert.equal(filesUndone.length, 0); }); it("should verify parse output - error exit code", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = noChangesPaths; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 42, stdout: "Something bad this way comes.", stderr: undefined }; try { await cmd.ParseOutput(executionResult); } catch (err) { assert.equal(err.exitCode, 42); assert.isTrue(err.message.startsWith(Strings.TfExecFailedError)); } }); /*********************************************************************************************** * The methods below are duplicates of the parse output methods but call the parseExeOutput. ***********************************************************************************************/ it("should verify parse EXE output - no output", async function() { const localPaths: string[] = ["/usr/alias/repos/Tfvc.L2VSCodeExtension.RC/README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 0); }); it("should verify parse EXE output - single file edit - no errors", async function() { const localPaths: string[] = ["README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing edit: README.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); it("should verify parse EXE output - single file add - no errors", async function() { const localPaths: string[] = ["README.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing add: README.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); it("should verify parse EXE output - multiple file add - no errors", async function() { const localPaths: string[] = ["README.md", "README2.md"]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "Undoing add: README.md\n" + "Undoing add: README2.md\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 2); assert.equal(filesUndone[0], "README.md"); assert.equal(filesUndone[1], "README2.md"); }); it("should verify parse EXE output - single folder+file edit - no errors", async function() { const localPaths: string[] = [path.join("folder1", "file1.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "folder1:\n" + "Undoing edit: file1.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse EXE output - single subfolder+file add - no errors", async function() { const localPaths: string[] = [path.join("folder1", "folder2", "file2.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: path.join("folder1", "folder2") + ":\n" + "Undoing edit: file2.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse EXE output - single folder+file edit - spaces - no errors", async function() { const localPaths: string[] = [path.join("fold er1", "file1.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: "fold er1:\n" + "Undoing edit: file1.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); it("should verify parse EXE output - single subfolder+file add - spaces - no errors", async function() { const localPaths: string[] = [path.join("fold er1", "fol der2", "file2.txt")]; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 0, stdout: path.join("fold er1", "fol der2") + ":\n" + "Undoing edit: file2.txt\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], localPaths[0]); }); //If we have at least 1 file undone but at least 1 with no pending changes, exit code is 1 //Proceed normally but ignore the files that have no pending changes. it("should verify parse EXE output - multiple files - several no pending changes", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = ["README.md"].concat(noChangesPaths); const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 1, stdout: "Undoing add: README.md\n" + "No pending changes were found for " + noChangesPaths[0] + ".\n" + "No pending changes were found for " + noChangesPaths[1] + ".\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.equal(filesUndone.length, 1); assert.equal(filesUndone[0], "README.md"); }); //If all files have no pending changes, exit code is 100 but we don't want to fail it("should verify parse EXE output - multiple files - all no pending changes", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = noChangesPaths; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 100, stdout: "" + "No pending changes were found for " + noChangesPaths[0] + ".\n" + "No pending changes were found for " + noChangesPaths[1] + ".\n", stderr: undefined }; const filesUndone: string[] = await cmd.ParseExeOutput(executionResult); assert.isDefined(filesUndone); assert.equal(filesUndone.length, 0); }); it("should verify parse EXE output - error exit code", async function() { const noChangesPaths: string[] = [path.join("folder1", "file1.txt"), path.join("folder2", "file2.txt")]; const localPaths: string[] = noChangesPaths; const cmd: Undo = new Undo(undefined, localPaths); const executionResult: IExecutionResult = { exitCode: 42, stdout: "Something bad this way comes.", stderr: undefined }; try { await cmd.ParseExeOutput(executionResult); } catch (err) { assert.equal(err.exitCode, 42); assert.isTrue(err.message.startsWith(Strings.TfExecFailedError)); } }); });
the_stack
import { strict as assert } from "assert"; import AWS, { AutoScaling } from "aws-sdk"; import { Subnet } from "./types"; import { log } from "@opstrace/utils"; import { autoScalingClient, ec2c, awsPromErrFilter } from "./util"; import { AWSResource } from "./resource"; class ASGRes extends AWSResource< AutoScaling.AutoScalingGroup, AutoScaling.CreateAutoScalingGroupType > { private asgname: string; protected rname = "auto-scaling group"; // Set by tryCreate() to the `MinSize` parameter from ASG creation // parameters. Can be used by `checkCreateSuccess()` private expectedInstanceCount = 0; constructor(opstraceClusterName: string) { super(opstraceClusterName); // source of truth for generating ASG name based on OCN. this.asgname = `${opstraceClusterName}-primary-asg`; } private async getASGforCluster(): Promise< AutoScaling.AutoScalingGroup | false > { const result = await awsPromErrFilter( autoScalingClient() .describeAutoScalingGroups({ AutoScalingGroupNames: [this.asgname] }) .promise() ); if ( result && result.AutoScalingGroups && result.AutoScalingGroups.length >= 1 ) { const agss = result.AutoScalingGroups; if (agss.length > 1) { log.warning( "found more than one asg, inspect manually:\n%s", JSON.stringify(agss, null, 2) ); } return agss[0]; } return false; } private async getScalingActivities(): Promise<AutoScaling.Activities> { // https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_DescribeScalingActivities.html // request activites for this asg. Note that as of the absence of specific // activity IDs, AWS will return "all activities for the past six weeks are // described", capped at 100 (as far as I understand docs) const result: AutoScaling.ActivitiesType = await awsPromErrFilter( autoScalingClient() .describeScalingActivities({ AutoScalingGroupName: this.asgname }) .promise() ); // Not sure if this can happen. Types are blurry. if (result.Activities === undefined) { return []; } return result.Activities; } protected async tryCreate( asgCreateParams: AutoScaling.CreateAutoScalingGroupType ) { // check naming convention // note that the deprecation warning doesn't quite make sense, this here // _is_ the strict assertion mode, as of how the `assert` module has been // imported. assert.equal(this.asgname, asgCreateParams.AutoScalingGroupName); this.expectedInstanceCount = asgCreateParams.MinSize; await awsPromErrFilter( autoScalingClient().createAutoScalingGroup(asgCreateParams).promise() ); return true; } protected async checkCreateSuccess(): Promise< AutoScaling.AutoScalingGroup | false > { const asg = await this.getASGforCluster(); if (asg === false) return false; if (asg.Instances === undefined) { log.debug( "%s setup: expected `Instances` property. Ignore, proceed.", this.rname ); return false; } const instanceCount = asg.Instances.length; log.info( "%s setup: EC2 instance count: %s (expected: %s)", this.rname, instanceCount, this.expectedInstanceCount ); const scalingacts: AutoScaling.Activities = await this.getScalingActivities(); if ( scalingacts.length === 0 && instanceCount === this.expectedInstanceCount ) { log.info( "%s setup: nothing to do, no scaling activities seen recently and already at desired capacity", this.rname ); return asg; } if (scalingacts.length === 0) { log.info("%s setup: no scaling activities seen yet", this.rname); return false; } // Get the last activity (the most recent one). From docs: "The scaling // activities. Activities are sorted by start time. Activities still in // progress are described first."" We just have to see in which order they // are sorted, ascending or descending. const lastActivity = scalingacts[0]; let msgsuffix = ""; if (lastActivity.StatusMessage !== undefined) { msgsuffix = ` (StatusMessage: ${lastActivity.StatusMessage})`; } log.info( "%s setup: last scaling activity has status `%s`%s", this.rname, lastActivity.StatusCode, msgsuffix ); if (lastActivity.StatusCode == "Failed") { // This for example hits in when the EC2 vCPU limit is hit, statusMessage // would then start with "You have requested more vCPU capacity than your // current vCPU limit of 32 allo....". That's why its critical to expose // the statusMessage to the user. Also see opstrace-prelaunch/issues/1874 // and opstrace-prelaunch/issues/1880. log.warning( "%s setup: last scaling activity has status FAILED: %s", this.rname, lastActivity.StatusMessage ); log.warning( "The Auto Scaling group shows a `failed`' scaling event (see above " + "for detail). This may have to be resolved through manual " + "intervention. To view the current quotas for your account, " + "open the Amazon EC2 console at " + "https://console.aws.amazon.com/ec2/ and navigate to the " + "Limits page. We will keep spinning and retrying here." ); } // Desired state: ASG status `successful`, and expected instance count. if (lastActivity.StatusCode === "Successful") { if (instanceCount === this.expectedInstanceCount) { log.info( "%s setup: state `Successful` and got expected number of EC2 instances", this.rname, instanceCount, this.expectedInstanceCount ); return asg; } } return false; } protected async tryDestroy() { const params = { AutoScalingGroupName: this.asgname, // do not wait for instances to terminate ForceDelete: true }; await awsPromErrFilter( autoScalingClient().deleteAutoScalingGroup(params).promise() ); } protected async checkDestroySuccess(): Promise<true | string> { const result = await this.getASGforCluster(); if (result === false) { return true; } // string representing state return JSON.stringify(result, null, 2); } } class EC2InstanceMetadata extends AWSResource<boolean> { // overridden in constructor, see below. protected rname = ""; private instanceid: string; constructor(opstraceClusterName: string, instanceid: string) { super(opstraceClusterName); this.rname = `ec2 instance metadata - ${instanceid}`; this.instanceid = instanceid; } protected async tryCreate(): Promise<boolean> { const req = { HttpPutResponseHopLimit: 2, InstanceId: this.instanceid }; const result = await awsPromErrFilter( ec2c().modifyInstanceMetadataOptions(req).promise() ); if (result && result.InstanceId) { return true; } throw new Error( `ec2 instance metadata modify error? Result object: ${JSON.stringify( result, null, 2 )}` ); } protected async checkCreateSuccess(): Promise<boolean> { const req: AWS.EC2.DescribeInstancesRequest = { InstanceIds: [this.instanceid] }; const result = await awsPromErrFilter( ec2c().describeInstances(req).promise() ); if (result.Reservations !== undefined) { if (result.Reservations.length === 1) { if (result.Reservations[0].Instances) { if (result.Reservations[0].Instances.length === 1) { const instance = result.Reservations[0].Instances[0]; if (instance.MetadataOptions?.HttpPutResponseHopLimit === 2) { log.info(`${this.rname}: HttpPutResponseHopLimit is 2`); return true; } else { const s = JSON.stringify(instance.MetadataOptions, null, 2); log.info( `${this.rname}: HttpPutResponseHopLimit is not 2:\n${s}` ); return false; } } } } } log.info( `${this.rname}: unexpected describeInstances result: :\n${JSON.stringify( result, null, 2 )}` ); return false; } protected async tryDestroy(): Promise<void> { // implementation not needed return; } protected async checkDestroySuccess(): Promise<true> { // Implementation not needed return true; } } export async function ensureAutoScalingGroupExists({ opstraceClusterName, subnets, maxSize, minSize, desiredCapacity, zone, launchConfigurationName }: { opstraceClusterName: string; subnets: Subnet[]; maxSize: number; minSize: number; desiredCapacity: number; zone: string; launchConfigurationName: string; }): Promise<void> { const asgname = `${opstraceClusterName}-primary-asg`; const asgCreateParams: AutoScaling.CreateAutoScalingGroupType = { AutoScalingGroupName: asgname, LaunchConfigurationName: launchConfigurationName, MaxSize: maxSize, MinSize: minSize, DesiredCapacity: desiredCapacity, AvailabilityZones: [zone], // Note(JP) set default tags, too (opstrace_cluster_name) Tags: [ { Key: `kubernetes.io/cluster/${opstraceClusterName}`, Value: "owned", PropagateAtLaunch: true } ], VPCZoneIdentifier: subnets .filter(s => s.AvailabilityZone === zone && !s.Public) .map(s => s.SubnetId) .join(",") }; const asgres = new ASGRes(opstraceClusterName); const asg = await asgres.setup(asgCreateParams); // Note(JP): at this point, it's known that the ASG is healthy, the EC2 // instance count in the ASG is as expected. Now, perform per-instance // checks/mutation. These mutations are not persistent: when an instance goes // away then the ASG will launch a new one, based on the launch // configuration. That is, the launch configuration would be the 'right' // place to implement EC2 instance properties when the goal is that all // instances created in the ASG should have them. The non-persistent mutation // however is helping for https://github.com/opstrace/opstrace/issues/1383. assert(asg.Instances); for (const instance of asg.Instances) { const ec2imres = new EC2InstanceMetadata( opstraceClusterName, instance.InstanceId ); // Could do this concurrently for all instances, but that makes log // output harder to read and probably only saves a few seconds. await ec2imres.setup(); } } export async function destroyAutoScalingGroup( opstraceClusterName: string ): Promise<void> { const asg = new ASGRes(opstraceClusterName); await asg.teardown(); }
the_stack
import type {Mutable, Class, AnyTiming} from "@swim/util"; import {Affinity, Property} from "@swim/component"; import {AnyLength, Length, AnyR2Point, R2Point, R2Box} from "@swim/math"; import {AnyGeoPoint, GeoPoint, GeoBox} from "@swim/geo"; import {AnyFont, Font, AnyColor, Color} from "@swim/style"; import {ThemeAnimator} from "@swim/theme"; import {ViewContextType, View} from "@swim/view"; import { GraphicsView, StrokeViewInit, StrokeView, PaintingContext, PaintingRenderer, CanvasContext, CanvasRenderer, } from "@swim/graphics"; import {GeoViewInit, GeoView} from "../geo/GeoView"; import {GeoRippleOptions, GeoRippleView} from "../effect/GeoRippleView"; import {AnyGeoPointView, GeoPointView} from "./GeoPointView"; import type {GeoPlotViewObserver} from "./GeoPlotViewObserver"; /** @public */ export type AnyGeoPlotView = GeoPlotView | GeoPlotViewInit; /** @public */ export interface GeoPlotViewInit extends GeoViewInit, StrokeViewInit { points?: ReadonlyArray<AnyGeoPointView>; hitWidth?: number; font?: AnyFont; textColor?: AnyColor; } /** @public */ export class GeoPlotView extends GeoView implements StrokeView { constructor() { super(); this.gradientStops = 0; Object.defineProperty(this, "viewBounds", { value: R2Box.undefined(), writable: true, enumerable: true, configurable: true, }); } override readonly observerType?: Class<GeoPlotViewObserver>; points(): ReadonlyArray<GeoPointView>; points(points: ReadonlyArray<AnyGeoPointView>, timing?: AnyTiming | boolean): this; points(points?: ReadonlyArray<AnyGeoPointView>, timing?: AnyTiming | boolean): ReadonlyArray<GeoPointView> | this { let child: View | null; if (points === void 0) { const points: GeoPointView[] = []; child = this.firstChild; while (child !== null) { if (child instanceof GeoPointView) { points.push(child); } child = child.nextSibling; } return points; } else { const oldGeoBounds = this.geoBounds; let lngMin = Infinity; let latMin = Infinity; let lngMax = -Infinity; let latMax = -Infinity; let lngMid = 0; let latMid = 0; let invalid = false; let i = 0; child = this.firstChild; while (child !== null && i < points.length) { if (child instanceof GeoPointView) { const point = points[i]!; child.setState(point); const {lng, lat} = child.geoPoint.getValue(); lngMid += lng; latMid += lat; lngMin = Math.min(lngMin, lng); latMin = Math.min(latMin, lat); lngMax = Math.max(lng, lngMax); latMax = Math.max(lat, latMax); invalid = invalid || !isFinite(lng) || !isFinite(lat); i += 1; } } while (i < points.length) { const point = GeoPointView.fromAny(points[i]!); this.appendChild(point); const {lng, lat} = point.geoPoint.getValue(); lngMid += lng; latMid += lat; lngMin = Math.min(lngMin, lng); latMin = Math.min(latMin, lat); lngMax = Math.max(lng, lngMax); latMax = Math.max(lat, latMax); invalid = invalid || !isFinite(lng) || !isFinite(lat); i += 1; } while (child !== null) { const next = child.nextSibling; if (child instanceof GeoPointView) { this.removeChild(child); } child = next; } if (!invalid && i !== 0) { lngMid /= i; latMid /= i; this.geoCentroid.setValue(new GeoPoint(lngMid, latMid), Affinity.Intrinsic); (this as Mutable<this>).geoBounds = new GeoBox(lngMin, latMin, lngMax, latMax); } else { this.geoCentroid.setValue(GeoPoint.origin(), Affinity.Intrinsic); (this as Mutable<this>).geoBounds = GeoBox.undefined(); } const newGeoBounds = this.geoBounds; if (!oldGeoBounds.equals(newGeoBounds)) { this.willSetGeoBounds(newGeoBounds, oldGeoBounds); this.onSetGeoBounds(newGeoBounds, oldGeoBounds); this.didSetGeoBounds(newGeoBounds, oldGeoBounds); } return this; } } appendPoint(point: AnyGeoPointView, key?: string): GeoPointView { point = GeoPointView.fromAny(point); this.appendChild(point, key); return point; } setPoint(key: string, point: AnyGeoPointView): GeoPointView { point = GeoPointView.fromAny(point); this.setChild(key, point); return point; } @Property({type: GeoPoint, value: GeoPoint.origin()}) readonly geoCentroid!: Property<this, GeoPoint, AnyGeoPoint>; @Property({type: R2Point, value: R2Point.origin()}) readonly viewCentroid!: Property<this, R2Point, AnyR2Point>; @ThemeAnimator({type: Color, value: null, inherits: true, updateFlags: View.NeedsRender}) readonly stroke!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Length, value: null, inherits: true, updateFlags: View.NeedsRender}) readonly strokeWidth!: ThemeAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Font, value: null, inherits: true}) readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>; @ThemeAnimator({type: Color, value: null, inherits: true}) readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @Property({type: Number}) readonly hitWidth!: Property<this, number | undefined>; /** @internal */ readonly gradientStops: number; protected override onInsertChild(childView: View, targetView: View | null): void { super.onInsertChild(childView, targetView); if (childView instanceof GeoPointView) { this.onInsertPoint(childView); } } protected onInsertPoint(childView: GeoPointView): void { childView.requireUpdate(View.NeedsAnimate | View.NeedsProject); } protected override didProject(viewContext: ViewContextType<this>): void { const oldGeoBounds = this.geoBounds; let lngMin = Infinity; let latMin = Infinity; let lngMax = -Infinity; let latMax = -Infinity; let lngMid = 0; let latMid = 0; let xMin = Infinity; let yMin = Infinity; let xMax = -Infinity; let yMax = -Infinity; let xMid = 0; let yMid = 0; let invalid = false; let gradientStops = 0; let pointCount = 0; let child = this.firstChild; while (child !== null) { if (child instanceof GeoPointView) { const {lng, lat} = child.geoPoint.getValue(); lngMid += lng; latMid += lat; lngMin = Math.min(lngMin, lng); latMin = Math.min(latMin, lat); lngMax = Math.max(lng, lngMax); latMax = Math.max(lat, latMax); invalid = invalid || !isFinite(lng) || !isFinite(lat); const {x, y} = child.viewPoint.getValue(); xMin = Math.min(xMin, x); yMin = Math.min(yMin, y); xMax = Math.max(x, xMax); yMax = Math.max(y, yMax); xMid += x; yMid += y; invalid = invalid || !isFinite(x) || !isFinite(y); if (child.isGradientStop()) { gradientStops += 1; } pointCount += 1; } child = child.nextSibling; } if (!invalid && pointCount !== 0) { lngMid /= pointCount; latMid /= pointCount; this.geoCentroid.setValue(new GeoPoint(lngMid, latMid), Affinity.Intrinsic); (this as Mutable<this>).geoBounds = new GeoBox(lngMin, latMin, lngMax, latMax); xMid /= pointCount; yMid /= pointCount; this.viewCentroid.setValue(new R2Point(xMid, yMid), Affinity.Intrinsic); (this as Mutable<this>).viewBounds = new R2Box(xMin, yMin, xMax, yMax); this.cullGeoFrame(viewContext.geoViewport.geoFrame); } else { this.geoCentroid.setValue(GeoPoint.origin(), Affinity.Intrinsic); (this as Mutable<this>).geoBounds = GeoBox.undefined(); this.viewCentroid.setValue(R2Point.origin(), Affinity.Intrinsic); (this as Mutable<this>).viewBounds = R2Box.undefined(); this.setCulled(true); } (this as Mutable<this>).gradientStops = gradientStops; const newGeoBounds = this.geoBounds; if (!oldGeoBounds.equals(newGeoBounds)) { this.willSetGeoBounds(newGeoBounds, oldGeoBounds); this.onSetGeoBounds(newGeoBounds, oldGeoBounds); this.didSetGeoBounds(newGeoBounds, oldGeoBounds); } super.didProject(viewContext); } protected override onRender(viewContext: ViewContextType<this>): void { super.onRender(viewContext); const renderer = viewContext.renderer; if (renderer instanceof PaintingRenderer && !this.hidden && !this.culled) { if (this.gradientStops !== 0 && renderer instanceof CanvasRenderer) { this.renderPlotGradient(renderer.context, viewContext.viewFrame); } else { this.renderPlotStroke(renderer.context, viewContext.viewFrame); } } } protected renderPlotStroke(context: PaintingContext, frame: R2Box): void { const stroke = this.stroke.value; if (stroke !== null) { let pointCount = 0; context.beginPath(); let child = this.firstChild; while (child !== null) { if (child instanceof GeoPointView) { const {x, y} = child.viewPoint.getValue(); if (pointCount === 0) { context.moveTo(x, y); } else { context.lineTo(x, y); } pointCount += 1; } child = child.nextSibling; } if (pointCount !== 0) { // save const contextLineWidth = context.lineWidth; const contextStrokeStyle = context.strokeStyle; const size = Math.min(frame.width, frame.height); const strokeWidth = this.strokeWidth.getValue().pxValue(size); context.lineWidth = strokeWidth; context.strokeStyle = stroke.toString(); context.stroke(); // restore context.lineWidth = contextLineWidth; context.strokeStyle = contextStrokeStyle; } } } protected renderPlotGradient(context: CanvasContext, frame: R2Box): void { const stroke = this.stroke.getValue(); const size = Math.min(frame.width, frame.height); const strokeWidth = this.strokeWidth.getValue().pxValue(size); // save const contextLineWidth = context.lineWidth; const contextStrokeStyle = context.strokeStyle; let p0: GeoPointView | undefined; let p1 = this.firstChild; while (p1 !== null) { if (p1 instanceof GeoPointView) { if (p0 !== void 0) { const x0 = p0.viewPoint.getValue().x; const y0 = p0.viewPoint.getValue().y; const x1 = p1.viewPoint.getValue().x; const y1 = p1.viewPoint.getValue().y; const gradient = context.createLinearGradient(x0, y0, x1, y1); let color = p0.color.getValueOr(stroke); let opacity = p0.opacity.value; if (typeof opacity === "number") { color = color.alpha(opacity); } gradient.addColorStop(0, color.toString()); color = p1.color.getValueOr(stroke); opacity = p1.opacity.value; if (typeof opacity === "number") { color = color.alpha(opacity); } gradient.addColorStop(1, color.toString()); context.beginPath(); context.moveTo(x0, y0); context.lineTo(x1, y1); context.lineWidth = strokeWidth; context.strokeStyle = gradient; context.stroke(); } p0 = p1; } p1 = p1.nextSibling; } // restore context.lineWidth = contextLineWidth; context.strokeStyle = contextStrokeStyle; } protected override updateGeoBounds(): void { // nop } override get popoverFrame(): R2Box { const viewCentroid = this.viewCentroid.value; const inversePageTransform = this.pageTransform.inverse(); const px = inversePageTransform.transformX(viewCentroid.x, viewCentroid.y); const py = inversePageTransform.transformY(viewCentroid.x, viewCentroid.y); return new R2Box(px, py, px, py); } override readonly viewBounds!: R2Box; protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null { const renderer = viewContext.renderer; if (renderer instanceof CanvasRenderer) { const p = renderer.transform.transform(x, y); return this.hitTestPlot(p.x, p.y, renderer.context, viewContext.viewFrame); } return null; } protected hitTestPlot(x: number, y: number, context: CanvasContext, frame: R2Box): GraphicsView | null { let pointCount = 0; context.beginPath(); let child = this.firstChild; while (child !== null) { if (child instanceof GeoPointView) { const {x, y} = child.viewPoint.getValue(); if (pointCount === 0) { context.moveTo(x, y); } else { context.lineTo(x, y); } pointCount += 1; } child = child.nextSibling; } if (pointCount !== 0) { // save const contextLineWidth = context.lineWidth; let hitWidth = this.hitWidth.getValueOr(0); const strokeWidth = this.strokeWidth.value; if (strokeWidth !== null) { const size = Math.min(frame.width, frame.height); hitWidth = Math.max(hitWidth, strokeWidth.pxValue(size)); } context.lineWidth = hitWidth; const pointInStroke = context.isPointInStroke(x, y); // restore context.lineWidth = contextLineWidth; if (pointInStroke) { return this; } } return null; } ripple(options?: GeoRippleOptions): GeoRippleView | null { return GeoRippleView.ripple(this, options); } override init(init: GeoPlotViewInit): void { super.init(init); if (init.stroke !== void 0) { this.stroke(init.stroke); } if (init.strokeWidth !== void 0) { this.strokeWidth(init.strokeWidth); } if (init.hitWidth !== void 0) { this.hitWidth(init.hitWidth); } if (init.font !== void 0) { this.font(init.font); } if (init.textColor !== void 0) { this.textColor(init.textColor); } const points = init.points; if (points !== void 0) { this.points(points); } } }
the_stack
import * as React from "react"; import * as R from "../resources"; import { EventSubscription } from "../../core"; import { Actions, DragData } from "../actions"; import { DraggableElement, FluentToolButton, SVGImageIcon, } from "../components"; import { ContextedComponent, MainReactContext } from "../context_component"; import { LinkCreationPanel } from "./panels/link_creator"; import { LegendCreationPanel } from "./panels/legend_creator"; import { AppStore } from "../stores"; import { strings } from "../../strings"; import { LayoutDirection, UndoRedoLocation } from "../main_view"; import { useContext } from "react"; import { Callout, DirectionalHint, IconButton } from "@fluentui/react"; import { getSVGIcon } from "../resources"; import { EditorType } from "../stores/app_store"; import { useState } from "react"; import { useEffect } from "react"; const minWidthToColapseButtons = Object.freeze({ guides: 1090, plotSegments: 1120, scaffolds: 1211, }); export const FluentUIToolbar: React.FC<{ layout: LayoutDirection; undoRedoLocation: UndoRedoLocation; toolbarLabels: boolean; }> = (props) => { const { store } = useContext(MainReactContext); const [innerWidth, setInnerWidth] = useState(window.innerWidth); const resizeListener = () => { setInnerWidth(window.innerWidth); }; useEffect(() => { setInnerWidth(window.innerWidth); window.addEventListener("resize", resizeListener); return () => { window.removeEventListener("resize", resizeListener); }; }, [setInnerWidth]); const getGlyphToolItems = (labels: boolean = true) => { return [ <> <> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.marks} </span> )} <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.rect", title: strings.toolbar.rectangle, icon: "RectangleShape", options: '{"shape":"rectangle"}', }, { classID: "mark.rect", title: strings.toolbar.ellipse, icon: "Ellipse", options: '{"shape":"ellipse"}', }, { classID: "mark.rect", title: strings.toolbar.triangle, icon: "TriangleShape", options: '{"shape":"triangle"}', }, ]} /> <ObjectButton classID="mark.symbol" title={strings.toolbar.symbol} icon="Shapes" /> <ObjectButton classID="mark.line" title={strings.toolbar.line} icon="Line" /> <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.text", title: strings.toolbar.text, icon: "FontColorA", }, { classID: "mark.textbox", title: strings.toolbar.textbox, icon: "TextField", }, ]} /> <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.icon", title: strings.toolbar.icon, icon: "ImagePixel", }, { classID: "mark.image", title: strings.toolbar.image, icon: "FileImage", }, ]} /> <ObjectButton classID="mark.data-axis" title={strings.toolbar.dataAxis} icon="mark/data-axis" /> {store.editorType === EditorType.Embedded ? ( <ObjectButton classID="mark.nested-chart" title={strings.toolbar.nestedChart} icon="BarChartVerticalFilter" /> ) : null} {props.undoRedoLocation === UndoRedoLocation.ToolBar ? ( <> <span className={"charticulator__toolbar-horizontal-separator"} /> <FluentToolButton title={strings.menuBar.undo} disabled={store.historyManager.statesBefore.length === 0} icon={"Undo"} onClick={() => new Actions.Undo().dispatch(store.dispatcher)} /> <FluentToolButton title={strings.menuBar.redo} disabled={store.historyManager.statesAfter.length === 0} icon={"Redo"} onClick={() => new Actions.Redo().dispatch(store.dispatcher)} /> </> ) : null} </> </>, ]; }; // eslint-disable-next-line max-lines-per-function const getChartToolItems = (labels: boolean = true) => { return [ <> <LinkButton label={true} /> <LegendButton /> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.guides} </span> )} <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "guide-y", title: strings.toolbar.guideY, icon: "guide/x", options: '{"shape":"rectangle"}', }, { classID: "guide-x", title: strings.toolbar.guideX, icon: "guide/y", options: '{"shape":"ellipse"}', }, { classID: "guide-coordinator-x", title: strings.toolbar.guideX, icon: "CharticulatorGuideX", options: '{"shape":"triangle"}', }, { classID: "guide-coordinator-y", title: strings.toolbar.guideY, icon: "CharticulatorGuideY", options: '{"shape":"triangle"}', }, { classID: "guide-coordinator-polar", title: strings.toolbar.guidePolar, icon: "CharticulatorGuideCoordinator", options: "", }, ]} /> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <> <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {props.layout === LayoutDirection.Vertical ? strings.toolbar.plot : strings.toolbar.plotSegments} </span> </> )} <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "plot-segment.cartesian", title: strings.toolbar.region2D, icon: "BorderDot", noDragging: true, }, { classID: "plot-segment.line", title: strings.toolbar.line, icon: "Line", noDragging: true, }, ]} /> <> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.scaffolds} </span> )} <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "scaffold/cartesian-x", title: strings.toolbar.lineH, icon: "scaffold/cartesian-x", onClick: () => null, onDrag: () => new DragData.ScaffoldType("cartesian-x"), }, { classID: "scaffold/cartesian-y", title: strings.toolbar.lineV, icon: "scaffold/cartesian-y", onClick: () => null, onDrag: () => new DragData.ScaffoldType("cartesian-y"), }, { classID: "scaffold/circle", title: strings.toolbar.polar, icon: "scaffold/circle", onClick: () => null, onDrag: () => new DragData.ScaffoldType("polar"), }, { classID: "scaffold/curve", title: strings.toolbar.curve, icon: "scaffold/curve", onClick: () => null, onDrag: () => new DragData.ScaffoldType("curve"), }, ]} /> </> </>, ]; }; const renderScaffoldButton = () => { return ( <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "scaffold/cartesian-x", title: strings.toolbar.lineH, icon: "scaffold/cartesian-x", onClick: () => null, onDrag: () => new DragData.ScaffoldType("cartesian-x"), }, { classID: "scaffold/cartesian-y", title: strings.toolbar.lineV, icon: "scaffold/cartesian-y", onClick: () => null, onDrag: () => new DragData.ScaffoldType("cartesian-y"), }, { classID: "scaffold/circle", title: strings.toolbar.polar, icon: "scaffold/circle", onClick: () => null, onDrag: () => new DragData.ScaffoldType("polar"), }, { classID: "scaffold/curve", title: strings.toolbar.curve, icon: "scaffold/curve", onClick: () => null, onDrag: () => new DragData.ScaffoldType("curve"), }, ]} /> ); }; const renderGuidesButton = () => { return ( <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "guide-y", title: strings.toolbar.guideY, icon: "guide/x", }, { classID: "guide-x", title: strings.toolbar.guideX, icon: "guide/y", options: "", }, { classID: "guide-coordinator-x", title: strings.toolbar.guideX, icon: "CharticulatorGuideX", options: "", }, { classID: "guide-coordinator-y", title: strings.toolbar.guideY, icon: "CharticulatorGuideY", options: "", }, { classID: "guide-coordinator-polar", title: strings.toolbar.guidePolar, icon: "CharticulatorGuideCoordinator", options: "", }, ]} /> ); }; // eslint-disable-next-line max-lines-per-function const getToolItems = ( labels: boolean = true, innerWidth: number = window.innerWidth ) => { return ( <> {props.undoRedoLocation === UndoRedoLocation.ToolBar ? ( <> <FluentToolButton title={strings.menuBar.undo} disabled={store.historyManager.statesBefore.length === 0} icon={"Undo"} onClick={() => new Actions.Undo().dispatch(store.dispatcher)} /> <FluentToolButton title={strings.menuBar.redo} disabled={store.historyManager.statesAfter.length === 0} icon={"Redo"} onClick={() => new Actions.Redo().dispatch(store.dispatcher)} /> <span className={"charticulator__toolbar-horizontal-separator"} /> </> ) : null} {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.marks} </span> )} <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.rect", title: strings.toolbar.rectangle, icon: "RectangleShape", options: '{"shape":"rectangle"}', }, { classID: "mark.rect", title: strings.toolbar.ellipse, icon: "Ellipse", options: '{"shape":"ellipse"}', }, { classID: "mark.rect", title: strings.toolbar.triangle, icon: "TriangleShape", options: '{"shape":"triangle"}', }, ]} /> <ObjectButton classID="mark.symbol" title="Symbol" icon="Shapes" /> <ObjectButton classID="mark.line" title="Line" icon="Line" /> <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.text", title: strings.toolbar.text, icon: "FontColorA", }, { classID: "mark.textbox", title: strings.toolbar.textbox, icon: "TextField", }, ]} /> <MultiObjectButton compact={props.layout === LayoutDirection.Vertical} tools={[ { classID: "mark.icon", title: strings.toolbar.icon, icon: "ImagePixel", }, { classID: "mark.image", title: strings.toolbar.image, icon: "FileImage", }, ]} /> <span className={"charticulator__toolbar-horizontal-separator"} /> <ObjectButton classID="mark.data-axis" title={strings.toolbar.dataAxis} icon="mark/data-axis" /> <ObjectButton classID="mark.nested-chart" title={strings.toolbar.nestedChart} icon="BarChartVerticalFilter" /> <LegendButton /> <span className={"charticulator__toolbar-horizontal-separator"} /> <LinkButton label={labels} /> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.guides} </span> )} {innerWidth > minWidthToColapseButtons.guides ? ( <> <ObjectButton classID="guide-y" title={strings.toolbar.guideY} icon="guide/x" /> <ObjectButton classID="guide-x" title={strings.toolbar.guideX} icon="guide/y" /> <ObjectButton classID="guide-coordinator-x" title={strings.toolbar.guideX} icon="CharticulatorGuideX" /> <ObjectButton classID="guide-coordinator-y" title={strings.toolbar.guideY} icon="CharticulatorGuideY" /> <ObjectButton classID="guide-coordinator-polar" title={strings.toolbar.guidePolar} icon="CharticulatorGuideCoordinator" /> </> ) : ( renderGuidesButton() )} <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <> <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {props.layout === LayoutDirection.Vertical ? strings.toolbar.plot : strings.toolbar.plotSegments} </span> </> )} <ObjectButton classID="plot-segment.cartesian" title={strings.toolbar.region2D} icon="BorderDot" noDragging={true} /> <ObjectButton classID="plot-segment.line" title={strings.toolbar.line} icon="Line" noDragging={true} /> <span className={"charticulator__toolbar-horizontal-separator"} /> {labels && ( <span className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-label" : "charticulator__toolbar-label" } > {strings.toolbar.scaffolds} </span> )} {innerWidth > minWidthToColapseButtons.scaffolds ? ( <> <ScaffoldButton type="cartesian-x" title={strings.toolbar.lineH} icon="scaffold/cartesian-x" currentTool={store.currentTool} /> <ScaffoldButton type="cartesian-y" title={strings.toolbar.lineV} icon="scaffold/cartesian-y" currentTool={store.currentTool} /> <ScaffoldButton type="polar" title={strings.toolbar.polar} icon="scaffold/circle" currentTool={store.currentTool} /> <ScaffoldButton type="curve" title={strings.toolbar.curve} icon="scaffold/curve" currentTool={store.currentTool} /> </> ) : ( renderScaffoldButton() )} </> ); }; let tooltipsItems = []; if (store.editorType === "embedded") { const chartToolItems = getChartToolItems(props.toolbarLabels); const glyphToolItems = getGlyphToolItems(props.toolbarLabels); tooltipsItems = [...chartToolItems, ...glyphToolItems]; } else { tooltipsItems = [getToolItems(props.toolbarLabels, innerWidth)]; } return ( <> <div className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical" : "charticulator__toolbar-horizontal" } > <div className="charticulator__toolbar-buttons-align-left"> {tooltipsItems.map((item, index) => { return ( <React.Fragment key={index}> <div key={index} className={ props.layout === LayoutDirection.Vertical ? "charticulator__toolbar-vertical-group" : "charticulator__toolbar-horizontal-group" } > {item} </div> </React.Fragment> ); })} </div> </div> </> ); }; export interface ObjectButtonProps { title: string; text?: string; classID: string; icon: string; options?: string; noDragging?: boolean; onClick?: () => void; onDrag?: () => any; compact?: boolean; } export class ObjectButton extends ContextedComponent< ObjectButtonProps, Record<string, unknown> > { public token: EventSubscription; public getIsActive() { return ( this.store.currentTool == this.props.classID && this.store.currentToolOptions == this.props.options ); } public componentDidMount() { this.token = this.context.store.addListener( AppStore.EVENT_CURRENT_TOOL, () => { this.forceUpdate(); } ); } public componentWillUnmount() { this.token.remove(); } public render() { return ( <> <DraggableElement dragData={ this.props.noDragging ? null : this.props.onDrag ? this.props.onDrag : () => { return new DragData.ObjectType( this.props.classID, this.props.options ); } } onDragStart={() => this.setState({ dragging: true })} onDragEnd={() => this.setState({ dragging: false })} renderDragElement={() => { return [ <SVGImageIcon url={getSVGIcon(this.props.icon)} width={32} height={32} />, { x: -16, y: -16 }, ]; }} > <IconButton iconProps={{ iconName: this.props.icon, }} title={this.props.title} text={this.props.text} checked={this.getIsActive()} onClick={() => { this.dispatch( new Actions.SetCurrentTool( this.props.classID, this.props.options ) ); if (this.props.onClick) { this.props.onClick(); } }} /> </DraggableElement> </> ); } } export class MultiObjectButton extends ContextedComponent< { compact?: boolean; tools: ObjectButtonProps[]; }, { currentSelection: { classID: string; options: string; }; dragging: boolean; } > { public state = { currentSelection: { classID: this.props.tools[0].classID, options: this.props.tools[0].options, }, dragging: false, }; public token: EventSubscription; public isActive() { const store = this.store; for (const item of this.props.tools) { if ( item.classID == store.currentTool && item.options == store.currentToolOptions ) { return true; } } return false; } public getSelectedTool() { for (const item of this.props.tools) { if ( item.classID == this.state.currentSelection.classID && item.options == this.state.currentSelection.options ) { return item; } } return this.props.tools[0]; } public componentDidMount() { this.token = this.store.addListener(AppStore.EVENT_CURRENT_TOOL, () => { for (const item of this.props.tools) { // If the tool is within the tools defined here, we update the current selection if ( this.store.currentTool == item.classID && this.store.currentToolOptions == item.options ) { this.setState({ currentSelection: { classID: item.classID, options: item.options, }, }); break; } } this.forceUpdate(); }); } public componentWillUnmount() { this.token.remove(); } public render() { const currentTool = this.getSelectedTool(); return ( <DraggableElement dragData={() => { if (currentTool?.onDrag) { return currentTool?.onDrag(); } return new DragData.ObjectType( currentTool.classID, currentTool.options ); }} onDragStart={() => this.setState({ dragging: true })} onDragEnd={() => this.setState({ dragging: false })} renderDragElement={() => { return [ <SVGImageIcon url={getSVGIcon(currentTool.icon)} width={24} height={24} />, { x: 16, y: 16 }, ]; }} > <IconButton split={true} menuProps={{ items: this.props.tools.map((tool, index) => { return { key: tool.classID + index, data: { classID: tool.classID, options: tool.options, }, text: tool.title, iconProps: { iconName: tool.icon }, }; }), onItemClick: (ev: any, item: any) => { if (item.data) { this.dispatch( new Actions.SetCurrentTool( item.data.classID, item.data.options ) ); } }, }} iconProps={{ iconName: currentTool.icon, }} onMenuClick={() => { if (currentTool) { this.dispatch( new Actions.SetCurrentTool( currentTool.classID, currentTool.options ) ); } }} /> </DraggableElement> ); } } export const ScaffoldButton: React.FC<{ currentTool: string; title: string; type: string; icon: string; }> = (props) => { return ( <FluentToolButton icon={props.icon} active={props.currentTool == props.type} title={props.title} onClick={() => { // this.dispatch(new Actions.SetCurrentTool(this.props.type)); }} dragData={() => { return new DragData.ScaffoldType(props.type); }} /> ); }; export const LinkButton: React.FC<{ label: boolean; }> = (props) => { const { store } = React.useContext(MainReactContext); const [isOpen, openDialog] = React.useState(false); return ( <span id="linkCreator"> <IconButton title={strings.toolbar.link} text={props.label ? strings.toolbar.link : ""} iconProps={{ iconName: "CharticulatorLine", }} checked={store.currentTool == "link"} onClick={() => { openDialog(true); }} /> {isOpen ? ( <Callout target={"#linkCreator"} hidden={!isOpen} onDismiss={() => openDialog(false)} > <LinkCreationPanel onFinish={() => openDialog(false)} /> </Callout> ) : null} </span> ); }; export const LegendButton: React.FC = () => { const { store } = React.useContext(MainReactContext); const [isOpen, setOpen] = React.useState(false); React.useEffect(() => { return () => { setOpen(false); }; }, [setOpen]); return ( <span id="createLegend"> <IconButton title={strings.toolbar.legend} iconProps={{ iconName: "CharticulatorLegend", }} checked={store.currentTool == "legend"} onClick={() => { setOpen(!isOpen); }} /> {isOpen ? ( <Callout onDismiss={() => setOpen(false)} target="#createLegend" directionalHint={DirectionalHint.bottomLeftEdge} > <LegendCreationPanel onFinish={() => setOpen(false)} /> </Callout> ) : null} </span> ); }; export class CheckboxButton extends React.Component< { value: boolean; text?: string; onChange?: (v: boolean) => void; }, Record<string, unknown> > { public render() { return ( <span className="charticulator__toolbar-checkbox" onClick={() => { const nv = !this.props.value; if (this.props.onChange) { this.props.onChange(nv); } }} > <SVGImageIcon url={R.getSVGIcon( this.props.value ? "checkbox/checked" : "checkbox/empty" )} /> <span className="el-label">{this.props.text}</span> </span> ); } }
the_stack
import { FeatureStateBaseHolder } from './feature_state_holders'; import { FeatureStateValueInterceptor, InterceptorValueMatch } from './interceptors'; import { FeatureStateHolder } from './feature_state'; import { AnalyticsCollector } from './analytics'; import { FeatureState, FeatureStateTypeTransformer, FeatureValueType, RolloutStrategy, SSEResultState } from './models'; import { ClientContext } from './client_context'; import { ApplyFeature, Applied } from './strategy_matcher'; import { InternalFeatureRepository } from './internal_feature_repository'; import { fhLog } from './feature_hub_config'; export enum Readyness { NotReady = 'NotReady', Ready = 'Ready', Failed = 'Failed' } export interface ReadynessListener { (state: Readyness): void; } export interface PostLoadNewFeatureStateAvailableListener { (repo: ClientFeatureRepository): void; } export interface FeatureHubRepository { // determines if the repository is ready readyness: Readyness; catchAndReleaseMode: boolean; // allows us to log an analytics event with this set of features logAnalyticsEvent(action: string, other?: Map<string, string>, ctx?: ClientContext); // returns undefined if the feature does not exist hasFeature(key: string): FeatureStateHolder; // synonym for getFeatureState feature(key: string): FeatureStateHolder; // deprecated getFeatureState(key: string): FeatureStateHolder; // release changes release(disableCatchAndRelease?: boolean): Promise<void>; // primary used to pass down the line in headers simpleFeatures(): Map<string, string | undefined>; getFlag(key: string): boolean | undefined; getString(key: string): string | undefined; getJson(key: string): string | undefined; getNumber(key: string): number | undefined; isSet(key: string): boolean; addValueInterceptor(interceptor: FeatureStateValueInterceptor); addReadynessListener(listener: ReadynessListener); addAnalyticCollector(collector: AnalyticsCollector): void; addPostLoadNewFeatureStateAvailableListener(listener: PostLoadNewFeatureStateAvailableListener); } export class ClientFeatureRepository implements InternalFeatureRepository { private hasReceivedInitialState: boolean; // indexed by key as that what the user cares about private features = new Map<string, FeatureStateBaseHolder>(); private analyticsCollectors = new Array<AnalyticsCollector>(); private readynessState: Readyness = Readyness.NotReady; private readynessListeners: Array<ReadynessListener> = []; private _catchAndReleaseMode: boolean = false; // indexed by id private _catchReleaseStates = new Map<string, FeatureState>(); private _newFeatureStateAvailableListeners: Array<PostLoadNewFeatureStateAvailableListener> = []; private _matchers: Array<FeatureStateValueInterceptor> = []; private readonly _applyFeature: ApplyFeature; constructor(applyFeature?: ApplyFeature) { this._applyFeature = applyFeature || new ApplyFeature(); } public apply(strategies: Array<RolloutStrategy>, key: string, featureValueId: string, context: ClientContext): Applied { return this._applyFeature.apply(strategies, key, featureValueId, context); } public get readyness(): Readyness { return this.readynessState; } public notify(state: SSEResultState, data: any): void { if (state !== null && state !== undefined) { switch (state) { case SSEResultState.Ack: break; case SSEResultState.Bye: this.readynessState = Readyness.NotReady; if (!this._catchAndReleaseMode) { this.broadcastReadynessState(); } break; case SSEResultState.DeleteFeature: this.deleteFeature(FeatureStateTypeTransformer.fromJson(data)); break; case SSEResultState.Failure: this.readynessState = Readyness.Failed; if (!this._catchAndReleaseMode) { this.broadcastReadynessState(); } break; case SSEResultState.Feature: const fs = FeatureStateTypeTransformer.fromJson(data); if (this._catchAndReleaseMode) { this._catchUpdatedFeatures([fs]); } else { if (this.featureUpdate(fs)) { this.triggerNewStateAvailable(); } } break; case SSEResultState.Features: const features = (data instanceof Array) ? (data as Array<FeatureState>) : (data as []).map((f) => FeatureStateTypeTransformer.fromJson(f)); if (this.hasReceivedInitialState && this._catchAndReleaseMode) { this._catchUpdatedFeatures(features); } else { let updated = false; features.forEach((f) => updated = this.featureUpdate(f) || updated); this.readynessState = Readyness.Ready; if (!this.hasReceivedInitialState) { this.hasReceivedInitialState = true; this.broadcastReadynessState(); } else if (updated) { this.triggerNewStateAvailable(); } } break; default: break; } } } public addValueInterceptor(matcher: FeatureStateValueInterceptor) { this._matchers.push(matcher); matcher.repository(this); } public valueInterceptorMatched(key: string): InterceptorValueMatch { for (let matcher of this._matchers) { const m = matcher.matched(key); if (m?.value) { return m; } } return null; } public addPostLoadNewFeatureStateAvailableListener(listener: PostLoadNewFeatureStateAvailableListener) { this._newFeatureStateAvailableListeners.push(listener); if (this._catchReleaseStates.size > 0) { listener(this); } } public addReadynessListener(listener: ReadynessListener) { this.readynessListeners.push(listener); // always let them know what it is in case its already ready listener(this.readynessState); } notReady(): void { this.readynessState = Readyness.NotReady; this.broadcastReadynessState(); } public async broadcastReadynessState() { this.readynessListeners.forEach((l) => l(this.readynessState)); } public addAnalyticCollector(collector: AnalyticsCollector): void { this.analyticsCollectors.push(collector); } public simpleFeatures(): Map<string, string | undefined> { const vals = new Map<string, string | undefined>(); this.features.forEach((value, key) => { if (value.getKey()) { // only include value features let val: any; switch (value.getType()) {// we need to pick up any overrides case FeatureValueType.Boolean: val = value.getBoolean() ? 'true' : 'false'; break; case FeatureValueType.String: val = value.getString(); break; case FeatureValueType.Number: val = value.getNumber(); break; case FeatureValueType.Json: val = value.getRawJson(); break; default: val = undefined; } vals.set(key, val === undefined ? val : val.toString()); } }); return vals; } public async logAnalyticsEvent(action: string, other?: Map<string, string>, ctx?: ClientContext) { const featureStateAtCurrentTime = []; for (let fs of this.features.values()) { if (fs.isSet()) { const fsVal: FeatureStateBaseHolder = ctx == null ? fs : fs.withContext(ctx) as FeatureStateBaseHolder; featureStateAtCurrentTime.push( fsVal.analyticsCopy() ); } } this.analyticsCollectors.forEach((ac) => ac.logEvent(action, other, featureStateAtCurrentTime)); } public hasFeature(key: string): FeatureStateHolder { return this.features.get(key); } public feature(key: string): FeatureStateHolder { let holder = this.features.get(key); if (holder === undefined) { holder = new FeatureStateBaseHolder(this, key); this.features.set(key, holder); } return holder; } // deprecated public getFeatureState(key: string): FeatureStateHolder { return this.feature(key); } get catchAndReleaseMode(): boolean { return this._catchAndReleaseMode; } set catchAndReleaseMode(value: boolean) { if (this._catchAndReleaseMode !== value && value === false) { this.release(true); } this._catchAndReleaseMode = value; } public async release(disableCatchAndRelease?: boolean): Promise<void> { while (this._catchReleaseStates.size > 0) { const states = [...this._catchReleaseStates.values()]; this._catchReleaseStates.clear(); // remove all existing items states.forEach((fs) => this.featureUpdate(fs)); } if (disableCatchAndRelease === true) { this._catchAndReleaseMode = false; } } public getFlag(key: string): boolean | undefined { return this.feature(key).getFlag(); } public getString(key: string): string | undefined { return this.feature(key).getString(); } public getJson(key: string): string | undefined { return this.feature(key).getRawJson(); } public getNumber(key: string): number | undefined { return this.feature(key).getNumber(); } public isSet(key: string): boolean { return this.feature(key).isSet(); } private _catchUpdatedFeatures(features: FeatureState[]) { let updatedValues = false; if (features && features.length > 0) { features.forEach((f) => { const existingFeature = this.features.get(f.key); if (existingFeature === null || (existingFeature.getKey() && f.version > existingFeature.getFeatureState().version)) { const fs = this._catchReleaseStates.get(f.id); if (fs == null) { this._catchReleaseStates.set(f.id, f); updatedValues = true; } else { // check it is newer if (fs.version === undefined || (f.version !== undefined && f.version > fs.version)) { this._catchReleaseStates.set(f.id, f); updatedValues = true; } } } }); } if (updatedValues) { this.triggerNewStateAvailable(); } } private async triggerNewStateAvailable() { if (this.hasReceivedInitialState && this._newFeatureStateAvailableListeners.length > 0) { if (!this._catchAndReleaseMode || (this._catchReleaseStates.size > 0)) { this._newFeatureStateAvailableListeners.forEach((l) => { try { l(this); } catch (e) { fhLog.log('failed', e); } }); } } else { // console.log('new data, no listeners'); } } private featureUpdate(fs: FeatureState): boolean { if (fs === undefined || fs.key === undefined) { return false; } let holder = this.features.get(fs.key); if (holder === undefined) { const newFeature = new FeatureStateBaseHolder(this, fs.key, holder); this.features.set(fs.key, newFeature); holder = newFeature; } else if (holder.getFeatureState() !== undefined) { if (fs.version < holder.getFeatureState().version) { return false; } else if (fs.version === holder.getFeatureState().version && fs.value === holder.getFeatureState().value) { return false; } } return holder.setFeatureState(fs); } private deleteFeature(featureState: FeatureState) { featureState.value = undefined; let holder = this.features.get(featureState.key); if (holder) { holder.setFeatureState(featureState); } } }
the_stack
import { basename } from '../Util' import { vdf } from '../Parsers/Vdf' import { BspTexture, Bsp } from '../Bsp' import { Reader, ReaderDataType } from '../Reader' import { BspLightmapParser } from '../Parsers/BspLightmapParser' import { paletteWithLastTransToRGBA, paletteToRGBA } from './Util' export function parseModels( models: BspLumpModel[], faces: BspLumpFace[], edges: BspLumpEdge[], surfEdges: BspLumpSurfedge[], vertices: BspLumpVertex[], texinfo: BspLumpTexInfo[], textures: BspTexture[], lightmap: BspLightmapParser ) { const parsedModels = [] for (let i = 0; i < models.length; ++i) { const model = models[i] const _faces: { buffer: Float32Array textureIndex: number }[] = [] const v0 = new Float32Array(3) const v1 = new Float32Array(3) const v2 = new Float32Array(3) const uv0 = new Float32Array(2) const uv1 = new Float32Array(2) const uv2 = new Float32Array(2) const luv0 = new Float32Array(2) const luv1 = new Float32Array(2) const luv2 = new Float32Array(2) let origin = i === 0 ? [0, 0, 0] : [0, 0, 0].map( (_, i) => (model.maxs[i] - model.mins[i]) / 2 + model.mins[i] ) for (let i = model.firstFace; i < model.firstFace + model.faceCount; ++i) { const faceData = { // 3 floats vertices | 2 floats uvs | 2 floats luvs buffer: new Float32Array((faces[i].edgeCount - 2) * 21), textureIndex: -1 } const faceTexInfo = texinfo[faces[i].textureInfo] const faceTexture = textures[faceTexInfo.textureIndex] const faceSurfEdges = surfEdges.slice( faces[i].firstEdge, faces[i].firstEdge + faces[i].edgeCount ) const v0idx = edges[Math.abs(faceSurfEdges[0])][faceSurfEdges[0] > 0 ? 0 : 1] v0[0] = vertices[v0idx][0] v0[1] = vertices[v0idx][1] v0[2] = vertices[v0idx][2] uv0[0] = v0[0] * faceTexInfo.s[0] + v0[1] * faceTexInfo.s[1] + v0[2] * faceTexInfo.s[2] + faceTexInfo.sShift uv0[1] = v0[0] * faceTexInfo.t[0] + v0[1] * faceTexInfo.t[1] + v0[2] * faceTexInfo.t[2] + faceTexInfo.tShift luv0[0] = 0 luv0[1] = 0 const v1idx = edges[Math.abs(faceSurfEdges[1])][faceSurfEdges[1] > 0 ? 0 : 1] v1[0] = vertices[v1idx][0] v1[1] = vertices[v1idx][1] v1[2] = vertices[v1idx][2] uv1[0] = v1[0] * faceTexInfo.s[0] + v1[1] * faceTexInfo.s[1] + v1[2] * faceTexInfo.s[2] + faceTexInfo.sShift uv1[1] = v1[0] * faceTexInfo.t[0] + v1[1] * faceTexInfo.t[1] + v1[2] * faceTexInfo.t[2] + faceTexInfo.tShift luv1[0] = 0 luv1[1] = 0.999 let compIndex = 0 for (let j = 2; j < faces[i].edgeCount; ++j) { const v2idx = edges[Math.abs(faceSurfEdges[j])][faceSurfEdges[j] > 0 ? 0 : 1] v2[0] = vertices[v2idx][0] v2[1] = vertices[v2idx][1] v2[2] = vertices[v2idx][2] uv2[0] = v2[0] * faceTexInfo.s[0] + v2[1] * faceTexInfo.s[1] + v2[2] * faceTexInfo.s[2] + faceTexInfo.sShift uv2[1] = v2[0] * faceTexInfo.t[0] + v2[1] * faceTexInfo.t[1] + v2[2] * faceTexInfo.t[2] + faceTexInfo.tShift luv2[0] = 0.999 luv2[1] = 0.999 // vert1: coord, uv and luv faceData.buffer[compIndex++] = v0[0] faceData.buffer[compIndex++] = v0[1] faceData.buffer[compIndex++] = v0[2] faceData.buffer[compIndex++] = uv0[0] faceData.buffer[compIndex++] = uv0[1] faceData.buffer[compIndex++] = luv0[0] faceData.buffer[compIndex++] = luv0[1] // vert2 faceData.buffer[compIndex++] = v1[0] faceData.buffer[compIndex++] = v1[1] faceData.buffer[compIndex++] = v1[2] faceData.buffer[compIndex++] = uv1[0] faceData.buffer[compIndex++] = uv1[1] faceData.buffer[compIndex++] = luv1[0] faceData.buffer[compIndex++] = luv1[1] // vert2 faceData.buffer[compIndex++] = v2[0] faceData.buffer[compIndex++] = v2[1] faceData.buffer[compIndex++] = v2[2] faceData.buffer[compIndex++] = uv2[0] faceData.buffer[compIndex++] = uv2[1] faceData.buffer[compIndex++] = luv2[0] faceData.buffer[compIndex++] = luv2[1] v1[0] = v2[0] v1[1] = v2[1] v1[2] = v2[2] uv1[0] = uv2[0] uv1[1] = uv2[1] luv1[0] = luv2[0] luv1[1] = luv2[1] } // face has a lightmap if flag is equal to 0 if (faceTexInfo.flags === 0 || faceTexInfo.flags === -65536) { lightmap.processFace( faceData.buffer, faceTexInfo, faces[i].lightmapOffset ) } faceData.textureIndex = faceTexInfo.textureIndex for (let j = 0; j < faceData.buffer.length / 7; ++j) { faceData.buffer[j * 7] -= origin[0] faceData.buffer[j * 7 + 1] -= origin[1] faceData.buffer[j * 7 + 2] -= origin[2] faceData.buffer[j * 7 + 3] /= faceTexture.width faceData.buffer[j * 7 + 4] /= faceTexture.height } _faces.push(faceData) } parsedModels.push({ origin, faces: _faces }) } return parsedModels } export enum BspLumpIndex { Entities = 0, Planes = 1, Textures = 2, Vertices = 3, Visibility = 4, Nodes = 5, TexInfo = 6, Faces = 7, Lighting = 8, ClipNodes = 9, Leaves = 10, MarkSurfaces = 11, Edges = 12, SurfEdges = 13, Models = 14 } export interface BspLump { offset: number length: number } export interface BspLumpFace { plane: number planeSide: number firstEdge: number edgeCount: number textureInfo: number styles: number[] lightmapOffset: number } export interface BspLumpModel { mins: number[] maxs: number[] origin: number[] headNodes: number[] visLeaves: number firstFace: number faceCount: number } export type BspLumpEdge = number[] export type BspLumpSurfedge = number export type BspLumpVertex = number[] export interface BspLumpTexInfo { s: number[] sShift: number t: number[] tShift: number textureIndex: number flags: number } export type BspLumpLightmap = Uint8Array export class BspParser { static parse(name: string, buffer: ArrayBuffer): Bsp { const r = new Reader(buffer) const version = r.ui() if (version !== 30) { throw new Error('Invalid map version') } const lumps: BspLump[] = [] for (let i = 0; i < 15; ++i) { lumps.push({ offset: r.ui(), length: r.ui() }) } const entities = this.loadEntities( r, lumps[BspLumpIndex.Entities].offset, lumps[BspLumpIndex.Entities].length ) const textures = this.loadTextures(r, lumps[BspLumpIndex.Textures].offset) const models = this.loadModels( r, lumps[BspLumpIndex.Models].offset, lumps[BspLumpIndex.Models].length ) const faces = this.loadFaces( r, lumps[BspLumpIndex.Faces].offset, lumps[BspLumpIndex.Faces].length ) const edges = this.loadEdges( r, lumps[BspLumpIndex.Edges].offset, lumps[BspLumpIndex.Edges].length ) const surfEdges = this.loadSurfEdges( r, lumps[BspLumpIndex.SurfEdges].offset, lumps[BspLumpIndex.SurfEdges].length ) const vertices = this.loadVertices( r, lumps[BspLumpIndex.Vertices].offset, lumps[BspLumpIndex.Vertices].length ) const texinfo = this.loadTexInfo( r, lumps[BspLumpIndex.TexInfo].offset, lumps[BspLumpIndex.TexInfo].length ) const lightmap = this.loadLightmap( r, lumps[BspLumpIndex.Lighting].offset, lumps[BspLumpIndex.Lighting].length ) const parsedLightmap = BspLightmapParser.init(lightmap) const parsedModels = parseModels( models, faces, edges, surfEdges, vertices, texinfo, textures, parsedLightmap ) return new Bsp(name, entities, textures, parsedModels, { width: BspLightmapParser.TEXTURE_SIZE, height: BspLightmapParser.TEXTURE_SIZE, data: parsedLightmap.getTexture() }) } private static loadFaces( r: Reader, offset: number, length: number ): BspLumpFace[] { r.seek(offset) const faces = [] for (let i = 0; i < length / 20; ++i) { faces.push({ plane: r.us(), planeSide: r.us(), firstEdge: r.ui(), edgeCount: r.us(), textureInfo: r.us(), styles: [r.ub(), r.ub(), r.ub(), r.ub()], lightmapOffset: r.ui() }) } return faces } private static loadModels( r: Reader, offset: number, length: number ): BspLumpModel[] { r.seek(offset) const models = [] for (let i = 0; i < length / 64; ++i) { models.push({ mins: [r.f(), r.f(), r.f()], maxs: [r.f(), r.f(), r.f()], origin: [r.f(), r.f(), r.f()], headNodes: [r.i(), r.i(), r.i(), r.i()], visLeaves: r.i(), firstFace: r.i(), faceCount: r.i() }) } return models } private static loadEdges( r: Reader, offset: number, length: number ): BspLumpEdge[] { r.seek(offset) const edges = [] for (let i = 0; i < length / 4; ++i) { edges.push([r.us(), r.us()]) } return edges } private static loadSurfEdges( r: Reader, offset: number, length: number ): BspLumpSurfedge[] { r.seek(offset) const surfEdges = [] for (let i = 0; i < length / 4; ++i) { surfEdges.push(r.i()) } return surfEdges } private static loadVertices( r: Reader, offset: number, length: number ): BspLumpVertex[] { r.seek(offset) const vertices = [] for (let i = 0; i < length / 12; ++i) { vertices.push([r.f(), r.f(), r.f()]) } return vertices } private static loadTexInfo( r: Reader, offset: number, length: number ): BspLumpTexInfo[] { r.seek(offset) const texinfo: BspLumpTexInfo[] = [] for (let i = 0; i < length / 40; ++i) { texinfo.push({ s: [r.f(), r.f(), r.f()], sShift: r.f(), t: [r.f(), r.f(), r.f()], tShift: r.f(), textureIndex: r.i(), flags: r.i() }) } return texinfo } private static loadLightmap( r: Reader, offset: number, length: number ): BspLumpLightmap { r.seek(offset) return r.arrx(length, ReaderDataType.UByte) } private static loadTextureData(r: Reader) { const name = r.nstr(16) const width = r.ui() const height = r.ui() const isExternal = !r.ui() // if mipmap offset == 0 if (isExternal) { const data = new Uint8Array(4) data[0] = data[1] = data[2] = data[3] = 255 return { name, width, height, data, isExternal } } else { r.skip(3 * 4) // skip mipmap offsets // read largest mipmap data const pixelCount = width * height const pixels = r.arrx(pixelCount, ReaderDataType.UByte) // skip other 3 mipmaps r.skip(21 * (pixelCount / 64)) r.skip(2) // skip padding bytes const palette = r.arrx(768, ReaderDataType.UByte) const data = name[0] === '{' ? paletteWithLastTransToRGBA(pixels, palette) : paletteToRGBA(pixels, palette) return { name, width, height, data, isExternal } } } private static loadTextures(r: Reader, offset: number) { r.seek(offset) const count = r.ui() const offsets = [] for (let i = 0; i < count; ++i) { offsets.push(r.ui()) } const textures: BspTexture[] = [] for (let i = 0; i < count; ++i) { if (offsets[i] === 0xffffffff) { textures.push({ name: 'ERROR404', width: 1, height: 1, data: new Uint8Array([0, 255, 0, 255]), isExternal: false }) } else { r.seek(offset + offsets[i]) textures.push(this.loadTextureData(r)) } } return textures } private static loadEntities(r: Reader, offset: number, length: number) { r.seek(offset) const entities: any[] = vdf(r.nstr(length)) as any const VECTOR_ATTRS = [ 'origin', 'angles', '_diffuse_light', '_light', 'rendercolor', 'avelocity' ] const NUMBER_ATTRS = ['renderamt', 'rendermode', 'scale'] const worldSpawn = entities[0] if (worldSpawn.classname === 'worldspawn') { worldSpawn.model = '*0' worldSpawn.wad = worldSpawn.wad || '' worldSpawn.wad = worldSpawn.wad .split(';') .filter((w: string) => w.length) .map((w: string) => w.replace(/\\/g, '/')) .map((w: string) => basename(w)) } entities.forEach(e => { if (e.model) { if (typeof e.renderamt === 'undefined') { e.renderamt = 0 } if (typeof e.rendermode === 'undefined') { e.rendermode = 0 } if (typeof e.renderfx === 'undefined') { e.renderfx = 0 } if (typeof e.rendercolor === 'undefined') { e.rendercolor = '0 0 0' } } VECTOR_ATTRS.forEach(attr => { if (e[attr]) { e[attr] = e[attr].split(' ').map((v: string) => Number.parseFloat(v)) } }) NUMBER_ATTRS.forEach(attr => { if (e[attr]) { e[attr] = Number.parseFloat(e[attr]) } }) }) return entities } }
the_stack
import { UnexpectedUndefinedError } from '../errors/internal-error'; import { ComponentItem } from '../items/component-item'; import { LayoutManager } from '../layout-manager'; import { DomConstants } from '../utils/dom-constants'; import { DragListener } from '../utils/drag-listener'; /** * Represents an individual tab within a Stack's header * @public */ export class Tab { /** @internal */ private readonly _element: HTMLDivElement; /** @internal */ private readonly _titleElement: HTMLSpanElement; /** @internal */ private readonly _closeElement: HTMLDivElement | undefined; /** @internal */ private _dragListener: DragListener | undefined; /** @internal */ private _isActive = false; /** @internal */ private readonly _tabClickListener = (ev: MouseEvent) => this.onTabClickDown(ev); /** @internal */ private readonly _tabTouchStartListener = (ev: TouchEvent) => this.onTabTouchStart(ev); /** @internal */ private readonly _closeClickListener = () => this.onCloseClick(); /** @internal */ private readonly _closeTouchStartListener = () => this.onCloseTouchStart(); // /** @internal */ // private readonly _closeMouseDownListener = () => this.onCloseMousedown(); /** @internal */ private readonly _dragStartListener = (x: number, y: number) => this.onDragStart(x, y); /** @internal */ private readonly _contentItemDestroyListener = () => this.onContentItemDestroy(); /** @internal */ private readonly _tabTitleChangedListener = (title: string) => this.setTitle(title) get isActive(): boolean { return this._isActive; } // get header(): Header { return this._header; } get componentItem(): ComponentItem { return this._componentItem; } /** @deprecated use {@link (Tab:class).componentItem} */ get contentItem(): ComponentItem { return this._componentItem; } get element(): HTMLElement { return this._element; } get titleElement(): HTMLElement { return this._titleElement; } get closeElement(): HTMLElement | undefined { return this._closeElement; } get reorderEnabled(): boolean { return this._dragListener !== undefined; } set reorderEnabled(value: boolean) { if (value !== this.reorderEnabled) { if (value) { this.enableReorder(); } else { this.disableReorder(); } } } /** @internal */ constructor( /** @internal */ private readonly _layoutManager: LayoutManager, /** @internal */ private _componentItem: ComponentItem, /** @internal */ private _closeEvent: Tab.CloseEvent | undefined, /** @internal */ private _focusEvent: Tab.FocusEvent | undefined, /** @internal */ private _dragStartEvent: Tab.DragStartEvent | undefined ) { this._element = document.createElement('div'); this._element.classList.add(DomConstants.ClassName.Tab); this._titleElement = document.createElement('span'); this._titleElement.classList.add(DomConstants.ClassName.Title); this._closeElement = document.createElement('div'); this._closeElement.classList.add(DomConstants.ClassName.CloseTab); this._element.appendChild(this._titleElement); this._element.appendChild(this._closeElement); if (_componentItem.isClosable) { this._closeElement.style.display = ''; } else { this._closeElement.style.display = 'none'; } this.setTitle(_componentItem.title); this._componentItem.on('titleChanged', this._tabTitleChangedListener); const reorderEnabled = _componentItem.reorderEnabled ?? this._layoutManager.layoutConfig.settings.reorderEnabled; if (reorderEnabled) { this.enableReorder(); } this._element.addEventListener('click', this._tabClickListener, { passive: true }); this._element.addEventListener('touchstart', this._tabTouchStartListener, { passive: true }); if (this._componentItem.isClosable) { this._closeElement.addEventListener('click', this._closeClickListener, { passive: true }); this._closeElement.addEventListener('touchstart', this._closeTouchStartListener, { passive: true }); // this._closeElement.addEventListener('mousedown', this._closeMouseDownListener, { passive: true }); } else { this._closeElement.remove(); this._closeElement = undefined; } this._componentItem.setTab(this); this._layoutManager.emit('tabCreated', this); } /** * Sets the tab's title to the provided string and sets * its title attribute to a pure text representation (without * html tags) of the same string. */ setTitle(title: string): void { this._titleElement.innerText = title; this._element.title = title; } /** * Sets this tab's active state. To programmatically * switch tabs, use Stack.setActiveComponentItem( item ) instead. */ setActive(isActive: boolean): void { if (isActive === this._isActive) { return; } this._isActive = isActive; if (isActive) { this._element.classList.add(DomConstants.ClassName.Active); } else { this._element.classList.remove(DomConstants.ClassName.Active); } } /** * Destroys the tab * @internal */ destroy(): void { this._closeEvent = undefined; this._focusEvent = undefined; this._dragStartEvent = undefined; this._element.removeEventListener('click', this._tabClickListener); this._element.removeEventListener('touchstart', this._tabTouchStartListener); this._closeElement?.removeEventListener('click', this._closeClickListener); this._closeElement?.removeEventListener('touchstart', this._closeTouchStartListener); // this._closeElement?.removeEventListener('mousedown', this._closeMouseDownListener); this._componentItem.off('titleChanged', this._tabTitleChangedListener); if (this.reorderEnabled) { this.disableReorder(); } this._element.remove(); } /** @internal */ setBlurred(): void { this._element.classList.remove(DomConstants.ClassName.Focused); this._titleElement.classList.remove(DomConstants.ClassName.Focused); } /** @internal */ setFocused(): void { this._element.classList.add(DomConstants.ClassName.Focused); this._titleElement.classList.add(DomConstants.ClassName.Focused); } /** * Callback for the DragListener * @param x - The tabs absolute x position * @param y - The tabs absolute y position * @internal */ private onDragStart(x: number, y: number): void { if (this._dragListener === undefined) { throw new UnexpectedUndefinedError('TODSDLU10093'); } else { if (this._dragStartEvent === undefined) { throw new UnexpectedUndefinedError('TODS23309'); } else { this._dragStartEvent(x, y, this._dragListener, this.componentItem); } } } /** @internal */ private onContentItemDestroy() { if (this._dragListener !== undefined) { this._dragListener.destroy(); this._dragListener = undefined; } } /** * Callback when the tab is clicked * @internal */ private onTabClickDown(event: MouseEvent) { const target = event.target; if (target === this._element || target === this._titleElement) { // left mouse button if (event.button === 0) { // event.stopPropagation(); this.notifyFocus(); // middle mouse button } else if (event.button === 1 && this._componentItem.isClosable) { // event.stopPropagation(); this.notifyClose(); } } } /** @internal */ private onTabTouchStart(event: TouchEvent) { if (event.target === this._element) { this.notifyFocus(); } } /** * Callback when the tab's close button is clicked * @internal */ private onCloseClick() { this.notifyClose(); } /** @internal */ private onCloseTouchStart() { this.notifyClose(); } /** * Callback to capture tab close button mousedown * to prevent tab from activating. * @internal */ // private onCloseMousedown(): void { // // event.stopPropagation(); // } /** @internal */ private notifyClose() { if (this._closeEvent === undefined) { throw new UnexpectedUndefinedError('TNC15007'); } else { this._closeEvent(this._componentItem); } } /** @internal */ private notifyFocus() { if (this._focusEvent === undefined) { throw new UnexpectedUndefinedError('TNA15007'); } else { this._focusEvent(this._componentItem); } } /** @internal */ private enableReorder() { this._dragListener = new DragListener(this._element, [this._titleElement]); this._dragListener.on('dragStart', this._dragStartListener); this._componentItem.on('destroy', this._contentItemDestroyListener); } /** @internal */ private disableReorder() { if (this._dragListener === undefined) { throw new UnexpectedUndefinedError('TDR87745'); } else { this._componentItem.off('destroy', this._contentItemDestroyListener); this._dragListener.off('dragStart', this._dragStartListener); this._dragListener = undefined; } } } /** @public */ export namespace Tab { /** @internal */ export type CloseEvent = (componentItem: ComponentItem) => void; /** @internal */ export type FocusEvent = (componentItem: ComponentItem) => void; /** @internal */ export type DragStartEvent = (x: number, y: number, dragListener: DragListener, componentItem: ComponentItem) => void; }
the_stack
import { Task, TaskGroup, WorkspaceFolder, RelativePattern, ShellExecution, Uri, workspace } from "vscode"; import * as path from "path"; import * as util from "../common/utils"; import * as log from "../common/log"; import { configuration } from "../common/configuration"; import { filesCache } from "../cache"; import { execSync } from "child_process"; import { TaskExplorerProvider } from "./provider"; import { TaskExplorerDefinition } from "../taskDefinition"; export class GulpTaskProvider extends TaskExplorerProvider implements TaskExplorerProvider { constructor() { super("gulp"); } public createTask(target: string, cmd: string, folder: WorkspaceFolder, uri: Uri): Task { const def = this.getDefaultDefinition(target, folder, uri); const cwd = path.dirname(uri.fsPath); const args = [ "gulp", target ]; const options = { cwd }; const execution = new ShellExecution("npx", args, options); return new Task(def, folder, target, "gulp", execution, "$msCompile"); } public getDocumentPosition(scriptName: string | undefined, documentText: string | undefined): number { if (!scriptName || !documentText) { return 0; } let idx = this.getDocumentPositionLine("gulp.task(", scriptName, documentText); if (idx === -1) { idx = this.getDocumentPositionLine("exports[", scriptName, documentText); } if (idx === -1) { idx = this.getDocumentPositionLine("exports.", scriptName, documentText, 0, 0, true); } return idx; } private findTargets(fsPath: string, logPad = ""): string[] { let scripts: string[] = []; log.methodStart("find gulp targets", 1, logPad, true); // // Try running 'gulp' itself to get the targets. If fail, just custom parse // // Sample Output of gulp --tasks : // // [13:17:46] Tasks for C:\Projects\vscode-taskexplorer\test-files\gulpfile.js // [13:17:46] ├── hello // [13:17:46] └── build:test // // Tasks for C:\Projects\.....\gulpfile.js // [12:28:59] ├─┬ lint // [12:28:59] │ └─┬ <series> // [12:28:59] │ └── lintSCSS // [12:28:59] ├─┬ watch // [12:28:59] │ └─┬ <parallel> // [12:28:59] │ ├── cssWatcher // [12:28:59] │ ├── jsWatcher // [12:28:59] │ └── staticWatcher // [12:28:59] ├── clean // [12:28:59] ├─┬ build // [12:28:59] │ └─┬ <series> // [12:28:59] │ ├── buildCSS // [12:28:59] │ ├── buildStatic // [12:28:59] │ └── buildJS // [12:28:59] ├── init // [12:28:59] ├─┬ dist:copy // [12:28:59] │ └─┬ <series> // [12:28:59] │ ├── cleanDistLibs // [12:28:59] │ └── copyLibs // [12:28:59] ├── dist:normalize // [12:28:59] ├─┬ dev // [12:28:59] │ └─┬ <parallel> // [12:28:59] │ ├─┬ watch // [12:28:59] │ │ └─┬ <parallel> // [12:28:59] │ │ ├── cssWatcher // [12:28:59] │ │ ├── jsWatcher // [12:28:59] │ │ └── staticWatcher // [12:28:59] │ └── devServer // [12:28:59] └─┬ default // [12:28:59] └─┬ <series> // [12:28:59] ├─┬ lint // [12:28:59] │ └─┬ <series> // [12:28:59] │ └── lintSCSS // [12:28:59] ├── clean // [12:28:59] └─┬ build // [12:28:59] └─┬ <series> // [12:28:59] ├── buildCSS // [12:28:59] ├── buildStatic // [12:28:59] └── buildJS // if (configuration.get("useGulp") === true) { let stdout: Buffer | undefined; try { stdout = execSync("npx gulp --tasks", { cwd: path.dirname(fsPath) }); } catch (e) { log.write(e); } // // Loop through all the lines and extract the task names // const contents = stdout?.toString().split("\n"); if (contents) { for (const c of contents) { const line = c.match(/(\[[\w\W][^\]]+\][ ](├─┬|├──|└──|└─┬) )([\w\-]+)/i); if (line && line.length > 3 && line[3]) { log.value(" Found target (gulp --tasks)", line[3], 3, logPad); scripts.push(line[3].toString()); } } } } else { scripts = this.parseGulpTasks(fsPath); } log.methodDone("find gulp targets", 1, logPad, true); return scripts; } public getDefaultDefinition(target: string, folder: WorkspaceFolder, uri: Uri): TaskExplorerDefinition { const def: TaskExplorerDefinition = { type: "gulp", script: target, target, path: util.getRelativePath(folder, uri), fileName: path.basename(uri.path), uri }; return def; } private parseGulpTasks(fsPath: string): string[] { const scripts: string[] = []; const contents = util.readFileSync(fsPath); let idx = 0; let eol = contents.indexOf("\n", 0); while (eol !== -1) { let tgtName: string | undefined; const line = contents.substring(idx, eol).trim(); if (line.length > 0) { if (line.toLowerCase().trimLeft().startsWith("exports")) { tgtName = this.parseGulpExport(line); } else if (line.toLowerCase().trimLeft().startsWith("gulp.task")) { tgtName = this.parseGulpTask(line, contents, eol); } if (tgtName) { scripts.push(tgtName); log.write(" found gulp target"); log.value(" name", tgtName); } } idx = eol + 1; eol = contents.indexOf("\n", idx); } return scripts; } private parseGulpExport(line: string) { let idx1: number, idx2: number; let tgtName: string | undefined; if (line.toLowerCase().trimLeft().startsWith("exports.")) { idx1 = line.indexOf(".") + 1; idx2 = line.indexOf(" ", idx1); if (idx2 === -1) { idx2 = line.indexOf("=", idx1); } if (idx1 !== -1) { tgtName = line.substring(idx1, idx2).trim(); } } else if (line.toLowerCase().trimLeft().startsWith("exports[")) { idx1 = line.indexOf("[") + 2; // skip past [ and '/" idx2 = line.indexOf("]", idx1) - 1; // move up to "/' if (idx1 !== -1) { tgtName = line.substring(idx1, idx2).trim(); } } return tgtName; } private parseGulpTask(line: string, contents: string, eol: number) { let idx1: number; let tgtName: string | undefined; idx1 = line.indexOf("'"); if (idx1 === -1) { idx1 = line.indexOf('"'); } if (idx1 === -1) // check next line for task name { let eol2 = eol + 1; eol2 = contents.indexOf("\n", eol2); line = contents.substring(eol + 1, eol2).trim(); if (line.startsWith("'") || line.startsWith('"')) { idx1 = line.indexOf("'"); if (idx1 === -1) { idx1 = line.indexOf('"'); } if (idx1 !== -1) { eol = eol2; } } } if (idx1 !== -1) { idx1++; let idx2 = line.indexOf("'", idx1); if (idx2 === -1) { idx2 = line.indexOf('"', idx1); } if (idx2 !== -1) { tgtName = line.substring(idx1, idx2).trim(); } } return tgtName; } public async readTasks(logPad = ""): Promise<Task[]> { log.methodStart("detect gulp files", 1, logPad, true); const allTasks: Task[] = []; const visitedFiles: Set<string> = new Set(); const paths = filesCache.get("gulp"); if (workspace.workspaceFolders && paths) { for (const fobj of paths) { if (!util.isExcluded(fobj.uri.path) && !visitedFiles.has(fobj.uri.fsPath)) { visitedFiles.add(fobj.uri.fsPath); const tasks = await this.readUriTasks(fobj.uri, undefined, logPad + " "); log.write(" processed gulp file", 3, logPad); log.value(" file", fobj.uri.fsPath, 3, logPad); log.value(" targets in file", tasks.length, 3, logPad); allTasks.push(...tasks); } } } log.value(" # of gulp tasks", allTasks.length, 2, logPad); log.methodDone("detect gulp files", 1, logPad, true); return allTasks; } public async readUriTasks(uri: Uri, wsFolder?: WorkspaceFolder, logPad = ""): Promise<Task[]> { const result: Task[] = []; const folder = wsFolder || workspace.getWorkspaceFolder(uri); log.methodStart("read gulp file uri task", 1, logPad, true, [["path", uri?.fsPath], ["project folder", folder?.name]]); if (folder) { const scripts = this.findTargets(uri.fsPath, logPad + " "); if (scripts) { for (const s of scripts) { const task = this.createTask(s, s, folder, uri); task.group = TaskGroup.Build; result.push(task); } } } log.methodDone("read gulp file uri tasks", 1, logPad, true); return result; } }
the_stack
import { Format } from "../../lib/parse"; import { Api, Auth, Trust, Infra, Rbac } from "../"; import ActionType from "./action_type"; import { State } from "./state"; import { Env } from "./envs"; import { Patch } from "rfc6902"; import Client from "."; export namespace Action { export type EnvkeyAction = Action.ClientAction | Api.Action.RequestAction; export type DispatchAction<ActionType extends EnvkeyAction = EnvkeyAction> = ActionType extends Api.Action.RequestAction ? Omit<ActionType, "meta"> & { meta?: Partial<ActionType["meta"]> } : ActionType; export type SuccessAction< ActionType extends EnvkeyAction = EnvkeyAction, SuccessType = any > = { type: string; meta: { rootAction: ActionType; }; payload: SuccessType; }; export type FailureAction< ActionType extends EnvkeyAction = EnvkeyAction, FailureType = Api.Net.ErrorResult > = { type: string; meta: { rootAction: ActionType; }; payload: FailureType; }; export type ReplayableEnvUpdateAction = { type: EnvUpdateAction["type"]; payload: { diffs: Patch; reverse: Patch; revert?: number; }; meta: { envParentId: string; environmentId: string; entryKeys: string[]; }; }; export type PendingEnvUpdateAction = Omit< ReplayableEnvUpdateAction, "meta" > & { meta: Omit<ReplayableEnvUpdateAction["meta"], "pendingAt"> & { pendingAt: number; }; }; export type EnvUpdateActions = { CreateEntry: { type: ActionType.CREATE_ENTRY; payload: { envParentId: string; entryKey: string; environmentId: string; val: Env.EnvWithMetaCell; }; }; UpdateEntry: { type: ActionType.UPDATE_ENTRY; payload: { envParentId: string; environmentId: string; entryKey: string; newEntryKey: string; }; }; RemoveEntry: { type: ActionType.REMOVE_ENTRY; payload: { envParentId: string; environmentId: string; entryKey: string; }; }; UpdateEntryVal: { type: ActionType.UPDATE_ENTRY_VAL; payload: { envParentId: string; environmentId: string; entryKey: string; update: Env.EnvWithMetaCell; }; }; RevertEnvironment: { type: ActionType.REVERT_ENVIRONMENT; payload: Env.TargetVersionParams; }; ImportEnvironment: { type: ActionType.IMPORT_ENVIRONMENT; payload: { envParentId: string; environmentId: string; parsed: { [k: string]: string }; }; }; }; export type ClientActions = EnvUpdateActions & { Register: { type: ActionType.REGISTER; payload: Pick<Api.Net.ApiParamTypes["Register"], "user" | "org"> & { device: Pick<Api.Net.DeviceParams, "name">; } & ( | ({ hostType: "cloud"; } & ( | { provider: "email"; emailVerificationToken: string; } | { provider: Auth.ExternalAuthProviderType; externalAuthSessionId: string; } )) | (({ hostType: "self-hosted"; provider: "email"; } & Omit<Infra.DeploySelfHostedParams, "registerAction">) & ( | { devOnlyLocalSelfHosted?: undefined; emailVerificationToken?: undefined; } | { devOnlyLocalSelfHosted: true; emailVerificationToken: string; } )) | { hostType: "community"; provider: "email"; emailVerificationToken: string; communityAuth: string; } ); }; CreateSession: { type: ActionType.CREATE_SESSION; payload: { accountId: string; emailVerificationToken?: string; externalAuthSessionId?: string; }; }; GetSession: { type: ActionType.GET_SESSION; payload?: { skipWaitForReencryption?: true }; }; AuthenticateCliKey: { type: ActionType.AUTHENTICATE_CLI_KEY; payload: { cliKey: string }; }; SelectDefaultAccount: { type: ActionType.SELECT_DEFAULT_ACCOUNT; payload: { accountId: string }; }; SignOut: { type: ActionType.SIGN_OUT; payload: { accountId: string }; }; ForgetDevice: { type: ActionType.FORGET_DEVICE; payload: { accountId: string }; }; AddTrustedSessionPubkey: { type: ActionType.ADD_TRUSTED_SESSION_PUBKEY; payload: { id: string; trusted: Trust.TrustedSessionPubkey; }; }; SetTrustedRootPubkey: { type: ActionType.SET_TRUSTED_ROOT_PUBKEY; payload: { id: string; trusted: Trust.TrustedRootPubkey; }; }; ProcessRootPubkeyReplacements: { type: ActionType.PROCESS_ROOT_PUBKEY_REPLACEMENTS; payload: { commitTrusted?: true }; }; ClearTrustedSessionPubkey: { type: ActionType.CLEAR_TRUSTED_SESSION_PUBKEY; payload: { id: string }; }; VerifiedSignedTrustedRootPubkey: { type: ActionType.VERIFIED_SIGNED_TRUSTED_ROOT_PUBKEY; payload: Required<State>["trustedRoot"]; }; ProcessRevocationRequests: { type: ActionType.PROCESS_REVOCATION_REQUESTS; }; CreateApp: { type: ActionType.CREATE_APP; payload: Api.Net.ApiParamTypes["CreateApp"] & { path?: string; }; }; CreateEntryRow: { type: ActionType.CREATE_ENTRY_ROW; payload: { envParentId: string; entryKey: string; vals: { [environmentId: string]: Env.EnvWithMetaCell }; }; }; UpdateEntryRow: { type: ActionType.UPDATE_ENTRY_ROW; payload: { envParentId: string; entryKey: string; newEntryKey: string; }; }; RemoveEntryRow: { type: ActionType.REMOVE_ENTRY_ROW; payload: { envParentId: string; entryKey: string; }; }; CommitEnvs: { type: ActionType.COMMIT_ENVS; payload: { pendingEnvironmentIds?: string[]; message?: string; autoCommit?: true; }; }; ResetEnvs: { type: ActionType.RESET_ENVS; payload: { pendingEnvironmentIds?: string[]; entryKeys?: string[]; }; }; ReencryptPermittedLoop: { type: ActionType.REENCRYPT_PERMITTED_LOOP; }; ReencryptEnvs: { type: ActionType.REENCRYPT_ENVS; payload: { environmentIds: string[]; }; }; FetchEnvs: { type: ActionType.FETCH_ENVS; payload: Api.Net.ApiParamTypes["FetchEnvs"] & { skipWaitForReencryption?: true; }; }; ExportEnvironment: { type: ActionType.EXPORT_ENVIRONMENT; payload: { envParentId: string; environmentId: string; format: Format; filePath: string; includeAncestors?: true; pending?: true; }; }; AddPendingInvite: { type: ActionType.ADD_PENDING_INVITE; payload: Client.PendingInvite; }; UpdatePendingInvite: { type: ActionType.UPDATE_PENDING_INVITE; payload: { index: number; pending: Client.PendingInvite }; }; RemovePendingInvite: { type: ActionType.REMOVE_PENDING_INVITE; payload: number; }; InviteUsers: { type: ActionType.INVITE_USERS; payload: Client.PendingInvite[]; }; ClearGeneratedInvites: { type: ActionType.CLEAR_GENERATED_INVITES; }; LoadInvite: { type: ActionType.LOAD_INVITE; payload: { emailToken: string; encryptionToken: string; }; }; AcceptInvite: { type: ActionType.ACCEPT_INVITE; payload: { deviceName: string; emailToken: string; encryptionToken: string; }; }; ResetInvite: { type: ActionType.RESET_INVITE; }; ApproveDevices: { type: ActionType.APPROVE_DEVICES; payload: Pick<Api.Net.ApiParamTypes["CreateDeviceGrant"], "granteeId">[]; }; ClearGeneratedDeviceGrants: { type: ActionType.CLEAR_GENERATED_DEVICE_GRANTS; }; LoadDeviceGrant: { type: ActionType.LOAD_DEVICE_GRANT; payload: { emailToken: string; encryptionToken: string; }; }; AcceptDeviceGrant: { type: ActionType.ACCEPT_DEVICE_GRANT; payload: { emailToken: string; encryptionToken: string; deviceName: string; }; }; ResetDeviceGrant: { type: ActionType.RESET_DEVICE_GRANT; }; ResetExternalAuth: { type: ActionType.RESET_EXTERNAL_AUTH; }; CreateCliUser: { type: ActionType.CREATE_CLI_USER; payload: Pick< Api.Net.ApiParamTypes["CreateCliUser"], "name" | "orgRoleId" | "appUserGrants" >; }; ClearGeneratedCliUsers: { type: ActionType.CLEAR_GENERATED_CLI_USERS; }; CreateServer: { type: ActionType.CREATE_SERVER; payload: Pick< Api.Net.ApiParamTypes["CreateServer"], "appId" | "name" | "environmentId" >; }; CreateLocalKey: { type: ActionType.CREATE_LOCAL_KEY; payload: Pick< Api.Net.ApiParamTypes["CreateLocalKey"], "appId" | "name" | "environmentId" | "autoGenerated" >; }; GenerateKey: { type: ActionType.GENERATE_KEY; payload: Pick< Api.Net.ApiParamTypes["GenerateKey"], "appId" | "keyableParentId" | "keyableParentType" >; }; ClearGeneratedEnvkey: { type: ActionType.CLEAR_GENERATED_ENVKEY; payload: { keyableParentId: string }; }; ClearAllGeneratedEnvkeys: { type: ActionType.CLEAR_ALL_GENERATED_ENVKEYS; }; ConnectBlocks: { type: ActionType.CONNECT_BLOCKS; payload: ( | Pick< Api.Net.ApiParamTypes["ConnectBlock"], "appId" | "blockId" | "orderIndex" > | Pick< Api.Net.ApiParamTypes["CreateAppBlockGroup"], "appId" | "blockGroupId" | "orderIndex" > | Pick< Api.Net.ApiParamTypes["CreateAppGroupBlock"], "appGroupId" | "blockId" | "orderIndex" > | Pick< Api.Net.ApiParamTypes["CreateAppGroupBlockGroup"], "appGroupId" | "blockGroupId" | "orderIndex" > )[]; }; GrantAppsAccess: { type: ActionType.GRANT_APPS_ACCESS; payload: ( | Pick< Api.Net.ApiParamTypes["GrantAppAccess"], "appId" | "userId" | "appRoleId" > | Pick< Api.Net.ApiParamTypes["CreateAppUserGroup"], "appId" | "userGroupId" | "appRoleId" > | Pick< Api.Net.ApiParamTypes["CreateAppGroupUser"], "appGroupId" | "userId" | "appRoleId" > | Pick< Api.Net.ApiParamTypes["CreateAppGroupUserGroup"], "appGroupId" | "userGroupId" | "appRoleId" > )[]; }; CreateGroupMemberships: { type: ActionType.CREATE_GROUP_MEMBERSHIPS; payload: { groupId: string; objectId: string; orderIndex?: number; }[]; }; CreateRecoveryKey: { type: ActionType.CREATE_RECOVERY_KEY; }; ClearGeneratedRecoveryKey: { type: ActionType.CLEAR_GENERATED_RECOVERY_KEY; }; LoadRecoveryKey: { type: ActionType.LOAD_RECOVERY_KEY; payload: { encryptionKey: string; hostUrl: string; emailToken?: string; }; }; RedeemRecoveryKey: { type: ActionType.REDEEM_RECOVERY_KEY; payload: { deviceName: string; encryptionKey: string; hostUrl: string; emailToken: string; }; }; ResetRecoveryKey: { type: ActionType.RESET_RECOVERY_KEY; }; UpdateUserRoles: { type: ActionType.UPDATE_USER_ROLES; payload: Pick< Api.Net.ApiParamTypes["UpdateUserRole"], "id" | "orgRoleId" >[]; }; RbacUpdateOrgRole: { type: ActionType.RBAC_UPDATE_ORG_ROLE; payload: Omit< Api.Net.ApiParamTypes["RbacUpdateOrgRole"], "envs" | "encryptedByTrustChain" >; }; RbacUpdateAppRole: { type: ActionType.RBAC_UPDATE_APP_ROLE; payload: Omit< Api.Net.ApiParamTypes["RbacUpdateAppRole"], "envs" | "encryptedByTrustChain" >; }; RbacUpdateEnvironmentRole: { type: ActionType.RBAC_UPDATE_ENVIRONMENT_ROLE; payload: Omit< Api.Net.ApiParamTypes["RbacUpdateEnvironmentRole"], "envs" | "encryptedByTrustChain" >; }; IncludeAppRoles: { type: ActionType.INCLUDE_APP_ROLES; payload: Omit< Api.Net.ApiParamTypes["RbacCreateIncludedAppRole"], "envs" | "encryptedByTrustChain" >[]; }; ClearLogs: { type: ActionType.CLEAR_LOGS; }; InitDevice: { type: ActionType.INIT_DEVICE; }; DisconnectClient: { type: ActionType.DISCONNECT_CLIENT; }; ResetClientState: { type: ActionType.RESET_CLIENT_STATE; }; SetDevicePassphrase: { type: ActionType.SET_DEVICE_PASSPHRASE; payload: { passphrase: string; }; }; ClearDevicePassphrase: { type: ActionType.CLEAR_DEVICE_PASSPHRASE; }; SetDefaultDeviceName: { type: ActionType.SET_DEFAULT_DEVICE_NAME; payload: { name: string; }; }; SetDeviceLockout: { type: ActionType.SET_DEVICE_LOCKOUT; payload: { lockoutMs: number; }; }; ClearDeviceLockout: { type: ActionType.CLEAR_DEVICE_LOCKOUT; }; LockDevice: { type: ActionType.LOCK_DEVICE; }; UnlockDevice: { type: ActionType.UNLOCK_DEVICE; payload: { passphrase: string; }; }; ResetEmailVerification: { type: ActionType.RESET_EMAIL_VERIFICATION; }; MergePersisted: { type: ActionType.MERGE_PERSISTED; payload: Client.PersistedProcState; }; FetchedClientState: { type: ActionType.FETCHED_CLIENT_STATE; }; ReceivedOrgSocketMessage: { type: ActionType.RECEIVED_ORG_SOCKET_MESSAGE; payload: { message: Api.OrgSocketUpdateMessage; account: Client.ClientUserAuth; }; }; OpenUrl: { type: ActionType.OPEN_URL; payload: { url: string }; }; SignInPendingSelfHosted: { type: ActionType.SIGN_IN_PENDING_SELF_HOSTED; payload: { index: number; initToken: string }; }; DeploySelfHosted: { type: ActionType.DEPLOY_SELF_HOSTED; payload: Infra.DeploySelfHostedParams & Omit< Client.PendingSelfHostedDeployment, | "type" | "addedAt" | "hostUrl" | "subdomain" | "deploymentTag" | "codebuildLink" >; }; SetDeploySelfHostedStatus: { type: ActionType.SET_DEPLOY_SELF_HOSTED_STATUS; payload: { status: string }; }; NetworkUnreachable: { type: ActionType.NETWORK_UNREACHABLE; }; NetworkReachable: { type: ActionType.NETWORK_REACHABLE; }; CheckSelfHostedUpgradesAvailable: { type: ActionType.CHECK_SELF_HOSTED_UPGRADES_AVAILABLE; payload: { lowestCurrentApiVersion: string; lowestCurrentInfraVersion: string; }; }; ClearPendingSelfHostedDeployment: { type: ActionType.CLEAR_PENDING_SELF_HOSTED_DEPLOYMENT; payload: { deploymentTag: string }; }; SkipUpgradeForNow: { type: ActionType.SKIP_SELF_HOSTED_UPGRADE_FOR_NOW; }; SetUiLastSelectedAccountId: { type: ActionType.SET_UI_LAST_SELECTED_ACCOUNT_ID; payload: { selectedAccountId: string | undefined }; }; SetUiLastSelectedUrl: { type: ActionType.SET_UI_LAST_SELECTED_URL; payload: { url: string | undefined }; }; ClearPendingExternalAuthSession: { type: ActionType.CLEAR_PENDING_EXTERNAL_AUTH_SESSION; }; SetExternalAuthSessionResult: { type: ActionType.SET_EXTERNAL_AUTH_SESSION_RESULT; payload: | { authorizingExternallyErrorMessage: string } | { externalAuthSessionId: string; externalAuthProviderId: string; orgId: string; userId: string; authType: "sign_in"; }; }; SetInviteExternalAuthSessionResult: { type: ActionType.SET_INVITE_EXTERNAL_AUTH_SESSION_RESULT; payload: | { authorizingExternallyErrorMessage: string } | { externalAuthSessionId: string; externalAuthProviderId: string; orgId: string; authType: "accept_invite" | "accept_device_grant"; userId: string; sentById: string; }; }; WaitForExternalAuth: { type: ActionType.WAIT_FOR_EXTERNAL_AUTH; payload: { externalAuthProviderId: string; externalAuthSessionId: string; authType: "sign_in"; // TODO: extend invites to oauth authMethod: "saml"; provider: "saml"; }; }; WaitForInviteExternalAuth: { type: ActionType.WAIT_FOR_INVITE_EXTERNAL_AUTH; payload: Client.ExternalAuthSetupPayload & { externalAuthSessionId: string; }; }; CreateExternalAuthSessionForLogin: { type: ActionType.CREATE_EXTERNAL_AUTH_SESSION_FOR_LOGIN; payload: { // how long to wait before triggering a web browser to open the auth url. allows injecting UI messages. waitBeforeOpenMillis: number; // TODO: extend invites to oauth authMethod: "saml"; provider: "saml"; externalAuthProviderId: string; orgId: string; userId: string; }; }; CreateExternalAuthSessionForInvite: { type: ActionType.CREATE_EXTERNAL_AUTH_SESSION_FOR_INVITE; payload: Client.ExternalAuthSetupPayload & { // TODO: extend invites to oauth authMethod: "saml"; provider: "saml"; // invite or device grant ID authObjectId: string; }; }; ClearCached: { type: ActionType.CLEAR_CACHED; }; AccountActive: { type: ActionType.ACCOUNT_ACTIVE; }; ImportOrg: { type: ActionType.IMPORT_ORG; payload: { filePath: string; encryptionKey: string; importOrgUsers: boolean; }; }; SetImportOrgStatus: { type: ActionType.SET_IMPORT_ORG_STATUS; payload: { status: string }; }; ExportOrg: { type: ActionType.EXPORT_ORG; payload: { filePath: string }; }; ClearThrottleError: { type: ActionType.CLEAR_THROTTLE_ERROR; }; ClearOrphanedBlobs: { type: ActionType.CLEAR_ORPHANED_BLOBS; }; }; export type EnvUpdateAction = EnvUpdateActions[keyof EnvUpdateActions]; export type ClientAction = ClientActions[keyof ClientActions]; }
the_stack
import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, Renderer2, SimpleChanges, Type } from '@angular/core'; import { GtConfig, GtConfigField, GtConfigSetting, GtEvent, GtExpandedRow, GtInformation, GtOptions, GtRenderField, GtRow, GtRowMeta, GtTexts } from '..'; import { GtMetaPipe } from '../pipes/gt-meta.pipe'; @Component({ selector: 'generic-table', templateUrl: './generic-table.component.html' }) export class GenericTableComponent<R extends GtRow, C extends GtExpandedRow<R>> implements OnInit, OnChanges, OnDestroy { get gtRowComponent(): Type<C> { return this._gtRowComponent; } get hasEdits(): boolean { return Object.keys(this.editedRows).length > 0; } get gtOptions(): GtOptions { return this._gtOptions; } get gtTotals(): any { return this._gtTotals; } get gtFields(): GtConfigField<R, any>[] { return this._gtFields; } get gtSettings(): GtConfigSetting[] { return this._gtSettings; } get gtData(): Array<any> { return this._gtData; } @Input() set gtOptions(value: GtOptions) { this._gtOptions = value; // if number of rows is passed and if number of rows differs from current record length... if ( this.gtOptions.numberOfRows && this.gtInfo.recordLength !== this.gtOptions.numberOfRows ) { // ...update record length and redraw table this.gtInfo.recordLength = this.gtOptions.numberOfRows; this.redraw(); } // ...extend gtOptions default values with values passed into component this._gtOptions = <GtOptions>this.extend( this.gtDefaultOptions, this._gtOptions ); } @Input() set gtTotals(value: any) { this._gtTotals = value; } @Input() set gtFields(value: GtConfigField<R, any>[]) { this._gtFields = value; const COLUMNS_WITH_CLASS_NAMES = this._gtFields .map(column => column) .filter(column => column.classNames); // TODO: remove deprecated warning when setting has been removed if (COLUMNS_WITH_CLASS_NAMES.length > 0) { console.warn( 'Field setting "classNames" have been deprecated in favor for "columnClass" and will be removed in the future, please update field settings for column with object key: ' + COLUMNS_WITH_CLASS_NAMES[0].objectKey ); } } @Input() set gtSettings(value: GtConfigSetting[]) { this._gtSettings = value; // loop through current settings for (let i = 0; i < this._gtSettings.length; i++) { // set sort enabled/disabled setting this._gtSettings[i].sortEnabled = this._gtSettings[i].sortEnabled !== false ? (this._gtSettings[i].sortEnabled = !( this._gtSettings[i].sort && this._gtSettings[i].sort.indexOf('disable') !== -1 )) : false; // check if sorting is undefined... if (typeof this._gtSettings[i].sort === 'undefined') { // ...is so, set sorting property to enable this._gtSettings[i].sort = 'enable'; } // check if column order is undefined... if ( typeof this._gtSettings[i].columnOrder === 'undefined' && this._gtSettings[i].enabled !== false ) { // ...is so, set sorting property to enable this._gtSettings[i].columnOrder = this._gtSettings[i - 1] ? this._gtSettings[i - 1].columnOrder + 1 : 0; } // check if column lock settings are undefined... if (typeof this._gtSettings[i].lockSettings === 'undefined') { // ...if so, set lock settings to false unless field is disabled (enable === false) this._gtSettings[i].lockSettings = this._gtSettings[i].enabled === false || false; } } this.restructureSorting(); } @Input() set gtData(initialData: Array<any>) { const data = this._gtOptions.mutateData ? [...initialData] : this.cloneDeep(initialData); if (this.gtOptions.lazyLoad && this.gtInfo) { this.gtMetaPipe.transform( data, this.gtOptions.rowIndex, this.gtInfo.pageCurrent - 1, this.gtInfo.recordLength ); if (this.lazyAllSelected) { const UNIQUE_ROWS = this.selectedRows.map(row => row.$$gtRowId); data.map(row => { if (UNIQUE_ROWS.indexOf(row.$$gtRowId) === -1) { this.selectedRows.push(row); } }); this._updateMetaInfo(this.selectedRows, 'isSelected', true); } } else { this.gtMetaPipe.transform(data, this.gtOptions.rowIndex); } if (this.gtOptions.rowSelectionInitialState) { data.map(row => { const selected = typeof this.gtOptions.rowSelectionInitialState === 'function' ? this.gtOptions.rowSelectionInitialState(row) : this.gtOptions.rowSelectionInitialState; if (selected) { if (typeof this.metaInfo[row.$$gtRowId] === 'undefined') { this.metaInfo[row.$$gtRowId] = { isSelected: true }; } else { this.metaInfo[row.$$gtRowId].isSelected = true; } this.selectedRows.push(row); } }); } if ( this.gtOptions.rowExpandInitialState && this.gtOptions.rowExpandInitialComponent ) { data.map(row => { const expanded = typeof this.gtOptions.rowExpandInitialState === 'function' ? this.gtOptions.rowExpandInitialState(row) : this.gtOptions.rowExpandInitialState; this.expandedRow = this.gtOptions.rowExpandInitialComponent; if (expanded) { if (typeof this.metaInfo[row.$$gtRowId] === 'undefined') { this.metaInfo[row.$$gtRowId] = { isOpen: true }; } else { this.metaInfo[row.$$gtRowId].isOpen = true; } } }); } this._gtData = data; } @Input() set gtRowComponent(value: Type<C>) { console.warn( 'GtRowComponent has been deprecated and support will be removed in a future release, see https://github.com/hjalmers/angular-generic-table/issues/34' ); this._gtRowComponent = value; } public columnWidth: Object = {}; public configObject: GtConfig<R>; public sortOrder: Array<any> = []; public metaInfo: { [gtRowId: string]: GtRowMeta } = {}; public selectedRows: Array<GtRow> = []; public openRows: Array<GtRow> = []; private _gtSettings: GtConfigSetting[] = []; private _gtFields: GtConfigField<R, any>[] = []; private _gtData: Array<any>; private _gtTotals: any; private _gtRowComponent: Type<C>; public expandedRow: { component: Type<C>; data?: Array<any>; }; public gtDefaultTexts: GtTexts = { loading: 'Loading...', noData: 'No data', noMatchingData: 'No data matching results found', noVisibleColumnsHeading: 'No visible columns', noVisibleColumns: 'Please select at least one column to be visible.', tableInfo: 'Showing #recordFrom to #recordTo of #recordsAfterSearch entries.', tableInfoAfterSearch: 'Showing #recordFrom to #recordTo of #recordsAfterSearch entries (filtered from a total of #recordsAll entries).', csvDownload: 'download', sortLabel: 'Sort:', paginateNext: 'Next page', paginatePrevious: 'Previous page', inlineEditEdited: 'Press enter to save' }; @Input() gtTexts: GtTexts = this.gtDefaultTexts; @Input() gtClasses: string; @Output() gtEvent: EventEmitter<GtEvent> = new EventEmitter(); public gtDefaultOptions: GtOptions = { csvDelimiter: ';', stack: false, lazyLoad: false, cache: false, debounceTime: 200, highlightSearch: false, rowSelection: false, rowSelectionAllowMultiple: true, rowExpandAllowMultiple: true, numberOfRows: 10, reportColumnWidth: false, allowUnsorted: true, mutateData: true }; private _gtOptions: GtOptions = this.gtDefaultOptions; public store: Array<any> = []; public loading = true; private debounceTimer: void = null; public loadingProperty: string; public lazyAllSelected = false; @Input() gtInfo: GtInformation = { pageCurrent: 1, pageTotal: 0, recordFrom: 0, recordTo: 0, recordLength: this.gtOptions.numberOfRows, recordsAll: 0, recordsAfterFilter: 0, recordsAfterSearch: 0 }; public refreshPipe = false; public refreshTotals = false; public refreshSorting = false; public refreshFilter = false; public refreshPageArray = false; private globalInlineEditListener: Function; public editedRows: { [key: string]: { changes: { [key: string]: GtRenderField<GtRow, any> }; row: GtRow; }; } = {}; public data: { exportData: Array<any> } = { exportData: [] }; // Store filtered data for export constructor(private renderer: Renderer2, private gtMetaPipe: GtMetaPipe) { this.gtEvent.subscribe(($event: GtEvent) => { if ($event.name === 'gt-info') { this.updateRecordRange(); } if ($event.name === 'gt-row-updated') { this.updateTotals(); } }); } /** * Sort table by object key. * @param objectKey - name of key to sort on. * @param event - such as key press during sorting. */ public gtSort = function(objectKey: string, event: any) { this.inlineEditCancel(); // cancel inline editing // loop through current settings for (let i = 0; i < this._gtSettings.length; i++) { if (this._gtSettings[i].objectKey === objectKey) { // check if sorting is disabled... if ( this._gtSettings[i].sort && this._gtSettings[i].sort.indexOf('disable') !== -1 ) { // ...if so, exit function without applying any sorting return; } else if ( /* check if sorting is undefined... */ typeof this._gtSettings[i] .sort === 'undefined' ) { // ...is so, set sorting property to enable this._gtSettings[i].sort = 'enable'; } } } // check length const ctrlKey = event.metaKey || event.ctrlKey; const sort = this.sortOrder.slice(0); let match = -1; let matchDesc = -1; let pos = -1; // check if property already exits for (let i = 0; i < sort.length; i++) { const hit = sort[i].indexOf(objectKey); if (hit !== -1) { match = this.sortOrder.indexOf(objectKey); matchDesc = match === -1 ? this.sortOrder.indexOf('-' + objectKey) : match; pos = Math.max(match, matchDesc); } } // if ctrl key or meta key is press together with sort... if (ctrlKey) { if (this.sortOrder[this.sortOrder.length - 1] === '$$gtInitialRowIndex') { this.sortOrder.pop(); } switch (pos) { // ...and property is not sorted before... case -1: // ...add property to sorting this.sortOrder.push(objectKey); break; default: // ...and property is sorted before... if (match !== -1) { // ...change from asc to desc if sorted asc this.sortOrder[pos] = '-' + objectKey; } else if (this.sortOrder.length > 1) { // ...remove sorting if sorted desc if (ctrlKey) { this.sortOrder[pos] = objectKey; } else { this.sortOrder.splice(pos, 1); } } else if (this.sortOrder.length === 1) { // ...set sorting to asc if only sorted property this.sortOrder[pos] = objectKey; } break; } } else { /* if ctrl key or meta key is not press together with sort... */ switch (pos) { // ...and property is not sorted before... case -1: // ...sort by property this.sortOrder = [objectKey]; break; default: // ...change from desc to asc and vise versa this.sortOrder = match !== -1 ? ['-' + objectKey] : ctrlKey || !this.gtOptions.allowUnsorted ? [objectKey] : []; break; } } // update settings object with new sorting information for (let i = 0; i < this._gtSettings.length; i++) { if (this._gtSettings[i].objectKey === objectKey) { switch (this._gtSettings[i].sort) { // if sorted asc... case 'asc': // ...change to desc this._gtSettings[i].sort = 'desc'; break; // if sorted desc... case 'desc': // ...change to asc if it's the only sorted property otherwise remove sorting this._gtSettings[i].sort = (this.sortOrder.length === 1 && sort.length < 2) || ctrlKey || !this.gtOptions.allowUnsorted ? 'asc' : 'enable'; break; // if sorting enabled... case 'enable': // ...change to asc this._gtSettings[i].sort = 'asc'; break; } this._gtSettings[i].sortOrder = this._gtSettings[i].sort === 'enable' ? this._gtSettings.length - 1 : this.sortOrder.indexOf(objectKey) === -1 ? this.sortOrder.indexOf('-' + objectKey) : this.sortOrder.indexOf(objectKey); } else if ( this._gtSettings[i].sort && this._gtSettings[i].sort.indexOf('disable') === -1 && this.sortOrder.indexOf(this._gtSettings[i].objectKey) === -1 && this.sortOrder.indexOf('-' + this._gtSettings[i].objectKey) === -1 ) { this._gtSettings[i].sort = 'enable'; this._gtSettings[i].sortOrder = this._gtSettings.length - 1; } } // refresh sorting pipe this.refreshSorting = !this.refreshSorting; this.refreshPageArray = !this.refreshPageArray; // sort by initial sort order as last resort this.sortOrder.push('$$gtInitialRowIndex'); // emit sort event this.gtEvent.emit({ name: 'gt-sorting-applied', value: this.sortOrder }); }; /** * Change number of rows to be displayed. * @param rowLength - total number of rows. * @param reset - should page be reset to first page. */ public changeRowLength = function(rowLength: any, reset?: boolean) { let lengthValue = isNaN(parseInt(rowLength, 10)) ? 0 : parseInt(rowLength, 10); let newPosition = 1; if (!lengthValue && this.gtData) { lengthValue = this.gtData.length; } // if reset is not true and we're not lazy loading data... if (reset !== true && this._gtOptions.lazyLoad !== true) { // ...get current position in record set const currentRecord = this.gtInfo.recordLength * (this.gtInfo.pageCurrent - 1); const currentPosition = this._gtData.indexOf(this._gtData[currentRecord]) + 1; // ...get new position newPosition = Math.ceil(currentPosition / lengthValue); } // change row length this.gtInfo.recordLength = lengthValue; // go to new position this.gtInfo.pageCurrent = newPosition; // if lazy loading data... if (this._gtOptions.lazyLoad) { // ...replace data with place holders for new data this._gtData[0] = this.loadingContent(lengthValue); // ...empty current store this.store = []; } // this.updateRecordRange(); this.gtEvent.emit({ name: 'gt-row-length-changed', value: lengthValue }); }; /** * Force a redraw of table rows. * As the table uses pure pipes, we need to force a redraw if an object in the array is changed to see the changes. */ public redraw = function($event?: any) { this.refreshSorting = !this.refreshSorting; this.refreshPageArray = !this.refreshPageArray; this.refreshPipe = !this.refreshPipe; }; /** Update record range. */ private updateRecordRange() { this.gtInfo.recordFrom = this.gtInfo.recordsAfterSearch === 0 ? 0 : (this.gtInfo.pageCurrent - 1) * this.gtInfo.recordLength + 1; this.gtInfo.recordTo = this.gtInfo.recordsAfterSearch < this.gtInfo.pageCurrent * this.gtInfo.recordLength ? this.gtInfo.recordsAfterSearch : this.gtInfo.pageCurrent * this.gtInfo.recordLength; } /** Update totals. */ private updateTotals() { this.refreshTotals = !this.refreshTotals; } /** Go to next page. */ public nextPage = function() { const page = this.gtInfo.pageCurrent === this.gtInfo.pageTotal ? this.gtInfo.pageTotal : this.gtInfo.pageCurrent + 1; this.goToPage(page); }; /** Go to previous page. */ public previousPage = function() { const page = this.gtInfo.pageCurrent === 1 ? 1 : this.gtInfo.pageCurrent - 1; this.goToPage(page); }; /** Request more data (used when lazy loading) */ private getData = function() { // ...emit event requesting for more data this.gtEvent.emit({ name: 'gt-page-changed-lazy', value: { pageCurrent: this.gtInfo.pageCurrent, recordLength: this.gtInfo.recordLength } }); }; /** * Go to specific page. * @param page - page number. */ public goToPage = function(page: number) { const previousPage = this.gtInfo.pageCurrent; this.gtInfo.pageCurrent = page; this.inlineEditCancel(); // cancel inline edit // if lazy loading and if page contains no records... if (this._gtOptions.lazyLoad) { // ...if data for current page contains no entries... if ( this._gtOptions.cache === false || this._gtData[this.gtInfo.pageCurrent - 1].length === 0 ) { // ...create temporary content while waiting for data this._gtData[this.gtInfo.pageCurrent - 1] = this.loadingContent( this.gtInfo.recordLength ); this.loading = true; // loading true } // ...if first entry in current page equals our loading placeholder... if ( this._gtData[this.gtInfo.pageCurrent - 1][0][this.loadingProperty] === this.gtTexts.loading ) { // ...get data clearTimeout(this.debounceTimer); this.debounceTimer = setTimeout(() => { this.getData(); }, this._gtOptions.debounceTime); } } // this.updateRecordRange(); // ...emit page change event if (previousPage !== page) { this.gtEvent.emit({ name: 'gt-page-changed', value: { pageCurrent: this.gtInfo.pageCurrent, pagePrevious: previousPage, recordLength: this.gtInfo.recordLength } }); } }; /** * Get meta data for row. */ public getRowState(row: R): GtRowMeta { return typeof this.metaInfo[row.$$gtRowId] === 'undefined' ? null : this.metaInfo[row.$$gtRowId]; } /** * Expand all rows. * @param expandedRow - component to render when rows are expanded. */ public expandAllRows(expandedRow: { component: Type<C>; data?: any }): void { this.expandedRow = expandedRow; this._toggleAllRowProperty('isOpen', true); } /** * Collapse all rows. */ public collapseAllRows(): void { this._toggleAllRowProperty('isOpen', false); } /** * Select all rows. */ public selectAllRows(): void { this._toggleAllRowProperty('isSelected', true); } /** * Deselect all rows. */ public deselectAllRows(): void { this._toggleAllRowProperty('isSelected', false); } /** * Toggle all rows. */ public toggleAllRows(): void { if (this._gtOptions.lazyLoad) { if (!this.lazyAllSelected || this.selectedRows.length === 0) { this.selectAllRows(); this.lazyAllSelected = true; } else { this.deselectAllRows(); this.lazyAllSelected = false; } } else { if (this.selectedRows.length !== this.gtData.length) { this.selectAllRows(); } else { this.deselectAllRows(); } } } /** * Toggle row collapsed state ie. expanded/open or collapsed/closed. * @param row - row object that should be expanded/collapsed. * @param expandedRow - component to render when row is expanded. */ public toggleCollapse( row: GtRow, expandedRow?: { component: Type<C>; data?: any } ) { if (expandedRow) { this.expandedRow = expandedRow; } this._toggleRowProperty(row, 'isOpen'); } /** * Toggle row selected state ie. selected or not. * @param row - row object that should be selected/deselected. */ public toggleSelect(row: GtRow) { this._toggleRowProperty(row, 'isSelected'); } public rowClick(row: GtRow, $event: MouseEvent) { this.gtEvent.emit({ name: 'gt-row-clicked', value: { row: row, event: $event } }); } /** * Update row data. * @param row - row object that has been edited. * @param oldValue - row object before edit. */ public updateRow(row: GtRow, oldValue: GtRow) { this._toggleRowProperty(row, 'isUpdated', oldValue); } /** * removes a row from the table * @param row - the row object to remove */ public removeRow(row: GtRow) { if (this.isRowSelected(row)) { this.toggleSelect(row); } const index = this._gtData.indexOf(row); this._gtData.splice(index, 1); } /** * check if a row is selected * @param row - row object */ public isRowSelected(row: GtRow): boolean { return ( this.metaInfo[row.$$gtRowId] && this.metaInfo[row.$$gtRowId].isSelected ); } /** * Update meta info for all rows, ie. isSelected, isOpen. * @param array - array that holds rows that need to be updated. * @param property - name of property that should be changed/toggled. * @param active - should rows be expanded/open, selected. * @param exception - update all rows except this one. */ private _updateMetaInfo( array: Array<GtRow>, property: string, active: boolean, exception?: GtRow ) { for (let i = 0; i < array.length; i++) { if (!this.metaInfo[array[i].$$gtRowId]) { this.metaInfo[array[i].$$gtRowId] = {}; } if (exception && array[i].$$gtRowId === exception.$$gtRowId) { } else { this.metaInfo[array[i].$$gtRowId][property] = active; } } } /** * Push selected/expanded lazy loaded rows to array with meta data. * @param target - array to which rows should be added. * @param source - array that holds rows that should be added. * @returns array with added rows. */ private _pushLazyRows( target: Array<GtRow>, source: Array<GtRow> ): Array<GtRow> { const UNIQUE_ROWS = target.map(row => row.$$gtRowId); for (let i = 0; i < source.length; i++) { // only add if not already in list if (UNIQUE_ROWS.indexOf(source[i].$$gtRowId) === -1) { target.push(source[i]); } } return target; } /** * Toggle meta info for all rows, ie. isSelected, isOpen. * @param property - name of property that should be changed/toggled. * @param active - should rows be expanded/open, selected. */ private _toggleAllRowProperty(property: string, active: boolean) { let eventName: string; let eventValue: any; switch (property) { case 'isOpen': // check if multiple expanded rows are allowed... if (this._gtOptions.rowExpandAllowMultiple === false) { // ...if not, exit function console.log( 'feature disabled: enable by setting "rowExpandAllowMultiple = true"' ); return; } if (active) { eventName = 'expand-all'; this.openRows = this._gtOptions.lazyLoad ? this._pushLazyRows( this.openRows, this._gtData[this.gtInfo.pageCurrent - 1].slice() ) : this._gtData.slice(); this._updateMetaInfo(this.openRows, property, active); } else { eventName = 'collapse-all'; this._updateMetaInfo(this.openRows, property, active); this.openRows = []; } eventValue = { expandedRows: this.openRows, changedRow: 'all' }; break; case 'isSelected': // check if multi row selection is allowed... if (this._gtOptions.rowSelectionAllowMultiple === false) { // ...if not, exit function console.log( 'feature disabled: enable by setting "rowSelectionAllowMultiple = true"' ); return; } if (active) { eventName = 'select-all'; this.selectedRows = this._gtOptions.lazyLoad ? this._pushLazyRows( this.selectedRows, this._gtData[this.gtInfo.pageCurrent - 1].slice() ) : this._gtData.slice(); this._updateMetaInfo(this.selectedRows, property, active); } else { eventName = 'deselect-all'; this._updateMetaInfo(this.selectedRows, property, active); this.selectedRows = []; } eventValue = { selectedRows: this.selectedRows, changedRow: 'all' }; break; } this.gtEvent.emit({ name: 'gt-row-' + eventName, value: eventValue }); } /** * Toggle meta info for row, ie. isSelected, isOpen. * @param row - row object. * @param property - name of property that should be changed/toggled. * @param propertyValues - optional property values that can be passed. */ private _toggleRowProperty( row: GtRow, property: string, propertyValues?: any ) { let eventName: string; let eventValue: any; // make sure gtRowId exists on row object if (typeof row.$$gtRowId !== 'undefined') { // check if meta info exists for row if (!this.metaInfo[row.$$gtRowId]) { // if not, add object to store meta info this.metaInfo[row.$$gtRowId] = {}; } switch (property) { case 'isOpen': const opened = this.metaInfo[row.$$gtRowId][property]; // check if multiple expanded rows are allowed... if (this._gtOptions.rowExpandAllowMultiple === false) { // ...if not, collapse all rows except current row this._updateMetaInfo(this.openRows, property, false, row); this.openRows = []; } // check if row is expanded if (!opened) { eventName = 'expand'; // add row to expanded rows this.openRows.push(row); } else { eventName = 'collapse'; // loop through expanded rows... for (let i = 0; i < this.openRows.length; i++) { // if expanded row equals passed row... if (this.openRows[i].$$gtRowId === row.$$gtRowId) { // ...remove row from expanded rows... this.openRows.splice(i, 1); // ...and exit loop break; } } } eventValue = { expandedRows: this.openRows, changedRow: row }; break; case 'isSelected': const selected = this.metaInfo[row.$$gtRowId][property]; // check if multi row selection is allowed... if (this._gtOptions.rowSelectionAllowMultiple === false) { // ...if not, deselect all rows except current row this._updateMetaInfo(this.selectedRows, property, false, row); this.selectedRows = []; } // check if row is selected if (!selected) { eventName = 'select'; // add row to selected rows this.selectedRows.push(row); } else { if (this.gtOptions.lazyLoad && this.lazyAllSelected) { this.lazyAllSelected = false; } eventName = 'deselect'; // loop through selected rows... for (let i = 0; i < this.selectedRows.length; i++) { // if selected row equals passed row... if (this.selectedRows[i].$$gtRowId === row.$$gtRowId) { // ...remove row from selected rows... this.selectedRows.splice(i, 1); // ...and exit loop break; } } } eventValue = { selectedRows: this.selectedRows, changedRow: row }; break; case 'isUpdated': eventName = 'updated'; const oldValue = propertyValues; // check if edit object exists for row if (typeof this.metaInfo[row.$$gtRowId][property] === 'undefined') { this.metaInfo[row.$$gtRowId][property] = { originalValue: oldValue, oldValue: oldValue, newValue: row }; } else { this.metaInfo[row.$$gtRowId][property].oldValue = oldValue; this.metaInfo[row.$$gtRowId][property].newValue = row; } eventValue = this.metaInfo[row.$$gtRowId][property]; this.redraw(); this.inlineEditCancel(row); // this.gtData = [...this.gtData.map((r) => { return{...r}; })]; break; } this.gtEvent.emit({ name: 'gt-row-' + eventName, value: eventValue }); if (property !== 'isUpdated') { this.metaInfo[row.$$gtRowId][property] = !this.metaInfo[row.$$gtRowId][ property ]; } } } /** * Update column. * @param $event - key up event. * @param row - row object. * @param column - column object. */ public gtUpdateColumn( $event: KeyboardEvent, row: GtRow, column: GtRenderField<any, any> ) { this._editRow(row, column); } /** * Dropdown select. * @param row - row object. * @param column - column object. */ public gtDropdownSelect(row: GtRow, column: GtRenderField<any, any>) { const oldValue = { ...row }; row[column.objectKey] = column.renderValue; this.updateRow(row, oldValue); } private _editRow(row: GtRow, column: GtRenderField<any, any>) { const OBJECT_KEY = column.objectKey; // declare object key which contains changes // check if cell has changed value column.edited = row[column.objectKey] !== column.renderValue; // check if row contains changes... if (!this.editedRows[row.$$gtRowId]) { // if not, create an object for the changed row this.editedRows[row.$$gtRowId] = { changes: {}, // create placeholder for changes row: row // store reference to the row that should be updated }; } // store changed column under changes if it has been edited if (column.edited) { this.editedRows[row.$$gtRowId].changes[OBJECT_KEY] = column; } else { // delete change object if column is unchanged delete this.editedRows[row.$$gtRowId].changes[OBJECT_KEY]; // check how many columns have been changed const CHANGED_COLUMNS = Object.keys( this.editedRows[row.$$gtRowId].changes ).length; if (CHANGED_COLUMNS === 0) { // delete row from edited rows if no columns have been edited delete this.editedRows[row.$$gtRowId]; } } // if no listener is present... if (!this.globalInlineEditListener) { // ...listen for update event this._listenForKeydownEvent(); } } /** * Listen for key down event - listen for key down event during inline edit. */ private _listenForKeydownEvent() { // add global listener for key down events this.globalInlineEditListener = this.renderer.listen( 'document', 'keydown', $event => { switch ($event.key) { case 'Enter': // update data object this.inlineEditUpdate(); break; case 'Escape': // cancel this.inlineEditCancel(); break; } } ); } /** * Inline edit update - accept changes and update row values. */ public inlineEditUpdate() { // loop through rows that have been edited Object.keys(this.editedRows).map(key => { const ROW = this.editedRows[key].row; // row to update const CHANGES = this.editedRows[key].changes; // changes to the row // loop through changes in row Object.keys(CHANGES).map(objectKey => { const oldValue = { ...ROW }; ROW[objectKey] = CHANGES[objectKey].renderValue; // update data value this.updateRow(ROW, oldValue); // update meta info for row and send event CHANGES[objectKey].edited = false; // disable edit mode }); }); // clear rows marked as edited as the rows have been updated this.editedRows = {}; // remove listener this._stopListeningForKeydownEvent(); } /** * Inline edit cancel - cancel and reset inline edits. */ public inlineEditCancel(row?: GtRow) { if (row) { delete this.editedRows[row.$$gtRowId]; // remove listener this._stopListeningForKeydownEvent(); return; } // loop through rows that have been edited Object.keys(this.editedRows).map(key => { const ROW = this.editedRows[key].row; // row to update const CHANGES = this.editedRows[key].changes; // changes to the row // loop through changes in row Object.keys(CHANGES).map(objectKey => { CHANGES[objectKey].renderValue = ROW[objectKey]; // reset rendered value CHANGES[objectKey].edited = false; // disable edit mode }); }); // clear rows marked as edited as the rows have been updated this.editedRows = {}; // remove listener this._stopListeningForKeydownEvent(); } /** * Stop listening for key down event - stop listening for key down events passed during inline edit. */ private _stopListeningForKeydownEvent() { if (this.globalInlineEditListener) { this.globalInlineEditListener(); this.globalInlineEditListener = null; } } /** * Apply filter(s). * @param filter - object containing key value pairs, where value should be array of values. */ public gtApplyFilter(filter: Object) { this.gtInfo.filter = filter; // go to first page this.goToPage(1); this.updateTotals(); } /** Clear/remove applied filter(s). */ public gtClearFilter() { this.gtInfo.filter = false; this.updateTotals(); // this.updateRecordRange(); } /** * Search * @param value - string containing one or more words */ public gtSearch(value: string) { this.gtInfo.searchTerms = value; // always go to first page when searching this.goToPage(1); this.updateTotals(); } /** * Add rows * @param rows - rows to add * @returns new data array. */ public gtAdd(rows: Array<R>): ReadonlyArray<R> { this.gtData = [...this.gtData, ...rows]; return [...this.gtData]; } /** * Delete row * @param objectKey - object key you want to find match with * @param value - the value that should be deleted * @param match - all: delete all matches, first: delete first match (default) * @returns new data array. */ public gtDelete( objectKey: string, value: string | number, match: 'first' | 'all' = 'first' ): ReadonlyArray<R> { if (match === 'first') { for (let i = 0; i < this.gtData.length; i++) { if (this.gtData[i][objectKey] === value) { if (this.isRowSelected(this.gtData[i])) { this.toggleSelect(this.gtData[i]); } this.gtData.splice(i, 1); this.gtData = [...this.gtData]; if (match === 'first') { break; } } } } else { for (let i = this.gtData.length; i > 0; i--) { if (this.gtData[i - 1][objectKey] === value) { if (this.isRowSelected(this.gtData[i - 1])) { this.toggleSelect(this.gtData[i - 1]); } this.gtData.splice(i - 1, 1); this.gtData = [...this.gtData]; } } } return [...this.gtData]; } /** * Create store to hold previously loaded records. * @param records - total number of records in store. * @param perPage - how many records to show per page. * @returns a nested array to hold records per page. */ private createStore(records: number, perPage: number): Array<Array<any>> { const stores = Math.ceil(records / perPage); const store: Array<Array<any>> = []; for (let i = 0; i < stores; i++) { store[i] = []; } return store; } /** * Create placeholders for rows while loading data from back-end. * @param perPage - how many records to show per page. * @returns an array containing empty records to be presented while fetching real data. */ private loadingContent(perPage: number) { // create row object const rowObject: Object = { $$loading: true }; let order = 0; // sort settings by column order this._gtSettings.sort(this.getColumnOrder); // loop through all settings objects... for (let i = 0; i < this._gtSettings.length; i++) { const setting = this._gtSettings[i]; // ...if column is visible and enabled... if (setting.visible !== false && setting.enabled !== false) { // ...if first column, set value to loading text otherwise leave it empty if (order === 0) { rowObject[setting.objectKey] = this.gtTexts.loading; this.loadingProperty = setting.objectKey; } else { rowObject[setting.objectKey] = ''; } order++; } else { rowObject[setting.objectKey] = ''; } } // create content placeholder const contentPlaceholder: Array<any> = []; // create equal number of rows as rows per page for (let i = 0; i < perPage; i++) { // ...add temporary row object contentPlaceholder.push(rowObject); } return contentPlaceholder; } // TODO: move to helper functions /** Sort by sort order */ private getSortOrder = function(a: GtConfigSetting, b: GtConfigSetting) { if (a.sortOrder < b.sortOrder) { return -1; } if (a.sortOrder > b.sortOrder || typeof a.sortOrder === 'undefined') { return 1; } return 0; }; // TODO: move to helper functions /** Sort by column order */ private getColumnOrder = function(a: GtConfigSetting, b: GtConfigSetting) { if (a.columnOrder === undefined) { return -1; } if (a.columnOrder < b.columnOrder) { return -1; } if (a.columnOrder > b.columnOrder) { return 1; } return 0; }; // TODO: move to helper functions /** Create a deep copy of data */ private cloneDeep = function(o: any) { return JSON.parse(JSON.stringify(o)); }; /** Export data as CSV * @param fileName - optional file name (overrides default file name). * @param useBOM - use BOM (byte order marker). */ public exportCSV(fileName?: string, useBOM: boolean = false) { const data = this.data.exportData; let csv = ''; const BOM = '\uFEFF'; // csv export headers for (let i = 0; i < this._gtSettings.length; i++) { if (this._gtSettings[i].export !== false) { // get field settings const fieldSetting = this.getProperty( this._gtFields, this._gtSettings[i].objectKey ); // get export value, if exportHeader string is defined use it otherwise returns name const exportValue: string = fieldSetting.exportHeader ? fieldSetting.exportHeader : fieldSetting.name; csv += this.escapeCSVDelimiter(exportValue); csv += this.getProperty(this._gtFields, this._gtSettings[i].objectKey) .name; if (i < this._gtSettings.length - 1) { csv += this._gtOptions.csvDelimiter; } } } // csv export body data.forEach(row => { csv += '\n'; for (let i = 0; i < this._gtSettings.length; i++) { if (this._gtSettings[i].export !== false) { // get field settings const fieldSetting = this.getProperty( this._gtFields, this._gtSettings[i].objectKey ); // get export value, if export function is defined use it otherwise check for value function and as a last resort export raw data const exportValue: string = fieldSetting.export && typeof fieldSetting.export === 'function' ? fieldSetting.export(row) : fieldSetting.value && typeof fieldSetting.value === 'function' ? fieldSetting.value(row) : row[this._gtSettings[i].objectKey]; csv += this.escapeCSVDelimiter(exportValue); if (i < this._gtSettings.length - 1) { csv += this._gtOptions.csvDelimiter; } } } }); const blob = new Blob([(useBOM ? BOM : '') + csv], { type: 'text/csv;charset=utf-8' }); if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveOrOpenBlob( blob, fileName ? fileName + '.csv' : this.gtTexts.csvDownload + '.csv' ); } else { const link = document.createElement('a'); link.style.display = 'none'; document.body.appendChild(link); if (link.download !== undefined) { link.setAttribute( 'href', 'data:text/csv;charset=utf-8,' + encodeURIComponent((useBOM ? BOM : '') + csv) ); // URL.createObjectURL(blob)); link.setAttribute( 'download', fileName ? fileName + '.csv' : this.gtTexts.csvDownload + '.csv' ); document.body.appendChild(link); link.click(); } else { csv = 'data:text/csv;charset=utf-8,' + (useBOM ? BOM : '') + csv; window.open(encodeURIComponent(csv)); } document.body.removeChild(link); } // emit export event this.gtEvent.emit({ name: 'gt-exported-csv', value: fileName ? fileName : this.gtTexts.csvDownload + '.csv' }); } /** Return property */ private getProperty = function(array: Array<any>, key: string) { for (let i = 0; i < array.length; i++) { if (array[i].objectKey === key) { return array[i]; } } }; private restructureSorting = function() { /** Check and store sort order upon initialization. * This is done by checking sort properties in the settings array of the table, if no sorting is defined * we'll sort the data by the first visible and enabled column in the table(ascending). Please note that actually * sorting have to be done server side when lazy loading data for obvious reasons. */ // create sorting array const sorting = []; if (this._gtSettings) { // ...sort settings by sort order this._gtSettings.sort(this.getSortOrder); // ...loop through settings for (let i = 0; i < this._gtSettings.length; i++) { const setting = this._gtSettings[i]; // ...if sorted ascending... if (setting.sort === 'asc') { // ... add to sorting sorting.push(setting.objectKey); } else if (setting.sort === 'desc') { /* ...else if sorted descending... */ // ... add to sorting sorting.push('-' + setting.objectKey); } } // ...if no sorting applied... if (sorting.length === 0) { sorting.push('$$gtRowId'); /*// ...sort settings by column order this._gtSettings.sort(this.getColumnOrder); // ...loop through settings for (let i = 0; i < this._gtSettings.length; i++) { const setting = this._gtSettings[i]; // ...if column is enabled and visible... if (setting.enabled !== false && setting.visible !== false) { // ...add first match and exit function this.sortOrder = [this._gtSettings[i].objectKey]; return; } }*/ } } if (this.sortOrder.length === 0) { this.sortOrder = sorting; } }; /** * Escape export value using double quotes (") if export value contains delimiter * @param value Value to be escaped */ private escapeCSVDelimiter(value) { return typeof value === 'string' && value.indexOf(this._gtOptions.csvDelimiter) !== -1 ? '"' + value + '"' : value; } ngOnInit() { // if number of row to display from start is set to null or 0... if (!this.gtOptions.numberOfRows) { // ...change row length this.changeRowLength(this.gtOptions.numberOfRows); } this.restructureSorting(); } /** * Extend object function. */ private extend = function(a: Object, b: Object) { for (const key in b) { if (b.hasOwnProperty(key)) { a[key] = b[key]; } } return a; }; ngOnChanges(changes: SimpleChanges) { // if gt texts have changed... if (changes['gtTexts']) { // ...extend gtOptions default values with values passed into component this.gtTexts = <GtTexts>this.extend(this.gtDefaultTexts, this.gtTexts); } // if lazy loading data and paging information is available... if (this.gtOptions.lazyLoad && this.gtInfo) { // ...calculate total number of pages this.gtInfo.pageTotal = Math.ceil( this.gtInfo.recordsAfterSearch / this.gtInfo.recordLength ); // ...declare store position const storePosition = this.gtInfo.pageCurrent - 1; // ...and if store is empty or page length has changed... if ( this.store.length === 0 || this.store[0].length !== this.gtInfo.recordLength ) { // ...create store this.store = this.createStore( this.gtInfo.recordsAfterSearch, this.gtInfo.recordLength ); } // ...store retrieved data in store at store position this.store[storePosition] = this.gtData; this.gtInfo.visibleRecords = [...this.gtData]; // add visible rows // replace data with store this._gtData = this.store; this.loading = false; this.updateRecordRange(); this.gtEvent.emit({ name: 'gt-info', value: this.gtInfo }); } else if ( this._gtData && this._gtData.length >= 0 && changes['gtData'] && changes['gtData'].previousValue ) { this.loading = false; } else if ( changes['gtData'] && changes['gtData'].firstChange && this._gtData && this._gtData.length > 0 ) { this.loading = false; } } trackByFn(index: number, item: GtRow) { return item.$$gtRowId; } trackByColumnFn(index: number, item: GtConfigField<any, any>) { return item.objectKey; } ngOnDestroy() { // remove listener this._stopListeningForKeydownEvent(); } }
the_stack
declare function If(props: { condition: boolean | number | string } & NornJ.Childrenable): any; /** * NornJ tag `If`, example: * * `<NjIf condition={false}><input /></NjIf>` */ declare function NjIf(props: { condition: boolean | number | string } & NornJ.Childrenable): any; /** * NornJ tag `Then`, example: * * `<If condition={foo > 10}><input /><Then>100</Then><Else>200</Else></If>` */ declare function Then(props: NornJ.Childrenable): any; /** * NornJ tag `Then`, example: * * `<NjIf condition={foo > 10}><input /><NjThen>100</NjThen><NjElse>200</NjElse></NjIf>` */ declare function NjThen(props: NornJ.Childrenable): any; /** * NornJ tag `Elseif`, example: * * `<If condition={foo > 10}><input /><Elseif condition={foo > 5}><input type="button" /></Elseif></If>` */ declare function Elseif(props: { condition: boolean | number | string } & NornJ.Childrenable): any; /** * NornJ tag `Elseif`, example: * * `<NjIf condition={foo > 10}><input /><NjElseif condition={foo > 5}><input type="button" /></NjElseif></NjIf>` */ declare function NjElseif(props: { condition: boolean | number | string } & NornJ.Childrenable): any; /** * NornJ tag `Else`, example: * * `<If condition={foo > 10}><input /><Else><input type="button" /></Else></If>` */ declare function Else(props: NornJ.Childrenable): any; /** * NornJ tag `Else`, example: * * `<NjIf condition={foo > 10}><input /><NjElse><input type="button" /></NjElse></NjIf>` */ declare function NjElse(props: NornJ.Childrenable): any; /** * NornJ tag `Switch`, example: * * `<Switch value={foo}><Case value={1}><input /></Case><Case value={2}><input type="button" /></Case><Default>nothing</Default></Switch>` */ declare function Switch(props: { value: any } & NornJ.Childrenable): any; /** * NornJ tag `Switch`, example: * * `<NjSwitch value={foo}><NjCase value={1}><input /></NjCase><NjCase value={2}><input type="button" /></NjCase><NjDefault>nothing</NjDefault></NjSwitch>` */ declare function NjSwitch(props: { value: any } & NornJ.Childrenable): any; /** * NornJ tag `Case`, example: * * `<Switch value={foo}><Case value={1}><input /></Case><Case value={2}><input type="button" /></Case><Default>nothing</Default></Switch>` */ declare function Case(props: { value: any } & NornJ.Childrenable): any; /** * NornJ tag `Case`, example: * * `<NjSwitch value={foo}><NjCase value={1}><input /></NjCase><NjCase value={2}><input type="button" /></NjCase><NjDefault>nothing</NjDefault></NjSwitch>` */ declare function NjCase(props: { value: any } & NornJ.Childrenable): any; /** * NornJ tag `Default`, example: * * `<Switch value={foo}><Case value={1}><input /></Case><Case value={2}><input type="button" /></Case><Default>nothing</Default></Switch>` */ declare function Default(props: NornJ.Childrenable): any; /** * NornJ tag `Default`, example: * * `<NjSwitch value={foo}><NjCase value={1}><input /></NjCase><NjCase value={2}><input type="button" /></NjCase><NjDefault>nothing</NjDefault></NjSwitch>` */ declare function NjDefault(props: NornJ.Childrenable): any; /** * NornJ tag `Each`, example: * * `<Each of={[1, 2, 3]}><i key={index}>{item}</i></Each>` */ declare function Each<T>(props: { of: Iterable<T> | string; item?: string; index?: string; $key?: string; first?: string; last?: string; children: NornJ.JSXChild; }): any; /** * NornJ tag `Each`, example: * * `<NjEach of={[1, 2, 3]}><i key={index}>{item}</i></NjEach>` */ declare function NjEach<T>(props: { of: Iterable<T> | string; item?: string; index?: string; $key?: string; first?: string; last?: string; children: NornJ.JSXChild; }): any; /** * The parameter `item` in NornJ tag `Each` loop, example: * * `<Each of={[1, 2, 3]}><i key={index}>{item}</i></Each>` */ declare const item: any; /** * The parameter `index` in NornJ tag `Each` loop, example: * * `<Each of={[1, 2, 3]}><i key={index}>{item}</i></Each>` */ declare const index: number; /** * The parameter `first` in NornJ tag `Each` loop, example: * * `<Each of={[1, 2, 3]}><i key={index}>isFirst:{first}</i></Each>` */ declare const first: boolean; /** * The parameter `last` in NornJ tag `Each` loop, example: * * `<Each of={[1, 2, 3]}><i key={index}>isLast:{last}</i></Each>` */ declare const last: boolean; /** * The parameter `key` in NornJ tag `Each` loop, example: * * `<Each of={{ a: 1, b: 2 }}><i key={index}>{key},{item}</i></Each>` */ declare const key: any; /** * NornJ tag `Empty`, example: * * `<Each of={[1, 2, 3]}><i key={index}>{item}</i><Empty>nothing</Empty></Each>` */ declare function Empty(props: NornJ.Childrenable): any; /** * NornJ tag `Empty`, example: * * `<NjEach of={[1, 2, 3]}><i key={index}>{item}</i><NjEmpty>nothing</NjEmpty></NjEach>` */ declare function NjEmpty(props: NornJ.Childrenable): any; /** * NornJ tag `For`, example: * * `<For of={[1, 2, 3]}><i key={index}>{item}</i></For>` */ declare function For<T>(props: { of: Iterable<T> | string; item?: string; index?: string; $key?: string; first?: string; last?: string; children: NornJ.JSXChild; }): any; /** * NornJ tag `For`, example: * * `<NjFor of={[1, 2, 3]}><i key={index}>{item}</i></NjFor>` */ declare function NjFor<T>(props: { of: Iterable<T> | string; item?: string; index?: string; $key?: string; first?: string; last?: string; children: NornJ.JSXChild; }): any; declare function With(props: { [id: string]: any }): any; declare function NjWith(props: { [id: string]: any }): any; /** * NornJ tagged templates syntax `nj`(full name is `nj.taggedTmplH`), example: * * `nj'<html>Hello World!</html>'()` */ declare function nj(strs: TemplateStringsArray, ...args: any): NornJ.Template.RenderFunc; /** * NornJ tagged templates syntax `html`(full name is `nj.taggedTmplH`), example: * * `html'<html>Hello World!</html>'()` */ declare function html(strs: TemplateStringsArray, ...args: any): NornJ.Template.RenderFunc; /** * NornJ tagged templates syntax `njs`(full name is `nj.taggedTmpl`), example: * * `njs'<each {[1, 2, 3]}><i key={@index}>{@item}</i></each>'()` */ declare function njs(strs: TemplateStringsArray, ...args: any): NornJ.Template.RenderFunc; /** * NornJ tagged templates syntax `t`(full name is `nj.template`), example: * * `t'<each {[1, 2, 3]}><i key={@index}>{@item}</i></each>'` */ declare function t(strs: TemplateStringsArray, ...args: any): any; /** * NornJ tagged templates syntax `n`(full name is `nj.expression`), example: * * `n'((1 + 2) .. 100)[50] * 0.3 | int'` */ declare function n(strs: TemplateStringsArray, ...args: any): any; /** * NornJ tagged templates syntax `s`(full name is `nj.css`), example: * * `s'margin-left:10px;padding-top:5px'` */ declare function s(strs: TemplateStringsArray, ...args: any): any; declare namespace JSX { namespace NJ { interface If extends NornJ.Childrenable { condition: boolean | number | string; } interface Then extends NornJ.Childrenable {} interface Elseif extends NornJ.Childrenable { condition: boolean | number | string; } interface Else extends NornJ.Childrenable {} interface Switch extends NornJ.Childrenable { value: any; } interface Case extends NornJ.Childrenable { value: any; } interface Default extends NornJ.Childrenable {} interface Each<T = any> extends NornJ.Childrenable { of: Iterable<T> | string; item?: string; index?: string; $key?: string; first?: string; last?: string; children: NornJ.JSXChild; } interface With extends NornJ.Childrenable { [id: string]: any; } interface Empty extends NornJ.Childrenable {} } interface IntrinsicElements { /** * NornJ tag `if`, example: * * `<if condition={false}><input /></if>` */ if: NJ.If; /** * NornJ tag `if`, example: * * `<n-if condition={false}><input /></n-if>` */ 'n-if': NJ.If; /** * NornJ tag `then`, example: * * `<if condition={foo > 10}><input /><then>100</then><else>200</else></if>` */ then: NJ.Then; /** * NornJ tag `then`, example: * * `<n-if condition={foo > 10}><input /><n-then>100</n-then><n-else>200</n-else></n-if>` */ 'n-then': NJ.Then; /** * NornJ tag `elseif`, example: * * `<if condition={foo > 10}><input /><elseif condition={foo > 5}><input type="button" /></elseif></if>` */ elseif: NJ.Elseif; /** * NornJ tag `elseif`, example: * * `<n-if condition={foo > 10}><input /><n-elseif condition={foo > 5}><input type="button" /></n-elseif></n-if>` */ 'n-elseif': NJ.Elseif; /** * NornJ tag `else`, example: * * `<if condition={foo > 10}><input /><else><input type="button" /></else></if>` */ else: NJ.Else; /** * NornJ tag `else`, example: * * `<n-if condition={foo > 10}><input /><n-else><input type="button" /></n-else></n-if>` */ 'n-else': NJ.Else; /** * NornJ tag `Switch`, example: * * `<n-switch value={foo}><n-case value={1}><input /></n-case><n-case value={2}><input type="button" /></n-case><n-default>nothing</n-default></n-switch>` */ 'n-switch': NJ.Switch; /** * NornJ tag `case`, example: * * `<switch value={foo}><case value={1}><input /></case><case value={2}><input type="button" /></case><default>nothing</default></switch>` */ case: NJ.Case; /** * NornJ tag `case`, example: * * `<n-switch value={foo}><n-case value={1}><input /></n-case><n-case value={2}><input type="button" /></n-case><n-default>nothing</n-default></n-switch>` */ 'n-case': NJ.Case; /** * NornJ tag `default`, example: * * `<switch value={foo}><case value={1}><input /></case><case value={2}><input type="button" /></case><default>nothing</default></switch>` */ default: NJ.Default; /** * NornJ tag `default`, example: * * `<n-switch value={foo}><n-case value={1}><input /></n-case><n-case value={2}><input type="button" /></n-case><n-default>nothing</n-default></n-switch>` */ 'n-default': NJ.Default; /** * NornJ tag `each`, example: * * `<each of={[1, 2, 3]}><i key={index}>{item}</i></each>` */ each: NJ.Each; /** * NornJ tag `each`, example: * * `<n-each of={[1, 2, 3]}><i key={index}>{item}</i></n-each>` */ 'n-each': NJ.Each; /** * NornJ tag `empty`, example: * * `<each of={[1, 2, 3]}><i key={index}>{item}</i><empty>nothing</empty></each>` */ empty: NJ.Empty; /** * NornJ tag `empty`, example: * * `<n-each of={[1, 2, 3]}><i key={index}>{item}</i><n-empty>nothing</n-empty></n-each>` */ 'n-empty': NJ.Empty; for: NJ.Each; 'n-for': NJ.Each; with: NJ.With; 'n-with': NJ.With; } interface IntrinsicAttributes { /** * NornJ directive `n-show`, example: * * `<input n-show={false} />` */ ['n-show']?: boolean | number | string; /** * NornJ directive `n-style`, example: * * `<input n-style="margin-left:5px;padding:10" />` */ ['n-style']?: string; /** * NornJ directive `n-debounce`, example: * * `<input n-debounce={200} />` */ ['n-debounce']?: number | string; } } declare module 'nornj/lib/*';
the_stack
import React, { useRef, useEffect } from 'react' import { useSprings, animated, SpringConfig } from 'react-spring' import { useDrag } from 'react-use-gesture' import useResizeObserver from 'use-resize-observer' type SliderProps = { children: React.ReactNode[] index: number onIndexChange: (newIndex: number) => void className?: string style?: React.CSSProperties slideClassName?: string slideStyle?: React.CSSProperties | ((index: number) => React.CSSProperties) indexRange?: [number, number] onDragStart?: (pressedIndex: number) => void onDragEnd?: (pressedIndex: number) => void onTap?: (pressedIndex: number) => void } & typeof defaultProps const defaultProps = { enabled: true, vertical: false, slideAlign: 'center', draggedScale: 1, draggedSpring: { tension: 1200, friction: 40 } as SpringConfig, trailingSpring: { tension: 120, friction: 30 } as SpringConfig, releaseSpring: { tension: 120, friction: 30 } as SpringConfig, trailingDelay: 50 } // style for the slides wrapper const slidesWrapperStyle = (vertical: boolean): React.CSSProperties => ({ display: 'flex', flexWrap: 'nowrap', alignItems: 'stretch', position: 'relative', WebkitUserSelect: 'none', userSelect: 'none', WebkitTouchCallout: 'none', flexDirection: vertical ? 'column' : 'row', touchAction: vertical ? 'pan-x' : 'pan-y' }) const clamp = (num: number, clamp: number, higher: number) => Math.min(Math.max(num, clamp), higher) export const Slider = ({ children, index, onIndexChange, className, style, slideStyle, slideClassName, enabled, vertical, indexRange, slideAlign, draggedScale, draggedSpring, releaseSpring, trailingSpring, trailingDelay, onDragStart, onDragEnd, onTap }: SliderProps) => { const slideStyleFunc = typeof slideStyle === 'function' ? slideStyle : () => slideStyle // root holds are slides wrapper node and we use a ResizeObserver // to observe its size in order to recompute the slides position // when it changes const root = useRef<HTMLInputElement>(null) const { width, height } = useResizeObserver({ ref: root }) const axis = vertical ? 'y' : 'x' const size = vertical ? height : width let [minIndex, maxIndex] = indexRange || [0, children.length - 1] maxIndex = maxIndex > 0 ? maxIndex : children.length - 1 + maxIndex // indexRef is an internal reference to the current slide index const indexRef = useRef(index) // restPos holds a reference to the adjusted position of the slider // when rested const restPos = useRef(0) const velocity = useRef(0) // visibleIndexes is a Set holding the index of slides that are // currently partially or fully visible (intersecting) in the // viewport const visibleIndexes = useRef(new Set<number>()) const firstVisibleIndex = useRef(0) const lastVisibleIndex = useRef(0) // instances holds a ref to an array of controllers // to simulate a spring trail. Mechanics is directly // copied from here https://github.com/react-spring/react-spring/blob/31200a79843ce85200b2a7692e8f14788e60f9e9/src/useTrail.js#L14 // const instances = useRef() // callback called by the intersection observer updating // visibleIndexes const cb: IntersectionObserverCallback = slides => { slides.forEach(({ isIntersecting, target }) => visibleIndexes.current[isIntersecting ? 'add' : 'delete']( Number(target.getAttribute('data-index')) ) ) const visibles = Array.from(visibleIndexes.current).sort() firstVisibleIndex.current = visibles[0] lastVisibleIndex.current = visibles[visibles.length - 1] } const observer = useRef<IntersectionObserver | null>(null) // we add the slides to the IntersectionObserver: // this is recomputed everytime the user adds or removes a slide useEffect(() => { if (!observer.current) observer.current = new IntersectionObserver(cb) Array.from(root.current!.children).forEach(t => observer.current!.observe(t) ) return () => observer.current!.disconnect() }, [children.length, root]) // setting the springs with initial position set to restPos: // this is important when adding slides since changing children // length recomputes useSprings const [springs, set] = useSprings(children.length, _i => { // zIndex will make sure the dragged slide stays on top of the others return { x: vertical ? 0 : restPos.current, y: vertical ? restPos.current : 0, s: 1, zIndex: 0, immediate: key => key === 'zIndex' } }) // everytime the index changes, we should calculate the right position // of the slide so that its centered: this is recomputed everytime // the index changes useEffect(() => { // if width and height haven't been set don't do anything // (this happens on first render before useResizeObserver had the time to kick in) if (!width || !height) return // here we take the selected slide // and calculate its position so its centered in the slides wrapper if (vertical) { const { offsetTop, offsetHeight } = root.current!.children[ index ] as HTMLElement restPos.current = Math.round(-offsetTop + (height - offsetHeight) / 2) } else { const { offsetLeft, offsetWidth } = root.current!.children[ index ] as HTMLElement restPos.current = Math.round(-offsetLeft + (width - offsetWidth) / 2) } // two options then: // 1. the index was changed through gestures: in that case indexRef // is equal to index, we just want to set the position where it should if (indexRef.current === index) { set(_i => ({ [axis]: restPos.current, s: 1, config: { ...releaseSpring, velocity: velocity.current } // config: key => // key === axis // ? { ...releaseSpring, velocity: velocity.current } // : undefined, })) } else { // 2. the user has changed the index props: in that case indexRef // is outdated and different from index. We want to animate depending // on the direction of the slide, with the furthest slide moving first // trailing the others const dir = index < indexRef.current ? -1 : 1 // if direction is 1 then the first slide to animate should be the lowest // indexed visible slide, if -1 the highest const firstToMove = dir > 0 ? firstVisibleIndex.current : lastVisibleIndex.current set(i => { return { [axis]: restPos.current, s: 1, // config: key => key === axis && releaseSpring, config: releaseSpring, delay: i * dir < firstToMove * dir ? 0 : Math.abs(firstToMove - i) * trailingDelay } }) } // finally we update indexRef to match index indexRef.current = index }, [ index, set, root, vertical, axis, height, width, releaseSpring, draggedSpring, trailingDelay ]) // adding the bind listener const bind = useDrag( ({ first, last, tap, vxvy: [vx, vy], delta: [dx, dy], swipe: [sx, sy], movement: [movX, movY], args: [pressedIndex], memo = springs[pressedIndex][axis].getValue() }) => { if (tap) { onTap && onTap(pressedIndex) return } const v = vertical ? vy : vx const dir = -Math.sign(vertical ? dy : dx) const mov = vertical ? movY : movX const swipe = vertical ? sy : sx if (first) { // if this is the first drag event, we're trailing the controllers // to the index being dragged and setting zIndex, scale and config set(i => { return { [axis]: memo + mov, s: draggedScale, config: key => key === axis && i === pressedIndex ? draggedSpring : trailingSpring, zIndex: i === pressedIndex ? 10 : 0 } }) // triggering onDragStart prop if it exists onDragStart && onDragStart(pressedIndex) } else if (last) { // when the user releases the drag and the distance or speed are superior to a threshold // we update the indexRef if (Math.abs(mov) > size! / 2 || swipe !== 0) { indexRef.current = clamp( indexRef.current + (mov > 0 ? -1 : 1), minIndex, maxIndex ) } // if the index is not equal to indexRef we know we've moved a slide // so we tell the user to update its index in the next tick and our useEffect // will do the rest. RAF is used to make sure we're not updating the index // too fast: that might happen if the user wants to update a slide onClick // TODO - need an example if (index !== indexRef.current) { velocity.current = v requestAnimationFrame(() => onIndexChange(indexRef.current)) } // if the index hasn't changed then we set the position back to where it should be else set(() => ({ [axis]: restPos.current, s: 1, // config: key => key === axis && releaseSpring, config: releaseSpring })) // triggering onDragEnd prop if it exists onDragEnd && onDragEnd(pressedIndex) } // if not we're just dragging and we're just updating the position else { const firstToMove = dir > 0 ? firstVisibleIndex.current : lastVisibleIndex.current set(i => { return { [axis]: mov + memo, delay: i * dir < firstToMove * dir || i === pressedIndex ? 0 : Math.abs(firstToMove - i) * trailingDelay, config: key => key === axis && i === pressedIndex ? draggedSpring : trailingSpring } }) } // and returning memo to keep the initial position in cache along drag return memo }, { enabled, axis, filterTaps: true } ) const rootStyle = slidesWrapperStyle(vertical) if (!className) rootStyle.width = '100%' return ( <div ref={root} className={className} style={{ ...rootStyle, ...style }}> {springs.map(({ [axis]: pos, s, zIndex }, i) => ( <animated.div // passing the index as an argument will let our handler know // which slide is being dragged {...bind(i)} key={i} data-index={i} className={slideClassName} style={{ [vertical ? 'justifyContent' : 'alignItems']: slideAlign, display: 'flex', ...slideStyleFunc(i), zIndex, [axis]: pos, scale: s, willChange: 'transform' }} > {children[i]} </animated.div> ))} </div> ) } Slider.defaultProps = defaultProps
the_stack
import { Mark, MarkType, Node as ProseMirrorNode, NodeRange, NodeType, ResolvedPos, Slice } from 'prosemirror-model'; import { AllSelection, EditorState, SelectionRange, TextSelection, Transaction } from 'prosemirror-state'; import { RemoveMarkStep } from 'prosemirror-transform'; import { EditorView } from 'prosemirror-view'; import { doLiftNode } from '../basic/keymap/behavior'; import { removeMark, Types } from '../libs'; type TSelectedNodes = { node: ProseMirrorNode; topPos: number; nodeRange: NodeRange; originDepth: number; }[]; interface IFixRangeInfo { extendedFrom: number; extendedTo: number; $originFrom: ResolvedPos; $originTo: ResolvedPos; } const clearFormat = (view: EditorView) => { const tr = view.state.tr; const { selection, doc } = view.state; selection.ranges.forEach(({ $from, $to }) => { const curMark = (tr.storedMarks || []).concat($from.marks()); curMark.forEach(mark => tr.removeStoredMark(mark)); removeMark(doc, tr, $from.pos, $to.pos); }); view.dispatch(tr); view.focus(); return true; }; const getMarkState = (mark: Mark) => { if (Object.keys(mark.attrs).length) { return mark.attrs; } else { return true; } }; const getFormat = (view: EditorView, range?: Types.IRangeStatic) => { const { tr: { doc }, selection, storedMarks, } = view.state; const docName = doc.type.name; const paragraphName = doc.type.contentMatch.defaultType!.name; let { from, to, $from } = selection; if (range && typeof range.index === 'number' && typeof range.length === 'number') { from = range.index; to = from + range.length; $from = doc.resolve(from); } const res: Types.StringMap<any> = {}; let parentNode = $from.depth === 1 ? $from.parent : $from.node(-1); if (!parentNode) parentNode = view.state.doc; if (![docName, paragraphName].includes(parentNode.type.name)) { res[parentNode.type.name] = parentNode.attrs; } if (from !== to) { doc.nodesBetween(from, to, (node, pos, parent) => { node.marks.forEach(mark => { res[mark.type.name] = getMarkState(mark); }); if (node.isTextblock) { // maybe nested node if (parent.type.name !== docName) { res[parent.type.name] = parent.attrs; } else if (node.type.name !== paragraphName) { res[node.type.name] = node.attrs; } } return !node.isLeaf; }); } else { const curMarks = storedMarks ? storedMarks : $from.marks(); if (curMarks.length) { curMarks.forEach(mark => { res[mark.type.name] = getMarkState(mark); }); } } return res; }; // handler for mark's spec `excludes`,remove all the marks that can't coexist. (the default behavior of `prosemirror` is prevent) const removeConflictMark = (tr: Transaction, markType: MarkType) => { let res = tr; tr.selection.ranges.forEach(({ $from, $to }) => { tr.doc.nodesBetween($from.pos, $to.pos, (node, nodePos) => { if (node.isText && node.marks.length) { node.marks.forEach(mark => { const excludes = mark.type.spec.excludes || ''; if (excludes === '_' || excludes.includes(markType.name)) { res = res.step( new RemoveMarkStep(Math.max($from.pos, nodePos), Math.min($to.pos, nodePos + node.nodeSize), mark), ); } }); } }); }); return res; }; const replaceMark = (markType: MarkType, attrs: { [key: string]: any }, nTr: Transaction) => { const tr = removeConflictMark(nTr, markType); nTr.selection.ranges.forEach(({ $from, $to }) => { if ($from.pos === $to.pos) { tr.removeStoredMark(markType).addStoredMark(markType.create(attrs)); } else { tr.removeMark($from.pos, $to.pos, markType).addMark($from.pos, $to.pos, markType.create(attrs)); } }); return nTr; }; const markApplies = (doc: ProseMirrorNode, ranges: SelectionRange<any>[], type: MarkType) => { const loop = (i: number) => { const ref = ranges[i]; const $from = ref.$from; const $to = ref.$to; let can = $from.depth === 0 ? doc.type.allowsMarkType(type) : false; doc.nodesBetween($from.pos, $to.pos, node => { if (can) { return false; } can = node.inlineContent && node.type.allowsMarkType(type); }); if (can) { return { v: true }; } }; for (let i = 0; i < ranges.length; i++) { const returned = loop(i); if (returned) return returned.v; } return false; }; const toggleMark = ( markType: MarkType<any>, attrs: boolean, nTr: Transaction, storedMarks: undefined | null | Mark[], ) => { const { empty, $cursor, ranges } = nTr.selection as TextSelection; if ((empty && !$cursor) || !markApplies(nTr.doc, ranges, markType)) { return nTr; } let tr = attrs ? removeConflictMark(nTr, markType) : nTr; if ($cursor) { if (attrs) { tr = tr.addStoredMark(markType.create()); } else if (markType.isInSet(storedMarks || $cursor.marks())) { tr = tr.removeStoredMark(markType); } } else { let has = false; for (let i = 0; !has && i < ranges.length; i++) { const ref$1 = ranges[i]; const $from = ref$1.$from; const $to = ref$1.$to; has = nTr.doc.rangeHasMark($from.pos, $to.pos, markType); } for (let i$1 = 0; i$1 < ranges.length; i$1++) { const ref$2 = ranges[i$1]; const $from$1 = ref$2.$from; const $to$1 = ref$2.$to; if (attrs) { tr.addMark($from$1.pos, $to$1.pos, markType.create()); } else if (has) { tr.removeMark($from$1.pos, $to$1.pos, markType); } } } return tr; }; interface TSelectedInfos { // Selected node and range information selectedNodes: Array<{ node: ProseMirrorNode; nodeRange: NodeRange; }>; // actually selected range selectedRange: { $from: ResolvedPos; $to: ResolvedPos; }; // actual processing range wrappingRange: { from: number; to: number; }; } // check whether there are `isolating` nodes in the range const containsIsolatingNode = (ranges: SelectionRange[]) => { const $from = ranges[0].$from; const $to = ranges[0].$to; let isContain = false; $from.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { if (isContain) return true; if (node.type.spec.isolating) { // `from` and `to` should not contain by same `isolating` node or selected the isolating node if ($from.pos <= pos || $to.pos >= pos + node.nodeSize) { isContain = true; } } }); return isContain; }; // return an array containing the contents of each `range` according to `selection.ranges` const getSelectedInfos = ({ doc, selection }: Transaction) => { const selectedInfos: Array<TSelectedInfos> = []; const ranges = selection.ranges.sort((a, b) => a.$from.pos - b.$from.pos); // the location to start collecting, mainly used for isolating nodes let startPos = selection.$from.depth ? ranges[0].$from.before(1) : 0; const containIsolatingNode = ranges.length === 1 && containsIsolatingNode(ranges); ranges.forEach(({ $to, $from: $selectFrom }) => { let $from: null | ResolvedPos = $selectFrom; let extendedFrom = $from.pos; let extendedTo = $to.pos; const from = $from.pos; const to = $to.pos; let selectedNodes: TSelectedInfos['selectedNodes'] = []; doc.nodesBetween(from, to, (curNode, nodePos, parent) => { if (nodePos < startPos) return false; // do not process cross-area selected isolating nodes if (containIsolatingNode && curNode.type.spec.isolating) { startPos = nodePos + curNode.nodeSize; $from && selectedNodes.length && selectedInfos.push({ selectedNodes, selectedRange: { $from, $to: doc.resolve(nodePos), }, wrappingRange: { from: extendedFrom, to: nodePos, }, }); selectedNodes = []; $from = null; extendedFrom = startPos; return false; } // collect the `inline block` and `leaf` node if (curNode.inlineContent) { const $pos = doc.resolve(nodePos + 1); if (!$from) $from = $pos; let blockRange = $pos.blockRange(); if (!blockRange) blockRange = { start: nodePos, end: nodePos } as NodeRange<any>; if (!selectedNodes.some(({ node }) => node === curNode)) { selectedNodes.push({ node: curNode, nodeRange: blockRange, }); } let fixFrom = extendedFrom; let fixTo = extendedTo; // fix the problem of incorrect range selection when selecting nodes, and stop when meet an `isolating` parent node if ($pos.depth > 1 && !parent.type.spec.isolating) { if (parent.firstChild === curNode) { fixFrom = $pos.before(-1); } if (parent.lastChild === curNode) { fixTo = $pos.after(-1); } } extendedFrom = Math.min(extendedFrom, blockRange.start, fixFrom); extendedTo = Math.max(extendedTo, blockRange.end, fixTo); return false; } else if (curNode.isLeaf) { selectedNodes.push({ node: curNode, nodeRange: { start: nodePos, end: nodePos } as NodeRange<any>, }); } return true; }); selectedNodes.length && selectedInfos.push({ selectedNodes, selectedRange: { $from, $to, }, wrappingRange: { from: extendedFrom, to: extendedTo, }, }); }); return selectedInfos.sort((a, b) => b.selectedRange.$from.pos - a.selectedRange.$from.pos); }; // fix the incorrect pos in selectedNodes after the list level is changed const fixNodeRange = (tr: Transaction, wrappingRange: { from: number; to: number }, nodes: TSelectedNodes) => { const doc = tr.doc; const { from, to } = wrappingRange; let i = 0; doc.nodesBetween(from, to > doc.nodeSize - 2 ? doc.nodeSize - 2 : to, (node, pos) => { if (nodes[i] && node === nodes[i].node) { nodes[i++].nodeRange = doc.resolve(pos + 1).blockRange()!; return false; } if (i >= nodes.length) return false; return !node.isLeaf; }); return nodes; }; // lift all nested nodes to the top level const liftNestedNode = ( selectedNodes: TSelectedInfos['selectedNodes'], _tr: Transaction, wrappingRange: { from: number; to: number }, ) => { let shouldFixRange = false; let { from: extendedFrom, to: extendedTo } = wrappingRange; let tr = _tr; let { from, to } = tr.selection; let res: TSelectedNodes = []; for (let i = selectedNodes.length - 1; i >= 0; i--) { const { node, nodeRange } = selectedNodes[i]; const topPos = _tr.doc.resolve(nodeRange.start).before(1); // stop depth calculation until `isolating` node or root let originDepth = nodeRange.depth; for (let j = nodeRange.depth; j >= 0; j--) { const parent = nodeRange.$from.node(j); originDepth = nodeRange.depth - j; if (parent.type.spec.isolating) { break; } } let depth = originDepth; const initPos = nodeRange.start + 1; let pos = initPos; while (depth > 0) { tr = doLiftNode(tr, pos); pos = tr.mapping.map(initPos); depth--; shouldFixRange = true; } res.unshift({ node, nodeRange, originDepth, topPos }); } if (shouldFixRange) res = fixNodeRange(tr, wrappingRange, res); extendedFrom = tr.mapping.map(extendedFrom); extendedTo = tr.mapping.map(extendedTo); from = tr.mapping.map(from); to = tr.mapping.map(to); return { nodes: res, extendedFrom, extendedTo, from, to, docSize: tr.doc.nodeSize, }; }; const checkAndMergeNestedItems = (nestedItems: ProseMirrorNode[], nodeType: NodeType) => { let start = null; let end = null; for (let i = 0; i <= nestedItems.length + 1; i++) { if (nestedItems[i]) { if (start === null) { start = i; end = i; } else if (typeof end === 'number') { end++; } } else if (typeof start === 'number' && typeof end === 'number') { // combine all previous child nodes into one node const deleteCount = end - start + 1; nestedItems.splice( start, deleteCount, nodeType.createAndFill({}, nestedItems.slice(start, end + 1))!, ...new Array(deleteCount - 1), ); i = start + 1; start = null; end = null; } } return nestedItems; }; // generate nested nodes based on nesting information const createNestedNode = (nodes: TSelectedNodes, nodeType: NodeType) => { const sortedNestItems = nodes.reduce((res, selectedNode, idx) => { const depth = selectedNode.originDepth - 1; const result = { node: selectedNode.node, idx }; if (!Array.isArray(res[depth])) { res[depth] = [result]; } else { res[depth].push(result); } return res; }, [] as { node: ProseMirrorNode; idx: number }[][]); let nestedItems: ProseMirrorNode[] = []; while (sortedNestItems.length) { const curItems = sortedNestItems.pop(); if (curItems) { curItems.forEach(({ node, idx }) => { nestedItems[idx] = node; }); } if (sortedNestItems.length) { nestedItems = checkAndMergeNestedItems(nestedItems, nodeType); } } return nestedItems.filter((item: any) => item); }; /** * @param nodeTy node type to be created * @param node child node * @param attrs attrs of the node to be created */ const createNode = (nodeTy: NodeType, node: ProseMirrorNode, attrs = {}) => nodeTy.createAndFill(Object.assign({}, node.attrs, attrs), node.content, node.marks); // restore selection based on content const getRangeAfterReplace = ( state: EditorState, tr: Transaction, { extendedFrom, extendedTo, $originFrom, $originTo }: IFixRangeInfo, ) => { const docSize = tr.doc.nodeSize - 2; let newFrom = extendedFrom; let newTo = extendedTo; if (!(state.selection instanceof AllSelection)) { let isMatchFrom = false; let defaultPos: null | number = null; const fromContent = $originFrom.node().textContent; const toContent = $originTo.node().textContent; tr.doc.nodesBetween(extendedFrom, Math.min(extendedTo, docSize), (node, pos) => { if (node.inlineContent) { if (defaultPos === null) defaultPos = pos + 1; if (!isMatchFrom && node.textContent === fromContent) { newFrom = pos + 1 + $originFrom.parentOffset; isMatchFrom = true; } if (isMatchFrom && node.textContent === toContent) { newTo = pos + 1 + Math.min(node.textContent.length, $originTo.parentOffset); } } return isMatchFrom ? false : !node.isLeaf; }); if (!isMatchFrom) { newFrom = defaultPos || newFrom; newTo = newFrom; } } return { from: newFrom, to: Math.min(newTo, docSize), }; }; // apply the format to the node and return to the new selection range const formatNodeType = ( targetNodeType: NodeType, attributes: Types.StringMap<any> | undefined, sNodes: TSelectedInfos['selectedNodes'], selectedRange: TSelectedInfos['selectedRange'], wrappingRange: { from: number; to: number }, nTr: Transaction, state: EditorState, ) => { let transaction = nTr; // check whether it is a nested node, the text of the nested node should be placed in the defaultType const isNestedNodeType = !targetNodeType.isTextblock; const contentNodeType = isNestedNodeType ? targetNodeType.contentMatch.defaultType! : targetNodeType; const { nodes: selectedNodes, extendedFrom, extendedTo, docSize } = liftNestedNode( sNodes, transaction, wrappingRange, ); const newNodes: ProseMirrorNode<any>[] = []; for (let i = 0; i < selectedNodes.length; i++) { const { node, originDepth } = selectedNodes[i]; if (node.isTextblock && originDepth && isNestedNodeType) { // nested textBlock const nestedContentNodes: TSelectedNodes = []; while ( selectedNodes[i] && selectedNodes[i].node.isTextblock && // if same parent node, continue (!nestedContentNodes.length || selectedNodes[i].topPos === nestedContentNodes[nestedContentNodes.length - 1].topPos) ) { nestedContentNodes.push(selectedNodes[i]); i++; } i--; newNodes.push(...createNestedNode(nestedContentNodes, targetNodeType)); } else { let addNode = node; if (!addNode.isLeaf) { addNode = createNode(contentNodeType, node, contentNodeType === targetNodeType && attributes)!; } addNode && newNodes.push(addNode); } } const rootNodeType: NodeType = isNestedNodeType ? targetNodeType : state.schema.nodes.doc; // dummy root const root = rootNodeType.createAndFill(attributes, newNodes)!; if (isNestedNodeType) { transaction.replaceRangeWith(extendedFrom, extendedTo, root); } else { transaction = transaction.replaceRange(extendedFrom, extendedTo, new Slice(root.content, 0, 0)); } return getRangeAfterReplace(state, transaction, { extendedFrom, extendedTo: extendedTo + transaction.doc.nodeSize - docSize, $originFrom: selectedRange.$from, $originTo: selectedRange.$to, }); }; const formatSelection = ( formatType: string, formatValue: Types.StringMap<any> | boolean, formatRange?: { from: number; to: number }, ) => (state: EditorState, tr: Transaction) => { const { schema, doc, selection: { from, to, ranges, anchor, head }, } = state; let reSelect = (_tr: Transaction) => _tr; // if `formatRange` is specified, keep the same selected content after setting if (formatRange) { reSelect = (_tr: Transaction) => { if (state.selection instanceof AllSelection) { _tr.setSelection(new AllSelection(_tr.doc)); // set format before the current selection } else if (formatRange.to <= from) { const diffSize = _tr.doc.nodeSize - state.doc.nodeSize; return _tr.setSelection(TextSelection.create(_tr.doc, from + diffSize, to + diffSize)); } else { _tr.setSelection(TextSelection.create(_tr.doc, from, to)); } return _tr.setSelection(TextSelection.create(_tr.doc, anchor, head)); }; // reset the selection according to the `formatRange` tr.setSelection(TextSelection.create(doc, formatRange.from, formatRange.to)); } if (schema.marks[formatType]) { if (typeof formatValue === 'boolean') { toggleMark(schema.marks[formatType], formatValue, tr, state.storedMarks); } else { replaceMark(schema.marks[formatType], formatValue, tr); } } else if (schema.nodes[formatType]) { const nodeType = schema.nodes[formatType]; const selectedInfos = getSelectedInfos(tr); if (!selectedInfos.length) return tr; let resultFrom = doc.nodeSize; let resultTo = 0; selectedInfos.forEach(({ selectedNodes, wrappingRange, selectedRange }) => { const { from: rFrom, to: rTo } = formatNodeType( formatValue ? nodeType : schema.nodes.paragraph, typeof formatValue === 'boolean' ? undefined : formatValue, selectedNodes, selectedRange, wrappingRange, tr, state, ); resultFrom = Math.min(resultFrom, rFrom); resultTo = Math.max(resultTo, rTo); }); /** * if there are multiple ranges, * the position of the node calculated at the beginning needs to consider the change of the previous node size */ if (selectedInfos.length > 1) { const diffSize = tr.doc.nodeSize - state.doc.nodeSize; resultTo += diffSize - Math.floor(diffSize / selectedInfos.length); } /** * if the selection area is split, or the `format range` actually contains the current `selection`, * the selection needs to modified to ensure that the same content is selected */ const firstRange = selectedInfos[0]; const lastRange = selectedInfos[selectedInfos.length - 1]; if (formatRange || (firstRange.wrappingRange.from < to && lastRange.wrappingRange.to > from)) { reSelect = (_tr: Transaction) => { if (state.selection instanceof AllSelection) return _tr.setSelection(new AllSelection(_tr.doc)); ranges.sort((a, b) => a.$from.pos - b.$from.pos); const newRange = getRangeAfterReplace(state, _tr, { extendedFrom: Math.min(from, resultFrom), extendedTo: Math.max(to, resultTo), $originFrom: ranges[0].$from, $originTo: ranges[ranges.length - 1].$to, }); return _tr.setSelection(TextSelection.create(_tr.doc, newRange.from, newRange.to)); }; } tr.setSelection(TextSelection.create(tr.doc, resultFrom, resultTo)); } return reSelect(tr); }; export { clearFormat, formatSelection, getFormat };
the_stack
import { mat4, quat, vec3, vec4 } from 'gl-matrix'; import { Component, NonFunctionProperties } from '../../ComponentManager'; export class TransformComponent extends Component<TransformComponent> { public static DIRTY = 1 << 0; public dirtyFlag: number; public localDirtyFlag: number; public parent: TransformComponent | null = null; /** * local space RTS */ /** * XMFLOAT4X4._41 * @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmfloat4x4-xmfloat4x4(constfloat)#remarks */ public localPosition = vec3.fromValues(0, 0, 0); public localRotation = quat.fromValues(0, 0, 0, 1); public localScale = vec3.fromValues(1, 1, 1); public localTransform = mat4.create(); /** * world space RTS */ public position = vec3.fromValues(0, 0, 0); public rotation = quat.fromValues(0, 0, 0, 1); public scaling = vec3.fromValues(1, 1, 1); public worldTransform = mat4.create(); // 高阶函数,利用闭包重复利用临时变量 // @see playcanvas graph node public matrixTransform = (() => { const transformed = mat4.create(); return (mat: mat4) => { mat4.multiply(transformed, this.getLocalTransform(), mat); mat4.getScaling(this.localScale, transformed); mat4.getTranslation(this.localPosition, transformed); mat4.getRotation(this.localRotation, transformed); }; })(); /** * @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw */ public rotateRollPitchYaw = (() => { const quatX = quat.create(); const quatY = quat.create(); const quatZ = quat.create(); return (x: number, y: number, z: number) => { this.setDirty(); quat.fromEuler(quatX, x, 0, 0); quat.fromEuler(quatY, 0, y, 0); quat.fromEuler(quatZ, 0, 0, z); quat.multiply(this.localRotation, quatX, this.localRotation); quat.multiply(this.localRotation, this.localRotation, quatY); quat.multiply(this.localRotation, quatZ, this.localRotation); quat.normalize(this.localRotation, this.localRotation); }; })(); /** * @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html */ public lerp = (() => { const aS = vec3.create(); const aR = quat.create(); const aT = vec3.create(); const bS = vec3.create(); const bR = quat.create(); const bT = vec3.create(); return (a: TransformComponent, b: TransformComponent, t: number) => { this.setDirty(); mat4.getScaling(aS, a.worldTransform); mat4.getTranslation(aT, a.worldTransform); mat4.getRotation(aR, a.worldTransform); mat4.getScaling(bS, b.worldTransform); mat4.getTranslation(bT, b.worldTransform); mat4.getRotation(bR, b.worldTransform); vec3.lerp(this.localScale, aS, bS, t); quat.slerp(this.localRotation, aR, bR, t); vec3.lerp(this.localPosition, aT, bT, t); }; })(); /** * TODO: 支持以下两种: * * translate(x, y, z) * * translate(vec3(x, y, z)) */ public translate = (() => { const tr = vec3.create(); return (translation: vec3) => { vec3.add(tr, this.getPosition(), translation); this.setPosition(tr); this.setDirty(true); return this; }; })(); public translateLocal = (() => { return (translation: vec3) => { vec3.transformQuat(translation, translation, this.localRotation); vec3.add(this.localPosition, this.localPosition, translation); this.setLocalDirty(true); return this; }; })(); public setPosition = (() => { const parentInvertMatrix = mat4.create(); return (position: vec3) => { this.position = position; this.setLocalDirty(true); if (this.parent === null) { vec3.copy(this.localPosition, position); } else { mat4.copy(parentInvertMatrix, this.parent.worldTransform); mat4.invert(parentInvertMatrix, parentInvertMatrix); vec3.transformMat4(this.localPosition, position, parentInvertMatrix); } return this; }; })(); public rotate = (() => { const parentInvertRotation = quat.create(); return (quaternion: quat) => { if (this.parent === null) { quat.multiply(this.localRotation, this.localRotation, quaternion); quat.normalize(this.localRotation, this.localRotation); } else { const rot = this.getRotation(); const parentRot = this.parent.getRotation(); quat.copy(parentInvertRotation, parentRot); quat.invert(parentInvertRotation, parentInvertRotation); quat.multiply(parentInvertRotation, parentInvertRotation, quaternion); quat.multiply(this.localRotation, quaternion, rot); quat.normalize(this.localRotation, this.localRotation); } this.setLocalDirty(); return this; }; })(); public rotateLocal = (() => { return (quaternion: quat) => { quat.multiply(this.localRotation, this.localRotation, quaternion); quat.normalize(this.localRotation, this.localRotation); this.setLocalDirty(true); return this; }; })(); public setRotation = (() => { const invParentRot = quat.create(); return (rotation: quat) => { if (this.parent === null) { quat.copy(this.localRotation, rotation); } else { quat.copy(invParentRot, this.parent.getRotation()); quat.invert(invParentRot, invParentRot); quat.copy(this.localRotation, invParentRot); quat.mul(this.localRotation, this.localRotation, rotation); } this.setLocalDirty(true); return this; }; })(); /** * @see https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline */ // public catmullRom = (() => { // const aS = vec3.create(); // const aR = quat.create(); // const aT = vec3.create(); // const bS = vec3.create(); // const bR = quat.create(); // const bT = vec3.create(); // const cS = vec3.create(); // const cR = quat.create(); // const cT = vec3.create(); // const dS = vec3.create(); // const dR = quat.create(); // const dT = vec3.create(); // const R = quat.create(); // return ( // a: TransformComponent, // b: TransformComponent, // c: TransformComponent, // d: TransformComponent, // t: number, // ) => { // this.setDirty(); // mat4.getScaling(aS, a.worldTransform); // mat4.getTranslation(aT, a.worldTransform); // mat4.getRotation(aR, a.worldTransform); // mat4.getScaling(bS, b.worldTransform); // mat4.getTranslation(bT, b.worldTransform); // mat4.getRotation(bR, b.worldTransform); // mat4.getScaling(cS, c.worldTransform); // mat4.getTranslation(cT, c.worldTransform); // mat4.getRotation(cR, c.worldTransform); // mat4.getScaling(dS, d.worldTransform); // mat4.getTranslation(dT, d.worldTransform); // mat4.getRotation(dR, d.worldTransform); // vec3.catmullRom(this.localPosition, aT, bT, cT, dT, t); // vec3.catmullRom(R, aR, bR, cR, dR, t); // quat.normalize(this.localRotation, R); // vec3.catmullRom(this.localScale, aS, bS, cS, dS, t); // }; // })(); constructor(data?: Partial<NonFunctionProperties<TransformComponent>>) { super(data); } public setLocalPosition(position: vec3) { vec3.copy(this.localPosition, position); this.setLocalDirty(true); } public setLocalScale(scale: vec3) { vec3.copy(this.localScale, scale); this.setLocalDirty(true); } public setLocalRotation(rotation: quat) { quat.copy(this.localRotation, rotation); this.setLocalDirty(true); return this; } public isDirty() { return this.dirtyFlag; } public setDirty(value = true) { if (value) { this.dirtyFlag |= TransformComponent.DIRTY; } else { this.dirtyFlag &= ~TransformComponent.DIRTY; } } public isLocalDirty() { return this.localDirtyFlag; } public setLocalDirty(value = true) { if (value) { this.localDirtyFlag |= TransformComponent.DIRTY; this.setDirty(true); } else { this.localDirtyFlag &= ~TransformComponent.DIRTY; } } public updateTransform() { if (this.isLocalDirty()) { this.getLocalTransform(); } if (this.isDirty()) { if (this.parent === null) { mat4.copy(this.worldTransform, this.getLocalTransform()); this.setDirty(false); } } } public updateTransformWithParent(parent: TransformComponent) { mat4.multiply( this.worldTransform, parent.worldTransform, this.getLocalTransform(), ); } public applyTransform() { this.setDirty(); mat4.getScaling(this.localScale, this.worldTransform); mat4.getTranslation(this.localPosition, this.worldTransform); mat4.getRotation(this.localRotation, this.worldTransform); } public clearTransform() { this.setDirty(); this.localPosition = vec3.fromValues(0, 0, 0); this.localRotation = quat.fromValues(0, 0, 0, 1); this.localScale = vec3.fromValues(1, 1, 1); } public scaleLocal(scaling: vec3) { this.setLocalDirty(); vec3.multiply(this.localScale, this.localScale, scaling); return this; } public getLocalPosition() { return this.localPosition; } public getLocalRotation() { return this.localRotation; } public getLocalScale() { return this.localScale; } public getLocalTransform() { if (this.localDirtyFlag) { mat4.fromRotationTranslationScale( this.localTransform, this.localRotation, this.localPosition, this.localScale, ); this.setLocalDirty(false); } return this.localTransform; } public getWorldTransform() { if (!this.isLocalDirty() && !this.isDirty()) { return this.worldTransform; } if (this.parent) { this.parent.getWorldTransform(); } this.updateTransform(); return this.worldTransform; } public getPosition() { mat4.getTranslation(this.position, this.worldTransform); return this.position; } public getRotation() { mat4.getRotation(this.rotation, this.worldTransform); return this.rotation; } public getScale() { mat4.getScaling(this.scaling, this.worldTransform); return this.scaling; } }
the_stack
import AWS from 'aws-sdk'; import chalk from 'chalk'; import { Listr, ListrTask, ListrTaskWrapper } from 'listr2'; import { ResourceTagMappingList } from 'aws-sdk/clients/resourcegroupstaggingapi'; import { TrickInterface } from '../types/trick.interface'; import { TrickOptionsInterface } from '../types/trick-options.interface'; import { ElasticacheReplicationGroupState } from '../states/elasticache-replication-group.state'; import { TrickContext } from '../types/trick-context'; export type SnapshotRemoveElasticacheRedisState = ElasticacheReplicationGroupState[]; export class SnapshotRemoveElasticacheRedisTrick implements TrickInterface<SnapshotRemoveElasticacheRedisState> { static machineName = 'snapshot-remove-elasticache-redis'; private elcClient: AWS.ElastiCache; private rgtClient: AWS.ResourceGroupsTaggingAPI; constructor() { this.elcClient = new AWS.ElastiCache(); this.rgtClient = new AWS.ResourceGroupsTaggingAPI(); } getMachineName(): string { return SnapshotRemoveElasticacheRedisTrick.machineName; } async prepareTags( task: ListrTaskWrapper<any, any>, context: TrickContext, options: TrickOptionsInterface, ): Promise<Listr | void> { const resourceTagMappings: ResourceTagMappingList = []; // TODO Add logic to go through all pages task.output = 'fetching page 1...'; resourceTagMappings.push( ...(( await this.rgtClient .getResources({ ResourcesPerPage: 100, ResourceTypeFilters: ['elasticache:cluster'], TagFilters: options.tags, }) .promise() ).ResourceTagMappingList as ResourceTagMappingList), ); context.resourceTagMappings = resourceTagMappings; task.output = 'done'; } async getCurrentState( task: ListrTaskWrapper<any, any>, context: TrickContext, state: SnapshotRemoveElasticacheRedisState, options: TrickOptionsInterface, ): Promise<Listr> { const replicationGroups = await this.listReplicationGroups(task); const subListr = task.newListr([], { concurrent: 10, exitOnError: false, rendererOptions: { collapse: true, }, }); if (!replicationGroups || replicationGroups.length === 0) { task.skip(chalk.dim('no ElastiCache Redis clusters found')); return subListr; } subListr.add( replicationGroups.map( (replicationGroup): ListrTask => { return { title: replicationGroup.ReplicationGroupId || chalk.italic('<no-id>'), task: async (ctx, task) => { if (replicationGroup.ReplicationGroupId === undefined) { throw new Error( `Unexpected error: ReplicationGroupId is missing for ElastiCache replication group`, ); } const replicationGroupState = { id: replicationGroup.ReplicationGroupId, } as ElasticacheReplicationGroupState; const changes = await this.getReplicationGroupState( context, task, replicationGroupState, replicationGroup, ); if (changes) { state.push({ ...replicationGroupState, ...changes }); } }, options: { persistentOutput: true, }, }; }, ), ); return subListr; } async conserve( task: ListrTaskWrapper<any, any>, currentState: SnapshotRemoveElasticacheRedisState, options: TrickOptionsInterface, ): Promise<Listr> { const subListr = task.newListr([], { concurrent: 10, exitOnError: false, rendererOptions: { collapse: true, }, }); if (currentState && currentState.length > 0) { for (const replicationGroup of currentState) { subListr.add({ title: chalk.blue(replicationGroup.id), task: (ctx, task) => this.conserveReplicationGroup(task, replicationGroup, options), options: { persistentOutput: true, }, }); } } else { task.skip(chalk.dim(`no ElastiCache Redis clusters found`)); } return subListr; } async restore( task: ListrTaskWrapper<any, any>, originalState: SnapshotRemoveElasticacheRedisState, options: TrickOptionsInterface, ): Promise<Listr> { const subListr = task.newListr([], { concurrent: 10, exitOnError: false, rendererOptions: { collapse: true, }, }); if (originalState && originalState.length > 0) { for (const replicationGroup of originalState) { subListr.add({ title: chalk.blue(replicationGroup.id), task: (ctx, task) => this.restoreReplicationGroup(task, replicationGroup, options), options: { persistentOutput: true, }, }); } } else { task.skip(chalk.dim(`no ElastiCache Redis clusters found`)); } return subListr; } private async conserveReplicationGroup( task: ListrTaskWrapper<any, any>, replicationGroupState: ElasticacheReplicationGroupState, options: TrickOptionsInterface, ): Promise<void> { if (replicationGroupState.status !== 'available') { task.skip( chalk.dim( `skipped, current state is not "available" it is "${replicationGroupState.status}" instead`, ), ); return; } if (options.dryRun) { task.skip(chalk.dim('skipped, would take a snapshot and delete')); return; } task.output = 'taking a snapshot and deleting replication group...'; await this.elcClient .deleteReplicationGroup({ ReplicationGroupId: replicationGroupState.id, FinalSnapshotIdentifier: replicationGroupState.snapshotName, }) .promise(); task.output = 'Waiting for snapshot to be created, and replication group to be deleted...'; await this.elcClient .waitFor('replicationGroupDeleted', { ReplicationGroupId: replicationGroupState.id, $waiter: { delay: 30, maxAttempts: 100, }, }) .promise(); task.output = `Snapshot ${replicationGroupState.snapshotName} taken and replication group deleted successfully`; } private async restoreReplicationGroup( task: ListrTaskWrapper<any, any>, replicationGroupState: ElasticacheReplicationGroupState, options: TrickOptionsInterface, ): Promise<void> { if (!replicationGroupState.snapshotName) { throw new Error(`Unexpected error: snapshotName is missing in state`); } if (!replicationGroupState.createParams) { throw new Error(`Unexpected error: createParams is missing in state`); } if (replicationGroupState.status !== 'available') { task.skip( chalk.dim( `skipped, previous state was not "available" it was "${replicationGroupState.status}" instead`, ), ); return; } if (await this.doesReplicationGroupExist(replicationGroupState)) { task.skip(chalk.dim('ElastiCache redis cluster already exists')); return; } if (options.dryRun) { task.skip( chalk.dim( `skipped, would re-create the cluster and remove the snapshot ${replicationGroupState.snapshotName}`, ), ); return; } task.output = `Creating replication group (snapshot: ${replicationGroupState.snapshotName})...`; await this.elcClient .createReplicationGroup(replicationGroupState.createParams) .promise(); task.output = `Waiting for replication group to be available (snapshot: ${replicationGroupState.snapshotName})...`; await this.elcClient .waitFor('replicationGroupAvailable', { ReplicationGroupId: replicationGroupState.id, $waiter: { delay: 30, maxAttempts: 100, }, }) .promise(); task.output = `Deleting snapshot ${replicationGroupState.snapshotName}...`; await this.elcClient .deleteSnapshot({ SnapshotName: replicationGroupState.snapshotName, }) .promise(); task.output = 'restored successfully'; } private async getReplicationGroupState( context: TrickContext, task: ListrTaskWrapper<any, any>, replicationGroupState: ElasticacheReplicationGroupState, replicationGroup: AWS.ElastiCache.ReplicationGroup, ): Promise<ElasticacheReplicationGroupState | undefined> { replicationGroupState.status = 'unknown'; if (replicationGroup.ARN === undefined) { throw new Error( `Unexpected error: ARN is missing for ElastiCache replication group`, ); } if (replicationGroup.Status === undefined) { throw new Error( `Unexpected error: Status is missing for ElastiCache replication group`, ); } if ( !replicationGroup.MemberClusters || replicationGroup.MemberClusters.length === 0 ) { throw new Error( `Unexpected error: No member clusters for ElastiCache replication group`, ); } if (replicationGroup.AuthTokenEnabled) { throw new Error( `Cannot conserve an AuthToken protected Redis Cluster because on restore token will change`, ); } task.output = 'fetching a sample cache cluster...'; const sampleCacheCluster = await this.describeCacheCluster( replicationGroup.MemberClusters[0], ); if (!sampleCacheCluster) { throw new Error(`Could not find sample cache cluster`); } if (!this.isClusterIncluded(context, sampleCacheCluster.ARN as string)) { task.skip(`excluded due to tag filters`); return; } task.output = 'preparing re-create params...'; const snapshotName = SnapshotRemoveElasticacheRedisTrick.generateSnapshotName( replicationGroup, ); const nodeGroups = this.generateNodeGroupConfigs(replicationGroup); const createParams = await this.buildCreateParams( snapshotName, replicationGroup, nodeGroups, sampleCacheCluster, ); replicationGroupState.snapshotName = snapshotName; replicationGroupState.status = replicationGroup.Status; replicationGroupState.createParams = createParams; task.output = 'done'; return replicationGroupState; } private generateNodeGroupConfigs( replicationGroup: AWS.ElastiCache.ReplicationGroup, ) { return ( replicationGroup.NodeGroups?.map( n => ({ NodeGroupId: n.NodeGroupId, ReplicaCount: n.NodeGroupMembers?.length, Slots: n.Slots, } as AWS.ElastiCache.NodeGroupConfiguration), ) || [] ); } private async buildCreateParams( snapshotName: string, replicationGroup: AWS.ElastiCache.ReplicationGroup, nodeGroups: AWS.ElastiCache.NodeGroupConfiguration[], sampleCacheCluster: AWS.ElastiCache.CacheCluster, ): Promise<AWS.ElastiCache.CreateReplicationGroupMessage> { return { // Required ReplicationGroupId: replicationGroup.ReplicationGroupId, ReplicationGroupDescription: replicationGroup.Description || `Restored by aws-cost-saver from snapshot: ${snapshotName}`, SnapshotName: snapshotName, // Replication Group Configs AtRestEncryptionEnabled: replicationGroup.AtRestEncryptionEnabled, TransitEncryptionEnabled: replicationGroup.TransitEncryptionEnabled, NumCacheClusters: nodeGroups.length > 1 ? undefined : replicationGroup.MemberClusters?.length || 1, NumNodeGroups: nodeGroups.length > 1 ? nodeGroups.length : undefined, MultiAZEnabled: replicationGroup.MultiAZ !== undefined && replicationGroup.MultiAZ === 'enabled', NodeGroupConfiguration: nodeGroups.length > 1 ? nodeGroups : undefined, GlobalReplicationGroupId: replicationGroup.GlobalReplicationGroupInfo?.GlobalReplicationGroupId, KmsKeyId: replicationGroup.KmsKeyId, AutomaticFailoverEnabled: replicationGroup.AutomaticFailover !== undefined && ['enabled', 'enabling'].includes(replicationGroup.AutomaticFailover), Port: sampleCacheCluster.CacheNodes && sampleCacheCluster.CacheNodes[0]?.Endpoint?.Port, Tags: await this.getTags(sampleCacheCluster.ARN as string), // Cache Clusters Configs PreferredCacheClusterAZs: nodeGroups.length > 1 ? undefined : sampleCacheCluster.PreferredAvailabilityZone ? [sampleCacheCluster.PreferredAvailabilityZone] : undefined, SecurityGroupIds: sampleCacheCluster.SecurityGroups?.map( s => s.SecurityGroupId as string, ), CacheSecurityGroupNames: sampleCacheCluster.CacheSecurityGroups?.map( c => c.CacheSecurityGroupName || '', ), // Shared Cache Cluster Configs AutoMinorVersionUpgrade: sampleCacheCluster.AutoMinorVersionUpgrade, CacheNodeType: sampleCacheCluster.CacheNodeType, SnapshotRetentionLimit: sampleCacheCluster.SnapshotRetentionLimit, Engine: sampleCacheCluster.Engine, EngineVersion: sampleCacheCluster.EngineVersion, CacheParameterGroupName: sampleCacheCluster.CacheParameterGroup?.CacheParameterGroupName, CacheSubnetGroupName: sampleCacheCluster.CacheSubnetGroupName, NotificationTopicArn: sampleCacheCluster.NotificationConfiguration?.TopicArn, SnapshotWindow: sampleCacheCluster.SnapshotWindow, PreferredMaintenanceWindow: sampleCacheCluster.PreferredMaintenanceWindow, } as AWS.ElastiCache.CreateReplicationGroupMessage; } private async doesReplicationGroupExist( replicationGroupState: ElasticacheReplicationGroupState, ) { const result = await this.elcClient .describeReplicationGroups({ ReplicationGroupId: replicationGroupState.id, }) .promise(); return Boolean( result.ReplicationGroups && result.ReplicationGroups.length > 0, ); } private async listReplicationGroups( task: ListrTaskWrapper<any, any>, ): Promise<AWS.ElastiCache.ReplicationGroupList> { const replicationGroups: AWS.ElastiCache.ReplicationGroupList = []; // TODO Add logic to go through all pages task.output = 'fetching page 1...'; replicationGroups.push( ...(( await this.elcClient .describeReplicationGroups({ MaxRecords: 100 }) .promise() ).ReplicationGroups as AWS.ElastiCache.ReplicationGroupList), ); task.output = 'done'; return replicationGroups; } private async describeCacheCluster( cacheClusterId: string, ): Promise<AWS.ElastiCache.CacheCluster | undefined> { return (( await this.elcClient .describeCacheClusters({ CacheClusterId: cacheClusterId, ShowCacheNodeInfo: true, }) .promise() ).CacheClusters as AWS.ElastiCache.CacheClusterList).pop(); } private async getTags(arn: string) { return ( await this.elcClient .listTagsForResource({ ResourceName: arn, }) .promise() ).TagList as AWS.ElastiCache.TagList; } private isClusterIncluded( context: TrickContext, clusterArn: string, ): boolean { return Boolean( context.resourceTagMappings?.find(rm => rm.ResourceARN === clusterArn), ); } private static generateSnapshotName( replicationGroup: AWS.ElastiCache.ReplicationGroup, ) { const now = new Date(); return `${ replicationGroup.ReplicationGroupId }-${now.getFullYear()}${now.getMonth()}${now.getDay()}${now.getHours()}${now.getMinutes()}`; } }
the_stack
import { MappedDataSource } from "./MappedDataSource"; import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation"; import { MappedSingleSourceInsertionOperation } from "./MappedSingleSourceInsertionOperation"; import { MappedSingleSourceUpdateOperation } from "./MappedSingleSourceUpdateOperation"; import { MappedSingleSourceDeletionOperation } from "./MappedSingleSourceDeletionOperation"; import { pluralize, singularize } from "inflection"; import { has, isPlainObject, identity } from "lodash"; import { isArray } from "util"; import { Interceptor } from "./utils/util-types"; /** * Default type of arguments expected by query operation preset * @api-category ConfigType */ export interface PresetQueryParams<TSrc extends MappedDataSource> { where: Partial<TSrc["ShallowEntityType"]>; } /** * Default type of arguments expected by update operation preset * @api-category ConfigType */ export interface PresetUpdateParams<TSrc extends MappedDataSource> extends PresetQueryParams<TSrc> { update: Partial<TSrc["ShallowEntityType"]>; } /** * Default type of arguments expected by deletion operation preset * @api-category ConfigType */ export interface PresetDeletionParams<TSrc extends MappedDataSource> extends PresetQueryParams<TSrc> {} /** * Default type of arguments expected by singular insertion preset * @api-category ConfigType */ export interface PresetSingleInsertionParams<TSrc extends MappedDataSource> { entity: TSrc["ShallowEntityType"]; } /** * Default type of arguments expected by multi-insertion preset * @api-category ConfigType */ export interface PresetMultiInsertionParams<TSrc extends MappedDataSource> { entities: TSrc["ShallowEntityType"][]; } export function isPresetSingleInsertionParams(params: any): params is PresetSingleInsertionParams<any> { return isPlainObject(params.entity); } export function isPresetMultiInsertionParams(params: any): params is PresetMultiInsertionParams<any> { return isArray(params.entities); } /** * Default type of arguments expected by insertion preset * @api-category ConfigType */ export type PresetInsertionParams<TSrc extends MappedDataSource> = | PresetSingleInsertionParams<TSrc> | PresetMultiInsertionParams<TSrc>; export function isPresentInsertionParams(params: any): params is PresetInsertionParams<any> { return isPresetSingleInsertionParams(params) || isPresetMultiInsertionParams(params); } export function isPresetQueryParams<TSrc extends MappedDataSource>(t: any): t is PresetQueryParams<TSrc> { return has(t, "where") && isPlainObject(t.where); } export function isPresetUpdateParams<TSrc extends MappedDataSource>(t: any): t is PresetUpdateParams<TSrc> { return isPresetQueryParams(t) && has(t, "update") && isPlainObject((t as any).update); } /** * @name operationPresets.query.findOneOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function findOneOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>( interceptMapping({ rootSource, name: `findOne${singularize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: true, shallow: false, }), ); } const getPresetPaginationConfig = (rootSource: MappedDataSource) => { const { primaryFields } = rootSource; if (primaryFields.length !== 1) throw new Error("Preset expects a single primary field"); const [primaryField] = primaryFields; return { cursorColumn: primaryField.sourceColumn!, }; }; /** * @name operationPresets.query.findManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function findManyOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>( interceptMapping({ rootSource, name: `findMany${pluralize(rootSource.mappedName)}`, returnType: undefined, description: undefined, args: undefined, singular: false, shallow: false, }), ); } /** * @name operationPresets.query.findManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function paginatedFindManyOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>["mapping"] > = identity, ) { const mapping = interceptMapping({ rootSource, name: `findMany${pluralize(rootSource.mappedName)}`, returnType: undefined, description: undefined, args: undefined, singular: false, shallow: false, }); mapping.paginate = mapping.paginate || getPresetPaginationConfig(rootSource); return new MappedSingleSourceQueryOperation<TSrc, PresetQueryParams<TSrc>>(interceptMapping(mapping)); } /** * @name operationPresets.mutation.insertOneOpeeration * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function insertOneOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceInsertionOperation<TSrc, PresetSingleInsertionParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceInsertionOperation<TSrc, PresetSingleInsertionParams<TSrc>>( interceptMapping({ rootSource, name: `insertOne${singularize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: true, shallow: true, }), ); } /** * @name operationPresets.mutation.insertManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function insertManyOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceInsertionOperation<TSrc, PresetMultiInsertionParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceInsertionOperation<TSrc, PresetMultiInsertionParams<TSrc>>( interceptMapping({ rootSource, name: `insertMany${pluralize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: false, shallow: true, }), ); } /** * @name operationPresets.mutations.updateManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function updateOneOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>( interceptMapping({ rootSource, name: `updateOne${singularize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: true, shallow: true, }), ); } /** * @name operationPresets.mutations.updateManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function updateManyOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceUpdateOperation<TSrc, PresetUpdateParams<TSrc>>( interceptMapping({ rootSource, name: `updateMany${pluralize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: false, shallow: true, }), ); } /** * Operation preset to delete a single entity matching some query criteria * * @name operationPresets.mutations.deleteOneOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function deleteOneOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>( interceptMapping({ rootSource, name: `deleteOne${singularize(rootSource.mappedName)}`, singular: true, shallow: true, }), ); } /** * Operation preset to delete multiple entities matching specified query criteria * * @name operationPresets.mutations.deleteManyOperation * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function deleteManyOperation<TSrc extends MappedDataSource>( rootSource: TSrc, interceptMapping: Interceptor< MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>["mapping"] > = identity, ) { return new MappedSingleSourceDeletionOperation<TSrc, PresetDeletionParams<TSrc>>( interceptMapping({ rootSource, name: `deleteMany${pluralize(rootSource.mappedName)}`, description: undefined, returnType: undefined, args: undefined, singular: false, shallow: true, }), ); } /** * Get list of all available query presets applied to specified data source * * @name operationPresets.query.all * @api-category PriamryAPI * @param rootSource The data source on which the operation is to be performed */ const defaultQueries = (rootSource: MappedDataSource) => [findOneOperation(rootSource), findManyOperation(rootSource)]; export const query = { findOneOperation, findManyOperation, defaults: defaultQueries, }; /** * Get list of all available mutation presets applied to specified data source * * @name operationPresets.mutation.all * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ const defaultMutations = (rootSource: MappedDataSource) => [ insertOneOperation(rootSource), insertManyOperation(rootSource), updateOneOperation(rootSource), updateManyOperation(rootSource), deleteOneOperation(rootSource), deleteManyOperation(rootSource), ]; export const mutation = { insertOneOperation, insertManyOperation, updateOneOperation, updateManyOperation, deleteOneOperation, deleteManyOperation, defaults: defaultMutations, }; /** * Get list of all available presets applied to specified data source * * @name operationPresets.all * @api-category PrimaryAPI * @param rootSource The data source on which the operation is to be performed */ export function defaults(rootSource: MappedDataSource) { return [...query.defaults(rootSource), ...mutation.defaults(rootSource)]; }
the_stack
import * as React from 'react'; import * as tinymce from 'tinymce'; import 'tinymce/themes/silver/theme'; // Import the theme import 'tinymce/icons/default/icons'; // Import the icons require('../../../tinymce/skins/ui/oxide/skin.min.css'); require('../../../tinymce/skins/ui/oxide/content.min.css'); // Import plugins being used import 'tinymce/plugins/advlist'; import 'tinymce/plugins/anchor'; import 'tinymce/plugins/autolink'; import 'tinymce/plugins/autoresize'; import 'tinymce/plugins/charmap'; import 'tinymce/plugins/code'; import 'tinymce/plugins/fullpage'; import 'tinymce/plugins/fullscreen'; import 'tinymce/plugins/help'; import 'tinymce/plugins/image'; import 'tinymce/plugins/insertdatetime'; import 'tinymce/plugins/link'; import 'tinymce/plugins/lists'; import 'tinymce/plugins/media'; import 'tinymce/plugins/paste'; import 'tinymce/plugins/preview'; import 'tinymce/plugins/print'; import 'tinymce/plugins/searchreplace'; import 'tinymce/plugins/table'; import 'tinymce/plugins/textcolor'; import 'tinymce/plugins/visualblocks'; import 'tinymce/plugins/wordcount'; // redux related import { connect } from 'react-redux'; import { IApplicationState } from 'webparts/questions/redux/reducers/appReducer'; import { uploadImageToQuestionsAssets, searchPeoplePicker, ensureUserInSite } from 'webparts/questions/redux/actions/actions'; import { LogHelper, Icons } from 'utilities'; import { Editor } from '@tinymce/tinymce-react'; import { Callout, getTheme, FontWeights, mergeStyleSets, Text } from 'office-ui-fabric-react'; import { getId } from 'office-ui-fabric-react/lib/Utilities'; import { Persona, PersonaSize } from 'office-ui-fabric-react/lib/Persona'; import { DetailsList, IColumn, SelectionMode, Selection, CheckboxVisibility } from 'office-ui-fabric-react/lib/DetailsList'; import { IPeoplePickerEntity } from '@pnp/sp/profiles'; interface IConnectedDispatch { uploadImageToQuestionsAssets: (title: string, blobInfo: any, progress) => Promise<string>; searchPeoplePicker: (input: string, maxCount: number) => Promise<IPeoplePickerEntity[]>; ensureUserInSite: (email: string) => Promise<boolean>; } interface IConnectedState { } // map actions to properties so they can be invoked function mapStateToProps(state: IApplicationState, ownProps: any): IConnectedState { return { }; } //Map the actions to the properties of the Component. Making them available in this.props inside the component. const mapDispatchToProps = { uploadImageToQuestionsAssets, searchPeoplePicker, ensureUserInSite }; interface IRichTextEditorProps { id: string; questionTitle: string; value: string; placeholder: string; onTextChange(htmlValue: string, textValue: string): void; } interface IRichTextEditorState { mentioningState: boolean; mentionFilter: string; people: IPeoplePickerEntity[]; columns: IColumn[]; selectedPersona: IPeoplePickerEntity | null; editor: React.RefObject<any>; showUserWarning: boolean; } const theme = getTheme(); const styles = mergeStyleSets({ callout: { maxWidth: 400, }, header: { padding: '18px 24px 12px', }, title: [ theme.fonts.mediumPlus, { margin: 0, fontWeight: FontWeights.semibold, }, ], inner: { height: '100%', padding: '0 24px 20px', }, tooltip: { padding: '20px' }, subtext: [ theme.fonts.smallPlus, { margin: 0, fontWeight: FontWeights.semibold, }, ], subtextwarning: [ theme.fonts.small, { margin: 0, fontWeight: FontWeights.semilight, color: theme.palette.accent } ], link: [ theme.fonts.medium, { color: theme.palette.neutralPrimary, }, ], }); class RichTextEditorComponent extends React.Component<IRichTextEditorProps & IConnectedState & IConnectedDispatch, IRichTextEditorState> { private _mentionSelection: Selection; constructor(props: IRichTextEditorProps & IConnectedState & IConnectedDispatch) { super(props); tinymce.default.init({}); LogHelper.verbose(this.constructor.name, 'ctor', 'start'); this.state = { mentioningState: false, mentionFilter: '', people: [], columns: this.SetupColumns(), selectedPersona: null, editor: React.createRef(), showUserWarning: false }; this._mentionSelection = new Selection({ onSelectionChanged: () => { const person = this.GetMentionSelectionPersona(); this.setState({ selectedPersona: person, }, () => { LogHelper.info('RichTextEditor._mentionSelection', 'onSelectionChanged', `New person selected for mention (${this.state.selectedPersona && this.state.selectedPersona.DisplayText})`); if (this.state.selectedPersona !== null) this.CompleteMentionState(); }); }, }); } public render(): React.ReactElement<IRichTextEditorProps> { const { value, placeholder } = this.props; const { mentioningState, mentionFilter, showUserWarning } = this.state; const labelId: string = getId('callout-label'); const descriptionId: string = getId('callout-description'); return ( <div className="customTextEditor"> <Editor initialValue={value} init={{ extended_valid_elements : `span[style]`, link_assume_external_targets: true, placeholder: placeholder, convert_urls: false, relative_urls: false, images_upload_handler: this.images_upload_handler, autoresize_on_init: false, paste_data_images: true, skin: "oxide", skin_url: "https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.5.1/skins/ui/oxide", content_css: "https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.5.1/skins/content/default/content.min.css, https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.5.1/skins/ui/oxide/skin.min.css,https://cdnjs.cloudflare.com/ajax/libs/tinymce/5.5.1/skins/ui/oxide/content.min.css", plugins: [ 'autolink lists link image charmap print preview anchor', 'searchreplace visualblocks autoresize', 'insertdatetime media table paste textcolor' ], menubar: false, toolbar: 'undo redo formatselect bold italic underline forecolor backcolor table \ alignleft aligncenter alignright alignjustify \ bullist numlist indent outdent link image removeformat', statusbar: false, block_formats: 'Paragraph=p;Header 1=h1;Header 2=h2;Header 3=h3', setup: (editor) => this.setupTinyMce(editor) }} onEditorChange={(html, editor) => this.handleEditorChange(html, editor)} onKeyUp={this.handleKeyUp} onKeyDown={this.handleKeyDown} ref={this.state.editor} /> {mentioningState && ( <Callout className={styles.callout} ariaLabelledBy={labelId} ariaDescribedBy={descriptionId} role="alertdialog" gapSpace={0} target={`.customTextEditor`} onDismiss={() => this.ExitMentionState} setInitialFocus > <div className={styles.header}> <Text className={styles.subtext} id={labelId}> {this.IsPeopleSearchAllowed(mentionFilter) ? 'Suggestions' : 'Type more characters'} </Text> </div> <div className={styles.inner}> <DetailsList selection={this._mentionSelection} selectionPreservedOnEmptyClick={true} items={this.state.people} columns={this.state.columns} onRenderItemColumn={this.onRenderItemColumn} selectionMode={SelectionMode.single} isHeaderVisible={false} enterModalSelectionOnTouch={true} checkboxVisibility={CheckboxVisibility.hidden} /> </div> </Callout> )} {showUserWarning && ( <Callout className={styles.callout} ariaLabelledBy={labelId} ariaDescribedBy={descriptionId} role="alertdialog" gapSpace={0} target={`.customTextEditor`} > <div className={styles.tooltip}>The mentioned user is not a member of this site and will not be notified.</div> </Callout> )} </div> ); } private onRenderItemColumn = (item: IPeoplePickerEntity, index: number, column: IColumn): React.ReactNode => { switch (column.key) { case 'persona': return <div style={{ cursor: 'pointer' }}><Persona text={item.DisplayText} secondaryText={item.EntityData.Email} tertiaryText={item.EntityData.Department} showSecondaryText={true} size={PersonaSize.size32} /></div>; default: return <></>; } } private SetupColumns = (): IColumn[] => { const retVal: IColumn[] = []; const personaCol: IColumn = { key: "persona", minWidth: 250, name: '', ariaLabel: 'Persona' }; retVal.push(personaCol); return retVal; } private GetMentionSelectionPersona = (): IPeoplePickerEntity | null => { const selectionCount = this._mentionSelection.getSelectedCount(); LogHelper.info('RichTextEditor', 'GetMentionSelctionPersona', `Current selection count: ${selectionCount}`); switch (selectionCount) { case 1: return (this._mentionSelection.getSelection()[0] as IPeoplePickerEntity); default: return null; } } private EnterMentionState = () => { LogHelper.info('RichTextEditor', 'EnterMentionState', 'Now in a mentioning state...'); this.setState({ mentioningState: true, people: [] }); } private ContinueMentionState = (nextChar: string, reduce?: boolean) => { if (reduce === true) { //Special check to leave the mentioning state if we have deleted past the @ symbol if (this.state.mentionFilter.length <= 0) { this.ExitMentionState(); } else { const reduceString = this.state.mentionFilter.substring(0, this.state.mentionFilter.length - 1); LogHelper.info('RichTextEditor', 'ContinueMentionState', `Reducing mention: ${reduceString}`); this.setState({ mentionFilter: reduceString}, () => { this.MentionSearch(reduceString); }); } } else { const concatString = this.state.mentionFilter.concat(nextChar); LogHelper.info('RichTextEditor', 'ContinueMentionState', `Adding to mention: ${concatString}`); this.setState({ mentionFilter: concatString}, () => { this.MentionSearch(concatString); }); } } private CompleteMentionState = () => { LogHelper.info('RichTextEditor', 'CompleteMentionState', 'Completing the mentioning state...'); //Inject the selected persona into the RTE const { mentionFilter, editor, selectedPersona } = this.state; //Only do something if we have a valid persona if (selectedPersona !== null) { LogHelper.info('RichTextEditor', 'CompleteMentionState', `Mentioning ${selectedPersona.DisplayText}`); let content: string = editor.current.editor.getContent(); let mentionWithAt = `@${mentionFilter}`; let index = content.indexOf(mentionWithAt); if (index >= 0) { //let personaLink = `<div style="display: inline-block">&nbsp;</div><div style="display: inline-block"><a href="mailto:${selectedPersona.Email}">${selectedPersona.Title}</a></div><div style="display: inline-block">&shy;</div>`; let personaLink = `<span><a href="mailto:${selectedPersona.EntityData.Email}">${selectedPersona.DisplayText}</a></span><span>&shy;</span>`; let newContent: string = content.replace(mentionWithAt, personaLink); editor.current.editor.setContent(newContent); editor.current.editor.focus(); editor.current.editor.selection.select(editor.current.editor.getBody(), true); editor.current.editor.selection.collapse(false); //Check if the user is actually in the site to determine whether or not to display the user warning tooltip if (selectedPersona.EntityData.Email !== undefined) { this.props.ensureUserInSite(selectedPersona.EntityData.Email) .then((response: boolean) => { LogHelper.info('RichTextEditor', 'CompleteMentionState', `${selectedPersona.EntityData.Email} in this site? ${response}`); this.setState({ showUserWarning: !response }, () => { this.ExitMentionState(); if (this.state.showUserWarning) { setTimeout(() => { this.setState({ showUserWarning: false }); }, 7000); } }); }) .catch((reason) => { LogHelper.error('RichTextEditor', 'CompleteMentionState', reason); this.ExitMentionState(); }); } else { LogHelper.error('RichTextEditor', 'CompleteMentionState', 'NO email found for selected person...'); this.ExitMentionState(); } } } else { LogHelper.info('RichTextEditor', 'CompleteMentionState', 'No one to mention...'); this.ExitMentionState(); } } private ExitMentionState = () => { LogHelper.info('RichTextEditor', 'EnterMentionState', 'Exiting the mentioning state...'); this.setState({ mentioningState: false, mentionFilter: '', people: [] }); } private MentionSearch = (searchVal: string) => { LogHelper.info('RichTextEditor', 'MentionSearch', searchVal); if (this.IsPeopleSearchAllowed(searchVal)) { this.props.searchPeoplePicker(searchVal, 8) .then((peopleFound: IPeoplePickerEntity[]) => { LogHelper.info('RichTextEditor', 'MentionSearch', `Search found ${peopleFound.length} suggestions.`); //console.log(peopleFound); this.setState({ people: [...peopleFound]}); }) .catch((reason) => { LogHelper.error('RichTextEditor', 'MentionSearch', reason); }); } else { LogHelper.warning('RichTextEditor', 'MentionSearch', 'Not enough characters for search.'); this.setState({ people: []}); } } private IsPeopleSearchAllowed = (searchVal: string): boolean => { return (searchVal.length > 2); } private setupTinyMce = (editor) => { editor.ui.registry.addIcon('undo', Icons.ic_fluent_arrow_undo_24_regular); editor.ui.registry.addIcon('redo', Icons.ic_fluent_arrow_redo_24_regular); editor.ui.registry.addIcon('bold', Icons.ic_fluent_text_bold_24_regular); editor.ui.registry.addIcon('italic', Icons.ic_fluent_text_italic_24_regular); editor.ui.registry.addIcon('underline', Icons.ic_fluent_text_underline_24_regular); editor.ui.registry.addIcon('text-color', Icons.ic_fluent_text_color_24_filled); editor.ui.registry.addIcon('highlight-bg-color', Icons.ic_fluent_highlight_24_regular); editor.ui.registry.addIcon('color-picker', Icons.ic_fluent_color_24_regular); editor.ui.registry.addIcon('table', Icons.ic_fluent_table_24_regular); editor.ui.registry.addIcon('table-delete-table', Icons.ic_fluent_table_delete_24_regular); editor.ui.registry.addIcon('table-cell-properties', Icons.ic_fluent_table_settings_24_regular); editor.ui.registry.addIcon('table-merge-cells', Icons.ic_fluent_table_cells_merge_24_regular); editor.ui.registry.addIcon('table-split-cells', Icons.ic_fluent_table_cells_split_24_regular); editor.ui.registry.addIcon('table-delete-column', Icons.ic_fluent_table_column_delete_24_regular); editor.ui.registry.addIcon('table-row-properties', Icons.ic_fluent_table_settings_24_regular); editor.ui.registry.addIcon('table-insert-row-after', Icons.ic_fluent_table_insert_down_24_regular); editor.ui.registry.addIcon('table-insert-column-before', Icons.ic_fluent_table_insert_left_24_regular); editor.ui.registry.addIcon('table-insert-column-after', Icons.ic_fluent_table_insert_right_24_regular); editor.ui.registry.addIcon('table-insert-row-above', Icons.ic_fluent_table_insert_up_24_regular); editor.ui.registry.addIcon('cut-row', Icons.ic_fluent_cut_24_regular); editor.ui.registry.addIcon('duplicate-row', Icons.ic_fluent_copy_24_regular); editor.ui.registry.addIcon('paste-row-after', Icons.ic_fluent_table_move_down_24_regular); editor.ui.registry.addIcon('paste-row-before', Icons.ic_fluent_table_move_up_24_regular); editor.ui.registry.addIcon('table-delete-row', Icons.ic_fluent_table_row_delete_24_regular); editor.ui.registry.addIcon('align-left', Icons.ic_fluent_text_align_left_24_regular); editor.ui.registry.addIcon('align-center', Icons.ic_fluent_text_align_center_24_regular); editor.ui.registry.addIcon('align-right', Icons.ic_fluent_text_align_right_24_regular); editor.ui.registry.addIcon('align-justify', Icons.ic_fluent_text_align_justify_24_regular); editor.ui.registry.addIcon('list-bull-default', Icons.ic_fluent_text_bullet_list_24_regular); editor.ui.registry.addIcon('list-num-default', Icons.ic_fluent_text_number_format_24_regular); editor.ui.registry.addIcon('indent', Icons.ic_fluent_text_indent_increase_24_regular); editor.ui.registry.addIcon('outdent', Icons.ic_fluent_text_indent_decrease_24_regular); editor.ui.registry.addIcon('link', Icons.ic_fluent_link_24_regular); editor.ui.registry.addIcon('unlink', Icons.ic_fluent_link_remove_20_regular); editor.ui.registry.addIcon('new-tab', Icons.ic_fluent_open_24_regular); editor.ui.registry.addIcon('image', Icons.ic_fluent_image_24_regular); editor.ui.registry.addIcon('remove-formatting', Icons.ic_fluent_text_clear_formatting_24_regular); editor.ui.registry.addIcon('close', Icons.ic_fluent_dismiss_24_regular); editor.ui.registry.addIcon('lock', Icons.ic_fluent_lock_24_regular); } private handleEditorChange = (html, editor) => { let text = editor.getContent({ format: 'text' }); LogHelper.info('RichTextEditor', 'handleEditorChange', `HTML: ${html} \n Mention State: ${this.state.mentioningState}`); this.props.onTextChange(html, text); } private handleKeyDown = (a: KeyboardEvent, editor?: any) => { if (a.key.toLowerCase() === 'tab' || a.keyCode == 9) { if (!this.state.mentioningState) editor.execCommand( 'mceInsertContent', false, '&emsp;&emsp;' ); // inserts tab a.preventDefault(); } } private handleKeyUp = (a: KeyboardEvent, editor?: any) => { if (this.state.mentioningState) { LogHelper.info('RichTextEditor', 'handleKeyDown (in mention state)', `${a.key}:${a.code}:${a.type}:${a.returnValue}`); const charList = 'abcdefghijklmnopqrstuvwxyz0123456789 '; const key = a.key.toLowerCase(); // we are only interested in proceeding with alphanumeric keys and spaces or spaces if (charList.indexOf(key) === -1 && key.indexOf('shift') === -1) { if (key === 'backspace') { this.ContinueMentionState(a.key, true); } else if (key === 'enter' || key === 'return') { this.ExitMentionState(); } else if (key === 'tab' || key === 'arrowright') { if (this.state.people.length > 0) this._mentionSelection.setIndexSelected(0, true, true); //We want the selection to trigger a Completion, if necessary } else { this.ExitMentionState(); } } else { if (key.indexOf('shift') === -1) this.ContinueMentionState(a.key); //Essentially we want to drop shift from keystroke tracking } } else { if (a.key === '@') { //Special rules to prevent a mentioning state let content: string = editor.getContent({ format: "text" }); if (content === '@' || content.endsWith(' @') || content.endsWith('\n@')) { this.EnterMentionState(); } } } } private images_upload_handler = async (blobInfo, success, failure, progress) => { this.props.uploadImageToQuestionsAssets(this.props.questionTitle, blobInfo, (uploadProgress) => { progress(uploadProgress); }) .then((imageUrl) => { success(imageUrl); }) .catch((reason) => { LogHelper.error('RichTextEditor', 'images_upload_handler', reason); failure('There was a problem uploading the image, please try again!'); }); } } export default connect( mapStateToProps, mapDispatchToProps )(RichTextEditorComponent);
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { CharStream } from "antlr4ts/CharStream"; import { Lexer } from "antlr4ts/Lexer"; import { LexerATNSimulator } from "antlr4ts/atn/LexerATNSimulator"; import { NotNull } from "antlr4ts/Decorators"; import { Override } from "antlr4ts/Decorators"; import { RuleContext } from "antlr4ts/RuleContext"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; export class ExpressionAntlrLexer extends Lexer { public static readonly STRING_INTERPOLATION_START = 1; public static readonly PLUS = 2; public static readonly SUBSTRACT = 3; public static readonly NON = 4; public static readonly XOR = 5; public static readonly ASTERISK = 6; public static readonly SLASH = 7; public static readonly PERCENT = 8; public static readonly DOUBLE_EQUAL = 9; public static readonly NOT_EQUAL = 10; public static readonly SINGLE_AND = 11; public static readonly DOUBLE_AND = 12; public static readonly DOUBLE_VERTICAL_CYLINDER = 13; public static readonly LESS_THAN = 14; public static readonly MORE_THAN = 15; public static readonly LESS_OR_EQUAl = 16; public static readonly MORE_OR_EQUAL = 17; public static readonly OPEN_BRACKET = 18; public static readonly CLOSE_BRACKET = 19; public static readonly DOT = 20; public static readonly OPEN_SQUARE_BRACKET = 21; public static readonly CLOSE_SQUARE_BRACKET = 22; public static readonly OPEN_CURLY_BRACKET = 23; public static readonly CLOSE_CURLY_BRACKET = 24; public static readonly COMMA = 25; public static readonly COLON = 26; public static readonly ARROW = 27; public static readonly NULL_COALESCE = 28; public static readonly QUESTION_MARK = 29; public static readonly NUMBER = 30; public static readonly WHITESPACE = 31; public static readonly IDENTIFIER = 32; public static readonly NEWLINE = 33; public static readonly STRING = 34; public static readonly INVALID_TOKEN_DEFAULT_MODE = 35; public static readonly TEMPLATE = 36; public static readonly ESCAPE_CHARACTER = 37; public static readonly TEXT_CONTENT = 38; public static readonly STRING_INTERPOLATION_MODE = 1; // tslint:disable:no-trailing-whitespace public static readonly channelNames: string[] = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN", ]; // tslint:disable:no-trailing-whitespace public static readonly modeNames: string[] = [ "DEFAULT_MODE", "STRING_INTERPOLATION_MODE", ]; public static readonly ruleNames: string[] = [ "LETTER", "DIGIT", "OBJECT_DEFINITION", "STRING_INTERPOLATION_START", "PLUS", "SUBSTRACT", "NON", "XOR", "ASTERISK", "SLASH", "PERCENT", "DOUBLE_EQUAL", "NOT_EQUAL", "SINGLE_AND", "DOUBLE_AND", "DOUBLE_VERTICAL_CYLINDER", "LESS_THAN", "MORE_THAN", "LESS_OR_EQUAl", "MORE_OR_EQUAL", "OPEN_BRACKET", "CLOSE_BRACKET", "DOT", "OPEN_SQUARE_BRACKET", "CLOSE_SQUARE_BRACKET", "OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "COMMA", "COLON", "ARROW", "NULL_COALESCE", "QUESTION_MARK", "NUMBER", "WHITESPACE", "IDENTIFIER", "NEWLINE", "STRING", "INVALID_TOKEN_DEFAULT_MODE", "STRING_INTERPOLATION_END", "TEMPLATE", "ESCAPE_CHARACTER", "TEXT_CONTENT", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, "'+'", "'-'", "'!'", "'^'", "'*'", "'/'", "'%'", "'=='", undefined, "'&'", "'&&'", "'||'", "'<'", "'>'", "'<='", "'>='", "'('", "')'", "'.'", "'['", "']'", "'{'", "'}'", "','", "':'", "'=>'", "'??'", "'?'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "STRING_INTERPOLATION_START", "PLUS", "SUBSTRACT", "NON", "XOR", "ASTERISK", "SLASH", "PERCENT", "DOUBLE_EQUAL", "NOT_EQUAL", "SINGLE_AND", "DOUBLE_AND", "DOUBLE_VERTICAL_CYLINDER", "LESS_THAN", "MORE_THAN", "LESS_OR_EQUAl", "MORE_OR_EQUAL", "OPEN_BRACKET", "CLOSE_BRACKET", "DOT", "OPEN_SQUARE_BRACKET", "CLOSE_SQUARE_BRACKET", "OPEN_CURLY_BRACKET", "CLOSE_CURLY_BRACKET", "COMMA", "COLON", "ARROW", "NULL_COALESCE", "QUESTION_MARK", "NUMBER", "WHITESPACE", "IDENTIFIER", "NEWLINE", "STRING", "INVALID_TOKEN_DEFAULT_MODE", "TEMPLATE", "ESCAPE_CHARACTER", "TEXT_CONTENT", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(ExpressionAntlrLexer._LITERAL_NAMES, ExpressionAntlrLexer._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return ExpressionAntlrLexer.VOCABULARY; } // tslint:enable:no-trailing-whitespace ignoreWS = true; // usually we ignore whitespace, but inside stringInterpolation, whitespace is significant constructor(input: CharStream) { super(input); this._interp = new LexerATNSimulator(ExpressionAntlrLexer._ATN, this); } // @Override public get grammarFileName(): string { return "ExpressionAntlrLexer.g4"; } // @Override public get ruleNames(): string[] { return ExpressionAntlrLexer.ruleNames; } // @Override public get serializedATN(): string { return ExpressionAntlrLexer._serializedATN; } // @Override public get channelNames(): string[] { return ExpressionAntlrLexer.channelNames; } // @Override public get modeNames(): string[] { return ExpressionAntlrLexer.modeNames; } // @Override public action(_localctx: RuleContext, ruleIndex: number, actionIndex: number): void { switch (ruleIndex) { case 3: this.STRING_INTERPOLATION_START_action(_localctx, actionIndex); break; case 38: this.STRING_INTERPOLATION_END_action(_localctx, actionIndex); break; } } private STRING_INTERPOLATION_START_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 0: this.ignoreWS = false; break; } } private STRING_INTERPOLATION_END_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 1: this.ignoreWS = true; break; } } // @Override public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { switch (ruleIndex) { case 33: return this.WHITESPACE_sempred(_localctx, predIndex); } return true; } private WHITESPACE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 0: return this.ignoreWS; } return true; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02(\u010F\b\x01" + "\b\x01\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06" + "\t\x06\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f" + "\x04\r\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04" + "\x12\t\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04" + "\x17\t\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04" + "\x1C\t\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x04\x1F\t\x1F\x04 \t \x04!\t!\x04" + "\"\t\"\x04#\t#\x04$\t$\x04%\t%\x04&\t&\x04\'\t\'\x04(\t(\x04)\t)\x04*" + "\t*\x04+\t+\x03\x02\x03\x02\x03\x03\x03\x03\x03\x04\x03\x04\x03\x04\x03" + "\x04\x05\x04a\n\x04\x03\x04\x03\x04\x03\x04\x03\x04\x06\x04g\n\x04\r\x04" + "\x0E\x04h\x07\x04k\n\x04\f\x04\x0E\x04n\v\x04\x03\x04\x03\x04\x03\x05" + "\x03\x05\x03\x05\x03\x05\x03\x05\x03\x06\x03\x06\x03\x07\x03\x07\x03\b" + "\x03\b\x03\t\x03\t\x03\n\x03\n\x03\v\x03\v\x03\f\x03\f\x03\r\x03\r\x03" + "\r\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x05\x0E\x8C\n\x0E\x03\x0F\x03\x0F\x03" + "\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03\x12\x03\x12\x03\x13\x03" + "\x13\x03\x14\x03\x14\x03\x14\x03\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03" + "\x17\x03\x17\x03\x18\x03\x18\x03\x19\x03\x19\x03\x1A\x03\x1A\x03\x1B\x03" + "\x1B\x03\x1C\x03\x1C\x03\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1F\x03\x1F\x03" + "\x1F\x03 \x03 \x03 \x03!\x03!\x03\"\x06\"\xBB\n\"\r\"\x0E\"\xBC\x03\"" + "\x03\"\x06\"\xC1\n\"\r\"\x0E\"\xC2\x05\"\xC5\n\"\x03#\x03#\x03#\x03#\x03" + "#\x03$\x03$\x03$\x03$\x03$\x05$\xD1\n$\x03$\x03$\x03$\x07$\xD6\n$\f$\x0E" + "$\xD9\v$\x03%\x05%\xDC\n%\x03%\x03%\x03%\x03%\x03&\x03&\x03&\x03&\x07" + "&\xE6\n&\f&\x0E&\xE9\v&\x03&\x03&\x03&\x03&\x03&\x07&\xF0\n&\f&\x0E&\xF3" + "\v&\x03&\x05&\xF6\n&\x03\'\x03\'\x03(\x03(\x03(\x03(\x03(\x03(\x03)\x03" + ")\x03)\x03)\x03)\x06)\u0105\n)\r)\x0E)\u0106\x03)\x03)\x03*\x03*\x03*" + "\x03+\x03+\x04\xE7\xF1\x02\x02,\x04\x02\x02\x06\x02\x02\b\x02\x02\n\x02" + "\x03\f\x02\x04\x0E\x02\x05\x10\x02\x06\x12\x02\x07\x14\x02\b\x16\x02\t" + "\x18\x02\n\x1A\x02\v\x1C\x02\f\x1E\x02\r \x02\x0E\"\x02\x0F$\x02\x10&" + "\x02\x11(\x02\x12*\x02\x13,\x02\x14.\x02\x150\x02\x162\x02\x174\x02\x18" + "6\x02\x198\x02\x1A:\x02\x1B<\x02\x1C>\x02\x1D@\x02\x1EB\x02\x1FD\x02 " + "F\x02!H\x02\"J\x02#L\x02$N\x02%P\x02\x02R\x02&T\x02\'V\x02(\x04\x02\x03" + "\f\x04\x02C\\c|\x03\x022;\t\x02\f\f\x0F\x0F$$))bb}}\x7F\x7F\x06\x02\v" + "\v\"\"\xA2\xA2\uFF01\uFF01\x05\x02%%BBaa\x04\x02))^^\x03\x02))\x04\x02" + "$$^^\x03\x02$$\x04\x02&&bb\x02\u0123\x02\n\x03\x02\x02\x02\x02\f\x03\x02" + "\x02\x02\x02\x0E\x03\x02\x02\x02\x02\x10\x03\x02\x02\x02\x02\x12\x03\x02" + "\x02\x02\x02\x14\x03\x02\x02\x02\x02\x16\x03\x02\x02\x02\x02\x18\x03\x02" + "\x02\x02\x02\x1A\x03\x02\x02\x02\x02\x1C\x03\x02\x02\x02\x02\x1E\x03\x02" + "\x02\x02\x02 \x03\x02\x02\x02\x02\"\x03\x02\x02\x02\x02$\x03\x02\x02\x02" + "\x02&\x03\x02\x02\x02\x02(\x03\x02\x02\x02\x02*\x03\x02\x02\x02\x02,\x03" + "\x02\x02\x02\x02.\x03\x02\x02\x02\x020\x03\x02\x02\x02\x022\x03\x02\x02" + "\x02\x024\x03\x02\x02\x02\x026\x03\x02\x02\x02\x028\x03\x02\x02\x02\x02" + ":\x03\x02\x02\x02\x02<\x03\x02\x02\x02\x02>\x03\x02\x02\x02\x02@\x03\x02" + "\x02\x02\x02B\x03\x02\x02\x02\x02D\x03\x02\x02\x02\x02F\x03\x02\x02\x02" + "\x02H\x03\x02\x02\x02\x02J\x03\x02\x02\x02\x02L\x03\x02\x02\x02\x02N\x03" + "\x02\x02\x02\x03P\x03\x02\x02\x02\x03R\x03\x02\x02\x02\x03T\x03\x02\x02" + "\x02\x03V\x03\x02\x02\x02\x04X\x03\x02\x02\x02\x06Z\x03\x02\x02\x02\b" + "\\\x03\x02\x02\x02\nq\x03\x02\x02\x02\fv\x03\x02\x02\x02\x0Ex\x03\x02" + "\x02\x02\x10z\x03\x02\x02\x02\x12|\x03\x02\x02\x02\x14~\x03\x02\x02\x02" + "\x16\x80\x03\x02\x02\x02\x18\x82\x03\x02\x02\x02\x1A\x84\x03\x02\x02\x02" + "\x1C\x8B\x03\x02\x02\x02\x1E\x8D\x03\x02\x02\x02 \x8F\x03\x02\x02\x02" + "\"\x92\x03\x02\x02\x02$\x95\x03\x02\x02\x02&\x97\x03\x02\x02\x02(\x99" + "\x03\x02\x02\x02*\x9C\x03\x02\x02\x02,\x9F\x03\x02\x02\x02.\xA1\x03\x02" + "\x02\x020\xA3\x03\x02\x02\x022\xA5\x03\x02\x02\x024\xA7\x03\x02\x02\x02" + "6\xA9\x03\x02\x02\x028\xAB\x03\x02\x02\x02:\xAD\x03\x02\x02\x02<\xAF\x03" + "\x02\x02\x02>\xB1\x03\x02\x02\x02@\xB4\x03\x02\x02\x02B\xB7\x03\x02\x02" + "\x02D\xBA\x03\x02\x02\x02F\xC6\x03\x02\x02\x02H\xD0\x03\x02\x02\x02J\xDB" + "\x03\x02\x02\x02L\xF5\x03\x02\x02\x02N\xF7\x03\x02\x02\x02P\xF9\x03\x02" + "\x02\x02R\xFF\x03\x02\x02\x02T\u010A\x03\x02\x02\x02V\u010D\x03\x02\x02" + "\x02XY\t\x02\x02\x02Y\x05\x03\x02\x02\x02Z[\t\x03\x02\x02[\x07\x03\x02" + "\x02\x02\\l\x07}\x02\x02]k\x05F#\x02^a\x05H$\x02_a\x05L&\x02`^\x03\x02" + "\x02\x02`_\x03\x02\x02\x02ab\x03\x02\x02\x02bf\x07<\x02\x02cg\x05L&\x02" + "dg\n\x04\x02\x02eg\x05\b\x04\x02fc\x03\x02\x02\x02fd\x03\x02\x02\x02f" + "e\x03\x02\x02\x02gh\x03\x02\x02\x02hf\x03\x02\x02\x02hi\x03\x02\x02\x02" + "ik\x03\x02\x02\x02j]\x03\x02\x02\x02j`\x03\x02\x02\x02kn\x03\x02\x02\x02" + "lj\x03\x02\x02\x02lm\x03\x02\x02\x02mo\x03\x02\x02\x02nl\x03\x02\x02\x02" + "op\x07\x7F\x02\x02p\t\x03\x02\x02\x02qr\x07b\x02\x02rs\b\x05\x02\x02s" + "t\x03\x02\x02\x02tu\b\x05\x03\x02u\v\x03\x02\x02\x02vw\x07-\x02\x02w\r" + "\x03\x02\x02\x02xy\x07/\x02\x02y\x0F\x03\x02\x02\x02z{\x07#\x02\x02{\x11" + "\x03\x02\x02\x02|}\x07`\x02\x02}\x13\x03\x02\x02\x02~\x7F\x07,\x02\x02" + "\x7F\x15\x03\x02\x02\x02\x80\x81\x071\x02\x02\x81\x17\x03\x02\x02\x02" + "\x82\x83\x07\'\x02\x02\x83\x19\x03\x02\x02\x02\x84\x85\x07?\x02\x02\x85" + "\x86\x07?\x02\x02\x86\x1B\x03\x02\x02\x02\x87\x88\x07#\x02\x02\x88\x8C" + "\x07?\x02\x02\x89\x8A\x07>\x02\x02\x8A\x8C\x07@\x02\x02\x8B\x87\x03\x02" + "\x02\x02\x8B\x89\x03\x02\x02\x02\x8C\x1D\x03\x02\x02\x02\x8D\x8E\x07(" + "\x02\x02\x8E\x1F\x03\x02\x02\x02\x8F\x90\x07(\x02\x02\x90\x91\x07(\x02" + "\x02\x91!\x03\x02\x02\x02\x92\x93\x07~\x02\x02\x93\x94\x07~\x02\x02\x94" + "#\x03\x02\x02\x02\x95\x96\x07>\x02\x02\x96%\x03\x02\x02\x02\x97\x98\x07" + "@\x02\x02\x98\'\x03\x02\x02\x02\x99\x9A\x07>\x02\x02\x9A\x9B\x07?\x02" + "\x02\x9B)\x03\x02\x02\x02\x9C\x9D\x07@\x02\x02\x9D\x9E\x07?\x02\x02\x9E" + "+\x03\x02\x02\x02\x9F\xA0\x07*\x02\x02\xA0-\x03\x02\x02\x02\xA1\xA2\x07" + "+\x02\x02\xA2/\x03\x02\x02\x02\xA3\xA4\x070\x02\x02\xA41\x03\x02\x02\x02" + "\xA5\xA6\x07]\x02\x02\xA63\x03\x02\x02\x02\xA7\xA8\x07_\x02\x02\xA85\x03" + "\x02\x02\x02\xA9\xAA\x07}\x02\x02\xAA7\x03\x02\x02\x02\xAB\xAC\x07\x7F" + "\x02\x02\xAC9\x03\x02\x02\x02\xAD\xAE\x07.\x02\x02\xAE;\x03\x02\x02\x02" + "\xAF\xB0\x07<\x02\x02\xB0=\x03\x02\x02\x02\xB1\xB2\x07?\x02\x02\xB2\xB3" + "\x07@\x02\x02\xB3?\x03\x02\x02\x02\xB4\xB5\x07A\x02\x02\xB5\xB6\x07A\x02" + "\x02\xB6A\x03\x02\x02\x02\xB7\xB8\x07A\x02\x02\xB8C\x03\x02\x02\x02\xB9" + "\xBB\x05\x06\x03\x02\xBA\xB9\x03\x02\x02\x02\xBB\xBC\x03\x02\x02\x02\xBC" + "\xBA\x03\x02\x02\x02\xBC\xBD\x03\x02\x02\x02\xBD\xC4\x03\x02\x02\x02\xBE" + "\xC0\x070\x02\x02\xBF\xC1\x05\x06\x03\x02\xC0\xBF\x03\x02\x02\x02\xC1" + "\xC2\x03\x02\x02\x02\xC2\xC0\x03\x02\x02\x02\xC2\xC3\x03\x02\x02\x02\xC3" + "\xC5\x03\x02\x02\x02\xC4\xBE\x03\x02\x02\x02\xC4\xC5\x03\x02\x02\x02\xC5" + "E\x03\x02\x02\x02\xC6\xC7\t\x05\x02\x02\xC7\xC8\x06#\x02\x02\xC8\xC9\x03" + "\x02\x02\x02\xC9\xCA\b#\x04\x02\xCAG\x03\x02\x02\x02\xCB\xD1\x05\x04\x02" + "\x02\xCC\xD1\t\x06\x02\x02\xCD\xCE\x07B\x02\x02\xCE\xD1\x07B\x02\x02\xCF" + "\xD1\x04&\'\x02\xD0\xCB\x03\x02\x02\x02\xD0\xCC\x03\x02\x02\x02\xD0\xCD" + "\x03\x02\x02\x02\xD0\xCF\x03\x02\x02\x02\xD1\xD7\x03\x02\x02\x02\xD2\xD6" + "\x05\x04\x02\x02\xD3\xD6\x05\x06\x03\x02\xD4\xD6\x07a\x02\x02\xD5\xD2" + "\x03\x02\x02\x02\xD5\xD3\x03\x02\x02\x02\xD5\xD4\x03\x02\x02\x02\xD6\xD9" + "\x03\x02\x02\x02\xD7\xD5\x03\x02\x02\x02\xD7\xD8\x03\x02\x02\x02\xD8I" + "\x03\x02\x02\x02\xD9\xD7\x03\x02\x02\x02\xDA\xDC\x07\x0F\x02\x02\xDB\xDA" + "\x03\x02\x02\x02\xDB\xDC\x03\x02\x02\x02\xDC\xDD\x03\x02\x02\x02\xDD\xDE" + "\x07\f\x02\x02\xDE\xDF\x03\x02\x02\x02\xDF\xE0\b%\x04\x02\xE0K\x03\x02" + "\x02\x02\xE1\xE7\x07)\x02\x02\xE2\xE3\x07^\x02\x02\xE3\xE6\t\x07\x02\x02" + "\xE4\xE6\n\b\x02\x02\xE5\xE2\x03\x02\x02\x02\xE5\xE4\x03\x02\x02\x02\xE6" + "\xE9\x03\x02\x02\x02\xE7\xE8\x03\x02\x02\x02\xE7\xE5\x03\x02\x02\x02\xE8" + "\xEA\x03\x02\x02\x02\xE9\xE7\x03\x02\x02\x02\xEA\xF6\x07)\x02\x02\xEB" + "\xF1\x07$\x02\x02\xEC\xED\x07^\x02\x02\xED\xF0\t\t\x02\x02\xEE\xF0\n\n" + "\x02\x02\xEF\xEC\x03\x02\x02\x02\xEF\xEE\x03\x02\x02\x02\xF0\xF3\x03\x02" + "\x02\x02\xF1\xF2\x03\x02\x02\x02\xF1\xEF\x03\x02\x02\x02\xF2\xF4\x03\x02" + "\x02\x02\xF3\xF1\x03\x02\x02\x02\xF4\xF6\x07$\x02\x02\xF5\xE1\x03\x02" + "\x02\x02\xF5\xEB\x03\x02\x02\x02\xF6M\x03\x02\x02\x02\xF7\xF8\v\x02\x02" + "\x02\xF8O\x03\x02\x02\x02\xF9\xFA\x07b\x02\x02\xFA\xFB\b(\x05\x02\xFB" + "\xFC\x03\x02\x02\x02\xFC\xFD\b(\x06\x02\xFD\xFE\b(\x07\x02\xFEQ\x03\x02" + "\x02\x02\xFF\u0100\x07&\x02\x02\u0100\u0104\x07}\x02\x02\u0101\u0105\x05" + "L&\x02\u0102\u0105\x05\b\x04\x02\u0103\u0105\n\x04\x02\x02\u0104\u0101" + "\x03\x02\x02\x02\u0104\u0102\x03\x02\x02\x02\u0104\u0103\x03\x02\x02\x02" + "\u0105\u0106\x03\x02\x02\x02\u0106\u0104\x03\x02\x02\x02\u0106\u0107\x03" + "\x02\x02\x02\u0107\u0108\x03\x02\x02\x02\u0108\u0109\x07\x7F\x02\x02\u0109" + "S\x03\x02\x02\x02\u010A\u010B\x07^\x02\x02\u010B\u010C\t\v\x02\x02\u010C" + "U\x03\x02\x02\x02\u010D\u010E\v\x02\x02\x02\u010EW\x03\x02\x02\x02\x18" + "\x02\x03`fhjl\x8B\xBC\xC2\xC4\xD0\xD5\xD7\xDB\xE5\xE7\xEF\xF1\xF5\u0104" + "\u0106\b\x03\x05\x02\x07\x03\x02\b\x02\x02\x03(\x03\t\x03\x02\x06\x02" + "\x02"; public static __ATN: ATN; public static get _ATN(): ATN { if (!ExpressionAntlrLexer.__ATN) { ExpressionAntlrLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(ExpressionAntlrLexer._serializedATN)); } return ExpressionAntlrLexer.__ATN; } }
the_stack
import type {Mutable, Proto} from "@swim/util"; import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "../fastener/Fastener"; /** @public */ export interface TimerInit extends FastenerInit { extends?: {prototype: Timer<any>} | string | boolean | null; delay?: number; fire?(): void; willSchedule?(delay: number): void; didSchedule?(delay: number): void; willCancel?(): void; didCancel?(): void; willExpire?(): void; didExpire?(): void; setTimeout?(callback: () => void, delay: number): unknown; clearTimeout?(timeout: unknown): void; } /** @public */ export type TimerDescriptor<O = unknown, I = {}> = ThisType<Timer<O> & I> & TimerInit & Partial<I>; /** @public */ export interface TimerClass<F extends Timer<any> = Timer<any>> extends FastenerClass<F> { } /** @public */ export interface TimerFactory<F extends Timer<any> = Timer<any>> extends TimerClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TimerFactory<F> & I; define<O>(className: string, descriptor: TimerDescriptor<O>): TimerFactory<Timer<any>>; define<O, I = {}>(className: string, descriptor: {implements: unknown} & TimerDescriptor<O, I>): TimerFactory<Timer<any> & I>; <O>(descriptor: TimerDescriptor<O>): PropertyDecorator; <O, I = {}>(descriptor: {implements: unknown} & TimerDescriptor<O, I>): PropertyDecorator; } /** @public */ export interface Timer<O = unknown> extends Fastener<O> { /** @override */ get fastenerType(): Proto<Timer<any>>; /** @protected @override */ onInherit(superFastener: Fastener): void; readonly delay: number; /** @internal @protected */ initDelay(delay: number): void; setDelay(delay: number): void; readonly deadline: number | undefined; get elapsed(): number | undefined; get remaining(): number | undefined; /** @internal @protected */ fire(): void; get scheduled(): boolean; schedule(delay?: number): void; throttle(delay?: number): void; debounce(delay?: number): void; /** @protected */ willSchedule(delay: number): void; /** @protected */ onSchedule(delay: number): void; /** @protected */ didSchedule(delay: number): void; cancel(): void; /** @protected */ willCancel(): void; /** @protected */ onCancel(): void; /** @protected */ didCancel(): void; /** @internal @protected */ expire(): void; /** @protected */ willExpire(): void; /** @protected */ onExpire(): void; /** @protected */ didExpire(): void; /** @internal */ readonly timeout: unknown | undefined; /** @internal @protected */ setTimeout(callback: () => void, delay: number): unknown; /** @internal @protected */ clearTimeout(timeoutId: unknown): void; /** @override @protected */ onUnmount(): void; /** @internal @override */ get lazy(): boolean; // prototype property /** @internal @override */ get static(): string | boolean; // prototype property } /** @public */ export const Timer = (function (_super: typeof Fastener) { const Timer: TimerFactory = _super.extend("Timer"); Object.defineProperty(Timer.prototype, "fastenerType", { get: function (this: Timer): Proto<Timer<any>> { return Timer; }, configurable: true, }); Timer.prototype.onInherit = function (this: Timer, superFastener: Timer): void { this.setDelay(superFastener.delay); }; Timer.prototype.initDelay = function (this: Timer, delay: number): void { (this as Mutable<typeof this>).delay = Math.max(0, delay); }; Timer.prototype.setDelay = function (this: Timer, delay: number): void { (this as Mutable<typeof this>).delay = Math.max(0, delay); }; Object.defineProperty(Timer.prototype, "elapsed", { get: function (this: Timer): number | undefined { const deadline = this.deadline; if (deadline !== void 0) { return Math.max(0, performance.now() - (deadline - this.delay)); } else { return void 0; } }, configurable: true, }); Object.defineProperty(Timer.prototype, "remaining", { get: function (this: Timer): number | undefined { const deadline = this.deadline; if (deadline !== void 0) { return Math.max(0, deadline - performance.now()); } else { return void 0; } }, configurable: true, }); Timer.prototype.fire = function (this: Timer): void { // hook }; Object.defineProperty(Timer.prototype, "scheduled", { get: function (this: Timer): boolean { return this.timeout !== void 0; }, configurable: true, }); Timer.prototype.schedule = function (this: Timer, delay?: number): void { let timeout = this.timeout; if (timeout === void 0) { if (delay === void 0) { delay = this.delay; } else { this.setDelay(delay); } this.willSchedule(delay); (this as Mutable<typeof this>).deadline = performance.now() + delay; timeout = this.setTimeout(this.expire.bind(this), delay); (this as Mutable<typeof this>).timeout = timeout; this.onSchedule(delay); this.didSchedule(delay); } else { throw new Error("timer already scheduled; call throttle or debounce to reschedule"); } }; Timer.prototype.throttle = function (this: Timer, delay?: number): void { let timeout = this.timeout; if (timeout === void 0) { if (delay === void 0) { delay = this.delay; } else { this.setDelay(delay); } this.willSchedule(delay); (this as Mutable<typeof this>).deadline = performance.now() + delay; timeout = this.setTimeout(this.expire.bind(this), delay); (this as Mutable<typeof this>).timeout = timeout; this.onSchedule(delay); this.didSchedule(delay); } }; Timer.prototype.debounce = function (this: Timer, delay?: number): void { let timeout = this.timeout; if (timeout !== void 0) { this.willCancel(); (this as Mutable<typeof this>).timeout = void 0; this.clearTimeout(timeout); this.onCancel(); this.didCancel(); } if (delay === void 0) { delay = this.delay; } else { this.setDelay(delay); } this.willSchedule(delay); (this as Mutable<typeof this>).deadline = performance.now() + delay; timeout = this.setTimeout(this.expire.bind(this), delay); (this as Mutable<typeof this>).timeout = timeout; this.onSchedule(delay); this.didSchedule(delay); }; Timer.prototype.willSchedule = function (this: Timer, delay: number): void { // hook }; Timer.prototype.onSchedule = function (this: Timer, delay: number): void { // hook }; Timer.prototype.didSchedule = function (this: Timer, delay: number): void { // hook }; Timer.prototype.cancel = function (this: Timer): void { const timeout = this.timeout; if (timeout !== void 0) { this.willCancel(); (this as Mutable<typeof this>).timeout = void 0; (this as Mutable<typeof this>).deadline = void 0; this.clearTimeout(timeout); this.onCancel(); this.didCancel(); } }; Timer.prototype.willCancel = function (this: Timer): void { // hook }; Timer.prototype.onCancel = function (this: Timer): void { // hook }; Timer.prototype.didCancel = function (this: Timer): void { // hook }; Timer.prototype.expire = function (this: Timer): void { (this as Mutable<typeof this>).timeout = void 0; (this as Mutable<typeof this>).deadline = void 0; this.willExpire(); this.fire(); this.onExpire(); this.didExpire(); }; Timer.prototype.willExpire = function (this: Timer): void { // hook }; Timer.prototype.onExpire = function (this: Timer): void { // hook }; Timer.prototype.didExpire = function (this: Timer): void { // hook }; Timer.prototype.setTimeout = function (this: Timer, callback: () => void, delay: number): unknown { return setTimeout(callback, delay); }; Timer.prototype.clearTimeout = function (this: Timer, timeout: unknown): void { clearTimeout(timeout as any); }; Timer.prototype.onUnmount = function (this: Timer): void { _super.prototype.onUnmount.call(this); this.cancel(); }; Object.defineProperty(Timer.prototype, "lazy", { get: function (this: Timer): boolean { return false; }, configurable: true, }); Object.defineProperty(Timer.prototype, "static", { get: function (this: Timer): string | boolean { return true; }, configurable: true, }); Timer.construct = function <F extends Timer<any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).delay = 0; (fastener as Mutable<typeof fastener>).deadline = 0; (fastener as Mutable<typeof fastener>).timeout = void 0; (fastener as Mutable<typeof fastener>).expire = fastener.expire.bind(fastener); return fastener; }; Timer.define = function <O>(className: string, descriptor: TimerDescriptor<O>): TimerFactory<Timer<any>> { let superClass = descriptor.extends as TimerFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const delay = descriptor.delay; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.delay; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: Timer<any>}, fastener: Timer<O> | null, owner: O): Timer<O> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (delay !== void 0) { fastener.initDelay(delay); } return fastener; }; return fastenerClass; }; return Timer; })(Fastener);
the_stack
* The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ export const DIFF_DELETE = -1; export const DIFF_INSERT = 1; export const DIFF_EQUAL = 0; export type DiffTuple = [number, string]; /* tslint:disable:variable-name no-conditional-assignment */ /** * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @return {Array} Array of diff tuples. */ export function diffStrings(text1: string, text2: string): DiffTuple[] { // Check for equality (speedup). if (text1 === text2) { if (text1) { return [[DIFF_EQUAL, text1]]; } return []; } // Trim off common prefix (speedup). let commonlength = diff_commonPrefix(text1, text2); const commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = diff_commonSuffix(text1, text2); const commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block. const diffs = diff_compute_(text1, text2); // Restore the prefix and suffix. if (commonprefix) { diffs.unshift([DIFF_EQUAL, commonprefix]); } if (commonsuffix) { diffs.push([DIFF_EQUAL, commonsuffix]); } diff_cleanupMerge(diffs); return diffs; }; /** * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @return {Array} Array of diff tuples. */ function diff_compute_(text1: string, text2: string): DiffTuple[] { let diffs: DiffTuple[]; if (!text1) { // Just add some text (speedup). return [[DIFF_INSERT, text2]]; } if (!text2) { // Just delete some text (speedup). return [[DIFF_DELETE, text1]]; } const longtext = text1.length > text2.length ? text1 : text2; const shorttext = text1.length > text2.length ? text2 : text1; const i = longtext.indexOf(shorttext); if (i !== -1) { // Shorter text is inside the longer text (speedup). diffs = [[DIFF_INSERT, longtext.substring(0, i)], [DIFF_EQUAL, shorttext], [DIFF_INSERT, longtext.substring(i + shorttext.length)]]; // Swap insertions for deletions if diff is reversed. if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length === 1) { // Single character string. // After the previous speedup, the character can't be an equality. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; } // Check to see if the problem can be split in two. const hm = diff_halfMatch_(text1, text2); if (hm) { // A half-match was found, sort out the return data. const text1_a = hm[0]; const text1_b = hm[1]; const text2_a = hm[2]; const text2_b = hm[3]; const mid_common = hm[4]; // Send both pairs off for separate processing. const diffs_a = diffStrings(text1_a, text2_a); const diffs_b = diffStrings(text1_b, text2_b); // Merge the results. return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b); } return diff_bisect_(text1, text2); }; /** * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its constiations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @return {Array} Array of diff tuples. * @private */ function diff_bisect_(text1: string, text2: string): DiffTuple[] { // Cache the text lengths to prevent multiple calls. const text1_length = text1.length; const text2_length = text2.length; const max_d = Math.ceil((text1_length + text2_length) / 2); const v_offset = max_d; const v_length = 2 * max_d; const v1 = new Array<number>(v_length); const v2 = new Array<number>(v_length); // Setting all elements to -1 is faster in Chrome & Firefox than mixing // integers and undefined. for (let x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; const delta = text1_length - text2_length; // If the total number of characters is odd, then the front path will collide // with the reverse path. const front = (delta % 2 !== 0); // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. let k1start = 0; let k1end = 0; let k2start = 0; let k2end = 0; for (let d = 0; d < max_d; d++) { // Walk the front path one step. for (let k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { const k1_offset = v_offset + k1; let x1: number; if (k1 === -d || (k1 !== d && v1[k1_offset - 1] < v1[k1_offset + 1])) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } let y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) === text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2_length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { const k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] !== -1) { // Mirror x2 onto top-left coordinate system. const x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit_(text1, text2, x1, y1); } } } } // Walk the reverse path one step. for (let k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { const k2_offset = v_offset + k2; let x2: number; if (k2 === -d || (k2 !== d && v2[k2_offset - 1] < v2[k2_offset + 1])) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } let y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) === text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2_length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { const k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] !== -1) { const x1 = v1[k1_offset]; const y1 = v_offset + x1 - k1_offset; // Mirror x2 onto top-left coordinate system. x2 = text1_length - x2; if (x1 >= x2) { // Overlap detected. return diff_bisectSplit_(text1, text2, x1, y1); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]]; }; /** * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @return {Array} Array of diff tuples. */ function diff_bisectSplit_(text1: string, text2: string, x: number, y: number): DiffTuple[] { const text1a = text1.substring(0, x); const text2a = text2.substring(0, y); const text1b = text1.substring(x); const text2b = text2.substring(y); // Compute both diffs serially. const diffs = diffStrings(text1a, text2a); const diffsb = diffStrings(text1b, text2b); return diffs.concat(diffsb); }; /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ function diff_commonPrefix(text1: string, text2: string): number { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) !== text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: http://neil.fraser.name/news/2007/10/09/ let pointermin = 0; let pointermax = Math.min(text1.length, text2.length); let pointermid = pointermax; let pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) === text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ function diff_commonSuffix(text1: string, text2: string) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(text1.length - 1) !== text2.charAt(text2.length - 1)) { return 0; } // Binary search. // Performance analysis: http://neil.fraser.name/news/2007/10/09/ let pointermin = 0; let pointermax = Math.min(text1.length, text2.length); let pointermid = pointermax; let pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) === text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Do the two texts share a substring which is at least half the length of the * longer text? * This speedup can produce non-minimal diffs. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {Array.<string>} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or null if there was no match. */ function diff_halfMatch_(text1: string, text2: string): string[] { const longtext = text1.length > text2.length ? text1 : text2; const shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; // Pointless. } /** * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * Closure, but does not reference any external constiables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {Array.<string>} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or null if there was no match. * @private */ function diff_halfMatchI_(longText: string, shortText: string, i: number) { // Start with a 1/4 length substring at position i as a seed. const seed = longText.substring(i, i + Math.floor(longText.length / 4)); let j = -1; let best_common = ''; let best_longtext_a: string; let best_longtext_b: string; let best_shorttext_a: string; let best_shorttext_b: string; while ((j = shortText.indexOf(seed, j + 1)) !== -1) { const prefixLength = diff_commonPrefix(longText.substring(i), shortText.substring(j)); const suffixLength = diff_commonSuffix(longText.substring(0, i), shortText.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shortText.substring(j - suffixLength, j) + shortText.substring(j, j + prefixLength); best_longtext_a = longText.substring(0, i - suffixLength); best_longtext_b = longText.substring(i + prefixLength); best_shorttext_a = shortText.substring(0, j - suffixLength); best_shorttext_b = shortText.substring(j + prefixLength); } } if (best_common.length * 2 >= longText.length) { return [best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common]; } else { return null; } } // First check if the second quarter is the seed for a half-match. const hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); // Check again based on the third quarter. const hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); let hm: string[]; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } // A half-match was found, sort out the return data. let text1_a: string; let text1_b: string; let text2_a: string; let text2_b: string; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } const mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; }; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {Array} diffs Array of diff tuples. */ function diff_cleanupMerge(diffs: DiffTuple[]): void { diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end. let pointer = 0; let count_delete = 0; let count_insert = 0; let text_delete = ''; let text_insert = ''; let commonlength: number; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { // Factor out any common prefixies. commonlength = diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if ((pointer - count_delete - count_insert) > 0 && diffs[pointer - count_delete - count_insert - 1][0] === DIFF_EQUAL) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, [DIFF_EQUAL, text_insert.substring(0, commonlength)]); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } // Delete the offending records and add the merged ones. if (count_delete === 0) { diffs.splice(pointer - count_insert, count_delete + count_insert, [DIFF_INSERT, text_insert]); } else if (count_insert === 0) { diffs.splice(pointer - count_delete, count_delete + count_insert, [DIFF_DELETE, text_delete]); } else { diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert, [DIFF_DELETE, text_delete], [DIFF_INSERT, text_insert]); } pointer = pointer - count_delete - count_insert + (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1; } else if (pointer !== 0 && diffs[pointer - 1][0] === DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; default: break; // impossible } } if (diffs[diffs.length - 1][1] === '') { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC let changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] === DIFF_EQUAL && diffs[pointer + 1][0] === DIFF_EQUAL) { // This is a single edit surrounded by equalities. if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) === diffs[pointer - 1][1]) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) === diffs[pointer + 1][1]) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { diff_cleanupMerge(diffs); } };
the_stack
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { addConnectionInternal, addEventToSpaceInternal, addSpaceInternal, BoardAudioType, forEachEvent, forEachEventParameter, getBoardEvent, IBoard, IBoardAudioChanges, IEventInstance, includeEventInBoardInternal, ISpace, _makeDefaultBoard } from "../boards"; import { createCustomEvent, ICustomEvent } from "../events/customevents"; import { EventParameterValue, IEvent, IEventParameter } from "../events/events"; import { CostumeType, EditorEventActivationType, EventCodeLanguage, EventParameterType, Space, SpaceSubtype } from "../types"; import { assert } from "../utils/debug"; import { lineDistance } from "../utils/number"; import { copyObject } from "../utils/obj"; import { RootState } from "./store"; export type SpaceIndexMap = { [index: number]: boolean }; export type EventMap = { [id: string]: IEvent }; export enum EventType { None, Library, Board, } type Coords = [number, number, number, number]; export interface BoardState { boards: IBoard[]; romBoards: IBoard[]; currentBoardIndex: number; currentBoardIsROM: boolean; selectedSpaceIndices: SpaceIndexMap; selectionBoxCoords: Coords | null; highlightedSpaceIndices: number[] | null; temporaryConnections: Coords[] | null; eventLibrary: EventMap; currentEventId: string | null; currentEventType: EventType; hoveredBoardEventIndex: number; } const initialState: BoardState = { boards: [], romBoards: [], currentBoardIndex: 0, currentBoardIsROM: false, selectedSpaceIndices: {}, selectionBoxCoords: null, highlightedSpaceIndices: null, temporaryConnections: null, eventLibrary: {}, currentEventId: null, currentEventType: EventType.None, hoveredBoardEventIndex: -1, }; export const boardStateSlice = createSlice({ name: "boardState", initialState, reducers: { setBoardsAction: (state, action: PayloadAction<{ boards: IBoard[], // ref ok }>) => { let { boards } = action.payload; state.boards = boards; }, addBoardAction: (state, action: PayloadAction<{ board: IBoard, // ref ok rom?: boolean, }>) => { let { board, rom } = action.payload; const collection = rom ? state.romBoards : state.boards; collection.push(board); }, deleteBoardAction: (state, action: PayloadAction<{ boardIndex: number, }>) => { const { boardIndex } = action.payload; if (isNaN(boardIndex) || boardIndex < 0 || boardIndex >= state.boards.length) return; if (state.boards.length === 1) { state.boards.push(_makeDefaultBoard()); // Can never leave empty. } state.boards.splice(boardIndex, 1); let nextBoardIndex = -1; if (state.currentBoardIndex > boardIndex) nextBoardIndex = state.currentBoardIndex - 1; else if (state.boards.length === 1) nextBoardIndex = 0; // We deleted the last remaining board else if (state.currentBoardIndex === boardIndex && state.currentBoardIndex === state.boards.length) nextBoardIndex = state.currentBoardIndex - 1; // We deleted the end and current entry. if (nextBoardIndex >= 0) { state.currentBoardIndex = nextBoardIndex; state.currentBoardIsROM = false; } }, setCurrentBoardAction: (state, action: PayloadAction<{ index: number, rom: boolean, }>) => { let { index, rom } = action.payload; const changing = state.currentBoardIndex !== index || state.currentBoardIsROM !== rom; state.currentBoardIndex = index; state.currentBoardIsROM = rom; if (changing) { state.selectedSpaceIndices = {}; state.selectionBoxCoords = null; state.hoveredBoardEventIndex = -1; state.temporaryConnections = null; state.highlightedSpaceIndices = null; } }, clearBoardsFromROMAction: (state) => { state.romBoards = []; if (!state.boards.length) { state.boards.push(_makeDefaultBoard()); // Can never leave empty. } }, copyCurrentBoardAction: (state, action: PayloadAction<{ makeCurrent?: boolean }>) => { let source = getCurrentBoard(state); let copy = copyObject(source); delete copy._rom; copy.name = "Copy of " + copy.name; let insertionIndex; if (state.currentBoardIsROM) { insertionIndex = state.boards.length; state.boards.push(copy); } else { insertionIndex = state.currentBoardIndex + 1; state.boards.splice(insertionIndex, 0, copy); } if (action.payload.makeCurrent) { state.currentBoardIndex = insertionIndex; state.currentBoardIsROM = false; } }, setBoardNameAction: (state, action: PayloadAction<{ name: string, }>) => { const currentBoard = getCurrentBoard(state); currentBoard.name = action.payload.name; }, setBoardDescriptionAction: (state, action: PayloadAction<{ description: string, }>) => { const currentBoard = getCurrentBoard(state); currentBoard.description = action.payload.description; }, setBoardDifficultyAction: (state, action: PayloadAction<{ difficulty: number, }>) => { const currentBoard = getCurrentBoard(state); currentBoard.difficulty = action.payload.difficulty; }, setBoardCostumeTypeIndexAction: (state, action: PayloadAction<{ costumeType: CostumeType, }>) => { const currentBoard = getCurrentBoard(state); currentBoard.costumeTypeIndex = action.payload.costumeType; }, setBackgroundAction: (state, action: PayloadAction<{ bg: string, }>) => { const { bg } = action.payload; const currentBoard = getCurrentBoard(state); currentBoard.bg.src = bg; }, setBoardOtherBgAction: (state, action: PayloadAction<{ name: keyof IBoard["otherbg"], value: string, }>) => { const { name, value } = action.payload; const currentBoard = getCurrentBoard(state); currentBoard.otherbg[name] = value; }, addAnimationBackgroundAction: (state, action: PayloadAction<{ bg: string, }>) => { const { bg } = action.payload; const board = getCurrentBoard(state); board.animbg = board.animbg || []; board.animbg.push(bg); }, removeAnimationBackgroundAction: (state, action: PayloadAction<{ index: number, }>) => { const { index } = action.payload; const board = getCurrentBoard(state); if (!board.animbg || board.animbg.length <= index || index < 0) return; board.animbg.splice(index, 1); }, addAdditionalBackgroundAction: (state, action: PayloadAction<{ bg: string, }>) => { let { bg } = action.payload; const board = getCurrentBoard(state); board.additionalbg = board.additionalbg || []; board.additionalbg.push(bg); }, removeAdditionalBackgroundAction: (state, action: PayloadAction<{ index: number, }>) => { let { index } = action.payload; const board = getCurrentBoard(state); if (!board.additionalbg || board.additionalbg.length <= index || index < 0) return; board.additionalbg.splice(index, 1); }, setAdditionalBackgroundCodeAction: (state, action: PayloadAction<{ code: string, language: EventCodeLanguage }>) => { let { code, language } = action.payload; const board = getCurrentBoard(state); if (code) { board.additionalbgcode = { code, language }; } else { delete board.additionalbgcode; } }, setAudioSelectCodeAction: (state, action: PayloadAction<{ code: string, language: EventCodeLanguage }>) => { let { code, language } = action.payload; const board = getCurrentBoard(state); if (code) { board.audioSelectCode = { code, language }; } else { delete board.audioSelectCode; } }, setBoardAudioAction: (state, action: PayloadAction<{ audioChanges: IBoardAudioChanges }>) => { let { audioChanges } = action.payload; const board = getCurrentBoard(state); if ("audioType" in audioChanges) { board.audioType = audioChanges.audioType!; switch (audioChanges.audioType) { case BoardAudioType.Custom: if (!board.audioData) { board.audioData = []; } break; } } if (typeof audioChanges.gameAudioIndex === "number") { board.audioIndex = audioChanges.gameAudioIndex; } const customAudioIndex = audioChanges.customAudioIndex; if (typeof customAudioIndex === "number") { assert(Array.isArray(board.audioData)); assert(customAudioIndex <= board.audioData.length); if (customAudioIndex === board.audioData.length) { board.audioData.push({ name: "(select a midi file)", data: "", soundbankIndex: 0 }); } if (audioChanges.delete) { assert(customAudioIndex < board.audioData.length); board.audioData.splice(customAudioIndex, 1); } else { if (audioChanges.midiName) { board.audioData[customAudioIndex].name = audioChanges.midiName; } if (audioChanges.midiData) { board.audioData[customAudioIndex].data = audioChanges.midiData; } if (typeof audioChanges.soundbankIndex === "number") { board.audioData[customAudioIndex].soundbankIndex = audioChanges.soundbankIndex; } } } }, addSpaceAction: (state, action: PayloadAction<{ x: number, y: number, type: Space, subtype?: SpaceSubtype, }>) => { let { x, y, type, subtype } = action.payload; const board = getCurrentBoard(state); addSpaceInternal(x, y, type, subtype, board, state.eventLibrary); }, removeSpaceAction: (state, action: PayloadAction<{ index: number, }>) => { let { index } = action.payload; const currentBoard = getCurrentBoard(state); removeSpace(state, currentBoard, index); }, removeSpacesAction: (state, action: PayloadAction<{ spaceIndices: number[], }>) => { const { spaceIndices } = action.payload; const currentBoard = getCurrentBoard(state); for (let i = 0; i < spaceIndices.length; i++) { const spaceIndex = spaceIndices[i]; if (removeSpace(state, currentBoard, spaceIndex)) { // Adjust indices, since deleting index N affects the indices after N. for (let j = i + 1; j < spaceIndices.length; j++) { if (spaceIndices[j] > spaceIndex) { spaceIndices[j]--; } } } } }, addConnectionAction: (state, action: PayloadAction<{ startSpaceIndex: number, endSpaceIndex: number, }>) => { let { startSpaceIndex, endSpaceIndex } = action.payload; const board = getCurrentBoard(state); addConnectionInternal(startSpaceIndex, endSpaceIndex, board); // Otherwise this may show up in undo/redo states. state.temporaryConnections = null; }, eraseConnectionsAction: (state, action: PayloadAction<{ x: number, y: number, }>) => { let { x, y } = action.payload; const currentBoard = getCurrentBoard(state); _eraseLines(currentBoard, x, y); }, setTemporaryUIConnections: (state, action: PayloadAction<{ connections: Coords[] | null, }>) => { let { connections } = action.payload; state.temporaryConnections = connections; }, setSpacePositionsAction: (state, action: PayloadAction<{ spaceIndices: number[], coords: { x?: number, y?: number, z?: number }[], }>) => { const { spaceIndices, coords } = action.payload; const currentBoard = getCurrentBoard(state); for (let i = 0; i < spaceIndices.length; i++) { const space = currentBoard.spaces[spaceIndices[i]]; const coordSet = coords[i]; if (typeof coordSet.x === "number") { space.x = coordSet.x; } if (typeof coordSet.y === "number") { space.y = coordSet.y; } if (typeof coordSet.z === "number") { space.z = coordSet.z; } } }, setSpaceTypeAction: (state, action: PayloadAction<{ spaceIndices: number[], type: Space, subtype: SpaceSubtype | undefined }>) => { const { spaceIndices, type, subtype } = action.payload; const currentBoard = getCurrentBoard(state); for (let i = 0; i < spaceIndices.length; i++) { const space = currentBoard.spaces[spaceIndices[i]]; if (type !== undefined) { space.type = type; if (space.rotation) { delete space.rotation; } } if (subtype !== undefined) space.subtype = subtype; else delete space.subtype; } }, setSpaceSubtypeAction: (state, action: PayloadAction<{ spaceIndices: number[], subtype: SpaceSubtype | undefined }>) => { const { spaceIndices, subtype } = action.payload; const currentBoard = getCurrentBoard(state); for (let i = 0; i < spaceIndices.length; i++) { const space = currentBoard.spaces[spaceIndices[i]]; if (typeof subtype === "undefined") { delete space.subtype; } else { space.subtype = subtype; } } }, setSpaceHostsStarAction: (state, action: PayloadAction<{ spaceIndices: number[], hostsStar: boolean }>) => { let { spaceIndices, hostsStar } = action.payload; const currentBoard = getCurrentBoard(state); for (let i = 0; i < spaceIndices.length; i++) { const space = currentBoard.spaces[spaceIndices[i]]; if (hostsStar) { space.star = true; } else { delete space.star; } } }, setSpaceRotationAction: (state, action: PayloadAction<{ spaceIndex: number, angleYAxisDeg: number }>) => { let { spaceIndex, angleYAxisDeg } = action.payload; assertNotROMBoard(state); const board = getCurrentBoard(state); const space = board.spaces[spaceIndex]; if (!space) { throw new Error("setSpaceRotation: Invalid space index " + spaceIndex); } space.rotation = Math.round(angleYAxisDeg); }, addSelectedSpaceAction: (state, action: PayloadAction<number>) => { let spaceIndex = action.payload; state.selectedSpaceIndices[spaceIndex] = true; }, setSelectedSpaceAction: (state, action: PayloadAction<number>) => { let spaceIndex = action.payload; state.selectedSpaceIndices = { [spaceIndex]: true }; }, setSelectedSpacesAction: (state, action: PayloadAction<number[]>) => { let spaceIndices = action.payload; const selectedSpaceIndices: { [index: number]: boolean } = {}; for (const index of spaceIndices) { selectedSpaceIndices[index] = true; } state.selectedSpaceIndices = selectedSpaceIndices; }, clearSelectedSpacesAction: (state, action: PayloadAction) => { state.selectedSpaceIndices = {}; }, setHighlightedSpacesAction: (state, action: PayloadAction<{ spaceIndices: number[] | null }>) => { const { spaceIndices } = action.payload; state.highlightedSpaceIndices = spaceIndices; }, setSelectionBoxCoordsAction: (state, action: PayloadAction<{ selectionCoords: Coords | null, }>) => { const { selectionCoords } = action.payload; state.selectionBoxCoords = selectionCoords; }, changeCurrentEventAction: (state, action: PayloadAction<{ id: string | null, type: EventType, }>) => { const { id, type } = action.payload; state.currentEventId = id; state.currentEventType = type; }, addEventToLibraryAction: (state, action: PayloadAction<{ event: IEvent, // ref ok }>) => { const { event } = action.payload; state.eventLibrary[event.id] = event; }, removeEventFromLibraryAction: (state, action: PayloadAction<{ eventId: string, }>) => { const { eventId } = action.payload; if (!state.eventLibrary[eventId]) throw new Error(`Cannot remove event ${eventId}, as it isn't in the event library`); if (!state.eventLibrary[eventId].custom) throw new Error(`Cannot remove event ${eventId}, as it is a built-in event`); delete state.eventLibrary[eventId]; }, addEventToBoardAction: (state, action: PayloadAction<{ event: IEventInstance, // ref ok }>) => { const { event } = action.payload; const board = getCurrentBoard(state); if (!board.boardevents) { board.boardevents = []; } board.boardevents.push(event); if (event.custom) { const customEvent = getEvent(state, event.id, board) as ICustomEvent; includeEventInBoardInternal(board, customEvent); } }, removeEventFromBoardAction: (state, action: PayloadAction<{ eventIndex: number, }>) => { const { eventIndex } = action.payload; const board = getCurrentBoard(state); removeEventFromBoard(board, eventIndex); }, includeEventInBoardAction: (state, action: PayloadAction<{ event: ICustomEvent, // ref ok }>) => { const { event } = action.payload; const board = getCurrentBoard(state); includeEventInBoardInternal(board, event); }, excludeEventFromBoardAction: (state, action: PayloadAction<{ eventId: string, }>) => { let { eventId } = action.payload; const board = getCurrentBoard(state); excludeEventFromBoard(board, eventId); }, setHoveredBoardEventIndexAction: (state, action: PayloadAction<{ eventIndex: number, }>) => { let { eventIndex } = action.payload; state.hoveredBoardEventIndex = eventIndex; }, setBoardEventActivationTypeAction: (state, action: PayloadAction<{ eventIndex: number, activationType: EditorEventActivationType, }>) => { let { eventIndex, activationType } = action.payload; const board = getCurrentBoard(state); const eventInstance = board.boardevents![eventIndex]; eventInstance.activationType = activationType; }, setBoardEventEventParameterAction: (state, action: PayloadAction<{ eventIndex: number, name: string, value: EventParameterValue }>) => { let { eventIndex, name, value } = action.payload; const board = getCurrentBoard(state); const eventInstance = board.boardevents![eventIndex]; if (!eventInstance.parameterValues) { eventInstance.parameterValues = {}; } eventInstance.parameterValues[name] = value; }, addEventToSpaceAction: (state, action: PayloadAction<{ event: IEventInstance, // ref ok toStart?: boolean }>) => { const { event, toStart } = action.payload; const board = getCurrentBoard(state); const selectedSpace = getCurrentSingleSelectedSpace(state); addEventToSpaceInternal(board, selectedSpace, event, toStart || false, state.eventLibrary); }, removeEventFromSpaceAction: (state, action: PayloadAction<{ eventIndex: number, }>) => { let { eventIndex } = action.payload; const selectedSpace = getCurrentSingleSelectedSpace(state); removeEventFromSpace(selectedSpace, eventIndex); }, setSpaceEventActivationTypeAction: (state, action: PayloadAction<{ eventIndex: number, activationType: EditorEventActivationType, }>) => { let { eventIndex, activationType } = action.payload; const selectedSpace = getCurrentSingleSelectedSpace(state); const eventInstance = selectedSpace.events![eventIndex]; eventInstance.activationType = activationType; }, setSpaceEventEventParameterAction: (state, action: PayloadAction<{ eventIndex: number, name: string, value: EventParameterValue }>) => { let { eventIndex, name, value } = action.payload; const selectedSpace = getCurrentSingleSelectedSpace(state); const eventInstance = selectedSpace.events![eventIndex]; if (!eventInstance.parameterValues) { eventInstance.parameterValues = {}; } eventInstance.parameterValues[name] = value; }, }, }); export const { setBoardsAction, addBoardAction, deleteBoardAction, setCurrentBoardAction, clearBoardsFromROMAction, copyCurrentBoardAction, setBoardNameAction, setBoardDescriptionAction, setBoardDifficultyAction, setBoardCostumeTypeIndexAction, setBackgroundAction, setBoardOtherBgAction, addAnimationBackgroundAction, removeAnimationBackgroundAction, addAdditionalBackgroundAction, removeAdditionalBackgroundAction, setAdditionalBackgroundCodeAction, setAudioSelectCodeAction, setBoardAudioAction, addConnectionAction, eraseConnectionsAction, setTemporaryUIConnections, addSpaceAction, removeSpaceAction, removeSpacesAction, setSpacePositionsAction, setSpaceTypeAction, setSpaceSubtypeAction, setSpaceHostsStarAction, setSpaceRotationAction, addSelectedSpaceAction, setSelectedSpaceAction, setSelectedSpacesAction, clearSelectedSpacesAction, setHighlightedSpacesAction, setSelectionBoxCoordsAction, changeCurrentEventAction, addEventToLibraryAction, removeEventFromLibraryAction, addEventToBoardAction, removeEventFromBoardAction, includeEventInBoardAction, excludeEventFromBoardAction, setHoveredBoardEventIndexAction, setBoardEventActivationTypeAction, setBoardEventEventParameterAction, addEventToSpaceAction, removeEventFromSpaceAction, setSpaceEventActivationTypeAction, setSpaceEventEventParameterAction, } = boardStateSlice.actions; export const selectData = (state: RootState) => state.data.present; export const selectBoards = (state: RootState) => state.data.present.boards; export const selectROMBoards = (state: RootState) => state.data.present.romBoards; export const selectCurrentBoardIndex = (state: RootState) => { return state.data.present.currentBoardIndex; } export const selectCurrentBoardIsROM = (state: RootState) => { return state.data.present.currentBoardIsROM; } export const selectCurrentBoard = (state: RootState) => { if (state.data.present.currentBoardIsROM) { return state.data.present.romBoards[state.data.present.currentBoardIndex]; } return state.data.present.boards[state.data.present.currentBoardIndex]; } export const selectSelectionBoxCoords = (state: RootState) => state.data.present.selectionBoxCoords; export const selectHoveredBoardEventIndex = (state: RootState) => state.data.present.hoveredBoardEventIndex; export const selectHighlightedSpaceIndices = (state: RootState) => state.data?.present?.highlightedSpaceIndices; export const selectTemporaryConnections = (state: RootState) => state.data.present.temporaryConnections; export const selectSelectedSpaceIndices = (state: RootState) => state.data.present.selectedSpaceIndices; export const selectCurrentEvent = (state: RootState) => { switch (state.data.present.currentEventType) { case EventType.Board: assert(!!state.data.present.currentEventId); const boardEvent = selectCurrentBoard(state).events[state.data.present.currentEventId]; assert(typeof boardEvent !== "string"); return createCustomEvent(boardEvent.language, boardEvent.code); case EventType.Library: assert(!!state.data.present.currentEventId); return state.data.present.eventLibrary[state.data.present.currentEventId]; case EventType.None: default: return null; } } export const selectCurrentEventType = (state: RootState) => state.data.present.currentEventType; export const selectEventLibrary = (state: RootState) => state.data.present.eventLibrary; function removeSpace(state: BoardState, board: IBoard, index: number): boolean { if (index < 0 || index >= board.spaces.length) return false; // Remove any attached connections. _removeConnections(index, board); _removeAssociations(index, board, state.eventLibrary); // Remove the actual space. let oldSpaceLen = board.spaces.length; board.spaces.splice(index, 1); function _adjust(oldIdx: any) { return parseInt(oldIdx) > parseInt(index as any) ? oldIdx - 1 : oldIdx; } // Update the links that are at a greater index. let start, end; for (let i = 0; i < oldSpaceLen; i++) { if (!board.links.hasOwnProperty(i)) continue; start = _adjust(i); end = board.links[i]; if (start !== i) delete board.links[i]; if (Array.isArray(end)) board.links[start] = end.map(_adjust); else board.links[start] = _adjust(end); } // Update space event parameter indices forEachEventParameter(board, state.eventLibrary, (parameter: IEventParameter, event: IEventInstance) => { switch (parameter.type) { case EventParameterType.Space: if (event.parameterValues && event.parameterValues.hasOwnProperty(parameter.name)) { event.parameterValues[parameter.name] = _adjust(event.parameterValues[parameter.name]); } break; case EventParameterType.SpaceArray: const parameterValue = event.parameterValues?.[parameter.name]; if (event.parameterValues && Array.isArray(parameterValue)) { event.parameterValues[parameter.name] = parameterValue.map(_adjust); } break; } }); return true; } // Removes all connections to a certain space. function _removeConnections(spaceIdx: number, board: IBoard) { if (!board.links) return; delete board.links[spaceIdx]; for (let startSpace in board.links) { let value = board.links[startSpace]; if (Array.isArray(value)) { let entry = value.indexOf(spaceIdx); if (entry !== -1) value.splice(entry, 1); if (value.length === 1) board.links[startSpace] = value[0]; else if (!value.length) delete board.links[startSpace]; } else if (value === spaceIdx) { delete board.links[startSpace]; } } } function _eraseLines(board: IBoard, x: number, y: number): boolean { let spaces = board.spaces; let links = board.links; let somethingErased = false; for (let startIdx in links) { let startSpace = spaces[startIdx]; let endSpace; let endLinks = links[startIdx]; if (Array.isArray(endLinks)) { let i = 0; while (i < endLinks.length) { endSpace = spaces[endLinks[i]]; if (_shouldEraseLine(startSpace, endSpace, x, y)) { endLinks.splice(i, 1); somethingErased = true; } else i++; } if (endLinks.length === 1) links[startIdx] = endLinks = endLinks[0]; else if (!endLinks.length) delete links[startIdx]; } else { endSpace = spaces[endLinks]; if (_shouldEraseLine(startSpace, endSpace, x, y)) { delete links[startIdx]; somethingErased = true; } } } return somethingErased; } function _shouldEraseLine(startSpace: ISpace, endSpace: ISpace, targetX: number, targetY: number) { if (targetX > startSpace.x && targetX > endSpace.x) return false; if (targetX < startSpace.x && targetX < endSpace.x) return false; if (targetY > startSpace.y && targetY > endSpace.y) return false; if (targetY < startSpace.y && targetY < endSpace.y) return false; return lineDistance(targetX, targetY, startSpace.x, startSpace.y, endSpace.x, endSpace.y) <= 4; } function _removeAssociations(spaceIdx: number, board: IBoard, eventLibrary: EventMap) { forEachEventParameter(board, eventLibrary, (parameter: IEventParameter, event: IEventInstance) => { switch (parameter.type) { case EventParameterType.Space: if (event.parameterValues && event.parameterValues.hasOwnProperty(parameter.name)) { if (event.parameterValues[parameter.name] === spaceIdx) { delete event.parameterValues[parameter.name]; } } break; case EventParameterType.SpaceArray: const parameterValue = event.parameterValues?.[parameter.name]; if (event.parameterValues && Array.isArray(parameterValue)) { event.parameterValues[parameter.name] = parameterValue.filter(s => s !== spaceIdx); } break; } }); } function getCurrentBoard(state: BoardState): IBoard { if (state.currentBoardIsROM) { return state.romBoards[state.currentBoardIndex]; } else { return state.boards[state.currentBoardIndex]; } } function getCurrentSingleSelectedSpace(state: BoardState): ISpace { const selectedSpaceIndices = Object.keys(state.selectedSpaceIndices).map(k => parseInt(k, 10)); assert(selectedSpaceIndices.length === 1); const space = getCurrentBoard(state).spaces[selectedSpaceIndices[0]]; assert(!!space); return space; } /** Removes an event from `boardevents`. */ function removeEventFromBoard(board: IBoard, eventIndex: number) { if (board.boardevents?.length) { if (eventIndex >= 0) { board.boardevents.splice(eventIndex, 1); } } } /** Removes an event from the collection of events stored in the board file. */ function excludeEventFromBoard(board: IBoard, eventId: string): void { if (board.events) { delete board.events[eventId]; } forEachEvent(board, (event, eventIndex, space) => { if (event.id === eventId) { if (space) { removeEventFromSpace(space, eventIndex); } else { removeEventFromBoard(board, eventIndex); } } }); } function removeEventFromSpace(space: ISpace, eventIndex: number) { if (!space || !space.events) return; if (eventIndex >= 0) { space.events.splice(eventIndex, 1); } } /** Gets an event, either from the board's set or the global library. */ export function getEvent(state: BoardState, eventId: string, board: IBoard): IEvent | undefined { if (board && board.events && !!getBoardEvent(board, eventId)) { const boardEvent = getBoardEvent(board, eventId); return createCustomEvent(boardEvent!.language, boardEvent!.code); } return state.eventLibrary[eventId]; } function assertNotROMBoard(state: BoardState): void { if (state.currentBoardIsROM) { throw new Error("Current board must not be a ROM board."); } } export default boardStateSlice.reducer;
the_stack
import tape from 'tape' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import { Block } from '@ethereumjs/block' import { PeerPool } from '../../lib/net/peerpool' import { TxPool } from '../../lib/sync/txpool' import { Config } from '../../lib/config' tape('[TxPool]', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) const config = new Config({ transports: [], loglevel: 'error' }) const A = { address: Buffer.from('0b90087d864e82a284dca15923f3776de6bb016f', 'hex'), privateKey: Buffer.from( '64bf9cc30328b0e42387b3c82c614e6386259136235e20c1357bd11cdee86993', 'hex' ), } const B = { address: Buffer.from('6f62d8382bf2587361db73ceca28be91b2acb6df', 'hex'), privateKey: Buffer.from( '2a6e9ad5a6a8e4f17149b8bc7128bf090566a11dbd63c30e5a0ee9f161309cd6', 'hex' ), } const createTx = (from = A, to = B, nonce = 0, value = 1) => { const txData = { nonce, maxFeePerGas: 1000000000, maxInclusionFeePerGas: 100000000, gasLimit: 100000, to: to.address, value, } const tx = FeeMarketEIP1559Transaction.fromTxData(txData, { common }) const signedTx = tx.sign(from.privateKey) return signedTx } const txA01 = createTx() // A -> B, nonce: 0, value: 1 const txA02 = createTx(A, B, 0, 2) // A -> B, nonce: 0, value: 2 (different hash) const txB01 = createTx(B, A) // B -> A, nonce: 0, value: 1 const txB02 = createTx(B, A, 1, 5) // B -> A, nonce: 1, value: 5 t.test('should initialize correctly', (t) => { const config = new Config({ transports: [], loglevel: 'error' }) const pool = new TxPool({ config }) t.equal(pool.pool.size, 0, 'pool empty') t.notOk((pool as any).opened, 'pool not opened yet') pool.open() t.ok((pool as any).opened, 'pool opened') pool.start() t.ok((pool as any).running, 'pool running') pool.stop() t.notOk((pool as any).running, 'pool not running anymore') pool.close() t.notOk((pool as any).opened, 'pool not opened anymore') t.end() }) t.test('should open/close', async (t) => { t.plan(3) const config = new Config({ transports: [], loglevel: 'error' }) const pool = new TxPool({ config }) pool.open() pool.start() t.ok((pool as any).opened, 'pool opened') t.equals(pool.open(), false, 'already opened') pool.stop() pool.close() t.notOk((pool as any).opened, 'closed') t.end() }) t.test('announcedTxHashes() -> add single tx / knownByPeer / getByHash()', async (t) => { // Safeguard that send() method from peer2 gets called t.plan(12) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { id: '1', eth: { getPooledTransactions: () => { return [null, [txA01]] }, send: () => { t.fail('should not send to announcing peer') }, }, } let sentToPeer2 = 0 const peer2: any = { id: '2', eth: { send: () => { sentToPeer2++ t.equal(sentToPeer2, 1, 'should send once to non-announcing peer') }, }, } const peerPool = new PeerPool({ config }) peerPool.add(peer) peerPool.add(peer2) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') t.equal((pool as any).pending.length, 0, 'cleared pending txs') t.equal((pool as any).handled.size, 1, 'added to handled txs') t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') t.equal((pool as any).knownByPeer.get(peer.id).length, 1, 'one tx added for peer 1') t.equal( (pool as any).knownByPeer.get(peer.id)[0].hash, txA01.hash().toString('hex'), 'new known tx hashes entry for announcing peer' ) const txs = pool.getByHash([txA01.hash()]) t.equal(txs.length, 1, 'should get correct number of txs by hash') t.equal( txs[0].serialize().toString('hex'), txA01.serialize().toString('hex'), 'should get correct tx by hash' ) pool.pool.clear() await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 0, 'should not add a once handled tx') t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should add tx only once to known tx hashes' ) t.equal((pool as any).knownByPeer.size, 2, 'known tx hashes size 2 (entries for both peers)') pool.stop() pool.close() t.end() }) t.test('announcedTxHashes() -> TX_RETRIEVAL_LIMIT', async (t) => { const pool = new TxPool({ config }) const TX_RETRIEVAL_LIMIT: number = (pool as any).TX_RETRIEVAL_LIMIT pool.open() pool.start() const peer = { eth: { getPooledTransactions: (res: any) => { t.equal(res['hashes'].length, TX_RETRIEVAL_LIMIT, 'should limit to TX_RETRIEVAL_LIMIT') return [null, []] }, }, } const peerPool = new PeerPool({ config }) const hashes = [] for (let i = 1; i <= TX_RETRIEVAL_LIMIT + 1; i++) { // One more than TX_RETRIEVAL_LIMIT hashes.push(Buffer.from(i.toString().padStart(64, '0'), 'hex')) // '0000000000000000000000000000000000000000000000000000000000000001',... } await pool.handleAnnouncedTxHashes(hashes, peer as any, peerPool) pool.stop() pool.close() t.end() }) t.test('announcedTxHashes() -> add two txs (different sender)', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') pool.stop() pool.close() t.end() }) t.test('announcedTxHashes() -> add two txs (same sender and nonce)', async (t) => { const config = new Config({ transports: [], loglevel: 'error' }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txA02]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash(), txA02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') t.deepEqual(poolContent[0].tx.hash(), txA02.hash(), 'only later-added tx') pool.stop() pool.close() t.end() }) t.test('announcedTxs()', async (t) => { const config = new Config({ transports: [], loglevel: 'error' }) const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { send: () => {}, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxs([txA01], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = A.address.toString('hex') const poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'one tx') t.deepEqual(poolContent[0].tx.hash(), txA01.hash(), 'correct tx') pool.stop() pool.close() t.end() }) t.test('newBlocks() -> should remove included txs', async (t) => { const config = new Config({ transports: [], loglevel: 'error' }) const pool = new TxPool({ config }) pool.open() pool.start() let peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01]] }, }, } const peerPool = new PeerPool({ config }) await pool.handleAnnouncedTxHashes([txA01.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx not in pool let block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txA01] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool should be empty') peer = { eth: { getPooledTransactions: () => { return [null, [txB01, txB02]] }, }, } await pool.handleAnnouncedTxHashes([txB01.hash(), txB02.hash()], peer, peerPool) t.equal(pool.pool.size, 1, 'pool size 1') const address = B.address.toString('hex') let poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx not in pool block = Block.fromBlockData({ transactions: [txA02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 1, 'pool size 1') poolContent = pool.pool.get(address)! t.equal(poolContent.length, 2, 'two txs') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB01] }, { common }) pool.removeNewBlockTxs([block]) poolContent = pool.pool.get(address)! t.equal(poolContent.length, 1, 'only one tx') // Craft block with tx in pool block = Block.fromBlockData({ transactions: [txB02] }, { common }) pool.removeNewBlockTxs([block]) t.equal(pool.pool.size, 0, 'pool size 0') pool.stop() pool.close() t.end() }) t.test('cleanup()', async (t) => { const pool = new TxPool({ config }) pool.open() pool.start() const peer: any = { eth: { getPooledTransactions: () => { return [null, [txA01, txB01]] }, }, send: () => {}, } const peerPool = new PeerPool({ config }) peerPool.add(peer) await pool.handleAnnouncedTxHashes([txA01.hash(), txB01.hash()], peer, peerPool) t.equal(pool.pool.size, 2, 'pool size 2') t.equal((pool as any).handled.size, 2, 'handled size 2') t.equal((pool as any).knownByPeer.size, 1, 'known by peer size 1') t.equal((pool as any).knownByPeer.get(peer.id).length, 2, '2 known txs') pool.cleanup() t.equal( pool.pool.size, 2, 'should not remove txs from pool (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).knownByPeer.size, 1, 'should not remove txs from known by peer map (POOLED_STORAGE_TIME_LIMIT within range)' ) t.equal( (pool as any).handled.size, 2, 'should not remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT within range)' ) const address = txB01.getSenderAddress().toString().slice(2) const poolObj = pool.pool.get(address)![0] poolObj.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 pool.pool.set(address, [poolObj]) const knownByPeerObj1 = (pool as any).knownByPeer.get(peer.id)[0] const knownByPeerObj2 = (pool as any).knownByPeer.get(peer.id)[1] knownByPeerObj1.added = Date.now() - pool.POOLED_STORAGE_TIME_LIMIT * 60 - 1 ;(pool as any).knownByPeer.set(peer.id, [knownByPeerObj1, knownByPeerObj2]) const hash = txB01.hash().toString('hex') const handledObj = (pool as any).handled.get(hash) handledObj.added = Date.now() - pool.HANDLED_CLEANUP_TIME_LIMIT * 60 - 1 ;(pool as any).handled.set(hash, handledObj) pool.cleanup() t.equal( pool.pool.size, 1, 'should remove txs from pool (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).knownByPeer.get(peer.id).length, 1, 'should remove one tx from known by peer map (POOLED_STORAGE_TIME_LIMIT before range)' ) t.equal( (pool as any).handled.size, 1, 'should remove txs from handled (HANDLED_CLEANUP_TIME_LIMIT before range)' ) pool.stop() pool.close() t.end() }) })
the_stack
import 'aurelia-polyfills' import * as DI from 'aurelia-dependency-injection' import * as Cesium from './cesium/cesium-imports' import './webvr' import { SessionService, ConnectService, LoopbackConnectService, DOMConnectService, DebugConnectService, WKWebViewConnectService, AndroidWebViewConnectService } from './session' import { Configuration, Role } from './common' import { DefaultUIService } from './ui' import { Event, isIOS, getEventSynthesizier, createEventForwarder, hasNativeWebVRImplementation } from './utils' import { EntityService, EntityServiceProvider } from './entity' import { ContextService, ContextServiceProvider } from './context' import { FocusService, FocusServiceProvider } from './focus' import { DeviceService, DeviceServiceProvider } from './device' import { RealityService, RealityServiceProvider } from './reality' import { ViewService, ViewServiceProvider, ViewItems, ViewportMode } from './view' import { VisibilityService, VisibilityServiceProvider } from './visibility' import { VuforiaService, VuforiaServiceProvider } from './vuforia' import { PermissionService, PermissionServiceProvider } from './permission' import { RealityViewer } from './reality-viewers/base' import { EmptyRealityViewer } from './reality-viewers/empty' import { LiveRealityViewer } from './reality-viewers/live' import { HostedRealityViewer } from './reality-viewers/hosted' export { DI, Cesium } export * from './common' export * from './context' export * from './entity' export * from './focus' export * from './device' export * from './reality' export * from './session' export * from './ui' export * from './utils' export * from './view' export * from './visibility' export * from './vuforia' export * from './permission' export { RealityViewer, EmptyRealityViewer, LiveRealityViewer, HostedRealityViewer } @DI.autoinject() export class ArgonSystemProvider { constructor( public entity:EntityServiceProvider, public context:ContextServiceProvider, public focus:FocusServiceProvider, public device:DeviceServiceProvider, public visibility:VisibilityServiceProvider, public reality:RealityServiceProvider, public view:ViewServiceProvider, public vuforia:VuforiaServiceProvider, public permission:PermissionServiceProvider ) {} } /** * A composition root which instantiates the object graph based on a provided configuration. * You generally want to create a new ArgonSystem via the provided [[init]] or [[initReality]] functions: * ```ts * var app = Argon.init(); // app is an instance of ArgonSystem * ``` */ @DI.autoinject export class ArgonSystem { /** * The ArgonSystem instance which shares a view provided by a manager */ static instance?: ArgonSystem; constructor( public container: DI.Container, public entity:EntityService, public context: ContextService, public device: DeviceService, public focus: FocusService, public reality: RealityService, public session: SessionService, public view: ViewService, public visibility: VisibilityService, public vuforia: VuforiaService, public permission: PermissionService ) { if (!ArgonSystem.instance) ArgonSystem.instance = this; if (this.container.hasResolver(ArgonSystemProvider)) this._provider = this.container.get(ArgonSystemProvider); this._setupDOM(); this.session.connect(); } private _setupDOM() { const viewItems:ViewItems = this.container.get(ViewItems); const element = viewItems.element; if (element && typeof document !== 'undefined' && document.createElement) { element.classList.add('argon-view'); // prevent pinch-zoom of the page in ios 10. if (isIOS) { const touchMoveListener = (event) => { if (event.touches.length > 1) event.preventDefault(); } element.addEventListener('touchmove', touchMoveListener, true); this.session.manager.closeEvent.addEventListener(()=>{ element.removeEventListener('touchmove', touchMoveListener) }); } // add styles describing the type of the current session if (this.session.isRealityViewer) { document.documentElement.classList.add('argon-reality-viewer'); } if (this.session.isRealityAugmenter) { document.documentElement.classList.add('argon-reality-augmenter'); } if (this.session.isRealityManager) { document.documentElement.classList.add('argon-reality-manager'); } // add/remove document-level css classes this.focus.focusEvent.addEventListener(() => { document.documentElement.classList.remove('argon-no-focus'); document.documentElement.classList.remove('argon-blur'); document.documentElement.classList.add('argon-focus'); }); this.focus.blurEvent.addEventListener(() => { document.documentElement.classList.remove('argon-focus'); document.documentElement.classList.add('argon-blur'); document.documentElement.classList.add('argon-no-focus'); }); this.view.viewportModeChangeEvent.addEventListener((mode)=>{ switch (mode) { case ViewportMode.EMBEDDED: const elementStyle = this.view.element.style; elementStyle.position = ''; elementStyle.left = '0px'; elementStyle.bottom = '0px'; elementStyle.width = '100%'; elementStyle.height = '100%'; document.documentElement.classList.remove('argon-immersive'); break; case ViewportMode.IMMERSIVE: document.documentElement.classList.add('argon-immersive'); break; } }); // Setup event forwarding / synthesizing if (this.session.isRealityViewer) { this.session.manager.on['ar.view.uievent'] = getEventSynthesizier()!; } else { createEventForwarder(this.view, (event)=>{ if (this.session.manager.isConnected && this.session.manager.version[0] >= 1) this.session.manager.send('ar.view.forwardUIEvent', event); }); this.view._watchEmbeddedViewport(); } this.context.renderEvent.addEventListener(()=>{ if (this.view.autoStyleLayerElements) { const layers = this.view.layers; if (!layers) return; const viewport = this.view.viewport; let zIndex = 0; for (const layer of layers) { const layerStyle = layer.source.style; layerStyle.position = 'absolute'; layerStyle.left = viewport.x + 'px'; layerStyle.bottom = viewport.y + 'px'; layerStyle.width = viewport.width + 'px'; layerStyle.height = viewport.height + 'px'; layerStyle.zIndex = '' + zIndex; zIndex++; } } }); if (!this.session.isRealityManager) { this.view.viewportChangeEvent.addEventListener((viewport)=>{ if (this.view.element && this.view.autoLayoutImmersiveMode && this.view.viewportMode === ViewportMode.IMMERSIVE) { const elementStyle = this.view.element.style; elementStyle.position = 'fixed'; elementStyle.left = viewport.x + 'px'; elementStyle.bottom = viewport.y + 'px'; elementStyle.width = viewport.width + 'px'; elementStyle.height = viewport.height + 'px'; } }); } } } public get suggestedPixelRatio() { if (this.device.isPresentingHMD && hasNativeWebVRImplementation) return 1; const devicePixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1 if (this.focus.hasFocus) { return devicePixelRatio; } else { return devicePixelRatio * 0.5; } } public _provider:ArgonSystemProvider; public get provider() { this.session.ensureIsRealityManager(); return this._provider; } // events public get updateEvent(): Event<any> { return this.context.updateEvent; } public get renderEvent(): Event<any> { return this.context.renderEvent; } public get focusEvent(): Event<void> { return this.focus.focusEvent; } public get blurEvent(): Event<void> { return this.focus.blurEvent; } public destroy() { this.session.manager.close(); if (ArgonSystem.instance === this) { ArgonSystem.instance = undefined; } } } export class ArgonConfigurationManager { static configure(configurationManager:ArgonConfigurationManager) { configurationManager.standardConfiguration(); } constructor( public configuration:Configuration, public container:DI.Container = new DI.Container, public elementOrSelector?:HTMLElement|string|null, ) { container.registerInstance(Configuration, configuration); if (Role.isRealityManager(configuration.role)) container.registerSingleton(ArgonSystemProvider); let element = elementOrSelector; if (!element || typeof element === 'string') { if (typeof document !== 'undefined') { const selector = element; element = selector ? <HTMLElement>document.querySelector(selector) : undefined; if (!element && !selector) { element = document.querySelector('#argon') as HTMLElement; if (!element) { element = document.createElement('div'); element.id = 'argon'; document.body.appendChild(element); } } else if (!element) { throw new Error('Unable to find element with selector: ' + selector); } } else { console.warn('No DOM environment is available'); element = undefined; } } const viewItems = new ViewItems(); viewItems.element = element; container.registerInstance(ViewItems, viewItems); ArgonConfigurationManager.configure(this); } standardConfiguration() { this.defaultConnect(); this.defaultUI(); } defaultConnect() { const container = this.container; const configuration = this.configuration; if (Role.isRealityManager(configuration.role)) { container.registerSingleton( ConnectService, LoopbackConnectService ); } else if (WKWebViewConnectService.isAvailable()) { container.registerSingleton( ConnectService, WKWebViewConnectService ) } else if (AndroidWebViewConnectService.isAvailable()) { container.registerSingleton( ConnectService, AndroidWebViewConnectService ) } else if (DOMConnectService.isAvailable()) { container.registerSingleton( ConnectService, DOMConnectService ) } else if (DebugConnectService.isAvailable()) { container.registerSingleton( ConnectService, DebugConnectService ); } } defaultUI() { if (Role.isRealityManager(this.configuration.role)) { if (typeof document !== 'undefined') { this.container.get(DefaultUIService); } } } } /** * Create an ArgonSystem instance. * If we are running within a [[REALITY_MANAGER]], * this function will create an ArgonSystem which has the [[REALITY_AUGMENTOR]] role. * If we are not running within a [[REALITY_MANAGER]], * this function will create an ArgonSystem which has the [[REALITY_MANAGER]] role. */ export function init(configuration?: Configuration, dependencyInjectionContainer?:DI.Container) : ArgonSystem; export function init(element?: string|HTMLDivElement|null, configuration?: Configuration, dependencyInjectionContainer?:DI.Container) : ArgonSystem; export function init( elementOrConfig?: any, configurationOrDIContainer?: any, dependencyInjectionContainer?:DI.Container ) : ArgonSystem { if (ArgonSystem.instance) throw new Error('A shared ArgonSystem instance already exists'); let element:string|HTMLDivElement|undefined; let configuration:Configuration|undefined; if (configurationOrDIContainer instanceof DI.Container) { configuration = elementOrConfig; dependencyInjectionContainer = configurationOrDIContainer; } else { element = elementOrConfig; configuration = configurationOrDIContainer; } // see if it is the old parameter interface if (element && (element['configuration'] || element['container'])) { const deprecatedParameters = element; if (!configuration && deprecatedParameters['configuration']) configuration = deprecatedParameters['configuration']; if (!configuration && deprecatedParameters['container']) dependencyInjectionContainer = deprecatedParameters['container']; element = undefined; } if (!configuration) configuration = {}; if (!configuration.role) { let role: Role; if (typeof HTMLElement === 'undefined') { role = Role.REALITY_MANAGER } else if (navigator.userAgent.indexOf('Argon') > 0 || window.top !== window) { role = Role.APPLICATION // TODO: switch to below after several argon-app releases // role = Role.REALITY_AUGMENTER } else { role = Role.REALITY_MANAGER } configuration.role = role; } if (!dependencyInjectionContainer) dependencyInjectionContainer = new DI.Container(); return new ArgonConfigurationManager(configuration, dependencyInjectionContainer, element).container.get(ArgonSystem); } /** * Initialize an [[ArgonSystem]] with the [[REALITY_VIEWER]] role */ export function initRealityViewer( configuration:Configuration = {}, dependencyInjectionContainer:DI.Container = new DI.Container ) : ArgonSystem { if (ArgonSystem.instance) throw new Error('A shared ArgonSystem instance already exists'); configuration.role = Role.REALITY_VIEW; // TODO: switch to below after several argon-app releases // configuration.role = Role.REALITY_VIEWER; configuration['supportsCustomProtocols'] = true; configuration['reality.supportsControlPort'] = true; // backwards compat for above configuration.protocols = configuration.protocols || []; configuration.protocols.push('ar.uievent') return new ArgonConfigurationManager(configuration, dependencyInjectionContainer).container.get(ArgonSystem); } /** * @private */ export const initReality = initRealityViewer;
the_stack
import RedisServer from "@/models/RedisServer" import IORedis, { RedisOptions } from "ioredis" import SSH2 from "ssh2" import Net, { Socket, Server, AddressInfo } from "net" import KeyInfo from "@/models/KeyInfo" export default class RedisStore { public static async createKey(server: RedisServer, dbIndex: number, key: string, value: string): Promise<string> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .set(key, value) // result 1 .exec() .then(result => { resolve(result) }) .catch(err => { reject(err) }) }) }) } public static async runCommand(server: RedisServer, command: string, args: any[], index: number): Promise<any> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis.select(index).then(() => { this.redis .send_command(command, args) .then((result: any) => { resolve(result) }) .catch((error: any) => { reject(error) }) }) }) }) } public static async exists(server: RedisServer, dbIndex: number, key: string): Promise<any> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .exists(key) // result 1 .exec() .then(result => { resolve(result[1][1]) }) .catch(err => { reject(err) }) }) }) } public static async move(server: RedisServer, dbIndex: number, key: string, toIndex: number): Promise<any> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .move(key, toIndex + "") .exec() .then(result => { resolve(result[1][1]) }) .catch(err => { reject(err) }) }) }) } public static async del(server: RedisServer, dbIndex: number, key: string): Promise<string> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .del(key) // result 1 .exec() .then(result => { resolve(result) }) .catch(err => { reject(err) }) }) }) } public static async rename(server: RedisServer, dbIndex: number, oldKey: string, newKey: string): Promise<string> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .rename(oldKey, newKey) // result 1 .exec() .then(result => { resolve(result) }) .catch(err => { reject(err) }) }) }) } public static async expire(server: RedisServer, dbIndex: number, key: string, seconds: number): Promise<string> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .expire(key, seconds) // result 1 .exec() .then(result => { resolve(result) }) .catch(err => { reject(err) }) }) }) } public static async persist(server: RedisServer, dbIndex: number, key: string): Promise<string> { return new Promise<string>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) // result 0 .persist(key) // result 1 .exec() .then(result => { resolve(result) }) .catch(err => { reject(err) }) }) }) } public static async dbsize(server: RedisServer, dbIndex: number): Promise<number> { return new Promise<number>((resolve, reject) => { this.create(server) .then(() => { this.redis .multi() .select(dbIndex) // result 0 .dbsize() // result 1 .exec() .then(result => { if (result[1][0]) { reject(result[1][0]) } else { resolve(result[1][1]) } }) }) .catch(err => { reject(err) }) }) } public static async databases(server: RedisServer): Promise<number> { return new Promise<number>((resolve, reject) => { this.create(server) .then(() => { this.redis.config("get", "databases").then((result: string[]) => { const databaseCount: number = (result[1] as unknown) as number resolve(databaseCount) }) }) .catch(err => { reject(err) }) }) } public static async keys(server: RedisServer, dbIndex: number, filter: string): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { this.create(server) .then(() => { if (filter !== "*") { filter = "*" + filter + "*" } this.redis .multi() .select(dbIndex) // result 0 .keys(filter) // result 1 .exec() .then(result => { if (result[1][0]) { reject(result[1][0]) } else { resolve(result[1][1]) } }) }) .catch(err => { reject(err) }) }) } public static async scanKeys(server: RedisServer, dbIndex: number, cursor: number, filter: string): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { this.create(server) .then(() => { if (filter !== "*") { filter = "*" + filter + "*" } this.redis .multi() .select(dbIndex) .scan(cursor, "count", 1000, "match", filter) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[1][0]) } else { resolve(result[1][1][1]) } }) }) .catch(err => { reject(err) }) }) } public static async info(server: RedisServer): Promise<any> { return new Promise<any>((resolve, reject) => { if (server.info.CPU) { resolve() } else { this.create(server).then(() => { this.redis.info((err, result) => { if (err) { reject(err) return } const infors = result.split("# ") out: for (const str of infors) { if (str === "") { continue out } const info = str.split("\r\n") server.info[info[0]] = {} inner: for (let j = 1; j < info.length; j++) { if (info[j] === "") { continue inner } const detail = info[j].split(":") server.info[info[0]][detail[0]] = detail[1] } } resolve() }) }) } }) } public static async keyInfo(server: RedisServer, dbIndex: number, key: string): Promise<KeyInfo> { return new Promise<KeyInfo>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .type(key) .ttl(key) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[1][0]) } else if (result[2][0]) { reject(result[2][0]) } else { const keyInfo: KeyInfo = new KeyInfo() keyInfo.type = result[1][1] keyInfo.ttl = result[2][1] resolve(keyInfo) } }) }) }) } public static async type(server: RedisServer, dbIndex: number, key: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .type(key) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[1][0]) } else { resolve(result[1][1]) } }) }) }) } public static async get(server: RedisServer, dbIndex: number, key: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .get(key) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve(result[1][1]) } }) }) }) } public static async set(server: RedisServer, dbIndex: number, key: string, value: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .set(key, value) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async hscan(server: RedisServer, dbIndex: number, key: string, filter: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .hscan(key, 0, "count", 1000, "match", filter) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { const arr: any[] = [] for (let i = 0; i < result[1][1][1].length; i += 2) { arr.push({ key: result[1][1][1][i], value: result[1][1][1][i + 1] }) } resolve(arr) } }) }) }) } public static async hset(server: RedisServer, dbIndex: number, key: string, hk: string, hv: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .hset(key, hk, hv) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async hsetnx(server: RedisServer, dbIndex: number, key: string, hk: string, hv: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .hsetnx(key, hk, hv) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async hdel(server: RedisServer, dbIndex: number, key: string, hk: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .hdel(key, hk) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async sscan(server: RedisServer, dbIndex: number, key: string, filter: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .sscan(key, 0, "count", 1000, "match", filter) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve(result[1][1][1]) } }) }) }) } public static async srem(server: RedisServer, dbIndex: number, key: string, item: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .srem(key, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async sadd(server: RedisServer, dbIndex: number, key: string, item: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .sadd(key, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async srename(server: RedisServer, dbIndex: number, key: string, oldField: string, newField: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .srem(key, oldField) .sadd(key, newField) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async zrename(server: RedisServer, dbIndex: number, key: string, oldField: string, newField: string, score: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .zrem(key, oldField) .zadd(key, score, newField) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async zscan(server: RedisServer, dbIndex: number, key: string, filter: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .zscan(key, 0, "count", 1000, "match", filter) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { const arr: any[] = [] for (let i = 0; i < result[1][1][1].length; i += 2) { arr.push({ key: result[1][1][1][i], value: result[1][1][1][i + 1] }) } resolve(arr) } }) }) }) } public static async zadd(server: RedisServer, dbIndex: number, key: string, item: string, score: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .zadd(key, score, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async zrem(server: RedisServer, dbIndex: number, key: string, item: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .zrem(key, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async lrange(server: RedisServer, dbIndex: number, key: string, start: number, end: number): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .lrange(key, start, end) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve(result[1][1]) } }) }) }) } public static async lrem(server: RedisServer, dbIndex: number, key: string, index: number): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .lset(key, index, "__การลบแท็ก__") // make list item a unique world .lrem(key, 1, "__การลบแท็ก__") // then delete it; .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async lpush(server: RedisServer, dbIndex: number, key: string, item: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .lpush(key, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async rpush(server: RedisServer, dbIndex: number, key: string, item: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .rpush(key, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } public static async llen(server: RedisServer, dbIndex: number, key: string): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .llen(key) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve(result[1][1]) } }) }) }) } public static async lset(server: RedisServer, dbIndex: number, key: string, item: string, index: number): Promise<any> { return new Promise<any>((resolve, reject) => { this.create(server).then(() => { this.redis .multi() .select(dbIndex) .lset(key, index, item) .exec() .then(result => { if (result[0][0]) { reject(result[0][0]) } else if (result[1][0]) { reject(result[0][0]) } else { resolve() } }) }) }) } private static redis: IORedis.Redis private static server?: RedisServer private static sshClient?: SSH2.Client private static async create(server: RedisServer): Promise<any> { return new Promise<any>((resolve, reject) => { if (this.server && this.server.name === server.name) { resolve() return } else { this.server = server if (this.redis) { this.redis.disconnect() } } const me = this const options: RedisOptions = { port: server.port, host: server.host, family: server.family, password: server.password, retryStrategy: () => { return false } } if (server.useSSH) { this.sshClient = new SSH2.Client() let netServer: Server this.sshClient .on("ready", () => { netServer = Net.createServer((socket: Socket) => { if (socket.remoteAddress && socket.remotePort && server.host && server.port) { if (me.sshClient) { me.sshClient.forwardOut(socket.remoteAddress, socket.remotePort, server.host, server.port, (err, stream) => { if (err) { socket.end() reject(err) } else { socket.pipe(stream).pipe(socket) } }) } } }).listen(0, () => { if (netServer != null) { const address: any = netServer.address() if (address) { me.redis = new IORedis( Object.assign( {}, options, { host: "127.0.0.1", port: address.port }, { retryStrategy: () => { return false } } ) ) me.redis.on("error", error => { reject(error) }) this.info(server).then(() => { resolve() }) } } }) }) .on("error", (err: any) => { reject(err) }) .connect({ host: server.sshHost, port: server.sshPort, username: server.sshUsername, privateKey: server.sshKeyPath ? require("fs").readFileSync(server.sshKeyPath) : "", password: server.sshPassword, passphrase: server.sshPassphrase }) } else { this.redis = new IORedis(options) this.info(server).then(() => { resolve() }) } }) } }
the_stack
import react_dom = require('react-dom'); import agile_keychain = require('../lib/agile_keychain'); import app_view = require('./app_view'); import assign = require('../lib/base/assign'); import autofill = require('./autofill'); import browser_access = require('./browser_access'); import dropboxvfs = require('../lib/vfs/dropbox'); import env = require('../lib/base/env'); import http_vfs = require('../lib/vfs/http'); import item_icons = require('./item_icons'); import key_agent = require('../lib/key_agent'); import key_value_store = require('../lib/base/key_value_store'); import local_store = require('../lib/local_store'); import settings = require('./settings'); import siteinfo_client = require('../lib/siteinfo/client'); import sync = require('../lib/sync'); import app_state = require('./stores/app'); import vfs = require('../lib/vfs/vfs'); import * as clipboard from './base/clipboard'; interface BrowserExtension { pageAccess: browser_access.BrowserAccess; clipboard: browser_access.ClipboardAccess; } export class App { // a reference to the rendered AppView instance private activeAppView: any; private state: app_state.Store; private services: app_view.AppServices; constructor() { var settingStore = new settings.LocalStorageStore(); var browserExt = this.setupBrowserExtension(); var keyAgent = new key_agent.SimpleKeyAgent(); keyAgent.setAutoLockTimeout( settingStore.get<number>(settings.Setting.AutoLockTimeout) ); var iconProvider = this.setupItemIconProvider(); this.services = { iconProvider: iconProvider, autofiller: new autofill.AutoFiller(browserExt.pageAccess), pageAccess: browserExt.pageAccess, keyAgent: keyAgent, clipboard: browserExt.clipboard, settings: settingStore, }; this.services.keyAgent.onLock().listen(() => { this.state.update({ isLocked: true }); }); this.state = new app_state.Store(); browserExt.pageAccess.events.listen(event => { switch (event.type) { case browser_access.MessageType.ExtensionUIShown: // in the Firefox add-on the active element loses focus when dismissing the // panel by focusing another UI element such as the URL input bar. // // Restore focus to the active element when the panel is shown again if (document.activeElement) { (<HTMLElement>document.activeElement).focus(); } break; case browser_access.MessageType.ActiveTabURLChanged: this.state.update({ currentUrl: (<browser_access.TabURLChangeMessage>event) .url, }); break; } }); // update the initial URL when the app is loaded this.state.update({ currentUrl: browserExt.pageAccess.currentUrl }); // handle login/logout events settingStore.onChanged.listen(setting => { if (setting == settings.Setting.ActiveAccount) { var accountId = settingStore.get<string>( settings.Setting.ActiveAccount ); var accounts = settingStore.get<settings.AccountMap>( settings.Setting.Accounts ); var account = accounts[accountId]; if (account) { this.initAccount(account); } else { keyAgent.forgetKeys(); this.state.update({ store: null, syncer: null }); } } }); // connect to current account if set var accountId = settingStore.get<string>( settings.Setting.ActiveAccount ); if (accountId) { var accounts = settingStore.get<settings.AccountMap>( settings.Setting.Accounts ); if (accounts && accounts[accountId]) { this.initAccount(accounts[accountId]); } } } private databaseKeyForAccount(account: settings.Account) { return `passcards-${account.id}`; } private createCloudFileSystem(account: settings.Account) { let fs: vfs.VFS; if (account.cloudService === settings.CloudService.Dropbox) { fs = new dropboxvfs.DropboxVFS(); } else if ( account.cloudService === settings.CloudService.LocalTestingServer ) { fs = new http_vfs.Client(http_vfs.DEFAULT_URL); } if (account.accessToken) { fs.setCredentials({ accessToken: account.accessToken, }); } return fs; } private updateAccount(updatedAccount: settings.Account) { let accounts = this.services.settings.get<settings.AccountMap>( settings.Setting.Accounts ); accounts[updatedAccount.id] = updatedAccount; this.services.settings.set(settings.Setting.Accounts, accounts); } // setup the local store, remote store and item syncing // once the user completes login private initAccount(account: settings.Account) { let fs = this.createCloudFileSystem(account); try { let itemDatabase = new key_value_store.IndexedDBDatabase(); let vault = new agile_keychain.Vault( fs, account.storePath, this.services.keyAgent ); let localDatabaseName = this.databaseKeyForAccount(account); let store = new local_store.Store( itemDatabase, localDatabaseName, this.services.keyAgent ); let syncer = new sync.CloudStoreSyncer(store, vault); // TODO - When setting up a new account, we need to defer the user logging in // until encryption keys have been synced syncer .syncKeys() .then(() => { console.log('Encryption keys synced'); }) .catch(err => { let handled = false; if (err instanceof vfs.VfsError) { let vfsErr = <vfs.VfsError>err; if (vfsErr.type === vfs.ErrorType.AuthError) { // if authentication fails, eg. due to the user revoking // access for the app, then prompt to sign in again this.state.update({ isSigningIn: true, authServerURL: fs.authURL.bind(fs), onReceiveCredentials: credentials => { fs.setCredentials(credentials); this.updateAccount( assign<settings.Account>( {}, account, credentials ) ); }, }); handled = true; } } if (!handled) { this.activeAppView.showError(err); } }); this.state.update({ store: store, syncer: syncer }); } catch (err) { this.activeAppView.showError(err, 'Store setup failed'); } } private getViewportRect(view: Window) { return { left: 0, right: view.innerWidth, top: 0, bottom: view.innerHeight, }; } /** Render the app into the given HTML element. */ renderInto(element: HTMLElement) { var rootInputElement = element.ownerDocument.body; // setup auto-lock rootInputElement.addEventListener('keydown', e => { this.services.keyAgent.resetAutoLock(); }); rootInputElement.addEventListener('click', e => { this.services.keyAgent.resetAutoLock(); }); // create main app view var appWindow = rootInputElement.ownerDocument.defaultView; var appView = app_view.AppViewF({ services: this.services, viewportRect: this.getViewportRect(appWindow), appState: this.state, }); this.activeAppView = react_dom.render(appView, element); if (!env.isTouchDevice()) { // the main item list only renders visible items, // so force a re-render when the window size changes. // // We don't do this for touch devices since the viewport // resizes (at least on Android) when the on-screen keyboard // is shown and we want to ignore that. // // TODO - Find a better solution for Android which // avoids re-rendering/zooming/scaling the UI when the keyboard // is shown but ensures that the app knows about the viewport // and can use it to avoid showing elements (eg. popup menus) // underneath the keyboard element.ownerDocument.defaultView.onresize = () => { this.activeAppView.setState({ viewportRect: this.getViewportRect( rootInputElement.ownerDocument.defaultView ), }); }; } } // setup the site icon database and connection to // the Passcards service for fetching site icons private setupItemIconProvider() { var siteInfoProvider = new siteinfo_client.PasscardsClient(); var iconDiskCache = new key_value_store.IndexedDBDatabase(); iconDiskCache.open('passcards', 1 /* version */, schemaModifier => { schemaModifier.createStore('icon-cache'); }); var ICON_SIZE = 48; return new item_icons.BasicIconProvider( iconDiskCache.store('icon-cache'), siteInfoProvider, ICON_SIZE ); } // setup access to the system clipboard and browser tabs via browser // extension APIs private setupBrowserExtension(): BrowserExtension { let pageAccess: browser_access.BrowserAccess; const clipboardAccess = { copy: clipboard.copy, clipboardAvailable() { return true; }, }; if (env.isChromeExtension()) { pageAccess = new browser_access.ChromeBrowserAccess(); } else { pageAccess = new browser_access.ExtensionBrowserAccess( new browser_access.FakeExtensionConnector() ); } return { pageAccess, clipboard: clipboardAccess, }; } }
the_stack
'use strict'; // eslint-disable-line strict import * as fs from 'fs'; import * as util from '../src/util/util'; import {createLayout, viewTypes} from '../src/util/struct_array'; import type {ViewType, StructArrayLayout} from '../src/util/struct_array'; import posAttributes from '../src/data/pos_attributes'; import rasterBoundsAttributes from '../src/data/raster_bounds_attributes'; import circleAttributes from '../src/data/bucket/circle_attributes'; import fillAttributes from '../src/data/bucket/fill_attributes'; import fillExtrusionAttributes from '../src/data/bucket/fill_extrusion_attributes'; import lineAttributes from '../src/data/bucket/line_attributes'; import lineAttributesExt from '../src/data/bucket/line_attributes_ext'; import patternAttributes from '../src/data/bucket/pattern_attributes'; // symbol layer specific arrays import { symbolLayoutAttributes, dynamicLayoutAttributes, placementOpacityAttributes, collisionBox, collisionBoxLayout, collisionCircleLayout, collisionVertexAttributes, quadTriangle, placement, symbolInstance, glyphOffset, lineVertex } from '../src/data/bucket/symbol_attributes'; const typeAbbreviations = { 'Int8': 'b', 'Uint8': 'ub', 'Int16': 'i', 'Uint16': 'ui', 'Int32': 'l', 'Uint32': 'ul', 'Float32': 'f' }; const arraysWithStructAccessors = []; const arrayTypeEntries = new Set(); const layoutCache = {}; function normalizeMembers(members, usedTypes) { return members.map((member) => { if (usedTypes && !usedTypes.has(member.type)) { usedTypes.add(member.type); } return util.extend(member, { size: sizeOf(member.type), view: member.type.toLowerCase() }); }); } // - If necessary, write the StructArrayLayout_* class for the given layout // - If `includeStructAccessors`, write the fancy subclass // - Add an entry for `name` in the array type registry function createStructArrayType(name: string, layout: StructArrayLayout, includeStructAccessors: boolean = false) { const hasAnchorPoint = layout.members.some(m => m.name === 'anchorPointX'); // create the underlying StructArrayLayout class exists const layoutClass = createStructArrayLayoutType(layout); const arrayClass = `${camelize(name)}Array`; if (includeStructAccessors) { const usedTypes = new Set(['Uint8']); const members = normalizeMembers(layout.members, usedTypes); arraysWithStructAccessors.push({ arrayClass, members, size: layout.size, usedTypes, hasAnchorPoint, layoutClass, includeStructAccessors }); } else { arrayTypeEntries.add(`${layoutClass} as ${arrayClass}`); } } function createStructArrayLayoutType({members, size, alignment}) { const usedTypes = new Set(['Uint8']); members = normalizeMembers(members, usedTypes); // combine consecutive 'members' with same underlying type, summing their // component counts if (!alignment || alignment === 1) members = members.reduce((memo, member) => { if (memo.length > 0 && memo[memo.length - 1].type === member.type) { const last = memo[memo.length - 1]; return memo.slice(0, -1).concat(util.extend({}, last, { components: last.components + member.components, })); } return memo.concat(member); }, []); const key = `${members.map(m => `${m.components}${typeAbbreviations[m.type]}`).join('')}${size}`; const className = `StructArrayLayout${key}`; // Layout alignment to 4 bytes boundaries can be an issue on some set of graphics cards. Particularly AMD. if (size % 4 !== 0) { console.warn(`Warning: The layout ${className} is not aligned to 4-bytes boundaries.`); } if (!layoutCache[key]) { layoutCache[key] = { className, members, size, usedTypes }; } return className; } function sizeOf(type: ViewType): number { return viewTypes[type].BYTES_PER_ELEMENT; } function camelize (str) { return str.replace(/(?:^|[-_])(.)/g, (_, x) => { return /^[0-9]$/.test(x) ? _ : x.toUpperCase(); }); } createStructArrayType('pos', posAttributes); createStructArrayType('raster_bounds', rasterBoundsAttributes); // layout vertex arrays const layoutAttributes = { circle: circleAttributes, fill: fillAttributes, 'fill-extrusion': fillExtrusionAttributes, heatmap: circleAttributes, line: lineAttributes, lineExt: lineAttributesExt, pattern: patternAttributes }; for (const name in layoutAttributes) { createStructArrayType(`${name.replace(/-/g, '_')}_layout`, layoutAttributes[name]); } createStructArrayType('symbol_layout', symbolLayoutAttributes); createStructArrayType('symbol_dynamic_layout', dynamicLayoutAttributes); createStructArrayType('symbol_opacity', placementOpacityAttributes); createStructArrayType('collision_box', collisionBox, true); createStructArrayType('collision_box_layout', collisionBoxLayout); createStructArrayType('collision_circle_layout', collisionCircleLayout); createStructArrayType('collision_vertex', collisionVertexAttributes); createStructArrayType('quad_triangle', quadTriangle); createStructArrayType('placed_symbol', placement, true); createStructArrayType('symbol_instance', symbolInstance, true); createStructArrayType('glyph_offset', glyphOffset, true); createStructArrayType('symbol_line_vertex', lineVertex, true); // feature index array createStructArrayType('feature_index', createLayout([ // the index of the feature in the original vectortile { type: 'Uint32', name: 'featureIndex' }, // the source layer the feature appears in { type: 'Uint16', name: 'sourceLayerIndex' }, // the bucket the feature appears in { type: 'Uint16', name: 'bucketIndex' } ]), true); // triangle index array createStructArrayType('triangle_index', createLayout([ { type: 'Uint16', name: 'vertices', components: 3 } ])); // line index array createStructArrayType('line_index', createLayout([ { type: 'Uint16', name: 'vertices', components: 2 } ])); // line strip index array createStructArrayType('line_strip_index', createLayout([ { type: 'Uint16', name: 'vertices', components: 1 } ])); // paint vertex arrays // used by SourceBinder for float properties createStructArrayLayoutType(createLayout([{ name: 'dummy name (unused for StructArrayLayout)', type: 'Float32', components: 1 }], 4)); // used by SourceBinder for color properties and CompositeBinder for float properties createStructArrayLayoutType(createLayout([{ name: 'dummy name (unused for StructArrayLayout)', type: 'Float32', components: 2 }], 4)); // used by CompositeBinder for color properties createStructArrayLayoutType(createLayout([{ name: 'dummy name (unused for StructArrayLayout)', type: 'Float32', components: 4 }], 4)); const layouts = Object.keys(layoutCache).map(k => layoutCache[k]); function emitStructArrayLayout(locals) { const output = []; const { className, members, size, usedTypes } = locals; const structArrayLayoutClass = className; output.push( `/** * Implementation of the StructArray layout:`); for (const member of members) { output.push( ` * [${member.offset}]: ${member.type}[${member.components}]`); } output.push( ` * * @private */ class ${structArrayLayoutClass} extends StructArray {`); for (const type of usedTypes) { output.push( ` ${type.toLowerCase()}: ${type}Array;`); } output.push(` _refreshViews() {`); for (const type of usedTypes) { output.push( ` this.${type.toLowerCase()} = new ${type}Array(this.arrayBuffer);`); } output.push( ' }'); // prep for emplaceBack: collect type sizes and count the number of arguments // we'll need const bytesPerElement = size; const usedTypeSizes = []; const argNames = []; const argNamesTyped = []; for (const member of members) { if (usedTypeSizes.indexOf(member.size) < 0) { usedTypeSizes.push(member.size); } for (let c = 0; c < member.components; c++) { // arguments v0, v1, v2, ... are, in order, the components of // member 0, then the components of member 1, etc. const name = `v${argNames.length}`; argNames.push(name); argNamesTyped.push(`${name}: number`); } } output.push( ` public emplaceBack(${argNamesTyped.join(', ')}) { const i = this.length; this.resize(i + 1); return this.emplace(i, ${argNames.join(', ')}); } public emplace(i: number, ${argNamesTyped.join(', ')}) {`); for (const size of usedTypeSizes) { output.push( ` const o${size.toFixed(0)} = i * ${(bytesPerElement / size).toFixed(0)};`); } let argIndex = 0; for (const member of members) { for (let c = 0; c < member.components; c++) { // The index for `member` component `c` into the appropriate type array is: // this.{TYPE}[o{SIZE} + MEMBER_OFFSET + {c}] = v{X} // where MEMBER_OFFSET = ROUND(member.offset / size) is the per-element // offset of this member into the array const index = `o${member.size.toFixed(0)} + ${(member.offset / member.size + c).toFixed(0)}`; output.push( ` this.${member.view}[${index}] = v${argIndex++};`); } } output.push( ` return i; } } ${structArrayLayoutClass}.prototype.bytesPerElement = ${size}; register('${structArrayLayoutClass}', ${structArrayLayoutClass}); `); return output.join('\n'); } function emitStructArray(locals) { const output = []; const { arrayClass, members, size, hasAnchorPoint, layoutClass, includeStructAccessors } = locals; const structTypeClass = arrayClass.replace('Array', 'Struct'); const structArrayClass = arrayClass; const structArrayLayoutClass = layoutClass; // collect components const components = []; for (const member of members) { for (let c = 0; c < member.components; c++) { let name = member.name; if (member.components > 1) { name += c; } components.push({name, member, component: c}); } } // exceptions for which we generate accessors on the array rather than a separate struct for performance const useComponentGetters = structArrayClass === 'GlyphOffsetArray' || structArrayClass === 'SymbolLineVertexArray'; if (includeStructAccessors && !useComponentGetters) { output.push( `class ${structTypeClass} extends Struct { _structArray: ${structArrayClass};`); for (const {name, member, component} of components) { const elementOffset = `this._pos${member.size.toFixed(0)}`; const componentOffset = (member.offset / member.size + component).toFixed(0); const index = `${elementOffset} + ${componentOffset}`; const componentAccess = `this._structArray.${member.view}[${index}]`; output.push( ` get ${name}() { return ${componentAccess}; }`); // generate setters for properties that are updated during runtime symbol placement; others are read-only if (name === 'crossTileID' || name === 'placedOrientation' || name === 'hidden') { output.push( ` set ${name}(x: number) { ${componentAccess} = x; }`); } } // Special case used for the CollisionBoxArray type if (hasAnchorPoint) { output.push( ' get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); }'); } output.push( `} ${structTypeClass}.prototype.size = ${size}; export type ${structTypeClass.replace('Struct', '')} = ${structTypeClass}; `); } // end 'if (includeStructAccessors)' output.push( `/** * @private */ export class ${structArrayClass} extends ${structArrayLayoutClass} {`); if (useComponentGetters) { for (const member of members) { for (let c = 0; c < member.components; c++) { if (!includeStructAccessors) continue; let name = `get${member.name}`; if (member.components > 1) { name += c; } const componentOffset = (member.offset / member.size + c).toFixed(0); const componentStride = size / member.size; output.push( ` ${name}(index: number) { return this.${member.view}[index * ${componentStride} + ${componentOffset}]; }`); } } } else if (includeStructAccessors) { // get(i) output.push( ` /** * Return the ${structTypeClass} at the given location in the array. * @param {number} index The index of the element. * @private */ get(index: number): ${structTypeClass} { assert(!this.isTransferred); return new ${structTypeClass}(this, index); }`); } output.push( `} register('${structArrayClass}', ${structArrayClass}); `); return output.join('\n'); } fs.writeFileSync('src/data/array_types.ts', `// This file is generated. Edit build/generate-struct-arrays.ts, then run \`npm run codegen\`. import assert from 'assert'; import {Struct, StructArray} from '../util/struct_array'; import {register} from '../util/web_worker_transfer'; import Point from '../util/point'; ${layouts.map(emitStructArrayLayout).join('\n')} ${arraysWithStructAccessors.map(emitStructArray).join('\n')} export { ${layouts.map(layout => layout.className).join(',\n ')}, ${[...arrayTypeEntries].join(',\n ')} }; `);
the_stack
declare module 'tle.js' { /** * Generic degrees. Generally 0 to 360 degrees unless otherwise noted. */ export type Degrees = number; export type Meters = number; export type Kilometers = number; export type KilometersPerSecond = number; /** * Latitude in degrees. * Range: from -90 to 90. */ export type LatitudeDegrees = number; /** * Longitude in degrees. * Range: from -180 to 180. */ export type LongitudeDegrees = number; /** * Unix timestamp in milliseconds. */ export type Timestamp = number; export type Minutes = number; export type Seconds = number; export type Milliseconds = number; /** * TLE in unknown format, to be normalized by parseTLE(). */ export type TLE = string | [string, TLELine, TLELine] | [TLELine, TLELine] | ParsedTLE; export type TLELine = string; /** * Three ground track arrays (last, current, and next orbit). */ export type ThreeGroundTracks = [LngLat[], LngLat[], LngLat[]]; /** * Output of getBstarDrag() in EarthRadii ^ -1 units. */ export type BSTARDragOutput = number; /** * Output of getFirstTimeDerivative() in orbits / day ^ 2 units. */ export type FirstTimeDerivativeOutput = number; /** * Output of getSecondTimeDerivative() in orbits / day ^ 3 units. */ export type SecondTimeDerivativeOutput = number; export enum SatelliteClassification { Unclassified = "U", Classified = "C", Secret = "S" } /** * Input for getGroundTracks() and getGroundTracksSync(). */ export interface GroundTracksInput { /** Satellite TLE. */ tle: TLE, /** * Unix timestamp in milliseconds. * @default Current time. */ startTimeMS?: Timestamp, /** * Time in milliseconds between points in the ground track. * @default 1000 */ stepMS?: Milliseconds, /** * Whether coords are in [lng, lat] format. * @default true */ isLngLatFormat?: boolean } /** * Longitude, latitude pair in Array format. Note that this format is reversed from the more familiar * lat/lng format in order to be easily used for GeoJSON, which formats points as [lng, lat]. * @example [-117.918976, 33.812511] */ export interface LngLat { [0]: LongitudeDegrees; [1]: LatitudeDegrees } /** * Latitude, longitude pair in Object format. * @example { lat: 33.812511, lng: -117.918976 } */ export interface LatLngObject { lat: LatitudeDegrees, lng: LongitudeDegrees } /** * Output of parseTLE(). TLE normalized into a predictable format for fast lookups. */ export interface ParsedTLE { /** * Satellite name (only extracted from 3-line TLE inputs). * @default "Unknown" */ name?: string, /** Two-line TLE. */ tle: [TLELine, TLELine] } /** * Input for getOrbitTrackSync(). Note that getOrbitTrack() uses OrbitTrackInput instead. */ export interface OrbitTrackSyncInput { /** * TLE input. */ tle: TLE, /** * Time to begin drawing the orbit track from. * @default Current time. */ startTimeMS?: Timestamp, /** * Time to begin drawing the orbit track from. * @default 1000 */ stepMS?: Timestamp, /** * Maximum milliseconds to process before returning. This is needed for geosynchronous satellites, * because they never cross the antemeridian. * @default 6000000 */ maxTimeMS?: Milliseconds, /** * Whether to output in [lng, lat] format. * @default true */ isLngLatFormat?: boolean } /** * Input for getOrbitTrack(). Note that getOrbitTrackSync() uses OrbitTrackInputSync instead. */ export interface OrbitTrackInput extends OrbitTrackSyncInput { /** * (Experimental) Time to "cool off" between processing chunks. * @default 0 */ sleepMS?: Milliseconds, /** * (Experimental) Satellite positions to calculate in one "chunk" before cooling off. * @default 1000 */ jobChunkSize?: number } /** * Output for getSatBearing(). */ export interface SatBearingOutput { degrees: Degrees, compass: string } /** * Output for getSatelliteInfo(). */ export interface SatelliteInfoOutput { /** (degrees) Satellite compass heading from observer (0 = north, 180 = south). */ azimuth: Degrees, /** (degrees) Satellite elevation from observer (90 is directly overhead). */ elevation: Degrees, /** (km) Distance from observer to spacecraft. */ range: Kilometers, /** (km) Spacecraft altitude. */ height: Kilometers, /** (degrees) Spacecraft latitude. */ lat: LatitudeDegrees, /** (degrees) Spacecraft longitude. */ lng: LongitudeDegrees, /** (km/s) Spacecraft velocity. */ velocity: KilometersPerSecond } /** * Input for getVisibleSatellites(). */ export interface VisibleSatellitesInput { /** * (degrees) Ground observer latitude. */ observerLat: LatitudeDegrees, /** * (degrees) Ground observer longitude. */ observerLng: LongitudeDegrees, /** * (km) Ground observer elevation. * @default 0 */ observerHeight: Kilometers, /** * Full list of known TLEs. * @default [] */ tles: TLE[], /** * (degrees) Filters out satellites that are below this degree threshold (0 is horizon, 90 is straight up, * negative numbers are below the horizon). * @default 0 */ elevationThreshold: Degrees, /** * Full list of known TLEs. * @default Current time. */ timestampMS: Timestamp } /** * Clears SGP caches to free up memory for long-running apps. */ export function clearCache(): undefined; /** * Returns the current sizes of SGP caches. */ export function getCacheSizes(): number[]; /** * (Async) Calculates three orbit tracks for a TLE (previous, current, and next orbits). */ export function getGroundTracks(input: GroundTracksInput): Promise<ThreeGroundTracks>; /** * (Sync) Calculates three orbit tracks for a TLE (previous, current, and next orbits). */ export function getGroundTracksSync(input: GroundTracksInput): ThreeGroundTracks; /** * Determines the last time the satellite crossed the antemeridian. Returns -1 if not found * (e.g. for geosynchronous satellites). * * @param parsedTLE TLE parsed by parseTLE(). * @param startTime Relative time to determine the previous antemeridian crossing time. */ export function getLastAntemeridianCrossingTimeMS(parsedTLE: ParsedTLE, startTime: Timestamp): Timestamp | -1; /** * Determines satellite position for the given time. * * @param tle TLE input. * @param timestamp Timestamp to get position for. */ export function getLatLngObj(tle: TLE, timestamp?: Timestamp): LatLngObject; /** * Determines the satellite's position at the time of the TLE epoch (when the TLE was generated). * * @param tle TLE input. */ export function getLngLatAtEpoch(tle: TLE): LngLat; /** * (Async) Generates an array of lng/lat pairs representing a ground track (orbit track), starting * from startTimeMS and continuing until just before crossing the antemeridian, which is considered the end * of the orbit for convenience. * * Consider pairing this with getLastAntemeridianCrossingTimeMS() to create a full orbit path (see usage * in getGroundTracks()). */ export function getOrbitTrack(input: OrbitTrackInput): Promise<LngLat[]>; /** * (Sync) Generates an array of lng/lat pairs representing a ground track (orbit track), starting * from startTimeMS and continuing until just before crossing the antemeridian, which is considered the end * of the orbit for convenience. * * Consider pairing this with getLastAntemeridianCrossingTimeMS() to create a full orbit path (see usage * in getGroundTracksSync()). */ export function getOrbitTrackSync(input: OrbitTrackSyncInput): LngLat[]; /** * (Experimental) Determines the compass bearing from the perspective of the satellite. * Useful for 3D / pitched map perspectives. */ export function getSatBearing(tle: TLE, timeMS?: Timestamp): SatBearingOutput; /** * Determines satellite position and look angles from an earth observer. * Note that observer input arguments are only needed if you are interested in observer-relative * outputs (azimuth, elevation, and range). */ export function getSatelliteInfo( /** TLE input. */ tle: TLE, /** Timestamp to get satellite position for. */ timestamp: Timestamp, /** * (degrees) Ground observer latitude. Only needed for azimuth, elevation, and range. * @default 36.9613422 */ observerLat?: LatitudeDegrees, /** * (degrees) Ground observer longitude. Only needed for azimuth, elevation, and range. * @default -122.0308 */ observerLng?: LongitudeDegrees, /** * (m) Ground observer meters above the ellipsoid. Only needed for azimuth, elevation, and range. * @default 0.37 */ observerHeight?: Meters): SatelliteInfoOutput; /** * Determines which satellites are currently visible, assuming a completely flat horizon. */ export function getVisibleSatellites(input: VisibleSatellitesInput): SatelliteInfoOutput[]; /** * BSTAR drag term. This estimates the effects of atmospheric drag on the satellite's motion. * See https://en.wikipedia.org/wiki/BSTAR, https://celestrak.com/columns/v04n03, and * http://www.castor2.ca/03_Mechanics/03_TLE/B_Star.html * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getBstarDrag('1 25544U 98067A 17206.18396726 ...'); * 0.000036771 */ export function getBstarDrag(tle: TLE, isTLEParsed?: boolean): BSTARDragOutput; /** * Returns the Space Catalog Number (aka NORAD Catalog Number). * See https://en.wikipedia.org/wiki/Satellite_Catalog_Number * Output range: 0 to 99999 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getCatalogNumber('1 25544U 98067A 17206.18396726 ...'); * 25544 */ export function getCatalogNumber(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the Space Catalog Number (aka NORAD Catalog Number) from the first line of the TLE. * See https://en.wikipedia.org/wiki/Satellite_Catalog_Number * Output range: 0 to 99999 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getCatalogNumber1('1 25544U 98067A 17206.18396726 ...'); * 25544 */ export function getCatalogNumber1(tle: TLE, isTLEParsed?: boolean): number; /** * TLE line 1 checksum (modulo 10), for verifying the integrity of this line of the TLE. Note that * letters, blanks, periods, and plus signs are counted as 0, while minus signs are counted as 1. * Output range: 0 to 9 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getChecksum1('1 25544U 98067A 17206.18396726 ...'); * 3 */ export function getChecksum1(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the satellite classification. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getClassification('1 25544U 98067A 17206.18396726 ...'); * 'U' // = unclassified */ export function getClassification(tle: TLE, isTLEParsed?: boolean): SatelliteClassification; /** * Returns the TLE epoch day of the year (day of year with fractional portion of the day) when the * TLE was generated. For example, a TLE generated on January 1 will return something like * `1.18396726`. * Output range: 1 to 365.99999999 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getEpochDay('1 25544U 98067A 17206.18396726 ...'); * 206.18396726 */ export function getEpochDay(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the TLE epoch year (last two digits) when the TLE was generated. For example, a TLE * generated in 2022 will return `22`. * Output range: 00 to 99. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getEpochYear('1 25544U 98067A 17206.18396726 ...'); * 17 */ export function getEpochYear(tle: TLE, isTLEParsed?: boolean): number; /** * First Time Derivative of the Mean Motion divided by two, measured in orbits per day per day * (orbits/day ^ 2). Defines how mean motion changes from day to day, so TLE propagators can still be * used to make reasonable guesses when distant from the original TLE epoch. Can be a negative * or positive number. * Aka mean motion dot. * See https://en.wikipedia.org/wiki/Mean_Motion * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getFirstTimeDerivative('1 25544U 98067A 17206.18396726 ...'); * 0.00001961 */ export function getFirstTimeDerivative(tle: TLE, isTLEParsed?: boolean): FirstTimeDerivativeOutput; /** * Returns the launch number of the year, which makes up part of the COSPAR id * (international designator). For example, the 50th launch of the year will return 50. * See https://en.wikipedia.org/wiki/International_Designator * Output range: 1 to 999 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getIntDesignatorLaunchNumber('1 25544U 98067A 17206.18396726 ...'); * 67 */ export function getIntDesignatorLaunchNumber(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the piece of the launch, which makes up part of the COSPAR id (international designator). * For example, "A" represents the primary payload, followed by secondary payloads, rockets involved * in the launch, and any subsequent debris. * See https://en.wikipedia.org/wiki/International_Designator * Output range: A to ZZZ * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getIntDesignatorPieceOfLaunch('1 25544U 98067A 17206.18396726 ...'); * "A" */ export function getIntDesignatorPieceOfLaunch(tle: TLE, isTLEParsed?: boolean): string; /** * Returns the launch year (last two digits), which makes up part of the COSPAR id * (international designator). For example, a satellite launched in 1999 will return "99". * See https://en.wikipedia.org/wiki/International_Designator * Output range: 00 to 99 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getIntDesignatorYear('1 25544U 98067A 17206.18396726 ...'); * 98 */ export function getIntDesignatorYear(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the line number from line 1. Should always return "1" for valid TLEs. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getLineNumber1('1 25544U 98067A 17206.18396726 ...'); * 1 */ export function getLineNumber1(tle: TLE, isTLEParsed?: boolean): number; /** * Private value - used by Air Force Space Command to reference the orbit model used to generate the * TLE (e.g. SGP, SGP4). Distributed TLES will always return 0 for this value. Note that all * distributed TLEs are generated with SGP4/SDP4. * See https://celestrak.com/columns/v04n03/ * Output range: 0 to 9 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getOrbitModel('1 25544U 98067A 17206.18396726 ...'); * 0 */ export function getOrbitModel(tle: TLE, isTLEParsed?: boolean): number; /** * Second Time Derivative of Mean Motion divided by six, measured in orbits per day per day per day * (orbits/day ^ 3). Similar to the first time derivative, it measures rate of change in the Mean * Motion Dot so software can make reasonable guesses when distant from the original TLE epoch. Normally * zero unless the satellite is manuevering or has a decaying orbit. * See https://en.wikipedia.org/wiki/Mean_Motion and http://castor2.ca/03_Mechanics/03_TLE/Mean_Mot_Dot.html * Aka mean motion double dot. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getSecondTimeDerivative('1 25544U 98067A 17206.18396726 ...'); * 0 */ export function getSecondTimeDerivative(tle: TLE, isTLEParsed?: boolean): SecondTimeDerivativeOutput; /** * TLE element set number, incremented for each new TLE generated since launch. 999 seems to mean * the TLE has maxed out. * Output range: technically 1 to 9999, though in practice the maximum number seems to be 999. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getTleSetNumber('1 25544U 98067A 17206.18396726 ...'); * 999 */ export function getTleSetNumber(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the Space Catalog Number (aka NORAD Catalog Number) from the second line of the TLE. * See https://en.wikipedia.org/wiki/Satellite_Catalog_Number * Output range: 0 to 99999 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getCatalogNumber2('1 25544U 98067A 17206.18396726 ...'); * 25544 */ export function getCatalogNumber2(tle: TLE, isTLEParsed?: boolean): number; /** * TLE line 2 checksum (modulo 10), for verifying the integrity of this line of the TLE. Note that * letters, blanks, periods, and plus signs are counted as 0, while minus signs are counted as 1. * Output range: 0 to 9 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getChecksum2('1 25544U 98067A 17206.18396726 ...'); * 0 */ export function getChecksum2(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the orbital eccentricity. All artificial Earth satellites have an eccentricity between 0 * (perfect circle) and 1 (parabolic orbit). * See https://en.wikipedia.org/wiki/Orbital_eccentricity * Output range: 0 to 1 * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getEccentricity('1 25544U 98067A 17206.18396726 ...'); * 0.0006317 */ export function getEccentricity(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the inclination relative to the Earth's equatorial plane in degrees (0 to 180 degrees). * 0 to 90 degrees is a prograde orbit and 90 to 180 degrees is a retrograde orbit. * See https://en.wikipedia.org/wiki/Orbital_inclination * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getInclination('1 25544U 98067A 17206.18396726 ...'); * 51.6400 */ export function getInclination(tle: TLE, isTLEParsed?: boolean): Degrees; /** * Returns the line number from line 2. Should always return "2" for valid TLEs. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getLineNumber2('1 25544U 98067A 17206.18396726 ...'); * 2 */ export function getLineNumber2(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the Mean Anomaly. Indicates where the satellite was located within its orbit at the * time of the TLE epoch. * See https://en.wikipedia.org/wiki/Mean_Anomaly * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getMeanAnomaly('1 25544U 98067A 17206.18396726 ...'); * 25.2906 */ export function getMeanAnomaly(tle: TLE, isTLEParsed?: boolean): Degrees; /** * Returns the revolutions around the Earth per day (mean motion). Theoretically can be a value * between 0 to 17. * See https://en.wikipedia.org/wiki/Mean_Motion * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getMeanMotion('1 25544U 98067A 17206.18396726 ...'); * 15.54225995 */ export function getMeanMotion(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the argument of perigee. * See https://en.wikipedia.org/wiki/Argument_of_perigee * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getPerigee('1 25544U 98067A 17206.18396726 ...'); * 69.9862 */ export function getPerigee(tle: TLE, isTLEParsed?: boolean): Degrees; /** * Returns the total satellite revolutions when this TLE was generated (0 to 99999). This number * seems to roll over (e.g. 99999 -> 0). * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getRevNumberAtEpoch('1 25544U 98067A 17206.18396726 ...'); * 6766 */ export function getRevNumberAtEpoch(tle: TLE, isTLEParsed?: boolean): number; /** * Returns the right ascension of the ascending node in degrees. Essentially, this is the angle of * the satellite as it crosses northward (ascending) across the Earth's equator (equatorial plane). * See https://en.wikipedia.org/wiki/Right_ascension_of_the_ascending_node * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getRightAscension('1 25544U 98067A 17206.18396726 ...'); * 208.9163 */ export function getRightAscension(tle: TLE, isTLEParsed?: boolean): Degrees; /** * Determines COSPAR ID (International Designator). * See https://en.wikipedia.org/wiki/International_Designator * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getCOSPAR('1 25544U 98067A 17206.18396726 ...'); * "1998-067A" */ export function getCOSPAR(tle: TLE, isTLEParsed: boolean): string; /** * Determines the name of a satellite, if present in the first line of a 3-line TLE. If not found, * returns "Unknown" by default (or the COSPAR ID when fallbackToCOSPAR is true). * * @param tle Input TLE. * @param fallbackToCOSPAR If satellite name isn't found, returns COSPAR ID instead of "Unknown". * * @example * getSatelliteName('1 25544U 98067A 17206.51418 ...'); * "ISS (ZARYA)" */ export function getSatelliteName(tle: TLE, fallbackToCOSPAR?: boolean): string; /** * Determines the timestamp of a TLE epoch (the time a TLE was generated). * * @param tle Input TLE. * * @example * getEpochTimestamp('1 25544U 98067A 17206.51418 ...'); * 1500956694771 */ export function getEpochTimestamp(): Timestamp; /** * Determines the average amount of milliseconds in one orbit. * * @param tle Input TLE. * * @example * getAverageOrbitTimeMS('1 25544U 98067A 17206.51418 ...'); * 5559037 */ export function getAverageOrbitTimeMS(tle: TLE): Milliseconds; /** * Determines the average amount of minutes in one orbit. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getAverageOrbitTimeMins('1 25544U 98067A 17206.51418 ...'); * 92.65061666666666 */ export function getAverageOrbitTimeMins(tle: TLE): Minutes; /** * Determines the average amount of seconds in one orbit. * * @param tle Input TLE. * @param isTLEParsed Bypasses TLE parsing when true. * * @example * getAverageOrbitTimeS('1 25544U 98067A 17206.51418 ...'); * 5559.037 */ export function getAverageOrbitTimeS(tle: TLE): Seconds; /** * Converts string and array TLE formats into a parsed TLE in a consistent object format. * Accepts 2 and 3-line (with satellite name) TLE variants in string (\n-delimited) and array * variants. * * @param tle Input TLE. */ export function parseTLE(tle: TLE): ParsedTLE; /** * Determines if a TLE is structurally valid. * * @param tle Input TLE. */ export function isValidTLE(tle: TLE): boolean; /** * Determines the checksum for a single line of a TLE. * Checksum = modulo 10 of sum of all numbers (including line number) + 1 for each negative * sign (-). Everything else is ignored. * * @param singleTLELine One line of a TLE. * * @example * computeChecksum('1 25544U 98067A 17206.51418 ...'); * 3 */ export function computeChecksum(singleTLELine: string): number; /** * Clears the TLE parse cache, which may be useful for long-running app.s */ export function clearTLEParseCache(): undefined; }
the_stack
import Decimal from 'break_infinity.js'; import { GlobalVariables } from './types/Synergism'; export const Globals: GlobalVariables = { runediv: [1.5, 2, 3, 5, 8, 1, 1], runeexpbase: [1, 4, 9, 16, 1000, 1e75, 1e256], runeMaxLvl: 40000, // this shows the logarithm of costs. ex: upgrade one will cost 1e+6 coins, upgrade 2 1e+7, etc. upgradeCosts: [0, 6, 7, 8, 10, 12, 20, 25, 30, 35, 45, 55, 75, 110, 150, 200, 250, 500, 750, 1000, 1500, 2, 3, 4, 5, 6, 7, 10, 13, 20, 30, 150, 400, 800, 1600, 3200, 10000, 20000, 50000, 100000, 200000, 1, 2, 3, 5, 6, 7, 42, 65, 87, 150, 300, 500, 1000, 1500, 2000, 3000, 6000, 12000, 25000, 75000, 0, 1, 2, 2, 3, 5, 6, 10, 15, 22, 30, 37, 45, 52, 60, 1900, 2500, 3000, 7482, 21397, 3, 6, 9, 12, 15, 20, 30, 6, 8, 8, 10, 13, 60, 1, 2, 4, 8, 16, 25, 40, 12, 16, 20, 30, 50, 500, 1250, 5000, 25000, 125000, 1500, 7500, 30000, 150000, 1000000, 250, 1000, 5000, 25000, 125000, 1e3, 1e6, 1e9, 1e12, 1e15], // Mega list of Variables to be used elsewhere crystalUpgradesCost: [6, 15, 20, 40, 100, 200, 500, 1000], crystalUpgradeCostIncrement: [8, 15, 20, 40, 100, 200, 500, 1000], researchBaseCosts: [1e200, 1, 1, 1, 1, 1, 1, 1e2, 1e4, 1e6, 1e8, 2, 2e2, 2e4, 2e6, 2e8, 4e4, 4e8, 10, 1e5, 1e9, 100, 100, 1e4, 2e3, 2e5, 40, 200, 50, 5000, 20000000, 777, 7777, 50000, 500000, 5000000, 2e3, 2e6, 2e9, 1e5, 1e9, 1, 1, 5, 25, 125, 2, 5, 320, 1280, 2.5e9, 10, 2e3, 4e5, 8e7, 2e9, 5, 400, 1e4, 3e6, 9e8, 100, 2500, 100, 2000, 2e5, 1, 20, 3e3, 4e5, 5e7, 10, 40, 160, 1000, 10000, 4e9, 7e9, 1e10, 1.2e10, 1.5e10, 1e12, 1e13, 3e12, 2e13, 2e13, 2e14, 6e14, 2e15, 6e15, 2e16, 1e16, 2e16, 2e17, 4e17, 1e18, 1e13, 1e14, 1e15, 7.777e18, 7.777e20, 1e16, 3e16, 1e17, 3e17, 1e20, 1e18, 3e18, 1e19, 3e19, 1e20, 1e20, 2e20, 4e20, 8e20, 1e21, 2e21, 4e21, 8e21, 2e22, 4e22, 3.2e21, 2e23, 4e23, 1e21, 7.777e32, 5e8, 5e12, 5e16, 5e20, 5e24, /*ascension tier */ 1e25, 2e25, 4e25, 8e25, 1e26, 4e26, 8e26, 1e27, 2e27, 1e28, 5e9, 5e15, 5e21, 5e27, 1e28, /*challenge 11 tier */ 1e29, 2e29, 4e29, 8e29, 1e27, 2e30, 4e30, 8e30, 1e31, 2e31, 5e31, 1e32, 2e32, 4e32, 8e32, /*challenge 12 tier */ 1e33, 2e33, 4e33, 8e33, 1e34, 3e34, 1e35, 3e35, 6e35, 1e36, 3e36, 1e37, 3e37, 1e38, 3e38, /*challenge 13 tier */ 1e39, 3e39, 1e40, 3e40, 1e50, 3e41, 1e42, 3e42, 6e42, 1e43, 3e43, 1e44, 3e44, 1e45, 3e45, /*challenge 14 tier */ 2e46, 6e46, 2e47, 6e47, 1e64, 6e48, 2e49, 1e50, 1e51, 4e56 ], researchMaxLevels: [0, 1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 1, 1, 25, 25, 25, 20, 20, 10, 10, 10, 10, 10, 12, 12, 10, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 1, 5, 4, 5, 5, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 10, 50, 50, 50, 50, 10, 1, 20, 20, 20, 20, 20, 20, 20, 10, 20, 20, 20, 20, 1, 20, 5, 5, 3, 2, 10, 10, 10, 10, 1, 10, 10, 20, 25, 25, 50, 50, 50, 50, 100, 10, 10, 10, 100, 100, 25, 25, 25, 1, 5, 10, 10, 10, 10, 1, 10, 10, 10, 1, 1, 25, 25, 25, 15, 1, 10, 10, 10, 10, 1, 10, 1, 6, 10, 1, 25, 25, 1, 15, 1, 10, 10, 10, 1, 1, 10, 10, 10, 10, 1, 25, 25, 25, 15, 1, 10, 10, 10, 1, 1, 10, 3, 6, 10, 5, 25, 25, 1, 15, 1, 20, 20, 20, 1, 1, 20, 1, 50, 50, 10, 25, 25, 25, 15, 100000 ], ticker: 0, costDivisor: 1, freeAccelerator: 0, totalAccelerator: 0, freeAcceleratorBoost: 0, totalAcceleratorBoost: 0, acceleratorPower: 1.10, acceleratorEffect: new Decimal(1), acceleratorEffectDisplay: new Decimal(1), generatorPower: new Decimal(1), freeMultiplier: 0, totalMultiplier: 0, multiplierPower: 2, multiplierEffect: new Decimal(1), challengeOneLog: 3, freeMultiplierBoost: 0, totalMultiplierBoost: 0, globalCoinMultiplier: new Decimal(1), totalCoinOwned: 0, prestigeMultiplier: new Decimal(1), buildingPower: 1, reincarnationMultiplier: new Decimal(1), coinOneMulti: new Decimal(1), coinTwoMulti: new Decimal(1), coinThreeMulti: new Decimal(1), coinFourMulti: new Decimal(1), coinFiveMulti: new Decimal(1), globalCrystalMultiplier: new Decimal(1), globalMythosMultiplier: new Decimal(0.01), grandmasterMultiplier: new Decimal(1), atomsMultiplier: new Decimal(1), mythosBuildingPower: 1, challengeThreeMultiplier: new Decimal(1), totalMythosOwned: 0, prestigePointGain: new Decimal(0), challengeFivePower: 1 / 3, transcendPointGain: new Decimal(0), reincarnationPointGain: new Decimal(0), produceFirst: new Decimal(0), produceSecond: new Decimal(0), produceThird: new Decimal(0), produceFourth: new Decimal(0), produceFifth: new Decimal(0), produceTotal: new Decimal(0), produceFirstDiamonds: new Decimal(0), produceSecondDiamonds: new Decimal(0), produceThirdDiamonds: new Decimal(0), produceFourthDiamonds: new Decimal(0), produceFifthDiamonds: new Decimal(0), produceDiamonds: new Decimal(0), produceFirstMythos: new Decimal(0), produceSecondMythos: new Decimal(0), produceThirdMythos: new Decimal(0), produceFourthMythos: new Decimal(0), produceFifthMythos: new Decimal(0), produceMythos: new Decimal(0), produceFirstParticles: new Decimal(0), produceSecondParticles: new Decimal(0), produceThirdParticles: new Decimal(0), produceFourthParticles: new Decimal(0), produceFifthParticles: new Decimal(0), produceParticles: new Decimal(0), producePerSecond: new Decimal(0), producePerSecondDiamonds: new Decimal(0), producePerSecondMythos: new Decimal(0), producePerSecondParticles: new Decimal(0), uFourteenMulti: new Decimal(1), uFifteenMulti: new Decimal(1), tuSevenMulti: 1, currentTab: 'buildings', researchfiller1: "Hover over the grid to get details about researches!", researchfiller2: "Level: ", ordinals: ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth", "seventeenth", "eighteenth", "nineteenth", "twentieth"] as const, cardinals: ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twentyone", "twentytwo", "twentythree", "twentyfour", "twentyfive", "twentysix", "twentyseven", "twentyeight", "twentynine", "thirty", "thirtyone", "thirtytwo", "thirtythree", "thirtyfour"], challengeBaseRequirements: [10, 20, 60, 100, 200, 125, 500, 7500, 2.0e8, 3.5e9], prestigeamount: 1, taxdivisor: new Decimal("1"), taxdivisorcheck: new Decimal("1"), runemultiplierincrease: { one: 1, two: 1, three: 1, four: 1, five: 1 }, mythosupgrade13: new Decimal("1"), mythosupgrade14: new Decimal("1"), mythosupgrade15: new Decimal("1"), challengefocus: 0, maxexponent: 10000, maxbuyresearch: false, effectiveLevelMult: 1, optimalOfferingTimer: 600, optimalObtainiumTimer: 3600, runeSum: 0, shopConfirmation: true, shopBuyMax: false, globalAntMult: new Decimal("1"), antMultiplier: new Decimal("1"), antOneProduce: new Decimal("1"), antTwoProduce: new Decimal("1"), antThreeProduce: new Decimal("1"), antFourProduce: new Decimal("1"), antFiveProduce: new Decimal("1"), antSixProduce: new Decimal("1"), antSevenProduce: new Decimal("1"), antEightProduce: new Decimal("1"), antCostGrowth: [1e41, 3, 10, 1e2, 1e4, 1e8, 1e16, 1e32], antUpgradeBaseCost: [100, 100, 1000, 1000, 1e5, 1e6, 1e8, 1e11, 1e15, 1e20, 1e40, 1e100], antUpgradeCostIncreases: [10, 10, 10, 10, 100, 100, 100, 100, 1000, 1000, 1000, 1e100], bonusant1: 0, bonusant2: 0, bonusant3: 0, bonusant4: 0, bonusant5: 0, bonusant6: 0, bonusant7: 0, bonusant8: 0, bonusant9: 0, bonusant10: 0, bonusant11: 0, bonusant12: 0, rune1level: 1, rune2level: 1, rune3level: 1, rune4level: 1, rune5level: 1, rune1Talisman: 0, rune2Talisman: 0, rune3Talisman: 0, rune4Talisman: 0, rune5Talisman: 0, talisman1Effect: [null, 0, 0, 0, 0, 0], talisman2Effect: [null, 0, 0, 0, 0, 0], talisman3Effect: [null, 0, 0, 0, 0, 0], talisman4Effect: [null, 0, 0, 0, 0, 0], talisman5Effect: [null, 0, 0, 0, 0, 0], talisman6Effect: [null, 0, 0, 0, 0, 0], talisman7Effect: [null, 0, 0, 0, 0, 0], talisman6Power: 0, talisman7Quarks: 0, runescreen: "runes", settingscreen: "settings", talismanResourceObtainiumCosts: [1e13, 1e14, 1e16, 1e18, 1e20, 1e22, 1e24], talismanResourceOfferingCosts: [100, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9], talismanLevelCostMultiplier: [null, 1, 4, 1e4, 1e8, 1e13, 10, 100], talismanPositiveModifier: [null, 0.75, 1.5, 2.25, 3, 3.75, 4.5], talismanNegativeModifier: [null, 0, 0, 0, 0, 0, 0], commonTalismanEnhanceCost: [null, 0, 3000, 1000, 0, 0, 0, 0], uncommonTalismanEnchanceCost: [null, 0, 10000, 3000, 1000, 0, 0, 0], rareTalismanEnchanceCost: [null, 0, 100000, 20000, 2000, 500, 0, 0], epicTalismanEnhanceCost: [null, 0, 2e6, 2e5, 2e4, 2000, 1000, 0], legendaryTalismanEnchanceCost: [null, 0, 4e7, 2e6, 1e5, 20000, 2500, 200], mythicalTalismanEnchanceCost: [null, 0, 0, 0, 0, 0, 0, 0], talismanRespec: 1, obtainiumGain: 0, mirrorTalismanStats: [null, 1, 1, 1, 1, 1], antELO: 0, effectiveELO: 0, timeWarp: false, blessingMultiplier: 1, spiritMultiplier: 1, runeBlessings: [0, 0, 0, 0, 0, 0], runeSpirits: [0, 0, 0, 0, 0, 0], effectiveRuneBlessingPower: [0, 0, 0, 0, 0, 0], effectiveRuneSpiritPower: [0, 0, 0, 0, 0, 0], blessingBaseCost: 1e6, spiritBaseCost: 1e20, triggerChallenge: 0, prevReductionValue: -1, buildingSubTab: "coin", //1,000 of each before Diminishing Returns blessingbase: [null, 1 / 500, 1 / 5000, 1 / 2000, 1 / 750, 1 / 200, 1 / 10000, 1 / 5000, 1 / 10, 1 / 10000, 1 / 1000], blessingDRPower: [null, 1 / 3, 1 / 3, 2 / 3, 1 / 2, 2 / 3, 2, 1 / 3, 1 / 3, 1 / 16, 1 / 16], giftbase: [1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000], giftDRPower: [1 / 6, 1 / 6, 1 / 3, 1 / 4, 1 / 3, 1, 1 / 6, 1 / 6, 1 / 32, 1 / 32], benedictionbase: [null, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000, 1 / 1000], benedictionDRPower: [null, 1 / 12, 1 / 12, 1 / 6, 1 / 8, 1 / 6, 1 / 2, 1 / 12, 1 / 12, 1 / 64, 1 / 64], //10 Million of each before Diminishing returns on first 3, 200k for second, and 10k for the last few platonicCubeBase: [2/4e6, 1.5/4e6, 1/4e6, 1/8e4, 1/1e4, 1/1e5, 1/1e4, 1/1e4], platonicDRPower: [1/5, 1/5, 1/5, 1/5, 1/16, 1/16, 1/4, 1/8], cubeBonusMultiplier: [null, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], tesseractBonusMultiplier: [null, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], hypercubeBonusMultiplier: [null, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], platonicBonusMultiplier: [1, 1, 1, 1, 1, 1, 1, 1], buyMaxCubeUpgrades: false, autoOfferingCounter: 0, researchOrderByCost: [], divisivenessPower: [1, 0.87, 0.80, 0.75, 0.70, 0.6, 0.54, 0.45, 0.39, 0.33, 0.3, 0.2, 0.1, 0.05], maladaptivePower: [1, 0.87, 0.80, 0.75, 0.70, 0.6, 0.54, 0.45, 0.39, 0.33, 0.3, 0.2, 0.1, 0.05], lazinessMultiplier: [1, 1 / 3, 1 / 10, 1 / 40, 1 / 200, 1 / 1e5, 1 / 1e7, 1 / 1e10, 1/1e13, 1/1e16, 1/1e20, 1/1e25, 1/1e35, 1/1e50], hyperchallengedMultiplier: [1, 1.2, 1.5, 1.7, 3, 5, 8, 13, 21, 34, 55, 100, 400, 1600], illiteracyPower: [1, 0.8, 0.7, 0.6, 0.5, 0.3, 0.2, 0.15, 0.10, 0.06, 0.04, 0.02, 0.01, 0.005], deflationMultiplier: [1, 0.3, 0.1, 0.03, 0.01, 1/1e6, 1/1e8, 1/1e10, 1/1e12, 1/1e15, 1/1e18, 1/1e25, 1/1e35, 1/1e50], extinctionMultiplier: [1, 0.92, 0.86, 0.8, 0.74, 0.65, 0.55, 0.5, 0.45, 0.4, 0.35, 0.3, 0.1, 0], droughtMultiplier: [1, 5, 25, 200, 1e4, 1e7, 1e11, 1e16, 1e22, 1e30, 1e40, 1e55, 1e80, 1e120], financialcollapsePower: [1, 0.9, 0.7, 0.6, 0.5, 0.37, 0.30, 0.23, 0.18, 0.15, 0.12, 0.09, 0.03, 0.01], corruptionPointMultipliers: [1, 2, 2.75, 3.5, 4.25, 5, 5.75, 6.5, 7, 7.5, 8, 9, 10, 11], ascendBuildingProduction: { first: new Decimal('0'), second: new Decimal('0'), third: new Decimal('0'), fourth: new Decimal('0'), fifth: new Decimal('0'), }, freeUpgradeAccelerator: 0, freeUpgradeMultiplier: 0, acceleratorMultiplier: 1, multiplierMultiplier: 1, constUpgradeCosts: [null, 1, 13, 17, 237, 316, 4216, 5623, 74989, 1e10, 1e24], globalConstantMult: new Decimal("1"), autoTalismanTimer: 0, autoChallengeTimerIncrement: 0, corruptionTrigger: 1, challenge15Rewards: { cube1: 1, ascensions: 1, coinExponent: 1, taxes: 1, obtainium: 1, offering: 1, accelerator: 1, multiplier: 1, runeExp: 1, runeBonus: 1, cube2: 1, transcendChallengeReduction: 1, reincarnationChallengeReduction: 1, antSpeed: 1, bonusAntLevel: 1, cube3: 1, talismanBonus: 1, globalSpeed: 1, blessingBonus: 1, constantBonus: 1, cube4: 1, spiritBonus: 1, score: 1, quarks: 1, hepteractUnlocked: 0, cube5: 1, powder: 1, exponent: 1, freeOrbs: 0, ascensionSpeed: 1, }, autoResetTimers: { prestige: 0, transcension: 0, reincarnation: 0, ascension: 0 }, timeMultiplier: 1, upgradeMultiplier: 1, historyCountMax: 20, isEvent: false, // talismanResourceObtainiumCosts: [1e13, 1e14, 1e16, 1e18, 1e20, 1e22, 1e24] // talismanResourceOfferingCosts: [0, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9] } export const blankGlobals = { ...Globals };
the_stack
module android.app{ import Bundle = android.os.Bundle; import Intent = android.content.Intent; import ViewGroup = android.view.ViewGroup; import View = android.view.View; import Animation = android.view.animation.Animation; /** * This manages the execution of the main thread in an * application process, scheduling and executing activities, * broadcasts, and other operations on it as the activity * manager requests. * * {@hide} */ export class ActivityThread { androidUI: androidui.AndroidUI; mLaunchedActivities = new Set<Activity>(); overrideExitAnimation:Animation; overrideEnterAnimation:Animation; overrideResumeAnimation:Animation; overrideHideAnimation:Animation;//null mean no animation, undefined mean not override constructor(androidUI:androidui.AndroidUI) { this.androidUI = androidUI; } private initWithPageStack(){ let backKeyDownEvent = android.view.KeyEvent.obtain(android.view.KeyEvent.ACTION_DOWN, android.view.KeyEvent.KEYCODE_BACK); let backKeyUpEvent = android.view.KeyEvent.obtain(android.view.KeyEvent.ACTION_UP, android.view.KeyEvent.KEYCODE_BACK); PageStack.backListener = ():boolean=>{ let handleDown = this.androidUI._viewRootImpl.dispatchInputEvent(backKeyDownEvent); let handleUp = this.androidUI._viewRootImpl.dispatchInputEvent(backKeyUpEvent); return handleDown || handleUp; }; PageStack.pageOpenHandler = (pageId:string, pageExtra?:Intent, isRestore?:boolean):boolean=>{ let intent = new Intent(pageId); if(pageExtra) intent.mExtras = new Bundle(pageExtra.mExtras); if(isRestore) this.overrideNextWindowAnimation(null, null, null, null); let activity = this.handleLaunchActivity(intent); return activity && !activity.mFinished; }; PageStack.pageCloseHandler = (pageId:string, pageExtra?:Intent):boolean=>{ //check is root activity if(this.mLaunchedActivities.size === 1){ let rootActivity = Array.from(this.mLaunchedActivities)[0]; if(pageId==null || rootActivity.getIntent().activityName == pageId){ this.handleDestroyActivity(rootActivity, true); return true; } return false; } for(let activity of Array.from(this.mLaunchedActivities).reverse()){ let intent = activity.getIntent(); if(intent.activityName == pageId){ this.handleDestroyActivity(activity, true); return true; } } }; PageStack.init(); } overrideNextWindowAnimation(enterAnimation:Animation, exitAnimation:Animation, resumeAnimation:Animation, hideAnimation:Animation):void { this.overrideEnterAnimation = enterAnimation; this.overrideExitAnimation = exitAnimation; this.overrideResumeAnimation = resumeAnimation; this.overrideHideAnimation = hideAnimation; } getOverrideEnterAnimation():Animation { return this.overrideEnterAnimation; } getOverrideExitAnimation():Animation { return this.overrideExitAnimation; } getOverrideResumeAnimation():Animation { return this.overrideResumeAnimation; } getOverrideHideAnimation():Animation { return this.overrideHideAnimation; } private scheduleApplicationHideTimeout; scheduleApplicationHide():void { if(this.scheduleApplicationHideTimeout) clearTimeout(this.scheduleApplicationHideTimeout); this.scheduleApplicationHideTimeout = setTimeout(()=>{ let visibleActivities = this.getVisibleToUserActivities(); if(visibleActivities.length==0) return; this.handlePauseActivity(visibleActivities[visibleActivities.length - 1]); for(let visibleActivity of visibleActivities){ this.handleStopActivity(visibleActivity, true); } }, 0); } scheduleApplicationShow():void { this.scheduleActivityResume(); } execStartActivity(callActivity:Activity, intent:Intent, options?:android.os.Bundle):void { if((intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0){ if(this.scheduleBackTo(intent)) return; } this.scheduleLaunchActivity(callActivity, intent, options); } private activityResumeTimeout; scheduleActivityResume():void { if(this.activityResumeTimeout) clearTimeout(this.activityResumeTimeout); this.activityResumeTimeout = setTimeout(()=>{ let visibleActivities = this.getVisibleToUserActivities(); if(visibleActivities.length==0) return; for(let visibleActivity of visibleActivities){ visibleActivity.performRestart(); } let activity = visibleActivities.pop(); this.handleResumeActivity(activity, false); //show activity behind the activity if(activity.getWindow().isFloating()) { for (let visibleActivity of visibleActivities.reverse()) { if (visibleActivity.mVisibleFromClient) { visibleActivity.makeVisible(); if(!visibleActivity.getWindow().isFloating()){ break; } } } } }, 0); } scheduleLaunchActivity(callActivity:Activity, intent:Intent, options?:android.os.Bundle):void { let activity = this.handleLaunchActivity(intent); activity.mCallActivity = callActivity; if(activity && !activity.mFinished){ PageStack.notifyNewPageOpened(intent.activityName, intent); } } scheduleDestroyActivityByRequestCode(requestCode:number):void { for(let activity of Array.from(this.mLaunchedActivities).reverse()){ if(activity.getIntent() && requestCode == activity.getIntent().mRequestCode){ this.scheduleDestroyActivity(activity); } } } scheduleDestroyActivity(activity:Activity, finishing = true):void { //delay destroy ensure activity call all start/resume life circle. setTimeout(()=>{ let isCreateSuc = this.mLaunchedActivities.has(activity);//common case it's true, finish() in onCreate() will false here if(activity.mCallActivity && activity.getIntent() && activity.getIntent().mRequestCode>=0){ activity.mCallActivity.dispatchActivityResult(null, activity.getIntent().mRequestCode, activity.mResultCode, activity.mResultData) } this.handleDestroyActivity(activity, finishing); if(!isCreateSuc) return; if(this.mLaunchedActivities.size == 0){ if(history.length<=2){ this.androidUI.showAppClosed(); }else{ PageStack.back(true); } }else if(activity.getIntent()){ PageStack.notifyPageClosed(activity.getIntent().activityName); } }, 0); } scheduleBackTo(intent:Intent):boolean { let destroyList = []; let findActivity = false; for(let activity of Array.from(this.mLaunchedActivities).reverse()){ if(activity.getIntent() && activity.getIntent().activityName == intent.activityName){ findActivity = true; break; } destroyList.push(activity); } if(findActivity){ for(let activity of destroyList){ this.scheduleDestroyActivity(activity); } return true; } return false; } canBackTo(intent:Intent):boolean { for(let activity of this.mLaunchedActivities){ if(activity.getIntent().activityName == intent.activityName){ return true; } } return false; } scheduleBackToRoot():void { let destroyList = Array.from(this.mLaunchedActivities).reverse(); destroyList.shift();//remove root for(let activity of destroyList){ this.scheduleDestroyActivity(activity); } } private handlePauseActivity(activity:Activity){ this.performPauseActivity(activity); } private performPauseActivity(activity:Activity):void { //if (finished) { // activity.mFinished = true; //} // Now we are idle. activity.performPause(); } private handleStopActivity(activity:Activity, show=false):void { this.performStopActivity(activity, true); this.updateVisibility(activity, show); } private performStopActivity(activity:Activity, saveState:boolean):void { // Next have the activity save its current state and managed dialogs... if (!activity.mFinished && saveState) { let state = new Bundle(); //state.setAllowFds(false); activity.performSaveInstanceState(state); } // Now we are idle. activity.performStop(); } private handleResumeActivity(a:Activity, launching:boolean){ this.performResumeActivity(a, launching); // If the window hasn't yet been added to the window manager, // and this guy didn't finish itself or start another activity, // then go ahead and add the window. let willBeVisible = !a.mStartedActivity && !a.mFinished; if (willBeVisible && a.mVisibleFromClient) { a.makeVisible(); //reset override Animation this.overrideEnterAnimation = undefined; this.overrideExitAnimation = undefined; this.overrideResumeAnimation = undefined; this.overrideHideAnimation = undefined; } } private performResumeActivity(a:Activity, launching:boolean){ if(!launching){//clear mStartedActivity after onPause/onStop a.mStartedActivity = false; } a.performResume(); } private handleLaunchActivity(intent:Intent):Activity { let visibleActivities = this.getVisibleToUserActivities(); let a = this.performLaunchActivity(intent); if(a){ this.handleResumeActivity(a, true); if(!a.mFinished && visibleActivities.length>0) { //pause this.handlePauseActivity(visibleActivities[visibleActivities.length - 1]); if (!a.getWindow().getAttributes().isFloating()) { //stop all visible activities for (let visibleActivity of visibleActivities) { this.handleStopActivity(visibleActivity); } } } } return a; } private performLaunchActivity(intent:Intent):Activity { let activity:Activity; let clazz:any = intent.activityName; try { if(typeof clazz === 'string') clazz = eval(clazz); } catch (e) {} if(typeof clazz === 'function') activity = new clazz(this.androidUI); if(activity instanceof Activity){ try { let savedInstanceState = null;//TODO saved state activity.mIntent = intent; activity.mStartedActivity = false; activity.mCalled = false; activity.performCreate(savedInstanceState); if (!activity.mCalled) { throw new Error("Activity " + intent.activityName + " did not call through to super.onCreate()"); } if (!activity.mFinished) { activity.performStart(); activity.performRestoreInstanceState(savedInstanceState); activity.mCalled = false; activity.onPostCreate(savedInstanceState); if (!activity.mCalled) { throw new Error("Activity " + intent.activityName + " did not call through to super.onPostCreate()"); } } } catch (e) { //launch Activity error console.error(e); return null; } if(!activity.mFinished){ this.mLaunchedActivities.add(activity); } return <Activity>activity; } return null; } private handleDestroyActivity(activity:Activity, finishing:boolean):void { let visibleActivities = this.getVisibleToUserActivities(); let isTopVisibleActivity = activity == visibleActivities[visibleActivities.length - 1]; let isRootActivity = this.isRootActivity(activity); this.performDestroyActivity(activity, finishing); if(isRootActivity) activity.getWindow().setWindowAnimations(null, null);//clear animation if root activity. this.androidUI.windowManager.removeWindow(activity.getWindow()); if(isTopVisibleActivity && !isRootActivity){ this.scheduleActivityResume(); } } private performDestroyActivity(activity:Activity, finishing:boolean):void { if (finishing) { activity.mFinished = true; } //pause activity.performPause(); //stop activity.performStop(); //destory activity.mCalled = false; activity.performDestroy(); if (!activity.mCalled) { throw new Error( "Activity " + ActivityThread.getActivityName(activity) + " did not call through to super.onDestroy()"); } this.mLaunchedActivities.delete(activity); } private updateVisibility(activity:Activity, show:boolean):void { if(show){ if (activity.mVisibleFromClient) { activity.makeVisible(); } }else{ activity.getWindow().getDecorView().setVisibility(View.INVISIBLE); } } private getVisibleToUserActivities():Activity[]{ let list = []; for(let activity of Array.from(this.mLaunchedActivities).reverse()){ list.push(activity); if(!activity.getWindow().getAttributes().isFloating()) break; } list.reverse(); return list; } private isRootActivity(activity:Activity):boolean { return this.mLaunchedActivities.values().next().value == activity; } private static getActivityName(activity:Activity){ if(activity.getIntent()) return activity.getIntent().activityName; return activity.constructor.name; } } }
the_stack
'use strict'; import { ITheme, IThemeService } from 'vs/platform/theme/common/themeService'; import { inputBackground, inputForeground, ColorIdentifier, selectForeground, selectBackground, selectBorder, inputBorder, foreground, editorBackground, contrastBorder, inputActiveOptionBorder, listFocusBackground, listActiveSelectionBackground, listActiveSelectionForeground, listInactiveSelectionBackground, listHoverBackground, listDropBackground, pickerGroupBorder, pickerGroupForeground, widgetShadow, inputValidationInfoBorder, inputValidationInfoBackground, inputValidationWarningBorder, inputValidationWarningBackground, inputValidationErrorBorder, inputValidationErrorBackground, activeContrastBorder, buttonForeground, buttonBackground, buttonHoverBackground, ColorFunction, lighten } from 'vs/platform/theme/common/colorRegistry'; import { IDisposable } from 'vs/base/common/lifecycle'; import { SIDE_BAR_SECTION_HEADER_BACKGROUND } from 'vs/workbench/common/theme'; export interface IThemable { style(colors: { [name: string]: ColorIdentifier }): void; } export function attachStyler(themeService: IThemeService, widget: IThemable, optionsMapping: { [optionsKey: string]: ColorIdentifier | ColorFunction }): IDisposable { function applyStyles(theme: ITheme): void { const styles = Object.create(null); for (let key in optionsMapping) { const value = optionsMapping[key]; if (typeof value === 'string') { styles[key] = theme.getColor(value); } else if (typeof value === 'function') { styles[key] = value(theme); } } widget.style(styles); } applyStyles(themeService.getTheme()); return themeService.onThemeChange(applyStyles); } export function attachCheckboxStyler(widget: IThemable, themeService: IThemeService, style?: { inputActiveOptionBorderColor?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { inputActiveOptionBorder: (style && style.inputActiveOptionBorderColor) || inputActiveOptionBorder }); } export function attachInputBoxStyler(widget: IThemable, themeService: IThemeService, style?: { inputBackground?: ColorIdentifier, inputForeground?: ColorIdentifier, inputBorder?: ColorIdentifier, inputValidationInfoBorder?: ColorIdentifier, inputValidationInfoBackground?: ColorIdentifier, inputValidationWarningBorder?: ColorIdentifier, inputValidationWarningBackground?: ColorIdentifier, inputValidationErrorBorder?: ColorIdentifier, inputValidationErrorBackground?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { inputBackground: (style && style.inputBackground) || inputBackground, inputForeground: (style && style.inputForeground) || inputForeground, inputBorder: (style && style.inputBorder) || inputBorder, inputValidationInfoBorder: (style && style.inputValidationInfoBorder) || inputValidationInfoBorder, inputValidationInfoBackground: (style && style.inputValidationInfoBackground) || inputValidationInfoBackground, inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || inputValidationWarningBorder, inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || inputValidationWarningBackground, inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || inputValidationErrorBorder, inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || inputValidationErrorBackground }); } export function attachSelectBoxStyler(widget: IThemable, themeService: IThemeService, style?: { selectBackground?: ColorIdentifier, selectForeground?: ColorIdentifier, selectBorder?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { selectBackground: (style && style.selectBackground) || selectBackground, selectForeground: (style && style.selectForeground) || selectForeground, selectBorder: (style && style.selectBorder) || selectBorder }); } export function attachFindInputBoxStyler(widget: IThemable, themeService: IThemeService, style?: { inputBackground?: ColorIdentifier, inputForeground?: ColorIdentifier, inputBorder?: ColorIdentifier, inputActiveOptionBorder?: ColorIdentifier, inputValidationInfoBorder?: ColorIdentifier, inputValidationInfoBackground?: ColorIdentifier, inputValidationWarningBorder?: ColorIdentifier, inputValidationWarningBackground?: ColorIdentifier, inputValidationErrorBorder?: ColorIdentifier, inputValidationErrorBackground?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { inputBackground: (style && style.inputBackground) || inputBackground, inputForeground: (style && style.inputForeground) || inputForeground, inputBorder: (style && style.inputBorder) || inputBorder, inputActiveOptionBorder: (style && style.inputActiveOptionBorder) || inputActiveOptionBorder, inputValidationInfoBorder: (style && style.inputValidationInfoBorder) || inputValidationInfoBorder, inputValidationInfoBackground: (style && style.inputValidationInfoBackground) || inputValidationInfoBackground, inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || inputValidationWarningBorder, inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || inputValidationWarningBackground, inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || inputValidationErrorBorder, inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || inputValidationErrorBackground }); } export function attachQuickOpenStyler(widget: IThemable, themeService: IThemeService, style?: { foreground?: ColorIdentifier, background?: ColorIdentifier, borderColor?: ColorIdentifier, widgetShadow?: ColorIdentifier, inputBackground?: ColorIdentifier, inputForeground?: ColorIdentifier, inputBorder?: ColorIdentifier, inputValidationInfoBorder?: ColorIdentifier, inputValidationInfoBackground?: ColorIdentifier, inputValidationWarningBorder?: ColorIdentifier, inputValidationWarningBackground?: ColorIdentifier, inputValidationErrorBorder?: ColorIdentifier, inputValidationErrorBackground?: ColorIdentifier pickerGroupForeground?: ColorIdentifier, pickerGroupBorder?: ColorIdentifier, listFocusBackground?: ColorIdentifier, listActiveSelectionBackground?: ColorIdentifier, listActiveSelectionForeground?: ColorIdentifier, listFocusAndSelectionBackground?: ColorIdentifier, listFocusAndSelectionForeground?: ColorIdentifier, listInactiveSelectionBackground?: ColorIdentifier, listHoverBackground?: ColorIdentifier, listDropBackground?: ColorIdentifier, listFocusOutline?: ColorIdentifier, listSelectionOutline?: ColorIdentifier, listHoverOutline?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { foreground: (style && style.foreground) || foreground, background: (style && style.background) || editorBackground, borderColor: style && style.borderColor || contrastBorder, widgetShadow: style && style.widgetShadow || widgetShadow, pickerGroupForeground: style && style.pickerGroupForeground || pickerGroupForeground, pickerGroupBorder: style && style.pickerGroupBorder || pickerGroupBorder, inputBackground: (style && style.inputBackground) || inputBackground, inputForeground: (style && style.inputForeground) || inputForeground, inputBorder: (style && style.inputBorder) || inputBorder, inputValidationInfoBorder: (style && style.inputValidationInfoBorder) || inputValidationInfoBorder, inputValidationInfoBackground: (style && style.inputValidationInfoBackground) || inputValidationInfoBackground, inputValidationWarningBorder: (style && style.inputValidationWarningBorder) || inputValidationWarningBorder, inputValidationWarningBackground: (style && style.inputValidationWarningBackground) || inputValidationWarningBackground, inputValidationErrorBorder: (style && style.inputValidationErrorBorder) || inputValidationErrorBorder, inputValidationErrorBackground: (style && style.inputValidationErrorBackground) || inputValidationErrorBackground, listFocusBackground: (style && style.listFocusBackground) || listFocusBackground, listActiveSelectionBackground: (style && style.listActiveSelectionBackground) || lighten(listActiveSelectionBackground, 0.1), listActiveSelectionForeground: (style && style.listActiveSelectionForeground) || listActiveSelectionForeground, listFocusAndSelectionBackground: style && style.listFocusAndSelectionBackground || listActiveSelectionBackground, listFocusAndSelectionForeground: (style && style.listFocusAndSelectionForeground) || listActiveSelectionForeground, listInactiveSelectionBackground: (style && style.listInactiveSelectionBackground) || listInactiveSelectionBackground, listHoverBackground: (style && style.listHoverBackground) || listHoverBackground, listDropBackground: (style && style.listDropBackground) || listDropBackground, listFocusOutline: (style && style.listFocusOutline) || activeContrastBorder, listSelectionOutline: (style && style.listSelectionOutline) || activeContrastBorder, listHoverOutline: (style && style.listHoverOutline) || activeContrastBorder }); } export function attachListStyler(widget: IThemable, themeService: IThemeService, style?: { listFocusBackground?: ColorIdentifier, listActiveSelectionBackground?: ColorIdentifier, listActiveSelectionForeground?: ColorIdentifier, listFocusAndSelectionBackground?: ColorIdentifier, listFocusAndSelectionForeground?: ColorIdentifier, listInactiveFocusBackground?: ColorIdentifier, listInactiveSelectionBackground?: ColorIdentifier, listHoverBackground?: ColorIdentifier, listDropBackground?: ColorIdentifier, listFocusOutline?: ColorIdentifier, listInactiveFocusOutline?: ColorIdentifier, listSelectionOutline?: ColorIdentifier, listHoverOutline?: ColorIdentifier, }): IDisposable { return attachStyler(themeService, widget, { listFocusBackground: (style && style.listFocusBackground) || listFocusBackground, listActiveSelectionBackground: (style && style.listActiveSelectionBackground) || lighten(listActiveSelectionBackground, 0.1), listActiveSelectionForeground: (style && style.listActiveSelectionForeground) || listActiveSelectionForeground, listFocusAndSelectionBackground: style && style.listFocusAndSelectionBackground || listActiveSelectionBackground, listFocusAndSelectionForeground: (style && style.listFocusAndSelectionForeground) || listActiveSelectionForeground, listInactiveFocusBackground: (style && style.listInactiveFocusBackground), listInactiveSelectionBackground: (style && style.listInactiveSelectionBackground) || listInactiveSelectionBackground, listHoverBackground: (style && style.listHoverBackground) || listHoverBackground, listDropBackground: (style && style.listDropBackground) || listDropBackground, listFocusOutline: (style && style.listFocusOutline) || activeContrastBorder, listSelectionOutline: (style && style.listSelectionOutline) || activeContrastBorder, listHoverOutline: (style && style.listHoverOutline) || activeContrastBorder, listInactiveFocusOutline: style && style.listInactiveFocusOutline // not defined by default, only opt-in }); } export function attachHeaderViewStyler(widget: IThemable, themeService: IThemeService, style?: { headerBackground?: ColorIdentifier, contrastBorder?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { headerBackground: (style && style.headerBackground) || SIDE_BAR_SECTION_HEADER_BACKGROUND, headerHighContrastBorder: (style && style.contrastBorder) || contrastBorder }); } export function attachButtonStyler(widget: IThemable, themeService: IThemeService, style?: { buttonForeground?: ColorIdentifier, buttonBackground?: ColorIdentifier, buttonHoverBackground?: ColorIdentifier }): IDisposable { return attachStyler(themeService, widget, { buttonForeground: (style && style.buttonForeground) || buttonForeground, buttonBackground: (style && style.buttonBackground) || buttonBackground, buttonHoverBackground: (style && style.buttonHoverBackground) || buttonHoverBackground }); }
the_stack
import { CanvasPanelCtrl } from './canvas-metric'; import { DistinctPoints, LegendValue } from './distinct-points'; import { isArray } from 'lodash'; import { DataQueryResponseData, LegacyResponseData, DataFrame, guessFieldTypes, toDataFrame, getTimeField, getFieldDisplayName, Field, ArrayVector, FieldType, } from '@grafana/data'; import _ from 'lodash'; import $ from 'jquery'; import kbn from 'grafana/app/core/utils/kbn'; import appEvents from 'grafana/app/core/app_events'; /* eslint-disable id-blacklist, no-restricted-imports, @typescript-eslint/ban-types */ import moment from 'moment'; const grafanaColors = [ '#7EB26D', '#EAB839', '#6ED0E0', '#EF843C', '#E24D42', '#1F78C1', '#BA43A9', '#705DA0', '#508642', '#CCA300', '#447EBC', '#C15C17', '#890F02', '#0A437C', '#6D1F62', '#584477', '#B7DBAB', '#F4D598', '#70DBED', '#F9BA8F', '#F29191', '#82B5D8', '#E5A8E2', '#AEA2E0', '#629E51', '#E5AC0E', '#64B0C8', '#E0752D', '#BF1B00', '#0A50A1', '#962D82', '#614D93', '#9AC48A', '#F2C96D', '#65C5DB', '#F9934E', '#EA6460', '#5195CE', '#D683CE', '#806EB7', '#3F6833', '#967302', '#2F575E', '#99440A', '#58140C', '#052B51', '#511749', '#3F2B5B', '#E0F9D7', '#FCEACA', '#CFFAFF', '#F9E2D2', '#FCE2DE', '#BADFF4', '#F9D9F9', '#DEDAF7', ]; // copied from public/app/core/utils/colors.ts because of changes in grafana 4.6.0 //(https://github.com/grafana/grafana/blob/master/PLUGIN_DEV.md) class DiscretePanelCtrl extends CanvasPanelCtrl { static templateUrl = 'partials/module.html'; static scrollable = true; defaults = { display: 'timeline', // or 'stacked' rowHeight: 50, valueMaps: [{ value: 'null', op: '=', text: 'N/A' }], rangeMaps: [{ from: 'null', to: 'null', text: 'N/A' }], colorMaps: [{ text: 'N/A', color: '#CCC' }], metricNameColor: '#000000', valueTextColor: '#000000', timeTextColor: '#d8d9da', crosshairColor: '#8F070C', backgroundColor: 'rgba(128,128,128,0.1)', lineColor: 'rgba(0,0,0,0.1)', textSize: 24, textSizeTime: 12, extendLastValue: true, writeLastValue: true, writeAllValues: false, writeMetricNames: false, showTimeAxis: true, showLegend: true, showLegendNames: true, showLegendValues: true, showLegendPercent: true, highlightOnMouseover: true, expandFromQueryS: 0, legendSortBy: '-ms', units: 'short', timeOptions: [ { name: 'Years', value: 'years', }, { name: 'Months', value: 'months', }, { name: 'Weeks', value: 'weeks', }, { name: 'Days', value: 'days', }, { name: 'Hours', value: 'hours', }, { name: 'Minutes', value: 'minutes', }, { name: 'Seconds', value: 'seconds', }, { name: 'Milliseconds', value: 'milliseconds', }, ], timePrecision: { name: 'Minutes', value: 'minutes', }, useTimePrecision: false, use12HourClock: false, }; annotations: any = []; data: DistinctPoints[] = []; legend: DistinctPoints[] = []; externalPT = false; isTimeline = true; isStacked = false; hoverPoint: any = null; colorMap: any = {}; unitFormats: any = null; // only used for editor formatter: any = null; _colorsPaleteCash: any = null; _renderDimensions: any = {}; _selectionMatrix: string[][] = []; fieldNamer = (field: Field, frame?: DataFrame, allFrames?: DataFrame[]): string => { if (field.config.displayName) { return field.config.displayName; } return field.name; }; /** @ngInject */ constructor($scope, $injector, public annotationsSrv) { super($scope, $injector); // defaults configs _.defaultsDeep(this.panel, this.defaults); this.panel.display = 'timeline'; // Only supported version now this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.events.on('render', this.onRender.bind(this)); this.events.on('refresh', this.onRefresh.bind(this)); // 6.4+ use DataFrames (this as any).useDataFrames = true; this.events.on('data-frames-received', this.onDataFramesReceived.bind(this)); this.events.on('data-snapshot-load', this.onSnapshotLoad.bind(this)); this.events.on('data-error', this.onDataError.bind(this)); // Try to load the 7+ naming strategy try { const a = getFieldDisplayName({ name: 'a', config: {}, type: FieldType.number, values: new ArrayVector([]) }); if (a === 'a') { this.fieldNamer = getFieldDisplayName; } } catch (err) { console.warn('Using 6x style field names', err); } } onPanelInitialized() { this.updateColorInfo(); this.onConfigChanged(); } onDataError(err) { this.annotations = []; console.log('onDataError', err); } onInitEditMode() { this.unitFormats = kbn.getUnitFormats(); this.addEditorTab('Options', 'public/plugins/natel-discrete-panel/partials/editor.options.html', 1); this.addEditorTab('Legend', 'public/plugins/natel-discrete-panel/partials/editor.legend.html', 3); this.addEditorTab('Colors', 'public/plugins/natel-discrete-panel/partials/editor.colors.html', 4); this.addEditorTab('Mappings', 'public/plugins/natel-discrete-panel/partials/editor.mappings.html', 5); this.editorTabIndex = 1; this.refresh(); } onRender() { if (this.data == null || !this.context) { return; } this._updateRenderDimensions(); this._updateSelectionMatrix(); this._updateCanvasSize(); this._renderRects(); this._renderTimeAxis(); this._renderLabels(); this._renderAnnotations(); this._renderSelection(); this._renderCrosshair(); this.renderingCompleted(); } showLegandTooltip(pos, info) { let body = '<div class="graph-tooltip-time">' + info.val + '</div>'; body += '<center>'; if (info.count > 1) { body += info.count + ' times<br/>for<br/>'; } body += this.formatDuration(moment.duration(info.ms)); if (info.count > 1) { body += '<br/>total'; } body += '</center>'; this.$tooltip.html(body).place_tt(pos.pageX + 20, pos.pageY); } clearTT() { this.$tooltip.detach(); } formatValue(val): string { if (_.isNumber(val)) { if (this.panel.rangeMaps) { for (let i = 0; i < this.panel.rangeMaps.length; i++) { const map = this.panel.rangeMaps[i]; // value/number to range mapping const from = parseFloat(map.from); const to = parseFloat(map.to); if (to >= val && from <= val) { return map.text; } } } // Convert it to a string first if (this.formatter) { val = this.formatter(val, this.panel.decimals); } } const isNull = _.isNil(val); if (!isNull && !_.isString(val)) { val = val.toString(); // convert everything to a string } for (let i = 0; i < this.panel.valueMaps.length; i++) { const map = this.panel.valueMaps[i]; // special null case if (map.value === 'null') { if (isNull) { return map.text; } continue; } if (val === map.value) { return map.text; } } if (isNull) { return 'null'; } return val; } getColor(val) { if (_.has(this.colorMap, val)) { return this.colorMap[val]; } if (this._colorsPaleteCash[val] === undefined) { const c = grafanaColors[this._colorsPaleteCash.length % grafanaColors.length]; this._colorsPaleteCash[val] = c; this._colorsPaleteCash.length++; } return this._colorsPaleteCash[val]; } randomColor() { const letters = 'ABCDE'.split(''); let color = '#'; for (let i = 0; i < 3; i++) { color += letters[Math.floor(Math.random() * letters.length)]; } return color; } // Override the applyPanelTimeOverrides() { super.applyPanelTimeOverrides(); if (this.panel.expandFromQueryS && this.panel.expandFromQueryS > 0) { const from = this.range.from.subtract(this.panel.expandFromQueryS, 's'); this.range.from = from; this.range.raw.from = from; } } // This should only be called from the snapshot callback onSnapshotLoad(dataList: LegacyResponseData[]) { this.onDataFramesReceived(getProcessedDataFrames(dataList)); } // Directly support DataFrame onDataFramesReceived(frames: DataFrame[]) { $(this.canvas).css('cursor', 'pointer'); const data: DistinctPoints[] = []; frames.forEach(frame => { const time = getTimeField(frame).timeField; if (time) { frame.fields.forEach(field => { if (field !== time) { const res = new DistinctPoints(this.fieldNamer(field, frame, frames)); for (let i = 0; i < time.values.length; i++) { res.add(time.values.get(i), this.formatValue(field.values.get(i))); } res.finish(this); data.push(res); } }); } }); this.data = data; this.updateLegendMetrics(); // Annotations Query this.annotationsSrv .getAnnotations({ dashboard: this.dashboard, panel: this.panel, // {id: 4}, // range: this.range, }) .then( result => { this.loading = false; if (result.annotations && result.annotations.length > 0) { this.annotations = result.annotations; } else { this.annotations = null; } this.onRender(); }, () => { this.loading = false; this.annotations = null; this.onRender(); console.log('ERRR', this); } ); } updateLegendMetrics(notify?: boolean) { if (!this.data || !this.panel.showLegend || this.panel.showLegendNames || this.data.length <= 1) { this.legend = this.data; } else { this.legend = [DistinctPoints.combineLegend(this.data, this)]; } if (notify) { this.onConfigChanged(); } } removeColorMap(map) { const index = _.indexOf(this.panel.colorMaps, map); this.panel.colorMaps.splice(index, 1); this.updateColorInfo(); } updateColorInfo() { const cm = {}; for (let i = 0; i < this.panel.colorMaps.length; i++) { const m = this.panel.colorMaps[i]; if (m.text) { cm[m.text] = m.color; } } this._colorsPaleteCash = {}; this._colorsPaleteCash.length = 0; this.colorMap = cm; this.render(); } addColorMap(what) { if (what === 'curent') { _.forEach(this.data, metric => { if (metric.legendInfo) { _.forEach(metric.legendInfo, info => { if (!_.has(this.colorMap, info.val)) { const v = { text: info.val, color: this.getColor(info.val) }; this.panel.colorMaps.push(v); this.colorMap[info.val] = v; } }); } }); } else { this.panel.colorMaps.push({ text: '???', color: this.randomColor() }); } this.updateColorInfo(); } removeValueMap(map) { const index = _.indexOf(this.panel.valueMaps, map); this.panel.valueMaps.splice(index, 1); this.render(); } addValueMap() { this.panel.valueMaps.push({ value: '', op: '=', text: '' }); } removeRangeMap(rangeMap) { const index = _.indexOf(this.panel.rangeMaps, rangeMap); this.panel.rangeMaps.splice(index, 1); this.render(); } addRangeMap() { this.panel.rangeMaps.push({ from: '', to: '', text: '' }); } onConfigChanged(update = false) { this.isTimeline = this.panel.display === 'timeline'; this.isStacked = this.panel.display === 'stacked'; this.formatter = null; if (this.panel.units && 'none' !== this.panel.units) { this.formatter = kbn.valueFormats[this.panel.units]; } if (update) { this.refresh(); } else { this.render(); } } formatDuration(duration) { if (!this.panel.useTimePrecision) { return duration.humanize(); } const dir: any = {}; let hasValue = false; let limit = false; for (const o of this.panel.timeOptions) { dir[o.value] = parseInt(duration.as(o.value), 10); hasValue = dir[o.value] || hasValue; duration.subtract(moment.duration(dir[o.value], o.value)); limit = this.panel.timePrecision.value === o.value || limit; // always show a value in case it is less than the configured // precision if (limit && hasValue) { break; } } const rs = Object.keys(dir).reduce((carry, key) => { const value = dir[key]; if (!value) { return carry; } key = value < 2 ? key.replace(/s$/, '') : key; return `${carry} ${value} ${key},`; }, ''); return rs.substr(0, rs.length - 1); } getLegendDisplay(info, metric) { let disp = info.val; if (this.panel.showLegendPercent || this.panel.showLegendCounts || this.panel.showLegendTime) { disp += ' ('; let hassomething = false; if (this.panel.showLegendTime) { disp += this.formatDuration(moment.duration(info.ms)); hassomething = true; } if (this.panel.showLegendPercent) { if (hassomething) { disp += ', '; } let dec = this.panel.legendPercentDecimals; if (_.isNil(dec)) { if (info.per > 0.98 && metric.changes.length > 1) { dec = 2; } else if (info.per < 0.02) { dec = 2; } else { dec = 0; } } disp += kbn.valueFormats.percentunit(info.per, dec); hassomething = true; } if (this.panel.showLegendCounts) { if (hassomething) { disp += ', '; } disp += info.count + 'x'; } disp += ')'; } return disp; } //------------------ // Mouse Events //------------------ showTooltip(evt, point, isExternal) { let from = point.start; let to = point.start + point.ms; let time = point.ms; let val = point.val; if (this.mouse.down != null) { from = Math.min(this.mouse.down.ts, this.mouse.position.ts); to = Math.max(this.mouse.down.ts, this.mouse.position.ts); time = to - from; val = 'Zoom To:'; } let timeformat = ''; if (this.panel.use12HourClock) { timeformat = 'YYYY-MM-DD h:mm:ss a'; } let body = '<div class="graph-tooltip-time">' + val + '</div>'; body += '<center>'; body += this.dashboard.formatDate(moment(from), timeformat) + '<br/>'; body += 'to<br/>'; body += this.dashboard.formatDate(moment(to), timeformat) + '<br/><br/>'; body += this.formatDuration(moment.duration(time)) + '<br/>'; body += '</center>'; let pageX = 0; let pageY = 0; if (isExternal) { const rect = this.canvas.getBoundingClientRect(); pageY = rect.top + evt.pos.panelRelY * rect.height; if (pageY < 0 || pageY > $(window).innerHeight()) { // Skip Hidden tooltip this.$tooltip.detach(); return; } pageY += $(window).scrollTop(); const elapsed = this.range.to - this.range.from; const pX = (evt.pos.x - this.range.from) / elapsed; pageX = rect.left + pX * rect.width; } else { pageX = evt.evt.pageX; pageY = evt.evt.pageY; } this.$tooltip.html(body).place_tt(pageX + 20, pageY + 5); } getCorrectTime(ts: number) { const from = moment(this.range.from).valueOf(); return ts < from ? from : ts; } onGraphHover(evt, showTT, isExternal) { this.externalPT = false; if (this.data && this.data.length) { let hover: any = null; let j = Math.floor(this.mouse.position.y / this.panel.rowHeight); if (j < 0) { j = 0; } if (j >= this.data.length) { j = this.data.length - 1; } if (this.isTimeline) { hover = this.data[j].changes[0]; for (let i = 0; i < this.data[j].changes.length; i++) { if (this.data[j].changes[i].start > this.mouse.position.ts) { break; } hover = this.data[j].changes[i]; } hover.start = this.getCorrectTime(hover.start); this.hoverPoint = hover; if (this.annotations && !isExternal && this._renderDimensions) { if (evt.pos.y > this._renderDimensions.rowsHeight - 5) { const min = _.isUndefined(this.range.from) ? null : this.range.from.valueOf(); const max = _.isUndefined(this.range.to) ? null : this.range.to.valueOf(); const width = this._renderDimensions.width; const anno = _.find(this.annotations, a => { if (a.isRegion) { return evt.pos.x > a.time && evt.pos.x < a.timeEnd; } const annoX = ((a.time - min) / (max - min)) * width; const mouseX = evt.evt.offsetX; return annoX > mouseX - 5 && annoX < mouseX + 5; }); if (anno) { console.log('TODO, hover <annotation-tooltip>', anno); // See: https://github.com/grafana/grafana/blob/master/public/app/plugins/panel/graph/jquery.flot.events.js#L10 this.$tooltip.html(anno.text).place_tt(evt.evt.pageX + 20, evt.evt.pageY + 5); return; } } } if (showTT) { this.externalPT = isExternal; this.showTooltip(evt, hover, isExternal); } this.onRender(); // refresh the view } else if (!isExternal) { if (this.isStacked) { hover = this.data[j].legendInfo[0]; // for (let i = 0; i < this.data[j].legendInfo.length; i++) { // if (this.data[j].legendInfo[i].x > this.mouse.position.x) { // break; // } // hover = this.data[j].legendInfo[i]; // } this.hoverPoint = hover; this.onRender(); // refresh the view if (showTT) { this.externalPT = isExternal; this.showLegandTooltip(evt.evt, hover); } } } } else { this.$tooltip.detach(); // make sure it is hidden } } onMouseClicked(where, event) { if (event.metaKey === true || event.ctrlKey === true) { console.log('TODO? Create Annotation?', where, event); return; } const pt = this.hoverPoint; if (pt && pt.start) { const range = { from: moment.utc(pt.start), to: moment.utc(pt.start + pt.ms) }; this.timeSrv.setTime(range); this.clear(); } } onMouseSelectedRange(range, event) { if (event.metaKey === true || event.ctrlKey === true) { console.log('TODO? Create range annotation?', range, event); return; } this.timeSrv.setTime(range); this.clear(); } clear() { this.mouse.position = null; this.mouse.down = null; this.hoverPoint = null; $(this.canvas).css('cursor', 'wait'); appEvents.emit('graph-hover-clear'); this.render(); } _updateRenderDimensions() { this._renderDimensions = {}; const rect = (this._renderDimensions.rect = this.wrap.getBoundingClientRect()); const rows = (this._renderDimensions.rows = this.data.length); const rowHeight = (this._renderDimensions.rowHeight = this.panel.rowHeight); const rowsHeight = (this._renderDimensions.rowsHeight = rowHeight * rows); const timeHeight = this.panel.showTimeAxis ? 14 + this.panel.textSizeTime : 0; const height = (this._renderDimensions.height = rowsHeight + timeHeight); const width = (this._renderDimensions.width = rect.width); this._renderDimensions.height = height; // First render? if (!this.range) { this.range = { to: 2000, from: 1000, }; } let top = 0; const elapsed = this.range.to - this.range.from; this._renderDimensions.matrix = []; _.forEach(this.data, metric => { const positions: any[] = []; if (this.isTimeline) { let point = metric.changes[0]; for (let i = 0; i < metric.changes.length; i++) { point = metric.changes[i]; if (point.start <= this.range.to) { const xt = Math.max(point.start - this.range.from, 0); const x = (xt / elapsed) * width; positions.push(x); } } } if (this.isStacked) { let point: LegendValue; let start = this.range.from; for (let i = 0; i < metric.legendInfo.length; i++) { point = metric.legendInfo[i]; const xt = Math.max(start - this.range.from, 0); const x = (xt / elapsed) * width; positions.push(x); start += point.ms; } } this._renderDimensions.matrix.push({ y: top, positions: positions, }); top += rowHeight; }); } _updateSelectionMatrix() { const selectionPredicates = { all: () => { return true; }, crosshairHover: function(i, j) { if (j + 1 === this.data[i].changes.length) { return this.data[i].changes[j].start <= this.mouse.position.ts; } return ( this.data[i].changes[j].start <= this.mouse.position.ts && this.mouse.position.ts < this.data[i].changes[j + 1].start ); }, mouseX: function(i, j) { const row = this._renderDimensions.matrix[i]; if (j + 1 === row.positions.length) { return row.positions[j] <= this.mouse.position.x; } return row.positions[j] <= this.mouse.position.x && this.mouse.position.x < row.positions[j + 1]; }, metric: function(i) { return this.data[i] === this._selectedMetric; }, legendItem: function(i, j) { if (this.data[i] !== this._selectedMetric) { return false; } return this._selectedLegendItem.val === this._getVal(i, j); }, }; function getPredicate() { if (this._selectedLegendItem !== undefined) { return 'legendItem'; } if (this._selectedMetric !== undefined) { return 'metric'; } if (this.mouse.down !== null) { return 'all'; } if (this.panel.highlightOnMouseover && this.mouse.position != null) { if (this.isTimeline) { return 'crosshairHover'; } if (this.isStacked) { return 'mouseX'; } } return 'all'; } const pn = getPredicate.bind(this)(); const predicate = selectionPredicates[pn].bind(this); this._selectionMatrix = []; for (let i = 0; i < this._renderDimensions.matrix.length; i++) { const rs: any[] = []; const r = this._renderDimensions.matrix[i]; for (let j = 0; j < r.positions.length; j++) { rs.push(predicate(i, j)); } this._selectionMatrix.push(rs); } } _updateCanvasSize() { this.canvas.width = this._renderDimensions.width * this._devicePixelRatio; this.canvas.height = this._renderDimensions.height * this._devicePixelRatio; $(this.canvas).css('width', this._renderDimensions.width + 'px'); $(this.canvas).css('height', this._renderDimensions.height + 'px'); this.context.scale(this._devicePixelRatio, this._devicePixelRatio); } _getVal(metricIndex, rectIndex) { let point: any; if (this.isTimeline) { point = this.data[metricIndex].changes[rectIndex]; } if (this.isStacked) { point = this.data[metricIndex].legendInfo[rectIndex]; } return point.val; } _renderRects() { const matrix = this._renderDimensions.matrix; const ctx = this.context; // Clear the background ctx.fillStyle = this.panel.backgroundColor; ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); _.forEach(this.data, (metric, i) => { const rowObj = matrix[i]; for (let j = 0; j < rowObj.positions.length; j++) { const currentX = rowObj.positions[j]; let nextX = this._renderDimensions.width; if (j + 1 !== rowObj.positions.length) { nextX = rowObj.positions[j + 1]; } ctx.fillStyle = this.getColor(this._getVal(i, j)); const globalAlphaTemp = ctx.globalAlpha; if (!this._selectionMatrix[i][j]) { ctx.globalAlpha = 0.3; } ctx.fillRect(currentX, matrix[i].y, nextX - currentX, this._renderDimensions.rowHeight); ctx.globalAlpha = globalAlphaTemp; } if (i > 0) { const top = matrix[i].y; ctx.strokeStyle = this.panel.lineColor; ctx.beginPath(); ctx.moveTo(0, top); ctx.lineTo(this._renderDimensions.width, top); ctx.stroke(); } }); } _renderLabels() { const ctx = this.context; ctx.lineWidth = 1; ctx.textBaseline = 'middle'; ctx.font = this.panel.textSize + 'px "Open Sans", Helvetica, Arial, sans-serif'; const offset = 2; const rowHeight = this._renderDimensions.rowHeight; _.forEach(this.data, (metric, i) => { const { y, positions } = this._renderDimensions.matrix[i]; const centerY = y + rowHeight / 2; // let labelPositionMetricName = y + rectHeight - this.panel.textSize / 2; // let labelPositionLastValue = y + rectHeight - this.panel.textSize / 2; // let labelPositionValue = y + this.panel.textSize / 2; const labelPositionMetricName = centerY; const labelPositionLastValue = centerY; const labelPositionValue = centerY; let minTextSpot = 0; let maxTextSpot = this._renderDimensions.width; if (this.panel.writeMetricNames) { ctx.fillStyle = this.panel.metricNameColor; ctx.textAlign = 'left'; ctx.fillText(metric.name, offset, labelPositionMetricName); minTextSpot = offset + ctx.measureText(metric.name).width + 2; } let hoverTextStart = -1; let hoverTextEnd = -1; if (this.mouse.position) { for (let j = 0; j < positions.length; j++) { if (positions[j] <= this.mouse.position.x) { if (j >= positions.length - 1 || positions[j + 1] >= this.mouse.position.x) { let val = this._getVal(i, j); ctx.fillStyle = this.panel.valueTextColor; ctx.textAlign = 'left'; hoverTextStart = positions[j] + offset; if (hoverTextStart < minTextSpot) { hoverTextStart = minTextSpot + 2; val = ': ' + val; } ctx.fillText(val, hoverTextStart, labelPositionValue); const txtinfo = ctx.measureText(val); hoverTextEnd = hoverTextStart + txtinfo.width + 4; break; } } } } if (this.panel.writeLastValue) { const val = this._getVal(i, positions.length - 1); ctx.fillStyle = this.panel.valueTextColor; ctx.textAlign = 'right'; const txtinfo = ctx.measureText(val); const xval = this._renderDimensions.width - offset - txtinfo.width; if (xval > hoverTextEnd) { ctx.fillText(val, this._renderDimensions.width - offset, labelPositionLastValue); maxTextSpot = this._renderDimensions.width - ctx.measureText(val).width - 10; } } if (this.panel.writeAllValues) { ctx.fillStyle = this.panel.valueTextColor; ctx.textAlign = 'left'; for (let j = 0; j < positions.length; j++) { const val = this._getVal(i, j); let nextX = this._renderDimensions.width; if (j + 1 !== positions.length) { nextX = positions[j + 1]; } const x = positions[j]; if (x > minTextSpot) { const width = nextX - x; if (maxTextSpot > x + width) { // This clips the text within the given bounds ctx.save(); ctx.rect(x, y, width, rowHeight); ctx.clip(); ctx.fillText(val, x + offset, labelPositionValue); ctx.restore(); } } } } }); } _renderSelection() { if (this.mouse.down === null) { return; } if (this.mouse.position === null) { return; } if (!this.isTimeline) { return; } const ctx = this.context; const height = this._renderDimensions.height; const xmin = Math.min(this.mouse.position.x, this.mouse.down.x); const xmax = Math.max(this.mouse.position.x, this.mouse.down.x); ctx.fillStyle = 'rgba(110, 110, 110, 0.5)'; ctx.strokeStyle = 'rgba(110, 110, 110, 0.5)'; ctx.beginPath(); ctx.fillRect(xmin, 0, xmax - xmin, height); ctx.strokeRect(xmin, 0, xmax - xmin, height); } _renderTimeAxis() { if (!this.panel.showTimeAxis) { return; } const ctx = this.context; // const rows = this.data.length; // const rowHeight = this.panel.rowHeight; // const height = this._renderDimensions.height; const width = this._renderDimensions.width; const top = this._renderDimensions.rowsHeight; const headerColumnIndent = 0; // header inset (zero for now) ctx.font = this.panel.textSizeTime + 'px "Open Sans", Helvetica, Arial, sans-serif'; ctx.fillStyle = this.panel.timeTextColor; ctx.textAlign = 'left'; ctx.strokeStyle = this.panel.timeTextColor; ctx.textBaseline = 'top'; ctx.setLineDash([7, 5]); // dashes are 5px and spaces are 3px ctx.lineDashOffset = 0; const min = _.isUndefined(this.range.from) ? null : this.range.from.valueOf(); const max = _.isUndefined(this.range.to) ? null : this.range.to.valueOf(); const minPxInterval = ctx.measureText('12/33 24:59').width * 2; const estNumTicks = width / minPxInterval; const estTimeInterval = (max - min) / estNumTicks; const timeResolution = this.getTimeResolution(estTimeInterval); const pixelStep = (timeResolution / (max - min)) * width; let nextPointInTime = this.roundDate(min, timeResolution) + timeResolution; let xPos = headerColumnIndent + ((nextPointInTime - min) / (max - min)) * width; const timeFormat = this.time_format(max - min, timeResolution / 1000); let displayOffset = 0; if (this.dashboard.getTimezone() === 'utc') { displayOffset = new Date().getTimezoneOffset() * 60000; } while (nextPointInTime < max) { // draw ticks ctx.beginPath(); ctx.moveTo(xPos, top + 5); ctx.lineTo(xPos, 0); ctx.lineWidth = 1; ctx.stroke(); // draw time label const date = new Date(nextPointInTime + displayOffset); const dateStr = this.formatDate(date, timeFormat); const xOffset = ctx.measureText(dateStr).width / 2; ctx.fillText(dateStr, xPos - xOffset, top + 10); nextPointInTime += timeResolution; xPos += pixelStep; } } _renderCrosshair() { if (this.mouse.down != null) { return; } if (this.mouse.position === null) { return; } if (!this.isTimeline) { return; } const ctx = this.context; const rows = this.data.length; //let rowHeight = this.panel.rowHeight; const height = this._renderDimensions.height; ctx.beginPath(); ctx.moveTo(this.mouse.position.x, 0); ctx.lineTo(this.mouse.position.x, height); ctx.strokeStyle = this.panel.crosshairColor; ctx.setLineDash([]); ctx.lineWidth = 1; ctx.stroke(); // Draw a Circle around the point if showing a tooltip if (this.externalPT && rows > 1) { ctx.beginPath(); ctx.arc(this.mouse.position.x, this.mouse.position.y, 3, 0, 2 * Math.PI, false); ctx.fillStyle = this.panel.crosshairColor; ctx.fill(); ctx.lineWidth = 1; } } _renderAnnotations() { if (!this.panel.showTimeAxis) { return; } if (!this.annotations) { return; } const ctx = this.context; //const rows = this.data.length; const rowHeight = this.panel.rowHeight; //const height = this._renderDimensions.height; const width = this._renderDimensions.width; const top = this._renderDimensions.rowsHeight; const headerColumnIndent = 0; // header inset (zero for now) ctx.font = this.panel.textSizeTime + 'px "Open Sans", Helvetica, Arial, sans-serif'; ctx.fillStyle = '#7FE9FF'; ctx.textAlign = 'left'; ctx.strokeStyle = '#7FE9FF'; ctx.textBaseline = 'top'; ctx.setLineDash([3, 3]); ctx.lineDashOffset = 0; ctx.lineWidth = 2; const min = _.isUndefined(this.range.from) ? null : this.range.from.valueOf(); const max = _.isUndefined(this.range.to) ? null : this.range.to.valueOf(); //let xPos = headerColumnIndent; _.forEach(this.annotations, anno => { ctx.setLineDash([3, 3]); let isAlert = false; if (anno.source.iconColor) { ctx.fillStyle = anno.source.iconColor; ctx.strokeStyle = anno.source.iconColor; } else if (anno.annotation === undefined) { // grafana annotation ctx.fillStyle = '#7FE9FF'; ctx.strokeStyle = '#7FE9FF'; } else { isAlert = true; ctx.fillStyle = '#EA0F3B'; //red ctx.strokeStyle = '#EA0F3B'; } this._drawVertical(ctx, anno.time, min, max, headerColumnIndent, top, width, isAlert); //do the TO rangeMap if (anno.isRegion) { this._drawVertical(ctx, anno.timeEnd, min, max, headerColumnIndent, top, width, isAlert); //draw horizontal line at bottom const xPosStart = headerColumnIndent + ((anno.time - min) / (max - min)) * width; const xPosEnd = headerColumnIndent + ((anno.timeEnd - min) / (max - min)) * width; // draw ticks ctx.beginPath(); ctx.moveTo(xPosStart, top + 5); ctx.lineTo(xPosEnd, top + 5); ctx.lineWidth = 4; ctx.setLineDash([]); ctx.stroke(); //end horizontal //do transparency if (isAlert === false) { ctx.save(); ctx.fillStyle = '#7FE9FF'; ctx.globalAlpha = 0.2; ctx.fillRect(xPosStart, 0, xPosEnd - xPosStart, rowHeight); ctx.stroke(); ctx.restore(); } } }); } _drawVertical(ctx, timeVal, min, max, headerColumnIndent, top, width, isAlert) { const xPos = headerColumnIndent + ((timeVal - min) / (max - min)) * width; // draw ticks ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(xPos, top + 5); ctx.lineTo(xPos, 0); ctx.stroke(); // draw triangle ctx.moveTo(xPos + 0, top); ctx.lineTo(xPos - 5, top + 7); ctx.lineTo(xPos + 5, top + 7); ctx.fill(); // draw alert label if (isAlert === true) { const dateStr = '\u25B2'; const xOffset = ctx.measureText(dateStr).width / 2; ctx.fillText(dateStr, xPos - xOffset, top + 10); } } } /** * All panels will be passed tables that have our best guess at colum type set * * This is also used by PanelChrome for snapshot support */ export function getProcessedDataFrames(results?: DataQueryResponseData[]): DataFrame[] { if (!results || !isArray(results)) { return []; } const dataFrames: DataFrame[] = []; for (const result of results) { const dataFrame = guessFieldTypes(toDataFrame(result)); // clear out any cached calcs for (const field of dataFrame.fields) { const f = field as any; f.calcs = undefined; f.state = undefined; } dataFrames.push(dataFrame); } return dataFrames; } export { DiscretePanelCtrl as PanelCtrl };
the_stack
import { Internationalization, createElement, remove, extend, EventHandler, Ajax, loadCldr } from '@syncfusion/ej2-base'; import { Dialog, Popup, Tooltip } from '@syncfusion/ej2-popups'; import { ResourceDetails, Schedule, ScheduleModel, EJ2Instance, ActionEventArgs, CallbackFunction } from '../../src/schedule/index'; import { cloneDataSource } from './base/datasource.spec'; import * as cls from '../../src/schedule/base/css-constant'; import { RecurrenceEditor, RecurrenceEditorModel } from '../../src/recurrence-editor/index'; import { DataManager } from '@syncfusion/ej2-data'; /** * schedule spec utils */ const instance: Internationalization = new Internationalization(); (window as TemplateFunction).getTimeIn12 = (value: Date) => instance.formatDate(value, { skeleton: 'hm' }); (window as TemplateFunction).getTimeIn24 = (value: Date) => instance.formatDate(value, { skeleton: 'Hm' }); (window as TemplateFunction).getDateHeaderText = (value: Date) => instance.formatDate(value, { skeleton: 'MEd' }); (window as TemplateFunction).getShortDateTime = (value: Date) => instance.formatDate(value, { type: 'dateTime', skeleton: 'short' }); (window as TemplateFunction).getResourceName = (value: ResourceDetails) => ((value as ResourceDetails).resourceData) ? (value as ResourceDetails).resourceData[(value as ResourceDetails).resource.textField] : (value as ResourceDetails).resourceName; (window as TemplateFunction).getCellText = (value: Date) => { return ([0, 6].indexOf(value.getDay()) >= 0) ? '<span class="caption">Weekend</span>' : ''; }; (window as TemplateFunction).getMonthCellText = (date: Date) => { if (date.getMonth() === 0 && date.getDate() === 1) { return '<span class="caption">Template</span>'; } else if (date.getMonth() === 0 && date.getDate() === 15) { return '<span class="caption">Template</span>'; } return ''; }; export interface TemplateFunction extends Window { getTimeIn12?: CallbackFunction; getTimeIn24?: CallbackFunction; getDateHeaderText?: CallbackFunction; getShortDateTime?: CallbackFunction; getResourceName?: CallbackFunction; getCellText?: CallbackFunction; getMonthCellText?: CallbackFunction; } /** * Method to create schedule component * * @param {ScheduleModel} options Accepts the schedule options * @param {Object[] | DataManager} data Accepts the datasource * @param {CallbackFunction} done Accepts the callback function * @param {HTMLElement} element Accepts the DOM element reference * @returns {Schedule} Returns the schedule instance * @private */ // eslint-disable-next-line max-len export function createSchedule(options: ScheduleModel, data: Record<string, any>[] | DataManager, done?: CallbackFunction, element?: HTMLElement): Schedule { element = element || createElement('div', { id: 'Schedule' }); document.body.appendChild(element); const defaultOptions: ScheduleModel = { height: 580, eventSettings: { dataSource: data instanceof DataManager ? data : cloneDataSource(data) }, // eslint-disable-next-line no-console actionFailure: (args: ActionEventArgs) => console.log(JSON.stringify(args)) }; if (done) { defaultOptions.dataBound = () => { disableScheduleAnimation(scheduleObj); done(); }; } const model: ScheduleModel = extend({}, defaultOptions, options, true); const scheduleObj: Schedule = new Schedule(model, element); return scheduleObj; } /** * Method to create recurrence editor component * * @param {RecurrenceEditorModel} model Accepts the recurrence editor options * @param {HTMLElement} element Accepts the DOM element reference * @returns {RecurrenceEditor} Returns the recurrence ediotr instance * @private */ export function createRecurrenceEditor(model?: RecurrenceEditorModel, element?: HTMLElement): RecurrenceEditor { element = element || createElement('div', { id: 'RecurrenceEditor' }); document.body.appendChild(element); const recurrenceObj: RecurrenceEditor = model ? new RecurrenceEditor(model) : new RecurrenceEditor(); recurrenceObj.appendTo(element); return recurrenceObj; } /** * Method to create group scheduler * * @param {number} groupCount Accepts the group count * @param {ScheduleModel} options Accepts the schedule model * @param {Object[]} dataSource Accepts the datasource * @param {CallbackFunction} done Accepts the callback function * @returns {Schedule} Returns the schedule instance */ // eslint-disable-next-line max-len export function createGroupSchedule(groupCount: number, options: ScheduleModel, dataSource: Record<string, any>[], done: CallbackFunction): Schedule { if (groupCount === 1) { const groupOptions: ScheduleModel = { group: { resources: ['Owners'] }, resources: [ { field: 'OwnerId', title: 'Owner', name: 'Owners', allowMultiple: true, dataSource: [ { OwnerText: 'Nancy', Id: 1, OwnerColor: '#ffaa00' }, { OwnerText: 'Steven', Id: 2, OwnerColor: '#f8a398' }, { OwnerText: 'Michael', Id: 3, OwnerColor: '#7499e1' }, { OwnerText: 'Oliver', Id: 4, OwnerColor: '#ffaa00' }, { OwnerText: 'John', Id: 5, OwnerColor: '#f8a398' }, { OwnerText: 'Barry', Id: 6, OwnerColor: '#7499e1' }, { OwnerText: 'Felicity', Id: 7, OwnerColor: '#ffaa00' }, { OwnerText: 'Cisco', Id: 8, OwnerColor: '#f8a398' }, { OwnerText: 'Sara', Id: 9, OwnerColor: '#7499e1' }, { OwnerText: 'Malcolm', Id: 10, OwnerColor: '#ffaa00' } ], textField: 'OwnerText', idField: 'Id', colorField: 'OwnerColor' } ] }; options = extend(groupOptions, options); } if (groupCount === 2) { const groupOptions: ScheduleModel = { group: { allowGroupEdit: true, resources: ['Rooms', 'Owners'] }, resources: [ { field: 'RoomId', title: 'Room', name: 'Rooms', allowMultiple: true, dataSource: [ { RoomText: 'ROOM 1', Id: 1, RoomColor: '#cb6bb2' }, { RoomText: 'ROOM 2', Id: 2, RoomColor: '#56ca85' } ], textField: 'RoomText', idField: 'Id', colorField: 'RoomColor' }, { field: 'OwnerId', title: 'Owner', name: 'Owners', allowMultiple: true, dataSource: [ { OwnerText: 'Nancy', Id: 1, OwnerGroupId: 1, OwnerColor: '#ffaa00' }, { OwnerText: 'Steven', Id: 2, OwnerGroupId: 2, OwnerColor: '#f8a398' }, { OwnerText: 'Michael', Id: 3, OwnerGroupId: 1, OwnerColor: '#7499e1' } ], textField: 'OwnerText', idField: 'Id', groupIDField: 'OwnerGroupId', colorField: 'OwnerColor' } ] }; options = extend(groupOptions, options); } return createSchedule(options, dataSource, done); } /** * Method to destroy component * * @param {Schedule | RecurrenceEditor} instance Accepts the component instance * @returns {void} * @private */ export function destroy(instance: Schedule | RecurrenceEditor): void { if (instance) { instance.destroy(); remove(document.getElementById(instance.element.id)); } } let touchTestObj: any; export interface CommonArgs { changedTouches?: any[]; clientX?: number; clientY?: number; target?: Element | HTMLElement; type?: string; preventDefault(): void; stopPropagation(): void; } let node: Element; const startMouseEventArs: CommonArgs = { clientX: 200, clientY: 200, target: node, type: 'touchstart', preventDefault: (): void => { /** Do Nothing */ }, stopPropagation: (): void => { /** Do Nothing */ } }; const moveMouseEventArs: CommonArgs = { clientX: 500, clientY: 200, target: node, type: 'touchmove', preventDefault: (): void => { /** Do Nothing */ }, stopPropagation: (): void => { /** Do Nothing */ } }; const endMouseEventArs: CommonArgs = { clientX: 200, clientY: 200, target: node, type: 'touchend', preventDefault: (): void => { /** Do Nothing */ }, stopPropagation: (): void => { /** Do Nothing */ } }; /** * Method to trigger swipe event * * @param {Element} target Accepts the DOM element * @param {number} x Accepts the X value * @param {number} y Accepts the Y value * @returns {void} * @private */ export function triggerSwipeEvent(target: Element, x?: number, y?: number): void { node = target; startMouseEventArs.target = node; moveMouseEventArs.target = node; endMouseEventArs.target = node; touchTestObj = ((node as EJ2Instance).ej2_instances[0] as any); const movedEnd: CommonArgs = moveMouseEventArs; movedEnd.type = 'touchend'; if (x) { movedEnd.clientX = x; } if (y) { movedEnd.clientY = y; } touchTestObj.startEvent(startMouseEventArs); touchTestObj.moveEvent(moveMouseEventArs); touchTestObj.endEvent(movedEnd); EventHandler.trigger(<HTMLElement>node, 'transitionend'); } /** * Method to trigger mouse event * * @param {HTMLElement} node Accepts the DOM element * @param {string} eventType Accepts the event type * @param {number} x Accepts the X value * @param {number} y Accepts the Y value * @param {boolean} isShiftKey Accepts the shift key allowed or not * @param {boolean} isCtrlKey Accepts the ctrl key allowed or not * @returns {void} * @private */ // eslint-disable-next-line max-len export function triggerMouseEvent(node: HTMLElement, eventType: string, x: number = 0, y: number = 0, isShiftKey?: boolean, isCtrlKey?: boolean): void { const mouseEve: MouseEvent = new MouseEvent(eventType); mouseEve.initMouseEvent(eventType, true, true, window, 0, 0, 0, x, y, isCtrlKey, false, isShiftKey, false, 0, null); node.dispatchEvent(mouseEve); } /** * Method to get the instance * * @param {string} className Accepts the element class name * @returns {Object[]} Returns the component instance * @private */ export function getInstance(className: string): Record<string, any> { return (document.querySelector('.' + cls.EVENT_WINDOW_DIALOG_CLASS + ' .' + className) as EJ2Instance).ej2_instances[0]; } /** * Method to trigger scroll event * * @param {HTMLElement} target Accepts the DOM element * @param {number} scrollTop Accepts the scroll top value * @param {number} scrollLeft Accepts the scroll left value * @returns {void} * @private */ export function triggerScrollEvent(target: HTMLElement, scrollTop: number, scrollLeft?: number): void { target.scrollTop = scrollTop; if (scrollLeft) { target.scrollLeft = scrollLeft; } const e: any = document.createEvent('UIEvents'); e.initUIEvent('scroll', true, true, window, 1); target.dispatchEvent(e); } /** * Method to trigger keydown event * * @param {HTMLElement} target Accepts the DOM element * @param {string} keyName Accepts the key value * @param {number} KeyCode Accepts the number * @returns {void} * @private */ export function triggerKeyDownEvent(target: HTMLElement, keyName: string, KeyCode: number): void { const event: { [key: string]: string } = {}; Object.defineProperties(event, { code: { value: keyName }, key: { value: keyName }, keyCode: { value: KeyCode }, view: { value: window }, bubbles: { value: true } }); const keyboardEvent: KeyboardEvent = new KeyboardEvent('keydown', event); target.dispatchEvent(keyboardEvent); } /** * Method to disable animation * * @param {Schedule} schObj Accepts the schedule instance * @returns {void} * @private */ export function disableScheduleAnimation(schObj: Schedule): void { disablePopupAnimation(schObj.quickPopup.quickPopup); disablePopupAnimation(schObj.quickPopup.morePopup); disableDialogAnimation(schObj.quickPopup.quickDialog); disableDialogAnimation(schObj.eventWindow.dialogObject); const resTree: Element = schObj.element.querySelector('.e-resource-tree-popup'); if (resTree) { const resTreePopup: Popup = (resTree as EJ2Instance).ej2_instances[0] as Popup; disablePopupAnimation(resTreePopup); } } /** * Method to disable animation * * @param {Popup} popupObj Accepts the popup instance * @returns {void} * @private */ export function disablePopupAnimation(popupObj: Popup): void { popupObj.showAnimation = null; popupObj.hideAnimation = null; popupObj.dataBind(); } /** * Method to disable animation * * @param {Dialog} dialogObject Accepts the dialog instance * @returns {void} * @private */ export function disableDialogAnimation(dialogObject: Dialog): void { dialogObject.animationSettings = { effect: 'None' }; dialogObject.dataBind(); dialogObject.hide(); } /** * Method to disable animation * * @param {Tooltip} tooltipObj Accepts the tooltip instance * @returns {void} * @private */ export function disableTooltipAnimation(tooltipObj: Tooltip): void { tooltipObj.animation = { open: { effect: 'None' }, close: { effect: 'None' } }; tooltipObj.dataBind(); } /** * Method to load culture files * * @param {string} name Accepts the culture name * @param {boolean} base Accepts the base value * @returns {void} * @private */ export function loadCultureFiles(name: string, base?: boolean): void { const files: string[] = base ? ['numberingSystems.json'] : ['ca-gregorian.json', 'numbers.json', 'timeZoneNames.json', 'currencies.json']; for (const prop of files) { let ajax: Ajax; if (base) { ajax = new Ajax('base/spec/cldr-data/supplemental/' + prop, 'GET', false); } else { ajax = new Ajax('base/spec/cldr-data/main/' + name + '/' + prop, 'GET', false); } ajax.onSuccess = (value: string) => loadCldr(JSON.parse(value)); ajax.send(); } }
the_stack
import * as React from 'react'; import OlStyle from 'ol/style/Style'; import OlStyleFill from 'ol/style/Fill'; import OlStyleCircle from 'ol/style/Circle'; import OlStyleStroke from 'ol/style/Stroke'; import OlMap from 'ol/Map'; import OlFeature from 'ol/Feature'; import OlSourceVector from 'ol/source/Vector'; import OlLayerVector from 'ol/layer/Vector'; import OlLayerBase from 'ol/layer/Base'; import OlGeometry from 'ol/geom/Geometry'; import OlGeomGeometryCollection from 'ol/geom/GeometryCollection'; import OlMapBrowserEvent from 'ol/MapBrowserEvent'; import { getUid } from 'ol'; import _isArray from 'lodash/isArray'; import _differenceWith from 'lodash/differenceWith'; import _isEqual from 'lodash/isEqual'; import _isFunction from 'lodash/isFunction'; import _kebabCase from 'lodash/kebabCase'; import MapUtil from '@terrestris/ol-util/dist/MapUtil/MapUtil'; import { CSS_PREFIX } from '../../constants'; import '@ag-grid-community/core/dist/styles/ag-grid.css'; import '@ag-grid-community/core/dist/styles/ag-theme-balham.css'; import '@ag-grid-community/core/dist/styles/ag-theme-fresh.css'; import { AgGridReact, AgGridReactProps } from '@ag-grid-community/react'; import { ClientSideRowModelModule } from '@ag-grid-community/client-side-row-model'; import { RowClickedEvent, CellMouseOverEvent, CellMouseOutEvent, SelectionChangedEvent } from '@ag-grid-community/core'; interface DefaultProps { /** * The height of the grid. */ height: number | string; /** * The theme to use for the grid. See * https://www.ag-grid.com/javascript-grid-styling/ for available options. * Note: CSS must be loaded to use the theme! */ theme: string; /** * The features to show in the grid and the map (if set). */ features: OlFeature<OlGeometry>[]; /** */ attributeBlacklist?: string[]; /** * The default style to apply to the features. */ featureStyle: OlStyle | (() => OlStyle); /** * The highlight style to apply to the features. */ highlightStyle: OlStyle | (() => OlStyle); /** * The select style to apply to the features. */ selectStyle: OlStyle | (() => OlStyle); /** * The name of the vector layer presenting the features in the grid. */ layerName: string; /** * Custom column definitions to apply to the given column (mapping via key). */ columnDefs: any; /** * A Function that creates the rowkey from the given feature. * Receives the feature as property. * Default is: feature => feature.ol_uid */ keyFunction: (feature: OlFeature<OlGeometry>) => string; /** * Whether the map should center on the current feature's extent on init or * not. */ zoomToExtent: boolean; /** * Whether rows and features should be selectable or not. */ selectable: boolean; } interface BaseProps { /** * The width of the grid. */ width: number | string; /** * A CSS class which should be added to the table. */ className?: string; /** * A CSS class to add to each table row or a function that * is evaluated for each record. */ rowClassName?: string | ((record: any) => string); /** * The map the features should be rendered on. If not given, the features * will be rendered in the table only. */ map: OlMap; /** * Custom row data to be shown in feature grid. This might be helpful if * original feature properties should be manipulated in some way before they * are represented in grid. * If provided, #getRowData method won't be called. */ rowData?: any[]; /** * Callback function, that will be called on rowclick. */ onRowClick?: (row: any, feature: OlFeature<OlGeometry>, evt: RowClickedEvent) => void; /** * Callback function, that will be called on rowmouseover. */ onRowMouseOver?: (row: any, feature: OlFeature<OlGeometry>, evt: CellMouseOverEvent) => void; /** * Callback function, that will be called on rowmouseout. */ onRowMouseOut?: (row: any, feature: OlFeature<OlGeometry>, evt: CellMouseOutEvent) => void; /** * Callback function, that will be called if the selection changes. */ onRowSelectionChange?: ( selectedRowsAfter: any[], selectedFeatures: OlFeature<OlGeometry>[], deselectedRows: any[], deselectedFeatures: OlFeature<OlGeometry>[], evt: SelectionChangedEvent ) => void; /** * Optional callback function, that will be called if `selectable` is set * `true` and the a `click` event on the map occurs, e.g. a feature has been * selected in the map. The function receives the olEvt and the selected * features (if any). */ onMapSingleClick?: (olEvt: OlMapBrowserEvent<MouseEvent>, selectedFeatures: OlFeature<OlGeometry>[]) => void; /* * A Function that is called once the grid is ready. */ onGridIsReady?: (grid: any) => void; } interface AgFeatureGridState { grid: any; selectedRows: any[]; } export type AgFeatureGridProps = BaseProps & Partial<DefaultProps> & AgGridReactProps; /** * The AgFeatureGrid. * * @class The AgFeatureGrid * @extends React.Component */ export class AgFeatureGrid extends React.Component<AgFeatureGridProps, AgFeatureGridState> { /** * The default properties. */ static defaultProps: DefaultProps = { theme: 'ag-theme-balham', height: 250, features: [], attributeBlacklist: [], featureStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(255, 255, 255, 0.5)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(255, 255, 255, 0.5)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }) }) }), highlightStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }) }) }), selectStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 2 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 2 }) }) }), layerName: 'react-geo-feature-grid-layer', columnDefs: {}, keyFunction: getUid, zoomToExtent: false, selectable: false }; /** * The reference of this grid. * @private */ _ref; /** * The className added to this component. * @private */ _className = `${CSS_PREFIX}ag-feature-grid`; /** * The class name to add to each table row. * @private */ _rowClassName = `${CSS_PREFIX}ag-feature-grid-row`; /** * The prefix to use for each table row class. * @private */ _rowKeyClassNamePrefix = 'row-key-'; /** * The hover class name. * @private */ _rowHoverClassName = 'ag-row-hover'; /** * The source holding the features of the grid. * @private */ _source = null; /** * The layer representing the features of the grid. * @private */ _layer = null; /** * The constructor. */ constructor(props: AgFeatureGridProps) { super(props); this.state = { grid: null, selectedRows: [] }; } /** * Called on lifecycle phase componentDidMount. */ componentDidMount() { const { map, features, zoomToExtent } = this.props; this.initVectorLayer(map); this.initMapEventHandlers(map); if (zoomToExtent) { this.zoomToFeatures(features); } } /** * Invoked immediately after updating occurs. This method is not called for * the initial render. * * @param prevProps The previous props. */ componentDidUpdate(prevProps: AgFeatureGridProps) { const { map, features, selectable, zoomToExtent } = this.props; if (!(_isEqual(prevProps.map, map))) { this.initVectorLayer(map); this.initMapEventHandlers(map); } if (!(_isEqual(prevProps.features, features))) { if (this._source) { this._source.clear(); this._source.addFeatures(features); } if (zoomToExtent) { this.zoomToFeatures(features); } } if (!(_isEqual(prevProps.selectable, selectable))) { if (selectable && map) { map.on('singleclick', this.onMapSingleClick); } else { if (map) { map.un('singleclick', this.onMapSingleClick); } } } } /** * Called on lifecycle phase componentWillUnmount. */ componentWillUnmount() { this.deinitVectorLayer(); this.deinitMapEventHandlers(); } /** * Initialized the vector layer that will be used to draw the input features * on and adds it to the map (if any). * * @param map The map to add the layer to. */ initVectorLayer = (map: OlMap) => { const { features, featureStyle, layerName } = this.props; if (!(map instanceof OlMap)) { return; } if (MapUtil.getLayerByName(map, layerName)) { return; } const source = new OlSourceVector({ features: features }); const layer = new OlLayerVector({ properties: { name: layerName, }, source: source, style: featureStyle }); map.addLayer(layer); this._source = source; this._layer = layer; }; /** * Adds map event callbacks to highlight and select features in the map (if * given) on pointermove and singleclick. Hovered and selected features will * be highlighted and selected in the grid as well. * * @param map The map to register the handlers to. */ initMapEventHandlers = (map: OlMap) => { const { selectable } = this.props; if (!(map instanceof OlMap)) { return; } map.on('pointermove', this.onMapPointerMove); if (selectable) { map.on('singleclick', this.onMapSingleClick); } }; /** * Highlights the feature beneath the cursor on the map and in the grid. * * @param olEvt The ol event. */ onMapPointerMove = (olEvt: any) => { const { map, features, highlightStyle, selectStyle } = this.props; const { grid } = this.state; const selectedRowKeys = this.getSelectedRowKeys(); const selectedFeatures = (map.getFeaturesAtPixel(olEvt.pixel, { layerFilter: layerCand => layerCand === this._layer }) || []) as OlFeature<OlGeometry>[]; if (!grid || !grid.api) { return; } const rowRenderer = grid.api.rowRenderer; features.forEach(feature => { const key = this.props.keyFunction(feature); let rc: any; rowRenderer.forEachRowComp((idx, rowComp) => { if (rowComp.getRowNode().data.key === key) { rc = rowComp; } }); if (rc) { const el = rc.getBodyRowElement(); if (el) { el.classList.remove(this._rowHoverClassName); } } if (selectedRowKeys.includes(key)) { feature.setStyle(selectStyle); } else { feature.setStyle(null); } }); selectedFeatures.forEach(feature => { const key = this.props.keyFunction(feature); let rc: any; rowRenderer.forEachRowComp((idx, rowComp) => { if (rowComp.getRowNode().data.key === key) { rc = rowComp; } }); if (rc) { const el = rc.getBodyRowElement(); if (el) { el.classList.add(this._rowHoverClassName); } } feature.setStyle(highlightStyle); }); }; /** * Selects the selected feature in the map and in the grid. * * @param olEvt The ol event. */ onMapSingleClick = (olEvt: OlMapBrowserEvent<MouseEvent>) => { const { map, selectStyle, onMapSingleClick } = this.props; const selectedRowKeys = this.getSelectedRowKeys(); const selectedFeatures = (map.getFeaturesAtPixel(olEvt.pixel, { layerFilter: (layerCand: OlLayerBase) => layerCand === this._layer }) || []) as OlFeature<OlGeometry>[]; if (_isFunction(onMapSingleClick)) { onMapSingleClick(olEvt, selectedFeatures); } selectedFeatures.forEach(selectedFeature => { const key = this.props.keyFunction(selectedFeature); if (selectedRowKeys && selectedRowKeys.includes(key)) { selectedFeature.setStyle(null); const node = this.getRowFromFeatureKey(key); if (node) { node.setSelected(false); } } else { selectedFeature.setStyle(selectStyle); const node = this.getRowFromFeatureKey(key); if (node) { node.setSelected(true); } } }); }; /** * Removes the vector layer from the given map (if any). */ deinitVectorLayer = () => { const { map } = this.props; if (!(map instanceof OlMap)) { return; } map.removeLayer(this._layer); }; /** * Unbinds the pointermove and click event handlers from the map (if given). */ deinitMapEventHandlers = () => { const { map, selectable } = this.props; if (!(map instanceof OlMap)) { return; } map.un('pointermove', this.onMapPointerMove); if (selectable) { map.un('singleclick', this.onMapSingleClick); } }; /** * Returns the column definitions out of the attributes of the first * given feature. * * @return The column definitions. */ getColumnDefs = () => { const { attributeBlacklist, features, columnDefs, selectable } = this.props; const columns = []; const feature = features[0]; if (!(feature instanceof OlFeature)) { return columns; } const props = feature.getProperties(); if (selectable) { columns.push({ headerName: '', checkboxSelection: true, headerCheckboxSelection: true, width: 28, pinned: 'left', lockPosition: true, suppressMenu: true, suppressSorting: true, suppressFilter: true, suppressResize: true, suppressMovable: true }); } let index = -1; Object.keys(props).forEach(key => { if (attributeBlacklist.includes(key)) { return; } if (props[key] instanceof OlGeometry) { return; } if (columnDefs[key] && columnDefs[key].index !== undefined) { index = columnDefs[key].index; } else { ++index; } columns[index] = { headerName: key, field: key, ...columnDefs[key] }; }); return columns; }; /** * Returns the table row data from all of the given features. * * @return The table data. */ getRowData = () => { const { features } = this.props; const data = []; features.forEach(feature => { const properties = feature.getProperties(); const filtered = Object.keys(properties) .filter(key => !(properties[key] instanceof OlGeometry)) .reduce((obj, key) => { obj[key] = properties[key]; return obj; }, {}); data.push({ key: this.props.keyFunction(feature), ...filtered }); }); return data; }; /** * Returns the correspondig feature for the given table row key. * * @param key The row key to obtain the feature from. * @return The feature candidate. */ getFeatureFromRowKey = (key: string): OlFeature<OlGeometry> => { const { features, keyFunction } = this.props; const feature = features.filter(f => keyFunction(f) === key); return feature[0]; }; /** * Returns the correspondig rowNode for the given feature id. * * @param key The feature's key to obtain the row from. * @return he row candidate. */ getRowFromFeatureKey = (key: string) => { const { grid } = this.state; let rowNode; if (!grid || !grid.api) { return; } grid.api.forEachNode((node: any) => { if (node.data.key === key) { rowNode = node; } }); return rowNode; }; /** * Returns the currently selected row keys. * * @return An array with the selected row keys. */ getSelectedRowKeys = (): string[] | undefined => { const { grid } = this.state; if (!grid || !grid.api) { return undefined; } const selectedRows = grid.api.getSelectedRows(); return selectedRows.map(row => row.key); }; /** * Called on row click and zooms the the corresponding feature's extent. * * @param evt The RowClickedEvent. */ onRowClick = (evt: RowClickedEvent) => { const { onRowClick } = this.props; const row = evt.data; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowClick)) { onRowClick(row, feature, evt); } else { this.zoomToFeatures([feature]); } }; /** * Called on row mouseover and hightlights the corresponding feature's * geometry. * * @param evt The ellMouseOverEvent. */ onRowMouseOver = (evt: CellMouseOverEvent) => { const { onRowMouseOver } = this.props; const row = evt.data; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowMouseOver)) { onRowMouseOver(row, feature, evt); } this.highlightFeatures([feature]); }; /** * Called on mouseout and unhightlights any highlighted feature. * * @param evt The CellMouseOutEvent. */ onRowMouseOut = (evt: CellMouseOutEvent) => { const { onRowMouseOut } = this.props; const row = evt.data; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowMouseOut)) { onRowMouseOut(row, feature, evt); } this.unhighlightFeatures([feature]); }; /** * Fits the map's view to the extent of the passed features. * * @param features The features to zoom to. */ zoomToFeatures = (features: OlFeature<OlGeometry>[]) => { const { map } = this.props; if (!(map instanceof OlMap)) { return; } const featGeometries = []; features.forEach(feature => { featGeometries.push(feature.getGeometry()); }); if (featGeometries.length > 0) { const geomCollection = new OlGeomGeometryCollection(featGeometries); map.getView().fit(geomCollection.getExtent()); } }; /** * Highlights the given features in the map. * * @param highlightFeatures The features to highlight. */ highlightFeatures = (highlightFeatures: OlFeature<OlGeometry>[]) => { const { map, highlightStyle } = this.props; if (!(map instanceof OlMap)) { return; } highlightFeatures.forEach(feature => feature.setStyle(highlightStyle)); }; /** * Unhighlights the given features in the map. * * @param unhighlightFeatures The features to unhighlight. */ unhighlightFeatures = (unhighlightFeatures: OlFeature<OlGeometry>[]) => { const { map, selectStyle } = this.props; if (!(map instanceof OlMap)) { return; } const selectedRowKeys = this.getSelectedRowKeys(); unhighlightFeatures.forEach(feature => { const key = this.props.keyFunction(feature); if (selectedRowKeys && selectedRowKeys.includes(key)) { feature.setStyle(selectStyle); } else { feature.setStyle(null); } }); }; /** * Sets the select style to the given features in the map. * * @param features The features to select. */ selectFeatures = (features: OlFeature<OlGeometry>[]) => { const { map, selectStyle } = this.props; if (!(map instanceof OlMap)) { return; } features.forEach(feature => { if (feature) { feature.setStyle(selectStyle); } }); }; /** * Resets the style of all features. */ resetFeatureStyles = () => { const { map, features } = this.props; if (!(map instanceof OlMap)) { return; } features.forEach(feature => feature.setStyle(null)); }; /** * Called if the selection changes. */ onSelectionChanged = (evt: SelectionChangedEvent) => { const { onRowSelectionChange } = this.props; const { grid, selectedRows } = this.state; let selectedRowsAfter: any[]; if (!grid || !grid.api) { selectedRowsAfter = evt.api.getSelectedRows(); } else { selectedRowsAfter = grid.api.getSelectedRows(); } const deselectedRows = _differenceWith(selectedRows, selectedRowsAfter, (a: any , b: any) => a.key === b.key); const selectedFeatures = selectedRowsAfter.map(row => this.getFeatureFromRowKey(row.key)); const deselectedFeatures = deselectedRows.map(row => this.getFeatureFromRowKey(row.key)); // update state this.setState({ selectedRows: selectedRowsAfter }); if (_isFunction(onRowSelectionChange)) { onRowSelectionChange(selectedRowsAfter, selectedFeatures, deselectedRows, deselectedFeatures, evt); } this.resetFeatureStyles(); this.selectFeatures(selectedFeatures); }; /** * * @param grid */ onGridReady(grid: any) { this.setState({ grid }, this.onVisiblityChange); if (this.props.onGridIsReady) { this.props.onGridIsReady(grid); } } /** * */ onVisiblityChange() { if (this.state.grid) { this.state.grid.api.sizeColumnsToFit(); } } /** * The render method. */ render() { const { className, height, width, theme, rowClassName, features, map, attributeBlacklist, onRowClick, onRowMouseOver, onRowMouseOut, zoomToExtent, selectable, featureStyle, highlightStyle, selectStyle, layerName, columnDefs, children, rowData, ...passThroughProps } = this.props; const finalClassName = className ? `${className} ${this._className} ${theme}` : `${this._className} ${theme}`; // TODO: Not sure, if this is still needed. One may want to get a specific // row by using getRowFromFeatureKey instead. let rowClassNameFn; if (_isFunction(rowClassName)) { rowClassNameFn = node => { const determinedRowClass = (rowClassName as ((record: any) => string))(node.data); return `${this._rowClassName} ${determinedRowClass}`; }; } else { const finalRowClassName = rowClassName ? `${rowClassName} ${this._rowClassName}` : this._rowClassName; rowClassNameFn = node => `${finalRowClassName} ${this._rowKeyClassNamePrefix}${_kebabCase(node.data.key)}`; } return ( <div className={finalClassName} // TODO: move to less?! style={{ height: height, width: width }} > <AgGridReact columnDefs={columnDefs && _isArray(columnDefs) ? columnDefs : this.getColumnDefs()} rowData={rowData && _isArray(rowData) ? rowData : this.getRowData()} onGridReady={this.onGridReady.bind(this)} rowSelection="multiple" suppressRowClickSelection={true} onSelectionChanged={this.onSelectionChanged.bind(this)} onRowClicked={this.onRowClick.bind(this)} onCellMouseOver={this.onRowMouseOver.bind(this)} onCellMouseOut={this.onRowMouseOut.bind(this)} ref={ref => this._ref = ref} getRowClass={rowClassNameFn} modules={[ ClientSideRowModelModule ]} {...passThroughProps} > {children} </AgGridReact> </div> ); } } export default AgFeatureGrid;
the_stack
/// <reference types="node" /> export as namespace PizZip; export = PizZip; declare class PizZip { /** * If the browser supports them, PizZip can take advantage of some "new" features : ArrayBuffer, Blob, Uint8Array. * To know if PizZip can use them, you can check the PizZip.support object. */ static support: { /** * true if PizZip can read and generate ArrayBuffer, false otherwise. */ arraybuffer: boolean; /** * true if PizZip can read and generate Uint8Array, false otherwise. */ uint8array: boolean; /** * true if PizZip can read and generate Blob, false otherwise. */ blob: boolean; /** * true if PizZip can read and generate nodejs Buffer, false otherwise. */ nodebuffer: boolean; }; /** * the ZipObjects inside the zip with the name as key. */ files: { [key: string]: PizZip.ZipObject }; /** * the comment of the zip file. */ comment: string; constructor(); /** * Specifying data & options is a shortcut for new PizZip().load(data, options); * * @param data the zip file * @param options the options to load the zip file */ // tslint:disable-next-line unified-signatures new (undefined, {options}) is not an acceptable input constructor(data: PizZip.LoadData, options?: PizZip.LoadOptions); /** * Read an existing zip and merge the data in the current PizZip object at the current folder level. * This technique has some limitations, see https://github.com/open-xml-templating/pizzip/blob/master/documentation/limitations.md * You shouldn't update the data given to this method : it is kept as it so any update will impact the stored data. * Throws an exception if the loaded data is not valid zip data or if it uses features (multi volume, password protected, etc). * @param data the zip file * @param options the options to load the zip file */ load(data: PizZip.LoadData, options?: PizZip.LoadOptions): this; /** * Add (or update) a file to the zip file. * You shouldn't update the data given to this method : it is kept as it so any update will impact the stored data. * Throws an exception if the data is not in a supported format. * @param name the name of the file. You can specify folders in the name : the folder separator is a forward slash ("/"). * @param data the content of the file. * @param options the options. */ file(name: string, data: PizZip.Data, options?: PizZip.FileOptions): this; /** * Get a file with the specified name. You can specify folders in the name : the folder separator is a forward slash ("/"). * @param name the name of the file. */ file(name: string): PizZip.ZipObject | null; /** * Search a file in the current folder and subfolders with a regular expression. The regex is tested against the relative filename. * @param regex the regex to use. */ file(regex: RegExp): PizZip.ZipObject[]; /** * Filter nested files/folders with the specified function. The predicate must return true if the file should be included, false otherwise. * @param predicate the predicate to use. */ filter( predicate: ( /** * the filename and its path, reliatively to the current folder. */ relativePath: string, /** * the file being tested */ file: PizZip.ZipObject, ) => boolean, ): PizZip.ZipObject[]; /** * Create a directory if it doesn't exist, return a new PizZip object with the new folder as root. * @param name the name of the directory. */ folder(name: string): this; /** * Search a subdirectory in the current directory with a regular expression. The regex is tested against the relative path. * @param regex the regex to use. */ folder(regex: RegExp): PizZip.ZipObject[]; /** * Generates the complete zip file. * Throws an exception if the asked type is not available in the browser, * see https://github.com/open-xml-templating/pizzip/blob/master/documentation/api_pizzip/support.md * @param options the options to generate the zip file */ generate(options?: PizZip.GenerateOptions & { type?: 'string' | 'base64' | undefined }): string; generate(options: PizZip.GenerateOptions & { type: 'blob' }): Blob; generate(options: PizZip.GenerateOptions & { type: 'nodebuffer' }): Buffer; generate(options: PizZip.GenerateOptions & { type: 'arraybuffer' }): ArrayBuffer; generate(options: PizZip.GenerateOptions & { type: 'uint8array' }): Uint8Array; /** * Delete a file or folder (recursively). * @param name the name of the file/folder to delete. */ remove(name: string): this; } declare namespace PizZip { type Compression = 'STORE' | 'DEFLATE'; type Data = string | ArrayBuffer | Uint8Array | Buffer; type LoadData = Data | number[]; interface ZipObject { /** * the absolute path of the file */ name: string; /** * true if this is a directory */ dir: boolean; /** * the last modification date */ date: Date; /** * the comment for this file */ comment: string; /** * The UNIX permissions of the file, if any. Also accepts a string representing the octal value : "644", "755", etc. On nodejs you can use the mode attribute of nodejs' fs.Stats. */ unixPermissions: number | string; /** * The DOS permissions of the file, if any. */ dosPermissions: number; /** * the options of the file. */ options: { /** * @deprecated */ base64: boolean; /** * @deprecated */ binary: boolean; /** * @deprecated use File.dir */ dir: boolean; /** * @deprecated use File.date */ date: Date; compression: Compression; }; /** * the content as an unicode string. */ asText(): string; /** * the content as binary string. */ asBinary(): string; /** * need a compatible browser. https://github.com/open-xml-templating/pizzip/blob/master/documentation/api_pizzip/support.md */ asArrayBuffer(): ArrayBuffer; /** * need a compatible browser. https://github.com/open-xml-templating/pizzip/blob/master/documentation/api_pizzip/support.md */ asUint8Array(): Uint8Array; /** * need nodejs. https://github.com/open-xml-templating/pizzip/blob/master/documentation/api_pizzip/support.md */ asNodeBuffer(): Buffer; } interface LoadOptions { /** * set to true if the data is base64 encoded, false for binary. * * @default false */ base64?: boolean | undefined; /** * set to true if the read data should be checked against its CRC32. * * @default false */ checkCRC32?: boolean | undefined; /** * set to true if (and only if) the input is a string and has already been prepared with a 0xFF mask. * * @default false */ optimizedBinaryString?: boolean | undefined; /** * set to true to create folders in the file path automatically. Leaving it false will result in only virtual folders * (i.e. folders that merely represent part of the file path) being created. * * @default false */ createFolders?: boolean | undefined; /** * the function to decode the file name / comment. Decodes from UTF-8 by default. * A zip file has a flag to say if the filename and comment are encoded with UTF-8. * If it's not set, PizZip has no way to know the encoding used. It usually is the default encoding of the operating system. * The function takes the bytes array (Uint8Array or Array) and returns the decoded string. */ decodeFileName?(bytes: Uint8Array | number[]): string; } interface FileOptions { /** * set to `true` if the data is base64 encoded. For example image data from a `<canvas>` element. Plain text and HTML do not need this option. * @default false */ base64?: boolean | undefined; /** * set to `true` if the data should be treated as raw content, `false` if this is a text. If base64 is used, this defaults to `true`, * if the data is not a string, this will be set to `true`. * @default false */ binary?: boolean | undefined; /** * the last modification date. defaults to the current date */ date?: Date | undefined; /** * If set, specifies compression method to use for this specific file. If not, the default file compression will be used (no compression) * @default "STORE" */ compression?: Compression | undefined; /** * With `STORE` (no compression), this parameter is ignored. * With `DEFLATE`, you can give the compression level with `compressionOptions : {level:6}` (or any level between 1 (best speed) and 9 (best compression)). */ compressionOptions?: { level: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; } | null | undefined; /** * The comment for this file. * the zip format has no flag or field to give the encoding of this field and PizZip will use UTF-8. * With non ASCII characters you might get encoding issues if the file archiver doesn't use UTF-8 to decode the comment. * If not set, PizZip will use the field comment on its options. * @default null */ comment?: string | null | undefined; /** * Set to true if (and only if) the input is a "binary string" and has already been prepared with a 0xFF mask. * @default false */ optimizedBinaryString?: boolean | undefined; /** * Set to true if folders in the file path should be automatically created, * otherwise there will only be virtual folders that represent the path to the file. * @default false */ createFolders?: boolean | undefined; /** * The UNIX permissions of the file, if any. Also accepts a string representing the octal value : "644", "755", etc. * On nodejs you can use the `mode` attribute of nodejs' fs.Stats. * @default null */ unixPermissions?: number | string | null | undefined; /** * The DOS permissions of the file, if any. * @default null */ dosPermissions?: number | null | undefined; /** * Set to true if this is a directory and content should be ignored. * If true or if a permission says it's a folder, this entry be flagged as a folder and the content will be ignored. * @default false */ dir?: boolean | undefined; } interface GenerateOptions { /** * @deprecated use `type` instead. If `type` is not used, set to `false` to get the result as a raw byte string, `true` to encode it as base64. * @default false */ base64?: boolean | undefined; /** * the default file compression method to use. Available methods are `STORE` and `DEFLATE`. You can also provide your own compression method. * @default "STORE" */ compression?: Compression | undefined; /** * the options to use when compressing the file. With `STORE` (no compression), this parameter is ignored. * With `DEFLATE`, you can give the compression level with `compressionOptions : {level:6}` * (or any level between 1 (best speed) and 9 (best compression)). * * Note : if the entry is already compressed (coming from a compressed zip file), * calling `generate()` with a different compression level won't update the entry. * The reason is simple : PizZip doesn't know how compressed the content was and how to match the compression level with the implementation we use. */ compressionOptions?: { level: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; } | null | undefined; /** * The type of zip to return. Note : when using type = "uint8array", "arraybuffer" or "blob", * be sure to check if the browser supports it (you can use PizZip.support) * * `base64` : the result will be a string, the binary in a base64 form. * * `string` : the result will be a string in "binary" form, using 1 byte per char (2 bytes). * * `uint8array` : the result will be a Uint8Array containing the zip. This requires a compatible browser. * * `arraybuffer` : the result will be a ArrayBuffer containing the zip. This requires a compatible browser. * * `blob` : the result will be a Blob containing the zip. This requires a compatible browser. * * `nodebuffer` : the result will be a nodejs Buffer containing the zip. This requires nodejs. * * @default "base64" */ type?: 'base64' | 'string' | 'uint8array' | 'arraybuffer' | 'blob' | 'nodebuffer' | undefined; /** * The comment to use for the zip file. */ comment?: string | undefined; /** * mime-type for the generated file. Useful when you need to generate a file with a different extension, ie: ".ods". * * @default "application/zip" */ mimeType?: string | undefined; /** * The platform to use when generating the zip file. When using `DOS`, the attribute `dosPermissions` of each file is used. * When using `UNIX`, the attribute `unixPermissions` of each file is used. * If you set the platform value on nodejs, be sure to use `process.platform`. * `fs.stats` returns a non executable mode for folders on windows, * if you force the platform to `UNIX` the generated zip file will have a strange behavior on UNIX platforms. * @default "DOS" */ platform?: 'DOS' | 'UNIX' | NodeJS.Platform | undefined; /** * the function to encode the file name / comment. * By default, PizZip uses UTF-8 to encode the file names / comments. You can use this method to force an other encoding. * Note : the encoding used is not stored in a zip file, not using UTF-8 may lead to encoding issues. * The function takes a string and returns a bytes array (Uint8Array or Array). */ encodeFileName?(name: string): Buffer; } }
the_stack
import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; import * as cloudwatch from "../cloudwatch"; import { LoadBalancer } from "./loadBalancer"; import { TargetGroup } from "./targetGroup"; import { ApplicationLoadBalancer, ApplicationTargetGroup } from "./application"; import { NetworkLoadBalancer, NetworkTargetGroup } from "./network"; export namespace metrics { interface CoreMetricChange extends cloudwatch.MetricChange { /** * Filters the metric data by load balancer. */ loadBalancer?: aws.lb.LoadBalancer | LoadBalancer; /** * Filters the metric data by target group. If this is a [NetworkTargetGroup] then * [loadBalancer] does not have to be provided. If this is an * [aws.lb.TargetGroup] then [loadBalancer] must be provided. */ targetGroup?: aws.lb.TargetGroup | TargetGroup; /** * Filters the metric data by Availability Zone. */ availabilityZone?: string; } function createDimensions(change: CoreMetricChange = {}) { const dimensions: Record<string, pulumi.Input<string>> = {}; if (change.loadBalancer !== undefined) { if (change.loadBalancer instanceof LoadBalancer) { dimensions.LoadBalancer = change.loadBalancer.loadBalancer.arnSuffix; } else { dimensions.LoadBalancer = change.loadBalancer.arnSuffix; } } if (change.targetGroup !== undefined) { if (change.targetGroup instanceof TargetGroup) { dimensions.TargetGroup = change.targetGroup.targetGroup.arnSuffix; dimensions.LoadBalancer = change.targetGroup.loadBalancer.loadBalancer.arnSuffix; } else { if (!change.loadBalancer) { throw new Error("[change.loadBalancer] must be provided if [change.targetGroup] is an [aws.lb.TargetGroup]"); } dimensions.TargetGroup = change.targetGroup.arnSuffix; } } if (change.availabilityZone !== undefined) { dimensions.AvailabilityZone = change.availabilityZone; } return dimensions; } export namespace application { type ApplicationMetricName = "ActiveConnectionCount" | "ClientTLSNegotiationErrorCount" | "ConsumedLCUs" | "HTTP_Fixed_Response_Count" | "HTTP_Redirect_Count" | "HTTP_Redirect_Url_Limit_Exceeded_Count" | "HTTPCode_ELB_3XX_Count" | "HTTPCode_ELB_4XX_Count" | "HTTPCode_ELB_5XX_Count" | "HTTPCode_ELB_500_Count" | "HTTPCode_ELB_502_Count" | "HTTPCode_ELB_503_Count" | "HTTPCode_ELB_504_Count" | "IPv6ProcessedBytes" | "IPv6RequestCount" | "NewConnectionCount" | "ProcessedBytes" | "RejectedConnectionCount" | "RequestCount" | "RuleEvaluations" | // Target group metrics "HealthyHostCount" | "HTTPCode_Target_2XX_Count" | "HTTPCode_Target_3XX_Count" | "HTTPCode_Target_4XX_Count" | "HTTPCode_Target_5XX_Count" | "NonStickyRequestCount" | "RequestCountPerTarget" | "TargetConnectionErrorCount" | "TargetResponseTime" | "TargetTLSNegotiationErrorCount" | "UnHealthyHostCount"; export interface ElasticLoadBalancingV2MetricChange extends cloudwatch.MetricChange { /** * Filters the metric data by load balancer. */ loadBalancer?: aws.lb.LoadBalancer | ApplicationLoadBalancer; /** * Filters the metric data by target group. If this is an [ApplicationTargetGroup] then * [loadBalancer] does not have to be provided. If this is an * [aws.lb.TargetGroup] then [loadBalancer] must be provided. */ targetGroup?: aws.lb.TargetGroup | ApplicationTargetGroup; /** * Filters the metric data by Availability Zone. */ availabilityZone?: string; } /** * Creates an AWS/ApplicationELB metric with the requested [metricName]. See * https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html * for list of all metric-names. * * Elastic Load Balancing publishes data points to Amazon CloudWatch for your load balancers * and your targets. CloudWatch enables you to retrieve statistics about those data points * as an ordered set of time-series data, known as metrics. Think of a metric as a variable * to monitor, and the data points as the values of that variable over time. For example, * you can monitor the total number of healthy targets for a load balancer over a specified * time period. Each data point has an associated time stamp and an optional unit of * measurement. * * You can use metrics to verify that your system is performing as expected. For example, * you can create a CloudWatch alarm to monitor a specified metric and initiate an action * (such as sending a notification to an email address) if the metric goes outside what you * consider an acceptable range. * * Elastic Load Balancing reports metrics to CloudWatch only when requests are flowing * through the load balancer. If there are requests flowing through the load balancer, * Elastic Load Balancing measures and sends its metrics in 60-second intervals. If there * are no requests flowing through the load balancer or no data for a metric, the metric is * not reported. * * To filter the metrics for your Application Load Balancer, use the following dimensions. * 1. "AvailabilityZone": Filters the metric data by Availability Zone. * 2. "LoadBalancer": Filters the metric data by load balancer. Specify the load balancer * using `LoadBalancer.arnSuffix`. * 3. "TargetGroup": Filters the metric data by target group. Specify the target group using * `TargetGroup.arnSuffix`. */ function metric(metricName: ApplicationMetricName, change: ElasticLoadBalancingV2MetricChange = {}) { const dimensions = createDimensions(change); return new cloudwatch.Metric({ namespace: "AWS/ApplicationELB", name: metricName, ...change, }).withDimensions(dimensions); } /** * The total number of concurrent TCP connections active from clients to the load balancer * and from the load balancer to targets. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions LoadBalancer */ export function activeConnectionCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("ActiveConnectionCount", { statistic: "Sum", ...change }); } /** * The number of TLS connections initiated by the client that did not establish a session * with the load balancer. Possible causes include a mismatch of ciphers or protocols. * Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: AvailabilityZone, LoadBalancer */ export function clientTLSNegotiationErrorCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("ClientTLSNegotiationErrorCount", { statistic: "Sum", ...change }); } /** * The number of load balancer capacity units (LCU) used by your load balancer. You pay for * the number of LCUs that you use per hour. For more information, see Elastic Load * Balancing Pricing. Reporting criteria: Always reported * * Statistics: All * * Dimensions: LoadBalancer */ export function consumedLCUs(change?: ElasticLoadBalancingV2MetricChange) { return metric("ConsumedLCUs", { ...change }); } /** * The number of fixed-response actions that were successful. Reporting criteria: There is a * nonzero value * * Statistics: The only meaningful statistic is Sum. * * Dimensions: LoadBalancer */ export function httpFixedResponseCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTP_Fixed_Response_Count", { statistic: "Sum", ...change }); } /** * The number of redirect actions that were successful. Reporting criteria: There is a * nonzero value * * Statistics: The only meaningful statistic is Sum. * * Dimensions: LoadBalancer */ export function httpRedirectCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTP_Redirect_Count", { statistic: "Sum", ...change }); } /** * The number of redirect actions that couldn't be completed because the URL in the response * location header is larger than 8K. Reporting criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. * * Dimensions: LoadBalancer */ export function httpRedirectUrlLimitExceededCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTP_Redirect_Url_Limit_Exceeded_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 3XX redirection codes that originate from the load balancer. Reporting * criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. * * Dimensions: LoadBalancer */ export function httpCodeELB3XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_3XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 4XX client error codes that originate from the load balancer. Client * errors are generated when requests are malformed or incomplete. These requests have not * been received by the target. This count does not include any response codes generated by * the targets. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer */ export function httpCodeELB4XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_4XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 5XX server error codes that originate from the load balancer. This * count does not include any response codes generated by the targets. Reporting criteria: * There is a nonzero value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer */ export function httpCodeELB5XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_5XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 500 error codes that originate from the load balancer. * * Reporting criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. */ export function httpCodeELB500Count(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_500_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 502 error codes that originate from the load balancer. Reporting * criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. */ export function httpCodeELB502Count(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_502_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 503 error codes that originate from the load balancer. Reporting * criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. */ export function httpCodeELB503Count(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_503_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP 504 error codes that originate from the load balancer. Reporting * criteria: There is a nonzero value * * Statistics: The only meaningful statistic is Sum. */ export function httpCodeELB504Count(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_ELB_504_Count", { statistic: "Sum", ...change }); } /** * The total number of bytes processed by the load balancer over IPv6. Reporting criteria: * There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer */ export function ipv6ProcessedBytes(change?: ElasticLoadBalancingV2MetricChange) { return metric("IPv6ProcessedBytes", { statistic: "Sum", ...change }); } /** * The number of IPv6 requests received by the load balancer. Reporting criteria: There is a * nonzero value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function ipv6RequestCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("IPv6RequestCount", { statistic: "Sum", ...change }); } /** * The total number of new TCP connections established from clients to the load balancer and * from the load balancer to targets. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer */ export function newConnectionCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("NewConnectionCount", { statistic: "Sum", ...change }); } /** * The total number of bytes processed by the load balancer over IPv4 and IPv6. Reporting * criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer */ export function processedBytes(change?: ElasticLoadBalancingV2MetricChange) { return metric("ProcessedBytes", { statistic: "Sum", ...change }); } /** * The number of connections that were rejected because the load balancer had reached its * maximum number of connections. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer */ export function rejectedConnectionCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("RejectedConnectionCount", { statistic: "Sum", ...change }); } /** * The number of requests processed over IPv4 and IPv6. This count includes only the * requests with a response generated by a target of the load balancer. Reporting criteria: * Always reported * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function requestCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("RequestCount", { statistic: "Sum", ...change }); } /** * The number of rules processed by the load balancer given a request rate averaged over an * hour. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer */ export function ruleEvaluations(change?: ElasticLoadBalancingV2MetricChange) { return metric("RuleEvaluations", { statistic: "Sum", ...change }); } /** * The number of targets that are considered healthy. Reporting criteria: Reported if health * checks are enabled * * Statistics: The most useful statistics are Average, Minimum, and Maximum. * * Dimensions: TargetGroup, LoadBalancer TargetGroup, AvailabilityZone, * LoadBalancer */ export function healthyHostCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HealthyHostCount", { ...change }); } /** * The number of HTTP response codes generated by the targets. This does not include any * response codes generated by the load balancer. Reporting criteria: There is a nonzero * value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function httpCodeTarget2XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_Target_2XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP response codes generated by the targets. This does not include any * response codes generated by the load balancer. Reporting criteria: There is a nonzero * value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function httpCodeTarget3XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_Target_3XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP response codes generated by the targets. This does not include any * response codes generated by the load balancer. Reporting criteria: There is a nonzero * value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function httpCodeTarget4XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_Target_4XX_Count", { statistic: "Sum", ...change }); } /** * The number of HTTP response codes generated by the targets. This does not include any * response codes generated by the load balancer. Reporting criteria: There is a nonzero * value * * Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, and Average all * return 1. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function httpCodeTarget5XXCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HTTPCode_Target_5XX_Count", { statistic: "Sum", ...change }); } /** * The number of requests where the load balancer chose a new target because it couldn't use * an existing sticky session. For example, the request was the first request from a new * client and no stickiness cookie was presented, a stickiness cookie was presented but it * did not specify a target that was registered with this target group, the stickiness * cookie was malformed or expired, or an internal error prevented the load balancer from * reading the stickiness cookie. Reporting criteria: Stickiness is enabled on the target * group. * * Statistics: The only meaningful statistic is Sum. */ export function nonStickyRequestCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("NonStickyRequestCount", { statistic: "Sum", ...change }); } /** * The average number of requests received by each target in a target group. You must * specify the target group using the TargetGroup dimension. This metric does not apply if * the target is a Lambda function. Reporting criteria: Always reported * * Statistics: The only valid statistic is Sum. Note that this represents the average not * the sum. * * Dimensions: TargetGroup TargetGroup, LoadBalancer */ export function requestCountPerTarget(change?: ElasticLoadBalancingV2MetricChange) { return metric("RequestCountPerTarget", { statistic: "Sum", ...change }); } /** * The number of connections that were not successfully established between the load * balancer and target. This metric does not apply if the target is a Lambda function. * Reporting criteria: There is a nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function targetConnectionErrorCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TargetConnectionErrorCount", { statistic: "Sum", ...change }); } /** * The time elapsed, in seconds, after the request leaves the load balancer until a response * from the target is received. This is equivalent to the target_processing_time field in * the access logs. Reporting criteria: There is a nonzero value * * Statistics: The most useful statistics are Average and pNN.NN (percentiles). * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function targetResponseTime(change?: ElasticLoadBalancingV2MetricChange) { return metric("TargetResponseTime", { ...change }); } /** * The number of TLS connections initiated by the load balancer that did not establish a * session with the target. Possible causes include a mismatch of ciphers or protocols. This * metric does not apply if the target is a Lambda function. Reporting criteria: There is a * nonzero value * * Statistics: The most useful statistic is Sum. * * Dimensions: LoadBalancer AvailabilityZone, LoadBalancer TargetGroup, LoadBalancer * TargetGroup, AvailabilityZone, LoadBalancer */ export function targetTLSNegotiationErrorCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TargetTLSNegotiationErrorCount", { statistic: "Sum", ...change }); } /** * The number of targets that are considered unhealthy. Reporting criteria: Reported if * health checks are enabled * * Statistics: The most useful statistics are Average, Minimum, and Maximum. * * Dimensions: TargetGroup, LoadBalancer TargetGroup, AvailabilityZone, LoadBalancer */ export function unHealthyHostCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("UnHealthyHostCount", { ...change }); } } export namespace network { type NetworkMetricName = "ActiveFlowCount" | "ActiveFlowCount_TLS" | "ClientTLSNegotiationErrorCount" | "ConsumedLCUs" | "HealthyHostCount" | "NewFlowCount" | "NewFlowCount_TLS" | "ProcessedBytes" | "ProcessedBytes_TLS" | "TargetTLSNegotiationErrorCount" | "TCP_Client_Reset_Count" | "TCP_ELB_Reset_Count" | "TCP_Target_Reset_Count" | "UnHealthyHostCount"; export interface ElasticLoadBalancingV2MetricChange extends cloudwatch.MetricChange { /** * Filters the metric data by load balancer. */ loadBalancer?: aws.lb.LoadBalancer | NetworkLoadBalancer; /** * Filters the metric data by target group. If this is a [NetworkTargetGroup] then * [loadBalancer] does not have to be provided. If this is an * [aws.lb.TargetGroup] then [loadBalancer] must be provided. */ targetGroup?: aws.lb.TargetGroup | NetworkTargetGroup; /** * Filters the metric data by Availability Zone. */ availabilityZone?: string; } /** * Creates an AWS/NetworkELB metric with the requested [metricName]. See * https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-cloudwatch-metrics.html * for list of all metric-names. * * Elastic Load Balancing publishes data points to Amazon CloudWatch for your load balancers * and your targets. CloudWatch enables you to retrieve statistics about those data points * as an ordered set of time-series data, known as metrics. Think of a metric as a variable * to monitor, and the data points as the values of that variable over time. For example, * you can monitor the total number of healthy targets for a load balancer over a specified * time period. Each data point has an associated time stamp and an optional unit of * measurement. * * You can use metrics to verify that your system is performing as expected. For example, * you can create a CloudWatch alarm to monitor a specified metric and initiate an action * (such as sending a notification to an email address) if the metric goes outside what you * consider an acceptable range. * * Elastic Load Balancing reports metrics to CloudWatch only when requests are flowing * through the load balancer. If there are requests flowing through the load balancer, * Elastic Load Balancing measures and sends its metrics in 60-second intervals. If there * are no requests flowing through the load balancer or no data for a metric, the metric is * not reported. * * To filter the metrics for your Application Load Balancer, use the following dimensions. * 1. "AvailabilityZone": Filters the metric data by Availability Zone. * 2. "LoadBalancer": Filters the metric data by load balancer. Specify the load balancer * using `LoadBalancer.arnSuffix`. * 3. "TargetGroup": Filters the metric data by target group. Specify the target group using * `TargetGroup.arnSuffix`. */ function metric(metricName: NetworkMetricName, change: ElasticLoadBalancingV2MetricChange = {}) { const dimensions = createDimensions(change); return new cloudwatch.Metric({ namespace: "AWS/NetworkELB ", name: metricName, ...change, }).withDimensions(dimensions); } /** * The total number of concurrent flows (or connections) from clients to targets. This * metric includes connections in the SYN_SENT and ESTABLISHED states. TCP connections are * not terminated at the load balancer, so a client opening a TCP connection to a target * counts as a single flow. * * Statistics: The most useful statistics are Average, Maximum, and Minimum. */ export function activeFlowCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("ActiveFlowCount", { ...change }); } /** * The total number of concurrent TLS flows (or connections) from clients to targets. This * metric includes only connections in the ESTABLISHED states. * * Statistics: The most useful statistics are Average, Maximum, and Minimum. */ export function activeFlowCount_TLS(change?: ElasticLoadBalancingV2MetricChange) { return metric("ActiveFlowCount_TLS", { ...change }); } /** * The total number of TLS handshakes that failed during negotiation between a client and a * TLS listener. * * Statistics: The most useful statistic is Sum. */ export function clientTLSNegotiationErrorCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("ClientTLSNegotiationErrorCount", { statistic: "Sum", ...change }); } /** * The number of load balancer capacity units (LCU) used by your load balancer. You pay for * the number of LCUs that you use per hour. For more information, see Elastic Load * Balancing Pricing. */ export function consumedLCUs(change?: ElasticLoadBalancingV2MetricChange) { return metric("ConsumedLCUs", { ...change }); } /** * The number of targets that are considered healthy. * * Statistics: The most useful statistics are Maximum and Minimum. */ export function healthyHostCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("HealthyHostCount", { statistic: "Maximum", ...change }); } /** * The total number of new flows (or connections) established from clients to targets in the * time period. * * Statistics: The most useful statistic is Sum. */ export function newFlowCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("NewFlowCount", { statistic: "Sum", ...change }); } /** * The total number of new TLS flows (or connections) established from clients to targets in * the time period. * * Statistics: The most useful statistic is Sum. */ export function newFlowCountTLS(change?: ElasticLoadBalancingV2MetricChange) { return metric("NewFlowCount_TLS", { statistic: "Sum", ...change }); } /** * The total number of bytes processed by the load balancer, including TCP/IP headers. * * Statistics: The most useful statistic is Sum. */ export function processedBytes(change?: ElasticLoadBalancingV2MetricChange) { return metric("ProcessedBytes", { statistic: "Sum", ...change }); } /** * The total number of bytes processed by TLS listeners. * * Statistics: The most useful statistic is Sum. */ export function processedBytesTLS(change?: ElasticLoadBalancingV2MetricChange) { return metric("ProcessedBytes_TLS", { statistic: "Sum", ...change }); } /** * The total number of TLS handshakes that failed during negotiation between a TLS listener * and a target. * * Statistics: The most useful statistic is Sum. */ export function targetTLSNegotiationErrorCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TargetTLSNegotiationErrorCount", { statistic: "Sum", ...change }); } /** * The total number of reset (RST) packets sent from a client to a target. These resets are * generated by the client and forwarded by the load balancer. * * Statistics: The most useful statistic is Sum. */ export function tcpClientResetCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TCP_Client_Reset_Count", { statistic: "Sum", ...change }); } /** * The total number of reset (RST) packets generated by the load balancer. * * Statistics: The most useful statistic is Sum. */ export function tcpELBResetCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TCP_ELB_Reset_Count", { statistic: "Sum", ...change }); } /** * The total number of reset (RST) packets sent from a target to a client. These resets are * generated by the target and forwarded by the load balancer. * * Statistics: The most useful statistic is Sum. */ export function tcpTargetResetCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("TCP_Target_Reset_Count", { statistic: "Sum", ...change }); } /** * The number of targets that are considered unhealthy. * * Statistics: The most useful statistics are Maximum and Minimum. */ export function unhealthyHostCount(change?: ElasticLoadBalancingV2MetricChange) { return metric("UnHealthyHostCount", { statistic: "Maximum", ...change }); } } }
the_stack
import * as nls from 'vs/nls'; import * as lifecycle from 'vs/base/common/lifecycle'; import { KeyCode } from 'vs/base/common/keyCodes'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import * as dom from 'vs/base/browser/dom'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ConfigurationChangedEvent, EditorOption } from 'vs/editor/common/config/editorOptions'; import { Position } from 'vs/editor/common/core/position'; import { Range, IRange } from 'vs/editor/common/core/range'; import { IContentWidget, ICodeEditor, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDebugService, IExpression, IExpressionContainer, IStackFrame } from 'vs/workbench/contrib/debug/common/debug'; import { Expression } from 'vs/workbench/contrib/debug/common/debugModel'; import { renderExpressionValue } from 'vs/workbench/contrib/debug/browser/baseDebugView'; import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { editorHoverBackground, editorHoverBorder, editorHoverForeground } from 'vs/platform/theme/common/colorRegistry'; import { ModelDecorationOptions } from 'vs/editor/common/model/textModel'; import { getExactExpressionStartAndEnd } from 'vs/workbench/contrib/debug/common/debugUtils'; import { AsyncDataTree } from 'vs/base/browser/ui/tree/asyncDataTree'; import { IListAccessibilityProvider } from 'vs/base/browser/ui/list/listWidget'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { WorkbenchAsyncDataTree } from 'vs/platform/list/browser/listService'; import { coalesce } from 'vs/base/common/arrays'; import { IAsyncDataSource } from 'vs/base/browser/ui/tree/tree'; import { VariablesRenderer } from 'vs/workbench/contrib/debug/browser/variablesView'; import { EvaluatableExpressionProviderRegistry } from 'vs/editor/common/modes'; import { CancellationTokenSource } from 'vs/base/common/cancellation'; import { isMacintosh } from 'vs/base/common/platform'; import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector'; const $ = dom.$; async function doFindExpression(container: IExpressionContainer, namesToFind: string[]): Promise<IExpression | null> { if (!container) { return Promise.resolve(null); } const children = await container.getChildren(); // look for our variable in the list. First find the parents of the hovered variable if there are any. const filtered = children.filter(v => namesToFind[0] === v.name); if (filtered.length !== 1) { return null; } if (namesToFind.length === 1) { return filtered[0]; } else { return doFindExpression(filtered[0], namesToFind.slice(1)); } } export async function findExpressionInStackFrame(stackFrame: IStackFrame, namesToFind: string[]): Promise<IExpression | undefined> { const scopes = await stackFrame.getScopes(); const nonExpensive = scopes.filter(s => !s.expensive); const expressions = coalesce(await Promise.all(nonExpensive.map(scope => doFindExpression(scope, namesToFind)))); // only show if all expressions found have the same value return expressions.length > 0 && expressions.every(e => e.value === expressions[0].value) ? expressions[0] : undefined; } export class DebugHoverWidget implements IContentWidget { static readonly ID = 'debug.hoverWidget'; // editor.IContentWidget.allowEditorOverflow allowEditorOverflow = true; private _isVisible: boolean; private showCancellationSource?: CancellationTokenSource; private domNode!: HTMLElement; private tree!: AsyncDataTree<IExpression, IExpression, any>; private showAtPosition: Position | null; private positionPreference: ContentWidgetPositionPreference[]; private highlightDecorations: string[]; private complexValueContainer!: HTMLElement; private complexValueTitle!: HTMLElement; private valueContainer!: HTMLElement; private treeContainer!: HTMLElement; private toDispose: lifecycle.IDisposable[]; private scrollbar!: DomScrollableElement; constructor( private editor: ICodeEditor, @IDebugService private readonly debugService: IDebugService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IThemeService private readonly themeService: IThemeService ) { this.toDispose = []; this._isVisible = false; this.showAtPosition = null; this.highlightDecorations = []; this.positionPreference = [ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW]; } private create(): void { this.domNode = $('.debug-hover-widget'); this.complexValueContainer = dom.append(this.domNode, $('.complex-value')); this.complexValueTitle = dom.append(this.complexValueContainer, $('.title')); this.treeContainer = dom.append(this.complexValueContainer, $('.debug-hover-tree')); this.treeContainer.setAttribute('role', 'tree'); const tip = dom.append(this.complexValueContainer, $('.tip')); tip.textContent = nls.localize({ key: 'quickTip', comment: ['"switch to editor language hover" means to show the programming language hover widget instead of the debug hover'] }, 'Hold {0} key to switch to editor language hover', isMacintosh ? 'Option' : 'Alt'); const dataSource = new DebugHoverDataSource(); const linkeDetector = this.instantiationService.createInstance(LinkDetector); this.tree = <WorkbenchAsyncDataTree<IExpression, IExpression, any>>this.instantiationService.createInstance(WorkbenchAsyncDataTree, 'DebugHover', this.treeContainer, new DebugHoverDelegate(), [this.instantiationService.createInstance(VariablesRenderer, linkeDetector)], dataSource, { accessibilityProvider: new DebugHoverAccessibilityProvider(), mouseSupport: false, horizontalScrolling: true, useShadows: false, keyboardNavigationLabelProvider: { getKeyboardNavigationLabel: (e: IExpression) => e.name }, filterOnType: false, simpleKeyboardNavigation: true, overrideStyles: { listBackground: editorHoverBackground } }); this.valueContainer = $('.value'); this.valueContainer.tabIndex = 0; this.valueContainer.setAttribute('role', 'tooltip'); this.scrollbar = new DomScrollableElement(this.valueContainer, { horizontal: ScrollbarVisibility.Hidden }); this.domNode.appendChild(this.scrollbar.getDomNode()); this.toDispose.push(this.scrollbar); this.editor.applyFontInfo(this.domNode); this.toDispose.push(attachStylerCallback(this.themeService, { editorHoverBackground, editorHoverBorder, editorHoverForeground }, colors => { if (colors.editorHoverBackground) { this.domNode.style.backgroundColor = colors.editorHoverBackground.toString(); } else { this.domNode.style.backgroundColor = ''; } if (colors.editorHoverBorder) { this.domNode.style.border = `1px solid ${colors.editorHoverBorder}`; } else { this.domNode.style.border = ''; } if (colors.editorHoverForeground) { this.domNode.style.color = colors.editorHoverForeground.toString(); } else { this.domNode.style.color = ''; } })); this.toDispose.push(this.tree.onDidChangeContentHeight(() => this.layoutTreeAndContainer(false))); this.registerListeners(); this.editor.addContentWidget(this); } private registerListeners(): void { this.toDispose.push(dom.addStandardDisposableListener(this.domNode, 'keydown', (e: IKeyboardEvent) => { if (e.equals(KeyCode.Escape)) { this.hide(); } })); this.toDispose.push(this.editor.onDidChangeConfiguration((e: ConfigurationChangedEvent) => { if (e.hasChanged(EditorOption.fontInfo)) { this.editor.applyFontInfo(this.domNode); } })); } isHovered(): boolean { return !!this.domNode?.matches(':hover'); } isVisible(): boolean { return this._isVisible; } willBeVisible(): boolean { return !!this.showCancellationSource; } getId(): string { return DebugHoverWidget.ID; } getDomNode(): HTMLElement { return this.domNode; } async showAt(range: Range, focus: boolean): Promise<void> { this.showCancellationSource?.cancel(); const cancellationSource = this.showCancellationSource = new CancellationTokenSource(); const session = this.debugService.getViewModel().focusedSession; if (!session || !this.editor.hasModel()) { return Promise.resolve(this.hide()); } const model = this.editor.getModel(); const pos = range.getStartPosition(); let rng: IRange | undefined = undefined; let matchingExpression: string | undefined; if (EvaluatableExpressionProviderRegistry.has(model)) { const supports = EvaluatableExpressionProviderRegistry.ordered(model); const promises = supports.map(support => { return Promise.resolve(support.provideEvaluatableExpression(model, pos, cancellationSource.token)).then(expression => { return expression; }, err => { //onUnexpectedExternalError(err); return undefined; }); }); const results = await Promise.all(promises).then(coalesce); if (results.length > 0) { matchingExpression = results[0].expression; rng = results[0].range; if (!matchingExpression) { const lineContent = model.getLineContent(pos.lineNumber); matchingExpression = lineContent.substring(rng.startColumn - 1, rng.endColumn - 1); } } } else { // old one-size-fits-all strategy const lineContent = model.getLineContent(pos.lineNumber); const { start, end } = getExactExpressionStartAndEnd(lineContent, range.startColumn, range.endColumn); // use regex to extract the sub-expression #9821 matchingExpression = lineContent.substring(start - 1, end); rng = new Range(pos.lineNumber, start, pos.lineNumber, start + matchingExpression.length); } if (!matchingExpression) { return Promise.resolve(this.hide()); } let expression; if (session.capabilities.supportsEvaluateForHovers) { expression = new Expression(matchingExpression); await expression.evaluate(session, this.debugService.getViewModel().focusedStackFrame, 'hover'); } else { const focusedStackFrame = this.debugService.getViewModel().focusedStackFrame; if (focusedStackFrame) { expression = await findExpressionInStackFrame(focusedStackFrame, coalesce(matchingExpression.split('.').map(word => word.trim()))); } } if (cancellationSource.token.isCancellationRequested || !expression || (expression instanceof Expression && !expression.available)) { this.hide(); return; } if (rng) { this.highlightDecorations = this.editor.deltaDecorations(this.highlightDecorations, [{ range: rng, options: DebugHoverWidget._HOVER_HIGHLIGHT_DECORATION_OPTIONS }]); } return this.doShow(pos, expression, focus); } private static readonly _HOVER_HIGHLIGHT_DECORATION_OPTIONS = ModelDecorationOptions.register({ description: 'bdebug-hover-highlight', className: 'hoverHighlight' }); private async doShow(position: Position, expression: IExpression, focus: boolean, forceValueHover = false): Promise<void> { if (!this.domNode) { this.create(); } this.showAtPosition = position; this._isVisible = true; if (!expression.hasChildren || forceValueHover) { this.complexValueContainer.hidden = true; this.valueContainer.hidden = false; renderExpressionValue(expression, this.valueContainer, { showChanged: false, colorize: true }); this.valueContainer.title = ''; this.editor.layoutContentWidget(this); this.scrollbar.scanDomNode(); if (focus) { this.editor.render(); this.valueContainer.focus(); } return Promise.resolve(undefined); } this.valueContainer.hidden = true; await this.tree.setInput(expression); this.complexValueTitle.textContent = expression.value; this.complexValueTitle.title = expression.value; this.layoutTreeAndContainer(true); this.tree.scrollTop = 0; this.tree.scrollLeft = 0; this.complexValueContainer.hidden = false; if (focus) { this.editor.render(); this.tree.domFocus(); } } private layoutTreeAndContainer(initialLayout: boolean): void { const scrollBarHeight = 10; const treeHeight = Math.min(Math.max(266, this.editor.getLayoutInfo().height * 0.55), this.tree.contentHeight + scrollBarHeight); this.treeContainer.style.height = `${treeHeight}px`; this.tree.layout(treeHeight, initialLayout ? 400 : undefined); this.editor.layoutContentWidget(this); this.scrollbar.scanDomNode(); } afterRender(positionPreference: ContentWidgetPositionPreference | null) { if (positionPreference) { // Remember where the editor placed you to keep position stable #109226 this.positionPreference = [positionPreference]; } } hide(): void { if (this.showCancellationSource) { this.showCancellationSource.cancel(); this.showCancellationSource = undefined; } if (!this._isVisible) { return; } if (dom.isAncestor(document.activeElement, this.domNode)) { this.editor.focus(); } this._isVisible = false; this.editor.deltaDecorations(this.highlightDecorations, []); this.highlightDecorations = []; this.editor.layoutContentWidget(this); this.positionPreference = [ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW]; } getPosition(): IContentWidgetPosition | null { return this._isVisible ? { position: this.showAtPosition, preference: this.positionPreference } : null; } dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } } class DebugHoverAccessibilityProvider implements IListAccessibilityProvider<IExpression> { getWidgetAriaLabel(): string { return nls.localize('treeAriaLabel', "Debug Hover"); } getAriaLabel(element: IExpression): string { return nls.localize({ key: 'variableAriaLabel', comment: ['Do not translate placeholders. Placeholders are name and value of a variable.'] }, "{0}, value {1}, variables, debug", element.name, element.value); } } class DebugHoverDataSource implements IAsyncDataSource<IExpression, IExpression> { hasChildren(element: IExpression): boolean { return element.hasChildren; } getChildren(element: IExpression): Promise<IExpression[]> { return element.getChildren(); } } class DebugHoverDelegate implements IListVirtualDelegate<IExpression> { getHeight(element: IExpression): number { return 18; } getTemplateId(element: IExpression): string { return VariablesRenderer.ID; } }
the_stack
import { IFormObj, FORM, IFAC1Parsed, IFAC1VertexEntry, IVTX1Vertex } from "./FORM"; import * as THREE from "three"; import { VertexNormalsHelper } from "three/examples/jsm/helpers/VertexNormalsHelper"; import { Face3, Geometry } from "three/examples/jsm/deprecated/Geometry"; import { invertColor } from "../utils/image"; import { $$hex, $$log } from "../utils/debug"; import { arrayBufferToDataURL } from "../utils/arrays"; import { degreesToRadians } from "../utils/number"; // Converts extracted FORM data into a Three.js scene. export class FormToThreeJs { public bgColor: number = 0x000000; public showTextures: boolean = true; public showWireframe: boolean = false; public showVertexNormals: boolean = false; public useFormCamera: boolean = false; private __threeResult: THREE.Object3D | undefined; private __promises: Promise<any>[] = []; createModel(form: IFormObj): Promise<THREE.Object3D> { const materials = this._parseMaterials(form); this.__threeResult = this._parseForm(form, materials); return new Promise((resolve) => { Promise.all(this.__promises).then(() => { this.__promises = []; resolve(this.__threeResult!); }); }); } _parseForm(form: IFormObj, materials: THREE.MeshBasicMaterial[]) { const childObjs = this._parseFormObj(form, materials, 0); if (childObjs.length !== 1) console.warn(`Expected 1 return object from _parseForm, got ${childObjs.length}`); return childObjs[0]; } _parseFormObj(form: IFormObj, materials: THREE.MeshBasicMaterial[], objIndex: number) { let objs = FORM.getByGlobalIndex(form, "OBJ1", objIndex); if (objs === null) { if (objIndex === 0) { // mp2 62/2 doesn't have 0 obj? objs = form.OBJ1[0].parsed.objects[0]; console.warn("Using first object rather than global index 0 object"); } if (!objs) throw new Error(`Attempted to get unavailable OBJ ${objIndex}`); } if (!Array.isArray(objs)) { objs = [objs]; } const newObjs = []; for (let o = 0; o < objs.length; o++) { const obj = objs[o]; if (obj.objType === 0x3D) { // Just references other objects, can transform them. const newObj = this._createObject3DFromOBJ1Entry(obj); for (let i = 0; i < obj.children.length; i++) { const childObjs = this._parseFormObj(form, materials, obj.children[i]); if (childObjs && childObjs.length) { childObjs.forEach(childObj => { newObj.add(childObj); }); } } newObjs.push(newObj); } else if (obj.objType === 0x10) { // References a SKL1, which will point back to other objects. const newObj = this._createObject3DFromOBJ1Entry(obj); const skl1GlobalIndex = obj.skeletonGlobalIndex; const sklObj = this._parseFormSkl(form, materials, skl1GlobalIndex); newObj.add(sklObj); newObjs.push(newObj); } else if (obj.objType === 0x3A) { const newObj = this._createObject3DFromOBJ1Entry(obj); const geometry = new Geometry(); for (let f = obj.faceIndex; f < obj.faceIndex + obj.faceCount; f++) { const face = form.FAC1[0].parsed.faces[f]; this._populateGeometryWithFace(form, geometry, face); } const bufferGeometry = geometry.toBufferGeometry(); // This is a hack - indexed geometry exports better with GLTFExporter currently. bufferGeometry.setIndex(geometry.vertices.map((_v, i) => i)); if (this.showTextures) { const textureMesh = new THREE.Mesh(bufferGeometry, materials); newObj.add(textureMesh); } if (this.showWireframe) { const wireframeMaterial = new THREE.LineBasicMaterial({ color: invertColor(this.bgColor), linewidth: this.showTextures ? 2 : 1 }); const wireframe = new THREE.LineSegments(new THREE.EdgesGeometry(bufferGeometry), wireframeMaterial); newObj.add(wireframe); } if (this.showVertexNormals) { const normalsHelper = new VertexNormalsHelper(new THREE.Mesh(bufferGeometry, materials), 8, 0x00FF00); newObj.add(normalsHelper); } newObjs.push(newObj); } // else if (obj.objType === 0x3E) { // if (isDebug()) { // const newObj = new THREE.Object3D(); // const geometry = new THREE.Geometry(); // geometry.vertices.push(new THREE.Vector3(0, 0, 0)); // const dotMaterial = new THREE.PointsMaterial( { color: 0xFF0000, size: 40 } ); // const dot = new THREE.Points( geometry, dotMaterial ); // newObj.add(dot); // newObjs.push(newObj); // } // } } return newObjs; } _createObject3DFromOBJ1Entry(obj: any) { const newObj = new THREE.Object3D(); // Name the nodes for animation - see MtnxToThreeJs if (obj.hasOwnProperty("globalIndex")) newObj.name = this._getObjNameFromId(obj.globalIndex); newObj.position.x = obj.posX; newObj.position.y = obj.posY; newObj.position.z = obj.posZ; newObj.rotation.x = degreesToRadians(obj.rotX); newObj.rotation.y = degreesToRadians(obj.rotY); newObj.rotation.z = degreesToRadians(obj.rotZ); newObj.rotation.order = "ZYX"; newObj.scale.x = obj.scaleX; newObj.scale.y = obj.scaleY; newObj.scale.z = obj.scaleZ; return newObj; } _getObjNameFromId(id: number) { return $$hex(id); } _parseFormSkl(form: IFormObj, materials: THREE.MeshBasicMaterial[], skl1GlobalIndex: number) { const sklMatch = FORM.getByGlobalIndex(form, "SKL1", skl1GlobalIndex); if (sklMatch === null || Array.isArray(sklMatch)) throw new Error("Unexpected SKL1 search result"); return this._parseFormSklNode(form, materials, sklMatch.skls, 0); } _parseFormSklNode(form: IFormObj, materials: THREE.MeshBasicMaterial[], skls: any, index: number) { const skl = skls[index]; const sklObj = this._createObject3DFromOBJ1Entry(skl); const objIndex = skl.objGlobalIndex; const childObjs = this._parseFormObj(form, materials, objIndex); if (childObjs && childObjs.length) { childObjs.forEach(childObj => { sklObj.add(childObj); }); } if (skl.isParentNode) { let currentChildIndex = index + 1; while (currentChildIndex) { const childSkl = skls[currentChildIndex]; const childSklObj = this._parseFormSklNode(form, materials, skls, currentChildIndex); sklObj.add(childSklObj); if (childSkl.nextSiblingRelativeIndex) { currentChildIndex += childSkl.nextSiblingRelativeIndex; } else { break; } } } return sklObj; } _populateGeometryWithFace(form: IFormObj, geometry: Geometry, face: IFAC1Parsed) { if (!face.vtxEntries.length) return; const scale = form.VTX1[0].parsed.scale; const vtxEntries = face.vtxEntries; let vtxIndices = []; for (let i = 0; i < 3; i++) { const vtxEntry = vtxEntries[i]; let vtx = form.VTX1[0].parsed.vertices[vtxEntry.vertexIndex]; vtxIndices.push(geometry.vertices.length); geometry.vertices.push(this._makeVertex(vtx, scale)); } if (vtxEntries.length === 4) { for (let i = 0; i < 4; i++) { if (i === 1) continue; // 0, 2, 3 const vtxEntry = vtxEntries[i]; let vtx = form.VTX1[0].parsed.vertices[vtxEntry.vertexIndex]; vtxIndices.push(geometry.vertices.length); geometry.vertices.push(this._makeVertex(vtx, scale)); } } if (vtxEntries.length === 3) { this._addFace(geometry, form, face, [vtxIndices[0], vtxIndices[1], vtxIndices[2]], [vtxEntries[0], vtxEntries[1], vtxEntries[2]] ); } else if (vtxEntries.length === 4) { this._addFace(geometry, form, face, [vtxIndices[0], vtxIndices[1], vtxIndices[2]], [vtxEntries[0], vtxEntries[1], vtxEntries[2]] ); this._addFace(geometry, form, face, [vtxIndices[3], vtxIndices[4], vtxIndices[5]], [vtxEntries[0], vtxEntries[2], vtxEntries[3]] ); } } _addFace(geometry: Geometry, form: IFormObj, face: IFAC1Parsed, indices: number[], vtxEntries: IFAC1VertexEntry[]) { const tri = new Face3(indices[0], indices[1], indices[2]); tri.vertexNormals = this._makeVertexNormals(form, vtxEntries[0].vertexIndex, vtxEntries[1].vertexIndex, vtxEntries[2].vertexIndex); tri.materialIndex = this._getMaterialIndex(face)!; tri.color = new THREE.Color(this._getColorBytes(form, face)); tri.vertexColors = this._makeVertexColors(form, face, vtxEntries[0], vtxEntries[1], vtxEntries[2]); geometry.faceVertexUvs[0].push(this._makeVertexUVs(vtxEntries[0], vtxEntries[1], vtxEntries[2])); geometry.faces.push(tri); } _parseMaterials(form: IFormObj): THREE.MeshBasicMaterial[] { const materials = [ new THREE.MeshBasicMaterial({ vertexColors: true }), new THREE.MeshBasicMaterial({ vertexColors: true }), ]; if (form.BMP1) { if (form.ATR1 && form.ATR1[0]) { const atrs = form.ATR1[0].parsed.atrs; for (let i = 0; i < atrs.length; i++) { const atr = atrs[i]; const bmp = FORM.getByGlobalIndex(form, "BMP1", atr.bmpGlobalIndex); if (bmp === null || Array.isArray(bmp)) { console.warn("Unexpected bitmap result from global index lookup"); continue; } const textureMaterial = this._createTextureMaterial(atr, bmp); materials.push(textureMaterial); } } else { console.warn("BMPs, but no ATRs"); } } return materials; } _createTextureMaterial(atr: any, bmp: any) { const dataUri = arrayBufferToDataURL(bmp.src, bmp.width, bmp.height); $$log("Texture", dataUri); const loader = new THREE.TextureLoader(); loader.crossOrigin = ""; let texture: any; const texturePromise = new Promise((resolve) => { texture = loader.load(dataUri, resolve); texture.flipY = false; texture.wrapS = this._getWrappingBehavior(atr.xBehavior); texture.wrapT = this._getWrappingBehavior(atr.yBehavior); }); this.__promises.push(texturePromise); return new THREE.MeshBasicMaterial({ alphaTest: 0.5, map: texture, //transparent: true, vertexColors: true, }); } _getWrappingBehavior(behavior: THREE.Wrapping) { switch (behavior) { case 0x2C: return THREE.MirroredRepeatWrapping; case 0x2D: return THREE.RepeatWrapping; case 0x2E: return THREE.ClampToEdgeWrapping; // default default: console.warn(`Unknown behavior ${$$hex(behavior)}`); return THREE.ClampToEdgeWrapping; // default } } _makeVertex(vtx: IVTX1Vertex, scale: number) { return new THREE.Vector3( (vtx.x * scale), (vtx.y * scale), (vtx.z * scale) ); } _makeVertexNormals(form: IFormObj, vtxIndex1: number, vtxIndex2: number, vtxIndex3: number) { return [ this._makeVertexNormal(form, vtxIndex1), this._makeVertexNormal(form, vtxIndex2), this._makeVertexNormal(form, vtxIndex3), ]; } _makeVertexNormal(form: IFormObj, vtxIndex: number) { const vtx = form.VTX1[0].parsed.vertices[vtxIndex]; const normalVector = new THREE.Vector3( (vtx.normalX) / (127 + (vtx.normalX < 0 ? 1 : 0)), (vtx.normalY) / (127 + (vtx.normalY < 0 ? 1 : 0)), (vtx.normalZ) / (127 + (vtx.normalZ < 0 ? 1 : 0)), ); normalVector.normalize(); return normalVector; } _makeVertexUVs(vtxEntry1: IFAC1VertexEntry, vtxEntry2: IFAC1VertexEntry, vtxEntry3: IFAC1VertexEntry) { return [ this._makeVertexUV(vtxEntry1), this._makeVertexUV(vtxEntry2), this._makeVertexUV(vtxEntry3), ]; } _makeVertexUV(vtxEntry: IFAC1VertexEntry) { return new THREE.Vector2(vtxEntry.u, vtxEntry.v); } _getMaterialIndex(face: IFAC1Parsed) { if (face.atrIndex >= 0 || face.mystery3 === 0x36) { // Face colors, or maybe bitmap // If it is 0xFFFF (-1) -> THREE.FaceColors material // If greater, it'll be a bitmap material return face.atrIndex + 2; } else if (face.mystery3 === 0x37) { // Vertex colors? return 0; // Vertex colors } } _getColorBytes(form: IFormObj, face: IFAC1Parsed) { if (face.mystery3 === 0x36) { const materialIndex = face.materialIndex; return this._getColorFromMaterial(form, materialIndex); } else if (face.mystery3 === 0x37) { // Vertex colors? return 0xFFFC00; // Puke green, shouldn't see this } console.warn("Could not determine color for face"); } _getColorFromMaterial(form: IFormObj, materialIndex: number) { let colorIndex; if (form.MAT1 && form.MAT1[0] && form.MAT1[0].parsed) { colorIndex = form.MAT1[0].parsed.materials[materialIndex].colorIndex; if (form.COL1 && form.COL1[0] && form.COL1[0].parsed) { if (form.COL1[0].parsed.hasOwnProperty(colorIndex)) return form.COL1[0].parsed[colorIndex] >>> 8; } } console.warn(`Could not find color ${colorIndex} specified by material ${materialIndex}`); return 0xFFFC00; // Puke green } _makeVertexColors(form: IFormObj, face: IFAC1Parsed, vtxEntry1: IFAC1VertexEntry, vtxEntry2: IFAC1VertexEntry, vtxEntry3: IFAC1VertexEntry) { if (face.mystery3 !== 0x37) return []; return [ this._makeVertexColor(form, vtxEntry1)!, this._makeVertexColor(form, vtxEntry2)!, this._makeVertexColor(form, vtxEntry3)!, ]; } _makeVertexColor(form: IFormObj, vtxEntry: IFAC1VertexEntry) { if (vtxEntry.materialIndex < 0) return null; return new THREE.Color(this._getColorFromMaterial(form, vtxEntry.materialIndex)); } createCamera(form: IFormObj, width: number, height: number) { const camera = new THREE.PerspectiveCamera(75, width / height, 1, 999999); if (this.useFormCamera) { const cameraObjs = FORM.getObjectsByType(form, 0x61); if (cameraObjs.length === 3) { const cameraEyeObj = cameraObjs[0]; const cameraInterestObj = cameraObjs[1]; camera.position.set( cameraEyeObj.posX, cameraEyeObj.posY, cameraEyeObj.posZ ); camera.lookAt(new THREE.Vector3( cameraInterestObj.posX, cameraInterestObj.posY, cameraInterestObj.posZ) ); return camera; } else { console.warn(`Unexpected camera object count: ${cameraObjs.length}`); } } camera.position.z = 500; return camera; } }
the_stack
import { promisify } from 'util' import { promises as fs, statSync } from 'fs' import path from 'path' import { getFilePathInCafs, PackageFilesIndex } from '@pnpm/cafs' import createClient from '@pnpm/client' import { streamParser } from '@pnpm/logger' import createPackageRequester, { PackageFilesResponse, PackageResponse } from '@pnpm/package-requester' import { createCafsStore } from '@pnpm/package-store' import { REGISTRY_MOCK_PORT } from '@pnpm/registry-mock' import { DependencyManifest } from '@pnpm/types' import delay from 'delay' import { depPathToFilename } from 'dependency-path' import loadJsonFile from 'load-json-file' import ncpCB from 'ncp' import nock from 'nock' import normalize from 'normalize-path' import tempy from 'tempy' const registry = `http://localhost:${REGISTRY_MOCK_PORT}` const IS_POSTIVE_TARBALL = path.join(__dirname, 'is-positive-1.0.0.tgz') const ncp = promisify(ncpCB as any) // eslint-disable-line @typescript-eslint/no-explicit-any const authConfig = { registry } const { resolve, fetchers } = createClient({ authConfig, cacheDir: '.store', }) test('request package', async () => { const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() const pkgResponse = await requestPackage({ alias: 'is-positive', pref: '1.0.0' }, { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, }) expect(pkgResponse).toBeTruthy() expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.id).toBe(`localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0`) expect(pkgResponse.body.resolvedVia).toBe('npm-registry') expect(pkgResponse.body.isLocal).toBe(false) expect(typeof pkgResponse.body.latest).toBe('string') expect(pkgResponse.body.manifest?.name).toBe('is-positive') expect(!pkgResponse.body.normalizedPref).toBeTruthy() expect(pkgResponse.body.resolution).toStrictEqual({ integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }) const files = await pkgResponse.files!() expect(Object.keys(files.filesIndex).sort()).toStrictEqual(['package.json', 'index.js', 'license', 'readme.md'].sort()) expect(files.fromStore).toBeFalsy() expect(pkgResponse.finishing!()).toBeTruthy() }) test('request package but skip fetching', async () => { const storeDir = '.store' const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() const pkgResponse = await requestPackage({ alias: 'is-positive', pref: '1.0.0' }, { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, skipFetch: true, }) expect(pkgResponse).toBeTruthy() expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.id).toBe(`localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0`) expect(pkgResponse.body.isLocal).toBe(false) expect(typeof pkgResponse.body.latest).toBe('string') expect(pkgResponse.body.manifest?.name).toBe('is-positive') expect(!pkgResponse.body.normalizedPref).toBeTruthy() expect(pkgResponse.body.resolution).toStrictEqual({ integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }) expect(pkgResponse.files).toBeFalsy() expect(pkgResponse.finishing).toBeFalsy() }) test('request package but skip fetching, when resolution is already available', async () => { const storeDir = '.store' const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() const pkgResponse = await requestPackage({ alias: 'is-positive', pref: '1.0.0' }, { currentPkg: { name: 'is-positive', version: '1.0.0', id: `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0`, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, skipFetch: true, update: false, }) as PackageResponse & { body: { latest: string manifest: {name: string} } files: () => Promise<object> finishing: () => Promise<void> } expect(pkgResponse).toBeTruthy() expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.id).toBe(`localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0`) expect(pkgResponse.body.isLocal).toBe(false) expect(typeof pkgResponse.body.latest).toBe('string') expect(pkgResponse.body.manifest.name).toBe('is-positive') expect(!pkgResponse.body.normalizedPref).toBeTruthy() expect(pkgResponse.body.resolution).toStrictEqual({ integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }) expect(pkgResponse.files).toBeFalsy() expect(pkgResponse.finishing).toBeFalsy() }) test('refetch local tarball if its integrity has changed', async () => { const projectDir = tempy.directory() const tarballPath = path.join(projectDir, 'tarball.tgz') const tarballRelativePath = path.relative(projectDir, tarballPath) await ncp(path.join(__dirname, 'pnpm-package-requester-0.8.1.tgz'), tarballPath) const tarball = `file:${tarballRelativePath}` const wantedPackage = { pref: tarball } const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const pkgId = `file:${normalize(tarballRelativePath)}` const requestPackageOpts = { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, skipFetch: true, update: false, } { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, { ...requestPackageOpts, currentPkg: { name: '@pnpm/package-requester', version: '0.8.1', id: pkgId, resolution: { integrity: 'sha512-lqODmYcc/FKOGROEUByd5Sbugqhzgkv+Hij9PXH0sZVQsU2npTQ0x3L81GCtHilFKme8lhBtD31Vxg/AKYrAvg==', tarball, }, }, }) as PackageResponse & { files: () => Promise<PackageFilesResponse> finishing: () => Promise<void> } await response.files() await response.finishing() expect(response.body.updated).toBeFalsy() expect((await response.files()).fromStore).toBeFalsy() expect(await response.bundledManifest!()).toBeTruthy() } await ncp(path.join(__dirname, 'pnpm-package-requester-4.1.2.tgz'), tarballPath) await delay(50) { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, { ...requestPackageOpts, currentPkg: { name: '@pnpm/package-requester', version: '0.8.1', id: pkgId, resolution: { integrity: 'sha512-lqODmYcc/FKOGROEUByd5Sbugqhzgkv+Hij9PXH0sZVQsU2npTQ0x3L81GCtHilFKme8lhBtD31Vxg/AKYrAvg==', tarball, }, }, }) await response.files!() await response.finishing!() expect(response.body.updated).toBeTruthy() expect((await response.files!()).fromStore).toBeFalsy() expect(await response.bundledManifest!()).toBeTruthy() } { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, { ...requestPackageOpts, currentPkg: { name: '@pnpm/package-requester', version: '0.8.1', id: pkgId, resolution: { integrity: 'sha512-v3uhYkN+Eh3Nus4EZmegjQhrfpdPIH+2FjrkeBc6ueqZJWWRaLnSYIkD0An6m16D3v+6HCE18ox6t95eGxj5Pw==', tarball, }, }, }) as PackageResponse & { files: () => Promise<PackageFilesResponse> finishing: () => Promise<void> } await response.files() await response.finishing() expect(response.body.updated).toBeFalsy() expect((await response.files()).fromStore).toBeTruthy() expect(await response.bundledManifest!()).toBeTruthy() } }) test('refetch local tarball if its integrity has changed. The requester does not know the correct integrity', async () => { const projectDir = tempy.directory() const tarballPath = path.join(projectDir, 'tarball.tgz') await ncp(path.join(__dirname, 'pnpm-package-requester-0.8.1.tgz'), tarballPath) const tarball = `file:${tarballPath}` const wantedPackage = { pref: tarball } const storeDir = path.join(__dirname, '..', '.store') const cafs = createCafsStore(storeDir) const requestPackageOpts = { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, update: false, } { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, requestPackageOpts) as PackageResponse & { files: () => Promise<PackageFilesResponse> finishing: () => Promise<void> } await response.files() await response.finishing() expect(response.body.updated).toBeTruthy() expect((await response.files()).fromStore).toBeFalsy() expect(await response.bundledManifest!()).toBeTruthy() } await ncp(path.join(__dirname, 'pnpm-package-requester-4.1.2.tgz'), tarballPath) await delay(50) { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, requestPackageOpts) as PackageResponse & { files: () => Promise<PackageFilesResponse> finishing: () => Promise<void> } await response.files() await response.finishing() expect(response.body.updated).toBeTruthy() expect((await response.files()).fromStore).toBeFalsy() expect(await response.bundledManifest!()).toBeTruthy() } { const requestPackage = createPackageRequester({ resolve, fetchers, cafs, storeDir, verifyStoreIntegrity: true, }) const response = await requestPackage(wantedPackage, requestPackageOpts) as PackageResponse & { files: () => Promise<PackageFilesResponse> finishing: () => Promise<void> } await response.files() await response.finishing() expect((await response.files()).fromStore).toBeTruthy() expect(await response.bundledManifest!()).toBeTruthy() } }) test('fetchPackageToStore()', async () => { const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const pkgId = `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0` const fetchResult = packageRequester.fetchPackageToStore({ force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }) expect(fetchResult.bundledManifest).toBeFalsy() const files = await fetchResult.files() expect(Object.keys(files.filesIndex).sort()).toStrictEqual(['package.json', 'index.js', 'license', 'readme.md'].sort()) expect(files.fromStore).toBeFalsy() const indexFile = await loadJsonFile<PackageFilesIndex>(fetchResult.filesIndexFile) expect(indexFile).toBeTruthy() expect(typeof indexFile.files['package.json'].checkedAt).toBeTruthy() expect(fetchResult.finishing()).toBeTruthy() const fetchResult2 = packageRequester.fetchPackageToStore({ fetchRawManifest: true, force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }) // This verifies that when a package has been cached with no full manifest // the full manifest is requested and added to the cache expect( await fetchResult2.bundledManifest!() ).toStrictEqual( { engines: { node: '>=0.10.0' }, name: 'is-positive', scripts: { test: 'node test.js' }, version: '1.0.0', } ) }) test('fetchPackageToStore() concurrency check', async () => { const storeDir = tempy.directory() const cafsDir = path.join(storeDir, 'files') const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const pkgId = `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0` const projectDir1 = tempy.directory() const projectDir2 = tempy.directory() const fetchResults = await Promise.all([ packageRequester.fetchPackageToStore({ force: false, lockfileDir: projectDir1, pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }), packageRequester.fetchPackageToStore({ force: false, lockfileDir: projectDir2, pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }), ]) let ino1!: Number let ino2!: Number { const fetchResult = fetchResults[0] const files = await fetchResult.files() ino1 = statSync(getFilePathInCafs(cafsDir, files.filesIndex['package.json'].integrity, 'nonexec')).ino expect(Object.keys(files.filesIndex).sort()).toStrictEqual(['package.json', 'index.js', 'license', 'readme.md'].sort()) expect(files.fromStore).toBeFalsy() expect(fetchResult.finishing).toBeTruthy() } { const fetchResult = fetchResults[1] const files = await fetchResult.files() ino2 = statSync(getFilePathInCafs(cafsDir, files.filesIndex['package.json'].integrity, 'nonexec')).ino expect(Object.keys(files.filesIndex).sort()).toStrictEqual(['package.json', 'index.js', 'license', 'readme.md'].sort()) expect(files.fromStore).toBeFalsy() expect(fetchResult.finishing()).toBeTruthy() } expect(ino1).toBe(ino2) }) test('fetchPackageToStore() does not cache errors', async () => { nock(registry) .get('/is-positive/-/is-positive-1.0.0.tgz') .reply(404) nock(registry) .get('/is-positive/-/is-positive-1.0.0.tgz') .replyWithFile(200, IS_POSTIVE_TARBALL) const noRetry = createClient({ authConfig, retry: { retries: 0 }, cacheDir: '.pnpm', }) const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve: noRetry.resolve, fetchers: noRetry.fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const pkgId = `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0` const badRequest = packageRequester.fetchPackageToStore({ force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }) await expect(badRequest.files()).rejects.toThrow() const fetchResult = packageRequester.fetchPackageToStore({ force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, }) const files = await fetchResult.files() expect(Object.keys(files.filesIndex).sort()).toStrictEqual(['package.json', 'index.js', 'license', 'readme.md'].sort()) expect(files.fromStore).toBeFalsy() expect(fetchResult.finishing()).toBeTruthy() expect(nock.isDone()).toBeTruthy() }) // This test was added to cover the issue described here: https://github.com/pnpm/supi/issues/65 test('always return a package manifest in the response', async () => { nock.cleanAll() const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() { const pkgResponse = await requestPackage({ alias: 'is-positive', pref: '1.0.0' }, { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, }) as PackageResponse & {body: {manifest: {name: string}}} expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.manifest.name).toBeTruthy() } { const pkgResponse = await requestPackage({ alias: 'is-positive', pref: '1.0.0' }, { currentPkg: { name: 'is-positive', version: '1.0.0', id: `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0`, resolution: { integrity: 'sha1-iACYVrZKLx632LsBeUGEJK4EUss=', registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, }, }, downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, }) as PackageResponse & {bundledManifest: () => Promise<DependencyManifest>} expect(pkgResponse.body).toBeTruthy() expect( await pkgResponse.bundledManifest() ).toStrictEqual( { engines: { node: '>=0.10.0' }, name: 'is-positive', scripts: { test: 'node test.js' }, version: '1.0.0', } ) } }) // Covers https://github.com/pnpm/pnpm/issues/1293 test('fetchPackageToStore() fetch raw manifest of cached package', async () => { nock(registry) .get('/is-positive/-/is-positive-1.0.0.tgz') .replyWithFile(200, IS_POSTIVE_TARBALL) const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const pkgId = `localhost+${REGISTRY_MOCK_PORT}/is-positive/1.0.0` const resolution = { registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/is-positive/-/is-positive-1.0.0.tgz`, } const fetchResults = await Promise.all([ packageRequester.fetchPackageToStore({ fetchRawManifest: false, force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution, }, }), packageRequester.fetchPackageToStore({ fetchRawManifest: true, force: false, lockfileDir: tempy.directory(), pkg: { name: 'is-positive', version: '1.0.0', id: pkgId, resolution, }, }), ]) expect(await fetchResults[1].bundledManifest!()).toBeTruthy() }) test('refetch package to store if it has been modified', async () => { nock.cleanAll() const storeDir = tempy.directory() const cafsDir = path.join(storeDir, 'files') const lockfileDir = tempy.directory() const pkgId = `localhost+${REGISTRY_MOCK_PORT}/magic-hook/2.0.0` const resolution = { registry: `http://localhost:${REGISTRY_MOCK_PORT}/`, tarball: `http://localhost:${REGISTRY_MOCK_PORT}/magic-hook/-/magic-hook-2.0.0.tgz`, } let indexJsFile!: string { const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const fetchResult = packageRequester.fetchPackageToStore({ fetchRawManifest: false, force: false, lockfileDir, pkg: { name: 'magic-hook', version: '2.0.0', id: pkgId, resolution, }, }) const { filesIndex } = await fetchResult.files() indexJsFile = getFilePathInCafs(cafsDir, filesIndex['index.js'].integrity, 'nonexec') } await delay(200) // Adding some content to the file to change its integrity await fs.appendFile(indexJsFile, '// foobar') const reporter = jest.fn() streamParser.on('data', reporter) { const cafs = createCafsStore(storeDir) const packageRequester = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) const fetchResult = packageRequester.fetchPackageToStore({ fetchRawManifest: false, force: false, lockfileDir, pkg: { name: 'magic-hook', version: '2.0.0', id: pkgId, resolution, }, }) await fetchResult.files() } streamParser.removeListener('data', reporter) expect(await fs.readFile(indexJsFile, 'utf8')).not.toContain('// foobar') expect(reporter).toBeCalledWith(expect.objectContaining({ level: 'warn', message: `Refetching ${path.join(storeDir, depPathToFilename(pkgId, process.cwd()))} to store. It was either modified or had no integrity checksums`, name: 'pnpm:package-requester', prefix: lockfileDir, })) }) test('do not fetch an optional package that is not installable', async () => { const storeDir = '.store' const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() const pkgResponse = await requestPackage({ alias: 'not-compatible-with-any-os', optional: true, pref: '*' }, { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, }) expect(pkgResponse).toBeTruthy() expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.isInstallable).toBe(false) expect(pkgResponse.body.id).toBe(`localhost+${REGISTRY_MOCK_PORT}/not-compatible-with-any-os/1.0.0`) expect(pkgResponse.files).toBeFalsy() expect(pkgResponse.finishing).toBeFalsy() }) // Test case for https://github.com/pnpm/pnpm/issues/1866 test('fetch a git package without a package.json', async () => { // a small Deno library with a 'denolib.json' instead of a 'package.json' const repo = 'denolib/camelcase' const commit = 'aeb6b15f9c9957c8fa56f9731e914c4d8a6d2f2b' nock.cleanAll() const storeDir = tempy.directory() const cafs = createCafsStore(storeDir) const requestPackage = createPackageRequester({ resolve, fetchers, cafs, networkConcurrency: 1, storeDir, verifyStoreIntegrity: true, }) expect(typeof requestPackage).toBe('function') const projectDir = tempy.directory() { const pkgResponse = await requestPackage({ alias: 'camelcase', pref: `${repo}#${commit}` }, { downloadPriority: 0, lockfileDir: projectDir, preferredVersions: {}, projectDir, registry, }) as PackageResponse & {body: {manifest: {name: string}}} expect(pkgResponse.body).toBeTruthy() expect(pkgResponse.body.manifest).toBeUndefined() expect(pkgResponse.body.isInstallable).toBeFalsy() expect(pkgResponse.body.id).toBe(`github.com/${repo}/${commit}`) } })
the_stack
import { isEIP55Address, ParsedMessage, ParsedMessageRegExp } from "@spruceid/siwe-parser"; import { providers, utils } from "ethers"; import * as uri from "valid-url"; import { SiweError, SiweErrorType, SiweResponse, VerifyOpts, VerifyOptsKeys, VerifyParams, VerifyParamsKeys } from "./types"; import { checkContractWalletSignature, generateNonce } from "./utils"; export class SiweMessage { /**RFC 4501 dns authority that is requesting the signing. */ domain: string; /**Ethereum address performing the signing conformant to capitalization * encoded checksum specified in EIP-55 where applicable. */ address: string; /**Human-readable ASCII assertion that the user will sign, and it must not * contain `\n`. */ statement?: string; /**RFC 3986 URI referring to the resource that is the subject of the signing * (as in the __subject__ of a claim). */ uri: string; /**Current version of the message. */ version: string; /**EIP-155 Chain ID to which the session is bound, and the network where * Contract Accounts must be resolved. */ chainId: number; /**Randomized token used to prevent replay attacks, at least 8 alphanumeric * characters. */ nonce: string; /**ISO 8601 datetime string of the current time. */ issuedAt: string; /**ISO 8601 datetime string that, if present, indicates when the signed * authentication message is no longer valid. */ expirationTime?: string; /**ISO 8601 datetime string that, if present, indicates when the signed * authentication message will become valid. */ notBefore?: string; /**System-specific identifier that may be used to uniquely refer to the * sign-in request. */ requestId?: string; /**List of information or references to information the user wishes to have * resolved as part of authentication by the relying party. They are * expressed as RFC 3986 URIs separated by `\n- `. */ resources?: Array<string>; /** * Creates a parsed Sign-In with Ethereum Message (EIP-4361) object from a * string or an object. If a string is used an ABNF parser is called to * validate the parameter, otherwise the fields are attributed. * @param param {string | SiweMessage} Sign message as a string or an object. */ constructor(param: string | Partial<SiweMessage>) { if (typeof param === "string") { const parsedMessage = new ParsedMessage(param); this.domain = parsedMessage.domain; this.address = parsedMessage.address; this.statement = parsedMessage.statement; this.uri = parsedMessage.uri; this.version = parsedMessage.version; this.nonce = parsedMessage.nonce; this.issuedAt = parsedMessage.issuedAt; this.expirationTime = parsedMessage.expirationTime; this.notBefore = parsedMessage.notBefore; this.requestId = parsedMessage.requestId; this.chainId = parsedMessage.chainId; this.resources = parsedMessage.resources; } else { Object.assign(this, param); if (typeof this.chainId === "string") { this.chainId = parseInt(this.chainId); } } this.nonce = this.nonce || generateNonce(); this.validateMessage(); } /** * Given a sign message (EIP-4361) returns the correct matching groups. * @param message {string} * @returns {RegExpExecArray} The matching groups for the message */ regexFromMessage(message: string): RegExpExecArray { const parsedMessage = new ParsedMessageRegExp(message); return parsedMessage.match; } /** * This function can be used to retrieve an EIP-4361 formated message for * signature, although you can call it directly it's advised to use * [prepareMessage()] instead which will resolve to the correct method based * on the [type] attribute of this object, in case of other formats being * implemented. * @returns {string} EIP-4361 formated message, ready for EIP-191 signing. */ toMessage(): string { /** Validates all fields of the object */ this.validateMessage(); const header = `${this.domain} wants you to sign in with your Ethereum account:`; const uriField = `URI: ${this.uri}`; let prefix = [header, this.address].join("\n"); const versionField = `Version: ${this.version}`; if (!this.nonce) { this.nonce = generateNonce(); } const chainField = `Chain ID: ` + this.chainId || "1"; const nonceField = `Nonce: ${this.nonce}`; const suffixArray = [uriField, versionField, chainField, nonceField]; if (this.issuedAt) { Date.parse(this.issuedAt); } this.issuedAt = this.issuedAt ? this.issuedAt : new Date().toISOString(); suffixArray.push(`Issued At: ${this.issuedAt}`); if (this.expirationTime) { const expiryField = `Expiration Time: ${this.expirationTime}`; suffixArray.push(expiryField); } if (this.notBefore) { suffixArray.push(`Not Before: ${this.notBefore}`); } if (this.requestId) { suffixArray.push(`Request ID: ${this.requestId}`); } if (this.resources) { suffixArray.push( [`Resources:`, ...this.resources.map((x) => `- ${x}`)].join("\n") ); } let suffix = suffixArray.join("\n"); prefix = [prefix, this.statement].join("\n\n"); if (this.statement) { prefix += "\n"; } return [prefix, suffix].join("\n"); } /** * This method parses all the fields in the object and creates a messaging for signing * message according with the type defined. * @returns {string} Returns a message ready to be signed according with the * type defined in the object. */ prepareMessage(): string { let message: string; switch (this.version) { case "1": { message = this.toMessage(); break; } default: { message = this.toMessage(); break; } } return message; } /** * @deprecated * Verifies the integrity of the object by matching its signature. * @param signature Signature to match the address in the message. * @param provider Ethers provider to be used for EIP-1271 validation */ async validate( signature: string, provider?: providers.Provider ) { console.warn("validate() has been deprecated, please update your code to use verify(). validate() may be removed in future versions."); return this.verify({ signature }, { provider, suppressExceptions: false }); } /** * Verifies the integrity of the object by matching its signature. * @param params Parameters to verify the integrity of the message, signature is required. * @returns {Promise<SiweMessage>} This object if valid. */ async verify( params: VerifyParams, opts: VerifyOpts = { suppressExceptions: false }, ): Promise<SiweResponse> { return new Promise<SiweResponse>(async (resolve, reject) => { Object.keys(params).forEach((key: keyof VerifyParams) => { if (!VerifyParamsKeys.includes(key)) { reject({ success: false, data: this, error: new Error(`${key} is not a valid key for VerifyParams.`), }); } }); Object.keys(opts).forEach((key: keyof VerifyOpts) => { if (!VerifyOptsKeys.includes(key)) { reject({ success: false, data: this, error: new Error(`${key} is not a valid key for VerifyOpts.`), }); } }); const assert = (result) => { if (opts.suppressExceptions) { resolve(result); } else { reject(result); } }; const { signature, domain, nonce, time } = params; /** Domain binding */ if (domain && domain !== this.domain) { assert({ success: false, data: this, error: new SiweError( SiweErrorType.DOMAIN_MISMATCH, domain, this.domain ), }); } /** Nonce binding */ if (nonce && nonce !== this.nonce) { assert({ success: false, data: this, error: new SiweError(SiweErrorType.NONCE_MISMATCH, nonce, this.nonce), }); } /** Check time or now */ const checkTime = new Date(time || new Date()); /** Message not expired */ if (this.expirationTime) { const expirationDate = new Date(this.expirationTime); if (checkTime.getTime() >= expirationDate.getTime()) { assert({ success: false, data: this, error: new SiweError( SiweErrorType.EXPIRED_MESSAGE, `${checkTime.toISOString()} < ${expirationDate.toISOString()}`, `${checkTime.toISOString()} >= ${expirationDate.toISOString()}` ), }); } } /** Message is valid already */ if (this.notBefore) { const notBefore = new Date(this.notBefore); if (checkTime.getTime() < notBefore.getTime()) { assert({ success: false, data: this, error: new SiweError( SiweErrorType.NOT_YET_VALID_MESSAGE, `${checkTime.toISOString()} >= ${notBefore.toISOString()}`, `${checkTime.toISOString()} < ${notBefore.toISOString()}` ), }); } } let EIP4361Message; try { EIP4361Message = this.prepareMessage(); } catch (e) { assert({ success: false, data: this, error: e, }); } /** Recover address from signature */ let addr; try { addr = utils.verifyMessage(EIP4361Message, signature); } catch (_) { } finally { /** Match signature with message's address */ if (addr !== this.address) { let isValid = false; try { /** Try resolving EIP-1271 if address doesn't match */ isValid = await checkContractWalletSignature( this, signature, opts.provider ); } catch (_) { isValid = false; } finally { if (!isValid) { assert({ success: false, data: this, error: new SiweError( SiweErrorType.INVALID_SIGNATURE, addr, `Resolved address to be ${this.address}` ), }); } } } } resolve({ success: true, data: this, }); }); } /** * Validates the values of this object fields. * @throws Throws an {ErrorType} if a field is invalid. */ private validateMessage(...args) { /** Checks if the user might be using the function to verify instead of validate. */ if (args.length > 0) { throw new SiweError(SiweErrorType.UNABLE_TO_PARSE, `Unexpected argument in the validateMessage function.`); } /** `domain` check. */ if (!this.domain || this.domain.length === 0 || !/[^#?]*/.test(this.domain)) { throw new SiweError(SiweErrorType.INVALID_DOMAIN, `${this.domain} to be a valid domain.`); } /** EIP-55 `address` check. */ if (!isEIP55Address(this.address)) { throw new SiweError( SiweErrorType.INVALID_ADDRESS, utils.getAddress(this.address), this.address ); } /** Check if the URI is valid. */ if (!uri.isUri(this.uri)) { throw new SiweError(SiweErrorType.INVALID_URI, `${this.uri} to be a valid uri.`); } /** Check if the version is 1. */ if (this.version !== "1") { throw new SiweError( SiweErrorType.INVALID_MESSAGE_VERSION, "1", this.version ); } /** Check if the nonce is alphanumeric and bigger then 8 characters */ const nonce = this?.nonce?.match(/[a-zA-Z0-9]{8,}/); if (!nonce || this.nonce.length < 8 || nonce[0] !== this.nonce) { throw new SiweError( SiweErrorType.INVALID_NONCE, `Length > 8 (${nonce.length}). Alphanumeric.`, this.nonce ); } const ISO8601 = /([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))/; /** `issuedAt` conforms to ISO-8601 */ if (this.issuedAt) { if (!ISO8601.test(this.issuedAt)) { throw new Error(SiweErrorType.INVALID_TIME_FORMAT); } } /** `expirationTime` conforms to ISO-8601 */ if (this.expirationTime) { if (!ISO8601.test(this.expirationTime)) { throw new Error(SiweErrorType.INVALID_TIME_FORMAT); } } /** `notBefore` conforms to ISO-8601 */ if (this.notBefore) { if (!ISO8601.test(this.notBefore)) { throw new Error(SiweErrorType.INVALID_TIME_FORMAT); } } } }
the_stack
import { AnonymousIdentity, DerEncodedPublicKey, Identity, Signature, SignIdentity, } from '@dfinity/agent'; import { isDelegationValid } from '@dfinity/authentication'; import { Delegation, DelegationChain, DelegationIdentity, Ed25519KeyIdentity, } from '@dfinity/identity'; import { Principal } from '@dfinity/principal'; const KEY_LOCALSTORAGE_KEY = 'identity'; const KEY_LOCALSTORAGE_DELEGATION = 'delegation'; const IDENTITY_PROVIDER_DEFAULT = 'https://identity.ic0.app'; const IDENTITY_PROVIDER_ENDPOINT = '#authorize'; /** * List of options for creating an {@link AuthClient}. */ export interface AuthClientCreateOptions { /** * An identity to use as the base */ identity?: SignIdentity; /** * Optional storage with get, set, and remove. Uses LocalStorage by default */ storage?: AuthClientStorage; } export interface AuthClientLoginOptions { /** * Identity provider. By default, use the identity service. */ identityProvider?: string | URL; /** * Expiration of the authentication in nanoseconds */ maxTimeToLive?: bigint; /** * Callback once login has completed */ onSuccess?: () => void; /** * Callback in case authentication fails */ onError?: (error?: string) => void; } /** * Interface for persisting user authentication data */ export interface AuthClientStorage { get(key: string): Promise<string | null>; set(key: string, value: string): Promise<void>; remove(key: string): Promise<void>; } interface InternetIdentityAuthRequest { kind: 'authorize-client'; sessionPublicKey: Uint8Array; maxTimeToLive?: bigint; } interface InternetIdentityAuthResponseSuccess { kind: 'authorize-client-success'; delegations: { delegation: { pubkey: Uint8Array; expiration: bigint; targets?: Principal[]; }; signature: Uint8Array; }[]; userPublicKey: Uint8Array; } async function _deleteStorage(storage: AuthClientStorage) { await storage.remove(KEY_LOCALSTORAGE_KEY); await storage.remove(KEY_LOCALSTORAGE_DELEGATION); } export class LocalStorage implements AuthClientStorage { constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {} public get(key: string): Promise<string | null> { return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key)); } public set(key: string, value: string): Promise<void> { this._getLocalStorage().setItem(this.prefix + key, value); return Promise.resolve(); } public remove(key: string): Promise<void> { this._getLocalStorage().removeItem(this.prefix + key); return Promise.resolve(); } private _getLocalStorage() { if (this._localStorage) { return this._localStorage; } const ls = typeof window === 'undefined' ? typeof global === 'undefined' ? typeof self === 'undefined' ? undefined : self.localStorage : global.localStorage : window.localStorage; if (!ls) { throw new Error('Could not find local storage.'); } return ls; } } interface AuthReadyMessage { kind: 'authorize-ready'; } interface AuthResponseSuccess { kind: 'authorize-client-success'; delegations: { delegation: { pubkey: Uint8Array; expiration: bigint; targets?: Principal[]; }; signature: Uint8Array; }[]; userPublicKey: Uint8Array; } interface AuthResponseFailure { kind: 'authorize-client-failure'; text: string; } type IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse; type AuthResponse = AuthResponseSuccess | AuthResponseFailure; export class AuthClient { public static async create(options: AuthClientCreateOptions = {}): Promise<AuthClient> { const storage = options.storage ?? new LocalStorage('ic-'); let key: null | SignIdentity = null; if (options.identity) { key = options.identity; } else { const maybeIdentityStorage = await storage.get(KEY_LOCALSTORAGE_KEY); if (maybeIdentityStorage) { try { key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage); } catch (e) { // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity // serialization. } } } let identity = new AnonymousIdentity(); let chain: null | DelegationChain = null; if (key) { try { const chainStorage = await storage.get(KEY_LOCALSTORAGE_DELEGATION); if (options.identity) { identity = options.identity; } else if (chainStorage) { chain = DelegationChain.fromJSON(chainStorage); // Verify that the delegation isn't expired. if (!isDelegationValid(chain)) { await _deleteStorage(storage); key = null; } else { identity = DelegationIdentity.fromDelegation(key, chain); } } } catch (e) { console.error(e); // If there was a problem loading the chain, delete the key. await _deleteStorage(storage); key = null; } } return new this(identity, key, chain, storage); } protected constructor( private _identity: Identity, private _key: SignIdentity | null, private _chain: DelegationChain | null, private _storage: AuthClientStorage, // A handle on the IdP window. private _idpWindow?: Window, // The event handler for processing events from the IdP. private _eventHandler?: (event: MessageEvent) => void, ) {} private _handleSuccess(message: InternetIdentityAuthResponseSuccess, onSuccess?: () => void) { const delegations = message.delegations.map(signedDelegation => { return { delegation: new Delegation( signedDelegation.delegation.pubkey, signedDelegation.delegation.expiration, signedDelegation.delegation.targets, ), signature: signedDelegation.signature.buffer as Signature, }; }); const delegationChain = DelegationChain.fromDelegations( delegations, message.userPublicKey.buffer as DerEncodedPublicKey, ); const key = this._key; if (!key) { return; } this._chain = delegationChain; this._identity = DelegationIdentity.fromDelegation(key, this._chain); this._idpWindow?.close(); onSuccess?.(); this._removeEventListener(); } public getIdentity(): Identity { return this._identity; } public async isAuthenticated(): Promise<boolean> { return !this.getIdentity().getPrincipal().isAnonymous() && this._chain !== null; } public async login(options?: AuthClientLoginOptions): Promise<void> { let key = this._key; if (!key) { // Create a new key (whether or not one was in storage). key = Ed25519KeyIdentity.generate(); this._key = key; await this._storage.set(KEY_LOCALSTORAGE_KEY, JSON.stringify(key)); } // Set default maxTimeToLive to 1 day const defaultTimeToLive = /* days */ BigInt(1) * /* hours */ BigInt(24) * /* nanoseconds */ BigInt(3600000000000); // Create the URL of the IDP. (e.g. https://XXXX/#authorize) const identityProviderUrl = new URL( options?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT, ); // Set the correct hash if it isn't already set. identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT; // If `login` has been called previously, then close/remove any previous windows // and event listeners. this._idpWindow?.close(); this._removeEventListener(); // Add an event listener to handle responses. this._eventHandler = this._getEventHandler(identityProviderUrl, { maxTimeToLive: defaultTimeToLive, ...options, }); window.addEventListener('message', this._eventHandler); // Open a new window with the IDP provider. this._idpWindow = window.open(identityProviderUrl.toString(), 'idpWindow') ?? undefined; } private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) { return async (event: MessageEvent) => { if (event.origin !== identityProviderUrl.origin) { return; } const message = event.data as IdentityServiceResponseMessage; switch (message.kind) { case 'authorize-ready': { // IDP is ready. Send a message to request authorization. const request: InternetIdentityAuthRequest = { kind: 'authorize-client', sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer() as ArrayBuffer), maxTimeToLive: options?.maxTimeToLive, }; this._idpWindow?.postMessage(request, identityProviderUrl.origin); break; } case 'authorize-client-success': // Create the delegation chain and store it. try { this._handleSuccess(message, options?.onSuccess); // Setting the storage is moved out of _handleSuccess to make // it a sync function. Having _handleSuccess as an async function // messes up the jest tests for some reason. if (this._chain) { await this._storage.set( KEY_LOCALSTORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()), ); } } catch (err) { this._handleFailure(err.message, options?.onError); } break; case 'authorize-client-failure': this._handleFailure(message.text, options?.onError); break; default: break; } }; } private _handleFailure(errorMessage?: string, onError?: (error?: string) => void): void { this._idpWindow?.close(); onError?.(errorMessage); this._removeEventListener(); } private _removeEventListener() { if (this._eventHandler) { window.removeEventListener('message', this._eventHandler); } this._eventHandler = undefined; } public async logout(options: { returnTo?: string } = {}): Promise<void> { _deleteStorage(this._storage); // Reset this auth client to a non-authenticated state. this._identity = new AnonymousIdentity(); this._key = null; this._chain = null; if (options.returnTo) { try { window.history.pushState({}, '', options.returnTo); } catch (e) { window.location.href = options.returnTo; } } } }
the_stack
import { ObjectType, Values, ElemID, BuiltinTypes, MapType, ListType } from '@salto-io/adapter-api' // eslint-disable-next-line import { generateType, toNestedTypeName } from '../../../src/elements/ducktype' import { TYPES_PATH, SUBTYPES_PATH } from '../../../src/elements' /* eslint-disable camelcase */ const ADAPTER_NAME = 'myAdapter' describe('ducktype_type_elements', () => { describe('generateType', () => { it('should generate empty types when no entries are provided', () => { const entries: Values[] = [] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: {} }))).toBeTruthy() expect(nestedTypes).toHaveLength(0) expect(type.path).toEqual([ADAPTER_NAME, TYPES_PATH, 'typeName']) }) it('should generate types recursively with correct fields when hasDynamicFields=false', () => { const entries = [ { id: 41619, api_collection_id: 11815, flow_id: 1381119, flow_ids: [1381119, 1382229], name: 'ab321', method: 'GET', url: 'https://some.url.com/a/bbb/user/{id}', legacy_url: null, base_path: '/a/bbb/user/{id}', path: 'user/{id}', active: false, legacy: false, created_at: '2020-12-21T16:08:03.762-08:00', updated_at: '2020-12-21T16:08:03.762-08:00', }, { id: 54775, api_collection_id: 22, flow_id: 890, flow_ids: [890, 980], name: 'some other name', field_with_complex_type: { number: 53, nested_type: { val: 'agds', another_val: 'dgadgasg', }, }, field_with_complex_list_type: [{ number: 53, }], }, { field_with_complex_type: { number: 222, nested_type: { val: 'agds', another_val: 7, abc: 'abc', unknown: null, }, }, }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { id: { refType: BuiltinTypes.NUMBER }, api_collection_id: { refType: BuiltinTypes.NUMBER }, flow_id: { refType: BuiltinTypes.NUMBER }, flow_ids: { refType: new ListType(BuiltinTypes.NUMBER) }, name: { refType: BuiltinTypes.STRING }, method: { refType: BuiltinTypes.STRING }, url: { refType: BuiltinTypes.STRING }, legacy_url: { refType: BuiltinTypes.UNKNOWN }, base_path: { refType: BuiltinTypes.STRING }, path: { refType: BuiltinTypes.STRING }, active: { refType: BuiltinTypes.BOOLEAN }, legacy: { refType: BuiltinTypes.BOOLEAN }, created_at: { refType: BuiltinTypes.STRING }, updated_at: { refType: BuiltinTypes.STRING }, field_with_complex_type: { refType: nestedTypes[0] }, field_with_complex_list_type: { refType: new ListType(nestedTypes[2]), }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(3) expect(nestedTypes[0].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_type'), fields: { number: { refType: BuiltinTypes.NUMBER }, nested_type: { refType: nestedTypes[1] }, }, }))).toBeTruthy() expect(nestedTypes[1].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_type__nested_type'), fields: { val: { refType: BuiltinTypes.STRING }, another_val: { refType: BuiltinTypes.UNKNOWN }, abc: { refType: BuiltinTypes.STRING }, unknown: { refType: BuiltinTypes.UNKNOWN }, }, }))).toBeTruthy() expect(nestedTypes[2].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_list_type'), fields: { number: { refType: BuiltinTypes.NUMBER }, }, }))).toBeTruthy() }) it('should generate types with correct names when sourceTypeName is used', () => { const entries = [ { id: 41619, api_collection_id: 11815, flow_id: 1381119, flow_ids: [1381119, 1382229], name: 'ab321', method: 'GET', url: 'https://some.url.com/a/bbb/user/{id}', legacy_url: null, base_path: '/a/bbb/user/{id}', path: 'user/{id}', active: false, legacy: false, created_at: '2020-12-21T16:08:03.762-08:00', updated_at: '2020-12-21T16:08:03.762-08:00', }, { id: 54775, api_collection_id: 22, flow_id: 890, flow_ids: [890, 980], name: 'some other name', field_with_complex_type: { number: 53, nested_type: { val: 'agds', another_val: 'dgadgasg', }, }, field_with_complex_list_type: [{ number: 53, }], }, { field_with_complex_type: { number: 222, nested_type: { val: 'agds', another_val: 7, abc: 'abc', unknown: null, }, }, }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: { renamedComplex: { sourceTypeName: 'renamedTypeName__field_with_complex_type', }, renamedTypeName: { sourceTypeName: 'typeName', }, }, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'renamedTypeName'), fields: { id: { refType: BuiltinTypes.NUMBER }, api_collection_id: { refType: BuiltinTypes.NUMBER }, flow_id: { refType: BuiltinTypes.NUMBER }, flow_ids: { refType: new ListType(BuiltinTypes.NUMBER) }, name: { refType: BuiltinTypes.STRING }, method: { refType: BuiltinTypes.STRING }, url: { refType: BuiltinTypes.STRING }, legacy_url: { refType: BuiltinTypes.UNKNOWN }, base_path: { refType: BuiltinTypes.STRING }, path: { refType: BuiltinTypes.STRING }, active: { refType: BuiltinTypes.BOOLEAN }, legacy: { refType: BuiltinTypes.BOOLEAN }, created_at: { refType: BuiltinTypes.STRING }, updated_at: { refType: BuiltinTypes.STRING }, field_with_complex_type: { refType: nestedTypes[0] }, field_with_complex_list_type: { refType: new ListType(nestedTypes[2]), }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(3) expect(nestedTypes[0].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'renamedComplex'), fields: { number: { refType: BuiltinTypes.NUMBER }, nested_type: { refType: nestedTypes[1] }, }, }))).toBeTruthy() expect(nestedTypes[1].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'renamedComplex__nested_type'), fields: { val: { refType: BuiltinTypes.STRING }, another_val: { refType: BuiltinTypes.UNKNOWN }, abc: { refType: BuiltinTypes.STRING }, unknown: { refType: BuiltinTypes.UNKNOWN }, }, }))).toBeTruthy() expect(nestedTypes[2].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'renamedTypeName__field_with_complex_list_type'), fields: { number: { refType: BuiltinTypes.NUMBER }, }, }))).toBeTruthy() }) it('should annotate fields marked as fieldsToHide with _hidden_value', () => { const entries = [ { id: 41619, api_collection_id: 11815, flow_id: 1381119, flow_ids: [1381119, 1382229], name: 'ab321', method: 'GET', url: 'https://some.url.com/a/bbb/user/{id}', legacy_url: null, base_path: '/a/bbb/user/{id}', path: 'user/{id}', active: false, legacy: false, created_at: '2020-12-21T16:08:03.762-08:00', updated_at: '2020-12-21T16:08:03.762-08:00', }, { id: 54775, api_collection_id: 22, flow_id: 890, flow_ids: [890, 980], name: 'some other name', field_with_complex_type: { number: 53, nested_type: { val: 'agds', another_val: 'dgadgasg', }, }, field_with_complex_list_type: [{ number: 53, }], }, { field_with_complex_type: { number: 222, nested_type: { val: 'agds', another_val: 7, abc: 'abc', unknown: null, }, }, }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: { typeName: { fieldsToHide: [ { fieldName: 'flow_id', fieldType: 'number' }, ], }, typeName__field_with_complex_type: { fieldsToHide: [ { fieldName: 'number' }, ], }, }, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { id: { refType: BuiltinTypes.NUMBER }, api_collection_id: { refType: BuiltinTypes.NUMBER }, flow_id: { refType: BuiltinTypes.NUMBER, annotations: { _hidden_value: true }, }, flow_ids: { refType: new ListType(BuiltinTypes.NUMBER) }, name: { refType: BuiltinTypes.STRING }, method: { refType: BuiltinTypes.STRING }, url: { refType: BuiltinTypes.STRING }, legacy_url: { refType: BuiltinTypes.UNKNOWN }, base_path: { refType: BuiltinTypes.STRING }, path: { refType: BuiltinTypes.STRING }, active: { refType: BuiltinTypes.BOOLEAN }, legacy: { refType: BuiltinTypes.BOOLEAN }, created_at: { refType: BuiltinTypes.STRING }, updated_at: { refType: BuiltinTypes.STRING }, field_with_complex_type: { refType: nestedTypes[0] }, field_with_complex_list_type: { refType: new ListType(nestedTypes[2]), }, }, }))).toBeTruthy() expect(nestedTypes[0].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_type'), fields: { number: { refType: BuiltinTypes.NUMBER, annotations: { _hidden_value: true }, }, nested_type: { refType: nestedTypes[1] }, }, }))).toBeTruthy() }) it('should ignore nulls when determining types for fields', () => { const entries = [ { id: 41619, name: 'ab321', active: false, only_exists_once: null, }, { id: null, name: undefined, field_with_complex_type: { number: 53, nested_type: { val: 'agds', another_val: 'dgadgasg', }, }, }, { field_with_complex_type: { number: null, nested_type: { val: null, another_val: 7, }, }, }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { id: { refType: BuiltinTypes.NUMBER }, name: { refType: BuiltinTypes.STRING }, active: { refType: BuiltinTypes.BOOLEAN }, only_exists_once: { refType: BuiltinTypes.UNKNOWN }, field_with_complex_type: { refType: nestedTypes[0] }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(2) expect(nestedTypes[0].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_type'), fields: { number: { refType: BuiltinTypes.NUMBER }, nested_type: { refType: nestedTypes[1] }, }, }))).toBeTruthy() expect(nestedTypes[1].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__field_with_complex_type__nested_type'), fields: { val: { refType: BuiltinTypes.STRING }, another_val: { refType: BuiltinTypes.UNKNOWN }, }, }))).toBeTruthy() }) it('should generate primitive types with correct fields when hasDynamicFields=true', () => { const entries = [ { 'a.b': 'some value abc', something: 'something else', }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: true, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { value: { refType: new MapType(BuiltinTypes.STRING) }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(0) }) it('should generate types recursively with correct fields when hasDynamicFields=true', () => { const entries = [ { 'a.b': { a: 'string', b: 123, complex: { str: 'str', num: 15478, }, }, something: { a: 'another string', c: true, }, }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: true, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { value: { refType: new MapType(nestedTypes[0]) }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(2) expect(nestedTypes[0].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__value'), fields: { a: { refType: BuiltinTypes.STRING }, b: { refType: BuiltinTypes.NUMBER }, c: { refType: BuiltinTypes.BOOLEAN }, complex: { refType: nestedTypes[1] }, }, }))).toBeTruthy() expect(nestedTypes[1].isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName__value__complex'), fields: { str: { refType: BuiltinTypes.STRING }, num: { refType: BuiltinTypes.NUMBER }, }, }))).toBeTruthy() }) it('should use unknown value when hasDynamicFields=true and values are inconsistent', () => { const entries = [ { 'a.b': 'some value abc', something: 'something else', }, { 'c.d': 123, something: 'something else', }, ] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName', entries, hasDynamicFields: true, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName'), fields: { value: { refType: new MapType(BuiltinTypes.UNKNOWN) }, }, }))).toBeTruthy() expect(nestedTypes).toHaveLength(0) }) it('should apply naclcase when needed', () => { const entries: Values[] = [] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'typeName.requiring_naclcase', entries, hasDynamicFields: false, isSubType: false, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'typeName_requiring_naclcase@vu'), fields: {}, }))).toBeTruthy() expect(nestedTypes).toHaveLength(0) expect(type.path).toEqual([ADAPTER_NAME, TYPES_PATH, 'typeName_requiring_naclcase']) }) it('should use subtypes path for subtypes', () => { const entries: Values[] = [] const { type, nestedTypes } = generateType({ adapterName: ADAPTER_NAME, name: 'parent_type__subtypeName', entries, hasDynamicFields: false, isSubType: true, transformationConfigByType: {}, transformationDefaultConfig: { idFields: [] }, }) expect(type.isEqual(new ObjectType({ elemID: new ElemID(ADAPTER_NAME, 'parent_type__subtypeName'), fields: {}, }))).toBeTruthy() expect(nestedTypes).toHaveLength(0) expect(type.path).toEqual([ADAPTER_NAME, TYPES_PATH, SUBTYPES_PATH, 'parent_type', 'subtypeName']) }) }) describe('toNestedTypeName', () => { it('should concatenate the parent and child types', () => { expect(toNestedTypeName('aaa', 'bbb')).toEqual('aaa__bbb') }) }) })
the_stack
export const description = ''; import { makeTestGroup } from '../../../../common/framework/test_group.js'; import { assert } from '../../../../common/util/util.js'; import { kTextureFormatInfo, kSizedTextureFormats } from '../../../capability_info.js'; import { align } from '../../../util/math.js'; import { bytesInACompleteRow, dataBytesForCopyOrOverestimate, dataBytesForCopyOrFail, kImageCopyTypes, } from '../../../util/texture/layout.js'; import { ImageCopyTest, texelBlockAlignmentTestExpanderForOffset, texelBlockAlignmentTestExpanderForRowsPerImage, formatCopyableWithMethod, } from './image_copy.js'; export const g = makeTestGroup(ImageCopyTest); g.test('bound_on_rows_per_image') .params(u => u .combine('method', kImageCopyTypes) .beginSubcases() .combine('rowsPerImage', [undefined, 0, 1, 2, 1024]) .combine('copyHeightInBlocks', [0, 1, 2]) .combine('copyDepth', [1, 3]) ) .fn(async t => { const { rowsPerImage, copyHeightInBlocks, copyDepth, method } = t.params; const format = 'rgba8unorm'; const copyHeight = copyHeightInBlocks * kTextureFormatInfo[format].blockHeight; const texture = t.device.createTexture({ size: { width: 4, height: 4, depthOrArrayLayers: 3 }, format, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, }); const layout = { bytesPerRow: 1024, rowsPerImage }; const copySize = { width: 0, height: copyHeight, depthOrArrayLayers: copyDepth }; const { minDataSizeOrOverestimate, copyValid } = dataBytesForCopyOrOverestimate({ layout, format, copySize, method, }); t.testRun({ texture }, layout, copySize, { dataSize: minDataSizeOrOverestimate, method, success: copyValid, }); }); g.test('copy_end_overflows_u64') .desc(`Test what happens when offset+requiredBytesInCopy overflows GPUSize64.`) .params(u => u .combine('method', kImageCopyTypes) .beginSubcases() .combineWithParams([ { bytesPerRow: 2 ** 31, rowsPerImage: 2 ** 31, depthOrArrayLayers: 1, _success: true }, // success case { bytesPerRow: 2 ** 31, rowsPerImage: 2 ** 31, depthOrArrayLayers: 16, _success: false }, // bytesPerRow * rowsPerImage * (depthOrArrayLayers - 1) overflows. ]) ) .fn(async t => { const { method, bytesPerRow, rowsPerImage, depthOrArrayLayers, _success } = t.params; const texture = t.device.createTexture({ size: [1, 1, depthOrArrayLayers], format: 'rgba8unorm', usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, }); t.testRun( { texture }, { bytesPerRow, rowsPerImage }, { width: 1, height: 1, depthOrArrayLayers }, { dataSize: 10000, method, success: _success, } ); }); g.test('required_bytes_in_copy') .desc( `Test that the min data size condition (requiredBytesInCopy) is checked correctly. - Exact requiredBytesInCopy should succeed. - requiredBytesInCopy - 1 should fail. ` ) .params(u => u .combine('method', kImageCopyTypes) .combine('format', kSizedTextureFormats) .filter(formatCopyableWithMethod) .beginSubcases() .combineWithParams([ { bytesPerRowPadding: 0, rowsPerImagePaddingInBlocks: 0 }, // no padding { bytesPerRowPadding: 0, rowsPerImagePaddingInBlocks: 6 }, // rowsPerImage padding { bytesPerRowPadding: 6, rowsPerImagePaddingInBlocks: 0 }, // bytesPerRow padding { bytesPerRowPadding: 15, rowsPerImagePaddingInBlocks: 17 }, // both paddings ]) .combineWithParams([ { copyWidthInBlocks: 3, copyHeightInBlocks: 4, copyDepth: 5, offsetInBlocks: 0 }, // standard copy { copyWidthInBlocks: 5, copyHeightInBlocks: 4, copyDepth: 3, offsetInBlocks: 11 }, // standard copy, offset > 0 { copyWidthInBlocks: 256, copyHeightInBlocks: 3, copyDepth: 2, offsetInBlocks: 0 }, // copyWidth is 256-aligned { copyWidthInBlocks: 0, copyHeightInBlocks: 4, copyDepth: 5, offsetInBlocks: 0 }, // empty copy because of width { copyWidthInBlocks: 3, copyHeightInBlocks: 0, copyDepth: 5, offsetInBlocks: 0 }, // empty copy because of height { copyWidthInBlocks: 3, copyHeightInBlocks: 4, copyDepth: 0, offsetInBlocks: 13 }, // empty copy because of depth, offset > 0 { copyWidthInBlocks: 1, copyHeightInBlocks: 4, copyDepth: 5, offsetInBlocks: 0 }, // copyWidth = 1 { copyWidthInBlocks: 3, copyHeightInBlocks: 1, copyDepth: 5, offsetInBlocks: 15 }, // copyHeight = 1, offset > 0 { copyWidthInBlocks: 5, copyHeightInBlocks: 4, copyDepth: 1, offsetInBlocks: 0 }, // copyDepth = 1 { copyWidthInBlocks: 7, copyHeightInBlocks: 1, copyDepth: 1, offsetInBlocks: 0 }, // copyHeight = 1 and copyDepth = 1 ]) // The test texture size will be rounded up from the copy size to the next valid texture size. // If the format is a depth/stencil format, its copy size must equal to subresource's size. // So filter out depth/stencil cases where the rounded-up texture size would be different from the copy size. .filter(({ format, copyWidthInBlocks, copyHeightInBlocks, copyDepth }) => { const info = kTextureFormatInfo[format]; return ( (!info.depth && !info.stencil) || (copyWidthInBlocks > 0 && copyHeightInBlocks > 0 && copyDepth > 0) ); }) ) .fn(async t => { const { offsetInBlocks, bytesPerRowPadding, rowsPerImagePaddingInBlocks, copyWidthInBlocks, copyHeightInBlocks, copyDepth, format, method, } = t.params; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); // In the CopyB2T and CopyT2B cases we need to have bytesPerRow 256-aligned, // to make this happen we align the bytesInACompleteRow value and multiply // bytesPerRowPadding by 256. const bytesPerRowAlignment = method === 'WriteTexture' ? 1 : 256; const copyWidth = copyWidthInBlocks * info.blockWidth; const copyHeight = copyHeightInBlocks * info.blockHeight; const offset = offsetInBlocks * info.bytesPerBlock; const rowsPerImage = copyHeight + rowsPerImagePaddingInBlocks * info.blockHeight; const bytesPerRow = align(bytesInACompleteRow(copyWidth, format), bytesPerRowAlignment) + bytesPerRowPadding * bytesPerRowAlignment; const copySize = { width: copyWidth, height: copyHeight, depthOrArrayLayers: copyDepth }; const layout = { offset, bytesPerRow, rowsPerImage }; const minDataSize = dataBytesForCopyOrFail({ layout, format, copySize, method }); const texture = t.createAlignedTexture(format, copySize); t.testRun({ texture }, { offset, bytesPerRow, rowsPerImage }, copySize, { dataSize: minDataSize, method, success: true, }); if (minDataSize > 0) { t.testRun({ texture }, { offset, bytesPerRow, rowsPerImage }, copySize, { dataSize: minDataSize - 1, method, success: false, }); } }); g.test('rows_per_image_alignment') .desc(`rowsPerImage is measured in multiples of block height, so has no alignment constraints.`) .params(u => u .combine('method', kImageCopyTypes) .combine('format', kSizedTextureFormats) .filter(formatCopyableWithMethod) .beginSubcases() .expand('rowsPerImage', texelBlockAlignmentTestExpanderForRowsPerImage) // Copy height is info.blockHeight, so rowsPerImage must be equal or greater than it. .filter(({ rowsPerImage, format }) => rowsPerImage >= kTextureFormatInfo[format].blockHeight) ) .fn(async t => { const { rowsPerImage, format, method } = t.params; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); const size = { width: info.blockWidth, height: info.blockHeight, depthOrArrayLayers: 1 }; const texture = t.device.createTexture({ size, format, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, }); t.testRun({ texture }, { bytesPerRow: 256, rowsPerImage }, size, { dataSize: info.bytesPerBlock, method, success: true, }); }); g.test('offset_alignment') .desc( `If texture format is not depth/stencil format, offset should be aligned with texture block. If texture format is depth/stencil format, offset should be a multiple of 4.` ) .params(u => u .combine('method', kImageCopyTypes) .combine('format', kSizedTextureFormats) .filter(formatCopyableWithMethod) .beginSubcases() .expand('offset', texelBlockAlignmentTestExpanderForOffset) ) .fn(async t => { const { format, offset, method } = t.params; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); const size = { width: info.blockWidth, height: info.blockHeight, depthOrArrayLayers: 1 }; const texture = t.device.createTexture({ size, format, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, }); let success = false; if (method === 'WriteTexture') success = true; if (info.depth || info.stencil) { if (offset % 4 === 0) success = true; } else { if (offset % info.bytesPerBlock === 0) success = true; } t.testRun({ texture }, { offset, bytesPerRow: 256 }, size, { dataSize: offset + info.bytesPerBlock, method, success, }); }); g.test('bound_on_bytes_per_row') .desc(`For all formats, verify image copy validations w.r.t bytesPerRow.`) .params(u => u .combine('method', kImageCopyTypes) .combine('format', kSizedTextureFormats) .filter(formatCopyableWithMethod) .beginSubcases() .combine('copyHeightInBlocks', [1, 2]) .combine('copyDepth', [1, 2]) .expandWithParams(p => { const info = kTextureFormatInfo[p.format]; // We currently have a built-in assumption that for all formats, 128 % bytesPerBlock === 0. // This assumption ensures that all division below results in integers. assert(128 % info.bytesPerBlock === 0); return [ // Copying exact fit with aligned bytesPerRow should work. { bytesPerRow: 256, widthInBlocks: 256 / info.bytesPerBlock, copyWidthInBlocks: 256 / info.bytesPerBlock, _success: true, }, // Copying into smaller texture when padding in bytesPerRow is enough should work unless // it is a depth/stencil typed format. { bytesPerRow: 256, widthInBlocks: 256 / info.bytesPerBlock, copyWidthInBlocks: 256 / info.bytesPerBlock - 1, _success: !(info.stencil || info.depth), }, // Unaligned bytesPerRow should not work unless the method is 'WriteTexture'. { bytesPerRow: 128, widthInBlocks: 128 / info.bytesPerBlock, copyWidthInBlocks: 128 / info.bytesPerBlock, _success: p.method === 'WriteTexture', }, { bytesPerRow: 384, widthInBlocks: 384 / info.bytesPerBlock, copyWidthInBlocks: 384 / info.bytesPerBlock, _success: p.method === 'WriteTexture', }, // When bytesPerRow is smaller than bytesInLastRow copying should fail. { bytesPerRow: 256, widthInBlocks: (2 * 256) / info.bytesPerBlock, copyWidthInBlocks: (2 * 256) / info.bytesPerBlock, _success: false, }, // When copyHeightInBlocks > 1, bytesPerRow must be specified. { bytesPerRow: undefined, widthInBlocks: 256 / info.bytesPerBlock, copyWidthInBlocks: 256 / info.bytesPerBlock, _success: !(p.copyHeightInBlocks > 1 || p.copyDepth > 1), }, ]; }) ) .fn(async t => { const { method, format, bytesPerRow, widthInBlocks, copyWidthInBlocks, copyHeightInBlocks, copyDepth, _success, } = t.params; const info = kTextureFormatInfo[format]; await t.selectDeviceOrSkipTestCase(info.feature); // We create an aligned texture using the widthInBlocks which may be different from the // copyWidthInBlocks. This allows us to test scenarios where the two may be different. const texture = t.createAlignedTexture(format, { width: widthInBlocks * info.blockWidth, height: copyHeightInBlocks * info.blockHeight, depthOrArrayLayers: copyDepth, }); const layout = { bytesPerRow, rowsPerImage: copyHeightInBlocks }; const copySize = { width: copyWidthInBlocks * info.blockWidth, height: copyHeightInBlocks * info.blockHeight, depthOrArrayLayers: copyDepth, }; const { minDataSizeOrOverestimate } = dataBytesForCopyOrOverestimate({ layout, format, copySize, method, }); t.testRun({ texture }, layout, copySize, { dataSize: minDataSizeOrOverestimate, method, success: _success, }); }); g.test('bound_on_offset') .params(u => u .combine('method', kImageCopyTypes) .beginSubcases() .combine('offsetInBlocks', [0, 1, 2]) .combine('dataSizeInBlocks', [0, 1, 2]) ) .fn(async t => { const { offsetInBlocks, dataSizeInBlocks, method } = t.params; const format = 'rgba8unorm'; const info = kTextureFormatInfo[format]; const offset = offsetInBlocks * info.bytesPerBlock; const dataSize = dataSizeInBlocks * info.bytesPerBlock; const texture = t.device.createTexture({ size: { width: 4, height: 4, depthOrArrayLayers: 1 }, format, usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST, }); const success = offset <= dataSize; t.testRun( { texture }, { offset, bytesPerRow: 0 }, { width: 0, height: 0, depthOrArrayLayers: 0 }, { dataSize, method, success } ); });
the_stack
import React from 'react'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import { FixedSizeList as List } from 'react-window'; import { noop } from 'lodash'; import PaginationFoundation, { AdapterPageList, KeyDownHandler, PageList, PaginationAdapter } from '@douyinfe/semi-foundation/pagination/foundation'; import { cssClasses, numbers } from '@douyinfe/semi-foundation/pagination/constants'; import '@douyinfe/semi-foundation/pagination/pagination.scss'; import { numbers as popoverNumbers } from '@douyinfe/semi-foundation/popover/constants'; import { IconChevronLeft, IconChevronRight } from '@douyinfe/semi-icons'; import warning from '@douyinfe/semi-foundation/utils/warning'; import ConfigContext, { ContextValue } from '../configProvider/context'; import LocaleConsumer from '../locale/localeConsumer'; import { Locale } from '../locale/interface'; import Select from '../select/index'; import InputNumber from '../inputNumber/index'; import BaseComponent from '../_base/baseComponent'; import Popover from '../popover/index'; import { Position } from '../tooltip'; const prefixCls = cssClasses.PREFIX; const { Option } = Select; export interface PaginationProps { total?: number; showTotal?: boolean; pageSize?: number; pageSizeOpts?: Array<number>; size?: 'small' | 'default'; currentPage?: number; defaultCurrentPage?: number; onPageChange?: (currentPage: number) => void; onPageSizeChange?: (newPageSize: number) => void; onChange?: (currentPage: number, pageSize: number) => void; prevText?: React.ReactNode; nextText?: React.ReactNode; showSizeChanger?: boolean; showQuickJumper?: boolean; popoverZIndex?: number; popoverPosition?: PopoverPosition; style?: React.CSSProperties; className?: string; hideOnSinglePage?: boolean; hoverShowPageSelect?: boolean; } export interface PaginationState { total: number; showTotal: boolean; currentPage: number; pageSize: number; pageList: PageList; prevDisabled: boolean; quickJumpPage: string | number; nextDisabled: boolean; restLeftPageList: number[]; restRightPageList: number[]; } export type PaginationLocale = Locale['Pagination']; export type PopoverPosition = Position; export { PageList }; export default class Pagination extends BaseComponent<PaginationProps, PaginationState> { static contextType = ConfigContext; static propTypes = { total: PropTypes.number, showTotal: PropTypes.bool, pageSize: PropTypes.number, pageSizeOpts: PropTypes.array, size: PropTypes.string, currentPage: PropTypes.number, defaultCurrentPage: PropTypes.number, onPageChange: PropTypes.func, onPageSizeChange: PropTypes.func, onChange: PropTypes.func, prevText: PropTypes.node, nextText: PropTypes.node, showSizeChanger: PropTypes.bool, popoverZIndex: PropTypes.number, popoverPosition: PropTypes.string, style: PropTypes.object, className: PropTypes.string, hideOnSinglePage: PropTypes.bool, hoverShowPageSelect: PropTypes.bool, showQuickJumper: PropTypes.bool, }; static defaultProps = { total: 1, popoverZIndex: popoverNumbers.DEFAULT_Z_INDEX, showTotal: false, pageSize: null as null, pageSizeOpts: numbers.PAGE_SIZE_OPTION, defaultCurrentPage: 1, size: 'default', onPageChange: noop, onPageSizeChange: noop, onChange: noop, showSizeChanger: false, className: '', hideOnSinglePage: false, showQuickJumper: false, }; constructor(props: PaginationProps) { super(props); this.state = { total: props.total, showTotal: props.showTotal, currentPage: props.currentPage || props.defaultCurrentPage, pageSize: props.pageSize || props.pageSizeOpts[0] || numbers.DEFAULT_PAGE_SIZE, // Use pageSize first, use the first of pageSizeOpts when not, use the default value when none pageList: [], prevDisabled: false, nextDisabled: false, restLeftPageList: [], restRightPageList: [], quickJumpPage: '', }; this.foundation = new PaginationFoundation(this.adapter); this.renderDefaultPage = this.renderDefaultPage.bind(this); this.renderSmallPage = this.renderSmallPage.bind(this); warning( Boolean(props.showSizeChanger && props.hideOnSinglePage), '[Semi Pagination] You should not use showSizeChanger and hideOnSinglePage in ths same time. At this time, hideOnSinglePage no longer takes effect, otherwise there may be a problem that the switch entry disappears' ); } context: ContextValue; get adapter(): PaginationAdapter<PaginationProps, PaginationState> { return { ...super.adapter, setPageList: (pageListState: AdapterPageList) => { const { pageList, restLeftPageList, restRightPageList } = pageListState; this.setState({ pageList, restLeftPageList, restRightPageList }); }, setDisabled: (prevIsDisabled: boolean, nextIsDisabled: boolean) => { this.setState({ prevDisabled: prevIsDisabled, nextDisabled: nextIsDisabled }); }, updateTotal: (total: number) => this.setState({ total }), updatePageSize: (pageSize: number) => this.setState({ pageSize }), updateQuickJumpPage: (quickJumpPage: string | number) => this.setState({ quickJumpPage }), // updateRestPageList: () => {}, setCurrentPage: (pageIndex: number) => { this.setState({ currentPage: pageIndex }); }, registerKeyDownHandler: (handler: KeyDownHandler) => { document.addEventListener('keydown', handler); }, unregisterKeyDownHandler: (handler: KeyDownHandler) => { document.removeEventListener('keydown', handler); }, notifyPageChange: (pageIndex: number) => { this.props.onPageChange(pageIndex); }, notifyPageSizeChange: (pageSize: number) => { this.props.onPageSizeChange(pageSize); }, notifyChange: (pageIndex: number, pageSize: number) => { this.props.onChange(pageIndex, pageSize); } }; } componentDidMount() { this.foundation.init(); } componentWillUnmount() { this.foundation.destroy(); } componentDidUpdate(prevProps: PaginationProps) { const pagerProps = { currentPage: this.props.currentPage, total: this.props.total, pageSize: this.props.pageSize, }; let pagerHasChanged = false; if (prevProps.currentPage !== this.props.currentPage) { pagerHasChanged = true; // this.foundation.updatePage(this.props.currentPage); } if (prevProps.total !== this.props.total) { pagerHasChanged = true; } if (prevProps.pageSize !== this.props.pageSize) { pagerHasChanged = true; } if (pagerHasChanged) { this.foundation.updatePage(pagerProps.currentPage, pagerProps.total, pagerProps.pageSize); } } renderPrevBtn() { const { prevText } = this.props; const { prevDisabled } = this.state; const preClassName = classNames({ [`${prefixCls}-item`]: true, [`${prefixCls}-prev`]: true, [`${prefixCls}-item-disabled`]: prevDisabled, }); return ( <li role="button" aria-disabled={prevDisabled ? true : false} aria-label="Previous" onClick={e => !prevDisabled && this.foundation.goPrev(e)} className={preClassName}> {prevText || <IconChevronLeft size="large" />} </li> ); } renderNextBtn() { const { nextText } = this.props; const { nextDisabled } = this.state; const nextClassName = classNames({ [`${prefixCls}-item`]: true, [`${prefixCls}-item-disabled`]: nextDisabled, [`${prefixCls}-next`]: true, }); return ( <li role="button" aria-disabled={nextDisabled ? true : false} aria-label="Next" onClick={e => !nextDisabled && this.foundation.goNext(e)} className={nextClassName}> {nextText || <IconChevronRight size="large" />} </li> ); } renderPageSizeSwitch(locale: PaginationLocale) { // rtl modify the default position const { direction } = this.context; const defaultPopoverPosition = direction === 'rtl' ? 'bottomRight' : 'bottomLeft'; const { showSizeChanger, popoverPosition = defaultPopoverPosition } = this.props; const { pageSize } = this.state; const switchCls = classNames(`${prefixCls}-switch`); if (!showSizeChanger) { return null; } const pageSizeText = locale.pageSize; const newPageSizeOpts = this.foundation.pageSizeInOpts(); const options = newPageSizeOpts.map((size: number) => ( <Option value={size} key={size}> <span> {`${size} `} {pageSizeText} </span> </Option> )); return ( <div className={switchCls}> <Select aria-label="Page size selector" onChange={newPageSize => this.foundation.changePageSize(newPageSize)} value={pageSize} key={pageSizeText} position={popoverPosition || 'bottomRight'} clickToHide dropdownClassName={`${prefixCls}-select-dropdown`} > {options} </Select> </div> ); } renderQuickJump(locale: PaginationLocale) { const { showQuickJumper } = this.props; const { quickJumpPage, total, pageSize } = this.state; if (!showQuickJumper) { return null; } const totalPageNum = this.foundation._getTotalPageNumber(total, pageSize); const isDisabled = totalPageNum === 1; const quickJumpCls = classNames({ [`${prefixCls}-quickjump`]: true, [`${prefixCls}-quickjump-disabled`]: isDisabled }); return ( <div className={quickJumpCls}> <span>{locale.jumpTo}</span> <InputNumber value={quickJumpPage} className={`${prefixCls}-quickjump-input-number`} hideButtons disabled={isDisabled} onBlur={(e: React.FocusEvent) => this.foundation.handleQuickJumpBlur()} onEnterPress={(e: React.KeyboardEvent) => this.foundation.handleQuickJumpEnterPress((e.target as any).value)} onChange={(v: string | number) => this.foundation.handleQuickJumpNumberChange(v)} /> <span>{locale.page}</span> </div> ); } renderPageList() { const { pageList, currentPage, restLeftPageList, restRightPageList, } = this.state; const { popoverPosition, popoverZIndex } = this.props; return pageList.map((page, i) => { const pageListClassName = classNames(`${prefixCls}-item`, { [`${prefixCls}-item-active`]: currentPage === page, // [`${prefixCls}-item-rest-opening`]: (i < 3 && isLeftRestHover && page ==='...') || (i > 3 && isRightRestHover && page === '...') }); const pageEl = ( <li key={`${page}${i}`} onClick={() => this.foundation.goPage(page, i)} className={pageListClassName} aria-label={page === '...' ? 'More' : `Page ${page}`} aria-current={currentPage === page ? "page" : false} > {page} </li> ); if (page === '...') { let content; i < 3 ? (content = restLeftPageList) : (content = restRightPageList); return ( <Popover trigger="hover" // onVisibleChange={visible=>this.handleRestHover(visible, i < 3 ? 'left' : 'right')} content={this.renderRestPageList(content)} key={`${page}${i}`} position={popoverPosition} zIndex={popoverZIndex} > {pageEl} </Popover> ); } return pageEl; }); } renderRestPageList(restList: ('...' | number)[]) { // The number of pages may be tens of thousands, here is virtualized with the help of react-window const { direction } = this.context; const className = classNames(`${prefixCls}-rest-item`); const count = restList.length; const row = (item: { index: number; style: React.CSSProperties }) => { const { index, style } = item; const page = restList[index]; return ( <div role="listitem" key={`${page}${index}`} className={className} onClick={() => this.foundation.goPage(page, index)} style={style} aria-label={`${page}`} > {page} </div> ); }; const itemHeight = 32; const listHeight = count >= 5 ? itemHeight * 5 : itemHeight * count; return ( // @ts-ignore skip type check cause react-window not update with @types/react 18 <List className={`${prefixCls}-rest-list`} itemData={restList} itemSize={itemHeight} width={78} itemCount={count} height={listHeight} style={{ direction }} > {row} </List> ); } renderSmallPage(locale: PaginationLocale) { const { className, style, hideOnSinglePage, hoverShowPageSelect, showSizeChanger } = this.props; const paginationCls = classNames(`${prefixCls}-small`, prefixCls, className); const { currentPage, total, pageSize } = this.state; const totalPageNum = Math.ceil(total / pageSize); if (totalPageNum < 2 && hideOnSinglePage && !showSizeChanger) { return null; } const pageNumbers = Array.from({ length: Math.ceil(total / pageSize) }, (v, i) => i + 1); const pageList = this.renderRestPageList(pageNumbers); const page = (<div className={`${prefixCls}-item ${prefixCls}-item-small`}>{currentPage}/{totalPageNum} </div>); return ( <div className={paginationCls} style={style}> {this.renderPrevBtn()} { hoverShowPageSelect ? ( <Popover content={pageList} > {page} </Popover> ) : page } {this.renderNextBtn()} {this.renderQuickJump(locale)} </div> ); } renderDefaultPage(locale: PaginationLocale) { const { total, pageSize } = this.state; const { showTotal, className, style, hideOnSinglePage, showSizeChanger } = this.props; const paginationCls = classNames(className, `${prefixCls}`); const showTotalCls = `${prefixCls}-total`; const totalPageNum = Math.ceil(total / pageSize); if (totalPageNum < 2 && hideOnSinglePage && !showSizeChanger) { return null; } return ( <ul className={paginationCls} style={style}> {showTotal ? ( <span className={showTotalCls}> {locale.total} {` ${Math.ceil(total / pageSize)} `} {locale.page} </span> ) : null} {this.renderPrevBtn()} {this.renderPageList()} {this.renderNextBtn()} {this.renderPageSizeSwitch(locale)} {this.renderQuickJump(locale)} </ul> ); } render() { const { size } = this.props; return ( <LocaleConsumer componentName="Pagination"> { (locale: PaginationLocale) => ( size === 'small' ? this.renderSmallPage(locale) : this.renderDefaultPage(locale) ) } </LocaleConsumer> ); } }
the_stack
namespace colibri.ui.ide.commands { export class CommandManager { private _commandIdMap: Map<string, Command>; private _commands: Command[]; private _commandMatcherMap: Map<Command, KeyMatcher[]>; private _commandHandlerMap: Map<Command, CommandHandler[]>; private _categoryMap: Map<string, ICommandCategory>; private _categories: ICommandCategory[]; constructor() { this._commands = []; this._commandIdMap = new Map(); this._commandMatcherMap = new Map(); this._commandHandlerMap = new Map(); this._categoryMap = new Map(); this._categories = []; window.addEventListener("keydown", e => { this.onKeyDown(e); }); } printTable() { let str = [ "Category", "Command", "Keys", "Description" ].join(",") + "\n"; for (const cat of this._categories) { const catName = cat.name; const commands = this._commands.filter(c => c.getCategoryId() === cat.id); for (const cmd of commands) { const keys = this.getCommandKeyString(cmd.getId()); str += [ '"' + catName + '"', '"' + cmd.getName() + '"', '"``' + keys + '``"', '"' + cmd.getTooltip() + '"' ].join(",") + "\n"; } } const elem = document.createElement("a"); elem.download = "phasereditor2d-commands-palette.csv"; elem.style.display = "none"; elem.href = "data:text/plain;charset=utf-8," + encodeURIComponent(str); document.body.appendChild(elem); elem.click(); document.body.removeChild(elem); } private onKeyDown(event: KeyboardEvent): void { if (event.isComposing) { return; } let executed = false; const args = this.makeArgs(); for (const command of this._commands) { let eventMatches = false; const matchers = this._commandMatcherMap.get(command); for (const matcher of matchers) { if (matcher.matchesKeys(event) && matcher.matchesTarget(event.target)) { eventMatches = true; break; } } if (eventMatches) { executed = this.executeHandler(command, args, event); } } if (!executed) { this.preventKeyEvent(event); } } private preventKeyEvent(event: KeyboardEvent) { const code = [ event.metaKey || event.ctrlKey ? "ctrl" : "", event.shiftKey ? "shift" : "", event.altKey ? "alt" : "", event.key.toLowerCase() ].filter(s => s.length > 0).join(" "); switch (code) { case "ctrl s": case "ctrl shift s": case "ctrl w": case "ctrl shift w": event.preventDefault(); break; } } canRunCommand(commandId: string) { const args = this.makeArgs(); const command = this.getCommand(commandId); if (command) { const handlers = this._commandHandlerMap.get(command); for (const handler of handlers) { if (this.testHandler(handler, args)) { return true; } } } return false; } private testHandler(handler: CommandHandler, args: HandlerArgs) { // const dlg = colibri.Platform.getWorkbench().getActiveDialog(); // if (dlg) { // if (!(dlg instanceof controls.dialogs.CommandDialog) && !dlg.processKeyCommands()) { // return false; // } // } return handler.test(args); } private executeHandler(command: Command, args: HandlerArgs, event: KeyboardEvent, checkContext: boolean = true): boolean { const handlers = this._commandHandlerMap.get(command); for (const handler of handlers) { if (!checkContext || this.testHandler(handler, args)) { if (event) { event.preventDefault(); } const dlg = colibri.Platform.getWorkbench().getActiveDialog(); if (dlg instanceof controls.dialogs.CommandDialog) { dlg.close(); } handler.execute(args); return true; } } return false; } addCategory(category: ICommandCategory) { this._categoryMap.set(category.id, category); this._categories.push(category); } getCategories() { return this._categories; } getCategory(id: string) { return this._categoryMap.get(id); } addCommand(cmd: Command): void { this._commands.push(cmd); this._commandIdMap.set(cmd.getId(), cmd); this._commandMatcherMap.set(cmd, []); this._commandHandlerMap.set(cmd, []); } addCommandHelper(config: { id: string, name: string, tooltip: string, category: string, icon?: controls.IImage, }) { this.addCommand(new Command(config)); } private makeArgs() { const wb = Workbench.getWorkbench(); const activeMenu = controls.Menu.getActiveMenu(); let activeElement = wb.getActiveElement(); if (activeMenu) { activeElement = activeMenu.getElement(); } // do not consider the command palette dialog as active dialog, // because we can execute any command there! const activeDialog = wb.getActiveDialog() instanceof ui.controls.dialogs.CommandDialog ? null : wb.getActiveDialog(); let activeEditor = wb.getActiveEditor(); if (activeDialog) { if (activeDialog instanceof QuickEditorDialog) { activeEditor = activeDialog.getEditor(); } else { activeEditor = null; } } return new HandlerArgs( activeDialog ? null : wb.getActivePart(), activeEditor, activeElement, activeMenu, wb.getActiveWindow(), activeDialog ); } getCommands() { const list = [...this._commands]; list.sort((a, b) => { return ((a.getCategoryId() || "") + a.getName()) .localeCompare((b.getCategoryId() || "") + b.getName()); }); return list; } getActiveCommands() { return this.getCommands().filter( command => this.canRunCommand(command.getId()) ); } getCommand(id: string) { const command = this._commandIdMap.get(id); if (!command) { console.error(`Command ${id} not found.`); } return command; } getCommandKeyString(commandId: string) { const command = this.getCommand(commandId); if (command) { const matchers = this._commandMatcherMap.get(command); if (matchers && matchers.length > 0) { const matcher = matchers[0]; return matcher.getKeyString(); } } return ""; } executeCommand(commandId: string, checkContext: boolean = true) { const command = this.getCommand(commandId); if (command) { this.executeHandler(command, this.makeArgs(), null, checkContext); } } addKeyBinding(commandId: string, matcher: KeyMatcher): void { const command = this.getCommand(commandId); if (command) { this._commandMatcherMap.get(command).push(matcher); } } addKeyBindingHelper(commandId: string, config: IKeyMatcherConfig) { this.addKeyBinding(commandId, new KeyMatcher(config)); } addHandler(commandId: string, handler: CommandHandler) { const command = this.getCommand(commandId); if (command) { this._commandHandlerMap.get(command).push(handler); } } addHandlerHelper( commandId: string, testFunc: (args: HandlerArgs) => boolean, executeFunc: (args: HandlerArgs) => void) { this.addHandler(commandId, new CommandHandler({ testFunc: testFunc, executeFunc: executeFunc })); } add( args: { command?: ICommandConfig, handler?: IHandlerConfig, keys?: IKeyMatcherConfig }, commandId?: string) { if (args.command) { this.addCommandHelper(args.command); } const id = args.command ? args.command.id : commandId; if (args.handler) { this.addHandler(id, new CommandHandler(args.handler)); } if (args.keys) { this.addKeyBinding(id, new KeyMatcher(args.keys)); } } } }
the_stack
export const ZipkinPom = `<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright 2015-2019 The OpenZipkin Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>io.zipkin</groupId> <artifactId>zipkin-parent</artifactId> <version>2.16.2-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>zipkin</module> <module>zipkin-tests</module> <module>zipkin-lens</module> <module>zipkin-junit</module> <module>benchmarks</module> <module>zipkin-storage</module> <module>zipkin-collector</module> <module>zipkin-server</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.resourceEncoding>UTF-8</project.build.resourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- default bytecode version for src/main --> <main.java.version>1.7</main.java.version> <main.signature.artifact>java17</main.signature.artifact> <!-- override to set exclusions per-project --> <errorprone.args /> <errorprone.version>2.3.3</errorprone.version> <main.basedir>x</main.basedir> <!-- This allows you to test feature branches with jitpack --> <armeria.groupId>com.linecorp.armeria</armeria.groupId> <armeria.version>0.90.3</armeria.version> <!-- This should only be used in tests, and be careful to avoid >= v20 apis --> <guava.version>28.0-jre</guava.version> <!-- only used for proto interop testing --> <wire.version>3.0.0-alpha01</wire.version> <unpack-proto.directory>x/test/proto</unpack-proto.directory> <brave.version>5.6.11</brave.version> <cassandra-driver-core.version>3.7.2</cassandra-driver-core.version> <okhttp.version>3.14.2</okhttp.version> <jooq.version>3.11.12</jooq.version> <micrometer.version>1.2.0</micrometer.version> <spring-boot.version>2.1.7.RELEASE</spring-boot.version> <!-- MySQL connector is GPL, even if it has an OSS exception. https://www.mysql.com/about/legal/licensing/foss-exception/ MariaDB has a friendlier license, LGPL, which is less scary in audits. --> <mariadb-java-client.version>2.4.3</mariadb-java-client.version> <!-- Java 8 dep, which is ok as zipkin-mysql is Java 8 anyway --> <HikariCP.version>3.3.1</HikariCP.version> <log4j.version>2.12.1</log4j.version> <junit.version>4.12</junit.version> <junit.jupiter.version>5.5.1</junit.jupiter.version> <powermock.version>2.0.2</powermock.version> <!-- Up to v2.27.0 of mockito has a conflict https://github.com/mockito/mockito/issues/1606 java.lang.NoSuchMethodError: net.bytebuddy.dynamic.loading.MultipleParentClassLoader$Builder.appendMostSpecific(Ljava/util/Collection;)Lnet/bytebuddy/dynamic/loading/MultipleParentClassLoader$Builder --> <mockito.version>2.23.4</mockito.version> <assertj.version>3.13.1</assertj.version> <awaitility.version>3.1.6</awaitility.version> <hamcrest.version>1.3</hamcrest.version> <testcontainers.version>1.12.0</testcontainers.version> <auto-value.version>1.6.5</auto-value.version> <animal-sniffer-maven-plugin.version>1.18</animal-sniffer-maven-plugin.version> <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version> <maven-deploy-plugin.version>3.0.0-M1</maven-deploy-plugin.version> <maven-install-plugin.version>3.0.0-M1</maven-install-plugin.version> <maven-release-plugin.version>2.5.3</maven-release-plugin.version> <maven-source-plugin.version>3.1.0</maven-source-plugin.version> <maven-javadoc-plugin.version>3.1.1</maven-javadoc-plugin.version> <license-maven-plugin.version>3.0</license-maven-plugin.version> <maven-jar-plugin.version>3.1.2</maven-jar-plugin.version> <maven-shade-plugin.version>3.2.1</maven-shade-plugin.version> <maven-failsafe-plugin.version>3.0.0-M3</maven-failsafe-plugin.version> <maven-enforcer-plugin.version>3.0.0-M2</maven-enforcer-plugin.version> <git-commit-id.version>3.0.0</git-commit-id.version> </properties> <name>Zipkin (Parent)</name> <description>Zipkin (Parent)</description> <url>https://github.com/openzipkin/zipkin</url> <inceptionYear>2015</inceptionYear> <organization> <name>OpenZipkin</name> <url>http://zipkin.io/</url> </organization> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url> <distribution>repo</distribution> </license> </licenses> <scm> <url>https://github.com/openzipkin/zipkin</url> <connection>scm:git:https://github.com/openzipkin/zipkin.git</connection> <developerConnection>scm:git:https://github.com/openzipkin/zipkin.git</developerConnection> <tag>HEAD</tag> </scm> <!-- Developer section is needed for Maven Central, but doesn't need to include each person --> <developers> <developer> <id>openzipkin</id> <name>OpenZipkin Gitter</name> <url>https://gitter.im/openzipkin/zipkin</url> </developer> </developers> <distributionManagement> <repository> <id>bintray</id> <url>https://api.bintray.com/maven/openzipkin/maven/zipkin/;publish=1</url> </repository> <snapshotRepository> <id>jfrog-snapshots</id> <url>https://oss.jfrog.org/artifactory/oss-snapshot-local</url> </snapshotRepository> </distributionManagement> <issueManagement> <system>Github</system> <url>https://github.com/openzipkin/zipkin/issues</url> </issueManagement> <dependencyManagement> <!-- TODO: remove override on next spring-boot version --> <dependencies> <dependency> <groupId>com.fasterxml.jackson</groupId> <artifactId>jackson-bom</artifactId> <version>2.9.9.20190807</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.jooq</groupId> <artifactId>jooq</artifactId> <version>x</version> </dependency> <dependency> <groupId>armeria.groupId</groupId> <artifactId>armeria-spring-boot-autoconfigure</artifactId> <version>armeria.version</version> <exclusions> <exclusion> <groupId>armeria.groupId</groupId> <artifactId>armeria-logback</artifactId> </exclusion> <exclusion> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>{armeria.groupId}</groupId> <artifactId>armeria-tomcat</artifactId> <version>{armeria.version}</version> </dependency> <!-- Makes sure spring doesn't eagerly bind tomcat or slf4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>{spring-boot.version}</version> <exclusions> <exclusion> <groupId>org.hibernate.validator</groupId> <artifactId>*</artifactId> </exclusion> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <version>{spring-boot.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- End spring-boot-dependencies overrides --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>{okhttp.version}</version> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>mockwebserver</artifactId> <version>{okhttp.version}</version> </dependency> <dependency> <groupId>com.google.auto.value</groupId> <artifactId>auto-value-annotations</artifactId> <version>{auto-value.version}</version> </dependency> <dependency> <groupId>com.google.auto.value</groupId> <artifactId>auto-value</artifactId> <version>{auto-value.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>{log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>{log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-jul</artifactId> <version>{log4j.version}</version> </dependency> <!-- used by our non-spring boot tests who have a slf4j dependency --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>{log4j.version}</version> </dependency> <!-- used by zipkin-server and zipkin-autoconfigure due to Spring Boot using slf4j --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-to-slf4j</artifactId> <version>{log4j.version}</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-1.2-api</artifactId> <version>{log4j.version}</version> </dependency> <!-- for testing flink --> <dependency> <groupId>com.esotericsoftware.kryo</groupId> <artifactId>kryo</artifactId> <version>2.24.0</version> </dependency> <!-- Internal classes used in SpanBytesDecoder.JSON_V[12] --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>{junit.version}</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>{junit.jupiter.version}</version> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>{junit.jupiter.version}</version> </dependency> <!-- Current versions of JUnit5 provide the above junit-jupiter artifact for convenience but we may still have transitive dependencies on these older artifacts and have to make sure they're all using the same version. --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>{junit.jupiter.version}</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>{junit.jupiter.version}</version> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>{assertj.version}</version> </dependency> <dependency> <groupId>org.awaitility</groupId> <artifactId>awaitility</artifactId> <version>{awaitility.version}</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>{mockito.version}</version> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers</artifactId> <version>{testcontainers.version}</version> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>mysql</artifactId> <version>{testcontainers.version}</version> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>{mariadb-java-client.version}</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>{HikariCP.version}</version> </dependency> <!-- Don't bring in brave's transitive dep on zipkin --> <dependency> <groupId>io.zipkin.brave</groupId> <artifactId>brave</artifactId> <version>{brave.version}</version> <exclusions> <exclusion> <groupId>io.zipkin.zipkin2</groupId> <artifactId>zipkin</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.zipkin.proto3</groupId> <artifactId>zipkin-proto3</artifactId> <version>0.2.1</version> </dependency> <dependency> <groupId>com.squareup.wire</groupId> <artifactId>wire-runtime</artifactId> <version>{wire.version}</version> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <pluginManagement> <plugins> <!-- mvn -N io.takari:maven:wrapper generates the ./mvnw script --> <plugin> <groupId>io.takari</groupId> <artifactId>maven</artifactId> <version>0.7.6</version> <configuration> <maven>3.6.1</maven> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>{maven-compiler-plugin.version}</version> <inherited>true</inherited> <configuration> <!-- Retrolambda will rewrite lambdas as Java 6 bytecode --> <source>1.8</source> <target>1.8</target> <!-- or die! com.sun.tools.javac.api.JavacTool --> <fork>true</fork> <showWarnings>true</showWarnings> </configuration> </plugin> <plugin> <artifactId>maven-javadoc-plugin</artifactId> <version>{maven-javadoc-plugin.version}</version> <configuration> <failOnError>false</failOnError> <excludePackageNames>zipkin2.internal,zipkin2.internal.*</excludePackageNames> <!-- hush pedantic warnings: we don't put param and return on everything! --> <doclint>none</doclint> </configuration> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>{maven-jar-plugin.version}</version> <configuration> <archive> <!-- prevents huge pom file from also being added to the jar under META-INF/maven --> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> </plugin> <plugin> <artifactId>maven-shade-plugin</artifactId> <version>{maven-shade-plugin.version}</version> </plugin> <!-- Need to block import of shaded packages in bnd.bnd as maven bundle plugin analyzes the unshaded jar --> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <version>4.2.0</version> <configuration> <obrRepository>NONE</obrRepository> <instructions> <Bundle-SymbolicName>{project.groupId}.{project.artifactId}</Bundle-SymbolicName> </instructions> </configuration> <executions> <execution> <phase>process-classes</phase> <goals> <goal>manifest</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <versionRange>[3.7,)</versionRange> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </pluginExecutionFilter> <action> <configurator> <id>org.eclipse.m2e.jdt.javaConfigurator</id> </configurator> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> <!-- The below plugins compile protobuf stubs in the indicated source tree --> <plugin> <artifactId>maven-dependency-plugin</artifactId> <executions> <!-- wire-maven-plugin cannot get proto definitions from dependencies: this will --> <execution> <id>unpack-proto</id> <phase>generate-sources</phase> <goals> <goal>unpack-dependencies</goal> </goals> <configuration> <includeArtifactIds>zipkin-proto3</includeArtifactIds> <includes>**/*.proto</includes> <outputDirectory>{unpack-proto.directory}</outputDirectory> </configuration> </execution> </executions> </plugin> <plugin> <groupId>com.squareup.wire</groupId> <artifactId>wire-maven-plugin</artifactId> <version>{wire.version}</version> <executions> <execution> <phase>generate-sources</phase> <goals> <goal>generate-sources</goal> </goals> <configuration> <protoSourceDirectory>{unpack-proto.directory}</protoSourceDirectory> <includes> <include>zipkin.proto3.*</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </pluginManagement> <plugins> <!-- Top-level to ensure our server can use JDK 1.8 (by checking we don't accidentally use later apis) --> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>animal-sniffer-maven-plugin</artifactId> <version>{animal-sniffer-maven-plugin.version}</version> <configuration> <signature> <groupId>org.codehaus.mojo.signature</groupId> <artifactId>{main.signature.artifact}</artifactId> <version>1.0</version> </signature> </configuration> <executions> <execution> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>{maven-failsafe-plugin.version}</version> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <version>{maven-failsafe-plugin.version}</version> <executions> <execution> <id>integration-test</id> <goals> <goal>integration-test</goal> </goals> </execution> <execution> <id>verify</id> <goals> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>{maven-install-plugin.version}</version> </plugin> <!-- Uploads occur as a last step (which also adds checksums) --> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>{maven-deploy-plugin.version}</version> </plugin> <plugin> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin</artifactId> <version>{license-maven-plugin.version}</version> <configuration> <!-- session.executionRootDirectory resolves properly even with nested modules --> <header>{main.basedir}/src/etc/header.txt</header> <mapping> <!-- Don't use javadoc style as this makes code formatters break it by adding tags! --> <java>SLASHSTAR_STYLE</java> <kt>SLASHSTAR_STYLE</kt> <jsx>SLASHSTAR_STYLE</jsx> <bnd>SCRIPT_STYLE</bnd> <ejs>XML_STYLE</ejs> <scss>DOUBLESLASH_STYLE</scss> </mapping> <excludes> <exclude>.travis.yml</exclude> <exclude>.editorconfig</exclude> <exclude>.gitattributes</exclude> <exclude>.gitignore</exclude> <exclude>.mvn/**</exclude> <exclude>mvnw*</exclude> <exclude>etc/header.txt</exclude> <exclude>**/.idea/**</exclude> <exclude>**/node_modules/**</exclude> <exclude>**/.babelrc</exclude> <exclude>**/.bowerrc</exclude> <exclude>**/.editorconfig</exclude> <exclude>**/.eslintrc</exclude> <exclude>**/.eslintrc</exclude> <exclude>**/.eslintrc.js</exclude> <exclude>**/testdata/**/*.json</exclude> <exclude>**/test/data/**/*.json</exclude> <exclude>LICENSE</exclude>&gt; <exclude>**/*.md</exclude> <exclude>**/src/main/resources/banner.txt</exclude> <exclude>**/src/main/resources/*.yml</exclude> <exclude>**/spring.factories</exclude> <!-- Cassandra integration tests break when license headers are present --> <exclude>**/src/main/resources/*.cql</exclude> <exclude>kafka_*/**</exclude> <exclude>**/nohup.out</exclude> <exclude>src/test/resources/**</exclude> <exclude>**/generated/**</exclude> </excludes> <strictCheck>true</strictCheck> </configuration> <dependencies> <dependency> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin-git</artifactId> <version>{license-maven-plugin.version}</version> </dependency> </dependencies> <executions> <execution> <goals> <goal>check</goal> </goals> <phase>compile</phase> </execution> </executions> </plugin> <plugin> <artifactId>maven-release-plugin</artifactId> <version>{maven-release-plugin.version}</version> <configuration> <useReleaseProfile>false</useReleaseProfile> <releaseProfiles>release</releaseProfiles> <autoVersionSubmodules>true</autoVersionSubmodules> <!-- to match zipkin-scala (openzipkin/zipkin) --> <tagNameFormat>@{project.version}</tagNameFormat> </configuration> </plugin> <plugin> <groupId>io.zipkin.centralsync-maven-plugin</groupId> <artifactId>centralsync-maven-plugin</artifactId> <version>0.1.1</version> <configuration> <packageName>zipkin</packageName> </configuration> </plugin> <plugin> <artifactId>maven-enforcer-plugin</artifactId> <version>{maven-enforcer-plugin.version}</version> <executions> <execution> <id>enforce-java</id> <goals> <goal>enforce</goal> </goals> <configuration> <rules> <requireJavaVersion> <!-- don't JDK 12 until https://github.com/google/error-prone/issues/1106 --> <version>[11,12)</version> </requireJavaVersion> </rules> </configuration> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>error-prone-9+</id> <activation> <jdk>[9,)</jdk> <activeByDefault>false</activeByDefault> </activation> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <executions> <execution> <!-- only use errorprone on main source tree --> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> <configuration> <forceJavacCompilerUse>true</forceJavacCompilerUse> <compilerArgs> <arg>-XDcompilePolicy=simple</arg> <arg>-Xplugin:ErrorProne {errorprone.args}</arg> </compilerArgs> <annotationProcessorPaths> <processorPath> <groupId>com.google.errorprone</groupId> <artifactId>error_prone_core</artifactId> <version>{errorprone.version}</version> </processorPath> <!-- auto-value is placed here eventhough not needed for all projects as configuring along with errorprone is tricky in subprojects --> <processorPath> <groupId>com.google.auto.value</groupId> <artifactId>auto-value</artifactId> <version>{auto-value.version}</version> </processorPath> </annotationProcessorPaths> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>release</id> <build> <plugins> <!-- disable license plugin since it should have already checked things and #1512 --> <plugin> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin</artifactId> <executions> <execution> <phase>none</phase> </execution> </executions> </plugin> <!-- Creates source jar --> <plugin> <artifactId>maven-source-plugin</artifactId> <version>{maven-source-plugin.version}</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <!-- Creates javadoc jar, skipping internal classes --> <plugin> <artifactId>maven-javadoc-plugin</artifactId> <version>{maven-javadoc-plugin.version}</version> <configuration> <failOnError>false</failOnError> <excludePackageNames>zipkin2.internal,zipkin2.internal.*</excludePackageNames> <!-- hush pedantic warnings: we don't put param and return on everything! --> <doclint>none</doclint> </configuration> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> <phase>package</phase> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>netbeans</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <!-- NetBeans --> <org-netbeans-modules-editor-indent.CodeStyle.usedProfile>project</org-netbeans-modules-editor-indent.CodeStyle.usedProfile> <org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width>2</org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width> <org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab>2</org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab> <org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>2</org-netbeans-modules-editor-indent.CodeStyle.project.tab-size> <org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>110</org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width> <org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs>true</org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs> </properties> </profile> </profiles> </project>`;
the_stack
import React from "react" import { I18nManager, Image, InteractionManager, PanResponderInstance, StyleSheet, TouchableOpacity, View, } from "react-native" import tinycolor from "tinycolor2" import { HsvColor, IPickerProps, Point2D } from "./typeHelpers" import { createPanResponder, rotatePoint } from "./utils" function makeRotationKey(props: ITrianglePickerProps, angle: number) { const { rotationHackFactor } = props if (rotationHackFactor < 1) { return undefined } const key = Math.floor(angle * rotationHackFactor) return `r${key}` } export interface ITrianglePickerProps extends IPickerProps { rotationHackFactor?: number; hideControls?: boolean; } export type ITrianglePickerState = { color: HsvColor; pickerSize: number; }; export class TriangleColorPicker extends React.PureComponent< ITrianglePickerProps, ITrianglePickerState > { private _layout: { width: number; height: number; x: number; y: number }; private _pageX: number; private _pageY: number; private _isRTL: boolean; private _pickerResponder: PanResponderInstance; private _changingHColor: boolean; public static defaultProps: ITrianglePickerProps = { rotationHackFactor: 100, }; constructor(props: ITrianglePickerProps, ctx: any) { super(props, ctx) const state = { color: { h: 0, s: 1, v: 1 }, pickerSize: null, } if (props.oldColor) { state.color = tinycolor(props.oldColor).toHsv() } if (props.defaultColor) { state.color = tinycolor(props.defaultColor).toHsv() } this.state = state this._layout = { width: 0, height: 0, x: 0, y: 0 } this._pageX = 0 this._pageY = 0 this._onLayout = this._onLayout.bind(this) this._onSValueChange = this._onSValueChange.bind(this) this._onVValueChange = this._onVValueChange.bind(this) this._onColorSelected = this._onColorSelected.bind(this) this._onOldColorSelected = this._onOldColorSelected.bind(this) this._isRTL = I18nManager.isRTL this._pickerResponder = createPanResponder({ onStart: ({ x, y }) => { const { s, v } = this._computeColorFromTriangle({ x, y }) this._changingHColor = s > 1 || s < 0 || v > 1 || v < 0 this._handleColorChange({ x, y }) return true }, onMove: this._handleColorChange, }) } _getColor() { const passedColor = typeof this.props.color === "string" ? tinycolor(this.props.color).toHsv() : this.props.color return passedColor || this.state.color } _onColorSelected() { const { onColorSelected } = this.props const color = tinycolor(this._getColor()).toHexString() onColorSelected && onColorSelected(color) } _onOldColorSelected() { const { oldColor, onOldColorSelected } = this.props const color = tinycolor(oldColor) this.setState({ color: color.toHsv() }) onOldColorSelected && onOldColorSelected(color.toHexString()) } _onSValueChange(s) { const { h, v } = this._getColor() this._onColorChange({ h, s, v }) } _onVValueChange(v) { const { h, s } = this._getColor() this._onColorChange({ h, s, v }) } _onColorChange(color) { this.setState({ color }) if (this.props.onColorChange) { this.props.onColorChange(color) } } _onLayout(l) { this._layout = l.nativeEvent.layout const { width, height } = this._layout const pickerSize = Math.min(width, height) if (this.state.pickerSize !== pickerSize) { this.setState({ pickerSize }) } // layout.x, layout.y is always 0 // we always measure because layout is the same even though picker is moved on the page InteractionManager.runAfterInteractions(() => { // measure only after (possible) animation ended this.refs.pickerContainer && (this.refs.pickerContainer as any).measure( (x, y, width, height, pageX, pageY) => { // picker position in the screen this._pageX = pageX this._pageY = pageY } ) }) } _computeHValue(x: number, y: number) { const mx = this.state.pickerSize / 2 const my = this.state.pickerSize / 2 const dx = x - mx const dy = y - my const rad = Math.atan2(dx, dy) + Math.PI + Math.PI / 2 return ((rad * 180) / Math.PI) % 360 } _hValueToRad(deg: number) { const rad = (deg * Math.PI) / 180 return rad - Math.PI - Math.PI / 2 } getColor() { return tinycolor(this._getColor()).toHexString() } _handleColorChange = ({ x, y }: Point2D) => { if (this._changingHColor) { this._handleHColorChange({ x, y }) } else { this._handleSVColorChange({ x, y }) } return true }; _handleHColorChange({ x, y }: Point2D) { const { s, v } = this._getColor() const marginLeft = (this._layout.width - this.state.pickerSize) / 2 const marginTop = (this._layout.height - this.state.pickerSize) / 2 const relativeX = x - this._pageX - marginLeft const relativeY = y - this._pageY - marginTop const h = this._computeHValue(relativeX, relativeY) this._onColorChange({ h, s, v }) } _handleSVColorChange({ x, y }) { const { h, s: rawS, v: rawV } = this._computeColorFromTriangle({ x, y }) const s = Math.min(Math.max(0, rawS), 1) const v = Math.min(Math.max(0, rawV), 1) this._onColorChange({ h, s, v }) } _normalizeTriangleTouch(s, v, sRatio) { const CORNER_ZONE_SIZE = 0.12 // relative size to be considered as corner zone const NORMAL_MARGIN = 0.1 // relative triangle margin to be considered as touch in triangle const CORNER_MARGIN = 0.05 // relative triangle margin to be considered as touch in triangle in corner zone let margin = NORMAL_MARGIN const posNS = v > 0 ? 1 - (1 - s) * sRatio : 1 - s * sRatio const negNS = v > 0 ? s * sRatio : (1 - s) * sRatio const ns = s > 1 ? posNS : negNS // normalized s value according to ratio and s value const rightCorner = s > 1 - CORNER_ZONE_SIZE && v > 1 - CORNER_ZONE_SIZE const leftCorner = ns < 0 + CORNER_ZONE_SIZE && v > 1 - CORNER_ZONE_SIZE const topCorner = ns < 0 + CORNER_ZONE_SIZE && v < 0 + CORNER_ZONE_SIZE if (rightCorner) { return { s, v } } if (leftCorner || topCorner) { margin = CORNER_MARGIN } // color normalization according to margin s = s < 0 && ns > 0 - margin ? 0 : s s = s > 1 && ns < 1 + margin ? 1 : s v = v < 0 && v > 0 - margin ? 0 : v v = v > 1 && v < 1 + margin ? 1 : v return { s, v } } /** * Computes s, v from position (x, y). If position is outside of triangle, * it will return invalid values (greater than 1 or lower than 0) */ _computeColorFromTriangle({ x, y }) { const { pickerSize } = this.state const { triangleHeight, triangleWidth } = getPickerProperties(pickerSize) const left = pickerSize / 2 - triangleWidth / 2 const top = pickerSize / 2 - (2 * triangleHeight) / 3 // triangle relative coordinates const marginLeft = (this._layout.width - this.state.pickerSize) / 2 const marginTop = (this._layout.height - this.state.pickerSize) / 2 const relativeX = x - this._pageX - marginLeft - left const relativeY = y - this._pageY - marginTop - top // rotation const { h } = this._getColor() const deg = (h - 330 + 360) % 360 // starting angle is 330 due to comfortable calculation const rad = (deg * Math.PI) / 180 const center = { x: triangleWidth / 2, y: (2 * triangleHeight) / 3, } const rotated = rotatePoint({ x: relativeX, y: relativeY }, rad, center) const line = (triangleWidth * rotated.y) / triangleHeight const margin = triangleWidth / 2 - ((triangleWidth / 2) * rotated.y) / triangleHeight const s = (rotated.x - margin) / line const v = rotated.y / triangleHeight // normalize const normalized = this._normalizeTriangleTouch( s, v, line / triangleHeight ) return { h, s: normalized.s, v: normalized.v } } render() { const { pickerSize } = this.state const { oldColor, style } = this.props const color = this._getColor() const { h } = color const angle = this._hValueToRad(h) const selectedColor = tinycolor(color).toHexString() const indicatorColor = tinycolor({ h, s: 1, v: 1 }).toHexString() const computed = makeComputedStyles({ pickerSize, selectedColorHsv: color, indicatorColor, angle, isRTL: this._isRTL, }) // Hack for https://github.com/instea/react-native-color-picker/issues/17 const rotationHack = makeRotationKey(this.props, angle) return ( <View style={style}> <View onLayout={this._onLayout} ref="pickerContainer" style={styles.pickerContainer} > {!pickerSize ? null : ( <View> <View key={rotationHack} style={[styles.triangleContainer, computed.triangleContainer]} > <View style={[ styles.triangleUnderlayingColor, computed.triangleUnderlayingColor, ]} /> <Image style={[computed.triangleImage]} source={require("../resources/hsv_triangle_mask.png")} /> </View> <View {...this._pickerResponder.panHandlers} style={[computed.picker]} collapsable={false} > <Image source={require("../resources/color-circle.png")} resizeMode="contain" style={[styles.pickerImage]} /> <View key={rotationHack} style={[styles.pickerIndicator, computed.pickerIndicator]} > <View style={[ styles.pickerIndicatorTick, computed.pickerIndicatorTick, ]} /> </View> <View style={[styles.svIndicator, computed.svIndicator]} /> </View> </View> )} </View> {this.props.hideControls == true ? null : ( <View style={[styles.colorPreviews, computed.colorPreviews]}> {oldColor && ( <TouchableOpacity style={[styles.colorPreview, { backgroundColor: oldColor }]} onPress={this._onOldColorSelected} activeOpacity={0.7} /> )} <TouchableOpacity style={[styles.colorPreview, { backgroundColor: selectedColor }]} onPress={this._onColorSelected} activeOpacity={0.7} /> </View> )} </View> ) } } function getPickerProperties(pickerSize) { const indicatorPickerRatio = 42 / 510 // computed from picker image const originalIndicatorSize = indicatorPickerRatio * pickerSize const indicatorSize = originalIndicatorSize const pickerPadding = originalIndicatorSize / 3 const triangleSize = pickerSize - 6 * pickerPadding const triangleRadius = triangleSize / 2 const triangleHeight = (triangleRadius * 3) / 2 const triangleWidth = 2 * triangleRadius * Math.sqrt(3 / 4) // pythagorean theorem return { triangleSize, triangleRadius, triangleHeight, triangleWidth, indicatorPickerRatio, indicatorSize, pickerPadding, } } const makeComputedStyles = ({ indicatorColor, angle, pickerSize, selectedColorHsv, isRTL, }) => { const { triangleSize, triangleHeight, triangleWidth, indicatorSize, pickerPadding, } = getPickerProperties(pickerSize) /* ===== INDICATOR ===== */ const indicatorRadius = pickerSize / 2 - indicatorSize / 2 - pickerPadding const mx = pickerSize / 2 const my = pickerSize / 2 const dx = Math.cos(angle) * indicatorRadius const dy = Math.sin(angle) * indicatorRadius /* ===== TRIANGLE ===== */ const triangleTop = pickerPadding * 3 const triangleLeft = pickerPadding * 3 const triangleAngle = -angle + Math.PI / 3 /* ===== SV INDICATOR ===== */ const markerColor = "rgba(0,0,0,0.8)" const { s, v, h } = selectedColorHsv const svIndicatorSize = 18 const svY = v * triangleHeight const margin = triangleWidth / 2 - v * (triangleWidth / 2) const svX = s * (triangleWidth - 2 * margin) + margin const svIndicatorMarginLeft = (pickerSize - triangleWidth) / 2 const svIndicatorMarginTop = (pickerSize - (4 * triangleHeight) / 3) / 2 const deg = (h - 330 + 360) % 360 // starting angle is 330 due to comfortable calculation const rad = (deg * Math.PI) / 180 const center = { x: pickerSize / 2, y: pickerSize / 2 } const notRotatedPoint = { x: svIndicatorMarginTop + svY, y: svIndicatorMarginLeft + svX, } const svIndicatorPoint = rotatePoint(notRotatedPoint, rad, center) return { picker: { padding: pickerPadding, width: pickerSize, height: pickerSize, }, pickerIndicator: { top: mx + dx - indicatorSize / 2, [isRTL ? "right" : "left"]: my + dy - indicatorSize / 2, width: indicatorSize, height: indicatorSize, transform: [ { rotate: -angle + "rad", }, ], }, pickerIndicatorTick: { height: indicatorSize / 2, backgroundColor: markerColor, }, svIndicator: { top: svIndicatorPoint.x - svIndicatorSize / 2, [isRTL ? "right" : "left"]: svIndicatorPoint.y - svIndicatorSize / 2, width: svIndicatorSize, height: svIndicatorSize, borderRadius: svIndicatorSize / 2, borderColor: markerColor, }, triangleContainer: { width: triangleSize, height: triangleSize, transform: [ { rotate: triangleAngle + "rad", }, ], top: triangleTop, left: triangleLeft, }, triangleImage: { width: triangleWidth, height: triangleHeight, }, triangleUnderlayingColor: { left: (triangleSize - triangleWidth) / 2, borderLeftWidth: triangleWidth / 2, borderRightWidth: triangleWidth / 2, borderBottomWidth: triangleHeight, borderBottomColor: indicatorColor, }, colorPreviews: { height: pickerSize * 0.1, // responsive height }, } } const styles = StyleSheet.create({ pickerContainer: { flex: 1, alignItems: "center", justifyContent: "center", }, pickerImage: { flex: 1, width: null, height: null, }, pickerIndicator: { position: "absolute", alignItems: "center", justifyContent: "center", }, triangleContainer: { position: "absolute", alignItems: "center", }, triangleUnderlayingColor: { position: "absolute", top: 0, width: 0, height: 0, backgroundColor: "transparent", borderStyle: "solid", borderLeftColor: "transparent", borderRightColor: "transparent", }, pickerAlignment: { alignItems: "center", }, svIndicator: { position: "absolute", borderWidth: 4, }, pickerIndicatorTick: { width: 5, }, colorPreviews: { flexDirection: "row", }, colorPreview: { flex: 1, }, })
the_stack
import { CAM_VIDEO_SIMULCAST_ENCODINGS } from '@xrengine/engine/src/networking/constants/VideoConstants' import { MessageTypes } from '@xrengine/engine/src/networking/enums/MessageTypes' import { MediaStreams } from '@xrengine/engine/src/networking/systems/MediaStreamSystem' import { DataProducer, Transport as MediaSoupTransport } from 'mediasoup-client/lib/types' import { EngineEvents } from '@xrengine/engine/src/ecs/classes/EngineEvents' import { Network } from '@xrengine/engine/src/networking/classes/Network' import { SocketWebRTCClientTransport } from './SocketWebRTCClientTransport' let networkTransport: any export async function createDataProducer( channel = 'default', type = 'raw', customInitInfo: any = {} ): Promise<DataProducer | Error> { networkTransport = Network.instance.transport as any const sendTransport = channel === 'instance' ? networkTransport.instanceSendTransport : networkTransport.channelSendTransport // else if (MediaStreams.instance.dataProducers.get(channel)) return Promise.reject(new Error('Data channel already exists!')) const dataProducer = await sendTransport.produceData({ appData: { data: customInitInfo }, ordered: false, label: channel, maxPacketLifeTime: 3000, // maxRetransmits: 3, protocol: type // sub-protocol for type of data to be transmitted on the channel e.g. json, raw etc. maybe make type an enum rather than string }) // dataProducer.on("open", () => { // networkTransport.dataProducer.send(JSON.stringify({ info: 'init' })); // }); dataProducer.on('transportclose', () => { Network.instance.dataProducers.delete(channel) if (channel === 'instance') networkTransport.instanceDataProducer?.close() else networkTransport.channelDataProducer?.close() }) if (channel === 'instance') networkTransport.instanceDataProducer = dataProducer else networkTransport.channelDataProducer = dataProducer Network.instance.dataProducers.set(channel, networkTransport.dataProducer) return Promise.resolve(networkTransport.dataProducer) } // utility function to create a transport and hook up signaling logic // appropriate to the transport's direction export async function createTransport(direction: string, channelType?: string, channelId?: string) { networkTransport = Network.instance.transport as any const request = channelType === 'instance' && channelId == null ? networkTransport.instanceRequest : networkTransport.channelRequest // ask the server to create a server-side transport object and send // us back the info we need to create a client-side transport let transport console.log('Requesting transport creation', direction, channelType, channelId) if (request != null) { const { transportOptions } = await request(MessageTypes.WebRTCTransportCreate.toString(), { direction, sctpCapabilities: networkTransport.mediasoupDevice.sctpCapabilities, channelType: channelType, channelId: channelId }) if (direction === 'recv') transport = await networkTransport.mediasoupDevice.createRecvTransport(transportOptions) else if (direction === 'send') transport = await networkTransport.mediasoupDevice.createSendTransport(transportOptions) else throw new Error(`bad transport 'direction': ${direction}`) // mediasoup-client will emit a connect event when media needs to // start flowing for the first time. send dtlsParameters to the // server, then call callback() on success or errback() on failure. transport.on('connect', async ({ dtlsParameters }: any, callback: () => void, errback: () => void) => { const connectResult = await request(MessageTypes.WebRTCTransportConnect.toString(), { transportId: transportOptions.id, dtlsParameters }) if (connectResult.error) { console.log('Transport connect error') console.log(connectResult.error) return errback() } callback() }) if (direction === 'send') { transport.on( 'produce', async ({ kind, rtpParameters, appData }: any, callback: (arg0: { id: any }) => void, errback: () => void) => { let paused = false if (appData.mediaTag === 'cam-video') paused = MediaStreams.instance.videoPaused else if (appData.mediaTag === 'cam-audio') paused = MediaStreams.instance.audioPaused // tell the server what it needs to know from us in order to set // up a server-side producer object, and get back a // producer.id. call callback() on success or errback() on // failure. const { error, id } = await request(MessageTypes.WebRTCSendTrack.toString(), { transportId: transportOptions.id, kind, rtpParameters, paused, appData }) if (error) { errback() console.log(error) return } callback({ id }) } ) transport.on( 'producedata', async (parameters: any, callback: (arg0: { id: any }) => void, errback: () => void) => { const { sctpStreamParameters, label, protocol, appData } = parameters const { error, id } = await request(MessageTypes.WebRTCProduceData, { transportId: transport.id, sctpStreamParameters, label, protocol, appData }) if (error) { console.log(error) errback() return } return callback({ id }) } ) } // any time a transport transitions to closed, // failed, or disconnected, leave the and reset transport.on('connectionstatechange', async (state: string) => { if (networkTransport.leaving !== true && (state === 'closed' || state === 'failed' || state === 'disconnected')) { EngineEvents.instance.dispatchEvent({ type: SocketWebRTCClientTransport.EVENTS.INSTANCE_DISCONNECTED }) console.error('Transport', transport, ' transitioned to state', state) console.error( 'If this occurred unexpectedly shortly after joining a world, check that the gameserver nodegroup has public IP addresses.' ) console.log('Waiting 5 seconds to make a new transport') setTimeout(async () => { console.log( 'Re-creating transport', direction, channelType, channelId, ' after unexpected closing/fail/disconnect' ) await createTransport(direction, channelType, channelId) console.log('Re-created transport', direction, channelType, channelId) }, 5000) // await request(MessageTypes.WebRTCTransportClose.toString(), {transportId: transport.id}); } // if (networkTransport.leaving !== true && state === 'connected' && transport.direction === 'recv') { // console.log('requesting current producers for', channelType, channelId) // await request(MessageTypes.WebRTCRequestCurrentProducers.toString(), { // channelType: channelType, // channelId: channelId // }) // } }) transport.channelType = channelType transport.channelId = channelId return Promise.resolve(transport) } else return Promise.resolve() } export async function initReceiveTransport( channelType: string, channelId?: string ): Promise<MediaSoupTransport | Error> { networkTransport = Network.instance.transport as any let newTransport if (channelType === 'instance' && channelId == null) newTransport = networkTransport.instanceRecvTransport = await createTransport('recv', channelType) else newTransport = networkTransport.channelRecvTransport = await createTransport('recv', channelType, channelId) return Promise.resolve(newTransport) } export async function initSendTransport(channelType: string, channelId?: string): Promise<MediaSoupTransport | Error> { networkTransport = Network.instance.transport as any let newTransport if (channelType === 'instance' && channelId == null) newTransport = networkTransport.instanceSendTransport = await createTransport('send', channelType) else newTransport = networkTransport.channelSendTransport = await createTransport('send', channelType, channelId) return Promise.resolve(newTransport) } export async function initRouter(channelType: string, channelId?: string): Promise<void> { networkTransport = Network.instance.transport as any const request = networkTransport.channelRequest await request(MessageTypes.InitializeRouter.toString(), { channelType: channelType, channelId: channelId }) return Promise.resolve() } export async function configureMediaTransports( mediaTypes: string[], channelType: string, channelId?: string ): Promise<boolean> { networkTransport = Network.instance.transport as any if (mediaTypes.indexOf('video') > -1 && MediaStreams.instance.videoStream == null) { await MediaStreams.instance.startCamera() if (MediaStreams.instance.videoStream == null) { console.warn('Video stream is null, camera must have failed or be missing') return false } } if (mediaTypes.indexOf('audio') > -1 && MediaStreams.instance.audioStream == null) { await MediaStreams.instance.startMic() if (MediaStreams.instance.audioStream == null) { console.warn('Audio stream is null, mic must have failed or be missing') return false } } //This probably isn't needed anymore with chanenls handling all audio and video, but left it in and commented //just in case. // if ( // networkTransport.channelSendTransport == null || // networkTransport.channelSendTransport.closed === true || // networkTransport.channelSendTransport.connectionState === 'disconnected' // ) { // await initRouter(channelType, channelId) // await Promise.all([initSendTransport(channelType, channelId), initReceiveTransport(channelType, channelId)]) // } return true } export async function createCamVideoProducer(channelType: string, channelId?: string): Promise<void> { if (MediaStreams.instance.videoStream !== null && networkTransport.videoEnabled === true) { if (networkTransport.channelSendTansport == null) { await new Promise((resolve) => { const waitForTransportReadyInterval = setInterval(() => { if (networkTransport.channelSendTransport) { clearInterval(waitForTransportReadyInterval) resolve(true) } }, 100) }) } const transport = networkTransport.channelSendTransport try { MediaStreams.instance.camVideoProducer = await transport.produce({ track: MediaStreams.instance.videoStream.getVideoTracks()[0], encodings: CAM_VIDEO_SIMULCAST_ENCODINGS, appData: { mediaTag: 'cam-video', channelType: channelType, channelId: channelId } }) if (MediaStreams.instance.videoPaused) await MediaStreams.instance?.camVideoProducer.pause() else await resumeProducer(MediaStreams.instance.camVideoProducer) } catch (err) { console.log('error producing video', err) } } } export async function createCamAudioProducer(channelType: string, channelId?: string): Promise<void> { if (MediaStreams.instance.audioStream !== null) { //To control the producer audio volume, we need to clone the audio track and connect a Gain to it. //This Gain is saved on MediaStreamSystem so it can be accessed from the user's component and controlled. const audioTrack = MediaStreams.instance.audioStream.getAudioTracks()[0] const ctx = new AudioContext() const src = ctx.createMediaStreamSource(new MediaStream([audioTrack])) const dst = ctx.createMediaStreamDestination() const gainNode = ctx.createGain() gainNode.gain.value = 1 ;[src, gainNode, dst].reduce((a, b) => a && (a.connect(b) as any)) MediaStreams.instance.audioGainNode = gainNode MediaStreams.instance.audioStream.removeTrack(audioTrack) MediaStreams.instance.audioStream.addTrack(dst.stream.getAudioTracks()[0]) // same thing for audio, but we can use our already-created if (networkTransport.channelSendTansport == null) { await new Promise((resolve) => { const waitForTransportReadyInterval = setInterval(() => { if (networkTransport.channelSendTransport) { clearInterval(waitForTransportReadyInterval) resolve(true) } }, 100) }) } const transport = networkTransport.channelSendTransport try { // Create a new transport for audio and start producing MediaStreams.instance.camAudioProducer = await transport.produce({ track: MediaStreams.instance.audioStream.getAudioTracks()[0], appData: { mediaTag: 'cam-audio', channelType: channelType, channelId: channelId } }) if (MediaStreams.instance.audioPaused) MediaStreams.instance?.camAudioProducer.pause() else await resumeProducer(MediaStreams.instance.camAudioProducer) } catch (err) { console.log('error producing audio', err) } } } export async function endVideoChat(options: { leftParty?: boolean; endConsumers?: boolean }): Promise<boolean> { if (Network.instance != null && Network.instance.transport != null) { try { networkTransport = Network.instance.transport as any const request = networkTransport.channelRequest const socket = networkTransport.channelSocket if (MediaStreams.instance?.camVideoProducer) { if (socket.connected === true && typeof request === 'function') await request(MessageTypes.WebRTCCloseProducer.toString(), { producerId: MediaStreams.instance?.camVideoProducer.id }) await MediaStreams.instance?.camVideoProducer?.close() } if (MediaStreams.instance?.camAudioProducer) { if (socket.connected === true && typeof request === 'function') await request(MessageTypes.WebRTCCloseProducer.toString(), { producerId: MediaStreams.instance?.camAudioProducer.id }) await MediaStreams.instance?.camAudioProducer?.close() } if (MediaStreams.instance?.screenVideoProducer) { if (socket.connected === true && typeof request === 'function') await request(MessageTypes.WebRTCCloseProducer.toString(), { producerId: MediaStreams.instance.screenVideoProducer.id }) await MediaStreams.instance.screenVideoProducer?.close() } if (MediaStreams.instance?.screenAudioProducer) { if (socket.connected === true && typeof request === 'function') await request(MessageTypes.WebRTCCloseProducer.toString(), { producerId: MediaStreams.instance.screenAudioProducer.id }) await MediaStreams.instance.screenAudioProducer?.close() } if (options?.endConsumers === true) { MediaStreams.instance?.consumers.map(async (c) => { if (request && typeof request === 'function') await request(MessageTypes.WebRTCCloseConsumer.toString(), { consumerId: c.id }) await c.close() }) } if (networkTransport.channelRecvTransport != null && networkTransport.channelRecvTransport.closed !== true) await networkTransport.channelRecvTransport.close() if (networkTransport.channelSendTransport != null && networkTransport.channelSendTransport.closed !== true) await networkTransport.channelSendTransport.close() resetProducer() return true } catch (err) { console.log('EndvideoChat error') console.log(err) } } } export function resetProducer(): void { if (MediaStreams) { if (MediaStreams.instance.audioStream) { const audioTracks = MediaStreams.instance.audioStream?.getTracks() audioTracks.forEach((track) => track.stop()) } if (MediaStreams.instance.videoStream) { const videoTracks = MediaStreams.instance.videoStream?.getTracks() videoTracks.forEach((track) => track.stop()) } MediaStreams.instance.camVideoProducer = null MediaStreams.instance.camAudioProducer = null MediaStreams.instance.screenVideoProducer = null MediaStreams.instance.screenAudioProducer = null MediaStreams.instance.audioStream = null MediaStreams.instance.videoStream = null MediaStreams.instance.localScreen = null // MediaStreams.instance.instance?.consumers = []; } } export function setRelationship(channelType: string, channelId: string): void { networkTransport = Network.instance.transport as any networkTransport.channelType = channelType networkTransport.channelId = channelId } export async function subscribeToTrack(peerId: string, mediaTag: string, channelType: string, channelId: string) { networkTransport = Network.instance.transport as any const request = networkTransport.channelRequest if (request != null) { // if we do already have a consumer, we shouldn't have called this method let consumer = MediaStreams.instance?.consumers.find( (c: any) => c.appData.peerId === peerId && c.appData.mediaTag === mediaTag ) // ask the server to create a server-side consumer object and send us back the info we need to create a client-side consumer const consumerParameters = await request(MessageTypes.WebRTCReceiveTrack.toString(), { mediaTag, mediaPeerId: peerId, rtpCapabilities: networkTransport.mediasoupDevice.rtpCapabilities, channelType: channelType, channelId: channelId }) // Only continue if we have a valid id if (consumerParameters?.id == null) return consumer = await networkTransport.channelRecvTransport.consume({ ...consumerParameters, appData: { peerId, mediaTag, channelType }, paused: true }) const existingConsumer = MediaStreams.instance?.consumers?.find( (c) => c?.appData?.peerId === peerId && c?.appData?.mediaTag === mediaTag ) if (existingConsumer == null) { MediaStreams.instance?.consumers.push(consumer) EngineEvents.instance.dispatchEvent({ type: MediaStreams.EVENTS.TRIGGER_UPDATE_CONSUMERS }) // okay, we're ready. let's ask the peer to send us media await resumeConsumer(consumer) } else if (existingConsumer?._track?.muted) { await closeConsumer(existingConsumer) console.log('consumers before splice', MediaStreams.instance?.consumers) MediaStreams.instance?.consumers.splice(existingConsumerIndex, 0, consumer) console.log('consumers after splice', MediaStreams.instance?.consumers) EngineEvents.instance.dispatchEvent({ type: MediaStreams.EVENTS.TRIGGER_UPDATE_CONSUMERS }) // okay, we're ready. let's ask the peer to send us media await resumeConsumer(consumer) } else await closeConsumer(consumer) } } export async function unsubscribeFromTrack(peerId: any, mediaTag: any) { const consumer = MediaStreams.instance?.consumers.find( (c) => c.appData.peerId === peerId && c.appData.mediaTag === mediaTag ) await closeConsumer(consumer) } export async function pauseConsumer(consumer: { appData: { peerId: any; mediaTag: any }; id: any; pause: () => any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCPauseConsumer.toString(), { consumerId: consumer.id }) await consumer.pause() } export async function resumeConsumer(consumer: { appData: { peerId: any; mediaTag: any } id: any resume: () => any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCResumeConsumer.toString(), { consumerId: consumer.id }) await consumer.resume() } export async function pauseProducer(producer: { appData: { mediaTag: any }; id: any; pause: () => any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCPauseProducer.toString(), { producerId: producer.id }) await producer.pause() } export async function resumeProducer(producer: { appData: { mediaTag: any }; id: any; resume: () => any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCResumeProducer.toString(), { producerId: producer.id }) await producer.resume() } export async function globalMuteProducer(producer: { id: any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCPauseProducer.toString(), { producerId: producer.id, globalMute: true }) } export async function globalUnmuteProducer(producer: { id: any }) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCResumeProducer.toString(), { producerId: producer.id }) } export async function closeConsumer(consumer: any) { await (Network.instance.transport as any).channelRequest(MessageTypes.WebRTCCloseConsumer.toString(), { consumerId: consumer.id }) await consumer.close() MediaStreams.instance.consumers = MediaStreams.instance?.consumers.filter( (c: any) => !(c.id === consumer.id) ) as any[] } export async function leave(instance: boolean, kicked?: boolean): Promise<boolean> { if (Network.instance?.transport != null) { try { networkTransport = Network.instance.transport as any networkTransport.leaving = true const socket = networkTransport.channelSocket const request = networkTransport.channelRequest if (kicked !== true && request && socket.connected === true) { // close everything on the server-side (transports, producers, consumers) const result = await Promise.race([ await request(MessageTypes.LeaveWorld.toString()), new Promise((resolve, reject) => { setTimeout(() => reject(new Error('Connect timed out')), 10000) }) ]) if (result?.error) console.error(result.error) EngineEvents.instance.dispatchEvent({ type: EngineEvents.EVENTS.LEAVE_WORLD }) } networkTransport.leaving = false networkTransport.left = true //Leaving the world should close all transports from the server side. //This will also destroy all the associated producers and consumers. //All we need to do on the client is null all references. networkTransport.channelRecvTransport = null networkTransport.channelSendTransport = null networkTransport.lastPollSyncData = {} if (MediaStreams) { if (MediaStreams.instance.audioStream) { const audioTracks = MediaStreams.instance.audioStream?.getTracks() audioTracks.forEach((track) => track.stop()) } if (MediaStreams.instance.videoStream) { const videoTracks = MediaStreams.instance.videoStream?.getTracks() videoTracks.forEach((track) => track.stop()) } MediaStreams.instance.camVideoProducer = null MediaStreams.instance.camAudioProducer = null MediaStreams.instance.screenVideoProducer = null MediaStreams.instance.screenAudioProducer = null MediaStreams.instance.videoStream = null MediaStreams.instance.audioStream = null MediaStreams.instance.localScreen = null MediaStreams.instance.consumers = [] } if (socket && socket.close) socket.close() return true } catch (err) { console.log('Error with leave()') console.log(err) networkTransport.leaving = false } } } // async startScreenshare(): Promise<boolean> { // console.log("start screen share"); // // // make sure we've joined the and that we have a sending transport // if (!transport.sendTransport) transport.sendTransport = await transport.createTransport("send"); // // // get a screen share track // MediaStreamSystem.localScreen = await (navigator.mediaDevices as any).getDisplayMedia( // { video: true, audio: true } // ); // // // create a producer for video // MediaStreamSystem.screenVideoProducer = await transport.sendTransport.produce({ // track: MediaStreamSystem.localScreen.getVideoTracks()[0], // encodings: [], // TODO: Add me // appData: { mediaTag: "screen-video" } // }); // // // create a producer for audio, if we have it // if (MediaStreamSystem.localScreen.getAudioTracks().length) { // MediaStreamSystem.screenAudioProducer = await transport.sendTransport.produce({ // track: MediaStreamSystem.localScreen.getAudioTracks()[0], // appData: { mediaTag: "screen-audio" } // }); // } // // // handler for screen share stopped event (triggered by the // // browser's built-in screen sharing ui) // MediaStreamSystem.screenVideoProducer.track.onended = async () => { // console.log("screen share stopped"); // await MediaStreamSystem.screenVideoProducer.pause(); // // const { error } = await transport.request(MessageTypes.WebRTCCloseProducer.toString(), { // producerId: MediaStreamSystem.screenVideoProducer.id // }); // // await MediaStreamSystem.screenVideoProducer.close(); // MediaStreamSystem.screenVideoProducer = null; // if (MediaStreamSystem.screenAudioProducer) { // const { error: screenAudioProducerError } = await transport.request(MessageTypes.WebRTCCloseProducer.toString(), { // producerId: MediaStreamSystem.screenAudioProducer.id // }); // // await MediaStreamSystem.screenAudioProducer.close(); // MediaStreamSystem.screenAudioProducer = null; // } // }; // return true; // }
the_stack
import { extend } from '@syncfusion/ej2-base'; import { Grid } from '../../../src/grid/base/grid'; import { Filter } from '../../../src/grid/actions/filter'; import { Edit } from '../../../src/grid/actions/edit'; import { Group } from '../../../src/grid/actions/group'; import { Sort } from '../../../src/grid/actions/sort'; import { DetailRow } from '../../../src/grid/actions/detail-row'; import { Reorder } from '../../../src/grid/actions/reorder'; import { Freeze } from '../../../src/grid/actions/freeze'; import { Toolbar } from '../../../src/grid/actions/toolbar'; import { Selection } from '../../../src/grid/actions/selection'; import { createGrid, destroy } from '../base/specutil.spec'; import { data } from '../base/datasource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { Logger, ItemDetails, detailLists } from '../../../src/grid/actions/logger'; import { VirtualScroll } from '../../../src/grid/actions/virtual-scroll'; import {profile , inMB, getMemoryProfile} from '../base/common.spec'; Grid.Inject(Filter, Selection, Group, Edit, Sort, Reorder, Toolbar, DetailRow, Freeze, Logger, VirtualScroll); describe('Logger module', () => { let dataSource: Function = (): Object[] => { let datasrc: Object[] = []; for (let i: number = 0; i < 15; i++) { datasrc.push(extend({}, {}, data[i], true)); } return datasrc; }; let module_missing: ItemDetails = detailLists['module_missing']; let promise_enabled: ItemDetails = detailLists['promise_enabled']; let primary_column_missing: ItemDetails = detailLists['primary_column_missing']; let selection_key_missing: ItemDetails = detailLists['selection_key_missing']; let actionfailure: ItemDetails = detailLists['actionfailure']; let locale_missing: ItemDetails = detailLists['locale_missing']; let action_disabled_column: ItemDetails = detailLists['action_disabled_column']; let limitation: ItemDetails = detailLists['limitation']; let check_datasource_columns: ItemDetails = detailLists['check_datasource_columns']; let virtual_height: ItemDetails = detailLists['virtual_height']; let exporting_begin: ItemDetails = detailLists['exporting_begin']; let exporting_complete: ItemDetails = detailLists['exporting_complete']; let resize_min_max: ItemDetails = detailLists['resize_min_max']; let grid_sort_comparer: ItemDetails = detailLists['grid_sort_comparer']; let grid_remote_edit: ItemDetails = detailLists['grid_remote_edit']; let foreign_key_failure: ItemDetails = detailLists['foreign_key_failure']; let initial_action: ItemDetails = detailLists['initial_action']; let frozen_rows_columns: ItemDetails = detailLists['frozen_rows_columns']; let column_type_missing: ItemDetails = detailLists['column_type_missing']; let datasource_syntax_mismatch: ItemDetails = detailLists['datasource_syntax_mismatch']; describe('Logger render => ', () => { let gridObj: Grid; let actionBegin: () => void; let actionComplete: () => void; beforeAll((done: Function) => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) } gridObj = createGrid( { dataSource: dataSource(), allowFiltering: true, allowGrouping: true, locale: 'fr-FR', allowSorting: true, frozenRows: 2, selectionSettings: {persistSelection: true}, editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Normal', showConfirmDialog: false, showDeleteConfirmDialog: false }, toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'], allowPaging: true, height: 400, columns: [ { field: 'OrderID', type: 'number', visible: true, validationRules: { required: true } }, { field: 'CustomerID', type: 'string', allowGrouping: false, allowReordering: false, allowSorting: false, allowFiltering: false }, { field: 'EmployeeID', type: 'number', allowEditing: false }, { field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' }, { field: 'ShipCity' } ], dataStateChange:(args:any) =>{ }, actionBegin: actionBegin, actionComplete: actionComplete }, done); }); it('Chceck promise_enabled test', () => { promise_enabled.check({}, gridObj); promise_enabled.generateMessage({}, gridObj); expect(true).toBeTruthy(); }); it('Chceck primary_column_missing test', () => { expect(primary_column_missing.check({}, gridObj).success).toBeTruthy(); }); it('Chceck selection_key_missing test', () => { expect(selection_key_missing.check({}, gridObj).success).toBeTruthy(); }); it('Chceck locale_missing test', () => { expect(locale_missing.check({}, gridObj).success).toBeTruthy(); }); it('Chceck action_disabled_column test', () => { gridObj.groupColumn('CustomerID'); gridObj.reorderColumns('CustomerID', 'OrderID'); gridObj.sortColumn('CustomerID', 'Ascending'); expect(action_disabled_column.check({moduleName: 'group', columnName: 'CustomerID' }, gridObj).success).toBeTruthy(); expect(action_disabled_column.check({moduleName: 'reorder', column: 'CustomerID' }, gridObj).success).toBeTruthy(); expect(action_disabled_column.check({moduleName: 'reorder', column: 'CustomerID', destColumn: 'OrderID' }, gridObj).success).toBeTruthy(); expect(action_disabled_column.check({moduleName: 'filter', columnName: 'CustomerID' }, gridObj).success).toBeTruthy(); expect(action_disabled_column.check({moduleName: 'sort', columnName: 'CustomerID' }, gridObj).success).toBeTruthy(); }); it('Check actionfailure test', () => { expect(actionfailure.generateMessage({error: 'Format options'}, gridObj)).not.toBeNull(); expect(actionfailure.generateMessage({error: 'Format'}, gridObj)).not.toBeNull(); expect(actionfailure.generateMessage({error: {error: {}}}, gridObj)).not.toBeNull(); expect(actionfailure.check({}, gridObj).success).toBeTruthy(); }); it('Check limitation test', () => { expect(limitation.generateMessage({error: {}}, gridObj, {name: 'freeze'})).not.toBeNull(); expect(limitation.generateMessage({error: {}}, gridObj, {name: 'virtualization'})).not.toBeNull(); expect(limitation.generateMessage({name: 'scroll'}, gridObj, {name: 'scroll'})).not.toBeNull(); gridObj.setProperties({allowGrouping: false, frozenRows: 0}, true); expect(limitation.check('freeze', gridObj).success).toBeFalsy(); expect(limitation.check('virtualization', gridObj).success).toBeFalsy(); expect(limitation.check('scroll', gridObj).success).toBeFalsy(); }); it('Check virtual_height test', () => { expect(virtual_height.check({}, gridObj).success).toBeFalsy(); expect(virtual_height.generateMessage({}, gridObj)).not.toBeNull(); }); it('Check exporting_begin test', () => { expect(exporting_begin.check({}, gridObj).success).toBeTruthy(); expect(exporting_begin.generateMessage({}, gridObj, {})).not.toBeNull(); }); it('Check exporting_complete test', () => { expect(exporting_complete.check({}, gridObj).success).toBeTruthy(); expect(exporting_complete.generateMessage({}, gridObj, {})).not.toBeNull(); }); it('Check resize_min_max test', () => { expect(resize_min_max.check({column: {}}, gridObj).success).toBeFalsy(); expect(resize_min_max.generateMessage({}, gridObj)).not.toBeNull(); }); it('Check grid_sort_comparer test', () => { expect(grid_sort_comparer.check({}, gridObj).success).toBeFalsy(); expect(grid_sort_comparer.generateMessage({}, gridObj)).not.toBeNull(); }); it('Check grid_remote_edit test', () => { expect(grid_remote_edit.check({result: []}, gridObj).success).toBeTruthy(); expect(grid_remote_edit.generateMessage({}, gridObj)).not.toBeNull(); }); it('Check foreign_key_failure test', () => { expect(foreign_key_failure.check({}, gridObj).success).toBeTruthy(); expect(foreign_key_failure.generateMessage({}, gridObj)).not.toBeNull(); }); it('Chceck initial_action test', () => { expect(initial_action.check({moduleName: 'group', columnName: 'CustomerID' }, gridObj).success).toBeTruthy(); expect(initial_action.check({moduleName: 'sort', column: 'CustomerID' }, gridObj).success).toBeTruthy(); expect(initial_action.check({moduleName: 'filter', column: 'CustomerID', destColumn: 'OrderID' }, gridObj).success).toBeTruthy(); expect(initial_action.generateMessage({}, gridObj, {fn: 'checking'})).not.toBeNull(); }); it('Chceck frozen_rows_columns test', () => { expect(frozen_rows_columns.check({}, gridObj).success).toBeFalsy(); expect(frozen_rows_columns.generateMessage({}, gridObj)).not.toBeNull(); gridObj.setProperties({frozenColumns: 8, frozenRows: 20}, true); expect(frozen_rows_columns.generateMessage({}, gridObj)).not.toBeNull(); }); it('Chceck column_type_missing test', () => { expect(column_type_missing.check({column: gridObj.getColumnByField('OrderID')}, gridObj).success).toBeFalsy(); expect(column_type_missing.generateMessage({}, gridObj, 'OrderID')).not.toBeNull(); }); it('Check check_datasource_columns test', () => { gridObj.setProperties({columns: []}, true); gridObj.getDataModule().dataManager.adaptor.beforeSend = () => true; (<any>gridObj).loggerModule.patchadaptor(); gridObj.getDataModule().dataManager.adaptor.beforeSend(); (<any>gridObj).loggerModule.destroy(); expect(check_datasource_columns.check({}, gridObj).success).toBeFalsy(); expect(check_datasource_columns.generateMessage({}, gridObj)).not.toBeNull(); }); it('datasource_format_mismatch test', () => { expect(datasource_syntax_mismatch.check({dataState:gridObj}, gridObj).success).toBeTruthy(); expect(datasource_syntax_mismatch.generateMessage({dataState:gridObj}, gridObj)).not.toBeNull(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); afterAll(() => { let index; // tslint:disable-next-line:no-unused-expression gridObj.getInjectedModules().some((m: Function, i: number) => { index = i; return m.prototype.getModuleName() === Logger.prototype.getModuleName(); }) && gridObj.getInjectedModules().splice(index, 1); destroy(gridObj); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_quotebookingservice_Information { interface tab__66B308CF_F821_44E8_997A_88593F18144F_Sections { _66B308CF_F821_44E8_997A_88593F18144F_COLUMN_3_SECTION_1: DevKit.Controls.Section; _66B308CF_F821_44E8_997A_88593F18144F_SECTION_3: DevKit.Controls.Section; _8F706D5B_6CB5_4A94_A35A_8AADCF2D33F4: DevKit.Controls.Section; } interface tab__66B308CF_F821_44E8_997A_88593F18144F extends DevKit.Controls.ITab { Section: tab__66B308CF_F821_44E8_997A_88593F18144F_Sections; } interface Tabs { _66B308CF_F821_44E8_997A_88593F18144F: tab__66B308CF_F821_44E8_997A_88593F18144F; } interface Body { Tab: Tabs; /** Shows the actual duration of service. */ msdyn_duration: DevKit.Controls.Integer; /** Shows the total cost amount of the service. It is calculated as (Unit Cost) * Duration */ msdyn_EstimatedCostAmount: DevKit.Controls.Money; /** Shows the total sales amount of the service. */ msdyn_EstimatedSalesAmount: DevKit.Controls.Money; /** Enter the amount charged as a minimum charge. */ msdyn_minimumchargeamount: DevKit.Controls.Money; /** Enter the duration of up to how long the minimum charge applies. */ msdyn_minimumchargeduration: DevKit.Controls.Integer; /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Unique identifier for Quote Booking Setup associated with Quote Booking Service. */ msdyn_quotebookingsetup: DevKit.Controls.Lookup; /** Unique identifier for Product/Service associated with Quote Booking Service. */ msdyn_Service: DevKit.Controls.Lookup; /** The unit that determines the pricing for this service when Price List is set */ msdyn_unit: DevKit.Controls.Lookup; /** Enter the amount you wish to charge the customer per unit. This field is optional. */ msdyn_unitamount: DevKit.Controls.Money; /** Shows the estimated cost amount per unit. */ msdyn_unitcostamount: DevKit.Controls.Money; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } } class Formmsdyn_quotebookingservice_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_quotebookingservice_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_quotebookingservice_Information */ Body: DevKit.Formmsdyn_quotebookingservice_Information.Body; } class msdyn_quotebookingserviceApi { /** * DynamicsCrm.DevKit msdyn_quotebookingserviceApi * @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; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** 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; /** The currency that will be used to charge this service */ msdyn_currency: DevKit.WebApi.MoneyValue; /** Value of the Currency in base currency. */ msdyn_currency_Base: DevKit.WebApi.MoneyValueReadonly; /** Customer Asset related to this Service */ msdyn_customerasset: DevKit.WebApi.LookupValue; /** Shows the actual duration of service. */ msdyn_duration: DevKit.WebApi.IntegerValue; /** Enter the duration you want to bill the customer for. By default, this will default to the same value as the "Duration" field. */ msdyn_durationtobill: DevKit.WebApi.IntegerValue; /** Shows the total cost amount of the service. It is calculated as (Unit Cost) * Duration */ msdyn_EstimatedCostAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimate Cost Amount in base currency. */ msdyn_estimatedcostamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total sales amount of the service. */ msdyn_EstimatedSalesAmount: DevKit.WebApi.MoneyValue; /** Value of the Estimate Sales Amount in base currency. */ msdyn_estimatedsalesamount_Base: DevKit.WebApi.MoneyValueReadonly; /** For internal use only. */ msdyn_Internalflags: DevKit.WebApi.StringValue; msdyn_iscopied: DevKit.WebApi.BooleanValue; /** Shows the order of this service within the agreement services. */ msdyn_lineorder: DevKit.WebApi.IntegerValue; /** Enter the amount charged as a minimum charge. */ msdyn_minimumchargeamount: DevKit.WebApi.MoneyValue; /** Value of the Minimum Charge Amount in base currency. */ msdyn_minimumchargeamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter the duration of up to how long the minimum charge applies. */ msdyn_minimumchargeduration: DevKit.WebApi.IntegerValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Optionally set Price List that will determine the pricing for this service on the Work Order */ msdyn_pricelist: DevKit.WebApi.LookupValue; /** Unique identifier for Quote associated with Quote Booking Service. */ msdyn_quote: DevKit.WebApi.LookupValue; /** The Quote Booking Incident related to this service */ msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** Unique identifier for entity instances */ msdyn_quotebookingserviceId: DevKit.WebApi.GuidValue; /** Unique identifier for Quote Booking Setup associated with Quote Booking Service. */ msdyn_quotebookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier for Product/Service associated with Quote Booking Service. */ msdyn_Service: DevKit.WebApi.LookupValue; /** The unit that determines the pricing for this service when Price List is set */ msdyn_unit: DevKit.WebApi.LookupValue; /** Enter the amount you wish to charge the customer per unit. This field is optional. */ msdyn_unitamount: DevKit.WebApi.MoneyValue; /** Value of the Unit Amount in base currency. */ msdyn_unitamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the estimated cost amount per unit. */ msdyn_unitcostamount: DevKit.WebApi.MoneyValue; /** Value of the Unit Cost in base currency. */ msdyn_unitcostamount_Base: DevKit.WebApi.MoneyValueReadonly; /** 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 Quote Booking Service */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Quote Booking Service */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_quotebookingservice { 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'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
declare module '~chai~assertion-error/main' { // Type definitions for assertion-error 1.0.0 // Project: https://github.com/chaijs/assertion-error // Definitions by: Bart van der Schoor <https://github.com/Bartvds> // Definitions: https://github.com/borisyankov/DefinitelyTyped export class AssertionError implements Error { constructor(message: string, props?: any, ssf?: Function); public name: string; public message: string; public showDiff: boolean; public stack: string; /** * Allow errors to be converted to JSON for static transfer. * * @param {Boolean} include stack (default: `true`) * @return {Object} object that can be `JSON.stringify` */ public toJSON(stack: boolean): Object; } } declare module '~chai~assertion-error' { import alias = require('~chai~assertion-error/main'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Assert.d.ts declare module '~chai/lib/Assert' { export interface AssertStatic extends Assert { } export interface Assert { /** * @param expression Expression to test for truthiness. * @param message Message to display on error. */ (expression: any, message?: string): void; (expression: any, messageCallback: () => string): void; fail(actual?: any, expected?: any, msg?: string, operator?: string): void; ok(val: any, msg?: string): void; isOk(val: any, msg?: string): void; notOk(val: any, msg?: string): void; isNotOk(val: any, msg?: string): void; equal(act: any, exp: any, msg?: string): void; notEqual(act: any, exp: any, msg?: string): void; strictEqual(act: any, exp: any, msg?: string): void; notStrictEqual(act: any, exp: any, msg?: string): void; deepEqual(act: any, exp: any, msg?: string): void; notDeepEqual(act: any, exp: any, msg?: string): void; isTrue(val: any, msg?: string): void; isFalse(val: any, msg?: string): void; isNotTrue(val: any, msg?: string): void; isNotFalse(val: any, msg?: string): void; isNull(val: any, msg?: string): void; isNotNull(val: any, msg?: string): void; isUndefined(val: any, msg?: string): void; isDefined(val: any, msg?: string): void; isNaN(val: any, msg?: string): void; isNotNaN(val: any, msg?: string): void; isAbove(val: number, abv: number, msg?: string): void; isBelow(val: number, blw: number, msg?: string): void; isAtLeast(val: number, atlst: number, msg?: string): void; isAtMost(val: number, atmst: number, msg?: string): void; isFunction(val: any, msg?: string): void; isNotFunction(val: any, msg?: string): void; isObject(val: any, msg?: string): void; isNotObject(val: any, msg?: string): void; isArray(val: any, msg?: string): void; isNotArray(val: any, msg?: string): void; isString(val: any, msg?: string): void; isNotString(val: any, msg?: string): void; isNumber(val: any, msg?: string): void; isNotNumber(val: any, msg?: string): void; isBoolean(val: any, msg?: string): void; isNotBoolean(val: any, msg?: string): void; typeOf(val: any, type: string, msg?: string): void; notTypeOf(val: any, type: string, msg?: string): void; instanceOf(val: any, type: Function, msg?: string): void; notInstanceOf(val: any, type: Function, msg?: string): void; include(exp: string, inc: any, msg?: string): void; include(exp: any[], inc: any, msg?: string): void; include(exp: Object, inc: Object, msg?: string): void; notInclude(exp: string, inc: any, msg?: string): void; notInclude(exp: any[], inc: any, msg?: string): void; match(exp: any, re: RegExp, msg?: string): void; notMatch(exp: any, re: RegExp, msg?: string): void; property(obj: Object, prop: string, msg?: string): void; notProperty(obj: Object, prop: string, msg?: string): void; deepProperty(obj: Object, prop: string, msg?: string): void; notDeepProperty(obj: Object, prop: string, msg?: string): void; propertyVal(obj: Object, prop: string, val: any, msg?: string): void; propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; lengthOf(exp: any, len: number, msg?: string): void; throw(fn: Function, msg?: string): void; throw(fn: Function, regExp: RegExp): void; throw(fn: Function, errType: Function, msg?: string): void; throw(fn: Function, errType: Function, regExp: RegExp): void; throws(fn: Function, msg?: string): void; throws(fn: Function, regExp: RegExp): void; throws(fn: Function, errType: Function, msg?: string): void; throws(fn: Function, errType: Function, regExp: RegExp): void; Throw(fn: Function, msg?: string): void; Throw(fn: Function, regExp: RegExp): void; Throw(fn: Function, errType: Function, msg?: string): void; Throw(fn: Function, errType: Function, regExp: RegExp): void; doesNotThrow(fn: Function, msg?: string): void; doesNotThrow(fn: Function, regExp: RegExp): void; doesNotThrow(fn: Function, errType: Function, msg?: string): void; doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; operator(val: any, operator: string, val2: any, msg?: string): void; closeTo(act: number, exp: number, delta: number, msg?: string): void; approximately(act: number, exp: number, delta: number, msg?: string): void; sameMembers(set1: any[], set2: any[], msg?: string): void; sameDeepMembers(set1: any[], set2: any[], msg?: string): void; includeMembers(superset: any[], subset: any[], msg?: string): void; includeDeepMembers(superset: any[], subset: any[], msg?: string): void; ifError(val: any, msg?: string): void; isExtensible(obj: {}, msg?: string): void; extensible(obj: {}, msg?: string): void; isNotExtensible(obj: {}, msg?: string): void; notExtensible(obj: {}, msg?: string): void; isSealed(obj: {}, msg?: string): void; sealed(obj: {}, msg?: string): void; isNotSealed(obj: {}, msg?: string): void; notSealed(obj: {}, msg?: string): void; isFrozen(obj: Object, msg?: string): void; frozen(obj: Object, msg?: string): void; isNotFrozen(obj: Object, msg?: string): void; notFrozen(obj: Object, msg?: string): void; oneOf(inList: any, list: any[], msg?: string): void; changes(fn: Function, obj: {}, property: string): void; doesNotChange(fn: Function, obj: {}, property: string): void; increases(fn: Function, obj: {}, property: string): void; doesNotIncrease(fn: Function, obj: {}, property: string): void; decreases(fn: Function, obj: {}, property: string): void; doesNotDecrease(fn: Function, obj: {}, property: string): void; } } declare module 'chai/lib/Assert' { import alias = require('~chai/lib/Assert'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Assertion.d.ts declare module '~chai/lib/Assertion' { export interface AssertionStatic { (target?: any, message?: string, stack?: Function): Assertion; new (target?: any, message?: string, stack?: Function): Assertion; } export interface Assertion extends LanguageChains, NumericComparison, TypeComparison { not: Assertion; deep: Deep; any: KeyFilter; all: KeyFilter; a: TypeComparison; an: TypeComparison; include: Include; includes: Include; contain: Include; contains: Include; ok: Assertion; true: Assertion; false: Assertion; null: Assertion; undefined: Assertion; NaN: Assertion; exist: Assertion; empty: Assertion; arguments: Assertion; Arguments: Assertion; equal: Equal; equals: Equal; eq: Equal; eql: Equal; eqls: Equal; property: Property; ownProperty: OwnProperty; haveOwnProperty: OwnProperty; ownPropertyDescriptor: OwnPropertyDescriptor; haveOwnPropertyDescriptor: OwnPropertyDescriptor; length: Length; lengthOf: Length; match: Match; matches: Match; string(str: string, message?: string): Assertion; keys: Keys; key(str: string): Assertion; throw: Throw; throws: Throw; Throw: Throw; respondTo: RespondTo; respondsTo: RespondTo; itself: Assertion; satisfy: Satisfy; satisfies: Satisfy; closeTo: CloseTo; approximately: CloseTo; members: Members; increase: PropertyChange; increases: PropertyChange; decrease: PropertyChange; decreases: PropertyChange; change: PropertyChange; changes: PropertyChange; extensible: Assertion; sealed: Assertion; frozen: Assertion; oneOf(list: any[], message?: string): Assertion; } export interface LanguageChains { to: Assertion; be: Assertion; been: Assertion; is: Assertion; that: Assertion; which: Assertion; and: Assertion; has: Assertion; have: Assertion; with: Assertion; at: Assertion; of: Assertion; same: Assertion; } export interface NumericComparison { above: NumberComparer; gt: NumberComparer; greaterThan: NumberComparer; least: NumberComparer; gte: NumberComparer; below: NumberComparer; lt: NumberComparer; lessThan: NumberComparer; most: NumberComparer; lte: NumberComparer; within(start: number, finish: number, message?: string): Assertion; } export interface NumberComparer { (value: number, message?: string): Assertion; } export interface TypeComparison { (type: string, message?: string): Assertion; instanceof: InstanceOf; instanceOf: InstanceOf; } export interface InstanceOf { (constructor: Object, message?: string): Assertion; } export interface CloseTo { (expected: number, delta: number, message?: string): Assertion; } export interface Deep { equal: Equal; equals: Equal; eq: Equal; include: Include; property: Property; members: Members; } export interface KeyFilter { keys: Keys; } export interface Equal { (value: any, message?: string): Assertion; } export interface Property { (name: string, value?: any, message?: string): Assertion; } export interface OwnProperty { (name: string, message?: string): Assertion; } export interface OwnPropertyDescriptor { (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; (name: string, message?: string): Assertion; } export interface Length extends LanguageChains, NumericComparison { (length: number, message?: string): Assertion; } export interface Include { (value: Object, message?: string): Assertion; (value: string, message?: string): Assertion; (value: number, message?: string): Assertion; string(value: string, message?: string): Assertion; keys: Keys; members: Members; any: KeyFilter; all: KeyFilter; } export interface Match { (regexp: RegExp | string, message?: string): Assertion; } export interface Keys { (...keys: any[]): Assertion; (keys: any[]): Assertion; (keys: Object): Assertion; } export interface Throw { (): Assertion; (expected: string, message?: string): Assertion; (expected: RegExp, message?: string): Assertion; (constructor: Error, expected?: string, message?: string): Assertion; (constructor: Error, expected?: RegExp, message?: string): Assertion; (constructor: Function, expected?: string, message?: string): Assertion; (constructor: Function, expected?: RegExp, message?: string): Assertion; } export interface RespondTo { (method: string, message?: string): Assertion; } export interface Satisfy { (matcher: Function, message?: string): Assertion; } export interface Members { (set: any[], message?: string): Assertion; } export interface PropertyChange { (object: Object, prop: string, msg?: string): Assertion; } } declare module 'chai/lib/Assertion' { import alias = require('~chai/lib/Assertion'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Expect.d.ts declare module '~chai/lib/Expect' { import {AssertionStatic} from '~chai/lib/Assertion'; export interface ExpectStatic extends AssertionStatic { fail(actual?: any, expected?: any, message?: string, operator?: string): void; } } declare module 'chai/lib/Expect' { import alias = require('~chai/lib/Expect'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Should.d.ts declare module '~chai/lib/Should' { export interface Should extends ShouldAssertion { not: ShouldAssertion; fail(actual: any, expected: any, message?: string, operator?: string): void; } export interface ShouldAssertion { Throw: ShouldThrow; throw: ShouldThrow; equal(value1: any, value2: any, message?: string): void; exist(value: any, message?: string): void; } export interface ShouldThrow { (actual: Function): void; (actual: Function, expected: string | RegExp, message?: string): void; (actual: Function, constructor: Error | Function, expected?: string | RegExp, message?: string): void; } } declare module 'chai/lib/Should' { import alias = require('~chai/lib/Should'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Config.d.ts declare module '~chai/lib/Config' { export interface Config { includeStack: boolean; showDiff: boolean; truncateThreshold: number; } } declare module 'chai/lib/Config' { import alias = require('~chai/lib/Config'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Utils.d.ts declare module '~chai/lib/Utils' { import {Assertion} from '~chai/lib/Assertion'; export interface PathInfo { parent: any; name: number|string; value: any; exists: boolean; } export interface Utils { addChainableMethod(ctx: any, name: string, chainingBehavior: (value: any) => void): void; addMethod(ctx: any, name: string, method: (value: any) => void): void; addProperty(ctx: any, name: string, getter: () => void): void; expectTypes(obj: Object, types: string[]): void; flag(obj: Object, key: string, value?: any): any; getActual(obj: Object, actual?: any): any; getEnumerableProperties(obj: Object): string[]; getMessage(obj: Object, params: any[]): string; getMessage(obj: Object, message: string, negateMessage: string): string; getName(func: Function): string; getPathInfo(path: string, obj: Object): PathInfo; getPathValue(path: string, obj: Object): any; getProperties(obj: Object): string[]; hasProperty(obj: Object, name: string): boolean; transferFlags(assertion: Assertion | any, obj: Object, includeAll?: boolean): void; inspect(obj: any): any; } } declare module 'chai/lib/Utils' { import alias = require('~chai/lib/Utils'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/lib/Chai.d.ts declare module '~chai/lib/Chai' { import * as AE from '~chai~assertion-error'; import * as Assert from '~chai/lib/Assert'; import * as A from '~chai/lib/Assertion'; import * as Expect from '~chai/lib/Expect'; import * as Should from '~chai/lib/Should'; import * as Config from '~chai/lib/Config'; import * as Utils from '~chai/lib/Utils'; namespace chai { export interface AssertionStatic extends A.AssertionStatic {} export class AssertionError extends AE.AssertionError {} export var Assertion: A.AssertionStatic; export var expect: Expect.ExpectStatic; export var assert: Assert.AssertStatic; export var config: Config.Config; export var util: Utils.Utils; export function should(): Should.Should; export function Should(): Should.Should; /** * Provides a way to extend the internals of Chai */ export function use(fn: (chai: any, utils: Utils.Utils) => void): typeof chai; } export = chai; /* tslint:disable:no-internal-module */ global { interface Object { should: A.Assertion; } } } declare module 'chai/lib/Chai' { import alias = require('~chai/lib/Chai'); export = alias; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-chai/793bee097a6a644e078a033603d88ac89eb7b560/index.d.ts declare module '~chai/index' { // Type definitions for chai 3.4.0 // Project: http://chaijs.com/ // Original Definitions by: Jed Mao <https://github.com/jedmao/>, // Bart van der Schoor <https://github.com/Bartvds>, // Andrew Brown <https://github.com/AGBrown>, // Olivier Chevet <https://github.com/olivr70>, // Matt Wistrand <https://github.com/mwistrand> import chai = require('~chai/lib/Chai'); export = chai; } declare module 'chai/index' { import alias = require('~chai/index'); export = alias; } declare module 'chai' { import alias = require('~chai/index'); export = alias; }
the_stack
import CommonUtils from "../../utils/CommonUtils"; import { BlockRegData } from "../Define/BlockDef"; import { BlockPort } from "../Define/Port"; export default { register, packageName: 'Set', version: 1, } function register() { //#region 创建集 let CreateSet = new BlockRegData("C3A78FF7-7A0E-D3E7-2211-CEE67C9C330E", "创建集", '创建一个集。\n集是一种元素不重复的数据结构。', '', '集合') CreateSet.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'IN0', paramType: 'any', name: '元素0', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'SET', paramType: 'any', paramSetType: 'set', name: '集合', description: '创建的集合实例', portAnyFlexable: { flexable: true } } ]; CreateSet.portAnyFlexables = { flexable: { setResultToData: 'opType' } } CreateSet.settings.parametersChangeSettings.userCanAddInputParameter = true; CreateSet.callbacks.onCreate = (block) => { if(!CommonUtils.isDefined(block.data['opType'])) block.data['opType'] = 'any'; }; CreateSet.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = new Set<any>(); Object.keys(block.inputPorts).forEach((key) => { let port = (<BlockPort>block.inputPorts[key]); if(!port.paramType.isExecute()) { let v = block.getInputParamValue(port); if(CommonUtils.isDefinedAndNotNull(v)) set.add(v); } }); block.setOutputParamValue('SET', set); block.activeOutputPort('OUT'); } }; CreateSet.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'IN' + block.data['portCount'], direction: 'input', name: '元素' + block.data['portCount'], paramType: block.data['opType'], portAnyFlexable: { flexable: true } } }; //#endregion //#region 存在 let SetHas = new BlockRegData("69A2F63E-7377-D5DB-52F1-2CBE47E03B04", "存在", '检查某个元素是否在集中存在', '', '集合') SetHas.ports = [ { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', description: '搜索项目的目标集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'any', description: '要检查的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUTCONTAINS', paramType: 'boolean', description: '存在?', }, ]; SetHas.portAnyFlexables = { flexable: {} } SetHas.callbacks.onPortParamRequest = (block, port, context) => { if(port.guid == 'OUTCONTAINS') { let set = <Set<any>>block.getInputParamValue('INSET', context); let item = block.getInputParamValue('INITEM', context); return set.has(item); } }; SetHas.blockStyle.noTitle = true; SetHas.blockStyle.logoBackground = '<span class="big-title">集合中存在</span>'; SetHas.blockStyle.minWidth = '150px'; //#endregion //#region 添加 let SetAdd = new BlockRegData("39EF0D42-8EE8-7FD9-34D0-A7C4FC487E02", "添加", '添加元素至集中', '', '集合') SetAdd.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'any', description: '要添加的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; SetAdd.portAnyFlexables = { flexable: {} } SetAdd.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); let item = block.getInputParamValue('INITEM'); set.add(item); block.activeOutputPort('OUT'); } }; SetAdd.blockStyle.noTitle = true; SetAdd.blockStyle.logoBackground = '<span class="big-title">集合添加元素</span>'; SetAdd.blockStyle.minWidth = '170px'; //#endregion //#region 移除 let SetRemove = new BlockRegData("CBDC0AC7-402A-F91D-A4D4-7B30AA25B61D", "移除", '从集中移除元素', '', '集合') SetRemove.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'any', description: '要移除的元素', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTRMED', paramType: 'boolean', description: '如果有元素被移除,返回真(返回假说明元素不在集中)', }, ]; SetRemove.portAnyFlexables = { flexable: {} } SetRemove.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); let item = block.getInputParamValue('INITEM'); block.setOutputParamValue('OUTRMED', set.delete(item)); block.activeOutputPort('OUT'); } }; SetRemove.blockStyle.noTitle = true; SetRemove.blockStyle.logoBackground = '<span class="big-title">集合移除元素</span>'; SetRemove.blockStyle.minWidth = '170px'; //#endregion //#region 清空集合 let SetClear = new BlockRegData("1AFC3FF1-D4F8-2190-F041-4277F9F0C6BE", "清空集合", '清空一个集合,移除所有元素', '', '集合') SetClear.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; SetClear.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); set.clear(); block.activeOutputPort('OUT'); } }; SetClear.blockStyle.noTitle = true; SetClear.blockStyle.logoBackground = '<span class="big-title">清空集合</span>'; SetClear.blockStyle.minWidth = '150px'; //#endregion //#region 集合长度 let SetLength = new BlockRegData("2FE1C73E-E14A-11EC-AEF5-107EB5BB9B43", "集合长度", '获取集合中元素的个数', '', '集合'); SetLength.ports = [ { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'array', }, { direction: 'output', guid: 'OUTLEN', paramType: 'number', description: '集合中元素的个数', }, ]; SetLength.callbacks.onPortParamRequest = (block, port, context) => { if(port.guid == 'OUTLEN') { let set = <Set<any>>block.getInputParamValue('INSET', context); return set.size; } }; SetLength.blockStyle.noTitle = true; SetLength.blockStyle.logoBackground = '<span class="big-title">集合长度</span>'; SetLength.blockStyle.minWidth = '150px'; //#endregion //#region 添加数组 let SetAddArray = new BlockRegData("D0256F02-97D2-5514-5E21-48EB09297F51", "添加", '添加数组中的所有元素至集中', '', '集合') SetAddArray.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', description: '搜索项目的目标集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INARRAY', paramType: 'any', paramSetType: 'array', description: '要添加的元素数组', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; SetAddArray.portAnyFlexables = { flexable: {} } SetAddArray.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); let array = <Array<any>>block.getInputParamValue('INARRAY'); array.forEach((item) => set.add(item)) block.activeOutputPort('OUT'); } }; SetAddArray.blockStyle.noTitle = true; SetAddArray.blockStyle.logoBackground = '<span class="big-title">添加数组到集合</span>'; SetAddArray.blockStyle.minWidth = '175px'; //#endregion //#region 移除数组 let SetRemoveArray = new BlockRegData("FC4B31C3-B8B1-FE7E-FEF7-2C32A33A4B15", "移除数组", '从集中移除数组中的元素', '', '集合') SetRemoveArray.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', description: '搜索项目的目标集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INARRAY', paramType: 'any', paramSetType: 'array', description: '要移除的元素数组', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; SetRemoveArray.portAnyFlexables = { flexable: {} } SetRemoveArray.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); let array = <Array<any>>block.getInputParamValue('INARRAY'); array.forEach((item) => { if(set.has(item)) set.delete(item) }); block.activeOutputPort('OUT'); } }; SetRemoveArray.blockStyle.noTitle = true; SetRemoveArray.blockStyle.logoBackground = '<span class="big-title">从集合移除数组</span>'; SetRemoveArray.blockStyle.minWidth = '175px'; //#endregion //#region 联合 let SetAddUnion = new BlockRegData("AEDAF3A2-C2E2-F851-B1ED-EE07AAFF43C7", "联合", '获取两个集合的并集(A+B),因为\n集的元素不可重复,因此两个集中相同的元素会被合并', '', '集合') SetAddUnion.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET1', paramType: 'any', paramSetType: 'set', description: '进行联合的一个集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INSET2', paramType: 'any', paramSetType: 'set', description: '进行联合的另一个集', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, ]; SetAddUnion.portAnyFlexables = { flexable: {} } SetAddUnion.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set1 = <Set<any>>block.getInputParamValue('INSET1'); let set2 = <Set<any>>block.getInputParamValue('INSET2'); let set3 = new Set<any>(); set1.forEach((k, v) => set3.add(v)); set2.forEach((k, v) => set3.add(v)); block.setOutputParamValue('OUTSET', set3); block.activeOutputPort('OUT'); } }; SetAddUnion.blockStyle.noTitle = true; SetAddUnion.blockStyle.logoBackground = '<span class="big-title">联合</span>'; SetAddUnion.blockStyle.minWidth = '175px'; //#endregion //#region 交集 let SetAddIntersection = new BlockRegData("9A6DCBC1-17D0-0965-E736-FA8A434BF489", "交集", '获取两个集合(A和B)的交集,即结果包含既在A中也在B中的元素', '', '集合') SetAddIntersection.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET1', paramType: 'any', paramSetType: 'set', description: '进行交叉的一个集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INSET2', paramType: 'any', paramSetType: 'set', description: '进行交叉的一个集', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, ]; SetAddIntersection.portAnyFlexables = { flexable: {} } SetAddIntersection.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set1 = <Set<any>>block.getInputParamValue('INSET1'); let set2 = <Set<any>>block.getInputParamValue('INSET2'); let set3 = new Set<any>(); set1.forEach((k, v) => { if(set2.has(v)) set3.add(v) }); block.setOutputParamValue('OUTSET', set3); block.activeOutputPort('OUT'); } }; SetAddIntersection.blockStyle.noTitle = true; SetAddIntersection.blockStyle.logoBackground = '<span class="big-title">交集</span>'; SetAddIntersection.blockStyle.minWidth = '175px'; //#endregion //#region 差异 let SetAddDifference = new BlockRegData("6B9298BB-AB17-1444-B545-D67FF74F86D9", "差异", '获取两个集合(A和B)的差异,即在A中存在但在B中不存在的所有元素。\n注意,开始集才会保留元素,开始集与比较集不能对调。', '', '集合') SetAddDifference.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET1', paramType: 'any', paramSetType: 'set', description: '开始集', portAnyFlexable: { flexable: true }, }, { direction: 'input', guid: 'INSET2', paramType: 'any', paramSetType: 'set', description: '比较集', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, ]; SetAddDifference.portAnyFlexables = { flexable: {} } SetAddDifference.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set1 = <Set<any>>block.getInputParamValue('INSET1'); let set2 = <Set<any>>block.getInputParamValue('INSET2'); let set3 = new Set<any>(); set1.forEach((k, v) => { if(!set2.has(v)) set3.add(v); }); block.setOutputParamValue('OUTSET', set3); block.activeOutputPort('OUT'); } }; SetAddDifference.blockStyle.noTitle = true; SetAddDifference.blockStyle.logoBackground = '<span class="big-title">差异</span>'; SetAddDifference.blockStyle.minWidth = '175px'; //#endregion //#region 到数组 let SetToArray = new BlockRegData("B5DAE865-44AD-6E03-5189-A6AC3373AC9E", "到数组", '将此集合拷贝到一个新数组', '', '集合') SetToArray.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', portAnyFlexable: { flexable: true }, }, ]; SetToArray.portAnyFlexables = { flexable: {} } SetToArray.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let set = <Set<any>>block.getInputParamValue('INSET'); block.setOutputParamValue('OUTARRAY', Array.from(set)); block.activeOutputPort('OUT'); } }; SetToArray.blockStyle.noTitle = true; SetToArray.blockStyle.logoBackground = '<span class="big-title">到数组</span>'; SetToArray.blockStyle.minWidth = '150px'; //#endregion //#region For Each Loop let SetForeach = new BlockRegData("37D2BF42-1EA8-4910-EF36-8E036E6C8C94", "For Each Loop (集合)", '遍历循环指定的集合', '', '集合'); SetForeach.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); SetForeach.ports = [ { name: "进入", direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { name: "集", description: '要遍历的集合', direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'set', portAnyFlexable: { flexable: true }, }, { name: "终止", description: '终止遍历循环', direction: 'input', guid: 'BREAK', paramType: 'execute', }, { guid: 'LOOPBODY', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'ELEMENT', paramType: 'number', direction: 'output', name: '当前元素', portAnyFlexable: { flexable: true }, }, { guid: 'EXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; SetForeach.portAnyFlexables = { flexable: {} } SetForeach.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { var variables = block.variables(); variables['breakActived'] = false; let EXIT = block.getPortByGUID('EXIT'); let LOOP = block.getPortByGUID('LOOP'); let ELEMENT = block.getPortByGUID('ELEMENT'); let set = <Set<any>>block.getInputParamValue('SET'); let breakActived = variables['breakActived']; let values = set.values(); let value = values.next() while(!value.done) { block.setOutputParamValue(ELEMENT, value.value); block.activeOutputPort(LOOP); breakActived = variables['breakActived']; if(breakActived) break; value = values.next(); } block.activeOutputPort(EXIT); }else if(port.guid == 'BREAK') { var variables = block.variables(); variables['breakActived'] = true; } }; //#endregion return [ CreateSet, SetHas, SetAdd, SetRemove, SetClear, SetLength, SetAddArray, SetRemoveArray, SetAddUnion, SetAddIntersection, SetAddDifference, SetToArray, SetForeach, ]; }
the_stack
import * as tracing from '@opentelemetry/tracing'; import * as resources from '@opentelemetry/resources'; import * as core from '@opentelemetry/core'; import * as api from '@opentelemetry/api'; import * as proto from './trace'; import { fromProtoResource, toProtoResource } from '../../resource/v1/transform'; import { fromInstrumentationLibrary, fromProtoSpanAttributes, toInstrumentationLibrary, toProtoKeyValue, toProtoSpanAttributes, } from '../../common/v1/transform'; import { bytesArrayToHex, hexToBytesArray, nanosecondsToHrTime } from '../../../../utils'; import { hrTimeDuration } from '@opentelemetry/core'; function groupSpansByResource(spans: tracing.ReadableSpan[]): Map<resources.Resource, tracing.ReadableSpan[]> { return spans.reduce((byResourceMap, sdkSpan) => { if (!byResourceMap.has(sdkSpan.resource)) { byResourceMap.set(sdkSpan.resource, []); } byResourceMap.get(sdkSpan.resource).push(sdkSpan); return byResourceMap; }, new Map<resources.Resource, tracing.ReadableSpan[]>()); } function groupSpansByInstrumentationLibrary( spans: tracing.ReadableSpan[] ): Map<core.InstrumentationLibrary, tracing.ReadableSpan[]> { return spans.reduce((byInstrumentationLibraryMap, sdkSpan) => { if (!byInstrumentationLibraryMap.has(sdkSpan.instrumentationLibrary)) { byInstrumentationLibraryMap.set(sdkSpan.instrumentationLibrary, []); } byInstrumentationLibraryMap.get(sdkSpan.instrumentationLibrary).push(sdkSpan); return byInstrumentationLibraryMap; }, new Map<core.InstrumentationLibrary, tracing.ReadableSpan[]>()); } export const spanKindToProtoMap = new Map<api.SpanKind, proto.Span_SpanKind>([ [api.SpanKind.INTERNAL, proto.Span_SpanKind.SPAN_KIND_INTERNAL], [api.SpanKind.SERVER, proto.Span_SpanKind.SPAN_KIND_SERVER], [api.SpanKind.CLIENT, proto.Span_SpanKind.SPAN_KIND_CLIENT], [api.SpanKind.PRODUCER, proto.Span_SpanKind.SPAN_KIND_PRODUCER], [api.SpanKind.CONSUMER, proto.Span_SpanKind.SPAN_KIND_CONSUMER], ]); export const spanKindFromProtoMap = new Map<proto.Span_SpanKind, api.SpanKind>([ [proto.Span_SpanKind.SPAN_KIND_INTERNAL, api.SpanKind.INTERNAL], [proto.Span_SpanKind.SPAN_KIND_SERVER, api.SpanKind.SERVER], [proto.Span_SpanKind.SPAN_KIND_CLIENT, api.SpanKind.CLIENT], [proto.Span_SpanKind.SPAN_KIND_PRODUCER, api.SpanKind.PRODUCER], [proto.Span_SpanKind.SPAN_KIND_CONSUMER, api.SpanKind.CONSUMER], ]); export const spanStatusCodeToProtoMap = new Map<api.SpanStatusCode, proto.Status_StatusCode>([ [api.SpanStatusCode.UNSET, proto.Status_StatusCode.STATUS_CODE_UNSET], [api.SpanStatusCode.OK, proto.Status_StatusCode.STATUS_CODE_OK], [api.SpanStatusCode.ERROR, proto.Status_StatusCode.STATUS_CODE_ERROR], ]); export const spanStatusCodeFromProtoMap = new Map<proto.Status_StatusCode, api.SpanStatusCode>([ [proto.Status_StatusCode.STATUS_CODE_UNSET, api.SpanStatusCode.UNSET], [proto.Status_StatusCode.STATUS_CODE_OK, api.SpanStatusCode.OK], [proto.Status_StatusCode.STATUS_CODE_ERROR, api.SpanStatusCode.ERROR], ]); export function toProtoTraceState(sdkTraceState?: api.TraceState): string | undefined { if (!sdkTraceState) return undefined; return sdkTraceState.serialize(); } export function fromProtoTraceState(protoTraceState: string): core.TraceState { if (!protoTraceState) return undefined; return new core.TraceState(protoTraceState); } export function toProtoSpanEvent(sdkSpanEvent: tracing.TimedEvent): proto.Span_Event { return { timeUnixNano: core.hrTimeToNanoseconds(sdkSpanEvent.time), name: sdkSpanEvent.name, attributes: toProtoSpanAttributes(sdkSpanEvent.attributes ?? {}), droppedAttributesCount: 0, }; } export function fromProtoSpanEvent(protoSpanEvent: proto.Span_Event): tracing.TimedEvent { return { time: nanosecondsToHrTime(protoSpanEvent.timeUnixNano), name: protoSpanEvent.name, attributes: fromProtoSpanAttributes(protoSpanEvent.attributes), }; } export function toProtoSpanLink(sdkLink: api.Link): proto.Span_Link { return { traceId: hexToBytesArray(sdkLink.context.traceId), spanId: hexToBytesArray(sdkLink.context.spanId), traceState: 'TODO', // https://github.com/open-telemetry/opentelemetry-js-api/issues/36 attributes: toProtoSpanAttributes(sdkLink.attributes ?? {}), droppedAttributesCount: 0, }; } export function fromProtoSpanLink(protoSpanLink: proto.Span_Link): api.Link { return { context: { traceId: bytesArrayToHex(protoSpanLink.traceId), spanId: bytesArrayToHex(protoSpanLink.spanId), traceFlags: 0, }, attributes: fromProtoSpanAttributes(protoSpanLink.attributes), }; } export function toProtoStatus(sdkSpanStatus: api.SpanStatus): proto.Status { return { deprecatedCode: proto.Status_DeprecatedStatusCode.UNRECOGNIZED, message: sdkSpanStatus.message, code: spanStatusCodeToProtoMap.get(sdkSpanStatus.code), }; } export function fromProtoStatus(protoStatus: proto.Status): api.SpanStatus { return { code: spanStatusCodeFromProtoMap.get(protoStatus.code), message: protoStatus.message, }; } export function toProtoSpan(sdkSpan: tracing.ReadableSpan): proto.Span { return { traceId: hexToBytesArray(sdkSpan.spanContext().traceId), spanId: hexToBytesArray(sdkSpan.spanContext().spanId), traceState: toProtoTraceState(sdkSpan.spanContext().traceState), parentSpanId: sdkSpan.parentSpanId ? hexToBytesArray(sdkSpan.parentSpanId) : undefined, name: sdkSpan.name, kind: spanKindToProtoMap.get(sdkSpan.kind) ?? proto.Span_SpanKind.SPAN_KIND_UNSPECIFIED, startTimeUnixNano: core.hrTimeToNanoseconds(sdkSpan.startTime), endTimeUnixNano: core.hrTimeToNanoseconds(sdkSpan.endTime), attributes: toProtoSpanAttributes(sdkSpan.attributes), droppedAttributesCount: 0, events: sdkSpan.events.map(toProtoSpanEvent), droppedEventsCount: 0, links: sdkSpan.links.map(toProtoSpanLink), droppedLinksCount: 0, status: toProtoStatus(sdkSpan.status), }; } export function fromProtoSpan( protoSpan: proto.Span, sdkResource: resources.Resource, sdkInstrumentationLibrary: core.InstrumentationLibrary ): tracing.ReadableSpan { const startTime = nanosecondsToHrTime(protoSpan.startTimeUnixNano); const endTime = nanosecondsToHrTime(protoSpan.endTimeUnixNano); return { name: protoSpan.name, kind: spanKindFromProtoMap.get(protoSpan.kind), spanContext: () => ({ traceId: bytesArrayToHex(protoSpan.traceId), spanId: bytesArrayToHex(protoSpan.spanId), traceFlags: 0, // we can't actually tell if the trace was sampled since this data is not in the protobuf spec traceState: fromProtoTraceState(protoSpan.traceState), }), parentSpanId: protoSpan.parentSpanId ? bytesArrayToHex(protoSpan.parentSpanId) : undefined, startTime, endTime, status: fromProtoStatus(protoSpan.status), attributes: fromProtoSpanAttributes(protoSpan.attributes), links: protoSpan.links.map(fromProtoSpanLink), events: protoSpan.events.map(fromProtoSpanEvent), duration: hrTimeDuration(startTime, endTime), ended: true, resource: sdkResource, instrumentationLibrary: sdkInstrumentationLibrary, }; } export function toProtoInstrumentationLibrarySpans( sdkInstrumentationLibrary: core.InstrumentationLibrary, sdkSpans: tracing.ReadableSpan[] ): proto.InstrumentationLibrarySpans { return { instrumentationLibrary: toInstrumentationLibrary(sdkInstrumentationLibrary), spans: sdkSpans.map((sdkSpan) => toProtoSpan(sdkSpan)), }; } export function fromProtoInstrumentationLibrarySpans( protoInstrumentationLibrarySpans: proto.InstrumentationLibrarySpans, sdkResource: resources.Resource ): tracing.ReadableSpan[] { const sdkInstrumentationLibrary = fromInstrumentationLibrary( protoInstrumentationLibrarySpans.instrumentationLibrary ); return protoInstrumentationLibrarySpans.spans.map((protoSpan) => fromProtoSpan(protoSpan, sdkResource, sdkInstrumentationLibrary) ); } export function toProtoResourceSpans( sdkResource: resources.Resource, sdkResourceSpans: tracing.ReadableSpan[], additionalAttributes: resources.ResourceAttributes = {} ): proto.ResourceSpans { const spansByInstrumentationLibrary = groupSpansByInstrumentationLibrary(sdkResourceSpans); return { resource: toProtoResource(sdkResource, additionalAttributes), instrumentationLibrarySpans: Array.from(spansByInstrumentationLibrary).map( ([sdkInstrumentationLibrary, sdkInstrumentationLibrarySpans]) => { return toProtoInstrumentationLibrarySpans(sdkInstrumentationLibrary, sdkInstrumentationLibrarySpans); } ), }; } export function fromProtoResourceSpans(protoResourceSpans: proto.ResourceSpans): tracing.ReadableSpan[] { const sdkResource = fromProtoResource(protoResourceSpans.resource); return protoResourceSpans.instrumentationLibrarySpans.flatMap((instrumentationLibrarySpans) => fromProtoInstrumentationLibrarySpans(instrumentationLibrarySpans, sdkResource) ); } export function toProtoResourceSpansArray( sdkSpans: tracing.ReadableSpan[], additionalAttributes: resources.ResourceAttributes = {} ): proto.ResourceSpans[] { const spansByResource = groupSpansByResource(sdkSpans); return Array.from(spansByResource).map(([sdkResource, sdkResourceSpans]) => toProtoResourceSpans(sdkResource, sdkResourceSpans, additionalAttributes) ); } export function fromProtoResourceSpansArray(protoResourceSpansArray: proto.ResourceSpans[]): tracing.ReadableSpan[] { return protoResourceSpansArray.flatMap(fromProtoResourceSpans); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * > **Note:** To prevent a race condition during service deletion, make sure to set `dependsOn` to the related `aws.iam.RolePolicy`; otherwise, the policy may be destroyed too soon and the ECS service will then get stuck in the `DRAINING` state. * * Provides an ECS service - effectively a task that is expected to run until an error occurs or a user terminates it (typically a webserver or a database). * * See [ECS Services section in AWS developer guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html). * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const mongo = new aws.ecs.Service("mongo", { * cluster: aws_ecs_cluster.foo.id, * taskDefinition: aws_ecs_task_definition.mongo.arn, * desiredCount: 3, * iamRole: aws_iam_role.foo.arn, * orderedPlacementStrategies: [{ * type: "binpack", * field: "cpu", * }], * loadBalancers: [{ * targetGroupArn: aws_lb_target_group.foo.arn, * containerName: "mongo", * containerPort: 8080, * }], * placementConstraints: [{ * type: "memberOf", * expression: "attribute:ecs.availability-zone in [us-west-2a, us-west-2b]", * }], * }, { * dependsOn: [aws_iam_role_policy.foo], * }); * ``` * ### Ignoring Changes to Desired Count * * You can use [`ignoreChanges`](https://www.pulumi.com/docs/intro/concepts/programming-model/#ignorechanges) to create an ECS service with an initial count of running instances, then ignore any changes to that count caused externally (e.g. Application Autoscaling). * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * // ... other configurations ... * const example = new aws.ecs.Service("example", {desiredCount: 2}); * ``` * ### Daemon Scheduling Strategy * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const bar = new aws.ecs.Service("bar", { * cluster: aws_ecs_cluster.foo.id, * taskDefinition: aws_ecs_task_definition.bar.arn, * schedulingStrategy: "DAEMON", * }); * ``` * ### External Deployment Controller * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.ecs.Service("example", { * cluster: aws_ecs_cluster.example.id, * deploymentController: { * type: "EXTERNAL", * }, * }); * ``` * * ## Import * * ECS services can be imported using the `name` together with ecs cluster `name`, e.g. * * ```sh * $ pulumi import aws:ecs/service:Service imported cluster-name/service-name * ``` */ 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 = 'aws:ecs/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; } /** * Capacity provider strategy to use for the service. Can be one or more. Detailed below. */ public readonly capacityProviderStrategies!: pulumi.Output<outputs.ecs.ServiceCapacityProviderStrategy[] | undefined>; /** * ARN of an ECS cluster */ public readonly cluster!: pulumi.Output<string>; /** * Configuration block for deployment circuit breaker. Detailed below. */ public readonly deploymentCircuitBreaker!: pulumi.Output<outputs.ecs.ServiceDeploymentCircuitBreaker | undefined>; /** * Configuration block for deployment controller configuration. Detailed below. */ public readonly deploymentController!: pulumi.Output<outputs.ecs.ServiceDeploymentController | undefined>; /** * Upper limit (as a percentage of the service's desiredCount) of the number of running tasks that can be running in a service during a deployment. Not valid when using the `DAEMON` scheduling strategy. */ public readonly deploymentMaximumPercent!: pulumi.Output<number | undefined>; /** * Lower limit (as a percentage of the service's desiredCount) of the number of running tasks that must remain running and healthy in a service during a deployment. */ public readonly deploymentMinimumHealthyPercent!: pulumi.Output<number | undefined>; /** * Number of instances of the task definition to place and keep running. Defaults to 0. Do not specify if using the `DAEMON` scheduling strategy. */ public readonly desiredCount!: pulumi.Output<number | undefined>; /** * Specifies whether to enable Amazon ECS managed tags for the tasks within the service. */ public readonly enableEcsManagedTags!: pulumi.Output<boolean | undefined>; /** * Specifies whether to enable Amazon ECS Exec for the tasks within the service. */ public readonly enableExecuteCommand!: pulumi.Output<boolean | undefined>; /** * Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination (e.g. `myimage:latest`), roll Fargate tasks onto a newer platform version, or immediately deploy `orderedPlacementStrategy` and `placementConstraints` updates. */ public readonly forceNewDeployment!: pulumi.Output<boolean | undefined>; /** * Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers. */ public readonly healthCheckGracePeriodSeconds!: pulumi.Output<number | undefined>; /** * ARN of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is required if you are using a load balancer with your service, but only if your task definition does not use the `awsvpc` network mode. If using `awsvpc` network mode, do not specify this role. If your account has already created the Amazon ECS service-linked role, that role is used by default for your service unless you specify a role here. */ public readonly iamRole!: pulumi.Output<string>; /** * Launch type on which to run your service. The valid values are `EC2`, `FARGATE`, and `EXTERNAL`. Defaults to `EC2`. */ public readonly launchType!: pulumi.Output<string>; /** * Configuration block for load balancers. Detailed below. */ public readonly loadBalancers!: pulumi.Output<outputs.ecs.ServiceLoadBalancer[] | undefined>; /** * Name of the service (up to 255 letters, numbers, hyphens, and underscores) */ public readonly name!: pulumi.Output<string>; /** * Network configuration for the service. This parameter is required for task definitions that use the `awsvpc` network mode to receive their own Elastic Network Interface, and it is not supported for other network modes. Detailed below. */ public readonly networkConfiguration!: pulumi.Output<outputs.ecs.ServiceNetworkConfiguration | undefined>; /** * Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. The maximum number of `orderedPlacementStrategy` blocks is `5`. Detailed below. */ public readonly orderedPlacementStrategies!: pulumi.Output<outputs.ecs.ServiceOrderedPlacementStrategy[] | undefined>; /** * Rules that are taken into consideration during task placement. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. Maximum number of `placementConstraints` is `10`. Detailed below. */ public readonly placementConstraints!: pulumi.Output<outputs.ecs.ServicePlacementConstraint[] | undefined>; /** * Platform version on which to run your service. Only applicable for `launchType` set to `FARGATE`. Defaults to `LATEST`. More information about Fargate platform versions can be found in the [AWS ECS User Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html). */ public readonly platformVersion!: pulumi.Output<string>; /** * Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values are `SERVICE` and `TASK_DEFINITION`. */ public readonly propagateTags!: pulumi.Output<string | undefined>; /** * Scheduling strategy to use for the service. The valid values are `REPLICA` and `DAEMON`. Defaults to `REPLICA`. Note that [*Tasks using the Fargate launch type or the `CODE_DEPLOY` or `EXTERNAL` deployment controller types don't support the `DAEMON` scheduling strategy*](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html). */ public readonly schedulingStrategy!: pulumi.Output<string | undefined>; /** * Service discovery registries for the service. The maximum number of `serviceRegistries` blocks is `1`. Detailed below. */ public readonly serviceRegistries!: pulumi.Output<outputs.ecs.ServiceServiceRegistries | undefined>; /** * Key-value map of resource tags. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service. Required unless using the `EXTERNAL` deployment controller. If a revision is not specified, the latest `ACTIVE` revision is used. */ public readonly taskDefinition!: pulumi.Output<string | undefined>; /** * If `true`, this provider will wait for the service to reach a steady state (like [`aws ecs wait services-stable`](https://docs.aws.amazon.com/cli/latest/reference/ecs/wait/services-stable.html)) before continuing. Default `false`. */ public readonly waitForSteadyState!: pulumi.Output<boolean | undefined>; /** * 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["capacityProviderStrategies"] = state ? state.capacityProviderStrategies : undefined; inputs["cluster"] = state ? state.cluster : undefined; inputs["deploymentCircuitBreaker"] = state ? state.deploymentCircuitBreaker : undefined; inputs["deploymentController"] = state ? state.deploymentController : undefined; inputs["deploymentMaximumPercent"] = state ? state.deploymentMaximumPercent : undefined; inputs["deploymentMinimumHealthyPercent"] = state ? state.deploymentMinimumHealthyPercent : undefined; inputs["desiredCount"] = state ? state.desiredCount : undefined; inputs["enableEcsManagedTags"] = state ? state.enableEcsManagedTags : undefined; inputs["enableExecuteCommand"] = state ? state.enableExecuteCommand : undefined; inputs["forceNewDeployment"] = state ? state.forceNewDeployment : undefined; inputs["healthCheckGracePeriodSeconds"] = state ? state.healthCheckGracePeriodSeconds : undefined; inputs["iamRole"] = state ? state.iamRole : undefined; inputs["launchType"] = state ? state.launchType : undefined; inputs["loadBalancers"] = state ? state.loadBalancers : undefined; inputs["name"] = state ? state.name : undefined; inputs["networkConfiguration"] = state ? state.networkConfiguration : undefined; inputs["orderedPlacementStrategies"] = state ? state.orderedPlacementStrategies : undefined; inputs["placementConstraints"] = state ? state.placementConstraints : undefined; inputs["platformVersion"] = state ? state.platformVersion : undefined; inputs["propagateTags"] = state ? state.propagateTags : undefined; inputs["schedulingStrategy"] = state ? state.schedulingStrategy : undefined; inputs["serviceRegistries"] = state ? state.serviceRegistries : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["taskDefinition"] = state ? state.taskDefinition : undefined; inputs["waitForSteadyState"] = state ? state.waitForSteadyState : undefined; } else { const args = argsOrState as ServiceArgs | undefined; inputs["capacityProviderStrategies"] = args ? args.capacityProviderStrategies : undefined; inputs["cluster"] = args ? args.cluster : undefined; inputs["deploymentCircuitBreaker"] = args ? args.deploymentCircuitBreaker : undefined; inputs["deploymentController"] = args ? args.deploymentController : undefined; inputs["deploymentMaximumPercent"] = args ? args.deploymentMaximumPercent : undefined; inputs["deploymentMinimumHealthyPercent"] = args ? args.deploymentMinimumHealthyPercent : undefined; inputs["desiredCount"] = args ? args.desiredCount : undefined; inputs["enableEcsManagedTags"] = args ? args.enableEcsManagedTags : undefined; inputs["enableExecuteCommand"] = args ? args.enableExecuteCommand : undefined; inputs["forceNewDeployment"] = args ? args.forceNewDeployment : undefined; inputs["healthCheckGracePeriodSeconds"] = args ? args.healthCheckGracePeriodSeconds : undefined; inputs["iamRole"] = args ? args.iamRole : undefined; inputs["launchType"] = args ? args.launchType : undefined; inputs["loadBalancers"] = args ? args.loadBalancers : undefined; inputs["name"] = args ? args.name : undefined; inputs["networkConfiguration"] = args ? args.networkConfiguration : undefined; inputs["orderedPlacementStrategies"] = args ? args.orderedPlacementStrategies : undefined; inputs["placementConstraints"] = args ? args.placementConstraints : undefined; inputs["platformVersion"] = args ? args.platformVersion : undefined; inputs["propagateTags"] = args ? args.propagateTags : undefined; inputs["schedulingStrategy"] = args ? args.schedulingStrategy : undefined; inputs["serviceRegistries"] = args ? args.serviceRegistries : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["taskDefinition"] = args ? args.taskDefinition : undefined; inputs["waitForSteadyState"] = args ? args.waitForSteadyState : undefined; inputs["tagsAll"] = 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 { /** * Capacity provider strategy to use for the service. Can be one or more. Detailed below. */ capacityProviderStrategies?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceCapacityProviderStrategy>[]>; /** * ARN of an ECS cluster */ cluster?: pulumi.Input<string>; /** * Configuration block for deployment circuit breaker. Detailed below. */ deploymentCircuitBreaker?: pulumi.Input<inputs.ecs.ServiceDeploymentCircuitBreaker>; /** * Configuration block for deployment controller configuration. Detailed below. */ deploymentController?: pulumi.Input<inputs.ecs.ServiceDeploymentController>; /** * Upper limit (as a percentage of the service's desiredCount) of the number of running tasks that can be running in a service during a deployment. Not valid when using the `DAEMON` scheduling strategy. */ deploymentMaximumPercent?: pulumi.Input<number>; /** * Lower limit (as a percentage of the service's desiredCount) of the number of running tasks that must remain running and healthy in a service during a deployment. */ deploymentMinimumHealthyPercent?: pulumi.Input<number>; /** * Number of instances of the task definition to place and keep running. Defaults to 0. Do not specify if using the `DAEMON` scheduling strategy. */ desiredCount?: pulumi.Input<number>; /** * Specifies whether to enable Amazon ECS managed tags for the tasks within the service. */ enableEcsManagedTags?: pulumi.Input<boolean>; /** * Specifies whether to enable Amazon ECS Exec for the tasks within the service. */ enableExecuteCommand?: pulumi.Input<boolean>; /** * Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination (e.g. `myimage:latest`), roll Fargate tasks onto a newer platform version, or immediately deploy `orderedPlacementStrategy` and `placementConstraints` updates. */ forceNewDeployment?: pulumi.Input<boolean>; /** * Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers. */ healthCheckGracePeriodSeconds?: pulumi.Input<number>; /** * ARN of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is required if you are using a load balancer with your service, but only if your task definition does not use the `awsvpc` network mode. If using `awsvpc` network mode, do not specify this role. If your account has already created the Amazon ECS service-linked role, that role is used by default for your service unless you specify a role here. */ iamRole?: pulumi.Input<string>; /** * Launch type on which to run your service. The valid values are `EC2`, `FARGATE`, and `EXTERNAL`. Defaults to `EC2`. */ launchType?: pulumi.Input<string>; /** * Configuration block for load balancers. Detailed below. */ loadBalancers?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceLoadBalancer>[]>; /** * Name of the service (up to 255 letters, numbers, hyphens, and underscores) */ name?: pulumi.Input<string>; /** * Network configuration for the service. This parameter is required for task definitions that use the `awsvpc` network mode to receive their own Elastic Network Interface, and it is not supported for other network modes. Detailed below. */ networkConfiguration?: pulumi.Input<inputs.ecs.ServiceNetworkConfiguration>; /** * Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. The maximum number of `orderedPlacementStrategy` blocks is `5`. Detailed below. */ orderedPlacementStrategies?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceOrderedPlacementStrategy>[]>; /** * Rules that are taken into consideration during task placement. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. Maximum number of `placementConstraints` is `10`. Detailed below. */ placementConstraints?: pulumi.Input<pulumi.Input<inputs.ecs.ServicePlacementConstraint>[]>; /** * Platform version on which to run your service. Only applicable for `launchType` set to `FARGATE`. Defaults to `LATEST`. More information about Fargate platform versions can be found in the [AWS ECS User Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html). */ platformVersion?: pulumi.Input<string>; /** * Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values are `SERVICE` and `TASK_DEFINITION`. */ propagateTags?: pulumi.Input<string>; /** * Scheduling strategy to use for the service. The valid values are `REPLICA` and `DAEMON`. Defaults to `REPLICA`. Note that [*Tasks using the Fargate launch type or the `CODE_DEPLOY` or `EXTERNAL` deployment controller types don't support the `DAEMON` scheduling strategy*](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html). */ schedulingStrategy?: pulumi.Input<string>; /** * Service discovery registries for the service. The maximum number of `serviceRegistries` blocks is `1`. Detailed below. */ serviceRegistries?: pulumi.Input<inputs.ecs.ServiceServiceRegistries>; /** * Key-value map of resource tags. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service. Required unless using the `EXTERNAL` deployment controller. If a revision is not specified, the latest `ACTIVE` revision is used. */ taskDefinition?: pulumi.Input<string>; /** * If `true`, this provider will wait for the service to reach a steady state (like [`aws ecs wait services-stable`](https://docs.aws.amazon.com/cli/latest/reference/ecs/wait/services-stable.html)) before continuing. Default `false`. */ waitForSteadyState?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a Service resource. */ export interface ServiceArgs { /** * Capacity provider strategy to use for the service. Can be one or more. Detailed below. */ capacityProviderStrategies?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceCapacityProviderStrategy>[]>; /** * ARN of an ECS cluster */ cluster?: pulumi.Input<string>; /** * Configuration block for deployment circuit breaker. Detailed below. */ deploymentCircuitBreaker?: pulumi.Input<inputs.ecs.ServiceDeploymentCircuitBreaker>; /** * Configuration block for deployment controller configuration. Detailed below. */ deploymentController?: pulumi.Input<inputs.ecs.ServiceDeploymentController>; /** * Upper limit (as a percentage of the service's desiredCount) of the number of running tasks that can be running in a service during a deployment. Not valid when using the `DAEMON` scheduling strategy. */ deploymentMaximumPercent?: pulumi.Input<number>; /** * Lower limit (as a percentage of the service's desiredCount) of the number of running tasks that must remain running and healthy in a service during a deployment. */ deploymentMinimumHealthyPercent?: pulumi.Input<number>; /** * Number of instances of the task definition to place and keep running. Defaults to 0. Do not specify if using the `DAEMON` scheduling strategy. */ desiredCount?: pulumi.Input<number>; /** * Specifies whether to enable Amazon ECS managed tags for the tasks within the service. */ enableEcsManagedTags?: pulumi.Input<boolean>; /** * Specifies whether to enable Amazon ECS Exec for the tasks within the service. */ enableExecuteCommand?: pulumi.Input<boolean>; /** * Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination (e.g. `myimage:latest`), roll Fargate tasks onto a newer platform version, or immediately deploy `orderedPlacementStrategy` and `placementConstraints` updates. */ forceNewDeployment?: pulumi.Input<boolean>; /** * Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers. */ healthCheckGracePeriodSeconds?: pulumi.Input<number>; /** * ARN of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is required if you are using a load balancer with your service, but only if your task definition does not use the `awsvpc` network mode. If using `awsvpc` network mode, do not specify this role. If your account has already created the Amazon ECS service-linked role, that role is used by default for your service unless you specify a role here. */ iamRole?: pulumi.Input<string>; /** * Launch type on which to run your service. The valid values are `EC2`, `FARGATE`, and `EXTERNAL`. Defaults to `EC2`. */ launchType?: pulumi.Input<string>; /** * Configuration block for load balancers. Detailed below. */ loadBalancers?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceLoadBalancer>[]>; /** * Name of the service (up to 255 letters, numbers, hyphens, and underscores) */ name?: pulumi.Input<string>; /** * Network configuration for the service. This parameter is required for task definitions that use the `awsvpc` network mode to receive their own Elastic Network Interface, and it is not supported for other network modes. Detailed below. */ networkConfiguration?: pulumi.Input<inputs.ecs.ServiceNetworkConfiguration>; /** * Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. The maximum number of `orderedPlacementStrategy` blocks is `5`. Detailed below. */ orderedPlacementStrategies?: pulumi.Input<pulumi.Input<inputs.ecs.ServiceOrderedPlacementStrategy>[]>; /** * Rules that are taken into consideration during task placement. Updates to this configuration will take effect next task deployment unless `forceNewDeployment` is enabled. Maximum number of `placementConstraints` is `10`. Detailed below. */ placementConstraints?: pulumi.Input<pulumi.Input<inputs.ecs.ServicePlacementConstraint>[]>; /** * Platform version on which to run your service. Only applicable for `launchType` set to `FARGATE`. Defaults to `LATEST`. More information about Fargate platform versions can be found in the [AWS ECS User Guide](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/platform_versions.html). */ platformVersion?: pulumi.Input<string>; /** * Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values are `SERVICE` and `TASK_DEFINITION`. */ propagateTags?: pulumi.Input<string>; /** * Scheduling strategy to use for the service. The valid values are `REPLICA` and `DAEMON`. Defaults to `REPLICA`. Note that [*Tasks using the Fargate launch type or the `CODE_DEPLOY` or `EXTERNAL` deployment controller types don't support the `DAEMON` scheduling strategy*](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html). */ schedulingStrategy?: pulumi.Input<string>; /** * Service discovery registries for the service. The maximum number of `serviceRegistries` blocks is `1`. Detailed below. */ serviceRegistries?: pulumi.Input<inputs.ecs.ServiceServiceRegistries>; /** * Key-value map of resource tags. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Family and revision (`family:revision`) or full ARN of the task definition that you want to run in your service. Required unless using the `EXTERNAL` deployment controller. If a revision is not specified, the latest `ACTIVE` revision is used. */ taskDefinition?: pulumi.Input<string>; /** * If `true`, this provider will wait for the service to reach a steady state (like [`aws ecs wait services-stable`](https://docs.aws.amazon.com/cli/latest/reference/ecs/wait/services-stable.html)) before continuing. Default `false`. */ waitForSteadyState?: pulumi.Input<boolean>; }
the_stack
import React, { FormHTMLAttributes, HTMLProps, InputHTMLAttributes, Ref } from 'react'; export type TreeItemIndex = string | number; export interface TreeItem<T = any> { index: TreeItemIndex; children?: Array<TreeItemIndex>; hasChildren?: boolean; // isChildrenLoading?: boolean; canMove?: boolean; canRename?: boolean; data: T; } export interface TreePosition { treeId: string; parent: TreeItemIndex; index: number; } export interface TreeItemActions { primaryAction: () => void; startRenamingItem: () => void; expandItem: () => void; collapseItem: () => void; toggleExpandedState: () => void; truncateItem: () => void; untruncateItem: () => void; toggleTruncatedState: () => void; selectItem: () => void; unselectItem: () => void; addToSelectedItems: () => void; selectUpTo: () => void; startDragging: () => void; focusItem: () => void; // toggleSelectedState: () => void; } export interface TreeItemRenderFlags { isSelected?: boolean; isExpanded?: boolean; isFocused?: boolean; isRenaming?: boolean; isDraggingOver?: boolean; isDraggingOverParent?: boolean; isSearchMatching?: boolean; canDrag?: boolean; canDropOn?: boolean; } export interface TreeItemRenderContext extends TreeItemActions, TreeItemRenderFlags { interactiveElementProps: HTMLProps<any>; itemContainerWithoutChildrenProps: HTMLProps<any>; itemContainerWithChildrenProps: HTMLProps<any>; arrowProps: HTMLProps<any>; } export interface TreeInformation extends TreeConfiguration { areItemsSelected: boolean; isRenaming: boolean; isFocused: boolean; isSearching: boolean; search: string | null; isProgrammaticallyDragging: boolean; } export interface TreeRenderProps<T = any> { renderItem?: (props: { item: TreeItem<T>; depth: number; children: React.ReactNode | null; title: React.ReactNode; arrow: React.ReactNode; context: TreeItemRenderContext; info: TreeInformation; }) => React.ReactElement | null; renderItemTitle?: (props: { title: string; item: TreeItem<T>; context: TreeItemRenderContext; info: TreeInformation; }) => React.ReactElement | null | string; renderItemArrow?: (props: { item: TreeItem<T>; context: TreeItemRenderContext; info: TreeInformation; }) => React.ReactElement | null; renderRenameInput?: (props: { item: TreeItem<T>; inputProps: InputHTMLAttributes<HTMLInputElement>; inputRef: Ref<HTMLInputElement>; submitButtonProps: HTMLProps<any>; submitButtonRef: Ref<any>; formProps: FormHTMLAttributes<HTMLFormElement>; }) => React.ReactElement | null; renderDraggingItem?: (props: { items: Array<TreeItem<T>> }) => React.ReactElement | null; renderDraggingItemTitle?: (props: { items: Array<TreeItem<T>> }) => React.ReactElement | null; renderItemsContainer?: (props: { children: React.ReactNode; containerProps: HTMLProps<any>; info: TreeInformation; }) => React.ReactElement | null; renderTreeContainer?: (props: { children: React.ReactNode; containerProps: HTMLProps<any>; info: TreeInformation; }) => React.ReactElement | null; renderDragBetweenLine?: (props: { draggingPosition: DraggingPosition; lineProps: HTMLProps<any>; }) => React.ReactElement | null; renderSearchInput?: (props: { inputProps: HTMLProps<HTMLInputElement> }) => React.ReactElement | null; renderLiveDescriptorContainer?: (props: { children: React.ReactNode; tree: TreeConfiguration; }) => React.ReactElement | null; renderDepthOffset?: number; } export type AllTreeRenderProps<T = any> = Required<TreeRenderProps<T>>; export enum InteractionMode { DoubleClickItemToExpand = 'double-click-item-to-expand', ClickItemToExpand = 'click-item-to-expand', ClickArrowToExpand = 'click-arrow-to-expand', } export interface InteractionManager { mode: InteractionMode | string; extends?: InteractionMode; createInteractiveElementProps: ( item: TreeItem, treeId: string, actions: TreeItemActions, renderFlags: TreeItemRenderFlags ) => HTMLProps<HTMLElement>; } export interface TreeCapabilities<T = any> { defaultInteractionMode?: InteractionMode | InteractionManager; canDragAndDrop?: boolean; canDropOnItemWithChildren?: boolean; canDropOnItemWithoutChildren?: boolean; canReorderItems?: boolean; canDrag?: (items: TreeItem<T>[]) => boolean; canDropAt?: (items: TreeItem<T>[], target: DraggingPosition) => boolean; canInvokePrimaryActionOnItemContainer?: boolean; canSearch?: boolean; canSearchByStartingTyping?: boolean; canRename?: boolean; autoFocus?: boolean; doesSearchMatchItem?: (search: string, item: TreeItem<T>, itemTitle: string) => boolean; showLiveDescription?: boolean; } export interface IndividualTreeViewState { selectedItems?: TreeItemIndex[]; expandedItems?: TreeItemIndex[]; untruncatedItems?: TreeItemIndex[]; focusedItem?: TreeItemIndex; } export interface TreeViewState { [treeId: string]: IndividualTreeViewState | undefined; } export interface ExplicitDataSource<T = any> { items: Record<TreeItemIndex, TreeItem<T>>; } export interface ImplicitDataSource<T = any> { dataProvider: TreeDataProvider<T>; } export type DataSource<T = any> = ExplicitDataSource<T> | ImplicitDataSource<T>; export interface TreeChangeHandlers<T = any> { onStartRenamingItem?: (item: TreeItem<T>, treeId: string) => void; onRenameItem?: (item: TreeItem<T>, name: string, treeId: string) => void; onAbortRenamingItem?: (item: TreeItem<T>, treeId: string) => void; onCollapseItem?: (item: TreeItem<T>, treeId: string) => void; onExpandItem?: (item: TreeItem<T>, treeId: string) => void; onSelectItems?: (items: TreeItemIndex[], treeId: string) => void; // TODO TreeItem instead of just index onFocusItem?: (item: TreeItem<T>, treeId: string) => void; onDrop?: (items: TreeItem<T>[], target: DraggingPosition) => void; onPrimaryAction?: (items: TreeItem<T>, treeId: string) => void; onRegisterTree?: (tree: TreeConfiguration) => void; onUnregisterTree?: (tree: TreeConfiguration) => void; onMissingItems?: (itemIds: TreeItemIndex[]) => void; onMissingChildren?: (itemIds: TreeItemIndex[]) => void; // TODO } export interface TreeEnvironmentChangeActions { focusTree: (treeId: string, autoFocus?: boolean) => void; renameItem: (itemId: TreeItemIndex, name: string, treeId: string) => void; collapseItem: (itemId: TreeItemIndex, treeId: string) => void; expandItem: (itemId: TreeItemIndex, treeId: string) => void; toggleItemExpandedState: (itemId: TreeItemIndex, treeId: string) => void; selectItems: (itemsIds: TreeItemIndex[], treeId: string) => void; toggleItemSelectStatus: (itemId: TreeItemIndex, treeId: string) => void; invokePrimaryAction: (itemId: TreeItemIndex, treeID: string) => void; focusItem: (itemId: TreeItemIndex, treeId: string) => void; moveFocusUp: (treeId: string) => void; moveFocusDown: (treeId: string) => void; startProgrammaticDrag: () => void; abortProgrammaticDrag: () => void; completeProgrammaticDrag: () => void; moveProgrammaticDragPositionUp: () => void; moveProgrammaticDragPositionDown: () => void; } export type TreeEnvironmentActionsContextProps = TreeEnvironmentChangeActions; export interface TreeEnvironmentRef<T = any> extends TreeEnvironmentChangeActions, Omit<TreeEnvironmentConfiguration<T>, keyof TreeChangeHandlers> { treeEnvironmentContext: TreeEnvironmentContextProps; dragAndDropContext: DragAndDropContextProps; } export interface TreeEnvironmentConfiguration<T = any> extends TreeRenderProps<T>, TreeCapabilities<T>, TreeChangeHandlers<T>, ExplicitDataSource<T> { viewState: TreeViewState; keyboardBindings?: KeyboardBindings; liveDescriptors?: LiveDescriptors; getItemTitle: (item: TreeItem<T>) => string; } export interface TreeEnvironmentContextProps<T = any> extends Omit<TreeEnvironmentConfiguration<T>, keyof TreeRenderProps>, AllTreeRenderProps<T> { registerTree: (tree: TreeConfiguration) => void; unregisterTree: (treeId: string) => void; activeTreeId?: string; setActiveTree: ( treeIdOrSetStateFunction: string | undefined | ((prevState: string | undefined) => string | undefined), autoFocus?: boolean ) => void; treeIds: string[]; trees: Record<string, TreeConfiguration>; } export interface DragAndDropContextProps<T = any> { onStartDraggingItems: (items: TreeItem<T>[], treeId: string) => void; draggingItems?: TreeItem<T>[]; itemHeight: number; isProgrammaticallyDragging?: boolean; startProgrammaticDrag: () => void; abortProgrammaticDrag: () => void; completeProgrammaticDrag: () => void; programmaticDragUp: () => void; programmaticDragDown: () => void; draggingPosition?: DraggingPosition; viableDragPositions?: { [treeId: string]: DraggingPosition[] }; linearItems?: Array<{ item: TreeItemIndex; depth: number }>; onDragOverTreeHandler: ( e: DragEvent, treeId: string, containerRef: React.MutableRefObject<HTMLElement | undefined> ) => void; } export type DraggingPosition = DraggingPositionItem | DraggingPositionBetweenItems; export interface AbstractDraggingPosition { targetType: 'item' | 'between-items'; treeId: string; parentItem: TreeItemIndex; linearIndex: number; depth: number; } export interface DraggingPositionItem extends AbstractDraggingPosition { targetType: 'item'; targetItem: TreeItemIndex; } export interface DraggingPositionBetweenItems extends AbstractDraggingPosition { targetType: 'between-items'; childIndex: number; linePosition: 'top' | 'bottom'; } export interface ControlledTreeEnvironmentProps<T = any> extends TreeEnvironmentConfiguration<T> { children?: JSX.Element | JSX.Element[] | null; } export interface UncontrolledTreeEnvironmentProps<T = any> extends TreeRenderProps<T>, TreeCapabilities, ImplicitDataSource<T>, TreeChangeHandlers<T> { viewState: TreeViewState; keyboardBindings?: KeyboardBindings; liveDescriptors?: LiveDescriptors; getItemTitle: (item: TreeItem<T>) => string; children: JSX.Element | JSX.Element[] | null; } export interface TreeConfiguration { treeId: string; rootItem: string; treeLabel?: string; treeLabelledBy?: string; } export interface TreeProps<T = any> extends TreeConfiguration, Partial<TreeRenderProps<T>> {} export interface TreeContextProps extends TreeConfiguration { search: string | null; setSearch: (searchValue: string | null) => void; renamingItem: TreeItemIndex | null; setRenamingItem: (item: TreeItemIndex | null) => void; renderers: AllTreeRenderProps; treeInformation: TreeInformation; getItemsLinearly: () => Array<{ item: TreeItemIndex; depth: number }>; } export interface TreeChangeActions { focusTree: (autoFocus?: boolean) => void; startRenamingItem: (itemId: TreeItemIndex) => void; stopRenamingItem: () => void; completeRenamingItem: () => void; abortRenamingItem: () => void; renameItem: (itemId: TreeItemIndex, name: string) => void; collapseItem: (itemId: TreeItemIndex) => void; expandItem: (itemId: TreeItemIndex) => void; toggleItemExpandedState: (itemId: TreeItemIndex) => void; selectItems: (itemsIds: TreeItemIndex[]) => void; toggleItemSelectStatus: (itemId: TreeItemIndex) => void; focusItem: (itemId: TreeItemIndex) => void; moveFocusUp: () => void; moveFocusDown: () => void; invokePrimaryAction: (itemId: TreeItemIndex) => void; setSearch: (search: string | null) => void; abortSearch: () => void; } export type TreeChangeActionsContextProps = TreeChangeActions; export interface TreeRef<T = any> extends TreeChangeActions, TreeInformation { treeContext: TreeContextProps; treeEnvironmentContext: TreeEnvironmentContextProps<T>; dragAndDropContext: DragAndDropContextProps<T>; search: string | null; } export interface TreeDataProvider<T = any> { onDidChangeTreeData?: (listener: (changedItemIds: TreeItemIndex[]) => void) => Disposable; getTreeItem: (itemId: TreeItemIndex) => Promise<TreeItem<T>>; getTreeItems?: (itemIds: TreeItemIndex[]) => Promise<TreeItem[]>; onRenameItem?: (item: TreeItem<T>, name: string) => Promise<void>; onChangeItemChildren?: (itemId: TreeItemIndex, newChildren: TreeItemIndex[]) => Promise<void>; } export type Disposable = { dispose: () => void; }; export interface KeyboardBindings { primaryAction?: string[]; moveFocusToFirstItem?: string[]; moveFocusToLastItem?: string[]; expandSiblings?: string[]; renameItem?: string[]; abortRenameItem?: string[]; toggleSelectItem?: string[]; abortSearch?: string[]; startSearch?: string[]; selectAll?: string[]; startProgrammaticDnd?: string[]; abortProgrammaticDnd?: string[]; completeProgrammaticDnd?: string[]; } /** * Live descriptors are written in an aria live region describing the state of the * tree to accessibility readers. They are displayed in a visually hidden area at the * bottom of the tree. Each descriptor composes a HTML string. Variables in the form * of {variableName} can be used. * * The {keybinding:bindingname} variable referns to a specific keybinding, i.e. {keybinding:primaryAction} * is a valid variable. * * See the implementation of the `defaultLiveDescriptors` for more details. */ export interface LiveDescriptors { /** * Supports the following variables: * {treeLabel} {keybinding:bindingname} */ introduction: string; /** * Supports the following variables: * {renamingItem} {keybinding:bindingname} */ renamingItem: string; /** * Supports the following variables: * {keybinding:bindingname} */ searching: string; /** * Supports the following variables: * {dropTarget} {dragItems} {keybinding:bindingname} */ programmaticallyDragging: string; /** * Will be displayed in addition to the programmaticallyDragging description, * but with the aria-live attribute assertive. * * Supports the following variables: * {dropTarget} {dragItems} {keybinding:bindingname} */ programmaticallyDraggingTarget: string; }
the_stack
import fastDeepEqual from 'fast-deep-equal'; import isPlainObject from 'is-plain-object'; export const mapOrElse = ( value: any, mappingFunction: (...args: any[]) => any, orElseValue: any ) => value !== null && value !== undefined ? mappingFunction(value) : orElseValue; export function identity<T>(val: T): T { return val; } export const isFunction = (x: any): x is Function => typeof x === 'function'; // tslint:disable-line ban-types export const noop = (..._args: any[]) => {}; export const falsy = (val: any): boolean => !val; export const truthy = (val: any): boolean => val; export const eq = (a: any) => (b: any) => a === b; // Add more if needed export function pipe<A, B>(f1: (x1: A) => B): (initial: A) => B; export function pipe<A, B, C>( f1: (x1: A) => B, f2: (x2: B) => C ): (initial: A) => C; export function pipe<A, B, C, D>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D ): (initial: A) => D; export function pipe<A, B, C, D, E>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E ): (initial: A) => E; export function pipe<A, B, C, D, E, F>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E, f5: (x5: E) => F ): (initial: A) => F; export function pipe<A, B, C, D, E, F, G>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E, f5: (x5: E) => F, f6: (x6: F) => G ): (initial: A) => G; export function pipe<A, B, C, D, E, F, G, H>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E, f5: (x5: E) => F, f6: (x6: F) => G, f7: (x7: G) => H ): (initial: A) => H; export function pipe<A, B, C, D, E, F, G, H, I>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E, f5: (x5: E) => F, f6: (x6: F) => G, f7: (x7: G) => H, f8: (x8: H) => I ): (initial: A) => I; export function pipe<A, B, C, D, E, F, G, H, I, J>( f1: (x1: A) => B, f2: (x2: B) => C, f3: (x3: C) => D, f4: (x4: D) => E, f5: (x5: E) => F, f6: (x6: F) => G, f7: (x7: G) => H, f8: (x8: H) => I, f9: (x9: I) => J ): (initial: A) => J; export function pipe(...fns: IFunctionAny[]) { return (initial: any) => fns.reduce((arg, f) => f(arg), initial); } export const first = <T>(arr: T[]): T => arr[0]; export const last = <T>(arr: T[]): T => arr[arr.length - 1]; export const zip = <F, S>(xs: F[], ys: Array<S | undefined>): Array<[F, S]> => xs .map((x: F, index: number): [F, S | undefined] => [x, ys[index]]) .filter(([_x, y]) => y !== undefined) as Array<[F, S]>; export const fst = <T>([f, _s]: [T, any]): T => f; export const snd = <T>([_f, s]: [any, T]): T => s; export function count<T>(items: T[], itemOrPredicate: T | ((x: T) => boolean)) { if (typeof itemOrPredicate === 'function') { return items.filter(itemOrPredicate as (x: T) => boolean).length; } else { return items.filter((item) => item === itemOrPredicate).length; } } export const filterValues = <T extends {}>( obj: T, fn: <K extends keyof T>(val: T[K], key: string) => boolean ) => Object.keys(obj).reduce((acc, key: string) => { if (fn(obj[key as keyof T], key)) { return { ...acc, [key]: obj[key as keyof T] }; } return acc; }, {}); export const tryOrDefault = <T>(fn: () => T, fallback: T) => { try { return fn(); } catch (e) { return fallback; } }; export const not = (fn: (...args: any[]) => boolean) => (...args: any[]) => !fn(...args); export const range = (from: number, to: number, step: number = 1) => { const arr = []; for (let i = from; i < to; i += step) { arr.push(i); } return arr; }; interface IIdLookup<T> { [index: string]: T; } export function dictionaryForIds< T extends { [key: string]: string | number } & any >(collection: T[], field: keyof T): IIdLookup<T> { return collection.reduce( (acc: IIdLookup<T>, item: T) => ({ ...acc, [String(get(item, field))]: item }), {} ); } const keys = (it: IObjectAny | any[]): string[] => { if (it == null) { return []; } else if (Array.isArray(it)) { return it.map((_: any, index) => String(index)); } else if (isObject(it)) { return Object.keys(it); } else { return []; } }; export const deepKeys = ( obj: IObjectAny, diveIntoArrays: boolean = false ): string[] => { return keys(obj).reduce((keys: string[], key: string) => { if (diveIntoArrays && obj[key] && Array.isArray(obj[key])) { if (obj[key].length === 0) { return keys; } const producedKeys = flatMap(obj[key], (it: IObjectAny, index) => deepKeys(it, diveIntoArrays).map( (deepKey) => `${key}[${index}].${deepKey}` ) ); return producedKeys.length === 0 ? [ ...keys, ...obj[key].map((_: any, index: number) => `${key}[${index}]`) ] : [...keys, ...producedKeys]; } else if ( obj[key] && isObject(obj[key]) && !Array.isArray(obj[key]) && typeof obj[key] !== 'function' ) { return [ ...keys, ...deepKeys(obj[key], diveIntoArrays).map( (deepKey) => `${key}.${deepKey}` ) ]; } else { return [...keys, key]; } }, []); }; export type Equality<T> = (a: T, b: T) => boolean; export const objectDiffBy = ( equalsFn: Equality<any>, objA: IObjectAny, objB: IObjectAny ) => { const keysA = deepKeys(objA); const keysB = deepKeys(objB); const allKeys = new Set([...keysA, ...keysB]); const diff = {}; allKeys.forEach((key: string) => { const valueA = get(objA, key); const valueB = get(objB, key); set(diff, key as any, !equalsFn(valueA, valueB)); }); return diff; }; export const objectDiff = ( objA: IObjectAny = {}, objB: IObjectAny = {} ): IObjectAny => { return objectDiffBy((a, b) => a === b, objA, objB); }; export const existsDeepDiffBy = ( equalsFn: Equality<any>, objA: IObjectAny, objB: IObjectAny ) => { const keysA = deepKeys(objA); const keysB = deepKeys(objB); const allKeys = Array.from(new Set([...keysA, ...keysB])); return allKeys.some((key) => !equalsFn(get(objA, key), get(objB, key))); }; export const existsDeepDiff = (objA: IObjectAny, objB: IObjectAny) => existsDeepDiffBy((a, b) => a === b, objA, objB); export const deduplicateBy = <T>(key: keyof T, items: T[]): T[] => { const uniqueProps = Array.from(new Set(items.map((item: T) => item[key]))); return uniqueProps.map((value) => items.find((item: T) => item[key] === value) ) as T[]; }; export const valueOrNull = <T>(x: T): T | null => { if (x == null) { return null; } else if (typeof x === 'number' || typeof x === 'boolean') { return x; } else { return !isEmpty(x) ? x : null; } }; export const flatten = <T>(xss: T[][]): T[] => xss.reduce((memo, val) => memo.concat(val), [] as T[]); export const flatMap = <T, S = T>( xs: T[], f: (x: T, index: number, arr: T[]) => S[] ): S[] => flatten(xs.map(f)); export const omit = <T, K extends keyof T>(o: T, ...keys: K[]): Omit<T, K> => { const target: any = {}; Object.keys(o).forEach((key: string) => { if (!keys.includes(key as K)) { target[key] = o[key as keyof T]; } }); return target as Omit<T, K>; }; export const pick = <T, K extends keyof T>(o: T, ...keys: K[]): Pick<T, K> => { const target: any = {}; keys.forEach((key) => { target[key] = o[key]; }); return target as Pick<T, K>; }; export const isObject = isPlainObject; export const isEmpty = (x: any): boolean => { if (!x) { return true; } if (Array.isArray(x) || typeof x === 'string') { return x.length === 0; } if (isObject(x)) { return Object.keys(x).filter((k) => x[k] != null).length === 0; } return true; }; export function groupBy<T, K extends string>( xs: T[], grouper: (x: T) => K ): { [key: string]: T[] }; export function groupBy<T, K extends number>( xs: T[], grouper: (x: T) => K ): { [key: number]: T[] }; export function groupBy<T, _K>(xs: T[], grouper: IFunctionAny) { const lookup: any = {}; xs.forEach((x: T) => { const key: keyof T = grouper(x); if (lookup[key] == null) { lookup[key] = []; } lookup[key].push(x); }); return lookup; } type ILookup<K extends string | number, T> = K extends string ? { [key: string]: T } : { [key: number]: T }; export function mapValues<T, K extends string, R>( map: ILookup<K, T>, fn: (x: T, key?: string) => R ): { [key: string]: R }; export function mapValues<T, K extends number, R>( map: ILookup<K, T>, fn: (x: T, key?: string) => R ): { [key: number]: R }; export function mapValues(map: any, fn: IFunctionAny) { return Object.keys(map).reduce( (acc, key) => ({ ...acc, [key]: fn(map[key], key) }), {} ); } export const isDeepEqual = fastDeepEqual; export const isEqual = <T>(xs?: T, ys?: T): boolean => { if (xs === ys) { return true; } if ( (typeof xs === 'string' || xs instanceof String) && (typeof ys === 'string' || ys instanceof String) ) { return xs.toString() === ys.toString(); } if ( (typeof xs === 'number' || xs instanceof Number) && (typeof ys === 'number' || ys instanceof Number) ) { if ( Number.isNaN(Number(xs).valueOf()) && Number.isNaN(Number(ys).valueOf()) ) { // tslint:disable-line no-construct return true; } return Number(xs).valueOf() === Number(ys).valueOf(); // tslint:disable-line no-construct } if ( (typeof xs === 'boolean' || xs instanceof Boolean) && (typeof ys === 'boolean' || ys instanceof Boolean) ) { const bxs = xs instanceof Boolean ? xs.valueOf() : xs; const bys = ys instanceof Boolean ? ys.valueOf() : ys; return bxs === bys; } if (Array.isArray(xs) && Array.isArray(ys)) { return ( (xs as any).length === (ys as any).length && (xs as any).every((x: any, i: number) => isEqual(x, ys[i])) ); } if (xs instanceof Set && ys instanceof Set) { if (xs.size !== ys.size) { return false; } for (const x of Array.from(xs)) { if (!ys.has(x)) { return false; } } return true; } if (isObject(xs) && isObject(ys)) { const keysXs = Object.keys(xs!); const keysYs = Object.keys(ys!); if (keysXs.length !== keysYs.length) { return false; } return keysXs.every((key) => isEqual(xs![key as keyof T], ys![key as keyof T]) ); } return false; }; export type Path = string | string[]; const normalizePath = <T>(path: Path): DeepKeyOf<T> & string[] => Array.isArray(path) ? path : path.replace(/\[(.+?)\]/g, '.$1').split('.'); const isNumberKey = (key: string | number) => { if (typeof key === 'number') { return key >= 0; } const parsed = Number.parseInt(key, 10); return !Number.isNaN(parsed) && parsed >= 0; }; export const set = <T, K extends DeepKeyOf<T>>( x: T, path: K, value?: DeepTypeOf<T, K> ): T => { const normalizedPath = normalizePath(path as Path); let target: any = x; normalizedPath.forEach((fragment, index) => { const nextFragment = normalizedPath[index + 1]; const key = isNumberKey(fragment) ? parseInt(fragment, 10) : fragment; const nextKey = isNumberKey(nextFragment) ? parseInt(nextFragment, 10) : nextFragment; if (index === normalizedPath.length - 1) { target[key] = value; return; } if (target[key] == null) { target[key] = typeof nextKey === 'number' ? [] : {}; } target = target[key]; }); return x; }; export const get = <T, K extends DeepKeyOf<T>>( x: T, path: K, fallback?: DeepTypeOf<T, K> ): DeepTypeOf<T, K> | undefined => { if (path == null) { return fallback; } const normalizedPath = normalizePath(path as Path); let target: any = x; let index = 0; for (const fragment of normalizedPath) { if (index++ === normalizedPath.length - 1) { return target != null && target[fragment] != null ? target[fragment] : fallback; } if (target == null || target[fragment] == null) { return fallback; } target = target[fragment]; } return fallback; }; export const mapIfDefined = <T, R>( x: T | undefined | null, f: (a: T) => R ): R | undefined | null => (x != null ? f(x) : null); export const defaulting = <T>(value: T | undefined | null, fallback: T): T => value != null ? value : fallback; export const mapOrDefault = <T, R>( x: T | undefined | null, f: (a: T) => R, fallback: R ): R => (x != null ? f(x) : fallback); export const takeWhile = <T>(xs: T[], p: (a: T) => boolean): T[] => { const result = []; for (const x of xs) { if (p(x)) { result.push(x); } else { break; } } return result; }; export const squashObject = <T>(x?: T): T | undefined => x == null || Object.keys(x).filter((k) => x[k as keyof T] != null).length === 0 ? undefined : x; // Checks if the passed object type is Set, and if not makes it a Set object accordingly // This function added to make sure selectors having the correct data types after Rehydration. // TODO: See IFOA-186 for details. export const ensureSet = <T>(item: IObjectAny): Set<T> => { let output: Set<T> | null = null; if (!(item instanceof Set)) { output = Array.isArray(item) && (item as T[]).length > 0 ? new Set<T>(item) : new Set<T>(); } return output != null ? output : new Set(item as Set<T>); }; export const concatUnique = <T>(xs: T[][]): T[] => { const result = []; const items = flatten(xs); for (const item of items) { if (result.find((i) => isEqual(item, i)) == null) { result.push(item); } } return result; }; export const moveFromToIndex = <T>(xs: T[], i: number, j: number): T[] => { const x = xs[i]; const result = [...xs]; if (i === j - 1) { return result; } result.splice(i, 1); result.splice(j, 0, x); return result; };
the_stack
import * as React from "react"; import { SchemaSelector } from "./SchemaSelector"; import { SchemaDetail } from "./SchemaDetail"; import { SchemaNewButton } from "./SchemaNewButton"; import { DragDropContext } from "react-beautiful-dnd"; import { SchemaFormModal } from "./SchemaFormModal"; import { SchemaForm } from "./SchemaForm"; import { TokenPluralization, UUID, CreatedByValues, PluginMetadata, buildDefaultConfiguration, SchemaInput, Primitives, ProjectInput, RelationInput, validateSchema, } from "@codotype/core"; import { reorder } from "../AttributeEditor/reorder"; import { EmptyState } from "./EmptyState"; // // // // interface EditorState { projectInput: ProjectInput; lastUpdatedAt: null | number; } /** * SchemaEditorLayout * @param props.projectInput * @param props.pluginMetadata * @param props.onChange */ export function SchemaEditorLayout(props: { projectInput: ProjectInput; pluginMetadata: PluginMetadata; onChange: (updatedProjectInput: ProjectInput) => void; }) { const { projectInput } = props; const { schemas } = projectInput; const [showModal, setShowModal] = React.useState(false); const [showEditModal, setShowEditModal] = React.useState(false); const [ newTokenPluralization, setNewTokenPluralization, ] = React.useState<TokenPluralization | null>(null); const [state, setState] = React.useState<EditorState>({ projectInput: props.projectInput, lastUpdatedAt: null, }); const [selectedSchemaId, setSelectedSchemaId] = React.useState<UUID | null>( null, ); // Update state.projectInput.schemas when schemas changes React.useEffect(() => { setState({ ...state, projectInput: { ...projectInput, schemas } }); }, [schemas]); // Invoke props.onChange when state.projectInput.schemas has updated React.useEffect(() => { props.onChange({ ...props.projectInput, schemas: state.projectInput.schemas, }); }, [state.lastUpdatedAt]); // Sets selectedSchemaId if none is defined if (state.projectInput.schemas[0] && selectedSchemaId == null) { setSelectedSchemaId(state.projectInput.schemas[0].id); return null; } // Defines selectedSchema const selectedSchema: | SchemaInput | undefined = state.projectInput.schemas.find((s: SchemaInput) => { return s.id === selectedSchemaId; }); // Defines handler for creating new schemas function createNewSchema() { // Short-circuit if newTokenPluralization is null if (newTokenPluralization === null) { return; } const errors = validateSchema({ schemaCollection: schemas, tokenPluralization: newTokenPluralization, }); // Short-circuit if if (errors.length > 0) { return; } // Defines new schema const newSchema: SchemaInput = new Primitives.Schema({ attributes: [ ...props.pluginMetadata.schemaEditorConfiguration.newSchemaDefaults.attributes.map( a => { return { ...a, }; }, ), ], locked: false, createdBy: CreatedByValues.user, identifiers: newTokenPluralization, configuration: buildDefaultConfiguration( props.pluginMetadata.schemaEditorConfiguration .configurationGroups, ), }); // ProjectInput.relations const defaultRelations = props.pluginMetadata.schemaEditorConfiguration.defaultRelations; const updatedRelations = [ ...state.projectInput.relations, ...defaultRelations.map(r => { // Return new relation where destinationSchemaID is the newly created SchemaInput if (r.destinationSchemaID === "") { return { ...r, destinationSchemaID: newSchema.id, }; } // Return new relation where sourceSchemaID is the newly created SchemaInput return { ...r, sourceSchemaID: newSchema.id, }; }), ]; // Defines updated schemas, including NEW schema const updatedSchemas: SchemaInput[] = [ ...state.projectInput.schemas, newSchema, ]; // Updates state.projectInput.schemas with the latest schemas setState({ ...state, lastUpdatedAt: Date.now(), projectInput: { ...state.projectInput, schemas: updatedSchemas, relations: updatedRelations, }, }); // Select the newly created schema setSelectedSchemaId(newSchema.id); // Clears newTokenPluralization setShowModal(false); setNewTokenPluralization(null); } // Defines handler for updating existing schemas function updateExistingSchema() { // Short-circuit if newTokenPluralization is null if (newTokenPluralization === null) { return; } if (!selectedSchema) { return; } // Defines updatedSchema const updatedSchema: SchemaInput = { ...selectedSchema, identifiers: newTokenPluralization, }; const errors = validateSchema({ schemaCollection: schemas, tokenPluralization: newTokenPluralization, }); // Short-circuit if if (errors.length > 0) { return; } // Defines updated schemas, including NEW schema const updatedSchemas: SchemaInput[] = state.projectInput.schemas.map( (s: SchemaInput) => { if (s.id === updatedSchema.id) { return updatedSchema; } return s; }, ); // Updates state.projectInput.schemas with the latest schemas setState({ ...state, lastUpdatedAt: Date.now(), projectInput: { ...state.projectInput, schemas: updatedSchemas, }, }); // Closes edit modal setShowEditModal(false); // Clears newTokenPluralization setNewTokenPluralization(null); } // Last check to ensure that selectedSchema _can_ be defined // NOTE - this should be simpler + combined with the above if (selectedSchema === undefined && state.projectInput.schemas.length > 0) { setSelectedSchemaId(state.projectInput.schemas[0].id); } // Show empty state if (selectedSchemaId === null || selectedSchema === undefined) { return ( <EmptyState plugin={props.pluginMetadata} onNewTokenChange={setNewTokenPluralization} onKeydownEnter={() => { createNewSchema(); }} disabled={ newTokenPluralization === null || newTokenPluralization.singular.title === "" } onSubmit={() => { createNewSchema(); }} onSelectExampleProject={(exampleProjectInput: ProjectInput) => { // Pull data model from exampleProjectInput props.onChange({ ...projectInput, identifiers: { ...exampleProjectInput.identifiers, }, schemas: [...exampleProjectInput.schemas], relations: [...exampleProjectInput.relations], }); }} /> ); } // Defines onDragEnd callback for <DragDropContext /> function onDragEnd(result: any) { if (!result.destination) { return; } if (result.destination.index === result.source.index) { return; } const updatedSchemas = reorder<SchemaInput>( state.projectInput.schemas, result.source.index, result.destination.index, ); setState({ ...state, lastUpdatedAt: Date.now(), projectInput: { ...state.projectInput, schemas: updatedSchemas, }, }); } // Render schema editor layout return ( <div className="grid grid-cols-12 mt-4 gap-4"> <div className="col-span-12 lg:col-span-4"> <SchemaNewButton onClick={() => { if (showModal === false) { setShowModal(true); } }} /> {/* Render SchemaForm + SchemaFormModal for CREATE Schema */} <SchemaFormModal renderNewTitle show={showModal} handleClose={() => { setShowModal(false); }} onSubmit={() => { createNewSchema(); }} errors={validateSchema({ schemaCollection: schemas, tokenPluralization: newTokenPluralization, })} > <SchemaForm label={""} onChange={updatedTokens => { setNewTokenPluralization(updatedTokens); }} onKeydownEnter={() => { createNewSchema(); }} /> </SchemaFormModal> <DragDropContext onDragEnd={onDragEnd}> <SchemaSelector schemaInputs={state.projectInput.schemas} selectedSchemaId={String(selectedSchemaId)} onChange={(updatedSelectedSchema: SchemaInput) => { setSelectedSchemaId(updatedSelectedSchema.id); }} /> </DragDropContext> </div> <div className="col-span-12 lg:col-span-8 mt-4 lg:mt-0"> <div className="card card-body shadow"> <SchemaDetail schema={selectedSchema} projectInput={props.projectInput} pluginMetadata={props.pluginMetadata} onSelectSchema={(nextSelectedSchemaId: UUID) => { setSelectedSchemaId(nextSelectedSchemaId); }} onChangeRelations={( updatedRelations: RelationInput[], ) => { props.onChange({ ...props.projectInput, relations: updatedRelations, }); }} onChange={(updatedSchema: SchemaInput) => { // Defines updatedSchemas to include `updatedSchema` const updatedSchemas: SchemaInput[] = state.projectInput.schemas.map( (s: SchemaInput) => { if (s.id === selectedSchemaId) { return updatedSchema; } return s; }, ); // Updates local state setState({ ...state, lastUpdatedAt: Date.now(), projectInput: { ...state.projectInput, schemas: updatedSchemas, }, }); }} onClickEdit={() => { setShowEditModal(true); }} onConfirmDelete={() => { // Defines updatedSchemas without `selectedSchema` const updatedSchemas: SchemaInput[] = state.projectInput.schemas.filter( (s: SchemaInput) => { return s.id !== selectedSchemaId; }, ); // Removes any relations that reference the deleted schema const updatedRelations: RelationInput[] = state.projectInput.relations.filter( r => { return ( r.destinationSchemaID !== selectedSchemaId && r.sourceSchemaID !== selectedSchemaId ); }, ); // Updates state props.onChange({ ...props.projectInput, schemas: updatedSchemas, relations: updatedRelations, }); // Sets selectedSchemaId to null setSelectedSchemaId(null); }} /> </div> {/* Render SchemaForm + SchemaFormModal for UPDATE Schema */} <SchemaFormModal show={showEditModal} handleClose={() => { setShowEditModal(false); }} onSubmit={() => { updateExistingSchema(); }} errors={validateSchema({ schemaCollection: schemas, tokenPluralization: newTokenPluralization, })} > <SchemaForm label={selectedSchema.identifiers.singular.title} onChange={updatedTokens => { setNewTokenPluralization(updatedTokens); }} onKeydownEnter={() => { updateExistingSchema(); }} /> </SchemaFormModal> </div> </div> ); }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class AuditManager extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: AuditManager.Types.ClientConfiguration) config: Config & AuditManager.Types.ClientConfiguration; /** * Associates an evidence folder to the specified assessment report in Audit Manager. */ associateAssessmentReportEvidenceFolder(params: AuditManager.Types.AssociateAssessmentReportEvidenceFolderRequest, callback?: (err: AWSError, data: AuditManager.Types.AssociateAssessmentReportEvidenceFolderResponse) => void): Request<AuditManager.Types.AssociateAssessmentReportEvidenceFolderResponse, AWSError>; /** * Associates an evidence folder to the specified assessment report in Audit Manager. */ associateAssessmentReportEvidenceFolder(callback?: (err: AWSError, data: AuditManager.Types.AssociateAssessmentReportEvidenceFolderResponse) => void): Request<AuditManager.Types.AssociateAssessmentReportEvidenceFolderResponse, AWSError>; /** * Associates a list of evidence to an assessment report in an Audit Manager assessment. */ batchAssociateAssessmentReportEvidence(params: AuditManager.Types.BatchAssociateAssessmentReportEvidenceRequest, callback?: (err: AWSError, data: AuditManager.Types.BatchAssociateAssessmentReportEvidenceResponse) => void): Request<AuditManager.Types.BatchAssociateAssessmentReportEvidenceResponse, AWSError>; /** * Associates a list of evidence to an assessment report in an Audit Manager assessment. */ batchAssociateAssessmentReportEvidence(callback?: (err: AWSError, data: AuditManager.Types.BatchAssociateAssessmentReportEvidenceResponse) => void): Request<AuditManager.Types.BatchAssociateAssessmentReportEvidenceResponse, AWSError>; /** * Create a batch of delegations for a specified assessment in Audit Manager. */ batchCreateDelegationByAssessment(params: AuditManager.Types.BatchCreateDelegationByAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.BatchCreateDelegationByAssessmentResponse) => void): Request<AuditManager.Types.BatchCreateDelegationByAssessmentResponse, AWSError>; /** * Create a batch of delegations for a specified assessment in Audit Manager. */ batchCreateDelegationByAssessment(callback?: (err: AWSError, data: AuditManager.Types.BatchCreateDelegationByAssessmentResponse) => void): Request<AuditManager.Types.BatchCreateDelegationByAssessmentResponse, AWSError>; /** * Deletes the delegations in the specified Audit Manager assessment. */ batchDeleteDelegationByAssessment(params: AuditManager.Types.BatchDeleteDelegationByAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.BatchDeleteDelegationByAssessmentResponse) => void): Request<AuditManager.Types.BatchDeleteDelegationByAssessmentResponse, AWSError>; /** * Deletes the delegations in the specified Audit Manager assessment. */ batchDeleteDelegationByAssessment(callback?: (err: AWSError, data: AuditManager.Types.BatchDeleteDelegationByAssessmentResponse) => void): Request<AuditManager.Types.BatchDeleteDelegationByAssessmentResponse, AWSError>; /** * Disassociates a list of evidence from the specified assessment report in Audit Manager. */ batchDisassociateAssessmentReportEvidence(params: AuditManager.Types.BatchDisassociateAssessmentReportEvidenceRequest, callback?: (err: AWSError, data: AuditManager.Types.BatchDisassociateAssessmentReportEvidenceResponse) => void): Request<AuditManager.Types.BatchDisassociateAssessmentReportEvidenceResponse, AWSError>; /** * Disassociates a list of evidence from the specified assessment report in Audit Manager. */ batchDisassociateAssessmentReportEvidence(callback?: (err: AWSError, data: AuditManager.Types.BatchDisassociateAssessmentReportEvidenceResponse) => void): Request<AuditManager.Types.BatchDisassociateAssessmentReportEvidenceResponse, AWSError>; /** * Uploads one or more pieces of evidence to the specified control in the assessment in Audit Manager. */ batchImportEvidenceToAssessmentControl(params: AuditManager.Types.BatchImportEvidenceToAssessmentControlRequest, callback?: (err: AWSError, data: AuditManager.Types.BatchImportEvidenceToAssessmentControlResponse) => void): Request<AuditManager.Types.BatchImportEvidenceToAssessmentControlResponse, AWSError>; /** * Uploads one or more pieces of evidence to the specified control in the assessment in Audit Manager. */ batchImportEvidenceToAssessmentControl(callback?: (err: AWSError, data: AuditManager.Types.BatchImportEvidenceToAssessmentControlResponse) => void): Request<AuditManager.Types.BatchImportEvidenceToAssessmentControlResponse, AWSError>; /** * Creates an assessment in Audit Manager. */ createAssessment(params: AuditManager.Types.CreateAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentResponse) => void): Request<AuditManager.Types.CreateAssessmentResponse, AWSError>; /** * Creates an assessment in Audit Manager. */ createAssessment(callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentResponse) => void): Request<AuditManager.Types.CreateAssessmentResponse, AWSError>; /** * Creates a custom framework in Audit Manager. */ createAssessmentFramework(params: AuditManager.Types.CreateAssessmentFrameworkRequest, callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentFrameworkResponse) => void): Request<AuditManager.Types.CreateAssessmentFrameworkResponse, AWSError>; /** * Creates a custom framework in Audit Manager. */ createAssessmentFramework(callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentFrameworkResponse) => void): Request<AuditManager.Types.CreateAssessmentFrameworkResponse, AWSError>; /** * Creates an assessment report for the specified assessment. */ createAssessmentReport(params: AuditManager.Types.CreateAssessmentReportRequest, callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentReportResponse) => void): Request<AuditManager.Types.CreateAssessmentReportResponse, AWSError>; /** * Creates an assessment report for the specified assessment. */ createAssessmentReport(callback?: (err: AWSError, data: AuditManager.Types.CreateAssessmentReportResponse) => void): Request<AuditManager.Types.CreateAssessmentReportResponse, AWSError>; /** * Creates a new custom control in Audit Manager. */ createControl(params: AuditManager.Types.CreateControlRequest, callback?: (err: AWSError, data: AuditManager.Types.CreateControlResponse) => void): Request<AuditManager.Types.CreateControlResponse, AWSError>; /** * Creates a new custom control in Audit Manager. */ createControl(callback?: (err: AWSError, data: AuditManager.Types.CreateControlResponse) => void): Request<AuditManager.Types.CreateControlResponse, AWSError>; /** * Deletes an assessment in Audit Manager. */ deleteAssessment(params: AuditManager.Types.DeleteAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentResponse) => void): Request<AuditManager.Types.DeleteAssessmentResponse, AWSError>; /** * Deletes an assessment in Audit Manager. */ deleteAssessment(callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentResponse) => void): Request<AuditManager.Types.DeleteAssessmentResponse, AWSError>; /** * Deletes a custom framework in Audit Manager. */ deleteAssessmentFramework(params: AuditManager.Types.DeleteAssessmentFrameworkRequest, callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentFrameworkResponse) => void): Request<AuditManager.Types.DeleteAssessmentFrameworkResponse, AWSError>; /** * Deletes a custom framework in Audit Manager. */ deleteAssessmentFramework(callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentFrameworkResponse) => void): Request<AuditManager.Types.DeleteAssessmentFrameworkResponse, AWSError>; /** * Deletes an assessment report from an assessment in Audit Manager. */ deleteAssessmentReport(params: AuditManager.Types.DeleteAssessmentReportRequest, callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentReportResponse) => void): Request<AuditManager.Types.DeleteAssessmentReportResponse, AWSError>; /** * Deletes an assessment report from an assessment in Audit Manager. */ deleteAssessmentReport(callback?: (err: AWSError, data: AuditManager.Types.DeleteAssessmentReportResponse) => void): Request<AuditManager.Types.DeleteAssessmentReportResponse, AWSError>; /** * Deletes a custom control in Audit Manager. */ deleteControl(params: AuditManager.Types.DeleteControlRequest, callback?: (err: AWSError, data: AuditManager.Types.DeleteControlResponse) => void): Request<AuditManager.Types.DeleteControlResponse, AWSError>; /** * Deletes a custom control in Audit Manager. */ deleteControl(callback?: (err: AWSError, data: AuditManager.Types.DeleteControlResponse) => void): Request<AuditManager.Types.DeleteControlResponse, AWSError>; /** * Deregisters an account in Audit Manager. */ deregisterAccount(params: AuditManager.Types.DeregisterAccountRequest, callback?: (err: AWSError, data: AuditManager.Types.DeregisterAccountResponse) => void): Request<AuditManager.Types.DeregisterAccountResponse, AWSError>; /** * Deregisters an account in Audit Manager. */ deregisterAccount(callback?: (err: AWSError, data: AuditManager.Types.DeregisterAccountResponse) => void): Request<AuditManager.Types.DeregisterAccountResponse, AWSError>; /** * Removes the specified member account as a delegated administrator for Audit Manager. When you remove a delegated administrator from your Audit Manager settings, or when you deregister a delegated administrator from Organizations, you continue to have access to the evidence that you previously collected under that account. However, Audit Manager will stop collecting and attaching evidence to that delegated administrator account moving forward. */ deregisterOrganizationAdminAccount(params: AuditManager.Types.DeregisterOrganizationAdminAccountRequest, callback?: (err: AWSError, data: AuditManager.Types.DeregisterOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.DeregisterOrganizationAdminAccountResponse, AWSError>; /** * Removes the specified member account as a delegated administrator for Audit Manager. When you remove a delegated administrator from your Audit Manager settings, or when you deregister a delegated administrator from Organizations, you continue to have access to the evidence that you previously collected under that account. However, Audit Manager will stop collecting and attaching evidence to that delegated administrator account moving forward. */ deregisterOrganizationAdminAccount(callback?: (err: AWSError, data: AuditManager.Types.DeregisterOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.DeregisterOrganizationAdminAccountResponse, AWSError>; /** * Disassociates an evidence folder from the specified assessment report in Audit Manager. */ disassociateAssessmentReportEvidenceFolder(params: AuditManager.Types.DisassociateAssessmentReportEvidenceFolderRequest, callback?: (err: AWSError, data: AuditManager.Types.DisassociateAssessmentReportEvidenceFolderResponse) => void): Request<AuditManager.Types.DisassociateAssessmentReportEvidenceFolderResponse, AWSError>; /** * Disassociates an evidence folder from the specified assessment report in Audit Manager. */ disassociateAssessmentReportEvidenceFolder(callback?: (err: AWSError, data: AuditManager.Types.DisassociateAssessmentReportEvidenceFolderResponse) => void): Request<AuditManager.Types.DisassociateAssessmentReportEvidenceFolderResponse, AWSError>; /** * Returns the registration status of an account in Audit Manager. */ getAccountStatus(params: AuditManager.Types.GetAccountStatusRequest, callback?: (err: AWSError, data: AuditManager.Types.GetAccountStatusResponse) => void): Request<AuditManager.Types.GetAccountStatusResponse, AWSError>; /** * Returns the registration status of an account in Audit Manager. */ getAccountStatus(callback?: (err: AWSError, data: AuditManager.Types.GetAccountStatusResponse) => void): Request<AuditManager.Types.GetAccountStatusResponse, AWSError>; /** * Returns an assessment from Audit Manager. */ getAssessment(params: AuditManager.Types.GetAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentResponse) => void): Request<AuditManager.Types.GetAssessmentResponse, AWSError>; /** * Returns an assessment from Audit Manager. */ getAssessment(callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentResponse) => void): Request<AuditManager.Types.GetAssessmentResponse, AWSError>; /** * Returns a framework from Audit Manager. */ getAssessmentFramework(params: AuditManager.Types.GetAssessmentFrameworkRequest, callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentFrameworkResponse) => void): Request<AuditManager.Types.GetAssessmentFrameworkResponse, AWSError>; /** * Returns a framework from Audit Manager. */ getAssessmentFramework(callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentFrameworkResponse) => void): Request<AuditManager.Types.GetAssessmentFrameworkResponse, AWSError>; /** * Returns the URL of a specified assessment report in Audit Manager. */ getAssessmentReportUrl(params: AuditManager.Types.GetAssessmentReportUrlRequest, callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentReportUrlResponse) => void): Request<AuditManager.Types.GetAssessmentReportUrlResponse, AWSError>; /** * Returns the URL of a specified assessment report in Audit Manager. */ getAssessmentReportUrl(callback?: (err: AWSError, data: AuditManager.Types.GetAssessmentReportUrlResponse) => void): Request<AuditManager.Types.GetAssessmentReportUrlResponse, AWSError>; /** * Returns a list of changelogs from Audit Manager. */ getChangeLogs(params: AuditManager.Types.GetChangeLogsRequest, callback?: (err: AWSError, data: AuditManager.Types.GetChangeLogsResponse) => void): Request<AuditManager.Types.GetChangeLogsResponse, AWSError>; /** * Returns a list of changelogs from Audit Manager. */ getChangeLogs(callback?: (err: AWSError, data: AuditManager.Types.GetChangeLogsResponse) => void): Request<AuditManager.Types.GetChangeLogsResponse, AWSError>; /** * Returns a control from Audit Manager. */ getControl(params: AuditManager.Types.GetControlRequest, callback?: (err: AWSError, data: AuditManager.Types.GetControlResponse) => void): Request<AuditManager.Types.GetControlResponse, AWSError>; /** * Returns a control from Audit Manager. */ getControl(callback?: (err: AWSError, data: AuditManager.Types.GetControlResponse) => void): Request<AuditManager.Types.GetControlResponse, AWSError>; /** * Returns a list of delegations from an audit owner to a delegate. */ getDelegations(params: AuditManager.Types.GetDelegationsRequest, callback?: (err: AWSError, data: AuditManager.Types.GetDelegationsResponse) => void): Request<AuditManager.Types.GetDelegationsResponse, AWSError>; /** * Returns a list of delegations from an audit owner to a delegate. */ getDelegations(callback?: (err: AWSError, data: AuditManager.Types.GetDelegationsResponse) => void): Request<AuditManager.Types.GetDelegationsResponse, AWSError>; /** * Returns evidence from Audit Manager. */ getEvidence(params: AuditManager.Types.GetEvidenceRequest, callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceResponse) => void): Request<AuditManager.Types.GetEvidenceResponse, AWSError>; /** * Returns evidence from Audit Manager. */ getEvidence(callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceResponse) => void): Request<AuditManager.Types.GetEvidenceResponse, AWSError>; /** * Returns all evidence from a specified evidence folder in Audit Manager. */ getEvidenceByEvidenceFolder(params: AuditManager.Types.GetEvidenceByEvidenceFolderRequest, callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceByEvidenceFolderResponse) => void): Request<AuditManager.Types.GetEvidenceByEvidenceFolderResponse, AWSError>; /** * Returns all evidence from a specified evidence folder in Audit Manager. */ getEvidenceByEvidenceFolder(callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceByEvidenceFolderResponse) => void): Request<AuditManager.Types.GetEvidenceByEvidenceFolderResponse, AWSError>; /** * Returns an evidence folder from the specified assessment in Audit Manager. */ getEvidenceFolder(params: AuditManager.Types.GetEvidenceFolderRequest, callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFolderResponse) => void): Request<AuditManager.Types.GetEvidenceFolderResponse, AWSError>; /** * Returns an evidence folder from the specified assessment in Audit Manager. */ getEvidenceFolder(callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFolderResponse) => void): Request<AuditManager.Types.GetEvidenceFolderResponse, AWSError>; /** * Returns the evidence folders from a specified assessment in Audit Manager. */ getEvidenceFoldersByAssessment(params: AuditManager.Types.GetEvidenceFoldersByAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFoldersByAssessmentResponse) => void): Request<AuditManager.Types.GetEvidenceFoldersByAssessmentResponse, AWSError>; /** * Returns the evidence folders from a specified assessment in Audit Manager. */ getEvidenceFoldersByAssessment(callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFoldersByAssessmentResponse) => void): Request<AuditManager.Types.GetEvidenceFoldersByAssessmentResponse, AWSError>; /** * Returns a list of evidence folders associated with a specified control of an assessment in Audit Manager. */ getEvidenceFoldersByAssessmentControl(params: AuditManager.Types.GetEvidenceFoldersByAssessmentControlRequest, callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFoldersByAssessmentControlResponse) => void): Request<AuditManager.Types.GetEvidenceFoldersByAssessmentControlResponse, AWSError>; /** * Returns a list of evidence folders associated with a specified control of an assessment in Audit Manager. */ getEvidenceFoldersByAssessmentControl(callback?: (err: AWSError, data: AuditManager.Types.GetEvidenceFoldersByAssessmentControlResponse) => void): Request<AuditManager.Types.GetEvidenceFoldersByAssessmentControlResponse, AWSError>; /** * Returns the name of the delegated Amazon Web Services administrator account for the organization. */ getOrganizationAdminAccount(params: AuditManager.Types.GetOrganizationAdminAccountRequest, callback?: (err: AWSError, data: AuditManager.Types.GetOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.GetOrganizationAdminAccountResponse, AWSError>; /** * Returns the name of the delegated Amazon Web Services administrator account for the organization. */ getOrganizationAdminAccount(callback?: (err: AWSError, data: AuditManager.Types.GetOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.GetOrganizationAdminAccountResponse, AWSError>; /** * Returns a list of the in-scope Amazon Web Services services for the specified assessment. */ getServicesInScope(params: AuditManager.Types.GetServicesInScopeRequest, callback?: (err: AWSError, data: AuditManager.Types.GetServicesInScopeResponse) => void): Request<AuditManager.Types.GetServicesInScopeResponse, AWSError>; /** * Returns a list of the in-scope Amazon Web Services services for the specified assessment. */ getServicesInScope(callback?: (err: AWSError, data: AuditManager.Types.GetServicesInScopeResponse) => void): Request<AuditManager.Types.GetServicesInScopeResponse, AWSError>; /** * Returns the settings for the specified account. */ getSettings(params: AuditManager.Types.GetSettingsRequest, callback?: (err: AWSError, data: AuditManager.Types.GetSettingsResponse) => void): Request<AuditManager.Types.GetSettingsResponse, AWSError>; /** * Returns the settings for the specified account. */ getSettings(callback?: (err: AWSError, data: AuditManager.Types.GetSettingsResponse) => void): Request<AuditManager.Types.GetSettingsResponse, AWSError>; /** * Returns a list of the frameworks available in the Audit Manager framework library. */ listAssessmentFrameworks(params: AuditManager.Types.ListAssessmentFrameworksRequest, callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentFrameworksResponse) => void): Request<AuditManager.Types.ListAssessmentFrameworksResponse, AWSError>; /** * Returns a list of the frameworks available in the Audit Manager framework library. */ listAssessmentFrameworks(callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentFrameworksResponse) => void): Request<AuditManager.Types.ListAssessmentFrameworksResponse, AWSError>; /** * Returns a list of assessment reports created in Audit Manager. */ listAssessmentReports(params: AuditManager.Types.ListAssessmentReportsRequest, callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentReportsResponse) => void): Request<AuditManager.Types.ListAssessmentReportsResponse, AWSError>; /** * Returns a list of assessment reports created in Audit Manager. */ listAssessmentReports(callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentReportsResponse) => void): Request<AuditManager.Types.ListAssessmentReportsResponse, AWSError>; /** * Returns a list of current and past assessments from Audit Manager. */ listAssessments(params: AuditManager.Types.ListAssessmentsRequest, callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentsResponse) => void): Request<AuditManager.Types.ListAssessmentsResponse, AWSError>; /** * Returns a list of current and past assessments from Audit Manager. */ listAssessments(callback?: (err: AWSError, data: AuditManager.Types.ListAssessmentsResponse) => void): Request<AuditManager.Types.ListAssessmentsResponse, AWSError>; /** * Returns a list of controls from Audit Manager. */ listControls(params: AuditManager.Types.ListControlsRequest, callback?: (err: AWSError, data: AuditManager.Types.ListControlsResponse) => void): Request<AuditManager.Types.ListControlsResponse, AWSError>; /** * Returns a list of controls from Audit Manager. */ listControls(callback?: (err: AWSError, data: AuditManager.Types.ListControlsResponse) => void): Request<AuditManager.Types.ListControlsResponse, AWSError>; /** * Returns a list of keywords that pre-mapped to the specified control data source. */ listKeywordsForDataSource(params: AuditManager.Types.ListKeywordsForDataSourceRequest, callback?: (err: AWSError, data: AuditManager.Types.ListKeywordsForDataSourceResponse) => void): Request<AuditManager.Types.ListKeywordsForDataSourceResponse, AWSError>; /** * Returns a list of keywords that pre-mapped to the specified control data source. */ listKeywordsForDataSource(callback?: (err: AWSError, data: AuditManager.Types.ListKeywordsForDataSourceResponse) => void): Request<AuditManager.Types.ListKeywordsForDataSourceResponse, AWSError>; /** * Returns a list of all Audit Manager notifications. */ listNotifications(params: AuditManager.Types.ListNotificationsRequest, callback?: (err: AWSError, data: AuditManager.Types.ListNotificationsResponse) => void): Request<AuditManager.Types.ListNotificationsResponse, AWSError>; /** * Returns a list of all Audit Manager notifications. */ listNotifications(callback?: (err: AWSError, data: AuditManager.Types.ListNotificationsResponse) => void): Request<AuditManager.Types.ListNotificationsResponse, AWSError>; /** * Returns a list of tags for the specified resource in Audit Manager. */ listTagsForResource(params: AuditManager.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: AuditManager.Types.ListTagsForResourceResponse) => void): Request<AuditManager.Types.ListTagsForResourceResponse, AWSError>; /** * Returns a list of tags for the specified resource in Audit Manager. */ listTagsForResource(callback?: (err: AWSError, data: AuditManager.Types.ListTagsForResourceResponse) => void): Request<AuditManager.Types.ListTagsForResourceResponse, AWSError>; /** * Enables Audit Manager for the specified account. */ registerAccount(params: AuditManager.Types.RegisterAccountRequest, callback?: (err: AWSError, data: AuditManager.Types.RegisterAccountResponse) => void): Request<AuditManager.Types.RegisterAccountResponse, AWSError>; /** * Enables Audit Manager for the specified account. */ registerAccount(callback?: (err: AWSError, data: AuditManager.Types.RegisterAccountResponse) => void): Request<AuditManager.Types.RegisterAccountResponse, AWSError>; /** * Enables an account within the organization as the delegated administrator for Audit Manager. */ registerOrganizationAdminAccount(params: AuditManager.Types.RegisterOrganizationAdminAccountRequest, callback?: (err: AWSError, data: AuditManager.Types.RegisterOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.RegisterOrganizationAdminAccountResponse, AWSError>; /** * Enables an account within the organization as the delegated administrator for Audit Manager. */ registerOrganizationAdminAccount(callback?: (err: AWSError, data: AuditManager.Types.RegisterOrganizationAdminAccountResponse) => void): Request<AuditManager.Types.RegisterOrganizationAdminAccountResponse, AWSError>; /** * Tags the specified resource in Audit Manager. */ tagResource(params: AuditManager.Types.TagResourceRequest, callback?: (err: AWSError, data: AuditManager.Types.TagResourceResponse) => void): Request<AuditManager.Types.TagResourceResponse, AWSError>; /** * Tags the specified resource in Audit Manager. */ tagResource(callback?: (err: AWSError, data: AuditManager.Types.TagResourceResponse) => void): Request<AuditManager.Types.TagResourceResponse, AWSError>; /** * Removes a tag from a resource in Audit Manager. */ untagResource(params: AuditManager.Types.UntagResourceRequest, callback?: (err: AWSError, data: AuditManager.Types.UntagResourceResponse) => void): Request<AuditManager.Types.UntagResourceResponse, AWSError>; /** * Removes a tag from a resource in Audit Manager. */ untagResource(callback?: (err: AWSError, data: AuditManager.Types.UntagResourceResponse) => void): Request<AuditManager.Types.UntagResourceResponse, AWSError>; /** * Edits an Audit Manager assessment. */ updateAssessment(params: AuditManager.Types.UpdateAssessmentRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentResponse) => void): Request<AuditManager.Types.UpdateAssessmentResponse, AWSError>; /** * Edits an Audit Manager assessment. */ updateAssessment(callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentResponse) => void): Request<AuditManager.Types.UpdateAssessmentResponse, AWSError>; /** * Updates a control within an assessment in Audit Manager. */ updateAssessmentControl(params: AuditManager.Types.UpdateAssessmentControlRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentControlResponse) => void): Request<AuditManager.Types.UpdateAssessmentControlResponse, AWSError>; /** * Updates a control within an assessment in Audit Manager. */ updateAssessmentControl(callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentControlResponse) => void): Request<AuditManager.Types.UpdateAssessmentControlResponse, AWSError>; /** * Updates the status of a control set in an Audit Manager assessment. */ updateAssessmentControlSetStatus(params: AuditManager.Types.UpdateAssessmentControlSetStatusRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentControlSetStatusResponse) => void): Request<AuditManager.Types.UpdateAssessmentControlSetStatusResponse, AWSError>; /** * Updates the status of a control set in an Audit Manager assessment. */ updateAssessmentControlSetStatus(callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentControlSetStatusResponse) => void): Request<AuditManager.Types.UpdateAssessmentControlSetStatusResponse, AWSError>; /** * Updates a custom framework in Audit Manager. */ updateAssessmentFramework(params: AuditManager.Types.UpdateAssessmentFrameworkRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentFrameworkResponse) => void): Request<AuditManager.Types.UpdateAssessmentFrameworkResponse, AWSError>; /** * Updates a custom framework in Audit Manager. */ updateAssessmentFramework(callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentFrameworkResponse) => void): Request<AuditManager.Types.UpdateAssessmentFrameworkResponse, AWSError>; /** * Updates the status of an assessment in Audit Manager. */ updateAssessmentStatus(params: AuditManager.Types.UpdateAssessmentStatusRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentStatusResponse) => void): Request<AuditManager.Types.UpdateAssessmentStatusResponse, AWSError>; /** * Updates the status of an assessment in Audit Manager. */ updateAssessmentStatus(callback?: (err: AWSError, data: AuditManager.Types.UpdateAssessmentStatusResponse) => void): Request<AuditManager.Types.UpdateAssessmentStatusResponse, AWSError>; /** * Updates a custom control in Audit Manager. */ updateControl(params: AuditManager.Types.UpdateControlRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateControlResponse) => void): Request<AuditManager.Types.UpdateControlResponse, AWSError>; /** * Updates a custom control in Audit Manager. */ updateControl(callback?: (err: AWSError, data: AuditManager.Types.UpdateControlResponse) => void): Request<AuditManager.Types.UpdateControlResponse, AWSError>; /** * Updates Audit Manager settings for the current user account. */ updateSettings(params: AuditManager.Types.UpdateSettingsRequest, callback?: (err: AWSError, data: AuditManager.Types.UpdateSettingsResponse) => void): Request<AuditManager.Types.UpdateSettingsResponse, AWSError>; /** * Updates Audit Manager settings for the current user account. */ updateSettings(callback?: (err: AWSError, data: AuditManager.Types.UpdateSettingsResponse) => void): Request<AuditManager.Types.UpdateSettingsResponse, AWSError>; /** * Validates the integrity of an assessment report in Audit Manager. */ validateAssessmentReportIntegrity(params: AuditManager.Types.ValidateAssessmentReportIntegrityRequest, callback?: (err: AWSError, data: AuditManager.Types.ValidateAssessmentReportIntegrityResponse) => void): Request<AuditManager.Types.ValidateAssessmentReportIntegrityResponse, AWSError>; /** * Validates the integrity of an assessment report in Audit Manager. */ validateAssessmentReportIntegrity(callback?: (err: AWSError, data: AuditManager.Types.ValidateAssessmentReportIntegrityResponse) => void): Request<AuditManager.Types.ValidateAssessmentReportIntegrityResponse, AWSError>; } declare namespace AuditManager { export interface AWSAccount { /** * The identifier for the specified account. */ id?: AccountId; /** * The email address associated with the specified account. */ emailAddress?: EmailAddress; /** * The name of the specified account. */ name?: AccountName; } export type AWSAccounts = AWSAccount[]; export interface AWSService { /** * The name of the Amazon Web Service. */ serviceName?: AWSServiceName; } export type AWSServiceName = string; export type AWSServices = AWSService[]; export type AccountId = string; export type AccountName = string; export type AccountStatus = "ACTIVE"|"INACTIVE"|"PENDING_ACTIVATION"|string; export type ActionEnum = "CREATE"|"UPDATE_METADATA"|"ACTIVE"|"INACTIVE"|"DELETE"|"UNDER_REVIEW"|"REVIEWED"|"IMPORT_EVIDENCE"|string; export type ActionPlanInstructions = string; export type ActionPlanTitle = string; export interface Assessment { /** * The Amazon Resource Name (ARN) of the assessment. */ arn?: AuditManagerArn; /** * The account associated with the assessment. */ awsAccount?: AWSAccount; /** * The metadata for the specified assessment. */ metadata?: AssessmentMetadata; /** * The framework from which the assessment was created. */ framework?: AssessmentFramework; /** * The tags associated with the assessment. */ tags?: TagMap; } export interface AssessmentControl { /** * The identifier for the specified control. */ id?: UUID; /** * The name of the specified control. */ name?: ControlName; /** * The description of the specified control. */ description?: ControlDescription; /** * The status of the specified control. */ status?: ControlStatus; /** * The response of the specified control. */ response?: ControlResponse; /** * The list of comments attached to the specified control. */ comments?: ControlComments; /** * The list of data sources for the specified evidence. */ evidenceSources?: EvidenceSources; /** * The amount of evidence generated for the control. */ evidenceCount?: Integer; /** * The amount of evidence in the assessment report. */ assessmentReportEvidenceCount?: Integer; } export interface AssessmentControlSet { /** * The identifier of the control set in the assessment. This is the control set name in a plain string format. */ id?: ControlSetId; /** * The description for the control set. */ description?: NonEmptyString; /** * Specifies the current status of the control set. */ status?: ControlSetStatus; /** * The roles associated with the control set. */ roles?: Roles; /** * The list of controls contained with the control set. */ controls?: AssessmentControls; /** * The delegations associated with the control set. */ delegations?: Delegations; /** * The total number of evidence objects retrieved automatically for the control set. */ systemEvidenceCount?: Integer; /** * The total number of evidence objects uploaded manually to the control set. */ manualEvidenceCount?: Integer; } export type AssessmentControlSets = AssessmentControlSet[]; export type AssessmentControls = AssessmentControl[]; export type AssessmentDescription = string; export interface AssessmentEvidenceFolder { /** * The name of the specified evidence folder. */ name?: AssessmentEvidenceFolderName; /** * The date when the first evidence was added to the evidence folder. */ date?: Timestamp; /** * The identifier for the specified assessment. */ assessmentId?: UUID; /** * The identifier for the control set. */ controlSetId?: ControlSetId; /** * The unique identifier for the specified control. */ controlId?: UUID; /** * The identifier for the folder in which evidence is stored. */ id?: UUID; /** * The Amazon Web Service from which the evidence was collected. */ dataSource?: String; /** * The name of the user who created the evidence folder. */ author?: String; /** * The total amount of evidence in the evidence folder. */ totalEvidence?: Integer; /** * The total count of evidence included in the assessment report. */ assessmentReportSelectionCount?: Integer; /** * The name of the control. */ controlName?: ControlName; /** * The amount of evidence included in the evidence folder. */ evidenceResourcesIncludedCount?: Integer; /** * The number of evidence that falls under the configuration data category. This evidence is collected from configuration snapshots of other Amazon Web Services services such as Amazon EC2, Amazon S3, or IAM. */ evidenceByTypeConfigurationDataCount?: Integer; /** * The number of evidence that falls under the manual category. This evidence is imported manually. */ evidenceByTypeManualCount?: Integer; /** * The number of evidence that falls under the compliance check category. This evidence is collected from Config or Security Hub. */ evidenceByTypeComplianceCheckCount?: Integer; /** * The total number of issues that were reported directly from Security Hub, Config, or both. */ evidenceByTypeComplianceCheckIssuesCount?: Integer; /** * The number of evidence that falls under the user activity category. This evidence is collected from CloudTrail logs. */ evidenceByTypeUserActivityCount?: Integer; /** * The total number of Amazon Web Services resources assessed to generate the evidence. */ evidenceAwsServiceSourceCount?: Integer; } export type AssessmentEvidenceFolderName = string; export type AssessmentEvidenceFolders = AssessmentEvidenceFolder[]; export interface AssessmentFramework { /** * The unique identifier for the framework. */ id?: UUID; /** * The Amazon Resource Name (ARN) of the specified framework. */ arn?: AuditManagerArn; metadata?: FrameworkMetadata; /** * The control sets associated with the framework. */ controlSets?: AssessmentControlSets; } export type AssessmentFrameworkDescription = string; export interface AssessmentFrameworkMetadata { /** * The Amazon Resource Name (ARN) of the framework. */ arn?: AuditManagerArn; /** * The unique identified for the specified framework. */ id?: UUID; /** * The framework type, such as standard or custom. */ type?: FrameworkType; /** * The name of the specified framework. */ name?: FrameworkName; /** * The description of the specified framework. */ description?: FrameworkDescription; /** * The logo associated with the framework. */ logo?: Filename; /** * The compliance type that the new custom framework supports, such as CIS or HIPAA. */ complianceType?: ComplianceType; /** * The number of controls associated with the specified framework. */ controlsCount?: ControlsCount; /** * The number of control sets associated with the specified framework. */ controlSetsCount?: ControlSetsCount; /** * Specifies when the framework was created. */ createdAt?: Timestamp; /** * Specifies when the framework was most recently updated. */ lastUpdatedAt?: Timestamp; } export interface AssessmentMetadata { /** * The name of the assessment. */ name?: AssessmentName; /** * The unique identifier for the assessment. */ id?: UUID; /** * The description of the assessment. */ description?: AssessmentDescription; /** * The name of a compliance standard related to the assessment, such as PCI-DSS. */ complianceType?: ComplianceType; /** * The overall status of the assessment. */ status?: AssessmentStatus; /** * The destination in which evidence reports are stored for the specified assessment. */ assessmentReportsDestination?: AssessmentReportsDestination; /** * The wrapper of accounts and services in scope for the assessment. */ scope?: Scope; /** * The roles associated with the assessment. */ roles?: Roles; /** * The delegations associated with the assessment. */ delegations?: Delegations; /** * Specifies when the assessment was created. */ creationTime?: Timestamp; /** * The time of the most recent update. */ lastUpdated?: Timestamp; } export interface AssessmentMetadataItem { /** * The name of the assessment. */ name?: AssessmentName; /** * The unique identifier for the assessment. */ id?: UUID; /** * The name of the compliance standard related to the assessment, such as PCI-DSS. */ complianceType?: ComplianceType; /** * The current status of the assessment. */ status?: AssessmentStatus; /** * The roles associated with the assessment. */ roles?: Roles; /** * The delegations associated with the assessment. */ delegations?: Delegations; /** * Specifies when the assessment was created. */ creationTime?: Timestamp; /** * The time of the most recent update. */ lastUpdated?: Timestamp; } export type AssessmentName = string; export interface AssessmentReport { /** * The unique identifier for the specified assessment report. */ id?: UUID; /** * The name given to the assessment report. */ name?: AssessmentReportName; /** * The description of the specified assessment report. */ description?: AssessmentReportDescription; /** * The identifier for the specified account. */ awsAccountId?: AccountId; /** * The identifier for the specified assessment. */ assessmentId?: UUID; /** * The name of the associated assessment. */ assessmentName?: AssessmentName; /** * The name of the user who created the assessment report. */ author?: Username; /** * The current status of the specified assessment report. */ status?: AssessmentReportStatus; /** * Specifies when the assessment report was created. */ creationTime?: Timestamp; } export type AssessmentReportDescription = string; export type AssessmentReportDestinationType = "S3"|string; export interface AssessmentReportEvidenceError { /** * The identifier for the evidence. */ evidenceId?: UUID; /** * The error code returned by the AssessmentReportEvidence API. */ errorCode?: ErrorCode; /** * The error message returned by the AssessmentReportEvidence API. */ errorMessage?: ErrorMessage; } export type AssessmentReportEvidenceErrors = AssessmentReportEvidenceError[]; export interface AssessmentReportMetadata { /** * The unique identifier for the assessment report. */ id?: UUID; /** * The name of the assessment report. */ name?: AssessmentReportName; /** * The description of the specified assessment report. */ description?: AssessmentReportDescription; /** * The unique identifier for the associated assessment. */ assessmentId?: UUID; /** * The name of the associated assessment. */ assessmentName?: AssessmentName; /** * The name of the user who created the assessment report. */ author?: Username; /** * The current status of the assessment report. */ status?: AssessmentReportStatus; /** * Specifies when the assessment report was created. */ creationTime?: Timestamp; } export type AssessmentReportName = string; export type AssessmentReportStatus = "COMPLETE"|"IN_PROGRESS"|"FAILED"|string; export interface AssessmentReportsDestination { /** * The destination type, such as Amazon S3. */ destinationType?: AssessmentReportDestinationType; /** * The destination of the assessment report. */ destination?: S3Url; } export type AssessmentReportsMetadata = AssessmentReportMetadata[]; export type AssessmentStatus = "ACTIVE"|"INACTIVE"|string; export interface AssociateAssessmentReportEvidenceFolderRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the folder in which evidence is stored. */ evidenceFolderId: UUID; } export interface AssociateAssessmentReportEvidenceFolderResponse { } export type AuditManagerArn = string; export interface BatchAssociateAssessmentReportEvidenceRequest { /** * The unique identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the folder in which the evidence is stored. */ evidenceFolderId: UUID; /** * The list of evidence identifiers. */ evidenceIds: EvidenceIds; } export interface BatchAssociateAssessmentReportEvidenceResponse { /** * The identifier for the evidence. */ evidenceIds?: EvidenceIds; /** * A list of errors returned by the BatchAssociateAssessmentReportEvidence API. */ errors?: AssessmentReportEvidenceErrors; } export interface BatchCreateDelegationByAssessmentError { /** * The API request to batch create delegations in Audit Manager. */ createDelegationRequest?: CreateDelegationRequest; /** * The error code returned by the BatchCreateDelegationByAssessment API. */ errorCode?: ErrorCode; /** * The error message returned by the BatchCreateDelegationByAssessment API. */ errorMessage?: ErrorMessage; } export type BatchCreateDelegationByAssessmentErrors = BatchCreateDelegationByAssessmentError[]; export interface BatchCreateDelegationByAssessmentRequest { /** * The API request to batch create delegations in Audit Manager. */ createDelegationRequests: CreateDelegationRequests; /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface BatchCreateDelegationByAssessmentResponse { /** * The delegations associated with the assessment. */ delegations?: Delegations; /** * A list of errors returned by the BatchCreateDelegationByAssessment API. */ errors?: BatchCreateDelegationByAssessmentErrors; } export interface BatchDeleteDelegationByAssessmentError { /** * The identifier for the specified delegation. */ delegationId?: UUID; /** * The error code returned by the BatchDeleteDelegationByAssessment API. */ errorCode?: ErrorCode; /** * The error message returned by the BatchDeleteDelegationByAssessment API. */ errorMessage?: ErrorMessage; } export type BatchDeleteDelegationByAssessmentErrors = BatchDeleteDelegationByAssessmentError[]; export interface BatchDeleteDelegationByAssessmentRequest { /** * The identifiers for the specified delegations. */ delegationIds: DelegationIds; /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface BatchDeleteDelegationByAssessmentResponse { /** * A list of errors returned by the BatchDeleteDelegationByAssessment API. */ errors?: BatchDeleteDelegationByAssessmentErrors; } export interface BatchDisassociateAssessmentReportEvidenceRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the folder in which evidence is stored. */ evidenceFolderId: UUID; /** * The list of evidence identifiers. */ evidenceIds: EvidenceIds; } export interface BatchDisassociateAssessmentReportEvidenceResponse { /** * The identifier for the evidence. */ evidenceIds?: EvidenceIds; /** * A list of errors returned by the BatchDisassociateAssessmentReportEvidence API. */ errors?: AssessmentReportEvidenceErrors; } export interface BatchImportEvidenceToAssessmentControlError { /** * Manual evidence that cannot be collected automatically by Audit Manager. */ manualEvidence?: ManualEvidence; /** * The error code returned by the BatchImportEvidenceToAssessmentControl API. */ errorCode?: ErrorCode; /** * The error message returned by the BatchImportEvidenceToAssessmentControl API. */ errorMessage?: ErrorMessage; } export type BatchImportEvidenceToAssessmentControlErrors = BatchImportEvidenceToAssessmentControlError[]; export interface BatchImportEvidenceToAssessmentControlRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: ControlSetId; /** * The identifier for the specified control. */ controlId: UUID; /** * The list of manual evidence objects. */ manualEvidence: ManualEvidenceList; } export interface BatchImportEvidenceToAssessmentControlResponse { /** * A list of errors returned by the BatchImportEvidenceToAssessmentControl API. */ errors?: BatchImportEvidenceToAssessmentControlErrors; } export type Boolean = boolean; export interface ChangeLog { /** * The changelog object type, such as an assessment, control, or control set. */ objectType?: ObjectTypeEnum; /** * The name of the changelog object. */ objectName?: NonEmptyString; /** * The action performed. */ action?: ActionEnum; /** * The time of creation for the changelog object. */ createdAt?: Timestamp; /** * The IAM user or role that performed the action. */ createdBy?: IamArn; } export type ChangeLogs = ChangeLog[]; export type ComplianceType = string; export interface Control { /** * The Amazon Resource Name (ARN) of the specified control. */ arn?: AuditManagerArn; /** * The unique identifier for the control. */ id?: UUID; /** * The type of control, such as custom or standard. */ type?: ControlType; /** * The name of the specified control. */ name?: ControlName; /** * The description of the specified control. */ description?: ControlDescription; /** * The steps to follow to determine if the control has been satisfied. */ testingInformation?: TestingInformation; /** * The title of the action plan for remediating the control. */ actionPlanTitle?: ActionPlanTitle; /** * The recommended actions to carry out if the control is not fulfilled. */ actionPlanInstructions?: ActionPlanInstructions; /** * The data source that determines from where Audit Manager collects evidence for the control. */ controlSources?: ControlSources; /** * The data mapping sources for the specified control. */ controlMappingSources?: ControlMappingSources; /** * Specifies when the control was created. */ createdAt?: Timestamp; /** * Specifies when the control was most recently updated. */ lastUpdatedAt?: Timestamp; /** * The IAM user or role that created the control. */ createdBy?: CreatedBy; /** * The IAM user or role that most recently updated the control. */ lastUpdatedBy?: LastUpdatedBy; /** * The tags associated with the control. */ tags?: TagMap; } export interface ControlComment { /** * The name of the user who authored the comment. */ authorName?: Username; /** * The body text of a control comment. */ commentBody?: ControlCommentBody; /** * The time when the comment was posted. */ postedDate?: Timestamp; } export type ControlCommentBody = string; export type ControlComments = ControlComment[]; export type ControlDescription = string; export interface ControlMappingSource { /** * The unique identifier for the specified source. */ sourceId?: UUID; /** * The name of the specified source. */ sourceName?: SourceName; /** * The description of the specified source. */ sourceDescription?: SourceDescription; /** * The setup option for the data source, which reflects if the evidence collection is automated or manual. */ sourceSetUpOption?: SourceSetUpOption; /** * Specifies one of the five types of data sources for evidence collection. */ sourceType?: SourceType; sourceKeyword?: SourceKeyword; /** * The frequency of evidence collection for the specified control mapping source. */ sourceFrequency?: SourceFrequency; /** * The instructions for troubleshooting the specified control. */ troubleshootingText?: TroubleshootingText; } export type ControlMappingSources = ControlMappingSource[]; export interface ControlMetadata { /** * The Amazon Resource Name (ARN) of the specified control. */ arn?: AuditManagerArn; /** * The unique identifier for the specified control. */ id?: UUID; /** * The name of the specified control. */ name?: ControlName; /** * The data source that determines from where Audit Manager collects evidence for the control. */ controlSources?: ControlSources; /** * Specifies when the control was created. */ createdAt?: Timestamp; /** * Specifies when the control was most recently updated. */ lastUpdatedAt?: Timestamp; } export type ControlMetadataList = ControlMetadata[]; export type ControlName = string; export type ControlResponse = "MANUAL"|"AUTOMATE"|"DEFER"|"IGNORE"|string; export interface ControlSet { /** * The identifier of the control set in the assessment. This is the control set name in a plain string format. */ id?: UUID; /** * The name of the control set. */ name?: ControlSetName; /** * The list of controls within the control set. */ controls?: Controls; } export type ControlSetId = string; export type ControlSetName = string; export type ControlSetStatus = "ACTIVE"|"UNDER_REVIEW"|"REVIEWED"|string; export type ControlSets = ControlSet[]; export type ControlSetsCount = number; export type ControlSources = string; export type ControlStatus = "UNDER_REVIEW"|"REVIEWED"|"INACTIVE"|string; export type ControlType = "Standard"|"Custom"|string; export type Controls = Control[]; export type ControlsCount = number; export interface CreateAssessmentFrameworkControl { /** * The unique identifier of the control. */ id?: UUID; } export interface CreateAssessmentFrameworkControlSet { /** * The name of the specified control set. */ name: ControlSetName; /** * The list of controls within the control set. This does not contain the control set ID. */ controls?: CreateAssessmentFrameworkControls; } export type CreateAssessmentFrameworkControlSets = CreateAssessmentFrameworkControlSet[]; export type CreateAssessmentFrameworkControls = CreateAssessmentFrameworkControl[]; export interface CreateAssessmentFrameworkRequest { /** * The name of the new custom framework. */ name: FrameworkName; /** * An optional description for the new custom framework. */ description?: FrameworkDescription; /** * The compliance type that the new custom framework supports, such as CIS or HIPAA. */ complianceType?: ComplianceType; /** * The control sets to be associated with the framework. */ controlSets: CreateAssessmentFrameworkControlSets; /** * The tags associated with the framework. */ tags?: TagMap; } export interface CreateAssessmentFrameworkResponse { /** * The name of the new framework returned by the CreateAssessmentFramework API. */ framework?: Framework; } export interface CreateAssessmentReportRequest { /** * The name of the new assessment report. */ name: AssessmentReportName; /** * The description of the assessment report. */ description?: AssessmentReportDescription; /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface CreateAssessmentReportResponse { /** * The new assessment report returned by the CreateAssessmentReport API. */ assessmentReport?: AssessmentReport; } export interface CreateAssessmentRequest { /** * The name of the assessment to be created. */ name: AssessmentName; /** * The optional description of the assessment to be created. */ description?: AssessmentDescription; /** * The assessment report storage destination for the specified assessment that is being created. */ assessmentReportsDestination: AssessmentReportsDestination; scope: Scope; /** * The list of roles for the specified assessment. */ roles: Roles; /** * The identifier for the specified framework. */ frameworkId: UUID; /** * The tags associated with the assessment. */ tags?: TagMap; } export interface CreateAssessmentResponse { assessment?: Assessment; } export interface CreateControlMappingSource { /** * The name of the control mapping data source. */ sourceName?: SourceName; /** * The description of the data source that determines from where Audit Manager collects evidence for the control. */ sourceDescription?: SourceDescription; /** * The setup option for the data source, which reflects if the evidence collection is automated or manual. */ sourceSetUpOption?: SourceSetUpOption; /** * Specifies one of the five types of data sources for evidence collection. */ sourceType?: SourceType; sourceKeyword?: SourceKeyword; /** * The frequency of evidence collection for the specified control mapping source. */ sourceFrequency?: SourceFrequency; /** * The instructions for troubleshooting the specified control. */ troubleshootingText?: TroubleshootingText; } export type CreateControlMappingSources = CreateControlMappingSource[]; export interface CreateControlRequest { /** * The name of the control. */ name: ControlName; /** * The description of the control. */ description?: ControlDescription; /** * The steps to follow to determine if the control has been satisfied. */ testingInformation?: TestingInformation; /** * The title of the action plan for remediating the control. */ actionPlanTitle?: ActionPlanTitle; /** * The recommended actions to carry out if the control is not fulfilled. */ actionPlanInstructions?: ActionPlanInstructions; /** * The data mapping sources for the specified control. */ controlMappingSources: CreateControlMappingSources; /** * The tags associated with the control. */ tags?: TagMap; } export interface CreateControlResponse { /** * The new control returned by the CreateControl API. */ control?: Control; } export interface CreateDelegationRequest { /** * A comment related to the delegation request. */ comment?: DelegationComment; /** * The unique identifier for the control set. */ controlSetId?: ControlSetId; /** * The Amazon Resource Name (ARN) of the IAM role. */ roleArn?: IamArn; /** * The type of customer persona. In CreateAssessment, roleType can only be PROCESS_OWNER. In UpdateSettings, roleType can only be PROCESS_OWNER. In BatchCreateDelegationByAssessment, roleType can only be RESOURCE_OWNER. */ roleType?: RoleType; } export type CreateDelegationRequests = CreateDelegationRequest[]; export type CreatedBy = string; export interface Delegation { /** * The unique identifier for the delegation. */ id?: UUID; /** * The name of the associated assessment. */ assessmentName?: AssessmentName; /** * The identifier for the associated assessment. */ assessmentId?: UUID; /** * The status of the delegation. */ status?: DelegationStatus; /** * The Amazon Resource Name (ARN) of the IAM role. */ roleArn?: IamArn; /** * The type of customer persona. In CreateAssessment, roleType can only be PROCESS_OWNER. In UpdateSettings, roleType can only be PROCESS_OWNER. In BatchCreateDelegationByAssessment, roleType can only be RESOURCE_OWNER. */ roleType?: RoleType; /** * Specifies when the delegation was created. */ creationTime?: Timestamp; /** * Specifies when the delegation was last updated. */ lastUpdated?: Timestamp; /** * The identifier for the associated control set. */ controlSetId?: ControlSetId; /** * The comment related to the delegation. */ comment?: DelegationComment; /** * The IAM user or role that created the delegation. */ createdBy?: CreatedBy; } export type DelegationComment = string; export type DelegationIds = UUID[]; export interface DelegationMetadata { /** * The unique identifier for the delegation. */ id?: UUID; /** * The name of the associated assessment. */ assessmentName?: AssessmentName; /** * The unique identifier for the specified assessment. */ assessmentId?: UUID; /** * The current status of the delgation. */ status?: DelegationStatus; /** * The Amazon Resource Name (ARN) of the IAM role. */ roleArn?: IamArn; /** * Specifies when the delegation was created. */ creationTime?: Timestamp; /** * Specifies the name of the control set delegated for review. */ controlSetName?: NonEmptyString; } export type DelegationMetadataList = DelegationMetadata[]; export type DelegationStatus = "IN_PROGRESS"|"UNDER_REVIEW"|"COMPLETE"|string; export type Delegations = Delegation[]; export interface DeleteAssessmentFrameworkRequest { /** * The identifier for the specified framework. */ frameworkId: UUID; } export interface DeleteAssessmentFrameworkResponse { } export interface DeleteAssessmentReportRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The unique identifier for the assessment report. */ assessmentReportId: UUID; } export interface DeleteAssessmentReportResponse { } export interface DeleteAssessmentRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface DeleteAssessmentResponse { } export interface DeleteControlRequest { /** * The identifier for the specified control. */ controlId: UUID; } export interface DeleteControlResponse { } export interface DeregisterAccountRequest { } export interface DeregisterAccountResponse { /** * The registration status of the account. */ status?: AccountStatus; } export interface DeregisterOrganizationAdminAccountRequest { /** * The identifier for the specified administrator account. */ adminAccountId?: AccountId; } export interface DeregisterOrganizationAdminAccountResponse { } export interface DisassociateAssessmentReportEvidenceFolderRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the folder in which evidence is stored. */ evidenceFolderId: UUID; } export interface DisassociateAssessmentReportEvidenceFolderResponse { } export type EmailAddress = string; export type ErrorCode = string; export type ErrorMessage = string; export type EventName = string; export interface Evidence { /** * The data source from which the specified evidence was collected. */ dataSource?: String; /** * The identifier for the specified account. */ evidenceAwsAccountId?: AccountId; /** * The timestamp that represents when the evidence was collected. */ time?: Timestamp; /** * The Amazon Web Service from which the evidence is collected. */ eventSource?: AWSServiceName; /** * The name of the specified evidence event. */ eventName?: EventName; /** * The type of automated evidence. */ evidenceByType?: String; /** * The list of resources assessed to generate the evidence. */ resourcesIncluded?: Resources; /** * The names and values used by the evidence event, including an attribute name (such as allowUsersToChangePassword) and value (such as true or false). */ attributes?: EvidenceAttributes; /** * The unique identifier for the IAM user or role associated with the evidence. */ iamId?: IamArn; /** * The evaluation status for evidence that falls under the compliance check category. For evidence collected from Security Hub, a Pass or Fail result is shown. For evidence collected from Config, a Compliant or Noncompliant result is shown. */ complianceCheck?: String; /** * The account from which the evidence is collected, and its organization path. */ awsOrganization?: String; /** * The identifier for the specified account. */ awsAccountId?: AccountId; /** * The identifier for the folder in which the evidence is stored. */ evidenceFolderId?: UUID; /** * The identifier for the evidence. */ id?: UUID; /** * Specifies whether the evidence is included in the assessment report. */ assessmentReportSelection?: String; } export type EvidenceAttributeKey = string; export type EvidenceAttributeValue = string; export type EvidenceAttributes = {[key: string]: EvidenceAttributeValue}; export type EvidenceIds = UUID[]; export type EvidenceList = Evidence[]; export type EvidenceSources = NonEmptyString[]; export type Filename = string; export interface Framework { /** * The Amazon Resource Name (ARN) of the specified framework. */ arn?: AuditManagerArn; /** * The unique identifier for the specified framework. */ id?: UUID; /** * The name of the specified framework. */ name?: FrameworkName; /** * The framework type, such as custom or standard. */ type?: FrameworkType; /** * The compliance type that the new custom framework supports, such as CIS or HIPAA. */ complianceType?: ComplianceType; /** * The description of the specified framework. */ description?: FrameworkDescription; /** * The logo associated with the framework. */ logo?: Filename; /** * The sources from which Audit Manager collects evidence for the control. */ controlSources?: ControlSources; /** * The control sets associated with the framework. */ controlSets?: ControlSets; /** * Specifies when the framework was created. */ createdAt?: Timestamp; /** * Specifies when the framework was most recently updated. */ lastUpdatedAt?: Timestamp; /** * The IAM user or role that created the framework. */ createdBy?: CreatedBy; /** * The IAM user or role that most recently updated the framework. */ lastUpdatedBy?: LastUpdatedBy; /** * The tags associated with the framework. */ tags?: TagMap; } export type FrameworkDescription = string; export interface FrameworkMetadata { /** * The name of the framework. */ name?: AssessmentName; /** * The description of the framework. */ description?: AssessmentFrameworkDescription; /** * The logo associated with the framework. */ logo?: Filename; /** * The compliance standard associated with the framework, such as PCI-DSS or HIPAA. */ complianceType?: ComplianceType; } export type FrameworkMetadataList = AssessmentFrameworkMetadata[]; export type FrameworkName = string; export type FrameworkType = "Standard"|"Custom"|string; export type GenericArn = string; export interface GetAccountStatusRequest { } export interface GetAccountStatusResponse { /** * The status of the specified account. */ status?: AccountStatus; } export interface GetAssessmentFrameworkRequest { /** * The identifier for the specified framework. */ frameworkId: UUID; } export interface GetAssessmentFrameworkResponse { /** * The framework returned by the GetAssessmentFramework API. */ framework?: Framework; } export interface GetAssessmentReportUrlRequest { /** * The identifier for the assessment report. */ assessmentReportId: UUID; /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface GetAssessmentReportUrlResponse { preSignedUrl?: URL; } export interface GetAssessmentRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; } export interface GetAssessmentResponse { assessment?: Assessment; userRole?: Role; } export interface GetChangeLogsRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId?: ControlSetId; /** * The identifier for the specified control. */ controlId?: UUID; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface GetChangeLogsResponse { /** * The list of user activity for the control. */ changeLogs?: ChangeLogs; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface GetControlRequest { /** * The identifier for the specified control. */ controlId: UUID; } export interface GetControlResponse { /** * The name of the control returned by the GetControl API. */ control?: Control; } export interface GetDelegationsRequest { /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface GetDelegationsResponse { /** * The list of delegations returned by the GetDelegations API. */ delegations?: DelegationMetadataList; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface GetEvidenceByEvidenceFolderRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the control set. */ controlSetId: ControlSetId; /** * The unique identifier for the folder in which the evidence is stored. */ evidenceFolderId: UUID; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface GetEvidenceByEvidenceFolderResponse { /** * The list of evidence returned by the GetEvidenceByEvidenceFolder API. */ evidence?: EvidenceList; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface GetEvidenceFolderRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: ControlSetId; /** * The identifier for the folder in which the evidence is stored. */ evidenceFolderId: UUID; } export interface GetEvidenceFolderResponse { /** * The folder in which evidence is stored. */ evidenceFolder?: AssessmentEvidenceFolder; } export interface GetEvidenceFoldersByAssessmentControlRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: ControlSetId; /** * The identifier for the specified control. */ controlId: UUID; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface GetEvidenceFoldersByAssessmentControlResponse { /** * The list of evidence folders returned by the GetEvidenceFoldersByAssessmentControl API. */ evidenceFolders?: AssessmentEvidenceFolders; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface GetEvidenceFoldersByAssessmentRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface GetEvidenceFoldersByAssessmentResponse { /** * The list of evidence folders returned by the GetEvidenceFoldersByAssessment API. */ evidenceFolders?: AssessmentEvidenceFolders; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface GetEvidenceRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: ControlSetId; /** * The identifier for the folder in which the evidence is stored. */ evidenceFolderId: UUID; /** * The identifier for the evidence. */ evidenceId: UUID; } export interface GetEvidenceResponse { /** * The evidence returned by the GetEvidenceResponse API. */ evidence?: Evidence; } export interface GetOrganizationAdminAccountRequest { } export interface GetOrganizationAdminAccountResponse { /** * The identifier for the specified administrator account. */ adminAccountId?: AccountId; /** * The identifier for the specified organization. */ organizationId?: organizationId; } export interface GetServicesInScopeRequest { } export interface GetServicesInScopeResponse { /** * The metadata associated with the Amazon Web Service. */ serviceMetadata?: ServiceMetadataList; } export interface GetSettingsRequest { /** * The list of SettingAttribute enum values. */ attribute: SettingAttribute; } export interface GetSettingsResponse { /** * The settings object that holds all supported Audit Manager settings. */ settings?: Settings; } export type HyperlinkName = string; export type IamArn = string; export type Integer = number; export type KeywordInputType = "SELECT_FROM_LIST"|string; export type KeywordValue = string; export type Keywords = KeywordValue[]; export type KmsKey = string; export type LastUpdatedBy = string; export interface ListAssessmentFrameworksRequest { /** * The type of framework, such as standard or custom. */ frameworkType: FrameworkType; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListAssessmentFrameworksResponse { /** * The list of metadata objects for the specified framework. */ frameworkMetadataList?: FrameworkMetadataList; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export type ListAssessmentMetadata = AssessmentMetadataItem[]; export interface ListAssessmentReportsRequest { /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListAssessmentReportsResponse { /** * The list of assessment reports returned by the ListAssessmentReports API. */ assessmentReports?: AssessmentReportsMetadata; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface ListAssessmentsRequest { /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListAssessmentsResponse { /** * The metadata associated with the assessment. */ assessmentMetadata?: ListAssessmentMetadata; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface ListControlsRequest { /** * The type of control, such as standard or custom. */ controlType: ControlType; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListControlsResponse { /** * The list of control metadata objects returned by the ListControls API. */ controlMetadataList?: ControlMetadataList; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface ListKeywordsForDataSourceRequest { /** * The control mapping data source to which the keywords apply. */ source: SourceType; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListKeywordsForDataSourceResponse { /** * The list of keywords for the specified event mapping source. */ keywords?: Keywords; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface ListNotificationsRequest { /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; /** * Represents the maximum number of results per page, or per API request call. */ maxResults?: MaxResults; } export interface ListNotificationsResponse { /** * The returned list of notifications. */ notifications?: Notifications; /** * The pagination token used to fetch the next set of results. */ nextToken?: Token; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) of the specified resource. */ resourceArn: AuditManagerArn; } export interface ListTagsForResourceResponse { /** * The list of tags returned by the ListTagsForResource API. */ tags?: TagMap; } export interface ManualEvidence { /** * The Amazon S3 URL that points to a manual evidence object. */ s3ResourcePath?: S3Url; } export type ManualEvidenceList = ManualEvidence[]; export type MaxResults = number; export type NonEmptyString = string; export interface Notification { /** * The unique identifier for the notification. */ id?: TimestampUUID; /** * The identifier for the specified assessment. */ assessmentId?: UUID; /** * The name of the related assessment. */ assessmentName?: AssessmentName; /** * The identifier for the specified control set. */ controlSetId?: ControlSetId; /** * Specifies the name of the control set that the notification is about. */ controlSetName?: NonEmptyString; /** * The description of the notification. */ description?: NonEmptyString; /** * The time when the notification was sent. */ eventTime?: Timestamp; /** * The sender of the notification. */ source?: NonEmptyString; } export type Notifications = Notification[]; export type ObjectTypeEnum = "ASSESSMENT"|"CONTROL_SET"|"CONTROL"|"DELEGATION"|"ASSESSMENT_REPORT"|string; export interface RegisterAccountRequest { /** * The KMS key details. */ kmsKey?: KmsKey; /** * The delegated administrator account for Audit Manager. */ delegatedAdminAccount?: AccountId; } export interface RegisterAccountResponse { /** * The status of the account registration request. */ status?: AccountStatus; } export interface RegisterOrganizationAdminAccountRequest { /** * The identifier for the specified delegated administrator account. */ adminAccountId: AccountId; } export interface RegisterOrganizationAdminAccountResponse { /** * The identifier for the specified delegated administrator account. */ adminAccountId?: AccountId; /** * The identifier for the specified organization. */ organizationId?: organizationId; } export interface Resource { /** * The Amazon Resource Name (ARN) for the specified resource. */ arn?: GenericArn; /** * The value of the specified resource. */ value?: String; } export type Resources = Resource[]; export interface Role { /** * The type of customer persona. In CreateAssessment, roleType can only be PROCESS_OWNER. In UpdateSettings, roleType can only be PROCESS_OWNER. In BatchCreateDelegationByAssessment, roleType can only be RESOURCE_OWNER. */ roleType?: RoleType; /** * The Amazon Resource Name (ARN) of the IAM role. */ roleArn?: IamArn; } export type RoleType = "PROCESS_OWNER"|"RESOURCE_OWNER"|string; export type Roles = Role[]; export type S3Url = string; export type SNSTopic = string; export interface Scope { /** * The accounts included in the scope of the assessment. */ awsAccounts?: AWSAccounts; /** * The Amazon Web Services services included in the scope of the assessment. */ awsServices?: AWSServices; } export interface ServiceMetadata { /** * The name of the Amazon Web Service. */ name?: AWSServiceName; /** * The display name of the Amazon Web Service. */ displayName?: NonEmptyString; /** * The description of the specified Amazon Web Service. */ description?: NonEmptyString; /** * The category in which the Amazon Web Service belongs, such as compute, storage, database, and so on. */ category?: NonEmptyString; } export type ServiceMetadataList = ServiceMetadata[]; export type SettingAttribute = "ALL"|"IS_AWS_ORG_ENABLED"|"SNS_TOPIC"|"DEFAULT_ASSESSMENT_REPORTS_DESTINATION"|"DEFAULT_PROCESS_OWNERS"|string; export interface Settings { /** * Specifies whether Organizations is enabled. */ isAwsOrgEnabled?: Boolean; /** * The designated Amazon Simple Notification Service (Amazon SNS) topic. */ snsTopic?: SNSTopic; /** * The default storage destination for assessment reports. */ defaultAssessmentReportsDestination?: AssessmentReportsDestination; /** * The designated default audit owners. */ defaultProcessOwners?: Roles; /** * The KMS key details. */ kmsKey?: KmsKey; } export type SnsArn = string; export type SourceDescription = string; export type SourceFrequency = "DAILY"|"WEEKLY"|"MONTHLY"|string; export interface SourceKeyword { /** * The method of input for the specified keyword. */ keywordInputType?: KeywordInputType; /** * The value of the keyword used to search CloudTrail logs, Config rules, Security Hub checks, and Amazon Web Services API names when mapping a control data source. */ keywordValue?: KeywordValue; } export type SourceName = string; export type SourceSetUpOption = "System_Controls_Mapping"|"Procedural_Controls_Mapping"|string; export type SourceType = "AWS_Cloudtrail"|"AWS_Config"|"AWS_Security_Hub"|"AWS_API_Call"|"MANUAL"|string; export type String = string; export type TagKey = string; export type TagKeyList = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) of the specified resource. */ resourceArn: AuditManagerArn; /** * The tags to be associated with the resource. */ tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type TestingInformation = string; export type Timestamp = Date; export type TimestampUUID = string; export type Token = string; export type TroubleshootingText = string; export interface URL { /** * The name or word used as a hyperlink to the URL. */ hyperlinkName?: HyperlinkName; /** * The unique identifier for the internet resource. */ link?: UrlLink; } export type UUID = string; export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) of the specified resource. */ resourceArn: AuditManagerArn; /** * The name or key of the tag. */ tagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateAssessmentControlRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: ControlSetId; /** * The identifier for the specified control. */ controlId: UUID; /** * The status of the specified control. */ controlStatus?: ControlStatus; /** * The comment body text for the specified control. */ commentBody?: ControlCommentBody; } export interface UpdateAssessmentControlResponse { /** * The name of the updated control set returned by the UpdateAssessmentControl API. */ control?: AssessmentControl; } export interface UpdateAssessmentControlSetStatusRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The identifier for the specified control set. */ controlSetId: String; /** * The status of the control set that is being updated. */ status: ControlSetStatus; /** * The comment related to the status update. */ comment: DelegationComment; } export interface UpdateAssessmentControlSetStatusResponse { /** * The name of the updated control set returned by the UpdateAssessmentControlSetStatus API. */ controlSet?: AssessmentControlSet; } export interface UpdateAssessmentFrameworkControlSet { /** * The unique identifier for the control set. */ id?: ControlSetName; /** * The name of the control set. */ name: ControlSetName; /** * The list of controls contained within the control set. */ controls?: CreateAssessmentFrameworkControls; } export type UpdateAssessmentFrameworkControlSets = UpdateAssessmentFrameworkControlSet[]; export interface UpdateAssessmentFrameworkRequest { /** * The identifier for the specified framework. */ frameworkId: UUID; /** * The name of the framework to be updated. */ name: FrameworkName; /** * The description of the framework that is to be updated. */ description?: FrameworkDescription; /** * The compliance type that the new custom framework supports, such as CIS or HIPAA. */ complianceType?: ComplianceType; /** * The control sets associated with the framework. */ controlSets: UpdateAssessmentFrameworkControlSets; } export interface UpdateAssessmentFrameworkResponse { /** * The name of the specified framework. */ framework?: Framework; } export interface UpdateAssessmentRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The name of the specified assessment to be updated. */ assessmentName?: AssessmentName; /** * The description of the specified assessment. */ assessmentDescription?: AssessmentDescription; /** * The scope of the specified assessment. */ scope: Scope; /** * The assessment report storage destination for the specified assessment that is being updated. */ assessmentReportsDestination?: AssessmentReportsDestination; /** * The list of roles for the specified assessment. */ roles?: Roles; } export interface UpdateAssessmentResponse { /** * The response object (name of the updated assessment) for the UpdateAssessmentRequest API. */ assessment?: Assessment; } export interface UpdateAssessmentStatusRequest { /** * The identifier for the specified assessment. */ assessmentId: UUID; /** * The current status of the specified assessment. */ status: AssessmentStatus; } export interface UpdateAssessmentStatusResponse { /** * The name of the updated assessment returned by the UpdateAssessmentStatus API. */ assessment?: Assessment; } export interface UpdateControlRequest { /** * The identifier for the specified control. */ controlId: UUID; /** * The name of the control to be updated. */ name: ControlName; /** * The optional description of the control. */ description?: ControlDescription; /** * The steps that to follow to determine if the control has been satisfied. */ testingInformation?: TestingInformation; /** * The title of the action plan for remediating the control. */ actionPlanTitle?: ActionPlanTitle; /** * The recommended actions to carry out if the control is not fulfilled. */ actionPlanInstructions?: ActionPlanInstructions; /** * The data mapping sources for the specified control. */ controlMappingSources: ControlMappingSources; } export interface UpdateControlResponse { /** * The name of the updated control set returned by the UpdateControl API. */ control?: Control; } export interface UpdateSettingsRequest { /** * The Amazon Simple Notification Service (Amazon SNS) topic to which Audit Manager sends notifications. */ snsTopic?: SnsArn; /** * The default storage destination for assessment reports. */ defaultAssessmentReportsDestination?: AssessmentReportsDestination; /** * A list of the default audit owners. */ defaultProcessOwners?: Roles; /** * The KMS key details. */ kmsKey?: KmsKey; } export interface UpdateSettingsResponse { /** * The current list of settings. */ settings?: Settings; } export type UrlLink = string; export type Username = string; export interface ValidateAssessmentReportIntegrityRequest { /** * The relative path of the specified Amazon S3 bucket in which the assessment report is stored. */ s3RelativePath: S3Url; } export interface ValidateAssessmentReportIntegrityResponse { /** * Specifies whether the signature key is valid. */ signatureValid?: Boolean; /** * The signature algorithm used to code sign the assessment report file. */ signatureAlgorithm?: String; /** * The date and time signature that specifies when the assessment report was created. */ signatureDateTime?: String; /** * The unique identifier for the validation signature key. */ signatureKeyId?: String; /** * Represents any errors that occurred when validating the assessment report. */ validationErrors?: ValidationErrors; } export type ValidationErrors = NonEmptyString[]; export type organizationId = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-07-25"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the AuditManager client. */ export import Types = AuditManager; } export = AuditManager;
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [backup](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbackup.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Backup extends PolicyStatement { public servicePrefix = 'backup'; /** * Statement provider for service [backup](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsbackup.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 copy from a backup vault * * Access Level: Write * * Possible conditions: * - .ifCopyTargets() * - .ifCopyTargetOrgPaths() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartCopyJob.html */ public toCopyFromBackupVault() { return this.to('CopyFromBackupVault'); } /** * Grants permission to copy into a backup vault * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartCopyJob.html */ public toCopyIntoBackupVault() { return this.to('CopyIntoBackupVault'); } /** * Grants permission to create a new backup plan * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_CreateBackupPlan.html */ public toCreateBackupPlan() { return this.to('CreateBackupPlan'); } /** * Grants permission to create a new resource assignment in a backup plan * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_CreateBackupSelection.html */ public toCreateBackupSelection() { return this.to('CreateBackupSelection'); } /** * Grants permission to create a new backup vault * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_CreateBackupVault.html */ public toCreateBackupVault() { return this.to('CreateBackupVault'); } /** * Grants permission to create a new framework * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_CreateFramework.html */ public toCreateFramework() { return this.to('CreateFramework'); } /** * Grants permission to create a new report plan * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * - .ifFrameworkArns() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_CreateReportPlan.html */ public toCreateReportPlan() { return this.to('CreateReportPlan'); } /** * Grants permission to delete a backup plan * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupPlan.html */ public toDeleteBackupPlan() { return this.to('DeleteBackupPlan'); } /** * Grants permission to delete a resource assignment from a backup plan * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupSelection.html */ public toDeleteBackupSelection() { return this.to('DeleteBackupSelection'); } /** * Grants permission to delete a backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupVault.html */ public toDeleteBackupVault() { return this.to('DeleteBackupVault'); } /** * Grants permission to delete backup vault access policy * * Access Level: Permissions management * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupVaultAccessPolicy.html */ public toDeleteBackupVaultAccessPolicy() { return this.to('DeleteBackupVaultAccessPolicy'); } /** * Grants permission to remove the lock configuration from a backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupVaultLockConfiguration.html */ public toDeleteBackupVaultLockConfiguration() { return this.to('DeleteBackupVaultLockConfiguration'); } /** * Grants permission to remove the notifications from a backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteBackupVaultNotifications.html */ public toDeleteBackupVaultNotifications() { return this.to('DeleteBackupVaultNotifications'); } /** * Grants permission to delete a framework * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteFramework.html */ public toDeleteFramework() { return this.to('DeleteFramework'); } /** * Grants permission to delete a recovery point from a backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteRecoveryPoint.html */ public toDeleteRecoveryPoint() { return this.to('DeleteRecoveryPoint'); } /** * Grants permission to delete a report plan * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DeleteReportPlan.html */ public toDeleteReportPlan() { return this.to('DeleteReportPlan'); } /** * Grants permission to describe a backup job * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeBackupJob.html */ public toDescribeBackupJob() { return this.to('DescribeBackupJob'); } /** * Grants permission to describe a new backup vault with the specified name * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeBackupVault.html */ public toDescribeBackupVault() { return this.to('DescribeBackupVault'); } /** * Grants permission to describe a copy job * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeCopyJob.html */ public toDescribeCopyJob() { return this.to('DescribeCopyJob'); } /** * Grants permission to describe a framework with the specified name * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeFramework.html */ public toDescribeFramework() { return this.to('DescribeFramework'); } /** * Grants permission to describe global settings * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeGlobalSettings.html */ public toDescribeGlobalSettings() { return this.to('DescribeGlobalSettings'); } /** * Grants permission to describe a protected resource * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeProtectedResource.html */ public toDescribeProtectedResource() { return this.to('DescribeProtectedResource'); } /** * Grants permission to describe a recovery point * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeRecoveryPoint.html */ public toDescribeRecoveryPoint() { return this.to('DescribeRecoveryPoint'); } /** * Grants permission to describe region settings * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeRegionSettings.html */ public toDescribeRegionSettings() { return this.to('DescribeRegionSettings'); } /** * Grants permission to describe a report job * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeReportJob.html */ public toDescribeReportJob() { return this.to('DescribeReportJob'); } /** * Grants permission to describe a report plan with the specified name * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeReportPlan.html */ public toDescribeReportPlan() { return this.to('DescribeReportPlan'); } /** * Grants permission to describe a restore job * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DescribeRestoreJob.html */ public toDescribeRestoreJob() { return this.to('DescribeRestoreJob'); } /** * Grants permission to disassociate a recovery point from a backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_DisassociateRecoveryPoint.html */ public toDisassociateRecoveryPoint() { return this.to('DisassociateRecoveryPoint'); } /** * Grants permission to export a backup plan as a JSON * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ExportBackupPlanTemplate.html */ public toExportBackupPlanTemplate() { return this.to('ExportBackupPlanTemplate'); } /** * Grants permission to get a backup plan * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupPlan.html */ public toGetBackupPlan() { return this.to('GetBackupPlan'); } /** * Grants permission to transform a JSON to a backup plan * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupPlanFromJSON.html */ public toGetBackupPlanFromJSON() { return this.to('GetBackupPlanFromJSON'); } /** * Grants permission to transform a template to a backup plan * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupPlanFromTemplate.html */ public toGetBackupPlanFromTemplate() { return this.to('GetBackupPlanFromTemplate'); } /** * Grants permission to get a backup plan resource assignment * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupSelection.html */ public toGetBackupSelection() { return this.to('GetBackupSelection'); } /** * Grants permission to get backup vault access policy * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupVaultAccessPolicy.html */ public toGetBackupVaultAccessPolicy() { return this.to('GetBackupVaultAccessPolicy'); } /** * Grants permission to get backup vault notifications * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetBackupVaultNotifications.html */ public toGetBackupVaultNotifications() { return this.to('GetBackupVaultNotifications'); } /** * Grants permission to get recovery point restore metadata * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetRecoveryPointRestoreMetadata.html */ public toGetRecoveryPointRestoreMetadata() { return this.to('GetRecoveryPointRestoreMetadata'); } /** * Grants permission to get supported resource types * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_GetSupportedResourceTypes.html */ public toGetSupportedResourceTypes() { return this.to('GetSupportedResourceTypes'); } /** * Grants permission to list backup jobs * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupJobs.html */ public toListBackupJobs() { return this.to('ListBackupJobs'); } /** * Grants permission to list backup plan templates provided by AWS Backup * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupPlanTemplates.html */ public toListBackupPlanTemplates() { return this.to('ListBackupPlanTemplates'); } /** * Grants permission to list backup plan versions * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupPlanVersions.html */ public toListBackupPlanVersions() { return this.to('ListBackupPlanVersions'); } /** * Grants permission to list backup plans * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupPlans.html */ public toListBackupPlans() { return this.to('ListBackupPlans'); } /** * Grants permission to list resource assignments for a specific backup plan * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupSelections.html */ public toListBackupSelections() { return this.to('ListBackupSelections'); } /** * Grants permission to list backup vaults * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListBackupVaults.html */ public toListBackupVaults() { return this.to('ListBackupVaults'); } /** * Grants permission to list copy jobs * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListCopyJobs.html */ public toListCopyJobs() { return this.to('ListCopyJobs'); } /** * Grants permission to list frameworks * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListFrameworks.html */ public toListFrameworks() { return this.to('ListFrameworks'); } /** * Grants permission to list protected resources by AWS Backup * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListProtectedResources.html */ public toListProtectedResources() { return this.to('ListProtectedResources'); } /** * Grants permission to list recovery points inside a backup vault * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListRecoveryPointsByBackupVault.html */ public toListRecoveryPointsByBackupVault() { return this.to('ListRecoveryPointsByBackupVault'); } /** * Grants permission to list recovery points for a resource * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListRecoveryPointsByResource.html */ public toListRecoveryPointsByResource() { return this.to('ListRecoveryPointsByResource'); } /** * Grants permission to list report jobs * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListReportJobs.html */ public toListReportJobs() { return this.to('ListReportJobs'); } /** * Grants permission to list report plans * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListReportPlans.html */ public toListReportPlans() { return this.to('ListReportPlans'); } /** * Grants permission to lists restore jobs * * Access Level: List * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListRestoreJobs.html */ public toListRestoreJobs() { return this.to('ListRestoreJobs'); } /** * Grants permission to list tags for a resource * * Access Level: Read * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_ListTags.html */ public toListTags() { return this.to('ListTags'); } /** * Grants permission to add an access policy to the backup vault * * Access Level: Permissions management * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_PutBackupVaultAccessPolicy.html */ public toPutBackupVaultAccessPolicy() { return this.to('PutBackupVaultAccessPolicy'); } /** * Grants permission to add a lock configuration to the backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_PutBackupVaultLockConfiguration.html */ public toPutBackupVaultLockConfiguration() { return this.to('PutBackupVaultLockConfiguration'); } /** * Grants permission to add an SNS topic to the backup vault * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_PutBackupVaultNotifications.html */ public toPutBackupVaultNotifications() { return this.to('PutBackupVaultNotifications'); } /** * Grants permission to start a new backup job * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartBackupJob.html */ public toStartBackupJob() { return this.to('StartBackupJob'); } /** * Grants permission to copy a backup from a source backup vault to a destination backup vault * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartCopyJob.html */ public toStartCopyJob() { return this.to('StartCopyJob'); } /** * Grants permission to start a new report job * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartReportJob.html */ public toStartReportJob() { return this.to('StartReportJob'); } /** * Grants permission to start a new restore job * * Access Level: Write * * Dependent actions: * - iam:PassRole * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StartRestoreJob.html */ public toStartRestoreJob() { return this.to('StartRestoreJob'); } /** * Grants permission to stop a backup job * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_StopBackupJob.html */ public toStopBackupJob() { return this.to('StopBackupJob'); } /** * Grants permission to tag a resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag a resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update a backup plan * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateBackupPlan.html */ public toUpdateBackupPlan() { return this.to('UpdateBackupPlan'); } /** * Grants permission to update a framework * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateFramework.html */ public toUpdateFramework() { return this.to('UpdateFramework'); } /** * Grants permission to update the current global settings for the AWS Account * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateGlobalSettings.html */ public toUpdateGlobalSettings() { return this.to('UpdateGlobalSettings'); } /** * Grants permission to update the lifecycle of the recovery point * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateRecoveryPointLifecycle.html */ public toUpdateRecoveryPointLifecycle() { return this.to('UpdateRecoveryPointLifecycle'); } /** * Grants permission to update the current service opt-in settings for the Region * * Access Level: Write * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateRegionSettings.html */ public toUpdateRegionSettings() { return this.to('UpdateRegionSettings'); } /** * Grants permission to update a report plan * * Access Level: Write * * Possible conditions: * - .ifFrameworkArns() * * https://docs.aws.amazon.com/aws-backup/latest/devguide/API_UpdateReportPlan.html */ public toUpdateReportPlan() { return this.to('UpdateReportPlan'); } protected accessLevelList: AccessLevelList = { "Write": [ "CopyFromBackupVault", "CopyIntoBackupVault", "CreateBackupPlan", "CreateBackupSelection", "CreateBackupVault", "CreateFramework", "CreateReportPlan", "DeleteBackupPlan", "DeleteBackupSelection", "DeleteBackupVault", "DeleteBackupVaultLockConfiguration", "DeleteBackupVaultNotifications", "DeleteFramework", "DeleteRecoveryPoint", "DeleteReportPlan", "DisassociateRecoveryPoint", "PutBackupVaultLockConfiguration", "PutBackupVaultNotifications", "StartBackupJob", "StartCopyJob", "StartReportJob", "StartRestoreJob", "StopBackupJob", "UpdateBackupPlan", "UpdateFramework", "UpdateGlobalSettings", "UpdateRecoveryPointLifecycle", "UpdateRegionSettings", "UpdateReportPlan" ], "Permissions management": [ "DeleteBackupVaultAccessPolicy", "PutBackupVaultAccessPolicy" ], "Read": [ "DescribeBackupJob", "DescribeBackupVault", "DescribeCopyJob", "DescribeFramework", "DescribeGlobalSettings", "DescribeProtectedResource", "DescribeRecoveryPoint", "DescribeRegionSettings", "DescribeReportJob", "DescribeReportPlan", "DescribeRestoreJob", "ExportBackupPlanTemplate", "GetBackupPlan", "GetBackupPlanFromJSON", "GetBackupPlanFromTemplate", "GetBackupSelection", "GetBackupVaultAccessPolicy", "GetBackupVaultNotifications", "GetRecoveryPointRestoreMetadata", "GetSupportedResourceTypes", "ListTags" ], "List": [ "ListBackupJobs", "ListBackupPlanTemplates", "ListBackupPlanVersions", "ListBackupPlans", "ListBackupSelections", "ListBackupVaults", "ListCopyJobs", "ListFrameworks", "ListProtectedResources", "ListRecoveryPointsByBackupVault", "ListRecoveryPointsByResource", "ListReportJobs", "ListReportPlans", "ListRestoreJobs" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type backupVault to the statement * * https://docs.aws.amazon.com/aws-backup/latest/devguide/vaults.html * * @param backupVaultName - Identifier for the backupVaultName. * @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 onBackupVault(backupVaultName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:backup:${Region}:${Account}:backup-vault:${BackupVaultName}'; arn = arn.replace('${BackupVaultName}', backupVaultName); 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 backupPlan to the statement * * https://docs.aws.amazon.com/aws-backup/latest/devguide/about-backup-plans.html * * @param backupPlanId - Identifier for the backupPlanId. * @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 onBackupPlan(backupPlanId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:backup:${Region}:${Account}:backup-plan:${BackupPlanId}'; arn = arn.replace('${BackupPlanId}', backupPlanId); 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 recoveryPoint to the statement * * https://docs.aws.amazon.com/aws-backup/latest/devguide/recovery-points.html * * @param recoveryPointId - Identifier for the recoveryPointId. * @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 onRecoveryPoint(recoveryPointId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:backup:${Region}:${Account}:recovery-point:${RecoveryPointId}'; arn = arn.replace('${RecoveryPointId}', recoveryPointId); 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 framework to the statement * * https://docs.aws.amazon.com/aws-backup/latest/devguide/frameworks.html * * @param frameworkName - Identifier for the frameworkName. * @param frameworkId - Identifier for the frameworkId. * @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 onFramework(frameworkName: string, frameworkId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:backup:${Region}:${Account}:framework:${FrameworkName}-${FrameworkId}'; arn = arn.replace('${FrameworkName}', frameworkName); arn = arn.replace('${FrameworkId}', frameworkId); 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 reportPlan to the statement * * https://docs.aws.amazon.com/aws-backup/latest/devguide/report-plans.html * * @param reportPlanName - Identifier for the reportPlanName. * @param reportPlanId - Identifier for the reportPlanId. * @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 onReportPlan(reportPlanName: string, reportPlanId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:backup:${Region}:${Account}:report-plan:${ReportPlanName}-${ReportPlanId}'; arn = arn.replace('${ReportPlanName}', reportPlanName); arn = arn.replace('${ReportPlanId}', reportPlanId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access by the organization unit * * https://docs.aws.amazon.com/aws-backup/latest/devguide/access-control.html#amazon-backup-keys * * Applies to actions: * - .toCopyFromBackupVault() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifCopyTargetOrgPaths(value: string | string[], operator?: Operator | string) { return this.if(`CopyTargetOrgPaths`, value, operator || 'StringLike'); } /** * Filters access by the ARN of an backup vault * * https://docs.aws.amazon.com/aws-backup/latest/devguide/access-control.html#amazon-backup-keys * * Applies to actions: * - .toCopyFromBackupVault() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifCopyTargets(value: string | string[], operator?: Operator | string) { return this.if(`CopyTargets`, value, operator || 'StringLike'); } /** * Filters access by the Framework ARNs * * https://docs.aws.amazon.com/aws-backup/latest/devguide/access-control.html#amazon-backup-keys * * Applies to actions: * - .toCreateReportPlan() * - .toUpdateReportPlan() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFrameworkArns(value: string | string[], operator?: Operator | string) { return this.if(`FrameworkArns`, value, operator || 'StringLike'); } }
the_stack
import { render, screen, waitFor, waitForElementToBeRemoved, within, } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { getProfileLinkA11yLabel } from "components/Avatar/constants"; import { Route, Switch } from "react-router-dom"; import { discussionBaseRoute, discussionRoute } from "routes"; import { service } from "service"; import comments from "test/fixtures/comments.json"; import community from "test/fixtures/community.json"; import discussions from "test/fixtures/discussions.json"; import { getHookWrapperWithClient } from "test/hookWrapper"; import { getThread, getUser } from "test/serviceMockDefaults"; import { assertErrorAlert, mockConsoleError, MockedService, wait, } from "test/utils"; import { CLOSE, COMMENT, COMMENTS, getByCreator, LOAD_EARLIER_COMMENTS, LOAD_EARLIER_REPLIES, NO_COMMENTS, PREVIOUS_PAGE, REPLY, WRITE_COMMENT_A11Y_LABEL, } from "../constants"; import { COMMENT_TEST_ID, REFETCH_LOADING_TEST_ID } from "./Comment"; import DiscussionPage, { CREATOR_TEST_ID } from "./DiscussionPage"; jest.mock("components/MarkdownInput"); const getUserMock = service.user.getUser as MockedService< typeof service.user.getUser >; const getCommunityMock = service.communities.getCommunity as MockedService< typeof service.communities.getCommunity >; const getDiscussionMock = service.discussions.getDiscussion as MockedService< typeof service.discussions.getDiscussion >; const getThreadMock = service.threads.getThread as MockedService< typeof service.threads.getThread >; const postReplyMock = service.threads.postReply as MockedService< typeof service.threads.postReply >; function renderDiscussion() { const { client, wrapper } = getHookWrapperWithClient({ initialRouterEntries: [ "/previous-page", `${discussionBaseRoute}/1/what-is-there-to-do-in-amsterdam`, ], initialIndex: 1, }); render( <Switch> <Route exact path={discussionRoute}> <DiscussionPage /> </Route> <Route exact path="/previous-page"> <h1 data-testid="previous-page">Previous page</h1> </Route> </Switch>, { wrapper } ); return client; } function getThreadAfterSuccessfulComment({ newComment, threadIdToUpdate, }: { newComment: string; threadIdToUpdate: number; }) { return async (threadId: number) => { const res = await getThread(threadId); if (threadId === threadIdToUpdate) { await wait(100); return { repliesList: [ { authorUserId: 1, content: newComment, numReplies: 0, threadId: 999, createdTime: { seconds: 1577960000, nanos: 0 }, }, ...res.repliesList, ], nextPageToken: "", }; } return res; }; } describe("Discussion page", () => { beforeAll(() => { jest.useFakeTimers("modern"); jest.setSystemTime(new Date("2021-05-10")); }); afterAll(() => { jest.useRealTimers(); }); beforeEach(() => { getUserMock.mockImplementation(getUser); getCommunityMock.mockResolvedValue(community); getDiscussionMock.mockResolvedValue(discussions[0]); getThreadMock.mockImplementation(getThread); postReplyMock.mockResolvedValue({ threadId: 999, }); }); it("renders the discussion successfully", async () => { renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); // Author and discussion content assertions expect( screen.getByRole("heading", { level: 1, name: "What is there to do in Amsterdam?", }) ).toBeVisible(); expect( screen.getByText(/i'm looking for activities to do here!/i) ).toBeVisible(); const creatorContainer = within(screen.getByTestId(CREATOR_TEST_ID)); expect( creatorContainer.getByRole("link", { name: getProfileLinkA11yLabel("Funny Cat current User"), }) ).toBeVisible(); expect(creatorContainer.getByText("Funny Cat current User")).toBeVisible(); expect(creatorContainer.getByText("Created at Jan 01, 2020")).toBeVisible(); }); it("renders a loading skeleton if the user info is still loading", async () => { getUserMock.mockImplementation(async () => new Promise(() => undefined)); renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); expect( await screen.findByRole("heading", { level: 1, name: "What is there to do in Amsterdam?", }) ).toBeVisible(); expect( screen.queryByRole("link", { name: getProfileLinkA11yLabel("Funny Cat current User"), }) ).not.toBeInTheDocument(); expect( screen.queryByText("Funny Cat current User") ).not.toBeInTheDocument(); expect( screen.queryByText("Created at Jan 01, 2020") ).not.toBeInTheDocument(); }); it("renders the comments tree in the discussion correctly", async () => { renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const commentCards = await ( await screen.findAllByTestId(COMMENT_TEST_ID) ).map((element) => within(element)); expect(commentCards).toHaveLength(8); expect(screen.getByRole("heading", { name: COMMENTS })).toBeVisible(); // check top level comment const firstTopLevelComment = comments.find((c) => c.threadId === 6); const commentUser = await getUser( firstTopLevelComment!.authorUserId.toString() ); expect( commentCards[0].getByRole("img", { name: commentUser.name }) ).toBeVisible(); expect( commentCards[0].getByRole("link", { name: getProfileLinkA11yLabel(commentUser.name), }) ).toBeVisible(); expect( commentCards[0].getByText( `${getByCreator(commentUser.name)} • 1 year ago` ) ).toBeVisible(); expect( commentCards[0].getByText(firstTopLevelComment!.content) ).toBeVisible(); expect(commentCards[0].getByRole("button", { name: REPLY })).toBeVisible(); // check nested comment/reply const replyUser = await getUser("3"); expect( commentCards[1].getByRole("img", { name: replyUser.name }) ).toBeVisible(); expect( commentCards[1].getByRole("link", { name: getProfileLinkA11yLabel(replyUser.name), }) ).toBeVisible(); expect( commentCards[1].getByText(`${getByCreator(replyUser.name)} • 1 year ago`) ).toBeVisible(); expect(commentCards[1].getByText("+6")).toBeVisible(); // Nested comment cannot be replied on further expect( commentCards[1].queryByRole("button", { name: REPLY }) ).not.toBeInTheDocument(); }); it("shows the no comments message if there aren't any in the discussion", async () => { getThreadMock.mockResolvedValue({ nextPageToken: "", repliesList: [] }); renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); expect(screen.getByText(NO_COMMENTS)).toBeVisible(); }); describe("when there are more than one page of comments", () => { it("shows a 'load earlier comments' button that lets you load earlier comments", async () => { getThreadMock.mockImplementation(async (threadId, pageToken) => { if (threadId === 2) { return pageToken ? { nextPageToken: "", repliesList: [comments[2], comments[3]] } : { nextPageToken: "4", repliesList: [comments[0], comments[1]] }; } return getThread(threadId); }); renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); userEvent.click( screen.getByRole("button", { name: LOAD_EARLIER_COMMENTS }) ); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const firstCommentAfterLoadMore = screen.getAllByTestId(COMMENT_TEST_ID)[0]; expect( within(firstCommentAfterLoadMore).getByText(comments[3].content) ).toBeVisible(); // 1 for main discussion + 4 comments + 1 for second page of discussion expect(getThreadMock).toHaveBeenCalledTimes(6); expect(getThreadMock).toHaveBeenCalledWith(2, "4"); }); it("shows a 'load more replies' button that lets you load earlier replies", async () => { getThreadMock.mockImplementation(async (threadId, pageToken) => { if (threadId === 3) { return pageToken ? { nextPageToken: "", repliesList: [ { ...comments[4], threadId: 72, content: "Agreed!" }, ], } : { nextPageToken: "71", repliesList: [comments[4]] }; } return getThread(threadId); }); renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); userEvent.click( screen.getByRole("button", { name: LOAD_EARLIER_REPLIES }) ); await waitForElementToBeRemoved(screen.getByRole("progressbar")); expect(screen.getByText("Agreed!")).toBeVisible(); // 1 for main discussion + 4 comments + 1 for second page of reply for oldest comment expect(getThreadMock).toHaveBeenCalledTimes(6); expect(getThreadMock).toHaveBeenCalledWith(3, "71"); }); }); it("shows an error alert if the comments fails to load", async () => { mockConsoleError(); const errorMessage = "Cannot get thread"; getThreadMock.mockRejectedValue(new Error(errorMessage)); renderDiscussion(); await assertErrorAlert(errorMessage); }); it("goes back to the previous page when the back button is clicked", async () => { renderDiscussion(); await screen.findByRole("heading", { level: 1, name: "What is there to do in Amsterdam?", }); userEvent.click(screen.getByRole("button", { name: PREVIOUS_PAGE })); expect(screen.getByTestId("previous-page")).toBeInTheDocument(); }); it("shows an error alert if the discussion fails to load", async () => { mockConsoleError(); const errorMessage = "Error getting discussion"; getDiscussionMock.mockRejectedValue(new Error(errorMessage)); renderDiscussion(); await assertErrorAlert(errorMessage); }); describe("Adding a comment to the discussion", () => { const COMMENT_TREE_COMMENT_FORM_TEST_ID = "comment-2-comment-form"; it("posts and displays the new comment to the discussion successfully", async () => { renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const discussionCommentForm = within( screen.getByTestId(COMMENT_TREE_COMMENT_FORM_TEST_ID) ); const newComment = "Glad I checked it out. It was great!"; getThreadMock.mockImplementation( getThreadAfterSuccessfulComment({ newComment, threadIdToUpdate: 2 }) ); userEvent.type( discussionCommentForm.getByLabelText(WRITE_COMMENT_A11Y_LABEL), newComment ); userEvent.click( discussionCommentForm.getByRole("button", { name: COMMENT }) ); expect(await screen.findByText(newComment)).toBeVisible(); expect(postReplyMock).toHaveBeenCalledTimes(1); expect(postReplyMock).toHaveBeenCalledWith(2, newComment); }); it("shows an error alert if the comment failed to post", async () => { mockConsoleError(); const errorMessage = "Error posting comment"; postReplyMock.mockRejectedValue(new Error(errorMessage)); renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const discussionCommentForm = within( screen.getByTestId(COMMENT_TREE_COMMENT_FORM_TEST_ID) ); userEvent.type( discussionCommentForm.getByLabelText(WRITE_COMMENT_A11Y_LABEL), "new comment" ); userEvent.click( discussionCommentForm.getByRole("button", { name: COMMENT }) ); await assertErrorAlert(errorMessage); }); }); describe("Adding a comment/reply to a comment", () => { const FIRST_COMMENT_FORM_TEST_ID = "comment-6-comment-form"; it("posts and displays the new comment below the top level comment successfully", async () => { renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const firstComment = within( (await screen.findAllByTestId(COMMENT_TEST_ID))[0] ); userEvent.click(firstComment.getByRole("button", { name: REPLY })); const commentFormContainer = screen.getByTestId( FIRST_COMMENT_FORM_TEST_ID ); // The comment form is opened when the transition container has height as "auto" await waitFor(() => { expect(window.getComputedStyle(commentFormContainer).height).toEqual( "auto" ); }); const newComment = "+100"; getThreadMock.mockImplementation( getThreadAfterSuccessfulComment({ newComment, threadIdToUpdate: 6 }) ); userEvent.type( within(commentFormContainer).getByLabelText(WRITE_COMMENT_A11Y_LABEL), newComment ); userEvent.click( within(commentFormContainer).getByRole("button", { name: COMMENT }) ); // Check refetch loading state is shown while user is waiting for reply expect( await screen.findByTestId(REFETCH_LOADING_TEST_ID) ).toBeInTheDocument(); expect(await screen.findByText(newComment)).toBeVisible(); expect(postReplyMock).toHaveBeenCalledTimes(1); // (threadId, content) expect(postReplyMock).toHaveBeenCalledWith(6, newComment); }); it("closes the comment form when the close button is clicked", async () => { renderDiscussion(); await waitForElementToBeRemoved(screen.getByRole("progressbar")); const firstComment = within( (await screen.findAllByTestId(COMMENT_TEST_ID))[0] ); userEvent.click(firstComment.getByRole("button", { name: REPLY })); // The comment form is opened when the transition container has height as "auto" const commentFormContainer = screen.getByTestId( FIRST_COMMENT_FORM_TEST_ID ); await waitFor(() => { expect(window.getComputedStyle(commentFormContainer).height).toEqual( "auto" ); }); userEvent.click( within(commentFormContainer).getByRole("button", { name: CLOSE }) ); // The transition container has 0 height when the form is closed await waitFor(() => { expect(window.getComputedStyle(commentFormContainer).height).toEqual( "0px" ); }); }); }); });
the_stack
import { Palette, PropertyExt, SVGWidget, Utility } from "@hpcc-js/common"; import { max as d3Max, mean as d3Mean, median as d3Median, min as d3Min, sum as d3Sum } from "d3-array"; import { sankey as d3Sankey, sankeyLinkHorizontal as d3SankeyLinkHorizontal } from "d3-sankey"; import { select as d3Select } from "d3-selection"; import "../src/Sankey.css"; const d3Aggr = { mean: d3Mean, median: d3Median, min: d3Min, max: d3Max, sum: d3Sum }; export class SankeyColumn extends PropertyExt { _owner: Sankey; constructor() { super(); } owner(): Sankey; owner(_: Sankey): this; owner(_?: Sankey): Sankey | this { if (!arguments.length) return this._owner; this._owner = _; return this; } valid(): boolean { return !!this.column(); } aggregate(values) { switch (this.aggrType()) { case null: case undefined: case "": return values.length; default: const columns = this._owner.columns(); const colIdx = columns.indexOf(this.aggrColumn()); return d3Aggr[this.aggrType()](values, function (value) { return +value[colIdx]; }); } } column: { (): string; (_: string): SankeyColumn; }; aggrType: { (): string; (_: string): SankeyColumn; }; aggrColumn: { (): string; (_: string): SankeyColumn; }; } SankeyColumn.prototype._class += " graph_Sankey.SankeyColumn"; SankeyColumn.prototype.publish("column", null, "set", "Field", function () { return this._owner ? this._owner.columns() : []; }, { optional: true }); SankeyColumn.prototype.publish("aggrType", null, "set", "Aggregation Type", [null, "mean", "median", "sum", "min", "max"], { optional: true, disable: w => !w._owner || w._owner.mappings().indexOf(w) === 0 }); SankeyColumn.prototype.publish("aggrColumn", null, "set", "Aggregation Field", function () { return this._owner ? this._owner.columns() : []; }, { optional: true, disable: w => !w._owner || !w.aggrType() || w._owner.mappings().indexOf(w) === 0 }); export class Sankey extends SVGWidget { Column; _palette; _d3Sankey; _d3SankeyPath; _selection; constructor() { super(); Utility.SimpleSelectionMixin.call(this); this._drawStartPos = "origin"; } sankeyData() { const retVal = { vertices: [], edges: [] }; if (this.data().length === 0) return retVal; const vertexIndex = {}; const valueIdx = 2; const mappings = this.mappings().filter(mapping => mapping.valid()); mappings.forEach(function (mapping, idx) { const view = this._db.rollupView([mapping.column()]); view.entries().forEach(function (row) { const id = mapping.column() + ":" + idx + ":" + row.key; if (!vertexIndex[id]) { retVal.vertices.push({ __id: id, __category: mapping.column(), name: row.key, origRow: row.value, value: row.value[idx][valueIdx] }); vertexIndex[id] = retVal.vertices.length - 1; } }, this); }, this); mappings.forEach(function (mapping, idx) { if (idx < mappings.length - 1) { const mapping2 = mappings[idx + 1]; const view = this._db.rollupView([mapping.column(), mapping2.column()]); view.entries().forEach(function (row) { const sourceID = mapping.column() + ":" + idx + ":" + row.key; row.values.forEach(function (value) { const targetID = mapping2.column() + ":" + (idx + 1) + ":" + value.key; retVal.edges.push({ __id: sourceID + "_" + targetID, source: vertexIndex[sourceID], target: vertexIndex[targetID], value: value.value[0][valueIdx] }); }); }); } }, this); return retVal; } enter(domNode, element) { super.enter(domNode, element); this._d3Sankey = new d3Sankey(); this._selection.widgetElement(element); } update(domNode, element) { super.update(domNode, element); this._palette = this._palette.switch(this.paletteID()); const strokeWidth = this.vertexStrokeWidth(); const sankeyData = this.sankeyData(); const sw2 = strokeWidth * 2; this._d3Sankey .extent([ [strokeWidth, strokeWidth], [this.width() - sw2, this.height() - sw2] ]) .nodeWidth(this.vertexWidth()) .nodePadding(this.vertexPadding()) ; this._d3Sankey({ nodes: sankeyData.vertices, links: sankeyData.edges }); const context = this; // Links --- const link = element.selectAll(".link").data(sankeyData.edges); link.enter().append("path") .attr("class", "link") .each(function () { d3Select(this) .append("title") ; }) .merge(link) .attr("d", d3SankeyLinkHorizontal()) .style("stroke-width", function (d) { return Math.max(1, d.width); }) .sort(function (a, b) { return b.width - a.width; }) .select("title") .text(function (d) { return d.source.name + " → " + d.target.name + "\n" + d.value; }) ; link.exit().remove(); // Nodes --- const node = element.selectAll(".node").data(sankeyData.vertices); node.enter().append("g") .attr("class", "node") .call(this._selection.enter.bind(this._selection)) .on("click", function (d) { context.click(context.rowToObj(d.origRow[0]), "", context._selection.selected(this)); }) .on("dblclick", function (d) { context.dblclick(context.rowToObj(d.origRow[0]), "", context._selection.selected(this)); }) .each(function () { const gElement = d3Select(this); gElement.append("rect"); gElement.append("text"); }) /* .call(d3.behavior.drag() .origin(function (d) { return d; }) .on("dragstart", function () { this.parentNode.appendChild(this); }) .on("drag", dragmove) ) */ .merge(node) .attr("transform", function (d) { let _x = 0; let _y = 0; if(d.x0)_x=d.x0; if(d.y0)_y=d.y0; return "translate(" + (_x+strokeWidth) + "," + (_y+strokeWidth) + ")"; }) .each(function () { const n = d3Select(this); n.select("rect") .attr("height", function (d: any) { return d.y1 - d.y0; }) .attr("width", context._d3Sankey.nodeWidth()) .style("fill", function (d: any) { return context._palette(d.name); }) .style("stroke", function (d: any) { return context.vertexStrokeColor(); }) .style("stroke-width", function (d: any) { return strokeWidth; }) .style("cursor", (context.xAxisMovement() || context.yAxisMovement()) ? null : "default") ; n.select("text") .attr("x", -6) .attr("y", function (d: any) { return (d.y1 - d.y0)/2; }) .attr("dy", ".35em") .attr("text-anchor", "end") .attr("transform", null) .text(function (d: any) { return d.name; }) .filter(function (d: any) { return d.x0 < context.width() / 2; }) .attr("x", 6 + context._d3Sankey.nodeWidth()) .attr("text-anchor", "start") ; }); node.exit().remove(); /* function dragmove(d) { var gElement = d3.select(this); if (context.xAxisMovement()) { d.x = Math.max(0, Math.min(context.width() - d.dx, d3.event.x)); } if (context.yAxisMovement()) { d.y = Math.max(0, Math.min(context.height() - d.dy, d3.event.y)); } gElement.attr("transform", "translate(" + d.x + "," + d.y + ")"); context._d3Sankey.relayout(); link.attr("d", context._d3SankeyPath); gElement.select("text") .attr("x", -6) .attr("y", function (d) { return d.dy / 2; }) .attr("dy", ".35em") .attr("text-anchor", "end") .attr("transform", null) .text(function (d) { return d.name; }) .filter(function (d) { return d.x < context.width() / 2; }) .attr("x", 6 + context._d3Sankey.nodeWidth()) .attr("text-anchor", "start") ; } */ } paletteID: { (): string; (_: string): Sankey; }; mappings: { (): SankeyColumn[]; (_: SankeyColumn[]): Sankey; }; vertexStrokeWidth: { (): number; (_: number): Sankey; }; vertexStrokeColor: { (): string; (_: string): Sankey; }; vertexWidth: { (): number; (_: number): Sankey; }; vertexPadding: { (): number; (_: number): Sankey; }; xAxisMovement: { (): boolean; (_: boolean): Sankey; }; yAxisMovement: { (): boolean; (_: boolean): Sankey; }; exit(domNode, element) { super.exit(domNode, element); } // Events --- click(row, column, selected) { console.log("Click: " + JSON.stringify(row) + ", " + column + "," + selected); } dblclick(row, column, selected) { console.log("Double Click: " + JSON.stringify(row) + ", " + column + "," + selected); } } Sankey.prototype._class += " graph_Sankey"; Sankey.prototype.Column = SankeyColumn; Sankey.prototype.mixin(Utility.SimpleSelectionMixin); Sankey.prototype._palette = Palette.ordinal("default"); Sankey.prototype.publish("paletteID", "default", "set", "Color palette for this widget", Sankey.prototype._palette.switch()); Sankey.prototype.publish("mappings", [], "propertyArray", "Source Columns", null, { autoExpand: SankeyColumn }); Sankey.prototype.publish("vertexStrokeWidth", 1, "number", "Vertex Stroke Width"); Sankey.prototype.publish("vertexStrokeColor", "darkgray", "string", "Vertex Stroke Color"); Sankey.prototype.publish("vertexWidth", 36, "number", "Vertex Width"); Sankey.prototype.publish("vertexPadding", 40, "number", "Vertex Padding"); Sankey.prototype.publish("xAxisMovement", false, "boolean", "Enable x-axis movement"); Sankey.prototype.publish("yAxisMovement", false, "boolean", "Enable y-axis movement");
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages an Azure Active Directory Diagnostic Setting for Azure Monitor. * * !> **Authentication** The API for this resource does not support service principal authentication. This resource can only be used with Azure CLI authentication. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "west europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountKind: "StorageV2", * accountReplicationType: "LRS", * }); * const exampleAadDiagnosticSetting = new azure.monitoring.AadDiagnosticSetting("exampleAadDiagnosticSetting", { * storageAccountId: exampleAccount.id, * logs: [ * { * category: "SignInLogs", * enabled: true, * retentionPolicy: { * enabled: true, * days: 1, * }, * }, * { * category: "AuditLogs", * enabled: true, * retentionPolicy: { * enabled: true, * days: 1, * }, * }, * { * category: "NonInteractiveUserSignInLogs", * enabled: true, * retentionPolicy: { * enabled: true, * days: 1, * }, * }, * { * category: "ServicePrincipalSignInLogs", * enabled: true, * retentionPolicy: { * enabled: true, * days: 1, * }, * }, * { * category: "ManagedIdentitySignInLogs", * enabled: false, * retentionPolicy: {}, * }, * { * category: "ProvisioningLogs", * enabled: false, * retentionPolicy: {}, * }, * { * category: "ADFSSignInLogs", * enabled: false, * retentionPolicy: {}, * }, * ], * }); * ``` * * ## Import * * Monitor Azure Active Directory Diagnostic Settings can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:monitoring/aadDiagnosticSetting:AadDiagnosticSetting example /providers/Microsoft.AADIAM/diagnosticSettings/setting1 * ``` */ export class AadDiagnosticSetting extends pulumi.CustomResource { /** * Get an existing AadDiagnosticSetting 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?: AadDiagnosticSettingState, opts?: pulumi.CustomResourceOptions): AadDiagnosticSetting { return new AadDiagnosticSetting(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:monitoring/aadDiagnosticSetting:AadDiagnosticSetting'; /** * Returns true if the given object is an instance of AadDiagnosticSetting. 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 AadDiagnosticSetting { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AadDiagnosticSetting.__pulumiType; } /** * Specifies the ID of an Event Hub Namespace Authorization Rule used to send Diagnostics Data. Changing this forces a new resource to be created. */ public readonly eventhubAuthorizationRuleId!: pulumi.Output<string | undefined>; /** * Specifies the name of the Event Hub where Diagnostics Data should be sent. If not specified, the default Event Hub will be used. Changing this forces a new resource to be created. */ public readonly eventhubName!: pulumi.Output<string | undefined>; /** * Specifies the ID of a Log Analytics Workspace where Diagnostics Data should be sent. */ public readonly logAnalyticsWorkspaceId!: pulumi.Output<string | undefined>; /** * One or more `log` blocks as defined below. */ public readonly logs!: pulumi.Output<outputs.monitoring.AadDiagnosticSettingLog[]>; /** * The name which should be used for this Monitor Azure Active Directory Diagnostic Setting. Changing this forces a new Monitor Azure Active Directory Diagnostic Setting to be created. */ public readonly name!: pulumi.Output<string>; /** * The ID of the Storage Account where logs should be sent. Changing this forces a new resource to be created. */ public readonly storageAccountId!: pulumi.Output<string | undefined>; /** * Create a AadDiagnosticSetting 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: AadDiagnosticSettingArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AadDiagnosticSettingArgs | AadDiagnosticSettingState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AadDiagnosticSettingState | undefined; inputs["eventhubAuthorizationRuleId"] = state ? state.eventhubAuthorizationRuleId : undefined; inputs["eventhubName"] = state ? state.eventhubName : undefined; inputs["logAnalyticsWorkspaceId"] = state ? state.logAnalyticsWorkspaceId : undefined; inputs["logs"] = state ? state.logs : undefined; inputs["name"] = state ? state.name : undefined; inputs["storageAccountId"] = state ? state.storageAccountId : undefined; } else { const args = argsOrState as AadDiagnosticSettingArgs | undefined; if ((!args || args.logs === undefined) && !opts.urn) { throw new Error("Missing required property 'logs'"); } inputs["eventhubAuthorizationRuleId"] = args ? args.eventhubAuthorizationRuleId : undefined; inputs["eventhubName"] = args ? args.eventhubName : undefined; inputs["logAnalyticsWorkspaceId"] = args ? args.logAnalyticsWorkspaceId : undefined; inputs["logs"] = args ? args.logs : undefined; inputs["name"] = args ? args.name : undefined; inputs["storageAccountId"] = args ? args.storageAccountId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AadDiagnosticSetting.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AadDiagnosticSetting resources. */ export interface AadDiagnosticSettingState { /** * Specifies the ID of an Event Hub Namespace Authorization Rule used to send Diagnostics Data. Changing this forces a new resource to be created. */ eventhubAuthorizationRuleId?: pulumi.Input<string>; /** * Specifies the name of the Event Hub where Diagnostics Data should be sent. If not specified, the default Event Hub will be used. Changing this forces a new resource to be created. */ eventhubName?: pulumi.Input<string>; /** * Specifies the ID of a Log Analytics Workspace where Diagnostics Data should be sent. */ logAnalyticsWorkspaceId?: pulumi.Input<string>; /** * One or more `log` blocks as defined below. */ logs?: pulumi.Input<pulumi.Input<inputs.monitoring.AadDiagnosticSettingLog>[]>; /** * The name which should be used for this Monitor Azure Active Directory Diagnostic Setting. Changing this forces a new Monitor Azure Active Directory Diagnostic Setting to be created. */ name?: pulumi.Input<string>; /** * The ID of the Storage Account where logs should be sent. Changing this forces a new resource to be created. */ storageAccountId?: pulumi.Input<string>; } /** * The set of arguments for constructing a AadDiagnosticSetting resource. */ export interface AadDiagnosticSettingArgs { /** * Specifies the ID of an Event Hub Namespace Authorization Rule used to send Diagnostics Data. Changing this forces a new resource to be created. */ eventhubAuthorizationRuleId?: pulumi.Input<string>; /** * Specifies the name of the Event Hub where Diagnostics Data should be sent. If not specified, the default Event Hub will be used. Changing this forces a new resource to be created. */ eventhubName?: pulumi.Input<string>; /** * Specifies the ID of a Log Analytics Workspace where Diagnostics Data should be sent. */ logAnalyticsWorkspaceId?: pulumi.Input<string>; /** * One or more `log` blocks as defined below. */ logs: pulumi.Input<pulumi.Input<inputs.monitoring.AadDiagnosticSettingLog>[]>; /** * The name which should be used for this Monitor Azure Active Directory Diagnostic Setting. Changing this forces a new Monitor Azure Active Directory Diagnostic Setting to be created. */ name?: pulumi.Input<string>; /** * The ID of the Storage Account where logs should be sent. Changing this forces a new resource to be created. */ storageAccountId?: pulumi.Input<string>; }
the_stack
import * as vscode from 'vscode'; import { getType, KeywordType } from './wordinfo'; export class DocInfo { static docScaned: vscode.TextDocument | undefined = undefined; static docInfoScaned: DocInfo | undefined = undefined; static getDocInfo(doc: vscode.TextDocument): DocInfo { if (DocInfo.docInfoScaned && DocInfo.docScaned?.version === doc.version && DocInfo.docScaned.fileName === doc.fileName) { } else { DocInfo.docInfoScaned = new DocInfo(doc); DocInfo.docScaned = doc; } return DocInfo.docInfoScaned; } lines: Asmline[]; flat?: AsmSymbol[]; tree?: vscode.DocumentSymbol[]; constructor(doc: vscode.TextDocument) { const asmlines = doc2lines(doc); const tree = lines2tree(asmlines); this.lines = asmlines; this.flat = tree.flat; this.tree = tree.tree; } public findSymbol(word: string): AsmSymbol | undefined { if (this.flat) { for (const sym of this.flat) { if (sym.name === word) { return sym; } } } return; } } /** convert the symboltype from assembly language to VSCode * * | assembly symbol | vscode symbol | 汇编关键字 | vscode关键字 | * | --------------- | ------------- | ---------- | ------------ | * | macro | Module | 宏 | 模块 | * | segment | Class | 段 | 类 | * | procedure | Function | 子程序 | 函数 | * | struct | Struct | 结构体 | 结构体 | * | label | Key | 标号 | 键 | * | variable | Variable | 变量 | 变量 | */ function SymbolVSCfy(asmType: KeywordType): vscode.SymbolKind { switch (asmType) { case KeywordType.Macro: return vscode.SymbolKind.Module; break; case KeywordType.Segment: return vscode.SymbolKind.Class; break; case KeywordType.Procedure: return vscode.SymbolKind.Function; break; case KeywordType.Structure: return vscode.SymbolKind.Struct; break; case KeywordType.Label: return vscode.SymbolKind.Key; break; case KeywordType.Variable: return vscode.SymbolKind.Variable; break; } return vscode.SymbolKind.Null; } class AsmSymbol { type: KeywordType; name: string; RangeorPosition: vscode.Range | vscode.Position; constructor(type: number, name: string, RangeorPosition: vscode.Range | vscode.Position) { this.type = type; this.name = name; this.RangeorPosition = RangeorPosition; } public location(docuri: vscode.Uri): vscode.Location { return new vscode.Location(docuri, this.RangeorPosition); } public markdown(): vscode.MarkdownString { const md = new vscode.MarkdownString(); const typestr: string = getType(this.type); md.appendMarkdown('**' + typestr + "** " + this.name); return md; } } export enum linetype { other, macro, endm, segment, ends, struct, proc, endp, label, variable, end, onlycomment } //TODO: add support for structure export class Asmline { docuri: vscode.Uri; type: linetype = linetype.other; line: number; str: string; name: string | undefined; index = 1; comment: string | undefined; main: string | undefined; commentIndex: number | undefined; operator: string | undefined; operand: string | undefined; treeUsed = false; constructor(str: string, line: number, docuri: vscode.Uri) { this.docuri = docuri; this.line = line; this.str = str; const main = this.getcomment(str);//split mainbody and comment if (main) { if (this.getsymbol1(main) === false)//get symbols of macros,segments,procedures { this.getvarlabel(main); }//get symbols of labels,variables } else { if (this.comment) { this.type = linetype.onlycomment; } } } private getcomment(str: string): string | undefined { let i: number, quoted: string | undefined = undefined; let main: string | null = null, comment: string | undefined = undefined; const arr = str.split(""); for (i = 0; i < arr.length; i++) { if ((arr[i] === "'" || arr[i] === "\"")) { if (quoted === arr[i]) { quoted = undefined; } else if (quoted === undefined) { quoted = arr[i]; } } if (arr[i] === ";" && quoted === undefined) { break; } } if (i < arr.length) { comment = str.substring(i); this.comment = comment?.trim(); } main = str.substring(0, i).trim(); if (main.length === 0) { this.main = undefined; } else { this.main = main; } return this.main; } private getsymbol1(str: string): boolean { let r: RegExpMatchArray | null = null, name: string | undefined; let flag = false; r = str.match(/^\s*(\w+)\s+(\w+)\s*/); let type1: linetype | undefined; if (r) { switch (r[2].toUpperCase()) { case 'MACRO': type1 = linetype.macro; break; case 'SEGMENT': type1 = linetype.segment; break; case 'PROC': type1 = linetype.proc; break; case 'ENDS': type1 = linetype.ends; break; case 'ENDP': type1 = linetype.endp; break; } if (type1) { name = r[1]; } if (r[1].toLowerCase() === 'end') { type1 = linetype.end; name = r[2]; } } //match the end of macro else if (r = str.match(/(endm|ENDM)/)) { type1 = linetype.endm; name = r[1]; } //match the simplified segment definition else if (r = str.match(/^\s*\.([a-zA-Z_@?$]\w+)\s*$/)) { type1 = linetype.segment; name = r[1]; } if (type1 && name) { this.type = type1; this.index = str.indexOf(name); this.name = name; flag = true; } return flag; } private getvarlabel(item: string): void { let r = item.match(/^\s*(\w+\s+|)([dD][bBwWdDfFqQtT]|=|EQU|equ)(\s+.*)$/); let name: string | undefined; if (r) { name = r[1].trim(); this.type = linetype.variable; if (name.length !== 0) { this.name = name; this.index = item.indexOf(r[1]); } this.operator = r[2]; this.operand = r[3].trim(); } else if (r = item.match(/^\s*(\w+\s*:|)\s*(\w+|)(\s+.*|)$/)) { name = r[1]; this.type = linetype.label; if (name.length !== 0) { this.name = name.slice(0, name.length - 1).trim(); this.index = item.indexOf(r[1]); } this.operator = r[2]; this.operand = r[3].trim(); } } public toTasmSymbol(): AsmSymbol | undefined { let one: AsmSymbol | undefined = undefined; if (this.name) { if (this.type === linetype.label) { one = new AsmSymbol(KeywordType.Label, this.name, new vscode.Position(this.line, this.index)); } else if (this.type === linetype.variable) { one = new AsmSymbol(KeywordType.Variable, this.name, new vscode.Position(this.line, this.index)); } } return one; } public varlabelsymbol(): vscode.DocumentSymbol | undefined { let vscsymbol: vscode.DocumentSymbol | undefined; const name = this.name; if (name && (this.type === linetype.variable || this.type === linetype.label)) { let kind: vscode.SymbolKind; const range = new vscode.Range(this.line, 0, this.line, this.str.length); const start = this.str.indexOf(name); const srange = new vscode.Range(this.line, start, this.line, start + name.length); if (this.type === linetype.label) { kind = SymbolVSCfy(KeywordType.Label); vscsymbol = new vscode.DocumentSymbol(name, " ", kind, range, srange); } else if (this.type === linetype.variable) { kind = SymbolVSCfy(KeywordType.Variable); vscsymbol = new vscode.DocumentSymbol(name, " ", kind, range, srange); } } return vscsymbol; } public selectrange(): vscode.Range | undefined { if (this.name && this.index) { return new vscode.Range(this.line, this.index, this.line, this.index + this.name?.length); } } } function doc2lines(document: vscode.TextDocument): Asmline[] { const asmlines: Asmline[] = []; let splitor = '\r\n'; if (document.eol === vscode.EndOfLine.LF) { splitor = '\n'; } const doc = document.getText().split(splitor); doc.forEach( (item, index) => { asmlines.push(new Asmline(item, index, document.uri)); } ); return asmlines; } interface SYMBOLINFO { tree: vscode.DocumentSymbol[]; flat: AsmSymbol[]; } function lines2tree(asmlines: Asmline[]): SYMBOLINFO { const VSCsymbols: vscode.DocumentSymbol[] = [], symbols: AsmSymbol[] = []; let i: number; //find the information of macro,segemnts and procedure asmlines.forEach( (line, index, array) => { //variables and labels const varlabel = line.toTasmSymbol(); if (varlabel) { symbols.push(varlabel); } //find macro if (line.type === linetype.macro) { let lineEndmacro: Asmline | undefined; //find the end of macro for (i = index; i < asmlines.length; i++) { if (array[i].type === linetype.endm) { lineEndmacro = array[i]; break; } } //finded the end of macro if (line.name && lineEndmacro?.line) { const macrorange = new vscode.Range(line.line, line.index, lineEndmacro?.line, lineEndmacro?.index); symbols.push(new AsmSymbol(KeywordType.Macro, line.name, macrorange)); const symbol1 = new vscode.DocumentSymbol(line.name, getType(KeywordType.Macro), SymbolVSCfy(KeywordType.Macro), macrorange, new vscode.Range(line.line, line.index, line.line, line.index + line.name.length)); VSCsymbols.push(symbol1); } } else if (line.type === linetype.segment) { let lineEndSegment: Asmline | undefined;//the line information of the endline of the segment let proc: Asmline | undefined;//the procedure finding const procschild: vscode.DocumentSymbol[] = []; //finding the end of segment line.name and collecting information of procedure for (i = index; i < asmlines.length; i++) { //find proc if (array[i].type === linetype.proc) { proc = array[i]; } //finding the end of proc if (array[i].type === linetype.endp && proc?.name === array[i].name) { const _name = array[i].name; if (proc?.name && _name) { const range: vscode.Range = new vscode.Range(proc?.line, proc?.index, array[i].line, array[i].index + _name.length); const srange: vscode.Range = new vscode.Range(proc.line, proc.index, proc?.line, proc?.index + proc?.name?.length); procschild.push(new vscode.DocumentSymbol(proc?.name, getType(KeywordType.Procedure), SymbolVSCfy(KeywordType.Procedure), range, srange)); symbols.push(new AsmSymbol(KeywordType.Procedure, _name, range)); } } //finding the end of segment if (array[i].type === linetype.ends && array[i].name === line.name) { lineEndSegment = array[i]; break; } //if finding another start of segment, also view as end of the finding segment if (array[i + 1].type === linetype.segment || array[i + 1].type === linetype.end) { lineEndSegment = array[i]; break; } } //finded the end of segment if (line.name && lineEndSegment?.line) { const range = new vscode.Range(line.line, line.index, lineEndSegment?.line, lineEndSegment?.index); symbols.push(new AsmSymbol(KeywordType.Segment, line.name, range)); const symbol1 = new vscode.DocumentSymbol(line.name, getType(KeywordType.Segment), SymbolVSCfy(KeywordType.Segment), range, new vscode.Range(line.line, line.line, line.line, line.line + line.name.length)); symbol1.children = procschild; VSCsymbols.push(symbol1); } } } ); //add information of variables and labels to the symbol tree VSCsymbols.forEach( (item) => { //add labels and variables to macro if (item.kind === SymbolVSCfy(KeywordType.Macro)) { let symbol3: vscode.DocumentSymbol | undefined; for (i = item.range.start.line; i <= item.range.end.line; i++) { symbol3 = asmlines[i].varlabelsymbol(); if (symbol3) { item.children.push(symbol3); } } } //add labels and variables to segemnt and procedure else if (item.kind === SymbolVSCfy(KeywordType.Segment)) { let symbol2: vscode.DocumentSymbol | undefined; item.children.forEach( (item2) => { for (i = item2.range.start.line; i <= item2.range.end.line; i++) { const symbol3 = asmlines[i].varlabelsymbol(); asmlines[i].treeUsed = true; if (symbol3) { item2.children.push(symbol3); } } }, ); for (i = item.range.start.line + 1; i < item.range.end.line; i++) { if (asmlines[i].treeUsed === false) { symbol2 = asmlines[i].varlabelsymbol(); } if (symbol2) { item.children.push(symbol2); } } } } ); return { tree: VSCsymbols, flat: symbols }; }
the_stack
import { HttpErrorResponse } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed, fakeAsync, flushMicrotasks } from '@angular/core/testing'; import { TranslatableTexts } from 'domain/opportunity/translatable-texts.model'; import { ImagesData } from 'services/image-local-storage.service'; import { TranslateTextBackendApiService } from './translate-text-backend-api.service'; describe('TranslateTextBackendApiService', () => { let translateTextBackendApiService: TranslateTextBackendApiService; let httpTestingController: HttpTestingController; const getTranslatableItem = (text: string) => { return { data_format: 'html', content: text, content_type: 'content', interaction_id: null, rule_type: null }; }; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); httpTestingController = TestBed.inject(HttpTestingController); translateTextBackendApiService = TestBed.inject( TranslateTextBackendApiService); }); afterEach(() => { httpTestingController.verify(); }); describe('getTranslatableTextsAsync', () => { let successHandler: jasmine.Spy<jasmine.Func>; let failHandler: (error: HttpErrorResponse) => void; it('should correctly request translatable texts for a given exploration ' + 'id and language code', fakeAsync(() => { successHandler = jasmine.createSpy('success'); failHandler = jasmine.createSpy('error'); const sampleDataResults = { state_names_to_content_id_mapping: { stateName1: { contentId1: getTranslatableItem('text1'), contentId2: getTranslatableItem('text2') }, stateName2: {contentId3: getTranslatableItem('text3')} }, version: '1' }; translateTextBackendApiService.getTranslatableTextsAsync('1', 'en').then( successHandler, failHandler ); const req = httpTestingController.expectOne( '/gettranslatabletexthandler?exp_id=1&language_code=en'); expect(req.request.method).toEqual('GET'); req.flush(sampleDataResults); flushMicrotasks(); expect(successHandler).toHaveBeenCalledWith( TranslatableTexts.createFromBackendDict(sampleDataResults)); })); it('should call the failHandler on error response', fakeAsync(() => { const errorEvent = new ErrorEvent('error'); failHandler = (error: HttpErrorResponse) => { expect(error.error).toBe(errorEvent); }; translateTextBackendApiService.getTranslatableTextsAsync('1', 'en').then( successHandler, failHandler ); const req = httpTestingController.expectOne( '/gettranslatabletexthandler?exp_id=1&language_code=en'); expect(req.request.method).toEqual('GET'); req.error(errorEvent); flushMicrotasks(); })); }); describe('suggestTranslatedTextAsync', () => { class MockReaderObject { result = 'data:image/png;base64,imageBlob1'; onload: () => string; constructor() { this.onload = () => { return 'Fake onload executed'; }; } readAsDataURL(file: Blob) { this.onload(); return 'The file is loaded'; } } let successHandler: jasmine.Spy<jasmine.Func>; let failHandler: (error: HttpErrorResponse) => void; let imagesData: ImagesData[]; beforeEach(() => { successHandler = jasmine.createSpy('success'); failHandler = jasmine.createSpy('error'); imagesData = [{ filename: 'imageFilename', imageBlob: new Blob(['imageBlob1'], {type: 'image'}) }]; }); it('should correctly submit a translation suggestion', fakeAsync(() => { // This throws "Argument of type 'mockReaderObject' is not assignable to // parameter of type 'HTMLImageElement'.". We need to suppress this // error because 'HTMLImageElement' has around 250 more properties. // We have only defined the properties we need in 'mockReaderObject'. // @ts-expect-error spyOn(window, 'FileReader').and.returnValue(new MockReaderObject()); const expectedPayload = { suggestion_type: 'translate_content', target_type: 'exploration', description: 'Adds translation', target_id: 'activeExpId', target_version_at_submission: 'activeExpVersion', change: { cmd: 'add_written_translation', content_id: 'activeContentId', state_name: 'activeStateName', language_code: 'languageCode', content_html: 'contentHtml', translation_html: 'translationHtml', data_format: 'html' }, files: { imageFilename: 'imageBlob1' } }; translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html').then(successHandler, failHandler); flushMicrotasks(); const req = httpTestingController.expectOne( '/suggestionhandler/'); expect(req.request.method).toEqual('POST'); expect(req.request.body.getAll('payload')[0]).toEqual( JSON.stringify(expectedPayload)); req.flush({}); flushMicrotasks(); expect(successHandler).toHaveBeenCalled(); })); it('should append image data to form data', fakeAsync(() => { spyOn(translateTextBackendApiService, 'blobtoBase64').and.returnValue( Promise.resolve('imageBlob')); translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html').then(successHandler, failHandler); flushMicrotasks(); const req = httpTestingController.expectOne( '/suggestionhandler/'); const files = JSON.parse(req.request.body.getAll('payload')[0]).files; const images = Object.values(files); expect(req.request.method).toEqual('POST'); expect(images).toContain('imageBlob'); req.flush({}); flushMicrotasks(); expect(successHandler).toHaveBeenCalled(); })); it('should handle multiple image blobs per filename', fakeAsync(() => { imagesData = [{ filename: 'imageFilename1', imageBlob: { size: 0, type: 'imageBlob1' } as Blob }, { filename: 'imageFilename1', imageBlob: { size: 0, type: 'imageBlob2' } as Blob }, { filename: 'imageFilename2', imageBlob: { size: 0, type: 'imageBlob1' } as Blob }, { filename: 'imageFilename2', imageBlob: { size: 0, type: 'imageBlob2' } as Blob }]; spyOn(translateTextBackendApiService, 'blobtoBase64').and.returnValue( Promise.resolve(['imageBlob1', 'imageBlob2']) ); translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html').then(successHandler, failHandler); flushMicrotasks(); const req = httpTestingController.expectOne( '/suggestionhandler/'); expect(req.request.method).toEqual('POST'); const files = JSON.parse(req.request.body.getAll('payload')[0]).files; const filename1Blobs = files.imageFilename1[0]; const filename2Blobs = files.imageFilename2[0]; const filename3Blobs = files.imageFilename1[1]; const filename4Blobs = files.imageFilename2[1]; expect(filename1Blobs).toContain('imageBlob1'); expect(filename2Blobs).toContain('imageBlob1'); expect(filename3Blobs).toContain('imageBlob2'); expect(filename4Blobs).toContain('imageBlob2'); req.flush({}); flushMicrotasks(); expect(successHandler).toHaveBeenCalled(); })); it('should call the failhandler on error response', fakeAsync(() => { const errorEvent = new ErrorEvent('error'); failHandler = (error: HttpErrorResponse) => { expect(error.error).toBe(errorEvent); }; spyOn(translateTextBackendApiService, 'blobtoBase64').and.returnValue( Promise.resolve('imageBlob')); translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html').then(successHandler, failHandler); flushMicrotasks(); const req = httpTestingController.expectOne( '/suggestionhandler/'); expect(req.request.method).toEqual('POST'); req.error(errorEvent); flushMicrotasks(); })); it('should throw error if Image Data is not present in' + ' local Storage', async() => { imagesData = [{ filename: 'imageFilename1', imageBlob: null }]; await expectAsync( translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html') ).toBeRejectedWithError('No image data found'); }); it('should throw error if prefix is invalid', async() => { imagesData = [{ filename: 'imageFilename1', imageBlob: new Blob(['data:random/xyz;base64,Blob1'], {type: 'image'}) }]; await expectAsync( translateTextBackendApiService.suggestTranslatedTextAsync( 'activeExpId', 'activeExpVersion', 'activeContentId', 'activeStateName', 'languageCode', 'contentHtml', 'translationHtml', imagesData, 'html') ).toBeRejectedWithError('No valid prefix found in data url'); }); }); });
the_stack
import type {EChartOption, ECharts, EChartsConvertFinder} from 'echarts'; import type {HistogramData, OffsetData, OverlayData, OverlayDataItem} from '~/resource/histogram'; import LineChart, {LineChartRef} from '~/components/LineChart'; import {Modes, options as chartOptions} from '~/resource/histogram'; import React, {FunctionComponent, useCallback, useEffect, useMemo, useRef, useState} from 'react'; import StackChart, {StackChartProps, StackChartRef} from '~/components/StackChart'; import {rem, size} from '~/utils/style'; import Chart from '~/components/Chart'; import {Chart as ChartLoader} from '~/components/Loader/ChartPage'; import ChartToolbox from '~/components/ChartToolbox'; import type {Run} from '~/types'; import {distance} from '~/utils'; import {format} from 'd3-format'; import minBy from 'lodash/minBy'; import queryString from 'query-string'; import styled from 'styled-components'; import {useRunningRequest} from '~/hooks/useRequest'; import useThrottleFn from '~/hooks/useThrottleFn'; import {useTranslation} from 'react-i18next'; import useWebAssembly from '~/hooks/useWebAssembly'; const formatTooltipXValue = format('.4f'); const formatTooltipYValue = format('.4'); const Wrapper = styled.div` ${size('100%', '100%')} display: flex; flex-direction: column; align-items: stretch; justify-content: space-between; `; const StyledLineChart = styled(LineChart)` flex-grow: 1; `; const StyledStackChart = styled(StackChart)` flex-grow: 1; `; const Toolbox = styled(ChartToolbox)` margin-left: ${rem(20)}; margin-right: ${rem(20)}; margin-bottom: ${rem(18)}; `; const Error = styled.div` ${size('100%', '100%')} display: flex; justify-content: center; align-items: center; `; const chartSize = { width: 430, height: 337 }; const chartSizeInRem = { width: rem(chartSize.width), height: rem(chartSize.height) }; type HistogramChartProps = { run: Run; tag: string; mode: Modes; running?: boolean; }; const HistogramChart: FunctionComponent<HistogramChartProps> = ({run, tag, mode, running}) => { const {t} = useTranslation(['histogram', 'common']); const echart = useRef<LineChartRef | StackChartRef>(null); const { data: dataset, error, loading } = useRunningRequest<HistogramData>(`/histogram/list?${queryString.stringify({run: run.label, tag})}`, !!running, { refreshInterval: 60 * 1000 }); const [maximized, setMaximized] = useState<boolean>(false); const title = useMemo(() => `${tag} (${run.label})`, [tag, run.label]); const params = useMemo(() => [dataset ?? [], mode], [dataset, mode]); const {data} = useWebAssembly<OffsetData | OverlayData>('histogram_transform', params); const [highlight, setHighlight] = useState<number | null>(null); useEffect(() => setHighlight(null), [mode]); const chartData = useMemo(() => { type Optional<T> = T | undefined; if (mode === Modes.Overlay) { return (data as Optional<OverlayData>)?.data.map((items, index) => ({ name: `${t('common:time-mode.step')}${items[0][1]}`, data: items, lineStyle: { color: run.colors[index === highlight || highlight == null ? 0 : 1] }, z: index === highlight ? data?.data.length : index, encode: { x: [2], y: [3] } })); } if (mode === Modes.Offset) { const offset = data as Optional<OffsetData>; return { minX: offset?.minX, maxX: offset?.maxX, minY: offset?.minStep, maxY: offset?.maxStep, minZ: offset?.minZ, maxZ: offset?.maxZ, data: offset?.data ?? [] }; } return null as never; }, [data, mode, run, highlight, t]); const formatter = useMemo( () => ({ [Modes.Overlay]: (params: EChartOption.Tooltip.Format | EChartOption.Tooltip.Format[]) => { if (!data || highlight == null) { return ''; } const series = (params as EChartOption.Tooltip.Format[]).find( s => s.data[1] === (data as OverlayData).data[highlight][0][1] ); return series?.seriesName ?? ''; }, [Modes.Offset]: (dot: [number, number, number]) => dot[2] }), [highlight, data] ); const pointerFormatter = useMemo( () => ({ [Modes.Overlay]: (params: {value: number; axisDimension: 'x' | 'y'}) => { if (params.axisDimension === 'x') { return formatTooltipXValue(params.value); } if (params.axisDimension === 'y') { return formatTooltipYValue(params.value); } return '' as never; }, [Modes.Offset]: (params: {axisDimension: 'x' | 'y'}, dot: [number, number, number]) => { if (params.axisDimension === 'x') { return formatTooltipXValue(dot?.[0]); } if (params.axisDimension === 'y') { return formatTooltipYValue(dot?.[1]); } return '' as never; } }), [] ); const options = useMemo( () => ({ ...chartOptions[mode], color: [run.colors[0]], tooltip: { formatter: formatter[mode] }, axisPointer: { label: { formatter: pointerFormatter[mode] } }, xAxis: { axisPointer: { snap: mode === Modes.Overlay }, splitLine: { show: false } }, yAxis: { axisPointer: { snap: mode === Modes.Overlay } } }), [mode, run, formatter, pointerFormatter] ); const mousemove = useCallback((echarts: ECharts, {offsetX, offsetY}: {offsetX: number; offsetY: number}) => { const series = echarts.getOption().series; const pt: [number, number] = [offsetX, offsetY]; if (series) { type Distance = number; type Index = number; const npts: [number, number, Distance, Index][] = series.map((s, i) => (s.data as OverlayDataItem[])?.reduce( (m, [, , x, y]) => { const px = echarts.convertToPixel('grid' as EChartsConvertFinder, [x, y]) as [number, number]; const d = distance(px, pt); if (d < m[2]) { return [x, y, d, i]; } return m; }, [0, 0, Number.POSITIVE_INFINITY, i] ) ); const npt = minBy(npts, p => p[2]); setHighlight(npt?.[3] ?? null); return; } }, []); const throttled = useThrottleFn(mousemove, {wait: 200}); const onInit = useCallback( (echarts: ECharts) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const zr = (echarts as any).getZr(); if (zr) { zr.on('mousemove', (e: {offsetX: number; offsetY: number}) => throttled.run(echarts, e)); zr.on('mouseout', () => { throttled.cancel(); setHighlight(null); }); } }, [throttled] ); const chart = useMemo(() => { if (mode === Modes.Overlay) { return ( <StyledLineChart ref={echart as React.RefObject<LineChartRef>} title={title} data={chartData as EChartOption<EChartOption.SeriesLine>['series']} options={options as EChartOption} loading={loading} onInit={onInit} /> ); } if (mode === Modes.Offset) { return ( <StyledStackChart ref={echart as React.RefObject<StackChartRef>} title={title} data={chartData as StackChartProps['data']} options={options as EChartOption} loading={loading} /> ); } return null; }, [chartData, loading, mode, options, title, onInit]); // display error only on first fetch if (!data && error) { return <Error>{t('common:error')}</Error>; } return ( <Chart maximized={maximized} {...chartSizeInRem}> <Wrapper> {chart} <Toolbox items={[ { icon: 'maximize', activeIcon: 'minimize', tooltip: t('common:maximize'), activeTooltip: t('common:minimize'), toggle: true, onClick: () => setMaximized(m => !m) }, { icon: 'download', tooltip: t('common:download-image'), onClick: () => echart.current?.saveAsImage() } ]} /> </Wrapper> </Chart> ); }; export default HistogramChart; export const Loader: FunctionComponent = () => ( <> <Chart {...chartSizeInRem}> <ChartLoader width={chartSize.width - 2} height={chartSize.height - 2} /> </Chart> <Chart {...chartSizeInRem}> <ChartLoader width={chartSize.width - 2} height={chartSize.height - 2} /> </Chart> </> );
the_stack
import React, { useEffect, useRef, useContext, // useLayoutEffect } from 'react'; // import equal from 'fast-deep-equal'; // import { SongContext } from './Song'; import { TrackContext } from './Track'; import Tone from '../lib/tone'; import { usePrevious } from '../lib/hooks'; // import { MidiNote } from '../types/midi-notes'; type NoteType = { name: string; velocity?: number; duration?: number | string; /** Use unique key to differentiate from same notes, otherwise it won't play */ key?: string | number; }; export type InstrumentType = | 'amSynth' | 'duoSynth' | 'fmSynth' | 'membraneSynth' | 'metalSynth' | 'monoSynth' | 'noiseSynth' | 'pluckSynth' | 'synth' | 'sampler'; export interface InstrumentProps { type: InstrumentType; notes?: NoteType[]; /** Should deprecate */ options?: any; polyphony?: number; oscillator?: { type: 'triangle' | 'sine' | 'square'; }; envelope?: { attack?: number; decay?: number; sustain?: number; release?: number; }; samples?: { [k: string]: string; }; // TODO: Add in next version // samples?: { // [key in MidiNote]?: string; // }; mute?: boolean; solo?: boolean; /** TODO: Type properly and consider loading status */ onLoad?: (buffers: any[]) => void; } interface InstrumentConsumerProps extends InstrumentProps { volume?: number; pan?: number; effectsChain?: React.ReactNode[]; onInstrumentsUpdate?: Function; } const InstrumentConsumer: React.FC<InstrumentConsumerProps> = ({ // <Instrument /> Props type = 'synth', options, polyphony = 4, oscillator, envelope, notes = [], samples, onLoad, // <Track /> Props volume, pan, mute, solo, effectsChain, onInstrumentsUpdate, }) => { const instrumentRef = useRef< Partial<{ curve: number; release: number; triggerAttack: Function; triggerAttackRelease: Function; triggerRelease: Function; add: Function; set: Function; chain: Function; dispose: Function; disconnect: Function; }> >(); // const trackChannelBase = useRef(new Tone.PanVol(pan, volume)); // const trackChannelBase = useRef(new Tone.Channel(volume, pan)); const trackChannelBase = useRef(null); const prevNotes: any[] = usePrevious(notes); // ------------------------------------------------------------------------- // CHANNEL // TODO: Consider moving this to <Track> // ------------------------------------------------------------------------- useEffect(() => { trackChannelBase.current = new Tone.Channel(volume, pan); return function cleanup() { if (trackChannelBase.current) { trackChannelBase.current.dispose(); } }; /* eslint-disable-next-line */ }, []); // ------------------------------------------------------------------------- // INSTRUMENT TYPE // ------------------------------------------------------------------------- const prevType = usePrevious<InstrumentType>(type); useEffect(() => { if (type === 'sampler') { instrumentRef.current = new Tone.Sampler(samples, onLoad); if (options && options.curve) { instrumentRef.current.curve = options.curve; } if (options && options.release) { instrumentRef.current.release = options.release; } } else if (type === 'membraneSynth') { instrumentRef.current = new Tone.MembraneSynth( buildSynthOptions({ oscillator, envelope, }), ); } else if (type === 'metalSynth') { instrumentRef.current = new Tone.MetalSynth(); } else if (type === 'noiseSynth') { instrumentRef.current = new Tone.NoiseSynth(); } else if (type === 'pluckSynth') { instrumentRef.current = new Tone.PluckSynth(); } else { let synth; if (type === 'amSynth') { synth = Tone.AMSynth; } else if (type === 'duoSynth') { synth = Tone.DuoSynth; } else if (type === 'fmSynth') { synth = Tone.FMSynth; } else if (type === 'monoSynth') { synth = Tone.MonoSynth; } else if (type === 'synth') { synth = Tone.Synth; } else { synth = Tone.Synth; } /** * PolySynth accepts other Synth types as second param, making them * polyphonic. As this is a common use case, all Synths will be created * via PolySynth. Monophonic synths can easily be created by setting the * `polyphony` prop to 1. */ instrumentRef.current = new Tone.PolySynth( polyphony, synth, buildSynthOptions({ oscillator, envelope, }), ); } instrumentRef.current.chain( ...effectsChain, trackChannelBase.current, Tone.Master, ); // Add this Instrument to Track Context onInstrumentsUpdate([instrumentRef.current]); return function cleanup() { if (instrumentRef.current) { instrumentRef.current.dispose(); } }; /* eslint-disable-next-line */ }, [type, polyphony]); useEffect(() => { if ( // TODO: Add other synth types type === 'synth' && instrumentRef && instrumentRef.current && oscillator ) { instrumentRef.current.set('oscillator', oscillator); // console.log(oscillator); } }, [oscillator, type]); // ------------------------------------------------------------------------- // VOLUME / PAN / MUTE / SOLO // ------------------------------------------------------------------------- useEffect(() => { trackChannelBase.current.volume.value = volume; }, [volume]); useEffect(() => { trackChannelBase.current.pan.value = pan; }, [pan]); useEffect(() => { trackChannelBase.current.mute = mute; }, [mute]); useEffect(() => { trackChannelBase.current.solo = solo; }, [solo]); // ------------------------------------------------------------------------- // NOTES // ------------------------------------------------------------------------- /** NOTE: Would prefer to use useLayoutEffect as it is a little faster, but unable to test it right now **/ useEffect(() => { // Loop through all current notes notes && notes.forEach((note) => { // Check if note is playing const isPlaying = prevNotes && prevNotes.filter((prevNote) => { // Check both note name and unique key. // Key helps differentiate same notes, otherwise it won't trigger return prevNote.name === note.name && prevNote.key === note.key; }).length > 0; // Only play note is it isn't already playing if (!isPlaying) { if (note.duration) { instrumentRef.current.triggerAttackRelease( note.name, note.duration, undefined, note.velocity, ); } else { instrumentRef.current.triggerAttack( note.name, undefined, note.velocity, ); } } }); // Loop through all previous notes prevNotes && prevNotes.forEach((note) => { // Check if note is still playing const isPlaying = notes && notes.filter((n) => n.name === note.name).length > 0; if (!isPlaying) { instrumentRef.current.triggerRelease(note.name); } }); }, [notes, prevNotes]); // ------------------------------------------------------------------------- // EFFECTS CHAIN // ------------------------------------------------------------------------- useEffect(() => { // NOTE: Using trackChannelBase causes effects to not turn off instrumentRef.current.disconnect(); instrumentRef.current.chain( ...effectsChain, trackChannelBase.current, Tone.Master, ); }, [effectsChain]); // ------------------------------------------------------------------------- // SAMPLES // Run whenever `samples` change, using Tone.Sampler's `add` method to load // more samples after initial mount // TODO: Check if first mount, as sampler constructor has already loaded samples // ------------------------------------------------------------------------- const prevSamples = usePrevious(samples); useEffect(() => { // When sampler is initiated, it already loads samples. // We'll use !isFirstSamplerInit to skip adding samples if sampler has been // initiated in this render. const isFirstSamplerInit = type === 'sampler' && prevType !== type; if (type === 'sampler' && Boolean(samples) && !isFirstSamplerInit) { // const isEqual = equal(samples, prevSamples); const prevSampleKeys = Object.keys(prevSamples); const sampleKeys = Object.keys(samples); // Samples to add const addSampleKeys = sampleKeys.filter( (key) => !prevSampleKeys.includes(key), ); // Samples to remove // const removeSampleKeys = prevSampleKeys.filter( // (key) => !sampleKeys.includes(key), // ); // console.log(addSampleKeys, removeSampleKeys); if (addSampleKeys.length) { // Create an array of promises from `samples` const loadSamplePromises = addSampleKeys.map((key) => { return new Promise((resolve: (buffer: any) => void) => { const sample = samples[key]; const prevSample = prevSamples ? (prevSamples as object)[key] : ''; // Only update sample if different than before if (sample !== prevSample) { // Pass `resolve` to `onLoad` parameter of Tone.Sampler // When sample loads, this promise will resolve instrumentRef.current.add(key, sample, resolve); } else { resolve(null); } }); }); // Once all promises in array resolve, run onLoad callback Promise.all(loadSamplePromises).then((event) => { if (typeof onLoad === 'function') { onLoad(event); } }); // TODO: Work out a way to remove samples. Below doesn't work // removeSampleKeys.forEach((key) => { // instrumentRef.current.add(key, null); // }); } } /* eslint-disable-next-line */ }, [samples, type]); return null; }; const Instrument: React.FC<InstrumentProps> = ({ type, options, notes, polyphony, oscillator, envelope, samples, onLoad, }) => { const { volume, pan, mute, solo, effectsChain, onInstrumentsUpdate, } = useContext(TrackContext); if (typeof window === 'undefined') { return null; } return ( <InstrumentConsumer // <Instrument /> Props type={type} options={options} notes={notes} polyphony={polyphony} oscillator={oscillator} envelope={envelope} samples={samples} onLoad={onLoad} // <Track /> Props volume={volume} pan={pan} mute={mute} solo={solo} effectsChain={effectsChain} onInstrumentsUpdate={onInstrumentsUpdate} /> ); }; /** * Use Instrument's flattened synth props to create options object for Tone JS */ const buildSynthOptions = ({ oscillator, envelope }) => { if (oscillator || envelope) { return { ...(envelope ? { envelope } : {}), ...(oscillator ? { oscillator } : {}), }; } return undefined; }; export default Instrument;
the_stack
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import '../settings_shared_css.js'; import 'chrome://resources/cr_elements/icons.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import 'chrome://resources/polymer/v3_0/iron-list/iron-list.js'; import 'chrome://resources/polymer/v3_0/paper-spinner/paper-spinner-lite.js'; import '../i18n_setup.js'; import '../route.js'; import '../prefs/prefs.js'; import './password_check_edit_dialog.js'; import './password_check_edit_disclaimer_dialog.js'; import './password_check_list_item.js'; import './password_remove_confirmation_dialog.js'; // <if expr="chromeos_ash or chromeos_lacros"> import '../controls/password_prompt_dialog.js'; // </if> import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {assert, assertNotReached} from 'chrome://resources/js/assert.m.js'; import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js'; import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {getDeepActiveElement} from 'chrome://resources/js/util.m.js'; // </if> import {WebUIListenerMixin, WebUIListenerMixinInterface} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {loadTimeData} from '../i18n_setup.js'; // </if> import {StoredAccount, SyncBrowserProxyImpl, SyncPrefs, SyncStatus} from '../people_page/sync_browser_proxy.js'; import {PrefsMixin, PrefsMixinInterface} from '../prefs/prefs_mixin.js'; import {routes} from '../route.js'; import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {BlockingRequestManager} from './blocking_request_manager.js'; // </if> import {PasswordCheckListItemElement} from './password_check_list_item.js'; import {PasswordCheckMixin, PasswordCheckMixinInterface} from './password_check_mixin.js'; import {PasswordCheckInteraction, SavedPasswordListChangedListener} from './password_manager_proxy.js'; const CheckState = chrome.passwordsPrivate.PasswordCheckState; interface SettingsPasswordCheckElement { $: { moreActionsMenu: CrActionMenuElement, }; } const SettingsPasswordCheckElementBase = RouteObserverMixin(WebUIListenerMixin( I18nMixin(PrefsMixin(PasswordCheckMixin((PolymerElement)))))) as { new (): PolymerElement & I18nMixinInterface & WebUIListenerMixinInterface & PrefsMixinInterface & PasswordCheckMixinInterface & RouteObserverMixinInterface }; class SettingsPasswordCheckElement extends SettingsPasswordCheckElementBase { static get is() { return 'settings-password-check'; } static get template() { return html`{__html_template__}`; } static get properties() { return { storedAccounts_: Array, title_: { type: String, computed: 'computeTitle_(status, canUsePasswordCheckup_)', }, isSignedOut_: { type: Boolean, computed: 'computeIsSignedOut_(syncStatus_, storedAccounts_)', }, isSyncingPasswords_: { type: Boolean, computed: 'computeIsSyncingPasswords_(syncPrefs_, syncStatus_)', }, canUsePasswordCheckup_: { type: Boolean, computed: 'computeCanUsePasswordCheckup_(syncPrefs_, syncStatus_)', }, isButtonHidden_: { type: Boolean, computed: 'computeIsButtonHidden_(status, isSignedOut_, isInitialStatus)', }, syncPrefs_: Object, syncStatus_: Object, showPasswordEditDialog_: Boolean, showPasswordRemoveDialog_: Boolean, showPasswordEditDisclaimer_: Boolean, /** * The password that the user is interacting with now. */ activePassword_: Object, showCompromisedCredentialsBody_: { type: Boolean, computed: 'computeShowCompromisedCredentialsBody_(' + 'isSignedOut_, leakedPasswords)', }, showNoCompromisedPasswordsLabel_: { type: Boolean, computed: 'computeShowNoCompromisedPasswordsLabel_(' + 'syncStatus_, prefs.*, status, leakedPasswords)', }, showHideMenuTitle_: { type: String, computed: 'computeShowHideMenuTitle(activePassword_)', }, iconHaloClass_: { type: String, computed: 'computeIconHaloClass_(' + 'status, isSignedOut_, leakedPasswords, weakPasswords)', }, /** * The ids of insecure credentials for which user clicked "Change * Password" button */ clickedChangePasswordIds_: { type: Object, value: new Set(), }, // <if expr="chromeos_ash or chromeos_lacros"> showPasswordPromptDialog_: Boolean, tokenRequestManager_: Object, // </if> }; } private storedAccounts_: Array<StoredAccount>; private title_: string; private isSignedOut_: boolean; private isSyncingPasswords_: boolean; private canUsePasswordCheckup_: boolean; private isButtonHidden_: boolean; private syncPrefs_: SyncPrefs; private syncStatus_: SyncStatus; private showPasswordEditDialog_: boolean; private showPasswordRemoveDialog_: boolean; private showPasswordEditDisclaimer_: boolean; private activePassword_: chrome.passwordsPrivate.InsecureCredential|null; private showCompromisedCredentialsBody_: boolean; private showNoCompromisedPasswordsLabel_: boolean; private showHideMenuTitle_: string; private iconHaloClass_: string; private clickedChangePasswordIds_: Set<number>; // <if expr="chromeos_ash or chromeos_lacros"> private showPasswordPromptDialog_: boolean; private tokenRequestManager_: BlockingRequestManager; // </if> private activeDialogAnchorStack_: Array<HTMLElement>|null; private activeListItem_: PasswordCheckListItemElement|null; startCheckAutomaticallySucceeded: boolean = false; private setSavedPasswordsListener_: SavedPasswordListChangedListener|null; constructor() { super(); /** * A stack of the elements that triggered dialog to open and should * therefore receive focus when that dialog is closed. The bottom of the * stack is the element that triggered the earliest open dialog and top of * the stack is the element that triggered the most recent (i.e. active) * dialog. If no dialog is open, the stack is empty. */ this.activeDialogAnchorStack_ = null; /** * The password_check_list_item that the user is interacting with now. */ this.activeListItem_ = null; /** * Observer for saved passwords to update startCheckAutomaticallySucceeded * once they are changed. It's needed to run password check on navigation * again once passwords changed. */ this.setSavedPasswordsListener_ = null; } connectedCallback() { super.connectedCallback(); // <if expr="chromeos_ash or chromeos_lacros"> // If the user's account supports the password check, an auth token will be // required in order for them to view or export passwords. Otherwise there // is no additional security so |tokenRequestManager_| will immediately // resolve requests. this.tokenRequestManager_ = loadTimeData.getBoolean('userCannotManuallyEnterPassword') ? new BlockingRequestManager() : new BlockingRequestManager(() => this.openPasswordPromptDialog_()); // </if> this.activeDialogAnchorStack_ = []; const setSavedPasswordsListener: SavedPasswordListChangedListener = _list => { this.startCheckAutomaticallySucceeded = false; }; this.setSavedPasswordsListener_ = setSavedPasswordsListener; this.passwordManager!.addSavedPasswordListChangedListener( setSavedPasswordsListener); // Set the manager. These can be overridden by tests. const syncBrowserProxy = SyncBrowserProxyImpl.getInstance(); const syncStatusChanged = (syncStatus: SyncStatus) => this.syncStatus_ = syncStatus; const syncPrefsChanged = (syncPrefs: SyncPrefs) => this.syncPrefs_ = syncPrefs; // Listen for changes. this.addWebUIListener('sync-status-changed', syncStatusChanged); this.addWebUIListener('sync-prefs-changed', syncPrefsChanged); // Request initial data. syncBrowserProxy.getSyncStatus().then(syncStatusChanged); syncBrowserProxy.sendSyncPrefsChanged(); // For non-ChromeOS, also check whether accounts are available. // <if expr="not (chromeos_ash or chromeos_lacros)"> const storedAccountsChanged = (accounts: Array<StoredAccount>) => this.storedAccounts_ = accounts; syncBrowserProxy.getStoredAccounts().then(storedAccountsChanged); this.addWebUIListener('stored-accounts-updated', storedAccountsChanged); // </if> } disconnectedCallback() { super.disconnectedCallback(); this.passwordManager!.removeSavedPasswordListChangedListener( assert(this.setSavedPasswordsListener_!)); this.setSavedPasswordsListener_ = null; } /** * Tries to start bulk password check on page open if instructed to do so and * didn't start successfully before */ currentRouteChanged(currentRoute: Route) { const router = Router.getInstance(); if (currentRoute.path === routes.CHECK_PASSWORDS.path && !this.startCheckAutomaticallySucceeded && router.getQueryParameters().get('start') === 'true') { this.passwordManager!.recordPasswordCheckInteraction( PasswordCheckInteraction.START_CHECK_AUTOMATICALLY); this.passwordManager!.startBulkPasswordCheck().then( () => { this.startCheckAutomaticallySucceeded = true; }, _error => { // Catching error }); } // Requesting status on navigation to update elapsedTimeSinceLastCheck this.passwordManager!.getPasswordCheckStatus().then( status => this.status = status); } /** * Start/Stop bulk password check. */ private onPasswordCheckButtonClick_() { switch (this.status.state) { case CheckState.RUNNING: this.passwordManager!.recordPasswordCheckInteraction( PasswordCheckInteraction.STOP_CHECK); this.passwordManager!.stopBulkPasswordCheck(); return; case CheckState.IDLE: case CheckState.CANCELED: case CheckState.OFFLINE: case CheckState.OTHER_ERROR: this.passwordManager!.recordPasswordCheckInteraction( PasswordCheckInteraction.START_CHECK_MANUALLY); this.passwordManager!.startBulkPasswordCheck(); return; case CheckState.SIGNED_OUT: // Runs the startBulkPasswordCheck to check passwords for weakness that // works for both sign in and sign out users. this.passwordManager!.recordPasswordCheckInteraction( PasswordCheckInteraction.START_CHECK_MANUALLY); this.passwordManager!.startBulkPasswordCheck().then( () => {}, _error => { // Catching error }); return; case CheckState.NO_PASSWORDS: case CheckState.QUOTA_LIMIT: } assertNotReached( 'Can\'t trigger an action for state: ' + this.status.state); } /** * @return true if there are any compromised credentials. */ private hasLeakedCredentials_(): boolean { return !!this.leakedPasswords.length; } /** * @return true if there are any weak credentials. */ private hasWeakCredentials_(): boolean { return !!this.weakPasswords.length; } /** * @return true if there are any insecure credentials. */ private hasInsecureCredentials_(): boolean { return !!this.leakedPasswords.length || this.hasWeakCredentials_(); } /** * @return A relevant help text for weak passwords. Contains a link that * depends on whether the user is syncing passwords or not. */ private getWeakPasswordsHelpText_(): string { return this.i18nAdvanced( this.isSyncingPasswords_ ? 'weakPasswordsDescriptionGeneration' : 'weakPasswordsDescription'); } private onMoreActionsClick_( event: CustomEvent<{moreActionsButton: HTMLElement}>) { const target = event.detail.moreActionsButton; this.$.moreActionsMenu.showAt(target); this.activeDialogAnchorStack_!.push(target); this.activeListItem_ = event.target as PasswordCheckListItemElement; this.activePassword_ = this.activeListItem_!.item; } private onMenuShowPasswordClick_() { this.activePassword_!.password ? this.activeListItem_!.hidePassword() : this.activeListItem_!.showPassword(); this.$.moreActionsMenu.close(); this.activePassword_ = null; this.activeDialogAnchorStack_!.pop(); } private onEditPasswordClick_() { this.passwordManager! .getPlaintextInsecurePassword( assert(this.activePassword_!), chrome.passwordsPrivate.PlaintextReason.EDIT) .then( insecureCredential => { this.activePassword_ = insecureCredential; this.showPasswordEditDialog_ = true; }, _error => { // <if expr="chromeos_ash or chromeos_lacros"> // If no password was found, refresh auth token and retry. this.tokenRequestManager_.request( () => this.onEditPasswordClick_()); // </if> // <if expr="not (chromeos_ash or chromeos_lacros)"> this.activePassword_ = null; this.onPasswordEditDialogClosed_(); // </if> }); this.$.moreActionsMenu.close(); } private onMenuRemovePasswordClick_() { this.$.moreActionsMenu.close(); this.showPasswordRemoveDialog_ = true; } private onPasswordRemoveDialogClosed_() { this.showPasswordRemoveDialog_ = false; focusWithoutInk(assert(this.activeDialogAnchorStack_!.pop()!)); } private onPasswordEditDialogClosed_() { this.showPasswordEditDialog_ = false; focusWithoutInk(assert(this.activeDialogAnchorStack_!.pop()!)); } private onAlreadyChangedClick_(event: CustomEvent<HTMLElement>) { const target = event.detail; // Setting required properties for Password Check Edit dialog this.activeDialogAnchorStack_!.push(target); this.activeListItem_ = event.target as PasswordCheckListItemElement; this.activePassword_ = this.activeListItem_.item; this.showPasswordEditDisclaimer_ = true; } private onEditDisclaimerClosed_() { this.showPasswordEditDisclaimer_ = false; focusWithoutInk(assert(this.activeDialogAnchorStack_!.pop()!)); } private computeShowHideMenuTitle(): string { return this.i18n( this.activeListItem_!.isPasswordVisible ? 'hideCompromisedPassword' : 'showCompromisedPassword'); } private computeIconHaloClass_(): string { return !this.isCheckInProgress_() && this.hasLeakedCredentials_() ? 'warning-halo' : ''; } /** * @return the icon (warning, info or error) indicating the check status. */ private getStatusIcon_(): string { if (!this.hasInsecureCredentialsOrErrors_()) { return 'settings:check-circle'; } if (this.hasLeakedCredentials_()) { return 'cr:warning'; } return 'cr:info'; } /** * @return the CSS class used to style the icon (warning, info or error). */ private getStatusIconClass_(): string { if (!this.hasInsecureCredentialsOrErrors_()) { return this.waitsForFirstCheck_() ? 'hidden' : 'no-security-issues'; } if (this.hasLeakedCredentials_()) { return 'has-security-issues'; } return ''; } /** * @return the title message indicating the state of the last/ongoing check. */ private computeTitle_(): string { switch (this.status.state) { case CheckState.IDLE: return this.waitsForFirstCheck_() ? '' : this.i18n('checkedPasswords'); case CheckState.CANCELED: return this.i18n('checkPasswordsCanceled'); case CheckState.RUNNING: // Returns the progress of a running check. Ensures that both numbers // are at least 1. const alreadyProcessed = this.status.alreadyProcessed || 0; return this.i18n( 'checkPasswordsProgress', alreadyProcessed + 1, Math.max(this.status.remainingInQueue! + alreadyProcessed, 1)); case CheckState.OFFLINE: return this.i18n('checkPasswordsErrorOffline'); case CheckState.SIGNED_OUT: // When user is signed out we run the password weakness check. Since it // works very fast, we always shows "Checked passwords" in this case. return this.i18n('checkedPasswords'); case CheckState.NO_PASSWORDS: return this.i18n('checkPasswordsErrorNoPasswords'); case CheckState.QUOTA_LIMIT: // Note: For the checkup case we embed the link as HTML, thus we need to // use i18nAdvanced() here as well as the `inner-h-t-m-l` attribute in // the DOM. return this.canUsePasswordCheckup_ ? this.i18nAdvanced('checkPasswordsErrorQuotaGoogleAccount') : this.i18n('checkPasswordsErrorQuota'); case CheckState.OTHER_ERROR: return this.i18n('checkPasswordsErrorGeneric'); } assertNotReached('Can\'t find a title for state: ' + this.status.state); } /** * @return true iff a check is running right according to the given |status|. */ private isCheckInProgress_(): boolean { return this.status.state === CheckState.RUNNING; } /** * @return true to show the timestamp when a check was completed successfully. */ private showsTimestamp_(): boolean { return !!this.status.elapsedTimeSinceLastCheck && (this.status.state === CheckState.IDLE || this.status.state === CheckState.SIGNED_OUT); } /** * @return the button caption indicating it's current functionality. */ private getButtonText_(): string { switch (this.status.state) { case CheckState.IDLE: return this.waitsForFirstCheck_() ? this.i18n('checkPasswords') : this.i18n('checkPasswordsAgain'); case CheckState.CANCELED: return this.i18n('checkPasswordsAgain'); case CheckState.RUNNING: return this.i18n('checkPasswordsStop'); case CheckState.OFFLINE: case CheckState.NO_PASSWORDS: case CheckState.OTHER_ERROR: return this.i18n('checkPasswordsAgainAfterError'); case CheckState.SIGNED_OUT: // We should allow signed out users to click the "Check again" button to // run the passwords weakness check. return this.i18n('checkPasswordsAgain'); case CheckState.QUOTA_LIMIT: return ''; // Undefined behavior. Don't show any misleading text. } assertNotReached( 'Can\'t find a button text for state: ' + this.status.state); } /** * @return 'action-button' only for the very first check. */ private getButtonTypeClass_(): string { return this.waitsForFirstCheck_() ? 'action-button' : ' '; } /** * @return true iff the check/stop button should be visible for a given state. */ private computeIsButtonHidden_(): boolean { switch (this.status.state) { case CheckState.IDLE: return this.isInitialStatus; // Only a native IDLE state allows checks. case CheckState.CANCELED: case CheckState.RUNNING: case CheckState.OFFLINE: case CheckState.OTHER_ERROR: case CheckState.SIGNED_OUT: return false; case CheckState.NO_PASSWORDS: case CheckState.QUOTA_LIMIT: return true; } assertNotReached( 'Can\'t determine button visibility for state: ' + this.status.state); return true; } /** * @return The chrome:// address where the banner image is located. */ private bannerImageSrc_(isDarkMode: boolean): string { const type = (this.status.state === CheckState.IDLE && !this.waitsForFirstCheck_()) ? 'positive' : 'neutral'; const suffix = isDarkMode ? '_dark' : ''; return `chrome://settings/images/password_check_${type}${suffix}.svg`; } /** * @return true iff the banner should be shown. */ private shouldShowBanner_(): boolean { if (this.hasInsecureCredentials_()) { return false; } return this.status.state === CheckState.CANCELED || !this.hasInsecureCredentialsOrErrors_(); } /** * @return true if there are insecure credentials or the status is unexpected * for a regular password check. */ private hasInsecureCredentialsOrErrors_(): boolean { if (this.hasInsecureCredentials_()) { return true; } switch (this.status.state) { case CheckState.IDLE: case CheckState.RUNNING: case CheckState.SIGNED_OUT: return false; case CheckState.CANCELED: case CheckState.OFFLINE: case CheckState.NO_PASSWORDS: case CheckState.QUOTA_LIMIT: case CheckState.OTHER_ERROR: return true; } assertNotReached( 'Not specified whether to state is an error: ' + this.status.state); } /** * @return true if there are insecure credentials or the status is unexpected * for a regular password check. */ private showsPasswordsCount_(): boolean { if (this.hasInsecureCredentials_()) { return true; } switch (this.status.state) { case CheckState.IDLE: return !this.waitsForFirstCheck_(); case CheckState.CANCELED: case CheckState.RUNNING: case CheckState.OFFLINE: case CheckState.NO_PASSWORDS: case CheckState.QUOTA_LIMIT: case CheckState.OTHER_ERROR: return false; case CheckState.SIGNED_OUT: // Shows "No security issues found" if user is signed out and doesn't // have insecure credentials. return true; } assertNotReached( 'Not specified whether to show passwords for state: ' + this.status.state); } /** * @return a localized and pluralized string of the passwords count, depending * on whether the user is signed in and whether other compromised passwords * exist. */ private getPasswordsCount_(): string { return this.isSignedOut_ && this.leakedPasswords.length === 0 ? this.weakPasswordsCount : this.insecurePasswordsCount; } /** * @return the label that should be shown in the compromised password section * if a user is signed out. This label depends on whether the user already had * compromised credentials that were found in the past. */ private getSignedOutUserLabel_(): string { // This label contains the link, thus we need to use i18nAdvanced() here as // well as the `inner-h-t-m-l` attribute in the DOM. return this.i18nAdvanced( this.hasLeakedCredentials_() ? 'signedOutUserHasCompromisedCredentialsLabel' : 'signedOutUserLabel'); } /** * @return true iff the leak or weak check was performed at least once before. */ private waitsForFirstCheck_(): boolean { return !this.status.elapsedTimeSinceLastCheck; } /** * @return true iff the user is signed out. */ private computeIsSignedOut_(): boolean { if (!this.syncStatus_ || !this.syncStatus_.signedIn) { return !this.storedAccounts_ || this.storedAccounts_.length === 0; } return !!this.syncStatus_.hasError; } /** * @return true iff the user is syncing passwords. */ private computeIsSyncingPasswords_(): boolean { return !!this.syncStatus_ && !!this.syncStatus_.signedIn && !this.syncStatus_.hasError && !!this.syncPrefs_ && this.syncPrefs_.passwordsSynced; } /** * @return whether the user can use the online Password Checkup. */ private computeCanUsePasswordCheckup_(): boolean { return !!this.syncStatus_ && !!this.syncStatus_.signedIn && (!this.syncPrefs_ || !this.syncPrefs_.encryptAllData); } private computeShowCompromisedCredentialsBody_(): boolean { // Always shows compromised credetnials section if user is signed out. return this.isSignedOut_ || this.hasLeakedCredentials_(); } private computeShowNoCompromisedPasswordsLabel_(): boolean { // Check if user isn't signed in. if (!this.syncStatus_ || !this.syncStatus_.signedIn) { return false; } // Check if breach detection is turned off in settings. if (!this.prefs || !this.getPref('profile.password_manager_leak_detection').value) { return false; } // Return true if there was a successful check and no compromised passwords // were found. return !this.hasLeakedCredentials_() && this.showsTimestamp_(); } private onChangePasswordClick_(event: CustomEvent<{id: number}>) { this.clickedChangePasswordIds_.add(event.detail.id); this.notifyPath('clickedChangePasswordIds_.size'); } private clickedChangePassword_( item: chrome.passwordsPrivate.InsecureCredential): boolean { return this.clickedChangePasswordIds_.has(item.id); } // <if expr="chromeos_ash or chromeos_lacros"> /** * Copied from passwords_section.js. * TODO(crbug.com/1074228): Extract to a separate behavior * * @param e Contains newly created auth token * chrome.quickUnlockPrivate.TokenInfo. Note that its precise value is * not relevant here, only the facts that it's created. */ private onTokenObtained_(e: CustomEvent<any>) { assert(e.detail); this.tokenRequestManager_.resolve(); } private onPasswordPromptClosed_() { this.showPasswordPromptDialog_ = false; focusWithoutInk(assert(this.activeDialogAnchorStack_!.pop()!)); } private openPasswordPromptDialog_() { this.activeDialogAnchorStack_!.push(getDeepActiveElement() as HTMLElement); this.showPasswordPromptDialog_ = true; } // </if> } customElements.define( SettingsPasswordCheckElement.is, SettingsPasswordCheckElement);
the_stack
import * as fse from 'fs-extra'; import * as path from 'path'; import { createTestActionContext } from 'vscode-azureextensiondev'; import { FuncVersion, getRandomHexString, ProjectLanguage, verifyVersionAndLanguage } from '../extension.bundle'; import { assertThrowsAsync } from './assertThrowsAsync'; import { testFolderPath } from './global.test'; suite('verifyVersionAndLanguage', () => { let net3Path: string; let net5Path: string; suiteSetup(async () => { net3Path = path.join(testFolderPath, getRandomHexString()); const net3ProjPath = path.join(net3Path, 'test.csproj'); await fse.ensureFile(net3ProjPath); await fse.writeFile(net3ProjPath, net3Proj); net5Path = path.join(testFolderPath, getRandomHexString()); const net5ProjPath = path.join(net5Path, 'test.csproj'); await fse.ensureFile(net5ProjPath); await fse.writeFile(net5ProjPath, net5Proj); }); test('Local: ~1, Remote: none', async () => { const props: { [name: string]: string } = {}; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v1, ProjectLanguage.JavaScript, props); }); test('Local: ~1, Remote: ~1', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~1' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v1, ProjectLanguage.JavaScript, props); }); test('Local: ~1, Remote: 1.0.0', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '1.0.0' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v1, ProjectLanguage.JavaScript, props); }); test('Local: ~1, Remote: ~2', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2' }; const context = await createTestActionContext(); await context.ui.runWithInputs(['Deploy Anyway'], async () => { await verifyVersionAndLanguage(context, undefined, 'testSite', FuncVersion.v1, ProjectLanguage.JavaScript, props); }); }); test('Local: ~1, Remote: 2.0.0', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '2.0.0' }; const context = await createTestActionContext(); await context.ui.runWithInputs(['Deploy Anyway'], async () => { await verifyVersionAndLanguage(context, undefined, 'testSite', FuncVersion.v1, ProjectLanguage.JavaScript, props); }); }); test('Local: ~2, Remote: none', async () => { const props: { [name: string]: string } = {}; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); test('Local: ~2, Remote: ~2', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); test('Local: ~2, Remote: 2.0.0', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '2.0.0' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); test('Local: ~2, Remote: ~1', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~1' }; const context = await createTestActionContext(); await context.ui.runWithInputs(['Deploy Anyway'], async () => { await verifyVersionAndLanguage(context, undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); }); test('Local: ~2, Remote: 1.0.0', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '1.0.0' }; const context = await createTestActionContext(); await context.ui.runWithInputs(['Deploy Anyway'], async () => { await verifyVersionAndLanguage(context, undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); }); test('Local: ~2/node, Remote: ~2/node', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2', FUNCTIONS_WORKER_RUNTIME: 'node' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props); }); test('Local: ~2/node, Remote: ~2/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await assertThrowsAsync(async () => await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props), /dotnet.*match.*node/i); }); test('Local: ~2/node, Remote: ~1/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~1', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await assertThrowsAsync(async () => await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.JavaScript, props), /dotnet.*match.*node/i); }); test('Local: ~2/unknown, Remote: ~2/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, <ProjectLanguage>"unknown", props); }); test('Local: ~2/C#, Remote: ~2/unknown', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2', FUNCTIONS_WORKER_RUNTIME: 'unknown' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, ProjectLanguage.CSharp, props); }); test('Local: ~2/unknown, Remote: ~2/unknown', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~2', FUNCTIONS_WORKER_RUNTIME: 'unknown' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v2, <ProjectLanguage>"unknown", props); }); test('Local: ~3/dotnet, Remote: ~3/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~3', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await verifyVersionAndLanguage(await createTestActionContext(), net3Path, 'testSite', FuncVersion.v3, ProjectLanguage.CSharp, props); }); test('Local: ~3/dotnet, Remote: ~3/dotnet-isolated', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~3', FUNCTIONS_WORKER_RUNTIME: 'dotnet-isolated' }; await assertThrowsAsync(async () => await verifyVersionAndLanguage(await createTestActionContext(), net3Path, 'testSite', FuncVersion.v3, ProjectLanguage.CSharp, props), /dotnet-isolated.*match.*dotnet/i); }); test('Local: ~3/dotnet-isolated, Remote: ~3/dotnet-isolated', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~3', FUNCTIONS_WORKER_RUNTIME: 'dotnet-isolated' }; await verifyVersionAndLanguage(await createTestActionContext(), net5Path, 'testSite', FuncVersion.v3, ProjectLanguage.CSharp, props); }); test('Local: ~3/dotnet-isolated, Remote: ~3/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~3', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await assertThrowsAsync(async () => await verifyVersionAndLanguage(await createTestActionContext(), net5Path, 'testSite', FuncVersion.v3, ProjectLanguage.CSharp, props), /dotnet.*match.*dotnet-isolated/i); }); test('Local: ~3/dotnet (unknown projectPath), Remote: ~3/dotnet', async () => { const props: { [name: string]: string } = { FUNCTIONS_EXTENSION_VERSION: '~3', FUNCTIONS_WORKER_RUNTIME: 'dotnet' }; await verifyVersionAndLanguage(await createTestActionContext(), undefined, 'testSite', FuncVersion.v3, ProjectLanguage.CSharp, props); }); }); const net3Proj: string = `<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <AzureFunctionsVersion>v3</AzureFunctionsVersion> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" /> </ItemGroup> <ItemGroup> <None Update="host.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="local.settings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>Never</CopyToPublishDirectory> </None> </ItemGroup> </Project> `; const net5Proj: string = `<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net5.0</TargetFramework> <AzureFunctionsVersion>v3</AzureFunctionsVersion> <OutputType>Exe</OutputType> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.0.12" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.0.3" OutputItemType="Analyzer" /> <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.1.0" /> </ItemGroup> <ItemGroup> <None Update="host.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> <None Update="local.settings.json"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>Never</CopyToPublishDirectory> </None> </ItemGroup> </Project> `;
the_stack
// clang-format off import {sendWithPromise} from 'chrome://resources/js/cr.m.js'; import {ChooserType,ContentSetting,ContentSettingsTypes,SiteSettingSource} from './constants.js'; // clang-format on /** * The handler will send a policy source that is similar, but not exactly the * same as a ControlledBy value. If the ContentSettingProvider is omitted it * should be treated as 'default'. */ export enum ContentSettingProvider { POLICY = 'policy', SUPERVISED_USER = 'supervised_user', EXTENSION = 'extension', INSTALLED_WEBAPP_PROVIDER = 'installed_webapp_provider', NOTIFICATION_ANDROID = 'notification_android', EPHEMERAL = 'ephemeral', PREFERENCE = 'preference', DEFAULT = 'default', TESTS = 'tests', TESTS_OTHER = 'tests_other' } /** * Stores information about if a content setting is valid, and why. */ type IsValid = { isValid: boolean, reason: string|null, }; /** * Stores origin information. The |hasPermissionSettings| will be set to true * when this origin has permissions or when there is a pattern permission * affecting this origin. */ export type OriginInfo = { origin: string, engagement: number, usage: number, numCookies: number, hasPermissionSettings: boolean, isInstalled: boolean, isPartitioned: boolean }; /** * Represents a list of sites, grouped under the same eTLD+1. For example, an * origin "https://www.example.com" would be grouped together with * "https://login.example.com" and "http://example.com" under a common eTLD+1 of * "example.com". */ export type SiteGroup = { etldPlus1: string, numCookies: number, origins: Array<OriginInfo>, hasInstalledPWA: boolean, }; /** * The site exception information passed from the C++ handler. * See also: SiteException. */ export type RawSiteException = { embeddingOrigin: string, incognito: boolean, isEmbargoed: boolean, origin: string, displayName: string, type: string, setting: ContentSetting, source: SiteSettingSource, }; /** * The site exception after it has been converted/filtered for UI use. * See also: RawSiteException. */ export type SiteException = { category: ContentSettingsTypes, embeddingOrigin: string, incognito: boolean, isEmbargoed: boolean, origin: string, displayName: string, setting: ContentSetting, enforcement: chrome.settingsPrivate.Enforcement|null, controlledBy: chrome.settingsPrivate.ControlledBy, // <if expr="chromeos"> showAndroidSmsNote?: boolean, // </if> }; /** * Represents a list of exceptions recently configured for a site, where recent * is defined by the maximum number of sources parameter passed to * GetRecentSitePermissions. */ export type RecentSitePermissions = { origin: string, incognito: boolean, recentPermissions: Array<RawSiteException>, }; /** * The chooser exception information passed from the C++ handler. * See also: ChooserException. */ export type RawChooserException = { chooserType: ChooserType, displayName: string, object: Object, sites: Array<RawSiteException>, }; /** * The chooser exception after it has been converted/filtered for UI use. * See also: RawChooserException. */ export type ChooserException = { chooserType: ChooserType, displayName: string, object: Object, sites: Array<SiteException>, }; export type DefaultContentSetting = { setting: ContentSetting, source: ContentSettingProvider, }; /** * The primary cookie setting states that are possible. Must be kept in sync * with the C++ enum of the same name in * chrome/browser/content_settings/generated_cookie_prefs.h */ export enum CookiePrimarySetting { ALLOW_ALL = 0, BLOCK_THIRD_PARTY_INCOGNITO = 1, BLOCK_THIRD_PARTY = 2, BLOCK_ALL = 3, } export type MediaPickerEntry = { name: string, id: string, }; type ProtocolHandlerEntry = { protocol: string, spec: string, }; export type ZoomLevelEntry = { displayName: string, origin: string, originForFavicon: string, setting: string, source: string, zoom: string, }; export interface SiteSettingsPrefsBrowserProxy { /** * Sets the default value for a site settings category. * @param contentType The name of the category to change. * @param defaultValue The name of the value to set as default. */ setDefaultValueForContentType(contentType: string, defaultValue: string): void; /** * Gets the default value for a site settings category. */ getDefaultValueForContentType(contentType: ContentSettingsTypes): Promise<DefaultContentSetting>; /** * Gets a list of sites, grouped by eTLD+1, affected by any content settings * that should be visible to the user. */ getAllSites(): Promise<Array<SiteGroup>>; /** * Returns a list of content settings types that are controlled via a standard * permissions UI and should be made visible to the user. * @param origin The associated origin for which categories should be shown or * hidden. */ getCategoryList(origin: string): Promise<Array<ContentSettingsTypes>>; /** * Get the string which describes the current effective cookie setting. */ getCookieSettingDescription(): Promise<string>; /** * Gets most recently changed permissions grouped by host and limited to * numSources different origin/profile (inconigto/regular) pairings. * This includes permissions adjusted by embargo, but excludes any set * via policy. * @param numSources Maximum number of different sources to return */ getRecentSitePermissions(numSources: number): Promise<Array<RecentSitePermissions>>; /** * Gets the chooser exceptions for a particular chooser type. * @param chooserType The chooser type to grab exceptions from. */ getChooserExceptionList(chooserType: ChooserType): Promise<Array<RawChooserException>>; /** * Converts a given number of bytes into a human-readable format, with data * units. */ getFormattedBytes(numBytes: number): Promise<string>; /** * Gets the exceptions (site list) for a particular category. * @param contentType The name of the category to query. */ getExceptionList(contentType: ContentSettingsTypes): Promise<Array<RawSiteException>>; /** * Gets a list of category permissions for a given origin. Note that this * may be different to the results retrieved by getExceptionList(), since it * combines different sources of data to get a permission's value. * @param origin The origin to look up permissions for. * @param contentTypes A list of categories to retrieve the ContentSetting * for. */ getOriginPermissions( origin: string, contentTypes: Array<ContentSettingsTypes>): Promise<Array<RawSiteException>>; /** * Resets the permissions for a list of categories for a given origin. This * does not support incognito settings or patterns. * @param origin The origin to reset permissions for. * @param category to set the permission for. If null, this applies to all * categories. (Sometimes it is useful to clear any permissions set for * all categories.) * @param blanketSetting The setting to set all permissions listed in * |contentTypes| to. */ setOriginPermissions( origin: string, category: ContentSettingsTypes|null, blanketSetting: ContentSetting): void; /** * Resets the category permission for a given origin (expressed as primary * and secondary patterns). Only use this if intending to remove an * exception - use setOriginPermissions() for origin-scoped settings. * @param primaryPattern The origin to change (primary pattern). * @param secondaryPattern The embedding origin to change (secondary * pattern). * @param contentType The name of the category to reset. * @param incognito Whether this applies only to a current * incognito session exception. */ resetCategoryPermissionForPattern( primaryPattern: string, secondaryPattern: string, contentType: string, incognito: boolean): void; /** * Removes a particular chooser object permission by origin and embedding * origin. * @param chooserType The chooser exception type * @param origin The origin to look up the permission for. * @param embeddingOrigin the embedding origin to look up. * @param exception The exception to revoke permission for. */ resetChooserExceptionForSite( chooserType: ChooserType, origin: string, embeddingOrigin: string, exception: Object): void; /** * Sets the category permission for a given origin (expressed as primary and * secondary patterns). Only use this if intending to set an exception - use * setOriginPermissions() for origin-scoped settings. * @param primaryPattern The origin to change (primary pattern). * @param secondaryPattern The embedding origin to change (secondary pattern). * @param contentType The name of the category to change. * @param value The value to change the permission to. * @param incognito Whether this rule applies only to the current incognito * session. */ setCategoryPermissionForPattern( primaryPattern: string, secondaryPattern: string, contentType: string, value: string, incognito: boolean): void; /** * Checks whether an origin is valid. */ isOriginValid(origin: string): Promise<boolean>; /** * Checks whether a setting is valid. * @param pattern The pattern to check. * @param category What kind of setting, e.g. Location, Camera, Cookies, etc. * @return Contains whether or not the pattern is valid for the type, and if * it is invalid, the reason why. */ isPatternValidForType(pattern: string, category: ContentSettingsTypes): Promise<IsValid>; /** * Gets the list of default capture devices for a given type of media. List * is returned through a JS call to updateDevicesMenu. * @param type The type to look up. */ getDefaultCaptureDevices(type: string): void; /** * Sets a default devices for a given type of media. * @param type The type of media to configure. * @param defaultValue The id of the media device to set. */ setDefaultCaptureDevice(type: string, defaultValue: string): void; /** * observes _all_ of the the protocol handler state, which includes a list * that is returned through JS calls to 'setProtocolHandlers' along with * other state sent with the messages 'setIgnoredProtocolHandler' and * 'setHandlersEnabled'. */ observeProtocolHandlers(): void; /** * observes _all_ of the the app protocol handler state, which includes a * list that is returned through 'setAppAllowedProtocolHandlers' events. */ observeAppProtocolHandlers(): void; /** * Observes one aspect of the protocol handler so that updates to the * enabled/disabled state are sent. A 'setHandlersEnabled' will be sent * from C++ immediately after receiving this observe request and updates * may follow via additional 'setHandlersEnabled' messages. * * If |observeProtocolHandlers| is called, there's no need to call this * observe as well. */ observeProtocolHandlersEnabledState(): void; /** * Enables or disables the ability for sites to ask to become the default * protocol handlers. * @param enabled Whether sites can ask to become default. */ setProtocolHandlerDefault(enabled: boolean): void; /** * Sets a certain url as default for a given protocol handler. * @param protocol The protocol to set a default for. * @param url The url to use as the default. */ setProtocolDefault(protocol: string, url: string): void; /** * Deletes a certain protocol handler by url. * @param protocol The protocol to delete the url from. * @param url The url to delete. */ removeProtocolHandler(protocol: string, url: string): void; /** * Deletes a protocol handler by url from the app allowed list. * @param protocol The protocol to delete the url from. * @param url The url to delete. * @param appId The web app's ID to delete. */ removeAppAllowedHandler(protocol: string, url: string, appId: string): void; /** * Deletes a protocol handler by url from the app approved list. * @param protocol The protocol to delete the url from. * @param url The url to delete. * @param app_id The web app's ID to delete. */ removeAppDisallowedHandler(protocol: string, url: string, app_id: string): void; /** * Fetches the incognito status of the current profile (whether an incognito * profile exists). Returns the results via onIncognitoStatusChanged. */ updateIncognitoStatus(): void; /** * Fetches the currently defined zoom levels for sites. Returns the results * via onZoomLevelsChanged. */ fetchZoomLevels(): void; /** * Removes a zoom levels for a given host. * @param host The host to remove zoom levels for. */ removeZoomLevel(host: string): void; /** * Fetches the current block autoplay state. Returns the results via * onBlockAutoplayStatusChanged. */ fetchBlockAutoplayStatus(): void; /** * Clears all the web storage data and cookies for a given etld+1. * @param etldPlus1 The etld+1 to clear data from. */ clearEtldPlus1DataAndCookies(etldPlus1: string): void; /** * Clears all the unpartitioned web storage data and cookies for a given * origin. * @param origin The origin to clear data from. */ clearUnpartitionedOriginDataAndCookies(origin: string): void; /** * Clears all the storage for |origin| which is partitioned on |etldPlus1|. * @param origin The origin to clear data from. * @param etldPlus1 The etld+1 which the data is partitioned for. */ clearPartitionedOriginDataAndCookies(origin: string, etldPlus1: string): void; /** * Record All Sites Page action for metrics. * @param action number. */ recordAction(action: number): void; } export class SiteSettingsPrefsBrowserProxyImpl implements SiteSettingsPrefsBrowserProxy { setDefaultValueForContentType(contentType: string, defaultValue: string) { chrome.send('setDefaultValueForContentType', [contentType, defaultValue]); } getDefaultValueForContentType(contentType: ContentSettingsTypes) { return sendWithPromise('getDefaultValueForContentType', contentType); } getAllSites() { return sendWithPromise('getAllSites'); } getCategoryList(origin: string) { return sendWithPromise('getCategoryList', origin); } getCookieSettingDescription() { return sendWithPromise('getCookieSettingDescription'); } getRecentSitePermissions(numSources: number) { return sendWithPromise('getRecentSitePermissions', numSources); } getChooserExceptionList(chooserType: ChooserType) { return sendWithPromise('getChooserExceptionList', chooserType); } getFormattedBytes(numBytes: number) { return sendWithPromise('getFormattedBytes', numBytes); } getExceptionList(contentType: ContentSettingsTypes) { return sendWithPromise('getExceptionList', contentType); } getOriginPermissions( origin: string, contentTypes: Array<ContentSettingsTypes>) { return sendWithPromise('getOriginPermissions', origin, contentTypes); } setOriginPermissions( origin: string, category: ContentSettingsTypes|null, blanketSetting: ContentSetting) { chrome.send('setOriginPermissions', [origin, category, blanketSetting]); } resetCategoryPermissionForPattern( primaryPattern: string, secondaryPattern: string, contentType: string, incognito: boolean) { chrome.send( 'resetCategoryPermissionForPattern', [primaryPattern, secondaryPattern, contentType, incognito]); } resetChooserExceptionForSite( chooserType: ChooserType, origin: string, embeddingOrigin: string, exception: Object) { chrome.send( 'resetChooserExceptionForSite', [chooserType, origin, embeddingOrigin, exception]); } setCategoryPermissionForPattern( primaryPattern: string, secondaryPattern: string, contentType: string, value: string, incognito: boolean) { chrome.send( 'setCategoryPermissionForPattern', [primaryPattern, secondaryPattern, contentType, value, incognito]); } isOriginValid(origin: string) { return sendWithPromise('isOriginValid', origin); } isPatternValidForType(pattern: string, category: ContentSettingsTypes) { return sendWithPromise('isPatternValidForType', pattern, category); } getDefaultCaptureDevices(type: string) { chrome.send('getDefaultCaptureDevices', [type]); } setDefaultCaptureDevice(type: string, defaultValue: string) { chrome.send('setDefaultCaptureDevice', [type, defaultValue]); } observeProtocolHandlers() { chrome.send('observeProtocolHandlers'); } observeAppProtocolHandlers() { chrome.send('observeAppProtocolHandlers'); } observeProtocolHandlersEnabledState() { chrome.send('observeProtocolHandlersEnabledState'); } setProtocolHandlerDefault(enabled: boolean) { chrome.send('setHandlersEnabled', [enabled]); } setProtocolDefault(protocol: string, url: string) { chrome.send('setDefault', [protocol, url]); } removeProtocolHandler(protocol: string, url: string) { chrome.send('removeHandler', [protocol, url]); } removeAppAllowedHandler(protocol: string, url: string, appId: string) { chrome.send('removeAppAllowedHandler', [protocol, url, appId]); } removeAppDisallowedHandler(protocol: string, url: string, app_id: string) { chrome.send('removeAppDisallowedHandler', [protocol, url, app_id]); } updateIncognitoStatus() { chrome.send('updateIncognitoStatus'); } fetchZoomLevels() { chrome.send('fetchZoomLevels'); } removeZoomLevel(host: string) { chrome.send('removeZoomLevel', [host]); } fetchBlockAutoplayStatus() { chrome.send('fetchBlockAutoplayStatus'); } clearEtldPlus1DataAndCookies(etldPlus1: string) { chrome.send('clearEtldPlus1DataAndCookies', [etldPlus1]); } clearUnpartitionedOriginDataAndCookies(origin: string) { chrome.send('clearUnpartitionedUsage', [origin]); } clearPartitionedOriginDataAndCookies(origin: string, etldPlus1: string) { chrome.send('clearPartitionedUsage', [origin, etldPlus1]); } recordAction(action: number) { chrome.send('recordAction', [action]); } static getInstance(): SiteSettingsPrefsBrowserProxy { return instance || (instance = new SiteSettingsPrefsBrowserProxyImpl()); } static setInstance(obj: SiteSettingsPrefsBrowserProxy) { instance = obj; } } let instance: SiteSettingsPrefsBrowserProxy|null = null;
the_stack
* @fileoverview Interfaces and abstract classes for MmlNode objects * * @author dpvc@mathjax.org (Davide Cervone) */ import {Attributes, INHERIT} from './Attributes.js'; import {Property, PropertyList, Node, AbstractNode, AbstractEmptyNode, NodeClass} from '../Tree/Node.js'; import {MmlFactory} from './MmlFactory.js'; import {DOMAdaptor} from '../DOMAdaptor.js'; /** * Used in setInheritedAttributes() to pass originating node kind as well as property value */ export type AttributeList = {[attribute: string]: [string, Property]}; /** * These are the TeX classes for spacing computations */ export const TEXCLASS = { ORD: 0, OP: 1, BIN: 2, REL: 3, OPEN: 4, CLOSE: 5, PUNCT: 6, INNER: 7, VCENTER: 8, // Used in TeXAtom, but not for spacing NONE: -1 }; export const TEXCLASSNAMES = ['ORD', 'OP', 'BIN', 'REL', 'OPEN', 'CLOSE', 'PUNCT', 'INNER', 'VCENTER']; /** * The spacing sizes used by the TeX spacing table below. */ const TEXSPACELENGTH = ['', 'thinmathspace', 'mediummathspace', 'thickmathspace']; /** * See TeXBook Chapter 18 (p. 170) */ const TEXSPACE = [ [ 0, -1, 2, 3, 0, 0, 0, 1], // ORD [-1, -1, 0, 3, 0, 0, 0, 1], // OP [ 2, 2, 0, 0, 2, 0, 0, 2], // BIN [ 3, 3, 0, 0, 3, 0, 0, 3], // REL [ 0, 0, 0, 0, 0, 0, 0, 0], // OPEN [ 0, -1, 2, 3, 0, 0, 0, 1], // CLOSE [ 1, 1, 0, 1, 1, 1, 1, 1], // PUNCT [ 1, -1, 2, 3, 1, 0, 1, 1] // INNER ]; /** * Attributes used to determine indentation and shifting */ export const indentAttributes = [ 'indentalign', 'indentalignfirst', 'indentshift', 'indentshiftfirst' ]; /** * The nodes that can be in the internal MathML tree */ export type MMLNODE = MmlNode | TextNode | XMLNode; /*****************************************************************/ /** * The MmlNode interface (extends Node interface) */ export interface MmlNode extends Node { /** * Test various properties of MathML nodes */ readonly isToken: boolean; readonly isEmbellished: boolean; readonly isSpacelike: boolean; readonly linebreakContainer: boolean; readonly hasNewLine: boolean; /** * The expected number of children (-1 means use inferred mrow) */ readonly arity: number; readonly isInferred: boolean; /** * Get the parent node (skipping inferred mrows and * other nodes marked as notParent) */ readonly Parent: MmlNode; readonly notParent: boolean; /** * The actual parent in the tree */ parent: MmlNode; /** * values needed for TeX spacing computations */ texClass: number; prevClass: number; prevLevel: number; /** * The attributes (explicit and inherited) for this node */ attributes: Attributes; /** * @return {MmlNode} For embellished operators, the child node that contains the * core <mo> node. For non-embellished nodes, the original node. */ core(): MmlNode; /** * @return {MmlNode} For embellished operators, the core <mo> element (at whatever * depth). For non-embellished nodes, the original node itself. */ coreMO(): MmlNode; /** * @return {number} For embellished operators, the index of the child node containing * the core <mo>. For non-embellished nodes, 0. */ coreIndex(): number; /** * @return {number} The index of this node in its parent's childNodes array. */ childPosition(): number; /** * @param {MmlNode} prev The node that is before this one for TeX spacing purposes * (not all nodes count in TeX measurements) * @return {MmlNode} The node that should be the previous node for the next one * in the tree (usually, either the last child, or the node itself) */ setTeXclass(prev: MmlNode): MmlNode; /** * @return {string} The spacing to use before this element (one of TEXSPACELENGTH array above) */ texSpacing(): string; /** * @return {boolean} The core mo element has an explicit 'form', 'lspace', or 'rspace' attribute */ hasSpacingAttributes(): boolean; /** * Sets the nodes inherited attributes, and pushes them to the nodes children. * * @param {AttributeList} attributes The list of inheritable attributes (with the node kinds * from which they came) * @param {boolean} display The displaystyle to inherit * @param {number} level The scriptlevel to inherit * @param {boolean} prime The TeX prime style to inherit (T vs. T', etc). */ setInheritedAttributes(attributes: AttributeList, display: boolean, level: number, prime: boolean): void; /** * Set the nodes inherited attributes based on the attributes of the given node * (used for creating extra nodes in the tree after setInheritedAttributes has already run) * * @param {MmlNode} node The node whose attributes are to be used as a template */ inheritAttributesFrom(node: MmlNode): void; /** * Replace the current node with an error message (or the name of the node) * * @param {string} message The error message to use * @param {PropertyList} options The options telling how much to verify * @param {boolean} short True means use just the kind if not using full errors * @return {MmlNode} The construted merror */ mError(message: string, options: PropertyList, short?: boolean): MmlNode; /** * Check integrity of MathML structure * * @param {PropertyList} options The options controlling the check */ verifyTree(options?: PropertyList): void; } /*****************************************************************/ /** * The MmlNode class interface (extends the NodeClass) */ export interface MmlNodeClass extends NodeClass { /** * The list of default attribute values for nodes of this class */ defaults?: PropertyList; /** * An MmlNode takes a NodeFactory (so it can create additional nodes as needed), a list * of attributes, and an array of children and returns the desired MmlNode with * those attributes and children * * @constructor * @param {MmlFactory} factory The MathML node factory to use to create additional nodes * @param {PropertyList} attributes The list of initial attributes for the node * @param {MmlNode[]} children The initial child nodes (more can be added later) */ new (factory: MmlFactory, attributes?: PropertyList, children?: MmlNode[]): MmlNode; } /*****************************************************************/ /** * The abstract MmlNode class (extends the AbstractNode class and implements * the IMmlNode interface) */ export abstract class AbstractMmlNode extends AbstractNode implements MmlNode { /** * The properties common to all MathML nodes */ public static defaults: PropertyList = { mathbackground: INHERIT, mathcolor: INHERIT, mathsize: INHERIT, // technically only for token elements, but <mstyle mathsize="..."> should // scale all spaces, fractions, etc. dir: INHERIT }; /** * This lists properties that do NOT get inherited between specific kinds * of nodes. The outer keys are the node kinds that are being inherited FROM, * while the second level of keys are the nodes that INHERIT the values. Any * property appearing in the innermost list is NOT inherited by the pair. * * For example, an mpadded element will not inherit a width attribute from an mstyle node. */ public static noInherit: {[node1: string]: {[node2: string]: {[attribute: string]: boolean}}} = { mstyle: { mpadded: {width: true, height: true, depth: true, lspace: true, voffset: true}, mtable: {width: true, height: true, depth: true, align: true} }, maligngroup: { mrow: {groupalign: true}, mtable: {groupalign: true} } }; /** * This lists the attributes that should always be inherited, * even when there is no default value for the attribute. */ public static alwaysInherit: {[name: string]: boolean} = { scriptminsize: true, scriptsizemultiplier: true }; /** * This is the list of options for the verifyTree() method */ public static verifyDefaults: PropertyList = { checkArity: true, checkAttributes: false, fullErrors: false, fixMmultiscripts: true, fixMtables: true }; /* * These default to being unset (the node doesn't participate in spacing calculations). * The correct values are produced when the setTeXclass() method is called on the tree. */ /** * The TeX class for the preceding node */ public prevClass: number = null; /** * The scriptlevel of the preceding node */ public prevLevel: number = null; /** * This node's attributes */ public attributes: Attributes; /** * Child nodes are MmlNodes (special case of Nodes). */ public childNodes: MmlNode[]; /** * The parent is an MmlNode */ public parent: MmlNode; /** * The node factory is an MmlFactory */ public readonly factory: MmlFactory; /** * The TeX class of this node (obtained via texClass below) */ protected texclass: number = null; /** * Create an MmlNode: * If the arity is -1, add the inferred row (created by the factory) * Add the children, if any * Create the Attribute object from the class defaults and the global defaults (the math node defaults) * * @override */ constructor(factory: MmlFactory, attributes: PropertyList = {}, children: MmlNode[] = []) { super(factory); if (this.arity < 0) { this.childNodes = [factory.create('inferredMrow')]; this.childNodes[0].parent = this; } this.setChildren(children); this.attributes = new Attributes( factory.getNodeClass(this.kind).defaults, factory.getNodeClass('math').defaults ); this.attributes.setList(attributes); } /** * @override * * @param {boolean} keepIds True to copy id attributes, false to skip them. * (May cause error in the future, since not part of the interface.) * @return {AbstractMmlNode} The copied node tree. */ public copy(keepIds: boolean = false): AbstractMmlNode { const node = this.factory.create(this.kind) as AbstractMmlNode; node.properties = {...this.properties}; if (this.attributes) { const attributes = this.attributes.getAllAttributes(); for (const name of Object.keys(attributes)) { if (name !== 'id' || keepIds) { node.attributes.set(name, attributes[name]); } } } if (this.childNodes && this.childNodes.length) { let children = this.childNodes as MmlNode[]; if (children.length === 1 && children[0].isInferred) { children = children[0].childNodes as MmlNode[]; } for (const child of children) { if (child) { node.appendChild(child.copy() as MmlNode); } else { node.childNodes.push(null); } } } return node; } /** * The TeX class for this node */ public get texClass(): number { return this.texclass; } /** * The TeX class for this node */ public set texClass(texClass: number) { this.texclass = texClass; } /** * @return {boolean} true if this is a token node */ public get isToken(): boolean { return false; } /** * @return {boolean} true if this is an embellished operator */ public get isEmbellished(): boolean { return false; } /** * @return {boolean} true if this is a space-like node */ public get isSpacelike(): boolean { return false; } /** * @return {boolean} true if this is a node that supports linebreaks in its children */ public get linebreakContainer(): boolean { return false; } /** * @return {boolean} true if this node contains a line break */ public get hasNewLine(): boolean { return false; } /** * @return {number} The number of children allowed, or Infinity for any number, * or -1 for when an inferred row is needed for the children. * Special case is 1, meaning at least one (other numbers * mean exactly that many). */ public get arity(): number { return Infinity; } /** * @return {boolean} true if this is an inferred mrow */ public get isInferred(): boolean { return false; } /** * @return {MmlNode} The logical parent of this node (skipping over inferred rows * some other node types) */ public get Parent(): MmlNode { let parent = this.parent; while (parent && parent.notParent) { parent = parent.Parent; } return parent; } /** * @return {boolean} true if this is a node that doesn't count as a parent node in Parent() */ public get notParent(): boolean { return false; } /** * If there is an inferred row, the the children of that instead * * @override */ public setChildren(children: MmlNode[]) { if (this.arity < 0) { return this.childNodes[0].setChildren(children); } return super.setChildren(children); } /** * If there is an inferred row, append to that instead. * If a child is inferred, append its children instead. * * @override */ public appendChild(child: MmlNode) { if (this.arity < 0) { this.childNodes[0].appendChild(child); return child; } if (child.isInferred) { // // If we can have arbitrary children, remove the inferred mrow // (just add its children). // if (this.arity === Infinity) { child.childNodes.forEach((node) => super.appendChild(node)); return child; } // // Otherwise, convert the inferred mrow to an explicit mrow // const original = child; child = this.factory.create('mrow'); child.setChildren(original.childNodes); child.attributes = original.attributes; for (const name of original.getPropertyNames()) { child.setProperty(name, original.getProperty(name)); } } return super.appendChild(child); } /** * If there is an inferred row, remove the child from there * * @override */ public replaceChild(newChild: MmlNode, oldChild: MmlNode) { if (this.arity < 0) { this.childNodes[0].replaceChild(newChild, oldChild); return newChild; } return super.replaceChild(newChild, oldChild); } /** * @override */ public core(): MmlNode { return this; } /** * @override */ public coreMO(): MmlNode { return this; } /** * @override */ public coreIndex() { return 0; } /** * @override */ public childPosition() { let child: MmlNode = this; let parent = child.parent; while (parent && parent.notParent) { child = parent; parent = parent.parent; } if (parent) { let i = 0; for (const node of parent.childNodes) { if (node === child) { return i; } i++; } } return null; } /** * @override */ public setTeXclass(prev: MmlNode): MmlNode { this.getPrevClass(prev); return (this.texClass != null ? this : prev); } /** * For embellished operators, get the data from the core and clear the core * * @param {MmlNode} core The core <mo> for this node */ protected updateTeXclass(core: MmlNode) { if (core) { this.prevClass = core.prevClass; this.prevLevel = core.prevLevel; core.prevClass = core.prevLevel = null; this.texClass = core.texClass; } } /** * Get the previous element's texClass and scriptlevel * * @param {MmlNode} prev The previous node to this one */ protected getPrevClass(prev: MmlNode) { if (prev) { this.prevClass = prev.texClass; this.prevLevel = prev.attributes.get('scriptlevel') as number; } } /** * @return {string} returns the spacing to use before this node */ public texSpacing(): string { let prevClass = (this.prevClass != null ? this.prevClass : TEXCLASS.NONE); let texClass = this.texClass || TEXCLASS.ORD; if (prevClass === TEXCLASS.NONE || texClass === TEXCLASS.NONE) { return ''; } if (prevClass === TEXCLASS.VCENTER) { prevClass = TEXCLASS.ORD; } if (texClass === TEXCLASS.VCENTER) { texClass = TEXCLASS.ORD; } let space = TEXSPACE[prevClass][texClass]; if ((this.prevLevel > 0 || this.attributes.get('scriptlevel') > 0) && space >= 0) { return ''; } return TEXSPACELENGTH[Math.abs(space)]; } /** * @return {boolean} The core mo element has an explicit 'form' attribute */ public hasSpacingAttributes(): boolean { return this.isEmbellished && this.coreMO().hasSpacingAttributes(); } /** * Sets the inherited propertis for this node, and pushes inherited properties to the children * * For each inheritable attribute: * If the node has a default for this attribute, try to inherit it * but check if the noInherit object prevents that. * If the node doesn't have an explicit displaystyle, inherit it * If the node doesn't have an explicit scriptstyle, inherit it * If the prime style is true, set it as a property (it is not a MathML attribute) * Check that the number of children is correct * Finally, push any inherited attributes to teh children. * * @override */ public setInheritedAttributes(attributes: AttributeList = {}, display: boolean = false, level: number = 0, prime: boolean = false) { let defaults = this.attributes.getAllDefaults(); for (const key of Object.keys(attributes)) { if (defaults.hasOwnProperty(key) || AbstractMmlNode.alwaysInherit.hasOwnProperty(key)) { let [node, value] = attributes[key]; let noinherit = (AbstractMmlNode.noInherit[node] || {})[this.kind] || {}; if (!noinherit[key]) { this.attributes.setInherited(key, value); } } } let displaystyle = this.attributes.getExplicit('displaystyle'); if (displaystyle === undefined) { this.attributes.setInherited('displaystyle', display); } let scriptlevel = this.attributes.getExplicit('scriptlevel'); if (scriptlevel === undefined) { this.attributes.setInherited('scriptlevel', level); } if (prime) { this.setProperty('texprimestyle', prime); } let arity = this.arity; if (arity >= 0 && arity !== Infinity && ((arity === 1 && this.childNodes.length === 0) || (arity !== 1 && this.childNodes.length !== arity))) { // // Make sure there are the right number of child nodes // (trim them or add empty mrows) // if (arity < this.childNodes.length) { this.childNodes = this.childNodes.slice(0, arity); } else { while (this.childNodes.length < arity) { this.appendChild(this.factory.create('mrow')); } } } this.setChildInheritedAttributes(attributes, display, level, prime); } /** * Apply inherited attributes to all children * (Some classes override this to handle changes in displaystyle and scriptlevel) * * @param {AttributeList} attributes The list of inheritable attributes (with the node kinds * from which they came) * @param {boolean} display The displaystyle to inherit * @param {number} level The scriptlevel to inherit * @param {boolean} prime The TeX prime style to inherit (T vs. T', etc). */ protected setChildInheritedAttributes(attributes: AttributeList, display: boolean, level: number, prime: boolean) { for (const child of this.childNodes) { child.setInheritedAttributes(attributes, display, level, prime); } } /** * Used by subclasses to add their own attributes to the inherited list * (e.g., mstyle uses this to augment the inherited attibutes) * * @param {AttributeList} current The current list of inherited attributes * @param {PropertyList} attributes The new attributes to add into the list */ protected addInheritedAttributes(current: AttributeList, attributes: PropertyList) { let updated: AttributeList = {...current}; for (const name of Object.keys(attributes)) { if (name !== 'displaystyle' && name !== 'scriptlevel' && name !== 'style') { updated[name] = [this.kind, attributes[name]]; } } return updated; } /** * Set the nodes inherited attributes based on the attributes of the given node * (used for creating extra nodes in the tree after setInheritedAttributes has already run) * * @param {MmlNode} node The node whose attributes are to be used as a template */ public inheritAttributesFrom(node: MmlNode) { const attributes = node.attributes; const display = attributes.get('displaystyle') as boolean; const scriptlevel = attributes.get('scriptlevel') as number; const defaults: AttributeList = (!attributes.isSet('mathsize') ? {} : { mathsize: ['math', attributes.get('mathsize')] }); const prime = node.getProperty('texprimestyle') as boolean || false; this.setInheritedAttributes(defaults, display, scriptlevel, prime); } /** * Verify the attributes, and that there are the right number of children. * Then verify the children. * * @param {PropertyList} options The options telling how much to verify */ public verifyTree(options: PropertyList = null) { if (options === null) { return; } this.verifyAttributes(options); let arity = this.arity; if (options['checkArity']) { if (arity >= 0 && arity !== Infinity && ((arity === 1 && this.childNodes.length === 0) || (arity !== 1 && this.childNodes.length !== arity))) { this.mError('Wrong number of children for "' + this.kind + '" node', options, true); } } this.verifyChildren(options); } /** * Verify that all the attributes are valid (i.e., have defaults) * * @param {PropertyList} options The options telling how much to verify */ protected verifyAttributes(options: PropertyList) { if (options['checkAttributes']) { const attributes = this.attributes; const bad = []; for (const name of attributes.getExplicitNames()) { if (name.substr(0, 5) !== 'data-' && attributes.getDefault(name) === undefined && !name.match(/^(?:class|style|id|(?:xlink:)?href)$/)) { // FIXME: provide a configurable checker for names that are OK bad.push(name); } // FIXME: add ability to check attribute values? } if (bad.length) { this.mError('Unknown attributes for ' + this.kind + ' node: ' + bad.join(', '), options); } } } /** * Verify the children. * * @param {PropertyList} options The options telling how much to verify */ protected verifyChildren(options: PropertyList) { for (const child of this.childNodes) { child.verifyTree(options); } } /** * Replace the current node with an error message (or the name of the node) * * @param {string} message The error message to use * @param {PropertyList} options The options telling how much to verify * @param {boolean} short True means use just the kind if not using full errors * @return {MmlNode} The constructed merror */ public mError(message: string, options: PropertyList, short: boolean = false): MmlNode { if (this.parent && this.parent.isKind('merror')) { return null; } let merror = this.factory.create('merror'); merror.attributes.set('data-mjx-message', message); if (options['fullErrors'] || short) { let mtext = this.factory.create('mtext'); let text = this.factory.create('text') as TextNode; text.setText(options['fullErrors'] ? message : this.kind); mtext.appendChild(text); merror.appendChild(mtext); this.parent.replaceChild(merror, this); } else { this.parent.replaceChild(merror, this); merror.appendChild(this); } return merror; } } /*****************************************************************/ /** * The abstract MmlNode Token node class (extends the AbstractMmlNode) */ export abstract class AbstractMmlTokenNode extends AbstractMmlNode { /** * Add the attributes common to all token nodes */ public static defaults: PropertyList = { ...AbstractMmlNode.defaults, mathvariant: 'normal', mathsize: INHERIT }; /** * @override */ public get isToken() { return true; } /** * Get the text of the token node (skipping mglyphs, and combining * multiple text nodes) */ public getText() { let text = ''; for (const child of this.childNodes) { if (child instanceof TextNode) { text += child.getText(); } } return text; } /** * Only inherit to child nodes that are AbstractMmlNodes (not TextNodes) * * @override */ protected setChildInheritedAttributes(attributes: AttributeList, display: boolean, level: number, prime: boolean) { for (const child of this.childNodes) { if (child instanceof AbstractMmlNode) { child.setInheritedAttributes(attributes, display, level, prime); } } } /** * Only step into children that are AbstractMmlNodes (not TextNodes) * @override */ public walkTree(func: (node: Node, data?: any) => void, data?: any) { func(this, data); for (const child of this.childNodes) { if (child instanceof AbstractMmlNode) { child.walkTree(func, data); } } return data; } } /*****************************************************************/ /** * The abstract MmlNode Layout class (extends the AbstractMmlNode) * * These have inferred mrows (so only one child) and can be * spacelike or embellished based on their contents. */ export abstract class AbstractMmlLayoutNode extends AbstractMmlNode { /** * Use the same defaults as AbstractMmlNodes */ public static defaults: PropertyList = AbstractMmlNode.defaults; /** * @override */ public get isSpacelike() { return this.childNodes[0].isSpacelike; } /** * @override */ public get isEmbellished() { return this.childNodes[0].isEmbellished; } /** * @override */ public get arity() { return -1; } /** * @override */ public core() { return this.childNodes[0]; } /** * @override */ public coreMO() { return this.childNodes[0].coreMO(); } /** * @override */ public setTeXclass(prev: MmlNode) { prev = this.childNodes[0].setTeXclass(prev); this.updateTeXclass(this.childNodes[0]); return prev; } } /*****************************************************************/ /** * The abstract MmlNode-with-base-node Class (extends the AbstractMmlNode) * * These have a base element and other elemetns, (e.g., script elements for msubsup). * They can be embellished (if their base is), and get their TeX classes * from their base with their scripts being handled as separate math lists. */ export abstract class AbstractMmlBaseNode extends AbstractMmlNode { /** * Use the same defaults as AbstractMmlNodes */ public static defaults: PropertyList = AbstractMmlNode.defaults; /** * @override */ public get isEmbellished() { return this.childNodes[0].isEmbellished; } /** * @override */ public core() { return this.childNodes[0]; } /** * @override */ public coreMO() { return this.childNodes[0].coreMO(); } /** * @override */ public setTeXclass(prev: MmlNode) { this.getPrevClass(prev); this.texClass = TEXCLASS.ORD; let base = this.childNodes[0]; if (base) { if (this.isEmbellished || base.isKind('mi')) { prev = base.setTeXclass(prev); this.updateTeXclass(this.core()); } else { base.setTeXclass(null); prev = this; } } else { prev = this; } for (const child of this.childNodes.slice(1)) { if (child) { child.setTeXclass(null); } } return prev; } } /*****************************************************************/ /** * The abstract MmlNode Empty Class (extends AbstractEmptyNode, implements MmlNode) * * These have no children and no attributes (TextNode and XMLNode), so we * override all the methods dealing with them, and with the data that usually * goes with an MmlNode. */ export abstract class AbstractMmlEmptyNode extends AbstractEmptyNode implements MmlNode { /** * Parent is an MmlNode */ public parent: MmlNode; /** * @return {boolean} Not a token element */ public get isToken(): boolean { return false; } /** * @return {boolean} Not embellished */ public get isEmbellished(): boolean { return false; } /** * @return {boolean} Not space-like */ public get isSpacelike(): boolean { return false; } /** * @return {boolean} Not a container of any kind */ public get linebreakContainer(): boolean { return false; } /** * @return {boolean} Does not contain new lines */ public get hasNewLine(): boolean { return false; } /** * @return {number} No children */ public get arity(): number { return 0; } /** * @return {boolean} Is not an inferred row */ public get isInferred(): boolean { return false; } /** * @return {boolean} Is not a container element */ public get notParent(): boolean { return false; } /** * @return {MmlNode} Parent is the actual parent */ public get Parent(): MmlNode { return this.parent; } /** * @return {number} No TeX class */ public get texClass(): number { return TEXCLASS.NONE; } /** * @return {number} No previous element */ public get prevClass(): number { return TEXCLASS.NONE; } /** * @return {number} No previous element */ public get prevLevel(): number { return 0; } /** * @return {boolean} The core mo element has an explicit 'form' attribute */ public hasSpacingAttributes(): boolean { return false; } /** * return {Attributes} No attributes, so don't store one */ public get attributes(): Attributes { return null; } /** * @override */ public core(): MmlNode { return this; } /** * @override */ public coreMO(): MmlNode { return this; } /** * @override */ public coreIndex() { return 0; } /** * @override */ public childPosition() { return 0; } /** * @override */ public setTeXclass(prev: MmlNode) { return prev; } /** * @override */ public texSpacing() { return ''; } /** * No children or attributes, so ignore this call. * * @override */ public setInheritedAttributes(_attributes: AttributeList, _display: boolean, _level: number, _prime: boolean) {} /** * No children or attributes, so ignore this call. * * @override */ public inheritAttributesFrom(_node: MmlNode) {} /** * No children or attributes, so ignore this call. * * @param {PropertyList} options The options for the check */ public verifyTree(_options: PropertyList) {} /** * @override */ public mError(_message: string, _options: PropertyList, _short: boolean = false) { return null as MmlNode; } } /*****************************************************************/ /** * The TextNode Class (extends AbstractMmlEmptyNode) */ export class TextNode extends AbstractMmlEmptyNode { /** * The text for this node */ protected text: string = ''; /** * @override */ public get kind() { return 'text'; } /** * @return {string} Return the node's text */ public getText(): string { return this.text; } /** * @param {string} text The text to use for the node * @return {TextNode} The text node (for chaining of method calls) */ public setText(text: string): TextNode { this.text = text; return this; } /** * @override */ public copy() { return (this.factory.create(this.kind) as TextNode).setText(this.getText()); } /** * Just use the text */ public toString() { return this.text; } } /*****************************************************************/ /** * The XMLNode Class (extends AbstractMmlEmptyNode) */ export class XMLNode extends AbstractMmlEmptyNode { /** * The XML content for this node */ protected xml: Object = null; /** * DOM adaptor for the content */ protected adaptor: DOMAdaptor<any, any, any> = null; /** * @override */ public get kind() { return 'XML'; } /** * @return {Object} Return the node's XML content */ public getXML(): Object { return this.xml; } /** * @param {object} xml The XML content to be saved * @param {DOMAdaptor} adaptor DOM adaptor for the content * @return {XMLNode} The XML node (for chaining of method calls) */ public setXML(xml: Object, adaptor: DOMAdaptor<any, any, any> = null): XMLNode { this.xml = xml; this.adaptor = adaptor; return this; } /** * @return {string} The serialized XML content */ public getSerializedXML(): string { return this.adaptor.serializeXML(this.xml); } /** * @override */ public copy(): XMLNode { return (this.factory.create(this.kind) as XMLNode).setXML(this.adaptor.clone(this.xml)); } /** * Just indicate that this is XML data */ public toString() { return 'XML data'; } }
the_stack
// Also relies on string-extensions provided by the web-utils package. namespace com.keyman.text { export class TextTransform implements Transform { readonly insert: string; readonly deleteLeft: number; readonly deleteRight?: number; constructor(insert: string, deleteLeft: number, deleteRight?: number) { this.insert = insert; this.deleteLeft = deleteLeft; this.deleteRight = deleteRight || 0; } public static readonly nil = new TextTransform('', 0, 0); } export class Transcription { readonly token: number; readonly keystroke: KeyEvent; readonly transform: Transform; alternates: Alternate[]; // constructed after the rest of the transcription. readonly preInput: Mock; private static tokenSeed: number = 0; constructor(keystroke: KeyEvent, transform: Transform, preInput: Mock, alternates?: Alternate[]/*, removedDks: Deadkey[], insertedDks: Deadkey[]*/) { let token = this.token = Transcription.tokenSeed++; this.keystroke = keystroke; this.transform = transform; this.alternates = alternates; this.preInput = preInput; this.transform.id = this.token; // Assign the ID to each alternate, as well. if(alternates) { alternates.forEach(function(alt) { alt.sample.id = token; }); } } } export type Alternate = ProbabilityMass<Transform>; export abstract class OutputTarget { private _dks: text.DeadkeyTracker; constructor() { this._dks = new text.DeadkeyTracker(); } /** * Signifies that this OutputTarget has no default key processing behaviors. This should be false * for OutputTargets backed by web elements like HTMLInputElement or HTMLTextAreaElement. */ get isSynthetic(): boolean { return true; } resetContext(): void { this.deadkeys().clear(); } deadkeys(): text.DeadkeyTracker { return this._dks; } hasDeadkeyMatch(n: number, d: number): boolean { return this.deadkeys().isMatch(this.getDeadkeyCaret(), n, d); } insertDeadkeyBeforeCaret(d: number) { var dk: Deadkey = new Deadkey(this.getDeadkeyCaret(), d); this.deadkeys().add(dk); } /** * Should be called by each output target immediately before text mutation operations occur. * * Maintains solutions to old issues: I3318,I3319 * @param {number} delta Use negative values if characters were deleted, positive if characters were added. */ protected adjustDeadkeys(delta: number) { this.deadkeys().adjustPositions(this.getDeadkeyCaret(), delta); } /** * Needed to properly clone deadkeys for use with Mock element interfaces toward predictive text purposes. * @param {object} dks An existing set of deadkeys to deep-copy for use by this element interface. */ protected setDeadkeys(dks: text.DeadkeyTracker) { this._dks = dks.clone(); } /** * Determines the basic operations needed to reconstruct the current OutputTarget's text from the prior state specified * by another OutputTarget based on their text and caret positions. * * This is designed for use as a "before and after" comparison to determine the effect of a single keyboard rule at a time. * As such, it assumes that the caret is immediately after any inserted text. * @param from An output target (preferably a Mock) representing the prior state of the input/output system. */ buildTransformFrom(original: OutputTarget): Transform { let to = this.getText(); let from = original.getText(); let fromCaret = original.getDeadkeyCaret(); let toCaret = this.getDeadkeyCaret(); // Step 1: Determine the number of left-deletions. let maxSMPLeftMatch = fromCaret < toCaret ? fromCaret : toCaret; // We need the corresponding non-SMP caret location in order to binary-search efficiently. // (Examining code units is much more computationally efficient.) let maxLeftMatch = to._kmwCodePointToCodeUnit(maxSMPLeftMatch); // 1.1: use a non-SMP-aware binary search to determine the divergence point. let start = 0; let end = maxLeftMatch; // the index AFTER the last possible matching char. // This search is O(maxLeftMatch). 1/2 + 1/4 + 1/8 + ... converges to = 1. while(start < end) { let mid = Math.floor((end+start+1) / 2); // round up (compare more) let fromLeft = from.substr(start, mid-start); let toLeft = to.substr(start, mid-start); if(fromLeft == toLeft) { start = mid; } else { end = mid - 1; } } // At the loop's end: `end` now holds the non-SMP-aware divergence point. // The 'caret' is after the last matching code unit. // 1.2: detect a possible surrogate-pair split scenario, correcting for it // (by moving the split before the high-surrogate) if detected. // If the split location is precisely on either end of the context, we can't // have split a surrogate pair. if(end > 0 && end < maxLeftMatch) { let potentialHigh = from.charCodeAt(end-1); let potentialFromLow = from.charCodeAt(end); let potentialToLow = to.charCodeAt(end); // if potentialHigh is a possible high surrogate... if(potentialHigh >= 0xD800 && potentialHigh <= 0xDBFF) { // and at least one potential 'low' is a possible low surrogate... let flag = potentialFromLow >= 0xDC00 && potentialFromLow <= 0xDFFF; flag = flag || (potentialToLow >= 0XDC00 && potentialToLow <= 0xDFFF); // Correct the split location, moving it 'before' the high surrogate. if(flag) { end = end - 1; } } } // 1.3: take substring from start to the split point; determine SMP-aware length. // This yields the SMP-aware divergence index, which gives the number of left-deletes. let newCaret = from._kmwCodeUnitToCodePoint(end); let deletedLeft = fromCaret - newCaret; // Step 2: Determine the other properties. // Since the 'after' OutputTarget's caret indicates the end of any inserted text, we // can easily calculate the rest. let insertedLength = toCaret - newCaret; let delta = to._kmwSubstr(newCaret, insertedLength); let undeletedRight = to._kmwLength() - toCaret; let originalRight = from._kmwLength() - fromCaret; let deletedRight = originalRight - undeletedRight; // May occur when reverting a suggestion that had been applied mid-word. if(deletedRight < 0) { // Restores deleteRight characters. delta = delta + to._kmwSubstr(toCaret, -deletedRight); deletedRight = 0; } return new TextTransform(delta, deletedLeft, deletedRight); } buildTranscriptionFrom(original: OutputTarget, keyEvent: KeyEvent, alternates?: Alternate[]): Transcription { let transform = this.buildTransformFrom(original); // If we ever decide to re-add deadkey tracking, this is the place for it. return new Transcription(keyEvent, transform, Mock.from(original), alternates); } /** * Restores the `OutputTarget` to the indicated state. Designed for use with `Transcription.preInput`. * @param original An `OutputTarget` (usually a `Mock`). */ restoreTo(original: OutputTarget) { // this.setTextBeforeCaret(original.getTextBeforeCaret()); this.setTextAfterCaret(original.getTextAfterCaret()); // Also, restore the deadkeys! this._dks = original._dks.clone(); } apply(transform: Transform) { if(transform.deleteRight) { this.setTextAfterCaret(this.getTextAfterCaret()._kmwSubstr(transform.deleteRight)); } if(transform.deleteLeft) { this.deleteCharsBeforeCaret(transform.deleteLeft); } if(transform.insert) { this.insertTextBeforeCaret(transform.insert); } // We assume that all deadkeys are invalidated after applying a Transform, since // prediction implies we'll be completing a word, post-deadkeys. this._dks.clear(); } /** * Helper to `restoreTo` - allows directly setting the 'before' context to that of another * `OutputTarget`. * @param s */ protected setTextBeforeCaret(s: string): void { // This one's easy enough to provide a default implementation for. this.deleteCharsBeforeCaret(this.getTextBeforeCaret()._kmwLength()); this.insertTextBeforeCaret(s); } /** * Helper to `restoreTo` - allows directly setting the 'after' context to that of another * `OutputTarget`. * @param s */ protected abstract setTextAfterCaret(s: string): void; /** * Clears any selected text within the wrapper's element(s). * Silently does nothing if no such text exists. */ abstract clearSelection(): void; /** * Clears any cached selection-related state values. */ abstract invalidateSelection(): void; /** * Indicates whether or not the underlying element has its own selection (input, textarea) * or is part of (or possesses) the DOM's active selection. */ abstract hasSelection(): boolean; /** * Returns an index corresponding to the caret's position for use with deadkeys. */ abstract getDeadkeyCaret(): number; /** * Relative to the caret, gets the current context within the wrapper's element. */ abstract getTextBeforeCaret(): string; /** * Relative to the caret (and/or active selection), gets the element's text after the caret, * excluding any actively selected text that would be immediately replaced upon text entry. */ abstract getTextAfterCaret(): string; /** * Gets the element's full text, including any text that is actively selected. */ abstract getText(): string; /** * Performs context deletions (from the left of the caret) as needed by the KeymanWeb engine and * corrects the location of any affected deadkeys. * * Does not delete deadkeys (b/c KMW 1 & 2 behavior maintenance). * @param dn The number of characters to delete. If negative, context will be left unchanged. */ abstract deleteCharsBeforeCaret(dn: number): void; /** * Inserts text immediately before the caret's current position, moving the caret after the * newly inserted text in the process along with any affected deadkeys. * * @param s Text to insert before the caret's current position. */ abstract insertTextBeforeCaret(s: string): void; /** * Allows element-specific handling for ENTER key inputs. Conceptually, this should usually * correspond to `insertTextBeforeCaret('\n'), but actual implementation will vary greatly among * elements. */ abstract handleNewlineAtCaret(): void; /** * Saves element-specific state properties prone to mutation, enabling restoration after * text-output operations. */ saveProperties() { // Most element interfaces won't need anything here. } /** * Restores previously-saved element-specific state properties. Designed for use after text-output * ops to facilitate more-seamless web-dev and user interactions. */ restoreProperties(){ // Most element interfaces won't need anything here. } /** * Generates a synthetic event on the underlying element, signalling that its value has changed. */ abstract doInputEvent(): void; } // Due to some interesting requirements on compile ordering in TS, // this needs to be in the same file as OutputTarget now. export class Mock extends OutputTarget { text: string; caretIndex: number; constructor(text?: string, caretPos?: number) { super(); this.text = text ? text : ""; var defaultLength = this.text._kmwLength(); // Ensures that `caretPos == 0` is handled correctly. this.caretIndex = typeof caretPos == "number" ? caretPos : defaultLength; } // Clones the state of an existing EditableElement, creating a Mock version of its state. static from(outputTarget: OutputTarget) { let clone: Mock; if(outputTarget instanceof Mock) { // Avoids the need to run expensive kmwstring.ts / `_kmwLength()` // calculations when deep-copying Mock instances. let priorMock = outputTarget as Mock; clone = new Mock(priorMock.text, priorMock.caretIndex); } else { // If we're 'cloning' a different OutputTarget type, we don't have a // guaranteed way to more efficiently get these values; these are the // best methods specified by the abstraction. let preText = outputTarget.getTextBeforeCaret(); let caretIndex = preText._kmwLength(); // We choose to ignore (rather, pre-emptively remove) any actively-selected text, // as since it's always removed instantly during any text mutation operations. clone = new Mock(preText + outputTarget.getTextAfterCaret(), caretIndex); } // Also duplicate deadkey state! (Needed for fat-finger ops.) clone.setDeadkeys(outputTarget.deadkeys()); return clone; } clearSelection(): void { return; } invalidateSelection(): void { return; } hasSelection(): boolean { return true; } getDeadkeyCaret(): number { return this.caretIndex; } setDeadkeyCaret(index: number) { if(index < 0 || index > this.text._kmwLength()) { throw new Error("Provided caret index is out of range."); } this.caretIndex = index; } getTextBeforeCaret(): string { return this.text.kmwSubstr(0, this.caretIndex); } getTextAfterCaret(): string { return this.text.kmwSubstr(this.caretIndex); } getText(): string { return this.text; } deleteCharsBeforeCaret(dn: number): void { if(dn >= 0) { if(dn > this.caretIndex) { dn = this.caretIndex; } this.text = this.text.kmwSubstr(0, this.caretIndex - dn) + this.getTextAfterCaret(); this.caretIndex -= dn; } } insertTextBeforeCaret(s: string): void { this.text = this.getTextBeforeCaret() + s + this.getTextAfterCaret(); this.caretIndex += s.kmwLength(); } handleNewlineAtCaret(): void { this.insertTextBeforeCaret('\n'); } protected setTextAfterCaret(s: string): void { this.text = this.getTextBeforeCaret() + s; } doInputEvent() { // Mock isn't backed by an element, so it won't have any event listeners. } } }
the_stack
/// <reference types="jquery" /> /// <reference types="monaco-editor" /> // === Extensions to the window scope interface Window { /** * The official API of the Monaco editor, exposed as a global variable. */ monaco: typeof import("monaco-editor"); /** * Exposes the internal API of monaco editor. May be used to customize the editor even further. * * __THIS IS UNSUPPORTED AND MAY BE CHANGED WITHOUT NOTICE. MAKE SURE YOU KNOW WHAT YOU ARE DOING AND USE AT YOUR OWN * RISK.__ */ monacoExtras: any; /** * Monaco editor environment, which contains the locale and some factory functions. */ MonacoEnvironment: import("monaco-editor").Environment; } // === Monaco editor widget declare namespace PrimeFaces { namespace widget { namespace ExtMonacoEditor { // === General helper types type ParametersIfFn<T> = T extends (...args: never[]) => unknown ? Parameters<T> : never[]; type ReturnTypeIfFn<T> = T extends (...args: never[]) => unknown ? ReturnType<T> : never; /** * Type signature for the factory method that creates the web worker for the Monaco editor. */ type WorkerFactory = (moduleId: string, label: string) => Worker; /** * Data passed to the extender in the {@link MonacoExtenderBase.createModel} method. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface CreateModelOptions<TEditorOpts extends import("monaco-editor").editor.IEditorOptions> { /** Resolved options for the monaco editor. */ editorOptions: Readonly<TEditorOpts>; /** Code language for the model. */ language: string; /** Default URI for the model. */ uri: import("monaco-editor").Uri; /** Initial value for the model. */ value: string; } // === Monaco context /** * Interface for objects that provide asynchronous access to a Monaco code editor or diff editor instances, such * as the widget instance for the Monaco editor in the iframe that can communicate with the editor in the iframe * only via `postMessage`. Note that objects that provide synchronous access also implement this interface for * convenience when you wish to write generic code that works with both types of editors. * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface AsyncMonacoBaseEditorContext< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions > { /** @returns The ID of the Monaco editor widget. */ getWidgetId(): string; /** @returns The current options for the Monaco editor widget. */ getWidgetOptions(): Partial<PrimeFaces.widget.ExtMonacoBaseEditorCfgBase<TEditorOpts>>; /** * Gets the current value (code) of the Monaco editor. May be called as soon as this widget is accessible, * even when the Monaco editor was not loaded or initialized yet. In that case, either the initial value * or the latest value set by {@link setValue} will be returned. * * This method will always fetch the value asynchronously, even when called on the inline Monaco editor. * * Note that for the inline editor, you can also get the value synchronously via `getValueNow`. This method * provides interoperability with the framed monaco editor and is available for both the inline and framed * monaco editor. */ getValue(): Promise<string>; /** * Invokes the given method on the monaco editor instance in the iframe, and returns the result. As the * communication with the iframes is done via `postMessage`, the result is returned asynchronously. * @template K Type of the method to invoke. * @param method A method of the monaco editor instance to invoke. * @param args Arguments that are passed to the method. * @returns A promise that resolves with the value returned by the given method. The promise is rejected when * the editor is not ready yet. */ invokeMonaco<K extends PrimeFaces.MatchingKeys<TEditor, (...args: never[]) => unknown>>( method: K, ...args: PrimeFaces.widget.ExtMonacoEditor.ParametersIfFn<TEditor[K]> ): Promise<Awaited<PrimeFaces.widget.ExtMonacoEditor.ReturnTypeIfFn<TEditor[K]>>>; /** * Invokes the given script on the Monaco editor instance in the iframe, and returns the result. As the * communication with the iframes is done via `postMessage`, the result is returned asynchronously. * * Note that if a function is given for the script, it is converted to a string, sent to the framed editor * and executed. Closing over variables in the lambda is therefore NOT supported. Explicitly specify those * variables as the arguments, they will be passed on to the iframe. * @template TRetVal Type of the value returned by the script. * @template TArgs Type of the arguments required by the script. * @param method A method of the monaco editor instance to invoke. This method receives the Monaco editor * instance as the first argument, and the given `args` as additional arguments. * @param args Arguments that are passed to the method. * @returns A promise that resolves with the value returned by the given method. */ invokeMonacoScript<TRetVal, TArgs extends any[]>( script: string | ((editor: TEditor, ...args: TArgs) => TRetVal), ...args: TArgs ): Promise<Awaited<TRetVal>>; /** * @returns `true` when the editor was already loaded and initialized and can be interacted with via * `getMonaco()`, `false` otherwise. */ isReady(): boolean; /** * Performs a layout on the monaco editor. Useful when the surrounding container has changed its dimensions * etc. Does nothing when the editor was not rendered yet. * * This method will always initiate the layout asynchronously, even when called on the inline editor. * * @returns A promise that resolves immediately when the editor is not ready, or when the layout command * was issued to the editor otherwise. */ layout(): Promise<void>; /** * Sets the value of this editor. May be called as soon as this widget is accessible, even when the * Monaco editor was not loaded or initialized yet. The value will be set on the editor once it * becomes ready. * * This method will always set the value asynchronously, even when called on the inline Monaco editor. * * Note that for the inline editor, you can also set the value synchronously via `setValueNow`. This method * provides interoperability with the framed Monaco editor and is available for both the inline and framed * monaco editor. * @param newValue The new value to set. * @returns A promise that resolves when the value was set. */ setValue(newValue: string): Promise<void>; /** * @returns A promise that is resolved once the editor has finished loading and was created successfully. * When the editor is already initialized, this promise will resolve as soon as possible. */ whenReady(): Promise<this>; } /** * Interface for objects that provide asynchronous access to a Monaco code editor instances, such as the widget * instance for the Monaco editor in the iframe that can communicate with the editor in the iframe only via * `postMessage`. Note that objects that provide synchronous access also implement this interface for convenience * when you wish to write generic code that works with both types of editors. */ interface AsyncMonacoCodeEditorContext extends AsyncMonacoBaseEditorContext< import("monaco-editor").editor.IStandaloneCodeEditor, import("monaco-editor").editor.IStandaloneEditorConstructionOptions > { // override with more specific types getWidgetOptions(): Partial< PrimeFaces.widget.ExtMonacoBaseEditorCfgBase< import("monaco-editor").editor.IStandaloneEditorConstructionOptions > & PrimeFaces.widget.ExtMonacoCodeEditorCfgBase >; } /** * Interface for objects that provide asynchronous access to a Monaco diff editor instances, such as the widget * instance for the Monaco editor in the iframe that can communicate with the editor in the iframe only via * `postMessage`. Note that objects that provide synchronous access also implement this interface for convenience * when you wish to write generic code that works with both types of editors. */ interface AsyncMonacoDiffEditorContext extends AsyncMonacoBaseEditorContext< import("monaco-editor").editor.IStandaloneDiffEditor, import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions > { /** * Gets the current value (code) of the original editor. May be called as soon as this widget is * accessible, even when the Monaco editor was not loaded or initialized yet. In that case, either the * initial value or the latest value set by {@link setValue} will be returned. * * This method will always fetch the value asynchronously, even when called on the inline Monaco editor. * * Note that for the inline editor, you can also get the value synchronously via `getValueNow`. This method * provides interoperability with the framed monaco editor and is available for both the inline and framed * monaco editor. */ getOriginalValue(): Promise<string>; /** * Sets the value of the original editor. May be called as soon as this widget is accessible, even when * the Monaco editor was not loaded or initialized yet. The value will be set on the editor once it * becomes ready. * * This method will always set the value asynchronously, even when called on the inline Monaco editor. * * Note that for the inline editor, you can also set the value synchronously via `setValueNow`. This method * provides interoperability with the framed Monaco editor and is available for both the inline and framed * monaco editor. * @param newValue The new value to set. * @returns A promise that resolves when the value was set. */ setOriginalValue(newValue: string): Promise<void>; // override with more specific types getWidgetOptions(): Partial< PrimeFaces.widget.ExtMonacoBaseEditorCfgBase< import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions > & PrimeFaces.widget.ExtMonacoDiffEditorCfgBase >; } /** * Interface for objects that provide synchronous access to a Monaco code editor or diff editor instance, such as * the widget instance for the inline monaco editor. Note that objects that provide synchronous access also * implement the asynchronous interface for convenience when you wish to write generic code that works with both * types of editors. * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface SyncMonacoBaseEditorContext< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends AsyncMonacoBaseEditorContext<TEditor, TEditorOpts> { /** * @returns The extender that was set for this monaco editor widget, if any. It can be used to customize * the editor via JavaScript. */ getExtender(): ExtenderBaseEditor< TEditor, TEditorOpts, never > | undefined; /** * Finds the current instance of the monaco editor, if it was created already. Use this to interact with the * editor via JavaScript. See also the * [monaco editor API docs](https://microsoft.github.io/monaco-editor/api/index.html). * @returns The current monaco editor instance. `undefined` in case the editor was not created yet. */ getMonaco(): TEditor | undefined; /** * Finds the initial options that were used for creating the Monaco editor. * @returns {TEditorOpts | undefined} The original editor options that were used when the editor was created. * When you updated the options manually at a later point in time, these changes will not be reflected in the * value returned by this method. When the editor options were not created yet, returns `undefined`. */ getMonacoOptions(): Readonly<TEditorOpts> | undefined; /** * Gets the value of this editor immediately, without a promise. This is possible only for the * inline editor, hence why this method only exists on the inline editor. May be called as soon * as this widget is accessible, even when the monaco editor was not loaded or initialized yet. * @returns The current value of this editor. */ getValueNow(): string; /** * Sets the value on the editor now, synchronously. This is possible only for the inline editor, * hence why this method only exists on the inline editor. May be called as soon as this widget * is accessible, even when the monaco editor was not loaded or initialized yet. * @param value The new value for the editor. */ setValueNow(value: string): void; /** * Calls the given handler with the current Monaco editor instance if it exists. * @template TReturn Type of the return value of the given handler. * @param handler Handler that is invoked with the current monaco editor instance. * @param defaultReturnValue Default value that is returned when no editor exists currently. * @returns The return value of the handler, or `undefined` if no editor exists. * @throws When the handler throws an error. */ withMonaco<TReturn>(handler: (editor: TEditor) => TReturn, defaultReturnValue: TReturn): TReturn; /** * Calls the given handler with the current Monaco editor instance if it exists and catches possible errors. * @template TReturn Type of the return value of the given handler. * @param handler Handler that is invoked with the current monaco editor instance. * @param defaultReturnValue Default value that is returned when no editor exists currently, or when the * handler throws. * @returns The return value of the handler, or the default return value if either no editor exists or the * handler throws an error. */ tryWithMonaco<TReturn>(handler: (editor: TEditor) => TReturn, defaultReturnValue: TReturn): TReturn; } /** * Interface for objects that provide synchronous access to a Monaco code editor instance, such as the widget * instance for the inline Monaco editor. Note that objects that provide synchronous access also implement the * asynchronous interface for convenience when you wish to write generic code that works with both types of * editors. */ interface SyncMonacoCodeEditorContext extends SyncMonacoBaseEditorContext< import("monaco-editor").editor.IStandaloneCodeEditor, import("monaco-editor").editor.IStandaloneEditorConstructionOptions >, AsyncMonacoCodeEditorContext { // override with more specific types getWidgetOptions(): Partial< PrimeFaces.widget.ExtMonacoBaseEditorCfgBase< import("monaco-editor").editor.IStandaloneEditorConstructionOptions > & PrimeFaces.widget.ExtMonacoCodeEditorCfgBase >; } /** * Interface for objects that provide synchronous access to a Monaco diff editor instance, such as the widget * instance for the inline Monaco diff editor. Note that objects that provide synchronous access also implement * the asynchronous interface for convenience when you wish to write generic code that works with both types of * editors. */ interface SyncMonacoDiffEditorContext extends SyncMonacoBaseEditorContext< import("monaco-editor").editor.IStandaloneDiffEditor, import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions >, AsyncMonacoDiffEditorContext { /** * Gets the value of the original editor immediately, without a promise. This is possible only for the * inline editor, hence why this method only exists on the inline editor. May be called as soon * as this widget is accessible, even when the monaco editor was not loaded or initialized yet. * @returns The current value of this editor. */ getOriginalValueNow(): string; /** * Sets the value on the original editor now, synchronously. This is possible only for the inline editor, * hence why this method only exists on the inline editor. May be called as soon as this widget * is accessible, even when the monaco editor was not loaded or initialized yet. * @param value The new value for the editor. */ setOriginalValueNow(value: string): void; // override with more specific types getWidgetOptions(): Partial< PrimeFaces.widget.ExtMonacoBaseEditorCfgBase< import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions > & PrimeFaces.widget.ExtMonacoDiffEditorCfgBase >; } // === Monaco extender /** * An extender object to further customize the Monaco code or diff editor via JavaScript. Specified via the * `extender` attribute on the `<p:monacoEditor />`, `<p:monacoDiffEditor />`, `<p:monacoEditorFramed />`, or * `<p:monacoDiffEditorFramed />` tag. * * All callback methods in the extender are optional, if not specified, corresponding defaults are used. * * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. * @template TContext Type of the context object that is passed to all callback methods. */ interface ExtenderBaseEditor< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends Readonly<import("monaco-editor").editor.IEditorOptions>, TContext extends AsyncMonacoBaseEditorContext<TEditor, TEditorOpts> > { /** * This method is called after the editor was created. * @param context The current context object. * @param wasLibLoaded `true` if the monaco editor library was reloaded, `false` otherwise. In case it was * reloaded, you may want to setup some language defaults again. */ afterCreate?: (context: TContext, wasLibLoaded: boolean) => void; /** * Called after the editor was destroyed; and also when updating a component via AJAX. * @param context The current context object. Note that you should not use it to retrieve the monaco editor * instance, as the editor has already been destroyed. */ afterDestroy?: (context: TContext) => void; /** * Called before monaco editor is created. This method is passed the current options object that would be used * to initialize the monaco editor. * * If this callback does not return a value, the options that were passed are used. You may modify the * options in-place. * * If it returns a new options object, that options object is used. * * If it returns a Thenable or Promise, the monaco editor is created only once the Promise resolves * (successfully). * If the Promise returns a new options object, these options are used to create the editor. * * See * [IStandaloneEditorConstructionOptions](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandaloneeditorconstructionoptions.html) * or * [IStandaloneDiffEditorConstructionOptions](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.istandalonediffeditorconstructionoptions.html) * for all editor options. * * @param context The current context object. Note that you should not use it to retrieve the monaco editor * instance, as the editor was not created yet. * @param options The current options that would be used to create the editor. * @param wasLibLoaded `true` if the monaco editor library was reloaded, `false` otherwise. In case it was * reloaded, you may want to setup some language defaults again. * @returns Either `undefined` to use the options as passed; a new options object to be used for creating the * editor; or a Promise that may return the new options. */ beforeCreate?: ( context: TContext, options: TEditorOpts, wasLibLoaded: boolean ) => import("monaco-editor").languages.ProviderResult<TEditorOpts>; /** * Called before the editor is destroyed, eg. when updating a component via AJAX. * @param context The current context object. */ beforeDestroy?: (context: TContext) => void; /** * Called when a worker for additional language support needs to be created. By default, monaco editor ships with * the workers for JSON, CSS, HTML, and TYPESCRIPT. The label is the name of the language, eg. `css` or * `javascript`. This method must return the worker to be used for the given language. * * @param context The current context object. Note that you should not use it to retrieve the monaco editor * instance, as the editor was not created yet. * @param moduleId Module ID for the worker. Useful only with the AMD version, can be ignored. * @param label Label of the language for which to create the worker. * @returns The worker to be used for the given code language. */ createWorker?: (context: TContext, moduleId: string, label: string) => Worker; /** * Called when monaco editor is created. May return an object with services that should be overridden. See * [here on github](https://github.com/Microsoft/monaco-editor/issues/935#issuecomment-402174095) for details * on the available services. * @param context The current context object. Note that you should not use it to retrieve the monaco editor * instance, as the editor was not created yet. * @param options The options that will be used to create the editor. and must not be changed. * @returns The override options to be used. If `undefined` is returned, no editor override services are used. */ createEditorOverrideServices?: ( context: TContext, options: Readonly<TEditorOpts> ) => import("monaco-editor").editor.IEditorOverrideServices | undefined; /** * Called when the model needs to be fetched. The default implementation attempts to find an existing model for * the given URI in the monaco store (`import("monaco-editor").editor.getModel`). If it cannot be found, it * creates a new model (`import("monaco-editor").editor.createModel`). Finally it sets the default value on the * model. This method can be used to create a custom when necessary, with possibly a different URI. * * If you implement this callback, you SHOULD set the initial value (`options.value`) on the model, it will NOT * be set automatically. * @param context The current context object. Note that you should not use it to retrieve the monaco editor * instance, as the editor was not created yet. * @param options Options with the default URI, the current value, and the editor configuration. * @returns The retrieved or created model. When `undefined`, the default mechanism to create the model is used. */ createModel?: ( context: TContext, options: CreateModelOptions<TEditorOpts> ) => import("monaco-editor").editor.ITextModel | undefined } /** * An extender object to further customize the Monaco code editor via JavaScript. Specified via the `extender` * attribute on the `<p:monacoEditor />` or `<p:monacoEditorFramed />` tag. * * All callback methods in the extender are optional, if not specified, corresponding defaults are used. * * @template TContext Type of the context object that is passed to all callback methods. */ interface ExtenderCodeEditor<TContext extends AsyncMonacoCodeEditorContext> extends ExtenderBaseEditor< import("monaco-editor").editor.IStandaloneCodeEditor, import("monaco-editor").editor.IStandaloneEditorConstructionOptions, TContext > { } /** * An extender object to further customize the Monaco diff editor via JavaScript. Specified via the `extender` * attribute on the `<p:monacoDiffEditor />` or `<p:monacoDiffEditorFramed />` tag. * * All callback methods in the extender are optional, if not specified, corresponding defaults are used. * * @template TContext Type of the context object that is passed to all callback methods. */ interface ExtenderDiffEditor<TContext extends AsyncMonacoDiffEditorContext> extends ExtenderBaseEditor< import("monaco-editor").editor.IStandaloneDiffEditor, import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions, TContext > { /** * Called when the model needs to be created for the original editor. The default implementation * attempts to find an existing model for the given URI in the monaco store * (`import("monaco-editor").editor.getModel`). If it cannot be found, it creates a new model * (`import("monaco-editor").editor.createModel`). Finally it sets the default value on the model. This * method can be used to create a custom when necessary, with possibly a different URI. * * If you implement this callback, you SHOULD set the initial value (`options.value`) on the model, it will * NOT be set automatically. * @param context The current context object. Note that you should not use it to retrieve the monaco * editor instance, as the editor was not created yet. * @param options Options with the default URI, the current value, and the editor configuration. * @returns The retrieved or created model. When `undefined`, the default mechanism to create the model * is used. */ createOriginalModel?: ( context: TContext, options: CreateModelOptions<import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions> ) => import("monaco-editor").editor.ITextModel | undefined } /** * Extender for the inline Monaco code editor that has direct access to the editor. */ interface ExtenderCodeEditorInline extends ExtenderCodeEditor<widget.ExtMonacoCodeEditorInline> { } /** * Extender for the inline Monaco diff editor that has direct access to the editor. */ interface ExtenderDiffEditorInline extends ExtenderDiffEditor<widget.ExtMonacoDiffEditorInline> { } /** * Extender for the framed Monaco code editor that must communicate via postMessage with the editor. */ interface ExtenderCodeEditorFramed extends ExtenderCodeEditor<IframeCodeEditorContext> { } /** * Extender for the framed Monaco diff editor that must communicate via postMessage with the editor. */ interface ExtenderDiffEditorFramed extends ExtenderDiffEditor<IframeDiffEditorContext> { } /** * Interface for objects that provide access to the controller for the Monaco code editor running in an iframe. */ interface IframeCodeEditorContext extends SyncMonacoCodeEditorContext { /** * The extender that was set for this monaco editor widget. It can be used to customize the editor via * JavaScript. */ getExtender(): ExtenderCodeEditorFramed | undefined; } /** * Interface for objects that provide access to the controller for the Monaco diff editor running in an iframe. */ interface IframeDiffEditorContext extends SyncMonacoDiffEditorContext { /** * The extender that was set for this monaco diff editor widget. It can be used to customize the editor via * JavaScript. */ getExtender(): ExtenderDiffEditorFramed | undefined; } } } } // === PrimeFaces integration declare namespace PrimeFaces { namespace widget { // === Our widget integration without BaseWidgetCfg /** * Base configuration for all Monaco editor and diff editor widgets, without the properties from the * {@link BaseWidgetCfg}. These properties mostly correspond to the values set on the widget in your XHTML view. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoBaseEditorCfgBase<TEditorOpts extends import("monaco-editor").editor.IEditorOptions> { /** List of events for which a client or server side listener exists. */ availableEvents: string[]; /** * Whether the monaco editor is resized automatically. Please not that this requires the browser to * support for [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) */ autoResize: boolean; /** * Basename for the URI used for the model. */ basename: string; /** Map between a theme name and the data for that theme. */ customThemes: Record<string, import("monaco-editor").editor.IStandaloneThemeData>; /** * Directory (path) for the URI used for the model. */ directory: string; /** * The options that were used to construct the monaco editor instance. */ editorOptions: Readonly<TEditorOpts>; /** * Extension for the URI used for the model. */ extension: string; /** * The extender for enhancing the editor with client-side functionality. Exact type depends on whether the inlined * or framed editor is used. */ extender: unknown; /** * Whether the editor is disabled. */ disabled: boolean; /** * The code language tag, eg. `css` or `javascript`. See also `monaco.language.getLanguages`. */ language: string; /** * The code of the current UI language of the monaco editor, eg. `en` or `de`. */ locale: string; /** * Whether the editor is read-only. */ readonly: boolean; /** * Scheme (protocol) for the URI used for the model. */ scheme: string; /** * Tab index for the editor. */ tabIndex: number | undefined; /** * The Uri to the locale file with the translations for the current language. */ localeUrl: string; } // Individual configurations for code editor, diff editor, inline editor, framed editor /** * Base configuration for both Monaco editor widgets, without the properties from the {@link BaseWidgetCfg}. * These properties mostly correspond to the values set on the widget in your XHTML view. */ interface ExtMonacoCodeEditorCfgBase { } /** * Base configuration for both Monaco diff editor widgets, without the properties from the * {@link BaseWidgetCfg}. These properties mostly correspond to the values set on the widget in your XHTML * view. */ interface ExtMonacoDiffEditorCfgBase { /** * Whether the original editor is disabled. */ originalDisabled: boolean; /** * Whether the original editor is read-only. */ originalReadonly: boolean; /** * Whether the original editor is required. */ originalRequired: boolean; /** * Code language of original editor. */ originalLanguage: string; /** * Scheme (protocol) for the URI used for the original model. */ originalScheme: string; /** * Directory (path) for the URI used for the original model. */ originalDirectory: string; /** * Basename for the URI used for the original model. */ originalBasename: string; /** * Extension for the URI used for the original model. */ originalExtension: string; } /** * Base configuration for inline widgets, without the properties from the {@link BaseWidgetCfg}. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoInlineEditorCfgBase< TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends ExtMonacoBaseEditorCfgBase<TEditorOpts> { /** * Factory function that creates the extender for this monaco editor widget. Either `undefined` or JavaScript code * that evaluates to the extender. */ extender: () => ExtMonacoEditor.ExtenderCodeEditorInline | ExtMonacoEditor.ExtenderDiffEditorInline; /** * ID or PrimeFaces search expression for a DOM node. Places overflow widgets inside an external DOM node. * Defaults to an internal DOM node. This is resolved to a DOM node and passed on to the monaco editor editor * constructor option with the same name. */ overflowWidgetsDomNode: string; } /** * Base configuration for framed widgets, without the properties from the {@link BaseWidgetCfg}. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoFramedEditorCfgBase< TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends ExtMonacoBaseEditorCfgBase<TEditorOpts> { /** * URL to the extender for this monaco editor widget. Either `undefined` or an URL that points to a script file * that sets `window.MonacoEnvironment` to the extender to be used. */ extender: string; /** * Additional URL params that are added to the iframe URL. May be useful to pass additional parameters to the * extender script. */ iframeUrlParams: Record<string, string[]>; } // Combined configurations for code+inline, code+framed, diff+inline, diff+framed /** * Base configuration for {@link ExtMonacoCodeEditorInline} widget, without the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoCodeEditorInlineCfgBase extends ExtMonacoInlineEditorCfgBase<import("monaco-editor").editor.IStandaloneEditorConstructionOptions>, ExtMonacoCodeEditorCfgBase { /** * Factory function that creates the extender for this monaco editor widget. * Either `undefined` or JavaScript code that evaluates to the extender. */ extender: () => ExtMonacoEditor.ExtenderCodeEditorInline; } /** * Base configuration for {@link ExtMonacoDiffEditorInline} widget, without the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoDiffEditorInlineCfgBase extends ExtMonacoInlineEditorCfgBase<import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions>, ExtMonacoDiffEditorCfgBase { /** * Factory function that creates the extender for this monaco editor widget. * Either `undefined` or JavaScript code that evaluates to the extender. */ extender: () => ExtMonacoEditor.ExtenderDiffEditorInline; } /** * Base configuration for {@link ExtMonacoCodeEditorFramed} widget, without the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoCodeEditorFramedCfgBase extends ExtMonacoFramedEditorCfgBase<import("monaco-editor").editor.IStandaloneEditorConstructionOptions>, ExtMonacoCodeEditorCfgBase { } /** * Base configuration for {@link ExtMonacoDiffEditorFramed} widget, without the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoDiffEditorFramedCfgBase extends ExtMonacoFramedEditorCfgBase<import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions>, ExtMonacoDiffEditorCfgBase { } // === Complete widget integration with BaseWidgetCfg /** * Base configuration for both Monaco editor widgets, with the properties from the {@link BaseWidgetCfg}. * These properties mostly correspond to the values set on the widget in your XHTML view. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoBaseEditorCfg< TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends ExtMonacoBaseEditorCfgBase<TEditorOpts>, BaseWidgetCfg { } /** * Base configuration for the Monaco editor and diff editor inline widgets, with the properties from the * {@link BaseWidgetCfg}. * These properties mostly correspond to the values set on the widget in your XHTML view. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoBaseEditorInlineCfg< TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends ExtMonacoInlineEditorCfgBase<TEditorOpts>, BaseWidgetCfg { } /** * Base configuration for {@link ExtMonacoCodeEditorInline} widget, with the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoCodeEditorInlineCfg extends ExtMonacoCodeEditorInlineCfgBase, BaseWidgetCfg { } /** * Base configuration for {@link ExtMonacoDiffEditorInline} widget, with the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoDiffEditorInlineCfg extends ExtMonacoDiffEditorInlineCfgBase, BaseWidgetCfg { } /** * Base configuration for the Monaco editor and diff editor framed widgets, with the properties from the * {@link BaseWidgetCfg}. * These properties mostly correspond to the values set on the widget in your XHTML view. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. */ interface ExtMonacoBaseEditorFramedCfg< TEditorOpts extends import("monaco-editor").editor.IEditorOptions > extends ExtMonacoFramedEditorCfgBase<TEditorOpts>, BaseWidgetCfg { } /** * Base configuration for {@link ExtMonacoCodeEditorFramed} widget, with the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoCodeEditorFramedCfg extends ExtMonacoCodeEditorFramedCfgBase, BaseWidgetCfg { } /** * Base configuration for {@link ExtMonacoDiffEditorFramed} widget, with the properties from the {@link BaseWidgetCfg}. */ interface ExtMonacoDiffEditorFramedCfg extends ExtMonacoDiffEditorFramedCfgBase, BaseWidgetCfg { } // === Widget classes /** * __PrimeFacesExtensions MonacoEditorBase Widget__ * * The MonacoEditorBase widget is the base class for both the inline and the framed Monaco editor widget. * The Monaco code editor is an advanced code editor with support vor IntelliSense. * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. * @template TCfg Type of the widget configuration. */ abstract class ExtMonacoBaseEditor< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TCfg extends widget.ExtMonacoBaseEditorCfg<TEditorOpts> > extends DeferredWidget<TCfg> implements ExtMonacoEditor.AsyncMonacoBaseEditorContext<TEditor, TEditorOpts> { /** * @returns The HTML container element holding the editor. It exists even if the editor was not created yet. */ getEditorContainer(): JQuery; /** * @returns The hidden textarea holding the value of the editor (eg. the code being edited, this is also the * value that is sent when the form is submitted). */ getInput(): JQuery; // copied from the interface, see there for docs getWidgetId(): string; getWidgetOptions(): PartialWidgetCfg<TCfg>; getValue(): Promise<string>; invokeMonaco<K extends PrimeFaces.MatchingKeys<TEditor, (...args: never[]) => unknown>>( method: K, ...args: PrimeFaces.widget.ExtMonacoEditor.ParametersIfFn<TEditor[K]> ): Promise<Awaited<PrimeFaces.widget.ExtMonacoEditor.ReturnTypeIfFn<TEditor[K]>>>; invokeMonacoScript<TRetVal, TArgs extends any[]>(script: string | ((editor: TEditor, ...args: TArgs) => TRetVal), ...args: TArgs): Promise<Awaited<TRetVal>>; isReady(): boolean; layout(): Promise<void>; setValue(newValue: string): Promise<void>; whenReady(): Promise<this>; } /** * __PrimeFacesExtensions ExtMonacoEditorInlineBase Widget__ * * The ExtMonacoEditorInlineBase widget is the base for the inline variant of the Monaco editor widget and * diff editor widget. It renders the editor directly in the page where the widget is used. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. * @template TContext Type of the context that provides access to Monaco related functionality. * @template TExtender Type of the extender for customizing the Monaco instance. * @template TCfg Type of the widget configuration. */ abstract class ExtMonacoBaseEditorInline< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TContext extends ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext>, TCfg extends widget.ExtMonacoBaseEditorInlineCfg<TEditorOpts> > extends ExtMonacoBaseEditor<TEditor, TEditorOpts, TCfg> implements ExtMonacoEditor.SyncMonacoBaseEditorContext<TEditor, TEditorOpts> { /** * @returns The Monaco editor context which lets you interact with the Monaco editor. */ abstract getContext(): TContext; // copied from the interface, see there for docs getExtender(): Partial<TExtender> | undefined; getMonaco(): TEditor | undefined; getMonacoOptions(): Readonly<TEditorOpts> | undefined; getValueNow(): string; setValueNow(value: string): void; withMonaco<TReturn>(handler: (editor: TEditor) => TReturn, defaultReturnValue: TReturn): TReturn; tryWithMonaco<TReturn>(handler: (editor: TEditor) => TReturn, defaultReturnValue: TReturn): TReturn; } /** * __PrimeFacesExtensions MonacoEditorInline Widget__ * * The MonacoEditorInline widget is the inline variant of the Monaco editor widget. It renders * the editor directly in the page where the widget is used. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. */ class ExtMonacoCodeEditorInline extends ExtMonacoBaseEditorInline< import("monaco-editor").editor.IStandaloneCodeEditor, import("monaco-editor").editor.IStandaloneEditorConstructionOptions, ExtMonacoCodeEditorInline, ExtMonacoEditor.ExtenderCodeEditorInline, widget.ExtMonacoCodeEditorInlineCfg > implements ExtMonacoEditor.SyncMonacoCodeEditorContext { // copied from the abstract superclass, see there for docs getContext(): ExtMonacoCodeEditorInline; } /** * __PrimeFacesExtensions MonacoEditorInline Widget__ * * The MonacoEditorInline widget is the inline variant of the Monaco diff editor widget. It renders * the editor directly in the page where the widget is used. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. */ class ExtMonacoDiffEditorInline extends ExtMonacoBaseEditorInline< import("monaco-editor").editor.IStandaloneDiffEditor, import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions, ExtMonacoDiffEditorInline, ExtMonacoEditor.ExtenderDiffEditorInline, widget.ExtMonacoDiffEditorInlineCfg > implements ExtMonacoEditor.SyncMonacoDiffEditorContext { /** * @returns The hidden textarea holding the value of the original editor. */ getOriginalInput(): JQuery; // copied from the abstract superclass, see there for docs getContext(): ExtMonacoDiffEditorInline; // copied from the interface, see there for docs getOriginalValue(): Promise<string>; getOriginalValueNow(): string; setOriginalValue(newValue: string): Promise<void>; setOriginalValueNow(value: string): void; } /** * __PrimeFacesExtensions MonacoEditorFramedBase Widget__ * * The MonacoEditorInline widget is base for both framed variants of the Monaco editor widget. It renders * the editor inside an iframe for improved encapsulation. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. * @template TEditor Type of the editor instance, either the code editor or the diff editor. * @template TEditorOpts Type of the editor construction options, either for the code editor or the diff editor. * @template TContext Type of the context that provides access to Monaco related functionality. * @template TExtender Type of the extender for customizing the Monaco instance. * @template TCfg Type of the widget configuration. */ abstract class ExtMonacoBaseEditorFramed< TEditor extends import("monaco-editor").editor.IEditor, TEditorOpts extends import("monaco-editor").editor.IEditorOptions, TContext extends ExtMonacoEditor.AsyncMonacoBaseEditorContext<TEditor, TEditorOpts>, TExtender extends ExtMonacoEditor.ExtenderBaseEditor<TEditor, TEditorOpts, TContext>, TCfg extends widget.ExtMonacoBaseEditorFramedCfg<TEditorOpts> > extends ExtMonacoBaseEditor<TEditor, TEditorOpts, TCfg> { } /** * __PrimeFacesExtensions MonacoEditorFramed Widget__ * * The MonacoEditorInline widget is the framed variant of the Monaco editor widget. It renders * the editor inside an iframe for improved encapsulation. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. */ class ExtMonacoCodeEditorFramed extends ExtMonacoBaseEditorFramed< import("monaco-editor").editor.IStandaloneCodeEditor, import("monaco-editor").editor.IStandaloneEditorConstructionOptions, ExtMonacoEditor.IframeCodeEditorContext, ExtMonacoEditor.ExtenderCodeEditorFramed, widget.ExtMonacoCodeEditorFramedCfg > { } /** * __PrimeFacesExtensions MonacoDiffEditorFramed Widget__ * * The MonacoEditorInline widget is the framed variant of the Monaco diff editor widget. It renders * the editor inside an iframe for improved encapsulation. * * The Monaco code editor is an advanced code editor with support vor IntelliSense. */ class ExtMonacoDiffEditorFramed extends ExtMonacoBaseEditorFramed< import("monaco-editor").editor.IStandaloneDiffEditor, import("monaco-editor").editor.IStandaloneDiffEditorConstructionOptions, ExtMonacoEditor.IframeDiffEditorContext, ExtMonacoEditor.ExtenderDiffEditorFramed, widget.ExtMonacoDiffEditorFramedCfg > implements ExtMonacoEditor.AsyncMonacoDiffEditorContext { /** * @returns The hidden textarea holding the value of the original editor. */ getOriginalInput(): JQuery; // copied from the interface, see there for docs getOriginalValue(): Promise<string>; setOriginalValue(newValue: string): Promise<void>; } } }
the_stack
import { TestBed, inject, waitForAsync, ComponentFixture } from '@angular/core/testing'; import 'hammerjs'; import { Component } from '@angular/core'; import { By } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { TdDataTableColumnComponent } from './data-table-column/data-table-column.component'; import { TdDataTableRowComponent } from './data-table-row/data-table-row.component'; import { TdDataTableComponent, ITdDataTableColumn } from './data-table.component'; import { TdDataTableService } from './services/data-table.service'; import { CovalentDataTableModule } from './data-table.module'; import { NgModule, DebugElement } from '@angular/core'; import { MatCheckbox } from '@angular/material/checkbox'; import { MatPseudoCheckbox } from '@angular/material/core'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; describe('Component: DataTable', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [NoopAnimationsModule, FormsModule, CovalentDataTableModule], declarations: [ TdDataTableBasicTestComponent, TdDataTableSelectableTestComponent, TdDataTableRowClickTestComponent, TdDataTableSelectableRowClickTestComponent, TdDataTableModelTestComponent, TdDataTableCompareWithTestComponent, ], providers: [TdDataTableService], }); TestBed.compileComponents(); }), ); it('should set hidden and not get search hits and set it to false and get search results', (done: DoneFn) => { inject([TdDataTableService], (tdDataTableService: TdDataTableService) => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableBasicTestComponent); const component: TdDataTableBasicTestComponent = fixture.debugElement.componentInstance; component.columns[1].hidden = false; // backwards compatability test expect(tdDataTableService.filterData(component.data, '1452-2', true).length).toBe(1); fixture.detectChanges(); fixture.whenStable().then(() => { // check if there are no hidden columns expect( fixture.debugElement.queryAll(By.directive(TdDataTableColumnComponent)).filter((col: DebugElement) => { return (<any>(<HTMLElement>col.nativeElement).attributes).hidden; }).length, ).toBe(0); // check how many rows would return that contain Pork if no hidden columns expect( tdDataTableService.filterData( component.data, 'Pork', true, component.columns .filter((column: ITdDataTableColumn) => { return column.hidden === true; }) .map((column: ITdDataTableColumn) => { return column.name; }), ).length, ).toBe(1); component.columns[1].hidden = true; fixture.debugElement.query(By.directive(TdDataTableComponent)).componentInstance.refresh(); fixture.detectChanges(); fixture.whenStable().then(() => { // check if there are hidden columns expect( fixture.debugElement.queryAll(By.directive(TdDataTableColumnComponent)).filter((col: DebugElement) => { return (<any>(<HTMLElement>col.nativeElement).attributes).hidden; }).length, ).toBe(1); // check how many rows would return that contain Pork if the column is hidden expect( tdDataTableService.filterData( component.data, 'Pork', true, component.columns .filter((column: ITdDataTableColumn) => { return column.hidden === true; }) .map((column: ITdDataTableColumn) => { return column.name; }), ).length, ).toBe(0); done(); }); }); })(); }); it('should set filter and not get search hits and set it to false and get search results', (done: DoneFn) => { inject([TdDataTableService], (tdDataTableService: TdDataTableService) => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableBasicTestComponent); const component: TdDataTableBasicTestComponent = fixture.debugElement.componentInstance; component.columns[1].filter = false; fixture.detectChanges(); fixture.whenStable().then(() => { expect(component.columns[1].filter).toBe(false); // backwards compatability test expect(tdDataTableService.filterData(component.data, '1452-2', true).length).toBe(1); // check how many rows would return that contain Pork if the second column has filter = false expect( tdDataTableService.filterData( component.data, 'Pork', true, component.columns .filter((column: ITdDataTableColumn) => { return typeof column.filter !== undefined && column.filter === false; }) .map((column: ITdDataTableColumn) => { return column.name; }), ).length, ).toBe(0); // set the second column as filtered component.columns[1].filter = true; fixture.detectChanges(); fixture.whenStable().then(() => { // check how many rows would return that contain Pork if the seconds column has filter = true expect( tdDataTableService.filterData( component.data, 'Pork', true, component.columns .filter((column: ITdDataTableColumn) => { return typeof column.filter !== undefined && column.filter === false; }) .map((column: ITdDataTableColumn) => { return column.name; }), ).length, ).toBe(1); done(); }); }); })(); }); describe('selectable and multiple', () => { it('should not set the data input and not fail', (done: DoneFn) => { inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableSelectableTestComponent); const component: TdDataTableSelectableTestComponent = fixture.debugElement.componentInstance; component.selectable = true; component.multiple = true; fixture.detectChanges(); fixture.whenStable().then(() => { // if it finishes in means it didnt fail done(); }); })(); }); it('should select one and be in indeterminate state, select all and then unselect all', (done: DoneFn) => { inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableSelectableTestComponent); const component: TdDataTableSelectableTestComponent = fixture.debugElement.componentInstance; component.selectable = true; component.multiple = true; component.columns = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; component.data = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, { sku: '1452-1', item: 'Sirlone', price: 22.11 }, { sku: '1421-3', item: 'T-Bone', price: 51.15 }, ]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); fixture.whenStable().then(() => { const dataTableComponent: TdDataTableComponent = fixture.debugElement.query( By.directive(TdDataTableComponent), ).componentInstance; // check how many rows were rendered expect(fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent)).length).toBe(4); // check to see checkboxes states expect(dataTableComponent.indeterminate).toBeFalsy(); expect(dataTableComponent.allSelected).toBeFalsy(); // select a row with a click event fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[2] .triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its in indeterminate state expect(dataTableComponent.indeterminate).toBeTruthy(); expect(dataTableComponent.allSelected).toBeFalsy(); // select the rest of the rows by clicking in selectAll fixture.debugElement.query(By.directive(MatCheckbox)).triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its in indeterminate state and allSelected expect(dataTableComponent.indeterminate).toBeTruthy(); expect(dataTableComponent.allSelected).toBeTruthy(); // unselect all rows by clicking in unselect all fixture.debugElement.query(By.directive(MatCheckbox)).triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its not in indeterminate state and not allSelected expect(dataTableComponent.indeterminate).toBeFalsy(); expect(dataTableComponent.allSelected).toBeFalsy(); done(); }); }); }); }); }); })(); }); it('should be interminate when atleast one row is selected and allSelected when all rows are selected', (done: DoneFn) => { inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableSelectableTestComponent); const component: TdDataTableSelectableTestComponent = fixture.debugElement.componentInstance; component.selectable = true; component.multiple = true; component.columns = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; component.data = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, { sku: '1452-1', item: 'Sirlone', price: 22.11 }, { sku: '1421-3', item: 'T-Bone', price: 51.15 }, ]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); fixture.whenStable().then(() => { const dataTableComponent: TdDataTableComponent = fixture.debugElement.query( By.directive(TdDataTableComponent), ).componentInstance; // check how many rows were rendered expect(fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent)).length).toBe(4); // check to see checkboxes states expect(dataTableComponent.indeterminate).toBeFalsy(); expect(dataTableComponent.allSelected).toBeFalsy(); // select a row with a click event fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[2] .triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its in indeterminate state expect(dataTableComponent.indeterminate).toBeTruthy(); expect(dataTableComponent.allSelected).toBeFalsy(); // select the rest of the rows fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[0] .triggerEventHandler('click', new Event('click')); fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[1] .triggerEventHandler('click', new Event('click')); fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[3] .triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its in indeterminate state and allSelected expect(dataTableComponent.indeterminate).toBeTruthy(); expect(dataTableComponent.allSelected).toBeTruthy(); // unselect one of the rows fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[2] .triggerEventHandler('click', new Event('click')); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if its in indeterminate state and not allSelected expect(dataTableComponent.indeterminate).toBeTruthy(); expect(dataTableComponent.allSelected).toBeFalsy(); done(); }); }); }); }); }); })(); }); it('should shift click and select a range of rows', (done: DoneFn) => { inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableSelectableTestComponent); const component: TdDataTableSelectableTestComponent = fixture.debugElement.componentInstance; component.selectable = true; component.multiple = true; component.columns = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; component.data = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, { sku: '1452-1', item: 'Sirlone', price: 22.11 }, { sku: '1421-3', item: 'T-Bone', price: 51.15 }, ]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); fixture.whenStable().then(() => { const dataTableComponent: TdDataTableComponent = fixture.debugElement.query( By.directive(TdDataTableComponent), ).componentInstance; // check how many rows were rendered expect(fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent)).length).toBe(4); // check to see checkboxes states expect(dataTableComponent.indeterminate).toBeFalsy(); expect(dataTableComponent.allSelected).toBeFalsy(); fixture.detectChanges(); fixture.whenStable().then(() => { // select the first and last row with shift key also selected and should then select all checkboxes const clickEvent: MouseEvent = document.createEvent('MouseEvents'); // the 12th parameter below 'true' sets the shift key to be clicked at the same time as as the mouse click clickEvent.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, document.body.parentNode, ); fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[0].nativeElement.dispatchEvent(clickEvent); const shiftClickEvent: MouseEvent = document.createEvent('MouseEvents'); shiftClickEvent.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, document.body.parentNode, ); fixture.debugElement .queryAll(By.directive(MatPseudoCheckbox))[3] .nativeElement.dispatchEvent(shiftClickEvent); fixture.detectChanges(); fixture.whenStable().then(() => { // check to see if allSelected is true expect(dataTableComponent.allSelected).toBeTruthy(); done(); }); }); }); }); })(); }); it( 'should click on a row and see the rowClick Event', waitForAsync( inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableRowClickTestComponent); const component: TdDataTableRowClickTestComponent = fixture.debugElement.componentInstance; const eventSpy: jasmine.Spy = spyOn(component, 'clickEvent'); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent))[1].nativeElement.click(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(eventSpy.calls.count()).toBe(0); component.clickable = true; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent))[1].nativeElement.click(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(eventSpy.calls.count()).toBe(1); }); }); }); }); }), ), ); it( 'should click on a row and see the rowClick event only when clicking on row', waitForAsync( inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableSelectableRowClickTestComponent); const component: TdDataTableSelectableRowClickTestComponent = fixture.debugElement.componentInstance; component.clickable = true; component.selectable = true; const clickEventSpy: jasmine.Spy = spyOn(component, 'clickEvent'); const selectEventSpy: jasmine.Spy = spyOn(component, 'selectEvent'); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.debugElement.queryAll(By.directive(TdDataTableRowComponent))[1].nativeElement.click(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(clickEventSpy.calls.argsFor(0)[0].index).toBe(1); expect(clickEventSpy.calls.count()).toBe(1); expect(selectEventSpy.calls.count()).toBe(0); fixture.detectChanges(); fixture.whenStable().then(() => { fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[0].nativeElement.click(); fixture.detectChanges(); fixture.whenStable().then(() => { expect(selectEventSpy.calls.argsFor(0)[0].index).toBe(0); expect(clickEventSpy.calls.count()).toBe(1); expect(selectEventSpy.calls.count()).toBe(1); }); }); }); }); }), ), ); it( 'should load table and have first row checked by reference', waitForAsync( inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableModelTestComponent); const component: TdDataTableModelTestComponent = fixture.debugElement.componentInstance; component.selectedRows = [component.data[0]]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[0].componentInstance.state).toBe( 'checked', ); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[1].componentInstance.state).toBe( 'unchecked', ); }); }), ), ); it( 'should load table and have no rows checked by reference', waitForAsync( inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableModelTestComponent); const component: TdDataTableModelTestComponent = fixture.debugElement.componentInstance; component.selectedRows = [{ sku: '1452-2', item: 'Pork Chops', price: 32.11 }]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[0].componentInstance.state).toBe( 'unchecked', ); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[1].componentInstance.state).toBe( 'unchecked', ); }); }), ), ); it( 'should load table and have first row checked using [compareWith]', waitForAsync( inject([], () => { const fixture: ComponentFixture<any> = TestBed.createComponent(TdDataTableCompareWithTestComponent); const component: TdDataTableCompareWithTestComponent = fixture.debugElement.componentInstance; component.selectedRows = [{ sku: '1452-2', item: 'Pork Chops', price: 32.11 }]; fixture.detectChanges(); fixture.whenStable().then(() => { fixture.detectChanges(); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[0].componentInstance.state).toBe( 'checked', ); expect(fixture.debugElement.queryAll(By.directive(MatPseudoCheckbox))[1].componentInstance.state).toBe( 'unchecked', ); }); }), ), ); }); }); @Component({ template: ` <td-data-table [data]="data" [columns]="columns"></td-data-table> `, }) class TdDataTableBasicTestComponent { data: any[] = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, ]; columns: ITdDataTableColumn[] = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; } @Component({ template: ` <td-data-table [data]="data" [columns]="columns" [selectable]="selectable" [multiple]="multiple" [style.height.px]="200" ></td-data-table> `, }) class TdDataTableSelectableTestComponent { data: any; columns: any; selectable: boolean = false; multiple: boolean = false; } @Component({ template: ` <td-data-table [data]="data" [columns]="columns" [clickable]="clickable" (rowClick)="clickEvent()"></td-data-table> `, }) class TdDataTableRowClickTestComponent { data: any[] = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, ]; columns: ITdDataTableColumn[] = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; clickable: boolean = false; clickEvent(): void { /* noop */ } } @Component({ template: ` <td-data-table [data]="data" [columns]="columns" [selectable]="selectable" [clickable]="clickable" (rowClick)="clickEvent($event)" (rowSelect)="selectEvent($event)" ></td-data-table> `, }) class TdDataTableSelectableRowClickTestComponent { data: any[] = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, ]; columns: ITdDataTableColumn[] = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; selectable: boolean = false; clickable: boolean = false; clickEvent(event: any): void { /* noop */ } selectEvent(event: any): void { /* noop */ } } @Component({ template: ` <td-data-table [data]="data" [columns]="columns" [selectable]="true" [(ngModel)]="selectedRows"></td-data-table> `, }) class TdDataTableModelTestComponent { data: any[] = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, ]; columns: ITdDataTableColumn[] = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; selectedRows: any[]; } @Component({ template: ` <td-data-table [data]="data" [columns]="columns" [selectable]="true" [(ngModel)]="selectedRows" [compareWith]="compareWith" ></td-data-table> `, }) class TdDataTableCompareWithTestComponent { data: any[] = [ { sku: '1452-2', item: 'Pork Chops', price: 32.11 }, { sku: '1421-0', item: 'Prime Rib', price: 41.15 }, ]; columns: ITdDataTableColumn[] = [ { name: 'sku', label: 'SKU #' }, { name: 'item', label: 'Item name' }, { name: 'price', label: 'Price (US$)', numeric: true }, ]; selectedRows: any[]; compareWith: (row: any, model: any) => boolean = (row: any, model: any) => { return row.sku === model.sku; }; }
the_stack
* @module Logging */ import { BentleyError, IModelStatus, LoggingMetaData } from "./BentleyError"; import { BentleyLoggerCategory } from "./BentleyLoggerCategory"; import { IDisposable } from "./Disposable"; /** Defines the *signature* for a log function. * @public */ export type LogFunction = (category: string, message: string, metaData: LoggingMetaData) => void; /** Use to categorize logging messages by severity. * @public */ export enum LogLevel { /** Tracing and debugging - low level */ Trace, /** Information - mid level */ Info, /** Warnings - high level */ Warning, /** Errors - highest level */ Error, /** Higher than any real logging level. This is used to turn a category off. */ None, } /** Identifies a logging category and the LogLevel that should be used for it. The LogLevel is specified by its string name. * @public */ export interface LoggerCategoryAndLevel { category: string; logLevel: string; } /** Specifies logging levels, including the default logging level and a set of categories and levels for them. * @public */ export interface LoggerLevelsConfig { defaultLevel?: string; categoryLevels?: LoggerCategoryAndLevel[]; } /** Logger allows libraries and apps to report potentially useful information about operations, and it allows apps and users to control * how or if the logged information is displayed or collected. See [Learning about Logging]($docs/learning/common/Logging.md). * @public */ export class Logger { protected static _logError: LogFunction | undefined; protected static _logWarning: LogFunction | undefined; protected static _logInfo: LogFunction | undefined; protected static _logTrace: LogFunction | undefined; private static _categoryFilter: Map<string, LogLevel> = new Map<string, LogLevel>(); private static _minLevel: LogLevel | undefined = undefined; /** Should the call stack be included when an exception is logged? */ public static logExceptionCallstacks = false; /** All static metadata is combined with per-call metadata and stringified in every log message. * Static metadata can either be an object or a function that returns an object. * Use a key to identify entries in the map so the can be removed individually. * @internal */ public static staticMetaData = new Map<string, LoggingMetaData>(); /** Initialize the logger streams. Should be called at application initialization time. */ public static initialize(logError?: LogFunction, logWarning?: LogFunction, logInfo?: LogFunction, logTrace?: LogFunction): void { Logger._logError = logError; Logger._logWarning = logWarning; Logger._logInfo = logInfo; Logger._logTrace = logTrace; Logger.turnOffLevelDefault(); Logger.turnOffCategories(); } /** Initialize the logger to output to the console. */ public static initializeToConsole(): void { const logConsole = (level: string) => (category: string, message: string, metaData: LoggingMetaData) => console.log(`${level} | ${category} | ${message} ${Logger.stringifyMetaData(metaData)}`); // eslint-disable-line no-console Logger.initialize(logConsole("Error"), logConsole("Warning"), logConsole("Info"), logConsole("Trace")); } /** merge the supplied metadata with all static metadata into one object */ public static getMetaData(metaData?: LoggingMetaData): object { const metaObj = {}; for (const meta of Logger.staticMetaData) { const val = BentleyError.getMetaData(meta[1]); if (val) Object.assign(metaObj, val); } Object.assign(metaObj, BentleyError.getMetaData(metaData)); // do this last so user supplied values take precedence return metaObj; } /** stringify the metadata for a log message by merging the supplied metadata with all static metadata into one object that is then `JSON.stringify`ed. */ public static stringifyMetaData(metaData?: LoggingMetaData): string { const metaObj = this.getMetaData(metaData); return Object.keys(metaObj).length > 0 ? JSON.stringify(metaObj) : ""; } /** Set the least severe level at which messages should be displayed by default. Call setLevel to override this default setting for specific categories. */ public static setLevelDefault(minLevel: LogLevel): void { Logger._minLevel = minLevel; } /** Set the minimum logging level for the specified category. The minimum level is least severe level at which messages in the * specified category should be displayed. */ public static setLevel(category: string, minLevel: LogLevel) { Logger._categoryFilter.set(category, minLevel); } /** Interpret a string as the name of a LogLevel */ public static parseLogLevel(str: string): LogLevel { switch (str.toUpperCase()) { case "EXCEPTION": return LogLevel.Error; case "FATAL": return LogLevel.Error; case "ERROR": return LogLevel.Error; case "WARNING": return LogLevel.Warning; case "INFO": return LogLevel.Info; case "TRACE": return LogLevel.Trace; case "DEBUG": return LogLevel.Trace; } return LogLevel.None; } /** Set the log level for multiple categories at once. Also see [[validateProps]] */ public static configureLevels(cfg: LoggerLevelsConfig) { Logger.validateProps(cfg); if (cfg.defaultLevel !== undefined) { this.setLevelDefault(Logger.parseLogLevel(cfg.defaultLevel)); } if (cfg.categoryLevels !== undefined) { for (const cl of cfg.categoryLevels) { this.setLevel(cl.category, Logger.parseLogLevel(cl.logLevel)); } } } private static isLogLevel(v: string) { return LogLevel.hasOwnProperty(v); } /** Check that the specified object is a valid LoggerLevelsConfig. This is useful when reading a config from a .json file. */ public static validateProps(config: any) { const validProps = ["defaultLevel", "categoryLevels"]; for (const prop of Object.keys(config)) { if (!validProps.includes(prop)) throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig - unrecognized property: ${prop}`); if (prop === "defaultLevel") { if (!Logger.isLogLevel(config.defaultLevel)) throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.defaultLevel must be a LogLevel. Invalid value: ${JSON.stringify(config.defaultLevel)}`); } else if (prop === "categoryLevels") { const value = config[prop]; if (!Array.isArray(value)) throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels must be an array. Invalid value: ${JSON.stringify(value)}`); for (const item of config[prop]) { if (!item.hasOwnProperty("category") || !item.hasOwnProperty("logLevel")) throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item must be a LoggerCategoryAndLevel {category: logLevel:}. Invalid value: ${JSON.stringify(item)}`); if (!Logger.isLogLevel(item.logLevel)) throw new BentleyError(IModelStatus.BadArg, `LoggerLevelsConfig.categoryLevels - each item's logLevel property must be a LogLevel. Invalid value: ${JSON.stringify(item.logLevel)}`); } } } } /** Get the minimum logging level for the specified category. */ public static getLevel(category: string): LogLevel | undefined { // Prefer the level set for this category specifically const minLevelForThisCategory = Logger._categoryFilter.get(category); if (minLevelForThisCategory !== undefined) return minLevelForThisCategory; // Fall back on the level set for the parent of this category. const parent = category.lastIndexOf("."); if (parent !== -1) return Logger.getLevel(category.slice(0, parent)); // Fall back on the default level. return Logger._minLevel; } /** Turns off the least severe level at which messages should be displayed by default. * This turns off logging for all messages for which no category minimum level is defined. */ public static turnOffLevelDefault(): void { Logger._minLevel = undefined; } /** Turns off all category level filters previously defined with [[Logger.setLevel]]. */ public static turnOffCategories(): void { Logger._categoryFilter.clear(); } /** Check if messages in the specified category should be displayed at this level of severity. */ public static isEnabled(category: string, level: LogLevel): boolean { const minLevel = Logger.getLevel(category); return (minLevel !== undefined) && (level >= minLevel); } /** Log the specified message to the **error** stream. * @param category The category of the message. * @param message The message. * @param metaData Optional data for the message */ public static logError(category: string, message: string, metaData?: LoggingMetaData): void { if (Logger._logError && Logger.isEnabled(category, LogLevel.Error)) Logger._logError(category, message, metaData); } private static getExceptionMessage(err: unknown): string { const stack = Logger.logExceptionCallstacks ? `\n${BentleyError.getErrorStack(err)}` : ""; return BentleyError.getErrorMessage(err) + stack; } /** Log the specified exception. The special "ExceptionType" property will be added as metadata, * in addition to any other metadata that may be supplied by the caller, unless the * metadata supplied by the caller already includes this property. * @param category The category of the message. * @param err The exception object. * @param log The logger output function to use - defaults to Logger.logError * @param metaData Optional data for the message */ public static logException(category: string, err: any, log: LogFunction = Logger.logError): void { log(category, Logger.getExceptionMessage(err), () => { return { ...BentleyError.getErrorMetadata(err), exceptionType: err.constructor.name }; }); } /** Log the specified message to the **warning** stream. * @param category The category of the message. * @param message The message. * @param metaData Optional data for the message */ public static logWarning(category: string, message: string, metaData?: LoggingMetaData): void { if (Logger._logWarning && Logger.isEnabled(category, LogLevel.Warning)) Logger._logWarning(category, message, metaData); } /** Log the specified message to the **info** stream. * @param category The category of the message. * @param message The message. * @param metaData Optional data for the message */ public static logInfo(category: string, message: string, metaData?: LoggingMetaData): void { if (Logger._logInfo && Logger.isEnabled(category, LogLevel.Info)) Logger._logInfo(category, message, metaData); } /** Log the specified message to the **trace** stream. * @param category The category of the message. * @param message The message. * @param metaData Optional data for the message */ public static logTrace(category: string, message: string, metaData?: LoggingMetaData): void { if (Logger._logTrace && Logger.isEnabled(category, LogLevel.Trace)) Logger._logTrace(category, message, metaData); } } /** Simple performance diagnostics utility. * It measures the time from construction to disposal. On disposal it logs the routine name along with * the duration in milliseconds. * It also logs the routine name at construction time so that nested calls can be disambiguated. * * The timings are logged using the log category **Performance** and log severity [[LogLevel.INFO]]. * Enable those, if you want to capture timings. * @public */ export class PerfLogger implements IDisposable { private static _severity: LogLevel = LogLevel.Info; private _operation: string; private _metaData?: LoggingMetaData; private _startTimeStamp: number; public constructor(operation: string, metaData?: LoggingMetaData) { this._operation = operation; this._metaData = metaData; if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity)) { this._startTimeStamp = 0; return; } Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},START`, this._metaData); this._startTimeStamp = new Date().getTime(); // take timestamp } private logMessage(): void { const endTimeStamp: number = new Date().getTime(); if (!Logger.isEnabled(BentleyLoggerCategory.Performance, PerfLogger._severity)) return; Logger.logInfo(BentleyLoggerCategory.Performance, `${this._operation},END`, () => { const mdata = this._metaData ? BentleyError.getMetaData(this._metaData) : {}; return { ...mdata, TimeElapsed: endTimeStamp - this._startTimeStamp, // eslint-disable-line @typescript-eslint/naming-convention }; }); } public dispose(): void { this.logMessage(); } }
the_stack
import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { Component, LOCALE_ID } from '@angular/core'; import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import { DOWN_ARROW, LEFT_ARROW, UP_ARROW, RIGHT_ARROW, HOME, END, ENTER } from '@angular/cdk/keycodes'; import { createGenericTestComponent, selectElements, dispatchEvent, dispatchKeyboardEvent } from '../../../test/util'; import { NglDatepickersModule } from './module'; const createTestComponent = (html?: string, detectChanges?: boolean) => createGenericTestComponent(TestComponent, html, detectChanges) as ComponentFixture<TestComponent>; // Microsoft Edge hack function removeNonPrintable(str: string) { return str.replace(/[^\x20-\x7E]+/g, ''); } export function getDayElements(element: HTMLElement): HTMLElement[] { return selectElements(element, '.slds-day'); } export function getDayHeaders(element: HTMLElement) { return selectElements(element, 'th').map(e => e.textContent.trim()).map(removeNonPrintable); } function getYearOptions(element: HTMLElement) { return selectElements(element, 'option'); } function buildArray(start: number, end: number) { const arr: string[] = []; while (start <= end) { arr.push(start++ + ''); } return arr; } function chooseYear(element: HTMLElement, year: number) { const select = <HTMLSelectElement>element.querySelector('select'); select.value = '' + year; dispatchEvent(select, 'change'); } function getMonthNavigationButtons(element: HTMLElement): HTMLButtonElement[] { return selectElements(element.querySelector('.slds-datepicker__filter_month'), 'button') as HTMLButtonElement[]; } function getPreviousButton(element: HTMLElement): HTMLButtonElement { const buttons = getMonthNavigationButtons(element); return buttons[0]; } function getNextButton(element: HTMLElement): HTMLButtonElement { const buttons = getMonthNavigationButtons(element); return buttons[1]; } function clickButton(element: HTMLElement, isNext = false) { const button = isNext ? getNextButton(element) : getPreviousButton(element); button.click(); } function dispatchKey(fixture: ComponentFixture<any>, key: number) { const table = fixture.nativeElement.querySelector('table.datepicker__month'); dispatchKeyboardEvent(table, 'keydown', key); fixture.detectChanges(); } function getTableRows(element: HTMLElement) { return selectElements(element, 'tbody > tr'); } function getTodayButton(fixture: ComponentFixture<any>): HTMLButtonElement { return fixture.nativeElement.querySelector('button.slds-text-link'); } function expectCalendar(fixture: ComponentFixture<TestComponent>, expectedDates: any[], expectedMonth: string, expectedYear: string) { const element = fixture.nativeElement; fixture.detectChanges(); return fixture.whenStable().then(() => { const dates = getTableRows(element).map((trElement: HTMLElement, row: number) => { return selectElements(trElement, 'td').map((td: HTMLElement, column: number) => { let text = td.textContent.trim(); if (td.classList.contains('slds-is-selected')) { text = '*' + text; } if (td.getAttribute('tabindex') === '0') { text += '+'; } if (td.classList.contains('slds-disabled-text')) { text += '-'; } if (td.classList.contains('slds-is-today')) { text += '^'; } return text; }); }); expect(dates).toEqual(expectedDates); const month = removeNonPrintable(element.querySelector('h2.slds-align-middle').textContent.trim()); expect(expectedMonth).toEqual(month); const year = (<HTMLSelectElement>element.querySelector('select.slds-select')).value; expect(expectedYear).toEqual(year); }); } export function expectYearOptions(element: HTMLElement, expectedYearFrom: number, expectedYearTo: number) { const expectedYears = buildArray(expectedYearFrom, expectedYearTo); expect(getYearOptions(element).map((e: HTMLOptionElement) => e.value)).toEqual(expectedYears); } describe('`Datepicker` Component', () => { beforeEach(() => TestBed.configureTestingModule({declarations: [TestComponent], imports: [NglDatepickersModule]})); let currentDate: Date; beforeEach(() => { currentDate = new Date(2005, 10, 9); // 9 November 2005 jasmine.clock().mockDate(currentDate); }); it('should render correctly', async(() => { const fixture = createTestComponent(); expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30+', '1-', '2-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ]); expectYearOptions(fixture.nativeElement, 1905, 2015); expect(getNextButton(fixture.nativeElement).getAttribute('title')).toEqual('Next Month'); expect(getPreviousButton(fixture.nativeElement).getAttribute('title')).toEqual('Previous Month'); }); })); it('render accessibility label for year select', async(() => { const fixture = createTestComponent(); const yearEl = (<HTMLSelectElement>fixture.nativeElement.querySelector('select.slds-select')); const labelEl = yearEl.parentElement.previousElementSibling; expect(yearEl.id).toEqual(labelEl.getAttribute('for')); })); it('should change view when input date is changing', async(() => { const fixture = createTestComponent(); fixture.componentInstance.date = new Date(2013, 7, 11); // 11 August 2013 expectCalendar(fixture, [ [ '28-', '29-', '30-', '31-', '1', '2', '3' ], [ '4', '5', '6', '7', '8', '9', '10' ], [ '*11+', '12', '13', '14', '15', '16', '17' ], [ '18', '19', '20', '21', '22', '23', '24' ], [ '25', '26', '27', '28', '29', '30', '31' ], ], 'August', '2013').then(() => { fixture.componentInstance.date = new Date(2014, 9, 23); // 23 October 2014 expectCalendar(fixture, [ [ '28-', '29-', '30-', '1', '2', '3', '4' ], [ '5', '6', '7', '8', '9', '10', '11' ], [ '12', '13', '14', '15', '16', '17', '18' ], [ '19', '20', '21', '22', '*23+', '24', '25' ], [ '26', '27', '28', '29', '30', '31', '1-' ], ], 'October', '2014'); }); })); it('does not change current view when model is cleared', async(() => { const fixture = createTestComponent(); fixture.componentInstance.date = null; expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '30+', '1-', '2-'], ], 'September', '2010'); })); it('should show current date if none is set', async(() => { jasmine.clock().mockDate(new Date(2013, 7, 11)); // 11 August 2013 const fixture = createTestComponent(null, false); fixture.componentInstance.date = null; expectCalendar(fixture, [ ['28-', '29-', '30-', '31-', '1', '2', '3'], ['4', '5', '6', '7', '8', '9', '10'], ['11+^', '12', '13', '14', '15', '16', '17'], ['18', '19', '20', '21', '22', '23', '24'], ['25', '26', '27', '28', '29', '30', '31'], ], 'August', '2013'); })); it('updates the model when a day is clicked', () => { const fixture = createTestComponent(); const days = getDayElements(fixture.nativeElement); days[25].click(); expect(fixture.componentInstance.dateChange).toHaveBeenCalledWith(new Date(2010, 8, 23)); }); it('do nothing when a disabled day is clicked', () => { const fixture = createTestComponent(); const days = getDayElements(fixture.nativeElement); days[1].click(); expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); }); it('moves to previous month correctly when button is clicked', async(() => { const fixture = createTestComponent(); clickButton(fixture.nativeElement, false); expectCalendar(fixture, [ ['1', '2', '3', '4', '5', '6', '7'], ['8', '9', '10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19', '20', '21'], ['22', '23', '24', '25', '26', '27', '28'], ['29', '30+', '31', '1-', '2-', '3-', '4-'], ], 'August', '2010').then(() => { expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); }); })); it('moves to next month correctly when button is clicked', async(() => { const fixture = createTestComponent(); clickButton(fixture.nativeElement, true); expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '*30-', '1', '2'], ['3', '4', '5', '6', '7', '8', '9'], ['10', '11', '12', '13', '14', '15', '16'], ['17', '18', '19', '20', '21', '22', '23'], ['24', '25', '26', '27', '28', '29', '30+'], ['31', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'October', '2010').then(() => { expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); }); })); it('should not "jump" months and keep current day in limits', async(() => { const fixture = createTestComponent(); fixture.componentInstance.date = new Date(2012, 0, 30); // 30 January 2012 fixture.detectChanges(); clickButton(fixture.nativeElement, true); expectCalendar(fixture, [ ['29-', '*30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29+', '1-', '2-', '3-'], ], 'February', '2012'); })); it('moves to selected year from dropdown', async(() => { const fixture = createTestComponent(); fixture.whenStable().then(() => { chooseYear(fixture.nativeElement, 2014); expectCalendar(fixture, [ [ '31-', '1', '2', '3', '4', '5', '6' ], [ '7', '8', '9', '10', '11', '12', '13' ], [ '14', '15', '16', '17', '18', '19', '20' ], [ '21', '22', '23', '24', '25', '26', '27' ], [ '28', '29', '30+', '1-', '2-', '3-', '4-' ], ], 'September', '2014'); }); })); it('should change year range based on selection', () => { jasmine.clock().mockDate(new Date(1983, 10, 7)); // 7 November 1983 const fixture = createTestComponent(); expectYearOptions(fixture.nativeElement, 1883, 1993); }); it('should change year range based on inputs', () => { jasmine.clock().mockDate(new Date(2005, 0, 1)); const fixture = createTestComponent(`<ngl-datepicker [date]="date" [relativeYearFrom]="-5" [relativeYearTo]="5"></ngl-datepicker>`); expectYearOptions(fixture.nativeElement, 2000, 2010); }); describe('keyboard navigation', () => { it('will be able to activate appropriate day', async(() => { const fixture = createTestComponent(); dispatchKey(fixture, DOWN_ARROW); expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '*30-', '1', '2'], ['3', '4', '5', '6', '7+', '8', '9'], ['10', '11', '12', '13', '14', '15', '16'], ['17', '18', '19', '20', '21', '22', '23'], ['24', '25', '26', '27', '28', '29', '30'], ['31', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'October', '2010').then(() => { dispatchKey(fixture, LEFT_ARROW); dispatchKey(fixture, LEFT_ARROW); return expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '*30-', '1', '2'], ['3', '4', '5+', '6', '7', '8', '9'], ['10', '11', '12', '13', '14', '15', '16'], ['17', '18', '19', '20', '21', '22', '23'], ['24', '25', '26', '27', '28', '29', '30'], ['31', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'October', '2010'); }).then(() => { dispatchKey(fixture, UP_ARROW); return expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28+', '29', '*30', '1-', '2-'], ], 'September', '2010'); }).then(() => { dispatchKey(fixture, RIGHT_ARROW); return expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29+', '*30', '1-', '2-'], ], 'September', '2010'); }); })); it('will be able to activate appropriate edge day', async(() => { const fixture = createTestComponent(); dispatchKey(fixture, HOME); expectCalendar(fixture, [ ['29-', '30-', '31-', '1+', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30', '1-', '2-'], ], 'September', '2010').then(() => { dispatchKey(fixture, END); return expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30+', '1-', '2-'], ], 'September', '2010'); }); })); it('will be able to select active day', () => { const fixture = createTestComponent(); dispatchKey(fixture, DOWN_ARROW); dispatchKey(fixture, LEFT_ARROW); dispatchKey(fixture, LEFT_ARROW); expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); dispatchKey(fixture, ENTER); expect(fixture.componentInstance.dateChange).toHaveBeenCalledWith(new Date(2010, 9, 5)); }); }); it('should render `Today` based on input', () => { currentDate = new Date(2014, 9, 23); // 23 October 2014 jasmine.clock().mockDate(currentDate); const fixture = createTestComponent(` <ngl-datepicker [date]="date" (dateChange)="dateChange($event)" [showToday]="showToday"></ngl-datepicker> `); fixture.componentInstance.showToday = true; fixture.detectChanges(); const todayEl = getTodayButton(fixture); expect(todayEl.textContent).toEqual('Today'); expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); todayEl.click(); expect(fixture.componentInstance.dateChange).toHaveBeenCalledWith(currentDate); fixture.componentInstance.showToday = false; fixture.detectChanges(); expect(getTodayButton(fixture)).toBeFalsy(); }); it('should support custom month and day names', async(() => { jasmine.clock().mockDate(new Date(2005, 10, 9)); // 9 November 2005 const fixture = createTestComponent(` <ngl-datepicker [date]="date" [monthNames]="customMonths" [dayNamesShort]="customDays" showToday="false"></ngl-datepicker> `); expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30+', '1-', '2-'], ], 'Sep', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7' ]); }); })); it('should support custom week start', async(() => { const fixture = createTestComponent(` <ngl-datepicker [date]="date" [firstDayOfWeek]="firstDayOfWeek" showToday="false"></ngl-datepicker> `); expectCalendar(fixture, [ ['30-', '31-', '1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12'], ['13', '14', '15', '16', '17', '18', '19'], ['20', '21', '22', '23', '24', '25', '26'], ['27', '28', '29', '*30+', '1-', '2-', '3-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]); fixture.componentInstance.firstDayOfWeek = 2; expectCalendar(fixture, [ ['31-', '1', '2', '3', '4', '5', '6'], ['7', '8', '9', '10', '11', '12', '13'], ['14', '15', '16', '17', '18', '19', '20'], ['21', '22', '23', '24', '25', '26', '27'], ['28', '29', '*30+', '1-', '2-', '3-', '4-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon' ]); }); }); })); it('should handle `firstDayOfWeek` as string attribute', async(() => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" firstDayOfWeek="1" showToday="false"></ngl-datepicker>`); expectCalendar(fixture, [ ['30-', '31-', '1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12'], ['13', '14', '15', '16', '17', '18', '19'], ['20', '21', '22', '23', '24', '25', '26'], ['27', '28', '29', '*30+', '1-', '2-', '3-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]); }); })); it('should handle when first day of week is after first day of month', async(() => { const fixture = createTestComponent(` <ngl-datepicker [date]="date" [firstDayOfWeek]="firstDayOfWeek" showToday="false"></ngl-datepicker> `, false); fixture.componentInstance.firstDayOfWeek = 3; expectCalendar(fixture, [ ['1', '2', '3', '4', '5', '6', '7'], ['8', '9', '10', '11', '12', '13', '14'], ['15', '16', '17', '18', '19', '20', '21'], ['22', '23', '24', '25', '26', '27', '28'], ['29', '*30+', '1-', '2-', '3-', '4-', '5-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue' ]); fixture.componentInstance.firstDayOfWeek = 4; expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '30-', '31-', '1'], ['2', '3', '4', '5', '6', '7', '8'], ['9', '10', '11', '12', '13', '14', '15'], ['16', '17', '18', '19', '20', '21', '22'], ['23', '24', '25', '26', '27', '28', '29'], ['*30+', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'September', '2010').then(() => { expect(getDayHeaders(fixture.nativeElement)).toEqual([ 'Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue', 'Wed' ]); }); }); })); describe('disabled dates', () => { let fixture; beforeEach(() => { fixture = createTestComponent(`<ngl-datepicker [date]="date" (dateChange)="dateChange($event)" [dateDisabled]="dateDisabled"></ngl-datepicker>`, false); fixture.componentInstance.dateDisabled = (d: Date) => { const day = d.getDay(); // Disable Saturday and Sunday return day === 0 || day === 6; }; fixture.detectChanges(); }); it('should be defined via input callback', () => { expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4-'], ['5-', '6', '7', '8', '9', '10', '11-'], ['12-', '13', '14', '15', '16', '17', '18-'], ['19-', '20', '21', '22', '23', '24', '25-'], ['26-', '27', '28', '29', '*30+', '1-', '2-'], ], 'September', '2010').then(() => { fixture.componentInstance.dateDisabled = null; fixture.detectChanges(); expectCalendar(fixture, [ ['29-', '30-', '31-', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '10', '11'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30+', '1-', '2-'], ], 'September', '2010'); }); }); it('should not be selected via click', () => { const days = getDayElements(fixture.nativeElement); days[6].click(); // 4th expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); }); it('should not be selected via today button', () => { jasmine.clock().mockDate(new Date(2013, 7, 11)); // Sunday const todayEl = getTodayButton(fixture); todayEl.click(); fixture.detectChanges(); expect(fixture.componentInstance.dateChange).not.toHaveBeenCalled(); // Move current view to today though expectCalendar(fixture, [ ['28-', '29-', '30-', '31-', '1', '2', '3-'], ['4-', '5', '6', '7', '8', '9', '10-'], ['11+-^', '12', '13', '14', '15', '16', '17-'], ['18-', '19', '20', '21', '22', '23', '24-'], ['25-', '26', '27', '28', '29', '30', '31-'], ], 'August', '2013'); }); }); describe('`min`', () => { it('should disable appropriate dates', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [min]="min"></ngl-datepicker>`); expectCalendar(fixture, [ ['29-', '30-', '31-', '1-', '2-', '3-', '4-'], ['5-', '6-', '7-', '8-', '9-', '10-', '11-'], ['12', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '*30+', '1-', '2-'], ], 'September', '2010'); }); it('should not allow move to earlier view ', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [min]="min"></ngl-datepicker>`); fixture.componentInstance.date = new Date(2009, 0, 1); expectCalendar(fixture, [ ['29-', '30-', '31-', '1-', '2-', '3-', '4-'], ['5-', '6-', '7-', '8-', '9-', '10-', '11-'], ['12+', '13', '14', '15', '16', '17', '18'], ['19', '20', '21', '22', '23', '24', '25'], ['26', '27', '28', '29', '30', '1-', '2-'], ], 'September', '2010'); }); it('should disable previous month button', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [min]="min"></ngl-datepicker>`); expect(getPreviousButton(fixture.nativeElement).disabled).toBe(true); fixture.componentInstance.min = null; fixture.detectChanges(); expect(getPreviousButton(fixture.nativeElement).disabled).toBe(false); }); it('should define minimum year on select menu', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [min]="min"></ngl-datepicker>`); expectYearOptions(fixture.nativeElement, 2010, 2015); fixture.componentInstance.min = new Date(1800, 10, 9); fixture.detectChanges(); expectYearOptions(fixture.nativeElement, 1800, 2015); }); }); describe('`max`', () => { it('should disable appropriate dates', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [max]="max"></ngl-datepicker>`); fixture.componentInstance.date = new Date(2010, 9, 15); // 15 October 2010 expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '30-', '1', '2'], ['3', '4', '5', '6', '7', '8', '9'], ['10', '11', '12', '13', '14', '*15+', '16'], ['17', '18', '19', '20', '21', '22', '23'], ['24', '25', '26-', '27-', '28-', '29-', '30-'], ['31-', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'October', '2010'); }); it('should not allow move to later view ', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [max]="max"></ngl-datepicker>`); fixture.componentInstance.date = new Date(2019, 0, 1); expectCalendar(fixture, [ ['26-', '27-', '28-', '29-', '30-', '1', '2'], ['3', '4', '5', '6', '7', '8', '9'], ['10', '11', '12', '13', '14', '15', '16'], ['17', '18', '19', '20', '21', '22', '23'], ['24', '25+', '26-', '27-', '28-', '29-', '30-'], ['31-', '1-', '2-', '3-', '4-', '5-', '6-'], ], 'October', '2010'); }); it('should disable next month button', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [max]="max"></ngl-datepicker>`); expect(getNextButton(fixture.nativeElement).disabled).toBe(false); fixture.componentInstance.date = new Date(2010, 9, 15); // 15 October 2010 fixture.detectChanges(); expect(getNextButton(fixture.nativeElement).disabled).toBe(true); fixture.componentInstance.max = null; fixture.detectChanges(); expect(getNextButton(fixture.nativeElement).disabled).toBe(false); }); it('should define maximum year on select menu', () => { const fixture = createTestComponent(`<ngl-datepicker [date]="date" [max]="max"></ngl-datepicker>`); expectYearOptions(fixture.nativeElement, 1905, 2010); fixture.componentInstance.max = new Date(2100, 10, 9); fixture.detectChanges(); expectYearOptions(fixture.nativeElement, 1905, 2100); }); }); describe('i18n', () => { registerLocaleData(localeFr); beforeEach(() => TestBed.configureTestingModule({ providers: [{ provide: LOCALE_ID, useValue: 'fr' }], })); it('should change day names, month names and first day of week', () => { const fixture = createTestComponent(); expectCalendar(fixture, [ ['30-', '31-', '1', '2', '3', '4', '5'], ['6', '7', '8', '9', '10', '11', '12'], ['13', '14', '15', '16', '17', '18', '19'], ['20', '21', '22', '23', '24', '25', '26'], ['27', '28', '29', '*30+', '1-', '2-', '3-'], ], 'septembre', '2010'); expect(getDayHeaders(fixture.nativeElement)).toEqual(['lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.', 'dim.']); }); }); }); @Component({ template: `<ngl-datepicker [date]="date" (dateChange)="dateChange($event)" showToday="false"></ngl-datepicker>`, }) export class TestComponent { date = new Date(2010, 8, 30); // 30 September 2010 showToday: boolean; dateChange = jasmine.createSpy('dateChange'); firstDayOfWeek = 1; customMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; customDays = [ 'D1', 'D2', 'D3', 'D4', 'D5', 'D6', 'D7' ]; dateDisabled: (date: Date) => boolean; min = new Date(2010, 8, 12); // 12 September 2010; max = new Date(2010, 9, 25); // 25 October 2010 }
the_stack
import { WebSocketServer as CWSServer, WebSocket } from '@clusterws/cws' import * as zlib from 'zlib' import { Client } from './Client' import { Player } from './Player' import { MetaData } from './MetaData' import { Command } from './Command' import { ConnectionError } from './models/Connection.model' import { Settings } from './models/Settings.model' import { Server } from './models/Server.model' import { ServerClientMessage, IServerClientMessage, ServerClient, IServerClient, IPlayerUpdate, ServerMessage, ConnectionDenied, Compression, Chat, Error as ErrorProto, IMeta } from './proto/ServerClientMessage' export const PLAYER_DATA_COMPRESSION_THRESHOLD = 3 export class WebSocketServer { public clients: Client[] = [] public players: Player[] = [] public gameMode: number public playerWithToken?: Player private readonly server: CWSServer private readonly metaData: MetaData = new MetaData() private readonly command: Command private ip?: string private readonly port: number private readonly name: string private readonly domain: string private readonly description: string private countryCode?: string public readonly passwordRequired: boolean public readonly password: string private readonly verbose: boolean constructor ( { port, gamemode, enableGamemodeVote, passwordRequired, password, name, domain, description, verbose }: Settings ) { this.gameMode = gamemode this.port = port this.name = name this.domain = domain this.description = description this.passwordRequired = passwordRequired this.password = password this.verbose = !!verbose this.command = new Command(enableGamemodeVote) this.onConnection = this.onConnection.bind(this) this.server = new CWSServer({ port: this.port }) this.metaData = new MetaData() this.clients = [] this.players = [] } public start (server?: Server) { this.ip = server ? server.ip : '' this.countryCode = server ? server.countryCode : 'LAN' console.info(`\nNet64+ ${process.env.VERSION} server successfully started!`) this.server.on('connection', this.onConnection) if (this.passwordRequired) { console.info('Password protection enabled') } } public addPlayer (player: Player): void { const playerId = player.client.id this.players[playerId] = player if (!this.playerWithToken) { this.grantNewServerToken(player) } this.broadcastPlayerListMessage() const activeUsers = this.players.filter(players => players).length console.info(`Active users: ${activeUsers}/24`) } public removePlayer (clientId: number): void { const playerToRemove = this.players[clientId] let shouldGrantNewToken = false if (playerToRemove === this.playerWithToken) { delete this.playerWithToken shouldGrantNewToken = true } delete this.players[clientId] if (shouldGrantNewToken) { this.grantNewServerToken() } this.broadcastPlayerListMessage() const activeUsers = this.players.filter(player => player).length console.info(`Active users: ${activeUsers}/24`) } private broadcastPlayerListMessage (): void { const playerMsg: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.PLAYER_LIST_UPDATE, playerListUpdate: { playerUpdates: this.generatePlayerUpdates() } } } const playerMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(playerMsg)).finish() this.broadcastMessageAll(playerMessage) } private generatePlayerUpdates (): IPlayerUpdate[] { return this.players .filter(player => player) .map(player => ({ player: { username: player.username, characterId: player.characterId }, playerId: player.client.id })) } public sendHandshake (client: Client): void { const handshake: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.HANDSHAKE, handshake: { playerId: client.id, ip: this.ip, port: this.port, domain: this.domain, name: this.name, description: this.description, countryCode: this.countryCode, gameMode: this.gameMode, playerList: { playerUpdates: this.generatePlayerUpdates() }, passwordRequired: this.passwordRequired } } } const handshakeMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(handshake)).finish() client.sendMessage(handshakeMessage) } public reorderPlayers (): void { const newClients: Client[] = [] const newPlayers: Player[] = [] let j = 1 for (const i in this.clients) { if (!this.clients[i]) continue newClients[j] = this.clients[i] newClients[j].id = j newPlayers[j++] = this.players[i] } this.clients = newClients this.players = newPlayers for (let id = 2; id < this.clients.length; id++) { this.clients[id].sendPlayerReorder(id) } } /** * Broadcast message to all authenticate clients. * * @param {Uint8Array} message - The message to broadcast */ public broadcastMessage (message: Uint8Array): void { this.players .filter(player => player) .forEach(({ client }) => { client.sendMessage(message) }) } /** * Broadcast message to all clients. * * @param {Uint8Array} message - The message to broadcast */ public broadcastMessageAll (message: Uint8Array): void { this.clients .filter(client => client) .forEach(client => { client.sendMessage(message) }) } public async broadcastData (): Promise<void> { const playerDataMessage = await this.getPlayerData() const metaDataMessage = this.getMetaData() for (const i in this.players) { const player = this.players[i] player.client.sendMessage(playerDataMessage) } if (metaDataMessage) { for (const i in this.players) { const player = this.players[i] player.client.sendMessage(metaDataMessage) } } } private async getPlayerData (): Promise<Uint8Array> { const playersWithPlayerData = this.players .filter(player => player && player.playerData[3] !== 0) const data = { messageType: ServerClient.MessageType.PLAYER_DATA, playerData: { dataLength: 0x1C, playerBytes: playersWithPlayerData .map(player => ({ playerId: player.client.id, playerData: player.playerData })) } } const playerData: IServerClientMessage = playersWithPlayerData.length >= PLAYER_DATA_COMPRESSION_THRESHOLD ? { compression: Compression.GZIP, compressedData: await this.getCompressedPlayerData(data) } : { compression: Compression.NONE, data } return ServerClientMessage.encode(ServerClientMessage.fromObject(playerData)).finish() } private getCompressedPlayerData (playerData: IServerClient): Promise<Buffer> { const dataBuffer = ServerClient.encode(ServerClient.fromObject(playerData)).finish() return new Promise((resolve, reject) => { zlib.gzip(dataBuffer as Buffer, (err, compressedDataBuffer) => { if (err) reject(err) resolve(compressedDataBuffer) }) }) } private getMetaData (): Uint8Array | undefined { const metas = this.metaData.getMetaData() if (metas.length === 0) return const metaData: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.PLAYER_DATA, metaData: { metaData: metas } } } return ServerClientMessage.encode(ServerClientMessage.fromObject(metaData)).finish() } public addMeta (meta: IMeta): void { this.metaData.addIfNotAlreadySent(meta) } public onGlobalChatMessage (client: Client, message: string) { console.info(`[${client.getName()}]: ${message}`) const chat: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.CHAT, chat: { chatType: Chat.ChatType.GLOBAL, message, senderId: client.id } } } const chatMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(chat)).finish() for (const i in this.players) { const player = this.players[i] player.client.sendMessage(chatMessage) } } public onPrivateChatMessage (client: Client, message: string, receiverId: number) { if (!this.clients[receiverId]) { throw new ConnectionError( `You were trying to send a private chat message, but no client with id ${receiverId} exists.`, ErrorProto.ErrorType.BAD_REQUEST ) } const chat: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.CHAT, chat: { chatType: Chat.ChatType.PRIVATE, message, senderId: client.id } } } const chatMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(chat)).finish() this.clients[receiverId].sendMessage(chatMessage) } public onCommandChatMessage (client: Client, message: string, args: string[]): void { switch (message) { case 'gamemode': this.command.onGameModeCommand(client, args) break default: this.onUnknownCommand(client) } } private onUnknownCommand (client: Client): void { const unknownCommand: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.CHAT, chat: { chatType: Chat.ChatType.COMMAND, message: 'Unknown command' } } } const unknownCommandMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(unknownCommand)).finish() client.sendMessage(unknownCommandMessage) } private grantNewServerToken (playerToGrant?: Player): void { if (playerToGrant) { this.grantTokenToPlayer(playerToGrant) return } for (let i = this.players.length; i >= 0; i--) { playerToGrant = this.players[i] if (!playerToGrant) continue this.grantTokenToPlayer(playerToGrant) this.clients[1] = playerToGrant.client this.players[1] = playerToGrant this.clients[1].id = 1 delete this.clients[i] delete this.players[i] return } } private grantTokenToPlayer (playerToGrant: Player): void { const serverToken: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.SERVER_MESSAGE, serverMessage: { messageType: ServerMessage.MessageType.PLAYER_REORDER, playerReorder: { playerId: 1, grantToken: true } } } } const serverTokenMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(serverToken)).finish() playerToGrant.client.sendMessage(serverTokenMessage) if (process.env.NODE_ENV === 'development' || this.verbose) { console.info(`New server token has been granted to ${playerToGrant.client.getName()}`) } this.playerWithToken = playerToGrant } private onConnection (ws: WebSocket): void { const id = this.getNextClientId() if (id == null) { this.sendServerFullMessage(ws) if (process.env.NODE_ENV === 'development' || this.verbose) { console.info(`Client [${ws._socket.remoteAddress}] connected, but server is full`) } return } if (process.env.NODE_ENV === 'development' || this.verbose) { console.info(`Client [${ws._socket.remoteAddress}] connected and received ID: ${id}`) } this.clients[id] = new Client(id, ws, this.verbose) } private getNextClientId (): number | null { for (let i = 1; i < 25; i++) { if (this.clients[i] == null) return i } return null } private sendServerFullMessage (ws: WebSocket): void { const serverFull: IServerClientMessage = { compression: Compression.NONE, data: { messageType: ServerClient.MessageType.SERVER_MESSAGE, serverMessage: { messageType: ServerMessage.MessageType.CONNECTION_DENIED, connectionDenied: { reason: ConnectionDenied.Reason.SERVER_FULL, serverFull: { maxPlayers: 24 } } } } } const serverFullMessage = ServerClientMessage.encode(ServerClientMessage.fromObject(serverFull)).finish() ws.send(Buffer.from(serverFullMessage), { binary: true }) } }
the_stack
import * as StartPure from './Start/StartPure'; import * as StartWithReact from './Start/StartWithReact'; /* -------------- Core --------------- */ import * as ActorComponent from './Core/ActorComponent'; import * as SceneComponentCompose from './Core/SceneComponentCompose'; import * as LifeCycle from './Core/LifeCycle'; import * as ErrorChain from './Core/ErrorChain'; import * as Timer from './Core/Timer'; import * as UnLinkReLink from './Core/UnLinkReLink'; /* -------------- Dispatch --------------- */ import * as SingleLevel from './Dispatch/SingleLevel'; import * as MultipleLevel from './Dispatch/MultipleLevel'; import * as MultipleWorld from './Dispatch/MultipleWorld'; import * as MultipleGame from './Dispatch/MultipleGame'; /* -------------- Material --------------- */ import * as PBRMaterial from './Material/PBRMaterial'; import * as ShaderMaterial from './Material/ShaderMaterial'; import * as RawShaderMaterial from './Material/RawShaderMaterial'; import * as ShaderChunk from './Material/ShaderChunk'; import * as MaterialExtension from './Material/MaterialExtension'; import * as MatScriptsInGlTF from './Material/MatScriptsInGlTF'; import * as KHRTechniqueWebgl from './Material/KHRTechniqueWebgl'; import * as GlobalUniformMaterial from './Material/GlobalUniformMaterial'; import * as CustomSemantic from './Material/CustomSemantic'; import * as CustomSpriteMaterial from './Material/CustomSpriteMaterial'; import * as RenderOptions from './Material/RenderOptions'; /* -------------- Camera --------------- */ import * as PerspectiveCamera from './Camera/PerspectiveCamera'; import * as OrthographicCamera from './Camera/OrthographicCamera'; import * as Skybox from './Camera/Skybox'; import * as ActorObserveControl from './Camera/ActorObserveControl'; import * as CameraOrbitControl from './Camera/CameraOrbitControl'; import * as CameraFreeControl from './Camera/CameraFreeControl'; import * as CaptureScreen from './Camera/CaptureScreen'; /* -------------- Light --------------- */ import * as AmbientLight from './Light/AmbientLight'; import * as DirectionalLight from './Light/DirectionalLight'; import * as PointLight from './Light/PointLight'; import * as SpotLight from './Light/SpotLight'; import * as Shadow from './Light/Shadow'; import * as Baking from './Light/Baking'; /* -------------- BSP --------------- */ import * as Box from './BSP/Box'; import * as Sphere from './BSP/Sphere'; import * as Plane from './BSP/Plane'; import * as Cylinder from './BSP/Cylinder'; import * as Morph from './BSP/Morph'; /* -------------- Event --------------- */ import * as EventBasic from './Event/Basic'; import * as EventCustomTrigger from './Event/CustomTrigger'; import * as EventGlobal from './Event/Global'; import * as EventPriorityAndPrevent from './Event/PriorityAndPrevent'; /* -------------- HID --------------- */ import * as HIDKeyboard from './HID/Keyboard'; import * as HIDMouse from './HID/Mouse'; import * as HIDTouch from './HID/Touch'; /* -------------- Resource --------------- */ import * as ImageLoader from './Resource/ImageLoader'; import * as TextureLoader from './Resource/TextureLoader'; import * as CubeTextureLoader from './Resource/CubeTextureLoader'; import * as AtlasLoader from './Resource/AtlasLoader'; import * as GlTFLoader from './Resource/GlTFLoader'; import * as ResourceFreeLoad from './Resource/FreeLoad'; import * as ResourceGLBLoad from './Resource/GLBLoad'; import * as ResourceCancel from './Resource/Cancel'; import * as GlTFMorph from './Resource/GlTFMorph'; import * as GlTFSkeletal from './Resource/GlTFSkeletal'; import * as ChangeCostume from './Resource/ChangeCostume'; import * as GlTFScriptBinding from './Resource/GlTFScriptBinding'; /* -------------- Render --------------- */ import * as Sprite from './Render/Sprite'; import * as Layers from './Render/Layers'; import * as RenderOrder from './Render/RenderOrder'; import * as Fog from './Render/Fog'; import * as Advance from './Render/Advance'; import * as Refraction from './Render/Refraction'; /* -------------- Atlas --------------- */ import * as AtlasBasic from './Atlas/Basic'; import * as AtlasAllocateRelease from './Atlas/AllocateRelease'; import * as AtlasFromGrid from './Atlas/FromGrid'; import * as AtlasFromTexture from './Atlas/FromTexture'; import * as AtlasGetTexture from './Atlas/GetTexture'; import * as AtlasFromGlTF from './Atlas/FromGlTF'; /* -------------- Animation --------------- */ import * as SpriteAnimation from './Animation/Sprite'; import * as ModelAnimation from './Animation/Model'; import * as TweenAnimation from './Animation/Tween'; import * as CustomAnimation from './Animation/Custom'; import * as EventsAnimation from './Animation/Events'; import * as CombinationAnimation from './Animation/Combination'; /* -------------- Physic --------------- */ import * as PhysicBase from './Physic/Base'; import * as PhysicCollisionEvents from './Physic/CollisionEvents'; import * as Disable from './Physic/Disable'; import * as Joint from './Physic/Joint'; import * as PhysicPick from './Physic/Pick'; /* -------------- HUD --------------- */ import * as DomHUD from './HUD/DomHUD'; import * as ReactHUD from './HUD/ReactHUD'; /* -------------- Player --------------- */ import * as PlayerBasic from './Player/Basic'; import * as PlayerAI from './Player/AI'; import * as PlayerPlayer from './Player/Player'; /* -------------- GPUParticleSystem --------------- */ import * as GPUEdgeEmitter from './GPUParticleSystem/EdgeEmitter'; import * as ParticlesAtlas from './GPUParticleSystem/Atlas'; import * as GPUWindEmitter from './GPUParticleSystem/WindEmitter'; import * as GPUSphereEmitter from './GPUParticleSystem/SphereEmitter'; import * as GPUHemisphericEmitter from './GPUParticleSystem/HemisphericEmitter'; import * as CustomTrajectory from './GPUParticleSystem/CustomTrajectory'; import * as GPUCircleEmitter from './GPUParticleSystem/CircleEmitter'; import * as GPURectangleEmitter from './GPUParticleSystem/RectangleEmitter'; import * as GPUConeEmitter from './GPUParticleSystem/ConeEmitter'; /* -------------- PostProcessing --------------- */ import * as Threshold from './PostProcessing/Threshold'; import * as LocalThreshold from './PostProcessing/LocalThreshold'; import * as Bloom from './PostProcessing/Bloom'; /* -------------- Audio --------------- */ import * as AudioBasic from './Audio/Basic'; import * as AudioMode from './Audio/Mode'; import * as AudioLazy from './Audio/Lazy'; import * as AudioSpace from './Audio/Space'; import * as AudioBGM from './Audio/BGM'; import * as AudioVolume from './Audio/Volume'; import * as AudioMultiListener from './Audio/MultiListener'; import * as AudioMultiSystem from './Audio/MultiSystem'; import * as AudioControl from './Audio/Control'; import * as AudioGlTF from './Audio/GlTF'; /* -------------- GUI --------------- */ import * as GUIBase from './GUI/Base'; import * as GUIBasicEvent from './GUI/BasicEvent'; import * as GUILabel from './GUI/Label-Button'; import * as GUISelection from './GUI/Selection'; import * as GUISlider from './GUI/Slider'; import * as GUICombineContainer from './GUI/Combine'; import * as GUIClip from './GUI/Clip'; import * as GUIList from './GUI/List'; import * as GUIScroll from './GUI/Scroll'; import * as GUIComplex from './GUI/Complex'; import * as GUIBitmapFont from './GUI/BitmapFont'; /* -------------- DebugTools --------------- */ import * as Inspector from './DebugTools/Inspector'; export interface II18NLabel { en: string; cn: string; } export interface IComponents { categories: {path: string, label: II18NLabel}[]; [path: string]: { path: string; label: II18NLabel; Component?: any; desc?: string; }[]; } export const components: IComponents = { categories: [ {path: 'start', label: {en: 'Start', cn: '开始'}}, {path: 'core', label: {en: 'Core', cn: '核心基础'}}, {path: 'dispatch', label: {en: 'Dispatch', cn: '场景调度'}}, {path: 'render', label: {en: 'Render', cn: '渲染'}}, {path: 'material', label: {en: 'Material', cn: '材质系统'}}, {path: 'atlas', label: {en: 'Atlas', cn: '图集'}}, {path: 'camera', label: {en: 'Camera', cn: '摄像机'}}, {path: 'light', label: {en: 'Light', cn: '灯光'}}, {path: 'bsp', label: {en: 'BSP', cn: '基础几何体'}}, {path: 'event', label: {en: 'Event', cn: '事件系统'}}, {path: 'hid', label: {en: 'HID', cn: '人体接口设备'}}, {path: 'resource', label: {en: 'Resource', cn: '资源管理'}}, {path: 'animation', label: {en: 'Animation', cn: '动画系统'}}, {path: 'physic', label: {en: 'Physic', cn: '物理系统'}}, {path: 'hud', label: {en: 'HUD', cn: '平视显示器'}}, {path: 'player', label: {en: 'Player', cn: '玩家系统'}}, {path: 'audio', label: {en: 'Audio', cn: '音频系统'}}, {path: 'gpu-particle-system', label: {en: 'GPUParticleSystem', cn: 'GPU粒子系统'}}, {path: 'post-processing-system', label: {en: 'PostProcessingSystem', cn: '后处理系统'}}, {path: 'gui', label: {en: 'GUI', cn: 'GUI系统'}}, {path: 'debug-tools', label: {en: 'DebugTools', cn: '调试工具'}} ], start: [ {path: 'start', ...StartPure}, {path: 'start-with-react', ...StartWithReact} ], core: [ {path: 'actor-component', ...ActorComponent}, {path: 'scene-component-compose', ...SceneComponentCompose}, {path: 'life-cycle', ...LifeCycle}, {path: 'unlink-relink', ...UnLinkReLink}, {path: 'error-chain', ...ErrorChain}, {path: 'timer', ...Timer} ], dispatch: [ {path: 'single-level', ...SingleLevel}, {path: 'multiple-level', ...MultipleLevel}, {path: 'multiple-world', ...MultipleWorld}, // {path: 'multiple-game', ...MultipleGame} ], render: [ {path: 'layers', ...Layers}, {path: '2d-sprite', ...Sprite}, {path: 'render-order', ...RenderOrder}, {path: 'fog', ...Fog}, {path: 'advance', ...Advance}, {path: 'refraction', ...Refraction} ], material: [ {path: 'pbr-material', ...PBRMaterial}, {path: 'shader-material', ...ShaderMaterial}, {path: 'raw-shader-material', ...RawShaderMaterial}, {path: 'shader-chunk', ...ShaderChunk}, {path: 'material-extension', ...MaterialExtension}, {path: 'mat-script-in-gltf', ...MatScriptsInGlTF}, {path: 'khr-technique-webgl', ...KHRTechniqueWebgl}, {path: 'global-uniform-material', ...GlobalUniformMaterial}, {path: 'custom-semantic', ...CustomSemantic}, {path: 'custom-sprite-material', ...CustomSpriteMaterial}, {path: 'render-options', ...RenderOptions} ], atlas: [ {path: 'basic', ...AtlasBasic}, {path: 'from-gird', ...AtlasFromGrid}, {path: 'from-texture', ...AtlasFromTexture}, {path: 'get-texture', ...AtlasGetTexture}, {path: 'from-gltf', ...AtlasFromGlTF}, {path: 'allocate-release', ...AtlasAllocateRelease} ], camera: [ {path: 'perspective-camera', ...PerspectiveCamera}, {path: 'orthographic-camera', ...OrthographicCamera}, {path: 'skybox', ...Skybox}, {path: 'actor-observe-control', ...ActorObserveControl}, {path: 'camera-orbit-control', ...CameraOrbitControl}, {path: 'camera-free-control', ...CameraFreeControl}, {path: 'capture-screen', ...CaptureScreen} ], light: [ {path: 'ambient-light', ...AmbientLight}, {path: 'directional-light', ...DirectionalLight}, {path: 'point-light', ...PointLight}, {path: 'spot-light', ...SpotLight}, {path: 'shadow', ...Shadow}, {path: 'baking', ...Baking} ], bsp: [ {path: 'box', ...Box}, {path: 'sphere', ...Sphere}, {path: 'plane', ...Plane}, {path: 'cylinder', ...Cylinder}, {path: 'morph', ...Morph} ], event: [ {path: 'basic', ...EventBasic}, {path: 'custom-trigger', ...EventCustomTrigger}, {path: 'global', ...EventGlobal}, {path: 'priority-and-prevent',...EventPriorityAndPrevent} ], hid: [ {path: 'keyboard', ...HIDKeyboard}, {path: 'mouse', ...HIDMouse}, {path: 'touch', ...HIDTouch} ], resource: [ {path: 'image-loader', ...ImageLoader}, {path: 'texture-loader', ...TextureLoader}, {path: 'cube-texture-loader', ...CubeTextureLoader}, {path: 'atlas-loader', ...AtlasLoader}, {path: 'gltf-loader', ...GlTFLoader}, {path: 'free-load', ...ResourceFreeLoad}, {path: 'glb-load', ...ResourceGLBLoad}, {path: 'cancel', ...ResourceCancel}, {path: 'gltf-morph', ...GlTFMorph}, {path: 'gltf-skeletal', ...GlTFSkeletal}, {path: 'change-costume', ...ChangeCostume}, {path: 'gltf-script-binding', ...GlTFScriptBinding} ], animation: [ {path: '2d-sprite', ...SpriteAnimation}, {path: 'model', ...ModelAnimation}, {path: 'tween', ...TweenAnimation}, {path: 'custom', ...CustomAnimation}, {path: 'events', ...EventsAnimation}, {path: 'combination', ...CombinationAnimation} ], physic: [ {path: 'base', ...PhysicBase}, {path: 'collision-events', ...PhysicCollisionEvents}, {path: 'pick', ...PhysicPick}, {path: 'disable', ...Disable}, {path: 'joint', ...Joint} ], hud: [ {path: 'dom-hud', ...DomHUD}, {path: 'react-hud', ...ReactHUD} ], player: [ {path: 'basic', ...PlayerBasic}, {path: 'ai', ...PlayerAI}, {path: 'player', ...PlayerPlayer} ], audio: [ {path: 'basic', ...AudioBasic}, {path: 'mode', ...AudioMode}, {path: 'lazy', ...AudioLazy}, {path: 'space', ...AudioSpace}, {path: 'bgm', ...AudioBGM}, {path: 'volume', ...AudioVolume}, {path: 'control', ...AudioControl}, {path: 'multi-listener', ...AudioMultiListener}, {path: 'multi-system', ...AudioMultiSystem}, {path: 'gltf', ...AudioGlTF} ], 'gpu-particle-system': [ {path: 'edge-emitter', ...GPUEdgeEmitter}, {path: 'particles-atlas', ...ParticlesAtlas}, {path: 'wind-emitter', ...GPUWindEmitter}, {path: 'sphere-emitter', ...GPUSphereEmitter}, {path: 'hemispheric-emitter', ...GPUHemisphericEmitter}, {path: 'custom-trajectory', ...CustomTrajectory}, {path: 'circle-emitter', ...GPUCircleEmitter}, {path: 'rectangle-emitter', ...GPURectangleEmitter}, {path: 'cone-emitter', ...GPUConeEmitter} ], 'post-processing-system': [ {path: 'threshold', ...Threshold}, {path: 'local-threshold', ...LocalThreshold}, {path: 'bloom', ...Bloom} ], gui: [ {path: 'base', ...GUIBase}, {path: 'basic-event', ...GUIBasicEvent}, {path: 'label', ...GUILabel}, {path: 'selection', ...GUISelection}, {path: 'slider', ...GUISlider}, {path: 'combine-container', ...GUICombineContainer}, {path: 'clip', ...GUIClip}, {path: 'list', ...GUIList}, {path: 'scroll', ...GUIScroll}, {path: 'complex', ...GUIComplex}, {path: 'bitmapfont', ...GUIBitmapFont} ], 'debug-tools': [ {path: 'inspector', ...Inspector} ] };
the_stack
namespace dragonBones { /** * - 2D Transform matrix. * @version DragonBones 3.0 * @language en_US */ /** * - 2D 转换矩阵。 * @version DragonBones 3.0 * @language zh_CN */ export class Matrix { /** * - The value that affects the positioning of pixels along the x axis when scaling or rotating an image. * @default 1.0 * @version DragonBones 3.0 * @language en_US */ /** * - 缩放或旋转图像时影响像素沿 x 轴定位的值。 * @default 1.0 * @version DragonBones 3.0 * @language zh_CN */ public a: number; /** * - The value that affects the positioning of pixels along the y axis when rotating or skewing an image. * @default 0.0 * @version DragonBones 3.0 * @language en_US */ /** * - 旋转或倾斜图像时影响像素沿 y 轴定位的值。 * @default 0.0 * @version DragonBones 3.0 * @language zh_CN */ public b: number; /** * - The value that affects the positioning of pixels along the x axis when rotating or skewing an image. * @default 0.0 * @version DragonBones 3.0 * @language en_US */ /** * - 旋转或倾斜图像时影响像素沿 x 轴定位的值。 * @default 0.0 * @version DragonBones 3.0 * @language zh_CN */ public c: number; /** * - The value that affects the positioning of pixels along the y axis when scaling or rotating an image. * @default 1.0 * @version DragonBones 3.0 * @language en_US */ /** * - 缩放或旋转图像时影响像素沿 y 轴定位的值。 * @default 1.0 * @version DragonBones 3.0 * @language zh_CN */ public d: number; /** * - The distance by which to translate each point along the x axis. * @default 0.0 * @version DragonBones 3.0 * @language en_US */ /** * - 沿 x 轴平移每个点的距离。 * @default 0.0 * @version DragonBones 3.0 * @language zh_CN */ public tx: number; /** * - The distance by which to translate each point along the y axis. * @default 0.0 * @version DragonBones 3.0 * @language en_US */ /** * - 沿 y 轴平移每个点的距离。 * @default 0.0 * @version DragonBones 3.0 * @language zh_CN */ public ty: number; /** * @private */ public constructor( a: number = 1.0, b: number = 0.0, c: number = 0.0, d: number = 1.0, tx: number = 0.0, ty: number = 0.0 ) { this.a = a; this.b = b; this.c = c; this.d = d; this.tx = tx; this.ty = ty; } public toString(): string { return "[object dragonBones.Matrix] a:" + this.a + " b:" + this.b + " c:" + this.c + " d:" + this.d + " tx:" + this.tx + " ty:" + this.ty; } /** * @private */ public copyFrom(value: Matrix): Matrix { this.a = value.a; this.b = value.b; this.c = value.c; this.d = value.d; this.tx = value.tx; this.ty = value.ty; return this; } /** * @private */ public copyFromArray(value: Array<number>, offset: number = 0): Matrix { this.a = value[offset]; this.b = value[offset + 1]; this.c = value[offset + 2]; this.d = value[offset + 3]; this.tx = value[offset + 4]; this.ty = value[offset + 5]; return this; } /** * - Convert to unit matrix. * The resulting matrix has the following properties: a=1, b=0, c=0, d=1, tx=0, ty=0. * @version DragonBones 3.0 * @language en_US */ /** * - 转换为单位矩阵。 * 该矩阵具有以下属性:a=1、b=0、c=0、d=1、tx=0、ty=0。 * @version DragonBones 3.0 * @language zh_CN */ public identity(): Matrix { this.a = this.d = 1.0; this.b = this.c = 0.0; this.tx = this.ty = 0.0; return this; } /** * - Multiplies the current matrix with another matrix. * @param value - The matrix that needs to be multiplied. * @version DragonBones 3.0 * @language en_US */ /** * - 将当前矩阵与另一个矩阵相乘。 * @param value - 需要相乘的矩阵。 * @version DragonBones 3.0 * @language zh_CN */ public concat(value: Matrix): Matrix { let aA = this.a * value.a; let bA = 0.0; let cA = 0.0; let dA = this.d * value.d; let txA = this.tx * value.a + value.tx; let tyA = this.ty * value.d + value.ty; if (this.b !== 0.0 || this.c !== 0.0) { aA += this.b * value.c; bA += this.b * value.d; cA += this.c * value.a; dA += this.c * value.b; } if (value.b !== 0.0 || value.c !== 0.0) { bA += this.a * value.b; cA += this.d * value.c; txA += this.ty * value.c; tyA += this.tx * value.b; } this.a = aA; this.b = bA; this.c = cA; this.d = dA; this.tx = txA; this.ty = tyA; return this; } /** * - Convert to inverse matrix. * @version DragonBones 3.0 * @language en_US */ /** * - 转换为逆矩阵。 * @version DragonBones 3.0 * @language zh_CN */ public invert(): Matrix { let aA = this.a; let bA = this.b; let cA = this.c; let dA = this.d; const txA = this.tx; const tyA = this.ty; if (bA === 0.0 && cA === 0.0) { this.b = this.c = 0.0; if (aA === 0.0 || dA === 0.0) { this.a = this.b = this.tx = this.ty = 0.0; } else { aA = this.a = 1.0 / aA; dA = this.d = 1.0 / dA; this.tx = -aA * txA; this.ty = -dA * tyA; } return this; } let determinant = aA * dA - bA * cA; if (determinant === 0.0) { this.a = this.d = 1.0; this.b = this.c = 0.0; this.tx = this.ty = 0.0; return this; } determinant = 1.0 / determinant; let k = this.a = dA * determinant; bA = this.b = -bA * determinant; cA = this.c = -cA * determinant; dA = this.d = aA * determinant; this.tx = -(k * txA + cA * tyA); this.ty = -(bA * txA + dA * tyA); return this; } /** * - Apply a matrix transformation to a specific point. * @param x - X coordinate. * @param y - Y coordinate. * @param result - The point after the transformation is applied. * @param delta - Whether to ignore tx, ty's conversion to point. * @version DragonBones 3.0 * @language en_US */ /** * - 将矩阵转换应用于特定点。 * @param x - 横坐标。 * @param y - 纵坐标。 * @param result - 应用转换之后的点。 * @param delta - 是否忽略 tx,ty 对点的转换。 * @version DragonBones 3.0 * @language zh_CN */ public transformPoint(x: number, y: number, result: { x: number, y: number }, delta: boolean = false): void { result.x = this.a * x + this.c * y; result.y = this.b * x + this.d * y; if (!delta) { result.x += this.tx; result.y += this.ty; } } /** * @private */ public transformRectangle(rectangle: { x: number, y: number, width: number, height: number }, delta: boolean = false): void { const a = this.a; const b = this.b; const c = this.c; const d = this.d; const tx = delta ? 0.0 : this.tx; const ty = delta ? 0.0 : this.ty; const x = rectangle.x; const y = rectangle.y; const xMax = x + rectangle.width; const yMax = y + rectangle.height; let x0 = a * x + c * y + tx; let y0 = b * x + d * y + ty; let x1 = a * xMax + c * y + tx; let y1 = b * xMax + d * y + ty; let x2 = a * xMax + c * yMax + tx; let y2 = b * xMax + d * yMax + ty; let x3 = a * x + c * yMax + tx; let y3 = b * x + d * yMax + ty; let tmp = 0.0; if (x0 > x1) { tmp = x0; x0 = x1; x1 = tmp; } if (x2 > x3) { tmp = x2; x2 = x3; x3 = tmp; } rectangle.x = Math.floor(x0 < x2 ? x0 : x2); rectangle.width = Math.ceil((x1 > x3 ? x1 : x3) - rectangle.x); if (y0 > y1) { tmp = y0; y0 = y1; y1 = tmp; } if (y2 > y3) { tmp = y2; y2 = y3; y3 = tmp; } rectangle.y = Math.floor(y0 < y2 ? y0 : y2); rectangle.height = Math.ceil((y1 > y3 ? y1 : y3) - rectangle.y); } } }
the_stack
import * as tf from '../index'; import {CHROME_ENVS, describeWithFlags} from '../jasmine_util'; import {deleteDatabase} from './indexed_db'; import {purgeLocalStorageArtifacts} from './local_storage'; // Disabled for non-Chrome browsers due to: // https://github.com/tensorflow/tfjs/issues/427 describeWithFlags('ModelManagement', CHROME_ENVS, () => { // Test data. const modelTopology1: {} = { 'class_name': 'Sequential', 'keras_version': '2.1.4', 'config': [{ 'class_name': 'Dense', 'config': { 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'name': 'dense', 'kernel_constraint': null, 'bias_regularizer': null, 'bias_constraint': null, 'dtype': 'float32', 'activation': 'linear', 'trainable': true, 'kernel_regularizer': null, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 1, 'batch_input_shape': [null, 3], 'use_bias': true, 'activity_regularizer': null } }], 'backend': 'tensorflow' }; const weightSpecs1: tf.io.WeightsManifestEntry[] = [ { name: 'dense/kernel', shape: [3, 1], dtype: 'float32', }, { name: 'dense/bias', shape: [1], dtype: 'float32', } ]; const weightData1 = new ArrayBuffer(16); const artifacts1: tf.io.ModelArtifacts = { modelTopology: modelTopology1, weightSpecs: weightSpecs1, weightData: weightData1, }; beforeEach(done => { purgeLocalStorageArtifacts(); deleteDatabase().then(() => { done(); }); }); afterEach(done => { purgeLocalStorageArtifacts(); deleteDatabase().then(() => { done(); }); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('List models: 0 result', done => { // Before any model is saved, listModels should return empty result. tf.io.listModels() .then(out => { expect(out).toEqual({}); done(); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('List models: 1 result', done => { const url = 'localstorage://baz/QuxModel'; const handler = tf.io.getSaveHandlers(url)[0]; handler.save(artifacts1) .then(saveResult => { // After successful saving, there should be one model. tf.io.listModels() .then(out => { expect(Object.keys(out).length).toEqual(1); expect(out[url].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url].modelTopologyBytes) .toEqual(saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); done(); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Manager: List models: 2 results in 2 mediums', done => { const url1 = 'localstorage://QuxModel'; const url2 = 'indexeddb://QuxModel'; // First, save a model in Local Storage. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult1 => { // Then, save the model in IndexedDB. const handler2 = tf.io.getSaveHandlers(url2)[0]; handler2.save(artifacts1) .then(saveResult2 => { // After successful saving, there should be two models. tf.io.listModels() .then(out => { expect(Object.keys(out).length).toEqual(2); expect(out[url1].modelTopologyType) .toEqual( saveResult1.modelArtifactsInfo.modelTopologyType); expect(out[url1].modelTopologyBytes) .toEqual(saveResult1.modelArtifactsInfo .modelTopologyBytes); expect(out[url1].weightSpecsBytes) .toEqual( saveResult1.modelArtifactsInfo.weightSpecsBytes); expect(out[url1].weightDataBytes) .toEqual( saveResult1.modelArtifactsInfo.weightDataBytes); expect(out[url2].modelTopologyType) .toEqual( saveResult2.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual(saveResult2.modelArtifactsInfo .modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual( saveResult2.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual( saveResult2.modelArtifactsInfo.weightDataBytes); done(); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful removeModel', done => { // First, save a model. const handler1 = tf.io.getSaveHandlers('localstorage://QuxModel')[0]; handler1.save(artifacts1) .then(saveResult1 => { // Then, save the model under another path. const handler2 = tf.io.getSaveHandlers('indexeddb://repeat/QuxModel')[0]; handler2.save(artifacts1) .then(saveResult2 => { // After successful saving, delete the first save, and then // `listModel` should give only one result. // Delete a model specified with a path that includes the // indexeddb:// scheme prefix should work. tf.io.removeModel('indexeddb://repeat/QuxModel') .then(deletedInfo => { tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([ 'localstorage://QuxModel' ]); tf.io.removeModel('localstorage://QuxModel') .then(out => { // The delete the remaining model. tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([]); done(); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful copyModel between mediums', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'indexeddb://a1/FooModel'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to another path. tf.io.copyModel(url1, url2) .then(modelInfo => { tf.io.listModels().then(out => { expect(Object.keys(out).length).toEqual(2); expect(out[url1].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url1].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url1].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url1].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); expect(out[url2].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); // Load the copy and verify the content. const handler2 = tf.io.getLoadHandlers(url2)[0]; handler2.load() .then(loaded => { expect(loaded.modelTopology).toEqual(modelTopology1); expect(loaded.weightSpecs).toEqual(weightSpecs1); expect(new Uint8Array(loaded.weightData)) .toEqual(new Uint8Array(weightData1)); done(); }) .catch(err => done.fail(err.stack)); }); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); // TODO(cais): Reenable this test once we fix // https://github.com/tensorflow/tfjs/issues/1198 // tslint:disable-next-line:ban xit('Successful moveModel between mediums', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'indexeddb://a1/FooModel'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, move the model to another path. tf.io.moveModel(url1, url2) .then(modelInfo => { tf.io.listModels().then(out => { expect(Object.keys(out)).toEqual([url2]); expect(out[url2].modelTopologyType) .toEqual(saveResult.modelArtifactsInfo.modelTopologyType); expect(out[url2].modelTopologyBytes) .toEqual( saveResult.modelArtifactsInfo.modelTopologyBytes); expect(out[url2].weightSpecsBytes) .toEqual(saveResult.modelArtifactsInfo.weightSpecsBytes); expect(out[url2].weightDataBytes) .toEqual(saveResult.modelArtifactsInfo.weightDataBytes); // Load the copy and verify the content. const handler2 = tf.io.getLoadHandlers(url2)[0]; handler2.load() .then(loaded => { expect(loaded.modelTopology).toEqual(modelTopology1); expect(loaded.weightSpecs).toEqual(weightSpecs1); expect(new Uint8Array(loaded.weightData)) .toEqual(new Uint8Array(weightData1)); done(); }) .catch(err => { done.fail(err.stack); }); }); }) .catch(err => done.fail(err.stack)); }) .catch(err => done.fail(err.stack)); }); it('Failed copyModel to invalid source URL', done => { const url1 = 'invalidurl'; const url2 = 'localstorage://a1/FooModel'; tf.io.copyModel(url1, url2) .then(out => { done.fail('Copying from invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no load handler is found for ' + 'source URL invalidurl.'); done(); }); }); it('Failed copyModel to invalid destination URL', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'invalidurl'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to another path. tf.io.copyModel(url1, url2) .then(out => { done.fail('Copying to invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no save handler is found for ' + 'destination URL invalidurl.'); done(); }); }) .catch(err => done.fail(err.stack)); }); it('Failed moveModel to invalid destination URL', done => { const url1 = 'localstorage://a1/FooModel'; const url2 = 'invalidurl'; // First, save a model. const handler1 = tf.io.getSaveHandlers(url1)[0]; handler1.save(artifacts1) .then(saveResult => { // Once model is saved, copy the model to an invalid path, which // should fail. tf.io.moveModel(url1, url2) .then(out => { done.fail('Copying to invalid URL succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Copying failed because no save handler is found for ' + 'destination URL invalidurl.'); // Verify that the source has not been removed. tf.io.listModels() .then(out => { expect(Object.keys(out)).toEqual([url1]); done(); }) .catch(err => done.fail(err.stack)); }); }) .catch(err => done.fail(err.stack)); }); it('Failed deletedModel: Absent scheme', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('foo') .then(out => { done.fail( 'Removing model with missing scheme succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toMatch(/The url string provided does not contain a scheme/); expect(err.message.indexOf('localstorage')).toBeGreaterThan(0); expect(err.message.indexOf('indexeddb')).toBeGreaterThan(0); done(); }); }); it('Failed deletedModel: Invalid scheme', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('invalidscheme://foo') .then(out => { done.fail('Removing nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model manager for scheme \'invalidscheme\''); done(); }); }); it('Failed deletedModel: Nonexistent model', done => { // Attempt to delete a nonexistent model is expected to fail. tf.io.removeModel('indexeddb://nonexistent') .then(out => { done.fail('Removing nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model with path \'nonexistent\' in IndexedDB.'); done(); }); }); it('Failed copyModel', done => { // Attempt to copy a nonexistent model should fail. tf.io.copyModel('indexeddb://nonexistent', 'indexeddb://destination') .then(out => { done.fail('Copying nonexistent model succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual( 'Cannot find model with path \'nonexistent\' in IndexedDB.'); done(); }); }); it('copyModel: Identical oldPath and newPath leads to Error', done => { tf.io.copyModel('a/1', 'a/1') .then(out => { done.fail( 'Copying with identical old & new paths succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual('Old path and new path are the same: \'a/1\''); done(); }); }); it('moveModel: Identical oldPath and newPath leads to Error', done => { tf.io.moveModel('a/1', 'a/1') .then(out => { done.fail( 'Copying with identical old & new paths succeeded unexpectedly.'); }) .catch(err => { expect(err.message) .toEqual('Old path and new path are the same: \'a/1\''); done(); }); }); });
the_stack
import { Address, BlockInfo, ChainId, isBlockInfoPending, isBlockInfoSucceeded, isConfirmedAndSignedTransaction, isSendTransaction, SendTransaction, TokenTicker, TransactionState, UnsignedTransaction, } from "@iov/bcp"; import { Random } from "@iov/crypto"; import { fromHex } from "@iov/encoding"; import { Ed25519HdWallet, HdPaths, UserProfile } from "@iov/keycontrol"; import { assert, sleep } from "@iov/utils"; import BN from "bn.js"; import { bnsCodec } from "./bnscodec"; import { BnsConnection } from "./bnsconnection"; import { decodeNumericId } from "./decodinghelpers"; import { bnsdTendermintUrl, cash, defaultAmount, getRandomInteger, pendingWithoutBnsd, randomBnsAddress, randomDomain, registerAmount, sendTokensFromFaucet, tendermintSearchIndexUpdated, unusedAddress, userProfileWithFaucet, } from "./testutils.spec"; import { ActionKind, ChainAddressPair, CreateEscrowTx, CreateMultisignatureTx, CreateProposalTx, CreateTextResolutionAction, DeleteDomainTx, isCreateEscrowTx, isCreateMultisignatureTx, isDeleteDomainTx, isRegisterDomainTx, isRegisterUsernameTx, isReleaseEscrowTx, isRenewDomainTx, isReturnEscrowTx, isTransferDomainTx, isUpdateEscrowPartiesTx, isUpdateMultisignatureTx, Participant, ProposalExecutorResult, ProposalResult, ProposalStatus, RegisterDomainTx, RegisterUsernameTx, ReleaseEscrowTx, RenewDomainTx, ReturnEscrowTx, SetMsgFeeAction, TransferDomainTx, TransferUsernameTx, UpdateEscrowPartiesTx, UpdateMultisignatureTx, UpdateTargetsOfUsernameTx, VoteOption, VoteTx, } from "./types"; import { encodeBnsAddress, identityToAddress } from "./util"; describe("BnsConnection (post txs)", () => { describe("postTx", () => { it("can send transaction", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const initialHeight = await connection.height(); const { profile, faucet } = await userProfileWithFaucet(chainId); const faucetAddr = identityToAddress(faucet); const recipient = await randomBnsAddress(); // construct a sendtx, this is normally used in the MultiChainSigner api const sendTx = await connection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: chainId, sender: bnsCodec.identityToAddress(faucet), recipient: recipient, memo: "My first payment", amount: { quantity: "5000075000", fractionalDigits: 9, tokenTicker: cash, }, }, faucetAddr, ); const nonce = await connection.getNonce({ pubkey: faucet.pubkey }); const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce); const txBytes = bnsCodec.bytesToPost(signed); const response = await connection.postTx(txBytes); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); // we should be a little bit richer const updatedAccount = await connection.getAccount({ address: recipient }); expect(updatedAccount).toBeDefined(); const paid = updatedAccount!; expect(paid.balance.length).toEqual(1); expect(paid.balance[0].quantity).toEqual("5000075000"); // and the nonce should go up, to be at least one // (worrying about replay issues) const fNonce = await connection.getNonce({ pubkey: faucet.pubkey }); expect(fNonce).toBeGreaterThanOrEqual(1); await tendermintSearchIndexUpdated(); // now verify we can query the same tx back const search = (await connection.searchTx({ sentFromOrTo: faucetAddr })).filter( isConfirmedAndSignedTransaction, ); expect(search.length).toBeGreaterThanOrEqual(1); // make sure we get a valid signature const mine = search[search.length - 1]; // make sure we have a txid expect(mine.height).toBeGreaterThan(initialHeight); expect(mine.transactionId).toMatch(/^[0-9A-F]{64}$/); const tx = mine.transaction; assert(isSendTransaction(tx), "Expected SendTransaction"); expect(tx).toEqual(sendTx); connection.disconnect(); }); // TODO: extend this with missing and high fees it("rejects send transaction with manual fees too low", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, faucet } = await userProfileWithFaucet(chainId); const faucetAddress = bnsCodec.identityToAddress(faucet); const sendTx: SendTransaction = { kind: "bcp/send", chainId: chainId, sender: faucetAddress, recipient: await randomBnsAddress(), memo: "This time I pay my bills", amount: { quantity: "100", fractionalDigits: 9, tokenTicker: cash, }, fee: { tokens: { quantity: "2", fractionalDigits: 9, tokenTicker: cash, }, payer: faucetAddress, }, }; const nonce = await connection.getNonce({ pubkey: faucet.pubkey }); const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce); try { await connection.postTx(bnsCodec.bytesToPost(signed)); fail("above line should reject with low fees"); } catch (err) { expect(err).toMatch(/fee less than minimum/); } connection.disconnect(); }); it("reports post errors (CheckTx)", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, faucet } = await userProfileWithFaucet(chainId); const faucetAddress = bnsCodec.identityToAddress(faucet); // memo too long will trigger failure in CheckTx (validation of message) const sendTx = await connection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: chainId, sender: faucetAddress, recipient: await randomBnsAddress(), amount: { ...defaultAmount, tokenTicker: "UNKNOWN" as TokenTicker, }, }, faucetAddress, ); const nonce = await connection.getNonce({ pubkey: faucet.pubkey }); const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce); await connection.postTx(bnsCodec.bytesToPost(signed)).then( () => fail("promise must be rejected"), (error) => expect(error).toMatch(/field \\"Amount\\": invalid currency: UNKNOWN/i), ); connection.disconnect(); }); it("can post transaction and watch confirmations", (done) => { pendingWithoutBnsd(); (async () => { const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, faucet } = await userProfileWithFaucet(chainId); const faucetAddress = bnsCodec.identityToAddress(faucet); const recipient = await randomBnsAddress(); // construct a sendtx, this is normally used in the MultiChainSigner api const sendTx = await connection.withDefaultFee<SendTransaction>( { kind: "bcp/send", chainId: chainId, sender: faucetAddress, recipient: recipient, memo: "My first payment", amount: { quantity: "5000075000", fractionalDigits: 9, tokenTicker: cash, }, }, faucetAddress, ); const nonce = await connection.getNonce({ pubkey: faucet.pubkey }); const signed = await profile.signTransaction(faucet, sendTx, bnsCodec, nonce); const heightBeforeTransaction = await connection.height(); const result = await connection.postTx(bnsCodec.bytesToPost(signed)); expect(result.blockInfo.value).toEqual({ state: TransactionState.Pending }); const events = new Array<BlockInfo>(); const subscription = result.blockInfo.updates.subscribe({ next: (info) => { events.push(info); if (events.length === 3) { expect(events[0]).toEqual({ state: TransactionState.Pending, }); expect(events[1]).toEqual({ state: TransactionState.Succeeded, height: heightBeforeTransaction + 1, confirmations: 1, result: undefined, }); expect(events[2]).toEqual({ state: TransactionState.Succeeded, height: heightBeforeTransaction + 1, confirmations: 2, result: undefined, }); subscription.unsubscribe(); connection.disconnect(); done(); } }, complete: done.fail, error: done.fail, }); })().catch(done.fail); }); it("can register a username", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const username = `testuser_${Math.random()}*iov`; const registration = await connection.withDefaultFee<RegisterUsernameTx>( { kind: "bns/register_username", chainId: registryChainId, username: username, targets: [{ chainId: "foobar" as ChainId, address: address }], }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registration, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterUsernameTx(firstSearchResultTransaction), "Expected RegisterUsernameTx"); expect(firstSearchResultTransaction.username).toEqual(username); expect(firstSearchResultTransaction.targets.length).toEqual(1); connection.disconnect(); }); it("can register a username with empty list of targets", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const username = `testuser_${Math.random()}*iov`; const registration = await connection.withDefaultFee<RegisterUsernameTx>( { kind: "bns/register_username", chainId: registryChainId, username: username, targets: [], }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registration, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterUsernameTx(firstSearchResultTransaction), "Expected RegisterUsernameTx"); expect(firstSearchResultTransaction.username).toEqual(username); expect(firstSearchResultTransaction.targets.length).toEqual(0); connection.disconnect(); }); it("can update targets of username", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const myAddress = identityToAddress(identity); await sendTokensFromFaucet(connection, myAddress, registerAmount); const targets1 = [{ chainId: "foobar" as ChainId, address: myAddress }] as const; const targets2 = [{ chainId: "barfoo" as ChainId, address: myAddress }] as const; // Create and send registration const username = `testuser_${Math.random()}*iov`; const usernameRegistration = await connection.withDefaultFee<RegisterUsernameTx>( { kind: "bns/register_username", chainId: registryChainId, username: username, targets: targets1, }, myAddress, ); { const response = await connection.postTx( bnsCodec.bytesToPost( await profile.signTransaction( identity, usernameRegistration, bnsCodec, await connection.getNonce({ pubkey: identity.pubkey }), ), ), ); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } // Update targets const updateTargets = await connection.withDefaultFee<UpdateTargetsOfUsernameTx>( { kind: "bns/update_targets_of_username", chainId: registryChainId, username: username, targets: targets2, }, myAddress, ); { const response = await connection.postTx( bnsCodec.bytesToPost( await profile.signTransaction( identity, updateTargets, bnsCodec, await connection.getNonce({ pubkey: identity.pubkey }), ), ), ); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } // Clear addresses const clearAddresses = await connection.withDefaultFee<UpdateTargetsOfUsernameTx>( { kind: "bns/update_targets_of_username", chainId: registryChainId, username: username, targets: [], }, myAddress, ); { const response = await connection.postTx( bnsCodec.bytesToPost( await profile.signTransaction( identity, clearAddresses, bnsCodec, await connection.getNonce({ pubkey: identity.pubkey }), ), ), ); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } connection.disconnect(); }); it("can transfer a username", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const myAddress = identityToAddress(identity); await sendTokensFromFaucet(connection, myAddress, registerAmount); const targets1 = [{ chainId: "foobar" as ChainId, address: myAddress }] as const; // Create and send registration const username = `testuser_${Math.random()}*iov`; const usernameRegistration = await connection.withDefaultFee<RegisterUsernameTx>( { kind: "bns/register_username", chainId: registryChainId, username: username, targets: targets1, }, myAddress, ); { const response = await connection.postTx( bnsCodec.bytesToPost( await profile.signTransaction( identity, usernameRegistration, bnsCodec, await connection.getNonce({ pubkey: identity.pubkey }), ), ), ); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } const transferUsername = await connection.withDefaultFee<TransferUsernameTx>( { kind: "bns/transfer_username", chainId: registryChainId, username: username, newOwner: unusedAddress, }, myAddress, ); { const response = await connection.postTx( bnsCodec.bytesToPost( await profile.signTransaction( identity, transferUsername, bnsCodec, await connection.getNonce({ pubkey: identity.pubkey }), ), ), ); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } const usernameAfterTransfer = (await connection.getUsernames({ username: username }))[0]; expect(usernameAfterTransfer.owner).toEqual(unusedAddress); connection.disconnect(); }); it("can register and update a username for an empty account", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, faucet, walletId } = await userProfileWithFaucet(chainId); const faucetAddress = identityToAddress(faucet); const brokeAccountPath = HdPaths.iov(666); const user = await profile.createIdentity(walletId, chainId, brokeAccountPath); const userAddress = identityToAddress(user); const username = `user${Math.random()}*iov`; const userAccount = await connection.getAccount({ address: userAddress }); if (userAccount && userAccount.balance.length) { throw new Error("Test should be run using empty account"); } const initialTargets: readonly ChainAddressPair[] = [ { chainId: "some-initial-chain" as ChainId, address: "some-initial-address" as Address, }, ]; const registerUsernameTx = await connection.withDefaultFee<RegisterUsernameTx>( { kind: "bns/register_username", chainId: chainId, username: username, targets: initialTargets, }, faucetAddress, ); const nonceUser1 = await connection.getNonce({ pubkey: user.pubkey }); const signed1 = await profile.signTransaction(user, registerUsernameTx, bnsCodec, nonceUser1); const nonceFaucet1 = await connection.getNonce({ pubkey: faucet.pubkey }); const doubleSigned1 = await profile.appendSignature(faucet, signed1, bnsCodec, nonceFaucet1); const txBytes1 = bnsCodec.bytesToPost(doubleSigned1); const response1 = await connection.postTx(txBytes1); const blockInfo1 = await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo1.state).toEqual(TransactionState.Succeeded); const retrieved1 = await connection.getUsernames({ username: username }); expect(retrieved1.length).toEqual(1); expect(retrieved1[0].owner).toEqual(userAddress); expect(retrieved1[0].targets).toEqual(initialTargets); const updatedTargets: readonly ChainAddressPair[] = [ { chainId: "some-updated-chain" as ChainId, address: "some-updated-address" as Address, }, ]; const updateTargetsTx = await connection.withDefaultFee<UpdateTargetsOfUsernameTx>( { kind: "bns/update_targets_of_username", chainId: chainId, username: username, targets: updatedTargets, }, faucetAddress, ); const nonce3 = await connection.getNonce({ pubkey: faucet.pubkey }); const signed3 = await profile.signTransaction(faucet, updateTargetsTx, bnsCodec, nonce3); const nonce4 = await connection.getNonce({ pubkey: user.pubkey }); const doubleSigned2 = await profile.appendSignature(user, signed3, bnsCodec, nonce4); const txBytes3 = bnsCodec.bytesToPost(doubleSigned2); const response3 = await connection.postTx(txBytes3); const blockInfo3 = await response3.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo3.state).toEqual(TransactionState.Succeeded); const retrieved2 = await connection.getUsernames({ username: username }); expect(retrieved2.length).toEqual(1); expect(retrieved2[0].owner).toEqual(userAddress); expect(retrieved2[0].targets).toEqual(updatedTargets); connection.disconnect(); }); it("can register a domain", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const domain = randomDomain(); const registerDomainTx = await connection.withDefaultFee<RegisterDomainTx>( { kind: "bns/register_domain", chainId: registryChainId, domain: domain, admin: address, hasSuperuser: true, msgFees: [], accountRenew: 100, }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registerDomainTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterDomainTx(firstSearchResultTransaction), "Expected RegisterDomainTx"); expect(firstSearchResultTransaction.admin).toEqual(address); connection.disconnect(); }); it("can transfer a domain", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const domain = randomDomain(); const registerDomainTx = await connection.withDefaultFee<RegisterDomainTx>( { kind: "bns/register_domain", chainId: registryChainId, domain: domain, admin: address, hasSuperuser: true, msgFees: [], accountRenew: 100, }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registerDomainTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterDomainTx(firstSearchResultTransaction), "Expected RegisterDomainTx"); expect(firstSearchResultTransaction.admin).toEqual(address); // Transfer domain const newAdmin = await randomBnsAddress(); const transferDomainTx = await connection.withDefaultFee<TransferDomainTx>( { kind: "bns/transfer_domain", chainId: registryChainId, domain: domain, newAdmin: newAdmin, }, address, ); const nonce2 = await connection.getNonce({ pubkey: identity.pubkey }); const signed2 = await profile.signTransaction(identity, transferDomainTx, bnsCodec, nonce2); const response2 = await connection.postTx(bnsCodec.bytesToPost(signed2)); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transfer transaction const searchResult2 = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(2); const firstSearchResultTransaction2 = searchResult2[1].transaction; assert(isTransferDomainTx(firstSearchResultTransaction2), "Expected TransferDomainTx"); expect(firstSearchResultTransaction2.newAdmin).toEqual(newAdmin); connection.disconnect(); }); it("can renew a domain", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const domain = randomDomain(); const registerDomainTx = await connection.withDefaultFee<RegisterDomainTx>( { kind: "bns/register_domain", chainId: registryChainId, domain: domain, admin: address, hasSuperuser: true, msgFees: [], accountRenew: 100, }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registerDomainTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterDomainTx(firstSearchResultTransaction), "Expected RegisterDomainTx"); expect(firstSearchResultTransaction.admin).toEqual(address); // Renew domain const renewDomainTx = await connection.withDefaultFee<RenewDomainTx>( { kind: "bns/renew_domain", chainId: registryChainId, domain: domain, }, address, ); const nonce2 = await connection.getNonce({ pubkey: identity.pubkey }); const signed2 = await profile.signTransaction(identity, renewDomainTx, bnsCodec, nonce2); const response2 = await connection.postTx(bnsCodec.bytesToPost(signed2)); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find renew transaction const searchResult2 = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(2); const firstSearchResultTransaction2 = searchResult2[1].transaction; assert(isRenewDomainTx(firstSearchResultTransaction2), "Expected RenewDomainTx"); connection.disconnect(); }); it("can delete a domain", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create and send registration const domain = randomDomain(); const registerDomainTx = await connection.withDefaultFee<RegisterDomainTx>( { kind: "bns/register_domain", chainId: registryChainId, domain: domain, admin: address, hasSuperuser: true, msgFees: [], accountRenew: 100, }, address, ); const nonce = await connection.getNonce({ pubkey: identity.pubkey }); const signed = await profile.signTransaction(identity, registerDomainTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find registration transaction const searchResult = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult.length).toEqual(1); const firstSearchResultTransaction = searchResult[0].transaction; assert(isRegisterDomainTx(firstSearchResultTransaction), "Expected RegisterDomainTx"); expect(firstSearchResultTransaction.admin).toEqual(address); // Delete domain const deleteDomainTx = await connection.withDefaultFee<DeleteDomainTx>( { kind: "bns/delete_domain", chainId: registryChainId, domain: domain, }, address, ); const nonce2 = await connection.getNonce({ pubkey: identity.pubkey }); const signed2 = await profile.signTransaction(identity, deleteDomainTx, bnsCodec, nonce2); const response2 = await connection.postTx(bnsCodec.bytesToPost(signed2)); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find delete transaction const searchResult2 = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(2); const firstSearchResultTransaction2 = searchResult2[1].transaction; assert(isDeleteDomainTx(firstSearchResultTransaction2), "Expected DeleteDomainTx"); connection.disconnect(); }); it("can create and update a multisignature account", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const identity = await profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(0)); // we need funds to pay the fees const address = identityToAddress(identity); await sendTokensFromFaucet(connection, address, registerAmount); // Create multisignature const otherIdentities = await Promise.all( [10, 11, 12, 13, 14].map((i) => profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(i))), ); const participants: readonly Participant[] = [identity, ...otherIdentities].map((id, i) => ({ address: identityToAddress(id), weight: i === 0 ? 5 : 1, })); const tx1 = await connection.withDefaultFee<CreateMultisignatureTx>( { kind: "bns/create_multisignature_contract", chainId: registryChainId, participants: participants, activationThreshold: 4, adminThreshold: 5, }, address, ); const nonce1 = await connection.getNonce({ pubkey: identity.pubkey }); const signed1 = await profile.signTransaction(identity, tx1, bnsCodec, nonce1); const txBytes1 = bnsCodec.bytesToPost(signed1); const response1 = await connection.postTx(txBytes1); const blockInfo1 = await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo1.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult1 = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult1.length).toEqual(1); const { result: contractId, transaction: firstSearchResultTransaction } = searchResult1[0]; assert(contractId, "Contract ID must be set"); // Contract ID is an incrementing fixed length uint64 expect(contractId.length).toEqual(8); expect(decodeNumericId(contractId)).toBeLessThan(Number.MAX_SAFE_INTEGER); assert(isCreateMultisignatureTx(firstSearchResultTransaction), "Expected CreateMultisignatureTx"); expect(firstSearchResultTransaction.participants.length).toEqual(6); firstSearchResultTransaction.participants.forEach((participant, i) => { expect(participant.address).toEqual(participants[i].address); expect(participant.weight).toEqual(participants[i].weight); }); expect(firstSearchResultTransaction.activationThreshold).toEqual(4); expect(firstSearchResultTransaction.adminThreshold).toEqual(5); // Update multisignature const participantsUpdated: readonly Participant[] = ( await Promise.all( [15, 16, 17].map((i) => profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(i))), ) ).map((id) => ({ address: identityToAddress(id), weight: 6, })); const tx2 = await connection.withDefaultFee<UpdateMultisignatureTx>( { kind: "bns/update_multisignature_contract", chainId: registryChainId, contractId: decodeNumericId(contractId), participants: participantsUpdated, activationThreshold: 2, adminThreshold: 6, }, address, ); const nonce2 = await connection.getNonce({ pubkey: identity.pubkey }); const signed2 = await profile.signTransaction(identity, tx2, bnsCodec, nonce2); const txBytes2 = bnsCodec.bytesToPost(signed2); const response2 = await connection.postTx(txBytes2); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction2 const searchResult2 = (await connection.searchTx({ signedBy: address })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(2); const { transaction: secondSearchResultTransaction } = searchResult2[1]; assert(isUpdateMultisignatureTx(secondSearchResultTransaction), "Expected UpdateMultisignatureTx"); expect(secondSearchResultTransaction.participants.length).toEqual(3); secondSearchResultTransaction.participants.forEach((participant, i) => { expect(participant.address).toEqual(participantsUpdated[i].address); expect(participant.weight).toEqual(participantsUpdated[i].weight); }); expect(secondSearchResultTransaction.activationThreshold).toEqual(2); expect(secondSearchResultTransaction.adminThreshold).toEqual(6); expect(contractId).toBeDefined(); connection.disconnect(); }); it("can create and release an escrow", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const [sender, recipient, arbiter] = await Promise.all( [0, 10, 20].map((i) => profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(i))), ); const [senderAddress, recipientAddress, arbiterAddress] = [sender, recipient, arbiter].map( identityToAddress, ); const timeout = { timestamp: Math.floor(Date.now() / 1000) + 3000, }; const memo = "testing 123"; // we need funds to pay the fees await sendTokensFromFaucet(connection, senderAddress, registerAmount); await sendTokensFromFaucet(connection, arbiterAddress, registerAmount); // Create escrow const tx1 = await connection.withDefaultFee<CreateEscrowTx>( { kind: "bns/create_escrow", chainId: registryChainId, sender: senderAddress, arbiter: arbiterAddress, recipient: recipientAddress, amounts: [defaultAmount], timeout: timeout, memo: memo, }, senderAddress, ); const nonce1 = await connection.getNonce({ pubkey: sender.pubkey }); const signed1 = await profile.signTransaction(sender, tx1, bnsCodec, nonce1); const txBytes1 = bnsCodec.bytesToPost(signed1); const response1 = await connection.postTx(txBytes1); const blockInfo1 = await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo1.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult1 = (await connection.searchTx({ signedBy: senderAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult1.length).toEqual(1); const { result, transaction: firstSearchResultTransaction } = searchResult1[0]; assert(isCreateEscrowTx(firstSearchResultTransaction), "Expected CreateEscrowTx"); expect(firstSearchResultTransaction.sender).toEqual(senderAddress); expect(firstSearchResultTransaction.recipient).toEqual(recipientAddress); expect(firstSearchResultTransaction.arbiter).toEqual(arbiterAddress); expect(firstSearchResultTransaction.amounts).toEqual([defaultAmount]); expect(firstSearchResultTransaction.timeout).toEqual(timeout); expect(firstSearchResultTransaction.memo).toEqual(memo); expect(result).toBeDefined(); const escrowId = decodeNumericId(result!); // Release escrow const tx2 = await connection.withDefaultFee<ReleaseEscrowTx>( { kind: "bns/release_escrow", chainId: registryChainId, escrowId: escrowId, amounts: [defaultAmount], }, arbiterAddress, ); const nonce2 = await connection.getNonce({ pubkey: arbiter.pubkey }); const signed2 = await profile.signTransaction(arbiter, tx2, bnsCodec, nonce2); const txBytes2 = bnsCodec.bytesToPost(signed2); const response2 = await connection.postTx(txBytes2); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult2 = (await connection.searchTx({ signedBy: arbiterAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(1); const { transaction: secondSearchResultTransaction } = searchResult2[0]; assert(isReleaseEscrowTx(secondSearchResultTransaction), "Expected ReleaseEscrowTx"); expect(secondSearchResultTransaction.escrowId).toEqual(escrowId); expect(secondSearchResultTransaction.amounts).toEqual([defaultAmount]); connection.disconnect(); }); it("any account can return an escrow (after the timeout)", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); let escrowId: Uint8Array; { const sender = await profile.createIdentity(wallet.id, chainId, HdPaths.iov(0)); const senderAddress = identityToAddress(sender); await sendTokensFromFaucet(connection, senderAddress, registerAmount); const timeout = Math.floor(Date.now() / 1000) + 3; const createEscrowTx = await connection.withDefaultFee<CreateEscrowTx>( { kind: "bns/create_escrow", chainId: chainId, sender: senderAddress, arbiter: encodeBnsAddress("tiov", fromHex("0000000000000000000000000000000000000000")), recipient: encodeBnsAddress("tiov", fromHex("0000000000000000000000000000000000000000")), amounts: [defaultAmount], timeout: { timestamp: timeout }, }, senderAddress, ); const nonce = await connection.getNonce({ pubkey: sender.pubkey }); const signed = await profile.signTransaction(sender, createEscrowTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); escrowId = blockInfo.result || fromHex(""); } await sleep(5_000); { // Use an external helper account (random path from random wallet) that returns the escrow for source const addressIndex = getRandomInteger(100, 2 ** 31); const helperIdentity = await profile.createIdentity(wallet.id, chainId, HdPaths.iov(addressIndex)); const helperAddress = identityToAddress(helperIdentity); await sendTokensFromFaucet(connection, helperAddress); const returnEscrowTx = await connection.withDefaultFee<ReturnEscrowTx>( { kind: "bns/return_escrow", chainId: chainId, escrowId: decodeNumericId(escrowId), }, helperAddress, ); const nonce = await connection.getNonce({ pubkey: helperIdentity.pubkey }); const signed = await profile.signTransaction(helperIdentity, returnEscrowTx, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); } }); it("can create and return an escrow", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const [sender, recipient, arbiter] = await Promise.all( [0, 10, 20].map((i) => profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(i))), ); const [senderAddress, recipientAddress, arbiterAddress] = [sender, recipient, arbiter].map( identityToAddress, ); const timeout = { timestamp: Math.floor(Date.now() / 1000) + 3, }; const memo = "testing 123"; // we need funds to pay the fees await sendTokensFromFaucet(connection, senderAddress, registerAmount); await sendTokensFromFaucet(connection, arbiterAddress, registerAmount); // Create escrow const tx1 = await connection.withDefaultFee<CreateEscrowTx>( { kind: "bns/create_escrow", chainId: registryChainId, sender: senderAddress, arbiter: arbiterAddress, recipient: recipientAddress, amounts: [defaultAmount], timeout: timeout, memo: memo, }, senderAddress, ); const nonce1 = await connection.getNonce({ pubkey: sender.pubkey }); const signed1 = await profile.signTransaction(sender, tx1, bnsCodec, nonce1); const txBytes1 = bnsCodec.bytesToPost(signed1); const response1 = await connection.postTx(txBytes1); const blockInfo1 = await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo1.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult1 = (await connection.searchTx({ signedBy: senderAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult1.length).toEqual(1); const { result, transaction: firstSearchResultTransaction } = searchResult1[0]; assert(isCreateEscrowTx(firstSearchResultTransaction), "Expected CreateEscrowTx"); expect(firstSearchResultTransaction.sender).toEqual(senderAddress); expect(firstSearchResultTransaction.recipient).toEqual(recipientAddress); expect(firstSearchResultTransaction.arbiter).toEqual(arbiterAddress); expect(firstSearchResultTransaction.amounts).toEqual([defaultAmount]); expect(firstSearchResultTransaction.timeout).toEqual(timeout); expect(firstSearchResultTransaction.memo).toEqual(memo); expect(result).toBeDefined(); const escrowId = decodeNumericId(result!); // Wait for timeout to pass await sleep(7000); // Return escrow const tx2 = await connection.withDefaultFee<ReturnEscrowTx>( { kind: "bns/return_escrow", chainId: registryChainId, escrowId: escrowId, }, arbiterAddress, ); const nonce2 = await connection.getNonce({ pubkey: arbiter.pubkey }); const signed2 = await profile.signTransaction(arbiter, tx2, bnsCodec, nonce2); const txBytes2 = bnsCodec.bytesToPost(signed2); const response2 = await connection.postTx(txBytes2); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult2 = (await connection.searchTx({ signedBy: arbiterAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(1); const { transaction: secondSearchResultTransaction } = searchResult2[0]; assert(isReturnEscrowTx(secondSearchResultTransaction), "Expected ReturnEscrowTx"); expect(secondSearchResultTransaction.escrowId).toEqual(escrowId); connection.disconnect(); }); it("can create and update an escrow", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const registryChainId = connection.chainId; const profile = new UserProfile(); const wallet = profile.addWallet(Ed25519HdWallet.fromEntropy(Random.getBytes(32))); const [sender, recipient, arbiter, newArbiter] = await Promise.all( [0, 10, 20, 21].map((i) => profile.createIdentity(wallet.id, registryChainId, HdPaths.iov(i))), ); const [senderAddress, recipientAddress, arbiterAddress, newArbiterAddress] = [ sender, recipient, arbiter, newArbiter, ].map(identityToAddress); const timeout = { timestamp: Math.floor(Date.now() / 1000) + 3000, }; const memo = "testing 123"; // we need funds to pay the fees await sendTokensFromFaucet(connection, senderAddress, registerAmount); await sendTokensFromFaucet(connection, arbiterAddress, registerAmount); // Create escrow const tx1 = await connection.withDefaultFee<CreateEscrowTx>( { kind: "bns/create_escrow", chainId: registryChainId, sender: senderAddress, arbiter: arbiterAddress, recipient: recipientAddress, amounts: [defaultAmount], timeout: timeout, memo: memo, }, senderAddress, ); const nonce1 = await connection.getNonce({ pubkey: sender.pubkey }); const signed1 = await profile.signTransaction(sender, tx1, bnsCodec, nonce1); const txBytes1 = bnsCodec.bytesToPost(signed1); const response1 = await connection.postTx(txBytes1); const blockInfo1 = await response1.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo1.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult1 = (await connection.searchTx({ signedBy: senderAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult1.length).toEqual(1); const { result, transaction: firstSearchResultTransaction } = searchResult1[0]; assert(isCreateEscrowTx(firstSearchResultTransaction), "Expected CreateEscrowTx"); expect(firstSearchResultTransaction.sender).toEqual(senderAddress); expect(firstSearchResultTransaction.recipient).toEqual(recipientAddress); expect(firstSearchResultTransaction.arbiter).toEqual(arbiterAddress); expect(firstSearchResultTransaction.amounts).toEqual([defaultAmount]); expect(firstSearchResultTransaction.timeout).toEqual(timeout); expect(firstSearchResultTransaction.memo).toEqual(memo); expect(result).toBeDefined(); const escrowId = decodeNumericId(result!); // Update escrow const tx2 = await connection.withDefaultFee<UpdateEscrowPartiesTx>( { kind: "bns/update_escrow_parties", chainId: registryChainId, escrowId: escrowId, arbiter: newArbiterAddress, }, arbiterAddress, ); const nonce2 = await connection.getNonce({ pubkey: arbiter.pubkey }); const signed2 = await profile.signTransaction(arbiter, tx2, bnsCodec, nonce2); const txBytes2 = bnsCodec.bytesToPost(signed2); const response2 = await connection.postTx(txBytes2); const blockInfo2 = await response2.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo2.state).toEqual(TransactionState.Succeeded); await tendermintSearchIndexUpdated(); // Find transaction1 const searchResult2 = (await connection.searchTx({ signedBy: arbiterAddress })).filter( isConfirmedAndSignedTransaction, ); expect(searchResult2.length).toEqual(1); const { transaction: secondSearchResultTransaction } = searchResult2[0]; assert(isUpdateEscrowPartiesTx(secondSearchResultTransaction), "Expected UpdateEscrowPartiesTx"); expect(secondSearchResultTransaction.escrowId).toEqual(escrowId); expect(secondSearchResultTransaction.arbiter).toEqual(newArbiterAddress); connection.disconnect(); }); it("can create and vote on a proposal", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, admin: author } = await userProfileWithFaucet(chainId); const authorAddress = identityToAddress(author); const someElectionRule = (await connection.getElectionRules()).find( // Dictatorship electorate ({ electorateId }) => electorateId === 2, ); if (!someElectionRule) { throw new Error("No election rule found"); } const startTime = Math.floor(Date.now() / 1000) + 3; const title = `Hello ${Math.random()}`; const description = `Hello ${Math.random()}`; const action: CreateTextResolutionAction = { kind: ActionKind.CreateTextResolution, resolution: `The winner is Alice ${Math.random()}`, }; let proposalId: number; { const createProposal = await connection.withDefaultFee<CreateProposalTx>( { kind: "bns/create_proposal", chainId: chainId, title: title, description: description, author: authorAddress, electionRuleId: someElectionRule.id, action: action, startTime: startTime, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, createProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); if (!blockInfo.result) { throw new Error("Transaction result missing"); } proposalId = new BN(blockInfo.result).toNumber(); } { // Election submitted, voting period not yet started const proposal = (await connection.getProposals()).find((p) => p.id === proposalId)!; expect(proposal.votingStartTime).toBeGreaterThan(Date.now() / 1000); expect(proposal.state.totalYes).toEqual(0); expect(proposal.state.totalNo).toEqual(0); expect(proposal.state.totalAbstain).toEqual(0); expect(proposal.status).toEqual(ProposalStatus.Submitted); expect(proposal.result).toEqual(ProposalResult.Undefined); expect(proposal.executorResult).toEqual(ProposalExecutorResult.NotRun); } await sleep(6_000); { // Election submitted, voting period started const proposal = (await connection.getProposals()).find((p) => p.id === proposalId)!; expect(proposal.votingStartTime).toBeLessThan(Date.now() / 1000); expect(proposal.votingEndTime).toBeGreaterThan(Date.now() / 1000); expect(proposal.state.totalYes).toEqual(0); expect(proposal.state.totalNo).toEqual(0); expect(proposal.state.totalAbstain).toEqual(0); expect(proposal.status).toEqual(ProposalStatus.Submitted); expect(proposal.result).toEqual(ProposalResult.Undefined); expect(proposal.executorResult).toEqual(ProposalExecutorResult.NotRun); } { const voteForProposal = await connection.withDefaultFee<VoteTx>( { kind: "bns/vote", chainId: chainId, proposalId: proposalId, selection: VoteOption.Yes, voter: authorAddress, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, voteForProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); } await sleep(15_000); { // Election ended, was tallied automatically and is accepted const proposal = (await connection.getProposals()).find((p) => p.id === proposalId)!; expect(proposal.state.totalYes).toEqual(10); expect(proposal.state.totalNo).toEqual(0); expect(proposal.state.totalAbstain).toEqual(0); expect(proposal.status).toEqual(ProposalStatus.Closed); expect(proposal.result).toEqual(ProposalResult.Accepted); expect(proposal.executorResult).toEqual(ProposalExecutorResult.Succeeded); } connection.disconnect(); }, 30_000); it("can create and vote on a proposal, and see the effects", async () => { pendingWithoutBnsd(); const connection = await BnsConnection.establish(bnsdTendermintUrl); const chainId = connection.chainId; const { profile, admin: author } = await userProfileWithFaucet(chainId); const authorAddress = identityToAddress(author); const someElectionRule = (await connection.getElectionRules()).find( // Dictatorship electorate ({ electorateId }) => electorateId === 2, ); if (!someElectionRule) { throw new Error("No election rule found"); } const fee1 = { fractionalDigits: 9, quantity: "888888888", tokenTicker: cash, }; let proposalId1: number; { const startTime = Math.floor(Date.now() / 1000) + 3; const title = `Hello ${Math.random()}`; const description = `Hello ${Math.random()}`; const action: SetMsgFeeAction = { kind: ActionKind.SetMsgFee, msgPath: "username/register_token", fee: fee1, }; const createProposal = await connection.withDefaultFee<CreateProposalTx>( { kind: "bns/create_proposal", chainId: chainId, title: title, description: description, author: authorAddress, electionRuleId: someElectionRule.id, action: action, startTime: startTime, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, createProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); if (!blockInfo.result) { throw new Error("Transaction result missing"); } proposalId1 = new BN(blockInfo.result).toNumber(); } await sleep(6_000); { const voteForProposal = await connection.withDefaultFee<VoteTx>( { kind: "bns/vote", chainId: chainId, proposalId: proposalId1, selection: VoteOption.Yes, voter: authorAddress, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, voteForProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); } await sleep(15_000); const registerUsernameTx: RegisterUsernameTx & UnsignedTransaction = { kind: "bns/register_username", chainId: chainId, username: "TestyMcTestface*iov", targets: [], }; const productFee1 = await connection.getFeeQuote(registerUsernameTx); expect(productFee1.tokens).toEqual(fee1); const fee2 = { fractionalDigits: 9, quantity: "5000000000", tokenTicker: cash, }; let proposalId2: number; { const startTime = Math.floor(Date.now() / 1000) + 3; const title = `Hello ${Math.random()}`; const description = `Hello ${Math.random()}`; const action: SetMsgFeeAction = { kind: ActionKind.SetMsgFee, msgPath: "username/register_token", fee: fee2, }; const createProposal = await connection.withDefaultFee<CreateProposalTx>( { kind: "bns/create_proposal", chainId: chainId, title: title, description: description, author: authorAddress, electionRuleId: someElectionRule.id, action: action, startTime: startTime, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, createProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); if (!blockInfo.result) { throw new Error("Transaction result missing"); } proposalId2 = new BN(blockInfo.result).toNumber(); } await sleep(6_000); { const voteForProposal = await connection.withDefaultFee<VoteTx>( { kind: "bns/vote", chainId: chainId, proposalId: proposalId2, selection: VoteOption.Yes, voter: authorAddress, }, authorAddress, ); const nonce = await connection.getNonce({ pubkey: author.pubkey }); const signed = await profile.signTransaction(author, voteForProposal, bnsCodec, nonce); const response = await connection.postTx(bnsCodec.bytesToPost(signed)); const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); assert(isBlockInfoSucceeded(blockInfo), `Expected success but got state: ${blockInfo.state}`); } await sleep(15_000); const productFee2 = await connection.getFeeQuote(registerUsernameTx); expect(productFee2.tokens).toEqual(fee2); connection.disconnect(); }, 60_000); }); });
the_stack
import ThePlugin from "../main"; import AddNewPluginModal from "../ui/AddNewPluginModal"; import { grabManifestJsonFromRepository, grabReleaseFileFromRepository } from "./githubUtils"; import { normalizePath, PluginManifest, Notice } from "obsidian"; import { addBetaPluginToList } from "../ui/settings"; import { ToastMessage } from "../utils/notifications"; import { isConnectedToInternet } from "../utils/internetconnection"; /** * all the files needed for a plugin based on the release files are hre */ interface ReleaseFiles { mainJs: string; manifest: string; styles: string; } /** * Primary handler for adding, updating, deleting beta plugins tracked by this plugin */ export default class BetaPlugins { plugin: ThePlugin; constructor(plugin: ThePlugin) { this.plugin = plugin; } /** * opens the AddNewPluginModal to get info for a new beta plugin * @param {boolean} openSettingsTabAfterwards will open settings screen afterwards. Used when this command is called from settings tab * @param {boolean} useFrozenVersion install the plugin using frozen version. * @return {<Promise><void>} */ async displayAddNewPluginModal(openSettingsTabAfterwards = false, useFrozenVersion = false): Promise<void> { const newPlugin = new AddNewPluginModal(this.plugin, this, openSettingsTabAfterwards, useFrozenVersion); newPlugin.open(); } /** * Validates that a GitHub repository is plugin * * @param {string} repositoryPath GithubUser/RepositoryName (example: TfThacker/obsidian42-brat) * @param {[type]} getBetaManifest test the beta version of the manifest, not at the root * @param {[type]} false [false description] * @param {[type]} reportIssues will display notices as it finds issues * * @return {Promise<PluginManifest>} the manifest file if found, or null if its incomplete */ async validateRepository(repositoryPath: string, getBetaManifest = false, reportIssues = false): Promise<PluginManifest> { const noticeTimeout = 15; const manifestJson = await grabManifestJsonFromRepository(repositoryPath, !getBetaManifest); if (!manifestJson) { // this is a plugin with a manifest json, try to see if there is a beta version if (reportIssues) ToastMessage(this.plugin, `${repositoryPath}\nThis does not seem to be an obsidian plugin, as there is no manifest.json file.`, noticeTimeout); return null; } // Test that the mainfest has some key elements, like ID and version if (!("id" in manifestJson)) { // this is a plugin with a manifest json, try to see if there is a beta version if (reportIssues) ToastMessage(this.plugin,`${repositoryPath}\nThe plugin id attribute for the release is missing from the manifest file`, noticeTimeout); return null; } if (!("version" in manifestJson)) { // this is a plugin with a manifest json, try to see if there is a beta version if (reportIssues) ToastMessage(this.plugin,`${repositoryPath}\nThe version attribute for the release is missing from the manifest file`, noticeTimeout); return null; } return manifestJson; } /** * Gets all the relese files based on the version number in the manifest * * @param {string} repositoryPath path to the GitHub repository * @param {PluginManifest<ReleaseFiles>} manifest manifest file * @param {boolean} getManifest grab the remote manifest file * @param {string} specifyVersion grab the specified version if set * * @return {Promise<ReleaseFiles>} all relase files as strings based on the ReleaseFiles interaface */ async getAllReleaseFiles(repositoryPath: string, manifest: PluginManifest, getManifest: boolean, specifyVersion = ""): Promise<ReleaseFiles> { const version = specifyVersion === "" ? manifest.version : specifyVersion; // if we have version specified, we always want to get the remote manifest file. const reallyGetManifestOrNot = getManifest || (specifyVersion !== ""); return { mainJs: await grabReleaseFileFromRepository(repositoryPath, version, "main.js"), manifest: reallyGetManifestOrNot ? await grabReleaseFileFromRepository(repositoryPath, version, "manifest.json") : null, styles: await grabReleaseFileFromRepository(repositoryPath, version, "styles.css") } } /** * Writes the plugin release files to the local obsidian .plugins folder * * @param {string} betaPluginID the id of the plugin (not the repository path) * @param {ReleaseFiles<void>} relFiles release file as strings, based on the ReleaseFiles interface * * @return {Promise<void>} */ async writeReleaseFilesToPluginFolder(betaPluginID: string, relFiles: ReleaseFiles): Promise<void> { const pluginTargetFolderPath = normalizePath(this.plugin.app.vault.configDir + "/plugins/" + betaPluginID) + "/"; const adapter = this.plugin.app.vault.adapter; if (await adapter.exists(pluginTargetFolderPath) === false || !(await adapter.exists(pluginTargetFolderPath + "manifest.json"))) { // if plugin folder doesnt exist or manifest.json doesn't exist, create it and save the plugin files await adapter.mkdir(pluginTargetFolderPath); } await adapter.write(pluginTargetFolderPath + "main.js", relFiles.mainJs); await adapter.write(pluginTargetFolderPath + "manifest.json", relFiles.manifest); if (relFiles.styles) await adapter.write(pluginTargetFolderPath + "styles.css", relFiles.styles); } /** * Primary function for adding a new beta plugin to obsidian. Also this function is use for updating * existing plugins. * * @param {string} repositoryPath path to GitHub repository formated as USERNAME/repository * @param {boolean} updatePluginFiles true if this is just an update not an install * @param {boolean} seeIfUpdatedOnly if true, and updatePluginFiles true, will just check for updates, but not do the update. will report to user that there is a new plugin * @param {boolean} reportIfNotUpdted if true, report if an update has not succed * @param {string} specifyVersion if not empty, need to install a specified version instead of the value in manifest{-beta}.json * * @return {Promise<boolean>} true if succeeds */ async addPlugin(repositoryPath: string, updatePluginFiles = false, seeIfUpdatedOnly = false, reportIfNotUpdted = false, specifyVersion = ""): Promise<boolean> { const noticeTimeout = 10; let primaryManifest = await this.validateRepository(repositoryPath, true, false); // attempt to get manifest-beta.json const usingBetaManifest: boolean = primaryManifest ? true : false; if (usingBetaManifest === false) primaryManifest = await this.validateRepository(repositoryPath, false, true); // attempt to get manifest.json if (primaryManifest === null) { const msg = `${repositoryPath}\nA manifest.json or manifest-beta.json file does not exist in the root directory of the repository. This plugin cannot be installed.`; this.plugin.log(msg, true); ToastMessage(this.plugin, `${msg}`, noticeTimeout); return false; } if (!primaryManifest.hasOwnProperty('version')) { const msg = `${repositoryPath}\nThe manifest${usingBetaManifest ? "-beta" : ""}.json file in the root directory of the repository does not have a version number in the file. This plugin cannot be installed.`; this.plugin.log(msg, true); ToastMessage(this.plugin, `${msg}`, noticeTimeout); return false; } const getRelease = async () => { const rFiles = await this.getAllReleaseFiles(repositoryPath, primaryManifest, usingBetaManifest, specifyVersion); if (usingBetaManifest || rFiles.manifest === null) //if beta, use that manifest, or if there is no manifest in release, use the primaryManifest rFiles.manifest = JSON.stringify(primaryManifest); if (rFiles.mainJs === null) { const msg = `${repositoryPath}\nThe release is not complete and cannot be download. main.js is missing from the Release`; this.plugin.log(msg, true); ToastMessage(this.plugin, `${msg}`, noticeTimeout); return null; } return rFiles; } if (updatePluginFiles === false) { const releaseFiles = await getRelease(); if (releaseFiles === null) return; await this.writeReleaseFilesToPluginFolder(primaryManifest.id, releaseFiles); await addBetaPluginToList(this.plugin, repositoryPath, specifyVersion); //@ts-ignore await this.plugin.app.plugins.loadManifests(); const versionText = specifyVersion === "" ? "" : ` (version: ${specifyVersion})`; const msg = `${repositoryPath}${versionText}\nThe plugin has been registered with BRAT. You may still need to enable it the Community Plugin List.`; this.plugin.log(msg, true); ToastMessage(this.plugin, msg, noticeTimeout); } else { // test if the plugin needs to be updated // if a specified version is provided, then we shall skip the update const pluginTargetFolderPath = this.plugin.app.vault.configDir + "/plugins/" + primaryManifest.id + "/"; let localManifestContents = null; try { localManifestContents = await this.plugin.app.vault.adapter.read(pluginTargetFolderPath + "manifest.json") } catch (e) { if (e.errno === -4058) { // file does not exist, try installing the plugin await this.addPlugin(repositoryPath, false, usingBetaManifest, false, specifyVersion); return true; // even though failed, return true since install will be attempted } else console.log("BRAT - Local Manifest Load", primaryManifest.id, JSON.stringify(e, null, 2)); } if ( specifyVersion !== "" || this.plugin.settings.pluginSubListFrozenVersion.map(x=>x.repo).includes(repositoryPath) ) { // skip the frozen version plugin ToastMessage(this.plugin, `The version of ${repositoryPath} is frozen, not updating.`, 3); return false; } const localManifestJSON = await JSON.parse(localManifestContents); if (localManifestJSON.version !== primaryManifest.version) { //manifest files are not the same, do an update const releaseFiles = await getRelease(); if (releaseFiles === null) return; if (seeIfUpdatedOnly) { // dont update, just report it const msg = `There is an update available for ${primaryManifest.id} from version ${localManifestJSON.version} to ${primaryManifest.version}. `; this.plugin.log(msg + `[Release Info](https://github.com/${repositoryPath}/releases/tag/${primaryManifest.version})`, false); ToastMessage(this.plugin, msg, 30, async () => { window.open(`https://github.com/${repositoryPath}/releases/tag/${primaryManifest.version}`)}); } else { await this.writeReleaseFilesToPluginFolder(primaryManifest.id, releaseFiles); //@ts-ignore await this.plugin.app.plugins.loadManifests(); //@ts-ignore if (this.plugin.app.plugins.plugins[primaryManifest.id]?.manifest) await this.reloadPlugin(primaryManifest.id); //reload if enabled const msg = `${primaryManifest.id}\nPlugin has been updated from version ${localManifestJSON.version} to ${primaryManifest.version}. `; this.plugin.log(msg + `[Release Info](https://github.com/${repositoryPath}/releases/tag/${primaryManifest.version})`, false); ToastMessage(this.plugin, msg, 30, async () => { window.open(`https://github.com/${repositoryPath}/releases/tag/${primaryManifest.version}`) } ); } } else if (reportIfNotUpdted) ToastMessage(this.plugin, `No update available for ${repositoryPath}`, 3); } return true; } /** * reloads a plugin (assuming it has been enabled by user) * pjeby, Thanks Bro https://github.com/pjeby/hot-reload/blob/master/main.js * * @param {string<void>} pluginName name of plugin * * @return {Promise<void>} */ async reloadPlugin(pluginName: string): Promise<void> { // @ts-ignore const plugins = this.plugin.app.plugins; try { await plugins.disablePlugin(pluginName); await plugins.enablePlugin(pluginName); } catch (e) { console.log("reload plugin", e) } } /** * updates a beta plugin * * @param {string} repositoryPath repository path on GitHub * @param {boolean} onlyCheckDontUpdate only looks for update * * @return {Promise<void>} */ async updatePlugin(repositoryPath: string, onlyCheckDontUpdate = false, reportIfNotUpdted = false): Promise<boolean> { const result = await this.addPlugin(repositoryPath, true, onlyCheckDontUpdate, reportIfNotUpdted); if (result === false && onlyCheckDontUpdate === false) ToastMessage(this.plugin, `${repositoryPath}\nUpdate of plugin failed.`) return result; } /** * walks through the list of plugins without frozen version and performs an update * * @param {boolean} showInfo should this with a started/completed message - useful when ran from CP * @return {Promise<void>} */ async checkForUpdatesAndInstallUpdates(showInfo = false, onlyCheckDontUpdate = false): Promise<void> { if(await isConnectedToInternet()===false) { console.log("BRAT: No internet detected.") return; } let newNotice: Notice; const msg1 = `Checking for plugin updates STARTED`; this.plugin.log(msg1, true); if (showInfo && this.plugin.settings.notificationsEnabled) newNotice = new Notice(`BRAT\n${msg1}`, 30000); const pluginSubListFrozenVersionNames = new Set(this.plugin.settings.pluginSubListFrozenVersion.map(f => f.repo)); for (const bp of this.plugin.settings.pluginList) { if (pluginSubListFrozenVersionNames.has(bp)) { continue; } await this.updatePlugin(bp, onlyCheckDontUpdate); } const msg2 = `Checking for plugin updates COMPLETED`; this.plugin.log(msg2, true); if (showInfo) { newNotice.hide(); ToastMessage(this.plugin, msg2, 10); } } /** * Removes the beta plugin from the list of beta plugins (does not delete them from disk) * * @param {string<void>} betaPluginID repository path * * @return {Promise<void>} [return description] */ async deletePlugin(repositoryPath: string): Promise<void> { const msg = `Removed ${repositoryPath} from BRAT plugin list`; this.plugin.log(msg, true); this.plugin.settings.pluginList = this.plugin.settings.pluginList.filter((b) => b != repositoryPath); this.plugin.settings.pluginSubListFrozenVersion = this.plugin.settings.pluginSubListFrozenVersion.filter( (b) => b.repo != repositoryPath ); this.plugin.saveSettings(); } /** * Returns a list of plugins that are currently enabled or currently disabled * * @param {boolean[]} enabled true for enabled plugins, false for disabled plutings * * @return {PluginManifest[]} manifests of plugins */ getEnabledDisabledPlugins(enabled: boolean): PluginManifest[] { // @ts-ignore const pl = this.plugin.app.plugins; const manifests: PluginManifest[] = Object.values(pl.manifests); // @ts-ignore const enabledPlugins: PluginManifest[] = Object.values(pl.plugins).map(p => p.manifest); return enabled ? manifests.filter(manifest => enabledPlugins.find(pluginName => manifest.id === pluginName.id)) : manifests.filter(manifest => !enabledPlugins.find(pluginName => manifest.id === pluginName.id)); } }
the_stack
module androidui.image { import Paint = android.graphics.Paint; import Rect = android.graphics.Rect; import Color = android.graphics.Color; import Drawable = android.graphics.drawable.Drawable; import Canvas = android.graphics.Canvas; export class NinePatchDrawable extends NetDrawable { private static GlobalBorderInfoCache = new Map<string, NinePatchBorderInfo>(); private mTmpRect = new Rect(); private mTmpRect2 = new Rect(); private mNinePatchBorderInfo:NinePatchBorderInfo; private mNinePatchDrawCache:Canvas; //constructor(src:string|NetImage, paint?:Paint, overrideImageRatio?:number) { // super(src, paint, overrideImageRatio); //} protected initBoundWithLoadedImage(image:NetImage){ let imageRatio = image.getImageRatio(); this.mImageWidth = Math.floor( (image.width-2) / imageRatio * android.content.res.Resources.getDisplayMetrics().density); this.mImageHeight = Math.floor( (image.height-2) / imageRatio * android.content.res.Resources.getDisplayMetrics().density); this.initNinePatchBorderInfo(image); } private initNinePatchBorderInfo(image:NetImage){ this.mNinePatchBorderInfo = NinePatchDrawable.GlobalBorderInfoCache.get(image.src); if(!this.mNinePatchBorderInfo){ image.getBorderPixels((leftBorder:number[], topBorder:number[], rightBorder:number[], bottomBorder:number[])=>{ this.mNinePatchBorderInfo = new NinePatchBorderInfo(leftBorder, topBorder, rightBorder, bottomBorder); NinePatchDrawable.GlobalBorderInfoCache.set(image.src, this.mNinePatchBorderInfo); }); } } protected onLoad():void { //parse nine patch border now. let image:NetImage = this.getImage(); let ninePatchBorderInfo = NinePatchDrawable.GlobalBorderInfoCache.get(image.src); if(ninePatchBorderInfo){ this.mNinePatchBorderInfo = ninePatchBorderInfo; super.onLoad(); return; } image.getBorderPixels((leftBorder:number[], topBorder:number[], rightBorder:number[], bottomBorder:number[])=>{ ninePatchBorderInfo = new NinePatchBorderInfo(leftBorder, topBorder, rightBorder, bottomBorder); NinePatchDrawable.GlobalBorderInfoCache.set(image.src, ninePatchBorderInfo); //parse border finish, notify load finish. super.onLoad(); }); } draw(canvas:Canvas):void { if(!this.mNinePatchBorderInfo) return; if(!this.isImageSizeEmpty()){ let cache = this.getNinePatchCache(); if(cache){ canvas.drawCanvas(cache); }else{ this.drawNinePatch(canvas); } } } private getNinePatchCache():Canvas { let bound = this.getBounds(); let width = bound.width(); let height = bound.height(); let cache = this.mNinePatchDrawCache; if(cache){ if(cache.getWidth() === width && cache.getHeight() === height){ return cache; } cache.recycle(); } const cachePixelSize:number = width * height * 4; const drawingCacheSize:number = android.view.ViewConfiguration.get().getScaledMaximumDrawingCacheSize(); if(cachePixelSize > drawingCacheSize) return null; cache = this.mNinePatchDrawCache = new Canvas(bound.width(), bound.height()); this.drawNinePatch(cache); return cache; } private drawNinePatch(canvas:Canvas):void { let smoothEnableBak = canvas.isImageSmoothingEnabled(); canvas.setImageSmoothingEnabled(false); let imageWidth = this.mImageWidth; let imageHeight = this.mImageHeight; if(imageHeight<=0 || imageWidth<=0) return; let image = this.getImage(); let bound = this.getBounds(); const staticRatioScale = android.content.res.Resources.getDisplayMetrics().density / image.getImageRatio(); const staticWidthSum = this.mNinePatchBorderInfo.getHorizontalStaticLengthSum(); const staticHeightSum = this.mNinePatchBorderInfo.getVerticalStaticLengthSum(); let extraWidth = bound.width() - Math.floor(staticWidthSum * staticRatioScale); let extraHeight = bound.height() - Math.floor(staticHeightSum * staticRatioScale); let staticWidthPartScale = (extraWidth>=0 || staticWidthSum==0) ? 1 : bound.width() / staticWidthSum; let staticHeightPartScale = (extraHeight>=0 || staticHeightSum==0) ? 1 : bound.height() / staticHeightSum; staticWidthPartScale *= staticRatioScale; staticHeightPartScale *= staticRatioScale; const scaleHorizontalWeightSum = this.mNinePatchBorderInfo.getHorizontalScaleLengthSum(); const scaleVerticalWeightSum = this.mNinePatchBorderInfo.getVerticalScaleLengthSum(); const drawColumn = (srcFromX:number, srcToX:number, dstFromX:number, dstToX:number)=>{ const heightParts = this.mNinePatchBorderInfo.getVerticalTypedValues(); let srcFromY = 1; let dstFromY = 0; for(let i = 0, size=heightParts.length; i<size; i++){ let typedValue = heightParts[i]; let isScalePart = NinePatchBorderInfo.isScaleType(typedValue); let srcHeight = NinePatchBorderInfo.getValueUnpack(typedValue); if(srcHeight <= 0) continue; let dstHeight; if(isScalePart){ if(scaleVerticalWeightSum == 0) continue; dstHeight = extraHeight * srcHeight / scaleVerticalWeightSum; if(dstHeight <= 0) continue; }else{ //static part dstHeight = srcHeight * staticHeightPartScale; } let srcRect = this.mTmpRect; let dstRect = this.mTmpRect2; srcRect.set(srcFromX, srcFromY, srcToX, srcFromY+srcHeight); dstRect.set(dstFromX, dstFromY, dstToX, dstFromY+dstHeight); // eat half pix for iOS to prevent draw the nine-patch border if (srcRect.bottom === image.height - 1) srcRect.bottom -= 0.5; if (srcRect.right === image.width - 1) srcRect.right -= 0.5; canvas.drawImage(image, srcRect, dstRect); srcFromY+=srcHeight; dstFromY+=dstHeight; } }; const widthParts = this.mNinePatchBorderInfo.getHorizontalTypedValues(); let srcFromX = 1; let dstFromX = 0; for(let i = 0, size=widthParts.length; i<size; i++){ let typedValue = widthParts[i]; let isScalePart = NinePatchBorderInfo.isScaleType(typedValue); let srcWidth = NinePatchBorderInfo.getValueUnpack(typedValue); let dstWidth; if(isScalePart) { dstWidth = extraWidth * srcWidth / scaleHorizontalWeightSum; } else {//static part dstWidth = srcWidth * staticWidthPartScale; } if(dstWidth <= 0) continue; drawColumn(srcFromX, srcFromX+srcWidth, dstFromX, dstFromX+dstWidth); srcFromX+=srcWidth; dstFromX+=dstWidth; } canvas.setImageSmoothingEnabled(smoothEnableBak); } getPadding(padding:android.graphics.Rect):boolean { let info = this.mNinePatchBorderInfo; if(!info) return false; let imageRatio = this.getImage() && this.getImage().getImageRatio() || 1; const staticRatioScale = android.content.res.Resources.getDisplayMetrics().density / imageRatio; padding.set(Math.floor(info.getPaddingLeft() * staticRatioScale), Math.floor(info.getPaddingTop() * staticRatioScale), Math.floor(info.getPaddingRight() * staticRatioScale), Math.floor(info.getPaddingBottom() * staticRatioScale)); return true; } } class NinePatchBorderInfo { //src data (start & end pixel excluded) //private leftBorder:number[]; //private topBorder:number[]; //private rightBorder:number[]; //private bottomBorder:number[]; //parsed data private horizontalTypedValues:number[]; private horizontalStaticLengthSum = 0; private horizontalScaleLengthSum = 0; private verticalTypedValues:number[]; private verticalStaticLengthSum = 0; private verticalScaleLengthSum = 0; private paddingLeft = 0; private paddingTop = 0; private paddingRight = 0; private paddingBottom = 0; constructor(leftBorder:number[], topBorder:number[], rightBorder:number[], bottomBorder:number[]){ //this.leftBorder = leftBorder; //this.topBorder = topBorder; //this.rightBorder = rightBorder; //this.bottomBorder = bottomBorder; this.horizontalTypedValues = []; this.verticalTypedValues = []; let tmpLength = 0; let currentStatic = true; for(let color of leftBorder){ let isScaleColor = NinePatchBorderInfo.isScaleColor(color); let typeChange = (isScaleColor && currentStatic) || (!isScaleColor && !currentStatic); if(typeChange) { let lengthValue = currentStatic ? tmpLength : -tmpLength; //negative value mean scale part if(currentStatic) this.verticalStaticLengthSum += tmpLength; this.verticalTypedValues.push(lengthValue); tmpLength = 1; }else{ tmpLength++; } currentStatic = !isScaleColor; } if(currentStatic) this.verticalStaticLengthSum += tmpLength; this.verticalScaleLengthSum = leftBorder.length - this.verticalStaticLengthSum; this.verticalTypedValues.push(currentStatic ? tmpLength : -tmpLength);//negative value mean scale pixel tmpLength = 0; currentStatic = true; for(let color of topBorder){ let isScaleColor = NinePatchBorderInfo.isScaleColor(color); let typeChange = (isScaleColor && currentStatic) || (!isScaleColor && !currentStatic); if(typeChange) { let lengthValue = currentStatic ? tmpLength : -tmpLength; //negative value mean scale part if(currentStatic) this.horizontalStaticLengthSum += tmpLength; this.horizontalTypedValues.push(lengthValue); tmpLength = 1; }else{ tmpLength++; } currentStatic = !isScaleColor; } if(currentStatic) this.horizontalStaticLengthSum += tmpLength; this.horizontalScaleLengthSum = topBorder.length - this.horizontalStaticLengthSum; this.horizontalTypedValues.push(currentStatic ? tmpLength : -tmpLength);//negative value mean scale pixel //padding from left & top if(this.horizontalTypedValues.length>=3){ this.paddingLeft = Math.max(0, this.horizontalTypedValues[0]); this.paddingRight = Math.max(0, this.horizontalTypedValues[this.horizontalTypedValues.length-1]); } if(this.verticalTypedValues.length>=3){ this.paddingTop = Math.max(0, this.verticalTypedValues[0]); this.paddingBottom = Math.max(0, this.verticalTypedValues[this.verticalTypedValues.length-1]); } //override if rightBorder / bottomBorder defined for(let i = 0, length = rightBorder.length; i<length; i++){ if(NinePatchBorderInfo.isScaleColor(rightBorder[i])){ this.paddingTop = i; break; } } for(let i = 0, length = rightBorder.length; i<length; i++){ if(NinePatchBorderInfo.isScaleColor(rightBorder[length-1-i])){ this.paddingBottom = i; break; } } for(let i = 0, length = bottomBorder.length; i<length; i++){ if(NinePatchBorderInfo.isScaleColor(bottomBorder[i])){ this.paddingLeft = i; break; } } for(let i = 0, length = bottomBorder.length; i<length; i++){ if(NinePatchBorderInfo.isScaleColor(bottomBorder[length-1-i])){ this.paddingRight = i; break; } } } static isScaleColor(color:number):boolean { //return color === 0xff000000; return Color.alpha(color) > 200 && Color.red(color) < 50 && Color.green(color) < 50 && Color.blue(color) < 50; } static isScaleType(typedValue:number):boolean { return typedValue < 0; } static getValueUnpack(typedValue:number):number { return Math.abs(typedValue); } getHorizontalTypedValues():number[] { return this.horizontalTypedValues; } getHorizontalStaticLengthSum():number { return this.horizontalStaticLengthSum; } getHorizontalScaleLengthSum():number { return this.horizontalScaleLengthSum; } getVerticalTypedValues():number[] { return this.verticalTypedValues; } getVerticalStaticLengthSum():number { return this.verticalStaticLengthSum; } getVerticalScaleLengthSum():number { return this.verticalScaleLengthSum; } getPaddingLeft():number { return this.paddingLeft; } getPaddingTop():number { return this.paddingTop; } getPaddingRight():number { return this.paddingRight; } getPaddingBottom():number { return this.paddingBottom; } } }
the_stack
import { ContainerAdapterClient } from '../../container_adapter_client' import { MasterNodeRegTestContainer } from '@defichain/testcontainers' import { ExtHTLC, HTLC, ICXClaimDFCHTLCInfo, ICXDFCHTLCInfo, ICXEXTHTLCInfo, ICXGenericResult, ICXHTLCStatus, ICXHTLCType, ICXListHTLCOptions, ICXOffer, ICXOfferInfo, ICXOrder, ICXOrderInfo, ICXOrderStatus } from '../../../src/category/icxorderbook' import BigNumber from 'bignumber.js' import { accountBTC, accountDFI, ICXSetup, idDFI, symbolDFI } from './icx_setup' describe('ICXOrderBook.listHTLCs', () => { const container = new MasterNodeRegTestContainer() const client = new ContainerAdapterClient(container) const icxSetup = new ICXSetup(container, client) beforeAll(async () => { await container.start() await container.waitForReady() await container.waitForWalletCoinbaseMaturity() await icxSetup.createAccounts() await icxSetup.createBTCToken() await icxSetup.initializeTokensIds() await icxSetup.mintBTCtoken(100) await icxSetup.fundAccount(accountDFI, symbolDFI, 500) await icxSetup.fundAccount(accountBTC, symbolDFI, 10) // for fee await icxSetup.createBTCDFIPool() await icxSetup.addLiquidityToBTCDFIPool(1, 100) await icxSetup.setTakerFee(0.001) }) afterAll(async () => { await container.stop() }) afterEach(async () => { await icxSetup.closeAllOpenOffers() }) it('should list HTLCs for particular offer', async () => { // create order - maker const order: ICXOrder = { tokenFrom: idDFI, chainTo: 'BTC', ownerAddress: accountDFI, receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', amountFrom: new BigNumber(15), orderPrice: new BigNumber(0.01) } const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, []) const createOrderTxId = createOrderResult.txid await container.generate(1) // list ICX orders anc check const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders() expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId].status).toStrictEqual(ICXOrderStatus.OPEN) const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber') // make offer to partial amount 10 DFI - taker const offer: ICXOffer = { orderTx: createOrderTxId, amount: new BigNumber(0.10), // 0.10 BTC = 10 DFI ownerAddress: accountBTC } const makeOfferResult = await client.icxorderbook.makeOffer(offer, []) const makeOfferTxId = makeOfferResult.txid await container.generate(1) const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber') // check fee of 0.01 DFI has been reduced from the accountBTCBeforeOffer[idDFI] // Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.01)) // List the ICX offers for orderTx = createOrderTxId and check const offersForOrder1: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.icxorderbook.listOrders({ orderTx: createOrderTxId }) expect(Object.keys(offersForOrder1).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. expect((offersForOrder1 as Record<string, ICXOfferInfo>)[makeOfferTxId].status).toStrictEqual(ICXOrderStatus.OPEN) const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') // create DFCHTLC - maker const DFCHTLC: HTLC = { offerTx: makeOfferTxId, amount: new BigNumber(10), // in DFC hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', timeout: 1440 } const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid await container.generate(1) const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01)) // List htlc anc check const listHTLCOptions: ICXListHTLCOptions = { offerTx: makeOfferTxId } const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptions) expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. expect(HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // submit EXT HTLC - taker const ExtHTLC: ExtHTLC = { offerTx: makeOfferTxId, amount: new BigNumber(0.10), hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N', ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252', timeout: 24 } const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid await container.generate(1) // List htlc and check const listHTLCOptionsAfterExtHTLC = { offerTx: makeOfferTxId } const HTLCsAfterExtHTLC: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsAfterExtHTLC) expect(Object.keys(HTLCsAfterExtHTLC).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm. expect(HTLCsAfterExtHTLC[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual( { type: ICXHTLCType.EXTERNAL, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: ExtHTLC.amount, amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice), hash: ExtHTLC.hash, htlcScriptAddress: ExtHTLC.htlcScriptAddress, ownerPubkey: ExtHTLC.ownerPubkey, timeout: new BigNumber(ExtHTLC.timeout), height: expect.any(BigNumber) } ) expect(HTLCsAfterExtHTLC[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) }) it('should test ICXListHTLCOptions.limit parameter functionality', async () => { const { order, createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01)) const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC) const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') // create DFCHTLC - maker const DFCHTLC: HTLC = { offerTx: makeOfferTxId, amount: new BigNumber(10), // in DFC hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', timeout: 1440 } const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid await container.generate(1) const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01)) // List htlc anc check const listHTLCOptions: ICXListHTLCOptions = { offerTx: makeOfferTxId } const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptions) expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. expect(HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // submit EXT HTLC - taker const ExtHTLC: ExtHTLC = { offerTx: makeOfferTxId, amount: new BigNumber(0.10), hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N', ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252', timeout: 24 } const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid await container.generate(1) // List htlc without limit param and check const listHTLCOptionsAfterExtHTLC = { offerTx: makeOfferTxId } const HTLCsAfterExtHTLC: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsAfterExtHTLC) expect(Object.keys(HTLCsAfterExtHTLC).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm. expect(HTLCsAfterExtHTLC[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual( { type: ICXHTLCType.EXTERNAL, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: ExtHTLC.amount, amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice), hash: ExtHTLC.hash, htlcScriptAddress: ExtHTLC.htlcScriptAddress, ownerPubkey: ExtHTLC.ownerPubkey, timeout: new BigNumber(ExtHTLC.timeout), height: expect.any(BigNumber) } ) expect(HTLCsAfterExtHTLC[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // List htlc with limit of 1 and check const listHTLCOptionsWithLimit1 = { offerTx: makeOfferTxId, limit: 1 } const HTLCsWithLimit1: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsWithLimit1) expect(Object.keys(HTLCsWithLimit1).length).toStrictEqual(2) }) it.skip('should list closed HTLCs with ICXListHTLCOptions.closed parameter after HTLCs are expired', async () => { jest.setTimeout(1200000) const startBlockHeight = (await container.call('getblockchaininfo', [])).blocks const { order, createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01)) const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC) const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') // create DFCHTLC - maker const DFCHTLC: HTLC = { offerTx: makeOfferTxId, amount: new BigNumber(10), // in DFC hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', timeout: 1440 } const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid await container.generate(1) const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01)) // submit EXT HTLC - taker const ExtHTLC: ExtHTLC = { offerTx: makeOfferTxId, amount: new BigNumber(0.10), hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N', ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252', timeout: 24 } const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid await container.generate(1) // List htlc without limit param and check const listHTLCOptions: ICXListHTLCOptions = { offerTx: makeOfferTxId } const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptions) expect(Object.keys(HTLCs).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm. expect(HTLCs[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual( { type: ICXHTLCType.EXTERNAL, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: ExtHTLC.amount, amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice), hash: ExtHTLC.hash, htlcScriptAddress: ExtHTLC.htlcScriptAddress, ownerPubkey: ExtHTLC.ownerPubkey, timeout: new BigNumber(ExtHTLC.timeout), height: expect.any(BigNumber) } ) expect(HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // expire HTLCs await container.generate(2000) const endBlockHeight = (await container.call('getblockchaininfo', [])).blocks expect(endBlockHeight).toBeGreaterThan(Number(startBlockHeight) + Number(550)) // List htlc anc check const listHTLCOptionsAfterExpiry = { offerTx: makeOfferTxId } const HTLCsAfterExpiry: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsAfterExpiry) expect(Object.keys(HTLCsAfterExpiry).length).toStrictEqual(2) // NOTE(surangap): EXT HTLC will still be in OPEN state // List refended htlcs also and check const listHTLCOptionsWithRefunded = { offerTx: makeOfferTxId, closed: true } const HTLCsWithRefunded: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsWithRefunded) expect(Object.keys(HTLCsWithRefunded).length).toStrictEqual(3) }) it('should list closed HTLCs with ICXListHTLCOptions.closed parameter after DFC HTLC claim', async () => { const { order, createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01)) const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC) const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') // create DFCHTLC - maker const DFCHTLC: HTLC = { offerTx: makeOfferTxId, amount: new BigNumber(10), // in DFC hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', timeout: 1440 } const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid await container.generate(1) const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01)) // List htlc anc check const listHTLCOptions: ICXListHTLCOptions = { offerTx: makeOfferTxId } const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptions) expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. expect(HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // submit EXT HTLC - taker const ExtHTLC: ExtHTLC = { offerTx: makeOfferTxId, amount: new BigNumber(0.10), hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', htlcScriptAddress: '13sJQ9wBWh8ssihHUgAaCmNWJbBAG5Hr9N', ownerPubkey: '036494e7c9467c8c7ff3bf29e841907fb0fa24241866569944ea422479ec0e6252', timeout: 24 } const ExtHTLCTxId = (await client.icxorderbook.submitExtHTLC(ExtHTLC)).txid await container.generate(1) // List htlc without limit param and check const listHTLCOptionsAfterExtHTLC = { offerTx: makeOfferTxId } const HTLCsAfterExtHTLC: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsAfterExtHTLC) expect(Object.keys(HTLCsAfterExtHTLC).length).toStrictEqual(3) // extra entry for the warning text returned by the RPC atm. expect(HTLCsAfterExtHTLC[ExtHTLCTxId] as ICXEXTHTLCInfo).toStrictEqual( { type: ICXHTLCType.EXTERNAL, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: ExtHTLC.amount, amountInDFCAsset: ExtHTLC.amount.dividedBy(order.orderPrice), hash: ExtHTLC.hash, htlcScriptAddress: ExtHTLC.htlcScriptAddress, ownerPubkey: ExtHTLC.ownerPubkey, timeout: new BigNumber(ExtHTLC.timeout), height: expect.any(BigNumber) } ) expect(HTLCsAfterExtHTLC[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // claim - taker const claimTxId = (await client.icxorderbook.claimDFCHTLC(DFCHTLCTxId, 'f75a61ad8f7a6e0ab701d5be1f5d4523a9b534571e4e92e0c4610c6a6784ccef')).txid await container.generate(1) // List HTLCs for offer const listHTLCOptionsAfterClaim = { offerTx: makeOfferTxId } const HTLCsAfterClaim: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsAfterClaim) expect(Object.keys(HTLCsAfterClaim).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. // we have a common field "type", use that to narrow down the record if (HTLCsAfterClaim[claimTxId].type === ICXHTLCType.CLAIM_DFC) { // ICXClaimDFCHTLCInfo cast const ClaimHTLCInfo: ICXClaimDFCHTLCInfo = HTLCsAfterClaim[claimTxId] as ICXClaimDFCHTLCInfo expect(ClaimHTLCInfo.dfchtlcTx).toStrictEqual(DFCHTLCTxId) expect(ClaimHTLCInfo.seed).toStrictEqual('f75a61ad8f7a6e0ab701d5be1f5d4523a9b534571e4e92e0c4610c6a6784ccef') } // List htlc with closed=true and check const listHTLCOptionsWithClosed = { offerTx: makeOfferTxId, closed: true } const HTLCsWithClosed: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsWithClosed) expect(Object.keys(HTLCsWithClosed).length).toStrictEqual(4) // extra entry for the warning text returned by the RPC atm. // we have a common field "type", use that to narrow down the record if (HTLCsWithClosed[claimTxId].type === ICXHTLCType.CLAIM_DFC) { // ICXClaimDFCHTLCInfo cast const ClaimHTLCInfo: ICXClaimDFCHTLCInfo = HTLCsWithClosed[claimTxId] as ICXClaimDFCHTLCInfo expect(ClaimHTLCInfo.dfchtlcTx).toStrictEqual(DFCHTLCTxId) expect(ClaimHTLCInfo.seed).toStrictEqual('f75a61ad8f7a6e0ab701d5be1f5d4523a9b534571e4e92e0c4610c6a6784ccef') } if (HTLCsWithClosed[DFCHTLCTxId].type === ICXHTLCType.DFC) { // ICXDFCHTLCInfo cast const DFCHTLCInfo: ICXDFCHTLCInfo = HTLCsWithClosed[DFCHTLCTxId] as ICXDFCHTLCInfo expect(DFCHTLCInfo.offerTx).toStrictEqual(makeOfferTxId) expect(DFCHTLCInfo.status).toStrictEqual(ICXHTLCStatus.CLAIMED) } if (HTLCsWithClosed[ExtHTLCTxId].type === ICXHTLCType.EXTERNAL) { // ICXEXTHTLCInfo cast const ExtHTLCInfo: ICXEXTHTLCInfo = HTLCsWithClosed[ExtHTLCTxId] as ICXEXTHTLCInfo expect(ExtHTLCInfo.offerTx).toStrictEqual(makeOfferTxId) expect(ExtHTLCInfo.status).toStrictEqual(ICXHTLCStatus.CLOSED) } }) it('should return an empty result set when invalid ICXListHTLCOptions.offerTx is passed', async () => { const { order, createOrderTxId } = await icxSetup.createDFISellOrder('BTC', accountDFI, '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941', new BigNumber(15), new BigNumber(0.01)) const { makeOfferTxId } = await icxSetup.createDFIBuyOffer(createOrderTxId, new BigNumber(0.10), accountBTC) const accountDFIBeforeDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') // create DFCHTLC - maker const DFCHTLC: HTLC = { offerTx: makeOfferTxId, amount: new BigNumber(10), // in DFC hash: '957fc0fd643f605b2938e0631a61529fd70bd35b2162a21d978c41e5241a5220', timeout: 1440 } const DFCHTLCTxId = (await client.icxorderbook.submitDFCHTLC(DFCHTLC)).txid await container.generate(1) const accountDFIAfterDFCHTLC: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber') expect(accountDFIAfterDFCHTLC[idDFI]).toStrictEqual(accountDFIBeforeDFCHTLC[idDFI].minus(0.01)) // List htlc and check const listHTLCOptions: ICXListHTLCOptions = { offerTx: makeOfferTxId } const HTLCs: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptions) expect(Object.keys(HTLCs).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm. expect(HTLCs[DFCHTLCTxId] as ICXDFCHTLCInfo).toStrictEqual( { type: ICXHTLCType.DFC, status: ICXOrderStatus.OPEN, offerTx: makeOfferTxId, amount: DFCHTLC.amount, amountInEXTAsset: DFCHTLC.amount.multipliedBy(order.orderPrice), hash: DFCHTLC.hash, timeout: new BigNumber(DFCHTLC.timeout as number), height: expect.any(BigNumber), refundHeight: expect.any(BigNumber) } ) // List htlcs with invalid offer tx "123" and check const listHTLCOptionsIncorrectOfferTx = { offerTx: '123' } const HTLCsForIncorrectOfferTx: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsIncorrectOfferTx) expect(Object.keys(HTLCsForIncorrectOfferTx).length).toStrictEqual(1) // extra entry for the warning text returned by the RPC atm. // List htlcs with invalid offer tx "INVALID_OFFER_TX" and check const listHTLCOptionsIncorrectOfferTx2 = { offerTx: 'INVALID_OFFER_TX' } const HTLCsForIncorrectOfferTx2: Record<string, ICXDFCHTLCInfo | ICXEXTHTLCInfo | ICXClaimDFCHTLCInfo> = await client.icxorderbook.listHTLCs(listHTLCOptionsIncorrectOfferTx2) expect(Object.keys(HTLCsForIncorrectOfferTx2).length).toStrictEqual(1) // extra entry for the warning text returned by the RPC atm. }) })
the_stack
import { errors, statuses } from '@tanker/core'; import type { Tanker, b64string, Verification, VerificationMethod, LegacyEmailVerificationMethod } from '@tanker/core'; import { utils } from '@tanker/crypto'; import { fetch } from '@tanker/http-utils'; import { expect, uuid } from '@tanker/test-utils'; import { createProvisionalIdentity, getPublicIdentity } from '@tanker/identity'; import type { AppHelper, TestArgs } from './helpers'; import { oidcSettings, trustchaindUrl } from './helpers'; const { READY, IDENTITY_VERIFICATION_NEEDED, IDENTITY_REGISTRATION_NEEDED } = statuses; const verificationThrottlingAttempts = 3; async function getGoogleIdToken(refreshToken: string): Promise<string> { const formData = JSON.stringify({ client_id: oidcSettings.googleAuth.clientId, client_secret: oidcSettings.googleAuth.clientSecret, grant_type: 'refresh_token', refresh_token: refreshToken, }); const response = await fetch('https://www.googleapis.com/oauth2/v4/token', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: formData, }); const data = await response.json(); return data.id_token; } const expectVerificationToMatchMethod = (verification: Verification, method: VerificationMethod | LegacyEmailVerificationMethod) => { // @ts-expect-error email might not be defined const { type, email, phoneNumber } = method; expect(type in verification).to.be.true; if (type === 'email') { // @ts-expect-error I tested the 'email' type already expect(email).to.equal(verification.email); expect(phoneNumber).to.be.undefined; // @ts-expect-error I tested the 'email' type expect(verification.phoneNumber).to.be.undefined; } else if (type === 'phoneNumber') { // @ts-expect-error I tested the 'phoneNumber' type already expect(phoneNumber).to.equal(verification.phoneNumber); expect(email).to.be.undefined; // @ts-expect-error I tested the 'phoneNumber' type already expect(verification.email).to.be.undefined; } }; const expectVerification = async (tanker: Tanker, identity: string, verification: Verification) => { await tanker.start(identity); expect(tanker.status).to.equal(IDENTITY_VERIFICATION_NEEDED); // Remember for later testing const [method, ...otherMethods] = await tanker.getVerificationMethods(); await tanker.verifyIdentity(verification); expect(tanker.status).to.equal(READY); // Test after verifyIdentity() to allow tests on unregistered verification types expect(otherMethods).to.be.an('array').that.is.empty; expectVerificationToMatchMethod(verification, method!); }; export const generateVerificationTests = (args: TestArgs) => { describe('verification', () => { let bobLaptop: Tanker; let bobPhone: Tanker; let bobIdentity: b64string; let appHelper: AppHelper; before(() => { ({ appHelper } = args); }); beforeEach(async () => { const bobId = uuid.v4(); bobIdentity = await appHelper.generateIdentity(bobId); bobLaptop = args.makeTanker(); bobPhone = args.makeTanker(); await bobLaptop.start(bobIdentity); }); afterEach(async () => { await Promise.all([ bobLaptop.stop(), bobPhone.stop(), ]); }); describe('verification method administration', () => { it('needs registration after start', async () => { expect(bobLaptop.status).to.equal(IDENTITY_REGISTRATION_NEEDED); }); it('can test that passphrase verification method has been registered', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'passphrase' }]); }); it('can test that email verification method has been registered', async () => { const email = 'john.doe@tanker.io'; const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'email', email }]); }); it('can test that phone number verification method has been registered', async () => { const phoneNumber = '+33639986789'; const verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber }]); }); it('should fail to register an email verification method if the verification code is wrong', async () => { const verificationCode = await appHelper.getWrongEmailVerificationCode('john.doe@tanker.io'); await expect(bobLaptop.registerIdentity({ email: 'elton.doe@tanker.io', verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to register a phone number verification method if the verification code is wrong', async () => { const phoneNumber = '+33639986789'; const verificationCode = await appHelper.getWrongSMSVerificationCode(phoneNumber); await expect(bobLaptop.registerIdentity({ phoneNumber, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to register an email verification method if the verification code is not for the targeted email', async () => { const verificationCode = await appHelper.getEmailVerificationCode('john.doe@tanker.io'); await expect(bobLaptop.registerIdentity({ email: 'elton.doe@tanker.io', verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to register a phone number verification method if the verification code is not for the targeted phone number', async () => { const verificationCode = await appHelper.getSMSVerificationCode('+33639986789'); await expect(bobLaptop.registerIdentity({ phoneNumber: '+33639989999', verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('can test that every verification methods have been registered', async () => { const email = 'john.doe@tanker.io'; const phoneNumber = '+33639986789'; const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ passphrase: 'passphrase' }); const smsVerificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.setVerificationMethod({ phoneNumber, verificationCode: smsVerificationCode }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([ { type: 'email', email }, { type: 'passphrase' }, { type: 'phoneNumber', phoneNumber }, ]); }); it('can test that email verification method has been updated and use it', async () => { let email = 'john.doe@tanker.io'; let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); // update email email = 'elton.doe@tanker.io'; verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.setVerificationMethod({ email, verificationCode }); // check email is updated in cache expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'email', email }]); // check email can be used on new device await bobPhone.start(bobIdentity); verificationCode = await appHelper.getEmailVerificationCode(email); await bobPhone.verifyIdentity({ email, verificationCode }); // check received email is the updated one on new device expect(await bobPhone.getVerificationMethods()).to.have.deep.members([{ type: 'email', email }]); }); it('can test that phone number verification method has been updated and use it', async () => { let phoneNumber = '+33639986789'; let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); // update phone number phoneNumber = '+33639989999'; verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.setVerificationMethod({ phoneNumber, verificationCode }); // check phone number is updated in cache expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber }]); // check phone number can be used on new device await bobPhone.start(bobIdentity); verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobPhone.verifyIdentity({ phoneNumber, verificationCode }); // check received phone number is the updated one on new device expect(await bobPhone.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber }]); }); it('should fail to update the email verification method if the verification code is wrong', async () => { let email = 'john.doe@tanker.io'; let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); // try to update email with a code containing a typo email = 'elton.doe@tanker.io'; verificationCode = await appHelper.getWrongEmailVerificationCode(email); await expect(bobLaptop.setVerificationMethod({ email, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to update the phone number verification method if the verification code is wrong', async () => { let phoneNumber = '+33639986789'; let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); // try to update phone number with a code containing a typo phoneNumber = '+33639989999'; verificationCode = await appHelper.getWrongSMSVerificationCode(phoneNumber); await expect(bobLaptop.setVerificationMethod({ phoneNumber, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to update the email verification method if the verification code is not for the targeted email', async () => { const email = 'john.doe@tanker.io'; let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); // try to update email with a code for another email address verificationCode = await appHelper.getEmailVerificationCode(email); await expect(bobLaptop.setVerificationMethod({ email: 'elton@doe.com', verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); it('should fail to update the phone number verification method if the verification code is not for the targeted phone number', async () => { const phoneNumber = '+33639986789'; let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); // try to update email with a code for another email address verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await expect(bobLaptop.setVerificationMethod({ phoneNumber: '+33639989999', verificationCode })).to.be.rejectedWith(errors.InvalidVerification); }); describe('concurrent calls when managing user permanent identity', () => { it('cannot registerIdentity() before start() is resolved', async () => { const email = 'elton.doe@tanker.io'; const verificationCode = await appHelper.getEmailVerificationCode(email); const promise = bobPhone.start(bobIdentity); await expect(bobPhone.registerIdentity({ email, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed, 'A mutually exclusive call is already in progress'); await expect(promise).to.not.be.rejected; }); it('cannot registerIdentity() concurrently', async () => { const email = 'elton.doe@tanker.io'; const email2 = 'elton.d@tanker.io'; const verificationCode = await appHelper.getEmailVerificationCode(email); const verificationCode2 = await appHelper.getEmailVerificationCode(email2); await bobPhone.start(bobIdentity); const promise = bobPhone.registerIdentity({ email, verificationCode }); await expect(bobPhone.registerIdentity({ email: email2, verificationCode: verificationCode2 })).to.be.rejectedWith(errors.PreconditionFailed, 'A mutually exclusive call is already in progress'); await expect(promise).to.not.be.rejected; }); it('cannot verifyIdentity() before registerIdentity() is resolved', async () => { const email = 'elton.doe@tanker.io'; const verificationCode = await appHelper.getEmailVerificationCode(email); await bobPhone.start(bobIdentity); const promise = bobPhone.registerIdentity({ email, verificationCode }); await expect(bobPhone.verifyIdentity({ email, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed, 'A mutually exclusive call is already in progress'); await expect(promise).to.not.be.rejected; }); it('cannot verifyIdentity() concurrently', async () => { const email = 'john.doe@tanker.io'; let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); verificationCode = await appHelper.getEmailVerificationCode(email); await bobPhone.start(bobIdentity); verificationCode = await appHelper.getEmailVerificationCode(email); const promise = bobPhone.verifyIdentity({ email, verificationCode }); await expect(bobPhone.verifyIdentity({ email, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed, 'A mutually exclusive call is already in progress'); await expect(promise).to.not.be.rejected; }); }); }); describe('verification by passphrase', () => { it('can register a verification passphrase and open a new device with it', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(expectVerification(bobPhone, bobIdentity, { passphrase: 'passphrase' })).to.be.fulfilled; }); it('fails to verify with a wrong passphrase', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(expectVerification(bobPhone, bobIdentity, { passphrase: 'my wrong pass' })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it(`gets throttled with a wrong passphrase over ${verificationThrottlingAttempts} times`, async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobPhone.start(bobIdentity); for (let i = 0; i < verificationThrottlingAttempts; ++i) { await expect(bobPhone.verifyIdentity({ passphrase: 'my wrong pass' })).to.be.rejectedWith(errors.InvalidVerification); } await expect(bobPhone.verifyIdentity({ passphrase: 'my wrong pass' })).to.be.rejectedWith(errors.TooManyAttempts); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('fails to verify without having registered a passphrase', async () => { const email = 'john.doe@tanker.io'; const phoneNumber = '+33639989999'; const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); const phoneNumberVerificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.setVerificationMethod({ phoneNumber, verificationCode: phoneNumberVerificationCode }); await expect(expectVerification(bobPhone, bobIdentity, { passphrase: 'my pass' })).to.be.rejectedWith(errors.PreconditionFailed); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('can register a verification passphrase, update it, and verify with the new passphrase only', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobLaptop.setVerificationMethod({ passphrase: 'new passphrase' }); await expect(expectVerification(bobPhone, bobIdentity, { passphrase: 'passphrase' })).to.be.rejectedWith(errors.InvalidVerification); await bobPhone.stop(); await expect(expectVerification(bobPhone, bobIdentity, { passphrase: 'new passphrase' })).to.be.fulfilled; }); it('fails to setVerificationMethod with preverified email if preverified verification flag is disabled', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const email = 'john.doe@tanker.io'; await expect(bobLaptop.setVerificationMethod({ preverifiedEmail: email })).to.be.rejectedWith(errors.PreconditionFailed); }); it('fails to setVerificationMethod with preverified phone number if preverified verification flag is disabled', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const phoneNumber = '+33639989999'; await expect(bobLaptop.setVerificationMethod({ preverifiedPhoneNumber: phoneNumber })).to.be.rejectedWith(errors.PreconditionFailed); }); }); describe('verification by email', () => { const email = 'john.doe@tanker.io'; it('can register a verification email and verify with a valid verification code', async () => { let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); verificationCode = await appHelper.getEmailVerificationCode(email); await expect(expectVerification(bobPhone, bobIdentity, { email, verificationCode })).to.be.fulfilled; }); it('fails to register with a wrong verification code', async () => { const verificationCode = await appHelper.getWrongEmailVerificationCode(email); await expect(bobLaptop.registerIdentity({ email, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobLaptop.status).to.equal(IDENTITY_REGISTRATION_NEEDED); }); it('fails to verify with a wrong verification code', async () => { let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); verificationCode = await appHelper.getWrongEmailVerificationCode(email); await expect(expectVerification(bobPhone, bobIdentity, { email, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it(`should get throttled if email verification code is wrong over ${verificationThrottlingAttempts} times`, async () => { let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); verificationCode = await appHelper.getWrongEmailVerificationCode(email); await bobPhone.start(bobIdentity); for (let i = 0; i < verificationThrottlingAttempts; ++i) { await expect(bobPhone.verifyIdentity({ email, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); } await expect(bobPhone.verifyIdentity({ email, verificationCode })).to.be.rejectedWith(errors.TooManyAttempts); }); it('fails to verify without having registered an email address', async () => { const phoneNumber = '+33639989999'; await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const phoneNumberVerificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.setVerificationMethod({ phoneNumber, verificationCode: phoneNumberVerificationCode }); const verificationCode = await appHelper.getEmailVerificationCode(email); await expect(expectVerification(bobPhone, bobIdentity, { email, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed); // status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); }); describe('verification by sms', () => { const phoneNumber = '+33639986789'; it('can register a verification phone number and verify with a valid verification code', async () => { let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await expect(expectVerification(bobPhone, bobIdentity, { phoneNumber, verificationCode })).to.be.fulfilled; }); it('fails to register with a wrong verification code', async () => { const verificationCode = await appHelper.getWrongSMSVerificationCode(phoneNumber); await expect(bobLaptop.registerIdentity({ phoneNumber, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobLaptop.status).to.equal(IDENTITY_REGISTRATION_NEEDED); }); it('fails to verify with a wrong verification code', async () => { let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); verificationCode = await appHelper.getWrongSMSVerificationCode(phoneNumber); await expect(expectVerification(bobPhone, bobIdentity, { phoneNumber, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it(`should get throttled if the verification code is wrong over ${verificationThrottlingAttempts} times`, async () => { let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); verificationCode = await appHelper.getWrongSMSVerificationCode(phoneNumber); await bobPhone.start(bobIdentity); for (let i = 0; i < verificationThrottlingAttempts; ++i) { await expect(bobPhone.verifyIdentity({ phoneNumber, verificationCode })).to.be.rejectedWith(errors.InvalidVerification); } await expect(bobPhone.verifyIdentity({ phoneNumber, verificationCode })).to.be.rejectedWith(errors.TooManyAttempts); }); it('fails to verify without having registered a phone number', async () => { const email = 'john.doe@tanker.io'; await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const emailVerificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.setVerificationMethod({ email, verificationCode: emailVerificationCode }); const verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await expect(expectVerification(bobPhone, bobIdentity, { phoneNumber, verificationCode })).to.be.rejectedWith(errors.PreconditionFailed); // status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); }); describe('verification with preverified email', () => { const email = 'john.doe@tanker.io'; const preverifiedEmail = 'elton.doe@tanker.io'; beforeEach(async () => { await appHelper.setPreverifiedMethodEnabled(); }); it('fails when registering with a preverified email', async () => { await expect(bobLaptop.registerIdentity({ preverifiedEmail })).to.be.rejectedWith(errors.InvalidArgument, 'cannot register identity with preverified methods'); }); it('fails when verifying identity with preverified email', async () => { const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobPhone.start(bobIdentity); await expect(bobPhone.verifyIdentity({ preverifiedEmail: email })).to.be.rejectedWith(errors.InvalidArgument, 'cannot verify identity with preverified methods'); }); it('registers with an email, updates to preverified email when calling setVerificationMethod, and updates to normal email when verifying', async () => { let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedEmail }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedEmail', preverifiedEmail }]); await bobPhone.start(bobIdentity); verificationCode = await appHelper.getEmailVerificationCode(preverifiedEmail); await bobPhone.verifyIdentity({ email: preverifiedEmail, verificationCode }); expect(await bobPhone.getVerificationMethods()).to.have.deep.members([{ type: 'email', email: preverifiedEmail }]); }); it('register with an email, updates to preverified email when calling setVerificationMethod with the same email', async () => { const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedEmail: email }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedEmail', preverifiedEmail: email }]); }); it('turns preverified email method into email method when calling setVerificationMethod', async () => { let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedEmail }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedEmail', preverifiedEmail }]); verificationCode = await appHelper.getEmailVerificationCode(preverifiedEmail); await bobLaptop.setVerificationMethod({ email: preverifiedEmail, verificationCode }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'email', email: preverifiedEmail }]); }); it('turns preverified email method into email method when calling verifyProvisionalIdentity', async () => { const verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedEmail }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedEmail', preverifiedEmail }]); const provisionalIdentity = await appHelper.generateEmailProvisionalIdentity(preverifiedEmail); await appHelper.attachVerifyEmailProvisionalIdentity(bobLaptop, provisionalIdentity); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'email', email: preverifiedEmail }]); }); it('adds preverified email as a new verification method', async () => { const phoneNumber = '+33639986789'; let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedEmail }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([ { type: 'phoneNumber', phoneNumber }, { type: 'preverifiedEmail', preverifiedEmail }]); await bobPhone.start(bobIdentity); verificationCode = await appHelper.getEmailVerificationCode(preverifiedEmail); await bobPhone.verifyIdentity({ email: preverifiedEmail, verificationCode }); expect(await bobPhone.getVerificationMethods()).to.have.deep.members([ { type: 'phoneNumber', phoneNumber }, { type: 'email', email: preverifiedEmail }]); }); }); describe('verification with preverified phone number', () => { const phoneNumber = '+33601020304'; const preverifiedPhoneNumber = '+33605060708'; beforeEach(async () => { await appHelper.setPreverifiedMethodEnabled(); }); it('fails when registering with a preverified phone number', async () => { await expect(bobLaptop.registerIdentity({ preverifiedPhoneNumber })).to.be.rejectedWith(errors.InvalidArgument, 'cannot register identity with preverified methods'); }); it('fails when verifying identity with preverified phone number', async () => { const verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobPhone.start(bobIdentity); await expect(bobPhone.verifyIdentity({ preverifiedPhoneNumber: phoneNumber })).to.be.rejectedWith(errors.InvalidArgument, 'cannot verify identity with preverified methods'); }); it('registers with a phone number, updates to preverified phone number when calling setVerificationMethod, and updates to normal phone number when verifying', async () => { let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedPhoneNumber }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedPhoneNumber', preverifiedPhoneNumber }]); await bobPhone.start(bobIdentity); verificationCode = await appHelper.getSMSVerificationCode(preverifiedPhoneNumber); await bobPhone.verifyIdentity({ phoneNumber: preverifiedPhoneNumber, verificationCode }); expect(await bobPhone.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber: preverifiedPhoneNumber }]); }); it('register with a phone number, updates to preverified phone number when calling setVerificationMethod with the same phone number', async () => { const verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedPhoneNumber: phoneNumber }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedPhoneNumber', preverifiedPhoneNumber: phoneNumber }]); }); it('turns preverified phone number method into phone number method when calling setVerificationMethod', async () => { let verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedPhoneNumber }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedPhoneNumber', preverifiedPhoneNumber }]); verificationCode = await appHelper.getSMSVerificationCode(preverifiedPhoneNumber); await bobLaptop.setVerificationMethod({ phoneNumber: preverifiedPhoneNumber, verificationCode }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber: preverifiedPhoneNumber }]); }); it('turns preverified phone number method into phone number method when calling verifyProvisionalIdentity', async () => { const verificationCode = await appHelper.getSMSVerificationCode(phoneNumber); await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedPhoneNumber }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'preverifiedPhoneNumber', preverifiedPhoneNumber }]); const provisionalIdentity = await appHelper.generatePhoneNumberProvisionalIdentity(preverifiedPhoneNumber); await appHelper.attachVerifyPhoneNumberProvisionalIdentity(bobLaptop, provisionalIdentity); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'phoneNumber', phoneNumber: preverifiedPhoneNumber }]); }); it('adds preverified phone number as a new verification method', async () => { const email = 'john.doe@tanker.io'; let verificationCode = await appHelper.getEmailVerificationCode(email); await bobLaptop.registerIdentity({ email, verificationCode }); await bobLaptop.setVerificationMethod({ preverifiedPhoneNumber }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([ { type: 'email', email }, { type: 'preverifiedPhoneNumber', preverifiedPhoneNumber }]); await bobPhone.start(bobIdentity); verificationCode = await appHelper.getSMSVerificationCode(preverifiedPhoneNumber); await bobPhone.verifyIdentity({ phoneNumber: preverifiedPhoneNumber, verificationCode }); expect(await bobPhone.getVerificationMethods()).to.have.deep.members([ { type: 'email', email }, { type: 'phoneNumber', phoneNumber: preverifiedPhoneNumber }]); }); }); describe('verification by oidc id token', () => { const martineRefreshToken = oidcSettings.googleAuth.users.martine.refreshToken; const kevinRefreshToken = oidcSettings.googleAuth.users.kevin.refreshToken; let martineIdToken: string; let kevinIdToken: string; before(async () => { await appHelper.setOIDC(); martineIdToken = await getGoogleIdToken(martineRefreshToken); kevinIdToken = await getGoogleIdToken(kevinRefreshToken); }); after(() => appHelper.unsetOIDC()); it('registers and verifies with an oidc id token', async () => { await bobLaptop.registerIdentity({ oidcIdToken: martineIdToken }); await expect(expectVerification(bobPhone, bobIdentity, { oidcIdToken: martineIdToken })).to.be.fulfilled; }); it('fails to verify a token with incorrect signature', async () => { await bobLaptop.registerIdentity({ oidcIdToken: martineIdToken }); const jwtBinParts = martineIdToken.split('.').map(part => utils.fromSafeBase64(part)); jwtBinParts[2]![5] += 1; // break signature const forgedIdToken = jwtBinParts.map(part => utils.toSafeBase64(part)).join('.').replace(/=/g, ''); await expect(expectVerification(bobPhone, bobIdentity, { oidcIdToken: forgedIdToken })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('fails to verify a valid token for the wrong user', async () => { await bobLaptop.registerIdentity({ oidcIdToken: martineIdToken }); await expect(expectVerification(bobPhone, bobIdentity, { oidcIdToken: kevinIdToken })).to.be.rejectedWith(errors.InvalidVerification); }); it(`gets throttled if failing over ${verificationThrottlingAttempts} times`, async () => { await bobLaptop.registerIdentity({ oidcIdToken: martineIdToken }); await bobPhone.start(bobIdentity); for (let i = 0; i < verificationThrottlingAttempts; ++i) { await expect(bobPhone.verifyIdentity({ oidcIdToken: kevinIdToken })).to.be.rejectedWith(errors.InvalidVerification); } await expect(bobPhone.verifyIdentity({ oidcIdToken: kevinIdToken })).to.be.rejectedWith(errors.TooManyAttempts); }); it('updates and verifies with an oidc id token', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(bobLaptop.setVerificationMethod({ oidcIdToken: martineIdToken })).to.be.fulfilled; await bobPhone.start(bobIdentity); expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); await expect(bobPhone.verifyIdentity({ oidcIdToken: martineIdToken })).to.be.fulfilled; expect(bobPhone.status).to.equal(READY); }); it('fails to verify a provisional identity if the oidc id token contains an email different from the provisional email', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const aliceIdentity = await args.appHelper.generateIdentity(); const aliceLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ passphrase: 'passphrase' }); const email = 'the-ceo@tanker.io'; const provisionalIdentity = await createProvisionalIdentity(utils.toBase64(args.appHelper.appId), 'email', email); const attachResult = await bobLaptop.attachProvisionalIdentity(provisionalIdentity); expect(attachResult).to.deep.equal({ status: IDENTITY_VERIFICATION_NEEDED, verificationMethod: { type: 'email', email }, }); await expect(bobLaptop.verifyProvisionalIdentity({ oidcIdToken: martineIdToken })).to.be.rejectedWith(errors.InvalidArgument, 'does not match provisional identity'); await aliceLaptop.stop(); }); it('decrypt data shared with an attached provisional identity', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const aliceIdentity = await args.appHelper.generateIdentity(); const aliceLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ passphrase: 'passphrase' }); const email = oidcSettings.googleAuth.users.martine.email; const provisionalIdentity = await createProvisionalIdentity(utils.toBase64(args.appHelper.appId), 'email', email); const publicProvisionalIdentity = await getPublicIdentity(provisionalIdentity); const clearText = 'Rivest Shamir Adleman'; const cipherText = await aliceLaptop.encrypt(clearText, { shareWithUsers: [publicProvisionalIdentity] }); const attachResult = await bobLaptop.attachProvisionalIdentity(provisionalIdentity); expect(attachResult).to.deep.equal({ status: IDENTITY_VERIFICATION_NEEDED, verificationMethod: { type: 'email', email }, }); await bobLaptop.verifyProvisionalIdentity({ oidcIdToken: martineIdToken }); const decrypted = await bobLaptop.decrypt(cipherText); expect(decrypted).to.equal(clearText); await aliceLaptop.stop(); }); }); describe('verification key', () => { const corruptVerificationKey = (key: b64string, field: string, position: number): b64string => { const unwrappedKey = utils.fromB64Json(key); const unwrappedField = utils.fromBase64(unwrappedKey[field]); unwrappedField[position] += 1; unwrappedKey[field] = utils.toBase64(unwrappedField); return utils.toB64Json(unwrappedKey); }; let verificationKey: string; let verificationKeyNotUsed: string; beforeEach(async () => { verificationKeyNotUsed = await bobLaptop.generateVerificationKey(); verificationKey = await bobLaptop.generateVerificationKey(); }); it('can use a generated verification key to register', async () => { await bobLaptop.registerIdentity({ verificationKey }); expect(bobLaptop.status).to.equal(READY); }); it('does list the verification key as the unique verification method', async () => { await bobLaptop.registerIdentity({ verificationKey }); expect(await bobLaptop.getVerificationMethods()).to.have.deep.members([{ type: 'verificationKey' }]); }); it('can verify with a verification key', async () => { await bobLaptop.registerIdentity({ verificationKey }); await expect(expectVerification(bobPhone, bobIdentity, { verificationKey })).to.be.fulfilled; }); it('should throw if setting another verification method after verification key has been used', async () => { await bobLaptop.registerIdentity({ verificationKey }); await expect(bobLaptop.setVerificationMethod({ passphrase: 'passphrase' })).to.be.rejectedWith(errors.PreconditionFailed); }); it.skip('registers and verifies two users with the same verificationKey', async () => { const aliceId = uuid.v4(); const aliceIdentity = await appHelper.generateIdentity(aliceId); const aliceLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); await aliceLaptop.registerIdentity({ verificationKey }); await bobLaptop.registerIdentity({ verificationKey }); await bobPhone.start(bobIdentity); await expect(bobPhone.verifyIdentity({ verificationKey })).to.be.fulfilled; const alicePhone = args.makeTanker(); await alicePhone.start(aliceIdentity); await expect(alicePhone.verifyIdentity({ verificationKey })).to.be.fulfilled; await aliceLaptop.stop(); }); describe('register identity with an invalid verification key', () => { beforeEach(async () => { await bobPhone.start(bobIdentity); }); it('throws InvalidVerification when using an obviously wrong verification key', async () => { await expect(bobPhone.registerIdentity({ verificationKey: 'not_a_verification_key' })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_REGISTRATION_NEEDED); }); it('throws InvalidVerification when using a corrupt verification key', async () => { const badKeys = [ corruptVerificationKey(verificationKey, 'privateSignatureKey', 4), // private part corruptVerificationKey(verificationKey, 'privateSignatureKey', 60), // public part // privateEncryptionKey can't be corrupted before registration... ]; for (let i = 0; i < badKeys.length; i++) { const badKey = badKeys[i]!; await expect(bobPhone.registerIdentity({ verificationKey: badKey }), `bad verification key #${i}`).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_REGISTRATION_NEEDED); } }); }); describe('verify identity with an invalid verification key', () => { beforeEach(async () => { await bobLaptop.registerIdentity({ verificationKey }); await bobPhone.start(bobIdentity); }); it('throws InvalidVerification when using an obviously wrong verification key', async () => { await expect(bobPhone.verifyIdentity({ verificationKey: 'not_a_verification_key' })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('throws InvalidVerification when using a verification key different from the one used at registration', async () => { await expect(bobPhone.verifyIdentity({ verificationKey: verificationKeyNotUsed })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('throws InvalidVerification when using a verification key fron a different user', async () => { const aliceId = uuid.v4(); const aliceIdentity = await appHelper.generateIdentity(aliceId); const aliceLaptop = args.makeTanker(); await aliceLaptop.start(aliceIdentity); const aliceVerificationKey = await aliceLaptop.generateVerificationKey(); await aliceLaptop.registerIdentity({ verificationKey: aliceVerificationKey }); await expect(bobPhone.verifyIdentity({ verificationKey: aliceVerificationKey })).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); }); it('throws InvalidVerification when using a corrupt verification key', async () => { const badKeys = [ corruptVerificationKey(verificationKey, 'privateSignatureKey', 4), // corrupt private part corruptVerificationKey(verificationKey, 'privateSignatureKey', 60), // corrupt public part corruptVerificationKey(verificationKey, 'privateEncryptionKey', 4), // does not match the one used at registration ]; for (let i = 0; i < badKeys.length; i++) { const badKey = badKeys[i]!; await expect(bobPhone.verifyIdentity({ verificationKey: badKey }), `bad verification key #${i}`).to.be.rejectedWith(errors.InvalidVerification); // The status must not change so that retry is possible expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); } }); }); describe('/verification/email/code HTTP request', () => { it('works', async () => { const email = 'bob@tanker.io'; const url = `${trustchaindUrl}/verification/email/code`; const response = await fetch(url, { method: 'POST', body: JSON.stringify({ app_id: utils.toBase64(args.appHelper.appId), auth_token: args.appHelper.authToken, email, }), }); expect(response.status).to.eq(200); const { verification_code: verificationCode } = await response.json(); expect(verificationCode).to.not.be.undefined; await bobLaptop.registerIdentity({ email, verificationCode }); const actualMethods = await bobLaptop.getVerificationMethods(); expect(actualMethods).to.have.deep.members([{ type: 'email', email }]); }); }); describe('/verification/sms/code HTTP request', () => { it('works', async () => { const phoneNumber = '+33639986789'; const url = `${trustchaindUrl}/verification/sms/code`; const response = await fetch(url, { method: 'POST', body: JSON.stringify({ app_id: utils.toBase64(args.appHelper.appId), auth_token: args.appHelper.authToken, phone_number: phoneNumber, }), }); expect(response.status).to.eq(200); const { verification_code: verificationCode } = await response.json(); expect(verificationCode).to.not.be.undefined; await bobLaptop.registerIdentity({ phoneNumber, verificationCode }); const actualMethods = await bobLaptop.getVerificationMethods(); expect(actualMethods).to.have.deep.members([{ type: 'phoneNumber', phoneNumber }]); }); }); }); }); };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Standard App Version resource to create a new version of standard GAE Application. * Learn about the differences between the standard environment and the flexible environment * at https://cloud.google.com/appengine/docs/the-appengine-environments. * Currently supporting Zip and File Containers. * * To get more information about StandardAppVersion, see: * * * [API documentation](https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions) * * How-to Guides * * [Official Documentation](https://cloud.google.com/appengine/docs/standard) * * ## Example Usage * ### App Engine Standard App Version * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const bucket = new gcp.storage.Bucket("bucket", {location: "US"}); * const object = new gcp.storage.BucketObject("object", { * bucket: bucket.name, * source: new pulumi.asset.FileAsset("./test-fixtures/appengine/hello-world.zip"), * }); * const myappV1 = new gcp.appengine.StandardAppVersion("myappV1", { * versionId: "v1", * service: "myapp", * runtime: "nodejs10", * entrypoint: { * shell: "node ./app.js", * }, * deployment: { * zip: { * sourceUrl: pulumi.interpolate`https://storage.googleapis.com/${bucket.name}/${object.name}`, * }, * }, * envVariables: { * port: "8080", * }, * automaticScaling: { * maxConcurrentRequests: 10, * minIdleInstances: 1, * maxIdleInstances: 3, * minPendingLatency: "1s", * maxPendingLatency: "5s", * standardSchedulerSettings: { * targetCpuUtilization: 0.5, * targetThroughputUtilization: 0.75, * minInstances: 2, * maxInstances: 10, * }, * }, * deleteServiceOnDestroy: true, * }); * const myappV2 = new gcp.appengine.StandardAppVersion("myappV2", { * versionId: "v2", * service: "myapp", * runtime: "nodejs10", * entrypoint: { * shell: "node ./app.js", * }, * deployment: { * zip: { * sourceUrl: pulumi.interpolate`https://storage.googleapis.com/${bucket.name}/${object.name}`, * }, * }, * envVariables: { * port: "8080", * }, * basicScaling: { * maxInstances: 5, * }, * noopOnDestroy: true, * }); * ``` * * ## Import * * StandardAppVersion can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:appengine/standardAppVersion:StandardAppVersion default apps/{{project}}/services/{{service}}/versions/{{version_id}} * ``` * * ```sh * $ pulumi import gcp:appengine/standardAppVersion:StandardAppVersion default {{project}}/{{service}}/{{version_id}} * ``` * * ```sh * $ pulumi import gcp:appengine/standardAppVersion:StandardAppVersion default {{service}}/{{version_id}} * ``` */ export class StandardAppVersion extends pulumi.CustomResource { /** * Get an existing StandardAppVersion 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?: StandardAppVersionState, opts?: pulumi.CustomResourceOptions): StandardAppVersion { return new StandardAppVersion(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:appengine/standardAppVersion:StandardAppVersion'; /** * Returns true if the given object is an instance of StandardAppVersion. 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 StandardAppVersion { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === StandardAppVersion.__pulumiType; } /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Structure is documented below. */ public readonly automaticScaling!: pulumi.Output<outputs.appengine.StandardAppVersionAutomaticScaling | undefined>; /** * Basic scaling creates instances when your application receives requests. Each instance will be shut down when the application becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity. * Structure is documented below. */ public readonly basicScaling!: pulumi.Output<outputs.appengine.StandardAppVersionBasicScaling | undefined>; /** * If set to `true`, the service will be deleted if it is the last version. */ public readonly deleteServiceOnDestroy!: pulumi.Output<boolean | undefined>; /** * Code and application artifacts that make up this version. * Structure is documented below. */ public readonly deployment!: pulumi.Output<outputs.appengine.StandardAppVersionDeployment>; /** * The entrypoint for the application. * Structure is documented below. */ public readonly entrypoint!: pulumi.Output<outputs.appengine.StandardAppVersionEntrypoint>; /** * Environment variables available to the application. */ public readonly envVariables!: pulumi.Output<{[key: string]: string} | undefined>; /** * An ordered list of URL-matching patterns that should be applied to incoming requests. * The first matching URL handles the request and other request handlers are not attempted. * Structure is documented below. */ public readonly handlers!: pulumi.Output<outputs.appengine.StandardAppVersionHandler[]>; /** * A list of the types of messages that this application is able to receive. * Each value may be one of `INBOUND_SERVICE_MAIL`, `INBOUND_SERVICE_MAIL_BOUNCE`, `INBOUND_SERVICE_XMPP_ERROR`, `INBOUND_SERVICE_XMPP_MESSAGE`, `INBOUND_SERVICE_XMPP_SUBSCRIBE`, `INBOUND_SERVICE_XMPP_PRESENCE`, `INBOUND_SERVICE_CHANNEL_PRESENCE`, and `INBOUND_SERVICE_WARMUP`. */ public readonly inboundServices!: pulumi.Output<string[] | undefined>; /** * Instance class that is used to run this version. Valid values are * AutomaticScaling: F1, F2, F4, F4_1G * BasicScaling or ManualScaling: B1, B2, B4, B4_1G, B8 * Defaults to F1 for AutomaticScaling and B2 for ManualScaling and BasicScaling. If no scaling is specified, AutomaticScaling is chosen. */ public readonly instanceClass!: pulumi.Output<string>; /** * Configuration for third-party Python runtime libraries that are required by the application. * Structure is documented below. */ public readonly libraries!: pulumi.Output<outputs.appengine.StandardAppVersionLibrary[] | undefined>; /** * A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. * Structure is documented below. */ public readonly manualScaling!: pulumi.Output<outputs.appengine.StandardAppVersionManualScaling | undefined>; /** * Full Serverless VPC Access Connector name e.g. /projects/my-project/locations/us-central1/connectors/c1. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * If set to `true`, the application version will not be deleted. */ public readonly noopOnDestroy!: pulumi.Output<boolean | undefined>; /** * 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>; /** * Desired runtime. Example python27. */ public readonly runtime!: pulumi.Output<string>; /** * The version of the API in the given runtime environment. * Please see the app.yaml reference for valid values at https://cloud.google.com/appengine/docs/standard//config/appref */ public readonly runtimeApiVersion!: pulumi.Output<string | undefined>; /** * AppEngine service resource */ public readonly service!: pulumi.Output<string>; /** * Whether multiple requests can be dispatched to this version at once. */ public readonly threadsafe!: pulumi.Output<boolean | undefined>; /** * Relative name of the version within the service. For example, `v1`. Version names can contain only lowercase letters, numbers, or hyphens. Reserved names,"default", "latest", and any name with the prefix "ah-". */ public readonly versionId!: pulumi.Output<string | undefined>; /** * Enables VPC connectivity for standard apps. * Structure is documented below. */ public readonly vpcAccessConnector!: pulumi.Output<outputs.appengine.StandardAppVersionVpcAccessConnector | undefined>; /** * Create a StandardAppVersion 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: StandardAppVersionArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: StandardAppVersionArgs | StandardAppVersionState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as StandardAppVersionState | undefined; inputs["automaticScaling"] = state ? state.automaticScaling : undefined; inputs["basicScaling"] = state ? state.basicScaling : undefined; inputs["deleteServiceOnDestroy"] = state ? state.deleteServiceOnDestroy : undefined; inputs["deployment"] = state ? state.deployment : undefined; inputs["entrypoint"] = state ? state.entrypoint : undefined; inputs["envVariables"] = state ? state.envVariables : undefined; inputs["handlers"] = state ? state.handlers : undefined; inputs["inboundServices"] = state ? state.inboundServices : undefined; inputs["instanceClass"] = state ? state.instanceClass : undefined; inputs["libraries"] = state ? state.libraries : undefined; inputs["manualScaling"] = state ? state.manualScaling : undefined; inputs["name"] = state ? state.name : undefined; inputs["noopOnDestroy"] = state ? state.noopOnDestroy : undefined; inputs["project"] = state ? state.project : undefined; inputs["runtime"] = state ? state.runtime : undefined; inputs["runtimeApiVersion"] = state ? state.runtimeApiVersion : undefined; inputs["service"] = state ? state.service : undefined; inputs["threadsafe"] = state ? state.threadsafe : undefined; inputs["versionId"] = state ? state.versionId : undefined; inputs["vpcAccessConnector"] = state ? state.vpcAccessConnector : undefined; } else { const args = argsOrState as StandardAppVersionArgs | undefined; if ((!args || args.deployment === undefined) && !opts.urn) { throw new Error("Missing required property 'deployment'"); } if ((!args || args.entrypoint === undefined) && !opts.urn) { throw new Error("Missing required property 'entrypoint'"); } if ((!args || args.runtime === undefined) && !opts.urn) { throw new Error("Missing required property 'runtime'"); } if ((!args || args.service === undefined) && !opts.urn) { throw new Error("Missing required property 'service'"); } inputs["automaticScaling"] = args ? args.automaticScaling : undefined; inputs["basicScaling"] = args ? args.basicScaling : undefined; inputs["deleteServiceOnDestroy"] = args ? args.deleteServiceOnDestroy : undefined; inputs["deployment"] = args ? args.deployment : undefined; inputs["entrypoint"] = args ? args.entrypoint : undefined; inputs["envVariables"] = args ? args.envVariables : undefined; inputs["handlers"] = args ? args.handlers : undefined; inputs["inboundServices"] = args ? args.inboundServices : undefined; inputs["instanceClass"] = args ? args.instanceClass : undefined; inputs["libraries"] = args ? args.libraries : undefined; inputs["manualScaling"] = args ? args.manualScaling : undefined; inputs["noopOnDestroy"] = args ? args.noopOnDestroy : undefined; inputs["project"] = args ? args.project : undefined; inputs["runtime"] = args ? args.runtime : undefined; inputs["runtimeApiVersion"] = args ? args.runtimeApiVersion : undefined; inputs["service"] = args ? args.service : undefined; inputs["threadsafe"] = args ? args.threadsafe : undefined; inputs["versionId"] = args ? args.versionId : undefined; inputs["vpcAccessConnector"] = args ? args.vpcAccessConnector : undefined; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(StandardAppVersion.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering StandardAppVersion resources. */ export interface StandardAppVersionState { /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Structure is documented below. */ automaticScaling?: pulumi.Input<inputs.appengine.StandardAppVersionAutomaticScaling>; /** * Basic scaling creates instances when your application receives requests. Each instance will be shut down when the application becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity. * Structure is documented below. */ basicScaling?: pulumi.Input<inputs.appengine.StandardAppVersionBasicScaling>; /** * If set to `true`, the service will be deleted if it is the last version. */ deleteServiceOnDestroy?: pulumi.Input<boolean>; /** * Code and application artifacts that make up this version. * Structure is documented below. */ deployment?: pulumi.Input<inputs.appengine.StandardAppVersionDeployment>; /** * The entrypoint for the application. * Structure is documented below. */ entrypoint?: pulumi.Input<inputs.appengine.StandardAppVersionEntrypoint>; /** * Environment variables available to the application. */ envVariables?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * An ordered list of URL-matching patterns that should be applied to incoming requests. * The first matching URL handles the request and other request handlers are not attempted. * Structure is documented below. */ handlers?: pulumi.Input<pulumi.Input<inputs.appengine.StandardAppVersionHandler>[]>; /** * A list of the types of messages that this application is able to receive. * Each value may be one of `INBOUND_SERVICE_MAIL`, `INBOUND_SERVICE_MAIL_BOUNCE`, `INBOUND_SERVICE_XMPP_ERROR`, `INBOUND_SERVICE_XMPP_MESSAGE`, `INBOUND_SERVICE_XMPP_SUBSCRIBE`, `INBOUND_SERVICE_XMPP_PRESENCE`, `INBOUND_SERVICE_CHANNEL_PRESENCE`, and `INBOUND_SERVICE_WARMUP`. */ inboundServices?: pulumi.Input<pulumi.Input<string>[]>; /** * Instance class that is used to run this version. Valid values are * AutomaticScaling: F1, F2, F4, F4_1G * BasicScaling or ManualScaling: B1, B2, B4, B4_1G, B8 * Defaults to F1 for AutomaticScaling and B2 for ManualScaling and BasicScaling. If no scaling is specified, AutomaticScaling is chosen. */ instanceClass?: pulumi.Input<string>; /** * Configuration for third-party Python runtime libraries that are required by the application. * Structure is documented below. */ libraries?: pulumi.Input<pulumi.Input<inputs.appengine.StandardAppVersionLibrary>[]>; /** * A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. * Structure is documented below. */ manualScaling?: pulumi.Input<inputs.appengine.StandardAppVersionManualScaling>; /** * Full Serverless VPC Access Connector name e.g. /projects/my-project/locations/us-central1/connectors/c1. */ name?: pulumi.Input<string>; /** * If set to `true`, the application version will not be deleted. */ noopOnDestroy?: pulumi.Input<boolean>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Desired runtime. Example python27. */ runtime?: pulumi.Input<string>; /** * The version of the API in the given runtime environment. * Please see the app.yaml reference for valid values at https://cloud.google.com/appengine/docs/standard//config/appref */ runtimeApiVersion?: pulumi.Input<string>; /** * AppEngine service resource */ service?: pulumi.Input<string>; /** * Whether multiple requests can be dispatched to this version at once. */ threadsafe?: pulumi.Input<boolean>; /** * Relative name of the version within the service. For example, `v1`. Version names can contain only lowercase letters, numbers, or hyphens. Reserved names,"default", "latest", and any name with the prefix "ah-". */ versionId?: pulumi.Input<string>; /** * Enables VPC connectivity for standard apps. * Structure is documented below. */ vpcAccessConnector?: pulumi.Input<inputs.appengine.StandardAppVersionVpcAccessConnector>; } /** * The set of arguments for constructing a StandardAppVersion resource. */ export interface StandardAppVersionArgs { /** * Automatic scaling is based on request rate, response latencies, and other application metrics. * Structure is documented below. */ automaticScaling?: pulumi.Input<inputs.appengine.StandardAppVersionAutomaticScaling>; /** * Basic scaling creates instances when your application receives requests. Each instance will be shut down when the application becomes idle. Basic scaling is ideal for work that is intermittent or driven by user activity. * Structure is documented below. */ basicScaling?: pulumi.Input<inputs.appengine.StandardAppVersionBasicScaling>; /** * If set to `true`, the service will be deleted if it is the last version. */ deleteServiceOnDestroy?: pulumi.Input<boolean>; /** * Code and application artifacts that make up this version. * Structure is documented below. */ deployment: pulumi.Input<inputs.appengine.StandardAppVersionDeployment>; /** * The entrypoint for the application. * Structure is documented below. */ entrypoint: pulumi.Input<inputs.appengine.StandardAppVersionEntrypoint>; /** * Environment variables available to the application. */ envVariables?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * An ordered list of URL-matching patterns that should be applied to incoming requests. * The first matching URL handles the request and other request handlers are not attempted. * Structure is documented below. */ handlers?: pulumi.Input<pulumi.Input<inputs.appengine.StandardAppVersionHandler>[]>; /** * A list of the types of messages that this application is able to receive. * Each value may be one of `INBOUND_SERVICE_MAIL`, `INBOUND_SERVICE_MAIL_BOUNCE`, `INBOUND_SERVICE_XMPP_ERROR`, `INBOUND_SERVICE_XMPP_MESSAGE`, `INBOUND_SERVICE_XMPP_SUBSCRIBE`, `INBOUND_SERVICE_XMPP_PRESENCE`, `INBOUND_SERVICE_CHANNEL_PRESENCE`, and `INBOUND_SERVICE_WARMUP`. */ inboundServices?: pulumi.Input<pulumi.Input<string>[]>; /** * Instance class that is used to run this version. Valid values are * AutomaticScaling: F1, F2, F4, F4_1G * BasicScaling or ManualScaling: B1, B2, B4, B4_1G, B8 * Defaults to F1 for AutomaticScaling and B2 for ManualScaling and BasicScaling. If no scaling is specified, AutomaticScaling is chosen. */ instanceClass?: pulumi.Input<string>; /** * Configuration for third-party Python runtime libraries that are required by the application. * Structure is documented below. */ libraries?: pulumi.Input<pulumi.Input<inputs.appengine.StandardAppVersionLibrary>[]>; /** * A service with manual scaling runs continuously, allowing you to perform complex initialization and rely on the state of its memory over time. * Structure is documented below. */ manualScaling?: pulumi.Input<inputs.appengine.StandardAppVersionManualScaling>; /** * If set to `true`, the application version will not be deleted. */ noopOnDestroy?: pulumi.Input<boolean>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * Desired runtime. Example python27. */ runtime: pulumi.Input<string>; /** * The version of the API in the given runtime environment. * Please see the app.yaml reference for valid values at https://cloud.google.com/appengine/docs/standard//config/appref */ runtimeApiVersion?: pulumi.Input<string>; /** * AppEngine service resource */ service: pulumi.Input<string>; /** * Whether multiple requests can be dispatched to this version at once. */ threadsafe?: pulumi.Input<boolean>; /** * Relative name of the version within the service. For example, `v1`. Version names can contain only lowercase letters, numbers, or hyphens. Reserved names,"default", "latest", and any name with the prefix "ah-". */ versionId?: pulumi.Input<string>; /** * Enables VPC connectivity for standard apps. * Structure is documented below. */ vpcAccessConnector?: pulumi.Input<inputs.appengine.StandardAppVersionVpcAccessConnector>; }
the_stack
import * as nls from "vscode-nls"; import * as semver from "semver"; import { QuickPickOptions, window } from "vscode"; import { ChildProcess } from "../../common/node/childProcess"; import { waitUntil } from "../../common/node/promise"; import { IDebuggableMobileTarget, MobileTarget } from "../mobileTarget"; import { MobileTargetManager } from "../mobileTargetManager"; import { TargetType } from "../../debugger/cordovaDebugSession"; nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone, })(); const localize = nls.loadMessageBundle(); export interface IDebuggableIOSTarget extends IDebuggableMobileTarget { name: string; system: string; simIdentifier?: string; simDataPath?: string; } export class IOSTarget extends MobileTarget implements IDebuggableIOSTarget { protected _system: string; protected _name: string; protected _simIdentifier?: string; protected _simDataPath?: string; public static fromInterface(obj: IDebuggableIOSTarget): IOSTarget { return new IOSTarget( obj.isOnline, obj.isVirtualTarget, obj.id, obj.name, obj.system, obj.simIdentifier, obj.simDataPath, ); } constructor( isOnline: boolean, isVirtualTarget: boolean, id: string, name: string, system: string, simIdentifier?: string, simDataPath?: string, ) { super(isOnline, isVirtualTarget, id, name); this._system = system; this._simIdentifier = simIdentifier; this._simDataPath = simDataPath; } get system(): string { return this._system; } get simIdentifier(): string | undefined { return this._simIdentifier; } get simDataPath(): string | undefined { return this._simDataPath; } get name(): string { return this._name; } set name(value: string) { this._name = value; } } export class IOSTargetManager extends MobileTargetManager { private static readonly XCRUN_COMMAND = "xcrun"; private static readonly SIMCTL_COMMAND = "simctl"; private static readonly BOOT_COMMAND = "boot"; private static readonly SIMULATORS_LIST_COMMAND = `${IOSTargetManager.XCRUN_COMMAND} ${IOSTargetManager.SIMCTL_COMMAND} list devices available --json`; private static readonly ALL_DEVICES_LIST_COMMAND = `${IOSTargetManager.XCRUN_COMMAND} xctrace list devices`; private static readonly BOOTED_STATE = "Booted"; private static readonly SIMULATOR_START_TIMEOUT = 120; private static readonly ANY_SYSTEM = "AnySystem"; private childProcess: ChildProcess = new ChildProcess(); protected targets?: IDebuggableIOSTarget[]; public async getTargetList(filter?: (el: IDebuggableIOSTarget) => boolean): Promise<IDebuggableIOSTarget[]> { return (await super.getTargetList(filter)) as IDebuggableIOSTarget[]; } public async collectTargets(targetType?: TargetType.Device | TargetType.Emulator): Promise<void> { this.targets = []; if (targetType === undefined || targetType === TargetType.Emulator) { const simulators = JSON.parse( await this.childProcess.execToString(`${IOSTargetManager.SIMULATORS_LIST_COMMAND}`), ); Object.keys(simulators.devices).forEach(rawSystem => { const temp = rawSystem.split(".").slice(-1)[0].split("-"); // "com.apple.CoreSimulator.SimRuntime.iOS-11-4" -> ["iOS", "11", "4"] simulators.devices[rawSystem].forEach((device: any) => { // Now we support selection only for iOS system if (temp[0] === "iOS") { const system = semver.coerce(temp.slice(1).join(".")).toString(); // ["iOS", "11", "4"] -> 11.4.0 let simIdentifier; try { const identifierPieces = device.deviceTypeIdentifier.split("."); simIdentifier = identifierPieces[identifierPieces.length - 1]; } catch { } this.targets?.push({ id: device.udid, name: device.name, system, isVirtualTarget: true, isOnline: device.state === IOSTargetManager.BOOTED_STATE, simIdentifier: simIdentifier, simDataPath: device.dataPath, }); } }); }); } if (targetType === undefined || targetType === TargetType.Device) { const allDevicesOutput = await this.childProcess.execToString( `${IOSTargetManager.ALL_DEVICES_LIST_COMMAND}`, ); // Output example: // == Devices == // sierra (EFDAAD01-E1A3-5F00-A357-665B501D5520) // My iPhone (14.4.2) (33n546e591e707bd64c718bfc1bf3e8b7c16bfc9) // // == Simulators == // Apple TV (14.5) (417BDFD8-6E22-4F87-BCAA-19C241AC9548) // Apple TV 4K (2nd generation) (14.5) (925E6E38-0D7B-45E9-ADE0-89C20779D467) // ... const lines = allDevicesOutput .split("\n") .map(line => line.trim()) .filter(line => !!line); const firstDevicesIndex = lines.indexOf("== Devices ==") + 1; const lastDevicesIndex = lines.indexOf("== Simulators ==") - 1; for (let i = firstDevicesIndex; i <= lastDevicesIndex; i++) { const line = lines[i]; const params = line .split(" ") .map(el => el.trim()) .filter(el => !!el); // Add only devices with system version if ( params[params.length - 1].match(/\(.+\)/) && params[params.length - 2].match(/\(.+\)/) ) { this.targets.push({ id: params[params.length - 1].replace(/\(|\)/g, "").trim(), name: params.slice(0, params.length - 2).join(" "), system: params[params.length - 2].replace(/\(|\)/g, "").trim(), isVirtualTarget: false, isOnline: true, }); } } } } public async selectAndPrepareTarget( filter?: (el: IDebuggableIOSTarget) => boolean, ): Promise<IOSTarget | undefined> { const selectedTarget = await this.startSelection(filter); if (selectedTarget) { return !selectedTarget.isOnline && selectedTarget.isVirtualTarget ? this.launchSimulator(selectedTarget) : IOSTarget.fromInterface(selectedTarget); } return undefined; } public async getOnlineTargets(): Promise<IOSTarget[]> { const onlineTargets = (await this.getTargetList(target => target.isOnline)) as IDebuggableIOSTarget[]; return onlineTargets.map(target => IOSTarget.fromInterface(target)); } public async getOnlineSimulators(): Promise<IOSTarget[]> { const onlineTargets = (await this.getTargetList(target => target.isOnline && target.isVirtualTarget)) as IDebuggableIOSTarget[]; return onlineTargets.map(target => IOSTarget.fromInterface(target)); } public async isVirtualTarget(targetString: string): Promise<boolean> { try { if (targetString === TargetType.Device) { return false; } else if (targetString === TargetType.Emulator) { return true; } const target = ( await this.getTargetList( target => target.id === targetString || target.name === targetString, ) )[0]; if (target) { return target.isVirtualTarget; } throw Error("There is no any target with specified target string"); } catch { throw new Error( localize( "CouldNotRecognizeTargetType", "Could not recognize type of the target {0}", targetString, ), ); } } protected async startSelection( filter?: (el: IDebuggableIOSTarget) => boolean, ): Promise<IDebuggableIOSTarget | undefined> { const system = await this.selectSystem(filter); if (system) { return (await this.selectTarget( (el: IDebuggableIOSTarget) => (filter ? filter(el) : true) && (system === IOSTargetManager.ANY_SYSTEM ? true : el.system === system), )) as IDebuggableIOSTarget | undefined; } return; } protected async selectSystem( filter?: (el: IDebuggableIOSTarget) => boolean, ): Promise<string | undefined> { const targets = (await this.getTargetList(filter)) as IDebuggableIOSTarget[]; // If we select only from devices, we should not select system if (!targets.find(target => target.isVirtualTarget)) { return IOSTargetManager.ANY_SYSTEM; } const names: Set<string> = new Set(targets.map(target => `iOS ${target.system}`)); const systemsList = Array.from(names); let result: string | undefined = systemsList[0]; if (systemsList.length > 1) { const quickPickOptions: QuickPickOptions = { ignoreFocusOut: true, canPickMany: false, placeHolder: localize( "SelectIOSSystemVersion", "Select system version of iOS target", ), }; result = await window.showQuickPick(systemsList, quickPickOptions); } return result?.toString().substring(4); } protected async launchSimulator( emulatorTarget: IDebuggableIOSTarget, ): Promise<IOSTarget | undefined> { return new Promise<IOSTarget | undefined>((resolve, reject) => { let emulatorLaunchFailed = false; const emulatorProcess = this.childProcess.spawn( IOSTargetManager.XCRUN_COMMAND, [IOSTargetManager.SIMCTL_COMMAND, IOSTargetManager.BOOT_COMMAND, emulatorTarget.id], { detached: true, }, true, ); emulatorProcess.spawnedProcess.unref(); emulatorProcess.outcome.catch(err => { emulatorLaunchFailed = true; reject(new Error(`Error while launching simulator ${emulatorTarget.name}(${emulatorTarget.id} with an exception: ${err}`)); }); const condition = async () => { if (emulatorLaunchFailed) throw new Error("iOS simulator launch failed unexpectedly"); await this.collectTargets(TargetType.Emulator); const onlineTarget = (await this.getTargetList()).find( target => target.id === emulatorTarget.id && target.isOnline, ); return onlineTarget ? true : null; }; void waitUntil<boolean>( condition, 1000, IOSTargetManager.SIMULATOR_START_TIMEOUT * 1000, ).then( isBooted => { if (isBooted) { emulatorTarget.isOnline = true; this.logger.log( localize("SimulatorLaunched", "Launched simulator {0}", emulatorTarget.name), ); resolve(IOSTarget.fromInterface(emulatorTarget)); } else { reject( new Error( `Virtual device launch finished with an exception: ${localize( "SimulatorStartWarning", "Could not start the simulator {0} within {1} seconds.", emulatorTarget.name, IOSTargetManager.SIMULATOR_START_TIMEOUT, )}` ) ); } }, () => {}, ); }); } }
the_stack
import { Unsubscribe, Emitter } from 'nanoevents' /** * Action unique ID accross all nodes. * * ```js * "1564508138460 380:R7BNGAP5:px3-J3oc 0" * ``` */ export type ID = string interface PreaddListener<ListenerAction extends Action, LogMeta extends Meta> { (action: ListenerAction, meta: LogMeta): void } interface ReadonlyListener< ListenerAction extends Action, LogMeta extends Meta > { (action: ListenerAction, meta: LogMeta): void } interface ActionIterator<LogMeta extends Meta> { (action: Action, meta: Readonly<LogMeta>): boolean | void } export function actionEvents( emitter: Emitter, event: 'preadd' | 'add' | 'clean', action: Action, meta: Meta ): void export interface Meta { /** * Sequence number of action in current log. Log fills it. */ added: number /** * Action created time in current node time. Milliseconds since UNIX epoch. */ time: number /** * Action unique ID. Log sets it automatically. */ id: ID /** * Why action should be kept in log. Action without reasons will be removed. */ reasons: string[] /** * Set code as reason and remove this reasons from previous actions. */ subprotocol?: string /** * Set value to `reasons` and this reason from old action. */ keepLast?: string /** * Indexes for action quick extraction. */ indexes?: string[] [extra: string]: any } export interface Action { /** * Action type name. */ type: string } export interface AnyAction { type: string [extra: string]: any } interface Criteria { /** * Remove reason only for actions with bigger `added`. */ minAdded?: number /** * Remove reason only for actions with lower `added`. */ maxAdded?: number /** * Remove reason only older than specific action. */ olderThan?: Meta /** * Remove reason only younger than specific action. */ youngerThan?: Meta /** * Remove reason only for action with `id`. */ id?: ID } interface LastSynced { /** * The `added` value of latest received event. */ received: number /** * The `added` value of latest sent event. */ sent: number } export interface LogPage { /** * Pagination page. */ entries: [Action, Meta][] /** * Next page loader. */ next?(): Promise<LogPage> } interface GetOptions { /** * Sort entries by created time or when they was added to current log. */ order?: 'created' | 'added' /** * Get entries with a custom index. */ index?: string } /** * Every Store class should provide 8 standard methods. */ export abstract class LogStore { /** * Add action to store. Action always will have `type` property. * * @param action The action to add. * @param meta Action’s metadata. * @returns Promise with `meta` for new action or `false` if action with * same `meta.id` was already in store. */ add(action: AnyAction, meta: Meta): Promise<Meta | false> /** * Return a Promise with first page. Page object has `entries` property * with part of actions and `next` property with function to load next page. * If it was a last page, `next` property should be empty. * * This tricky API is used, because log could be very big. So we need * pagination to keep them in memory. * * @param opts Query options. * @returns Promise with first page. */ get(opts?: GetOptions): Promise<LogPage> /** * Remove action from store. * * @param id Action ID. * @returns Promise with entry if action was in store. */ remove(id: ID): Promise<[Action, Meta] | false> /** * Change action metadata. * * @param id Action ID. * @param diff Object with values to change in action metadata. * @returns Promise with `true` if metadata was changed or `false` * on unknown ID. */ changeMeta(id: ID, diff: Partial<Meta>): Promise<boolean> /** * Return action by action ID. * * @param id Action ID. * @returns Promise with array of action and metadata. */ byId(id: ID): Promise<[Action, Meta] | [null, null]> /** * Remove reason from action’s metadata and remove actions without reasons. * * @param reason The reason name. * @param criteria Criteria to select action for reason removing. * @param callback Callback for every removed action. * @returns Promise when cleaning will be finished. */ removeReason( reason: string, criteria: Criteria, callback: ReadonlyListener<Action, Meta> ): Promise<void> /** * Remove all data from the store. * * @returns Promise when cleaning will be finished. */ clean(): Promise<void> /** * Return biggest `added` number in store. * All actions in this log have less or same `added` time. * * @returns Promise with biggest `added` number. */ getLastAdded(): Promise<number> /** * Get `added` values for latest synchronized received/sent events. * * @returns Promise with `added` values */ getLastSynced(): Promise<LastSynced> /** * Set `added` value for latest synchronized received or/and sent events. * @param values Object with latest sent or received values. * @returns Promise when values will be saved to store. */ setLastSynced(values: LastSynced): Promise<void> } interface LogOptions<Store extends LogStore = LogStore> { /** * Store for log. */ store: Store /** * Unique current machine name. */ nodeId: string } /** * Stores actions with time marks. Log is main idea in Logux. * In most end-user tools you will work with log and should know log API. * * ```js * import Log from '@logux/core' * const log = new Log({ * store: new MemoryStore(), * nodeId: 'client:134' * }) * * log.on('add', beeper) * log.add({ type: 'beep' }) * ``` */ export class Log< LogMeta extends Meta = Meta, Store extends LogStore = LogStore > { /** * @param opts Log options. */ constructor(opts: LogOptions<Store>) /** * Log store. */ store: Store /** * Unique node ID. It is used in action IDs. */ nodeId: string /** * * Add action to log. * * It will set `id`, `time` (if they was missed) and `added` property * to `meta` and call all listeners. * * ```js * removeButton.addEventListener('click', () => { * log.add({ type: 'users:remove', user: id }) * }) * ``` * * @param action The new action. * @param meta Open structure for action metadata. * @returns Promise with `meta` if action was added to log or `false` * if action was already in log. */ add<NewAction extends Action = AnyAction>( action: NewAction, meta?: Partial<LogMeta> ): Promise<LogMeta | false> /** * Add listener for adding action with specific type. * Works faster than `on('add', cb)` with `if`. * * Setting `opts.id` will filter events ponly from actions with specific * `action.id`. * * ```js * const unbind = log.type('beep', (action, meta) => { * beep() * }) * function disableBeeps () { * unbind() * } * ``` * * @param type Action’s type. * @param listener The listener function. * @param event * @returns Unbind listener from event. */ type< NewAction extends Action = Action, Type extends string = NewAction['type'] >( type: Type, listener: ReadonlyListener<NewAction, LogMeta>, opts?: { id?: string; event?: 'add' | 'clean' } ): Unsubscribe type< NewAction extends Action = Action, Type extends string = NewAction['type'] >( type: Type, listener: PreaddListener<NewAction, LogMeta>, opts: { id?: string; event: 'preadd' } ): Unsubscribe /** * Subscribe for log events. It implements nanoevents API. Supported events: * * * `preadd`: when somebody try to add action to log. * It fires before ID check. The best place to add reason. * * `add`: when new action was added to log. * * `clean`: when action was cleaned from store. * * Note, that `Log#type()` will work faster than `on` event with `if`. * * ```js * log.on('preadd', (action, meta) => { * if (action.type === 'beep') { * meta.reasons.push('test') * } * }) * ``` * * @param event The event name. * @param listener The listener function. * @returns Unbind listener from event. */ on( event: 'add' | 'clean', listener: ReadonlyListener<Action, LogMeta> ): Unsubscribe on(event: 'preadd', listener: PreaddListener<Action, LogMeta>): Unsubscribe /** * Generate next unique action ID. * * ```js * const id = log.generateId() * ``` * * @returns Unique ID for action. */ generateId(): ID /** * Iterates through all actions, from last to first. * * Return false from callback if you want to stop iteration. * * ```js * log.each((action, meta) => { * if (compareTime(meta.id, lastBeep) <= 0) { * return false; * } else if (action.type === 'beep') { * beep() * lastBeep = meta.id * return false; * } * }) * ``` * * @param callback Function will be executed on every action. * @returns When iteration will be finished by iterator or end of actions. */ each(callback: ActionIterator<LogMeta>): Promise<void> /** * @param opts Iterator options. * @param callback Function will be executed on every action. */ each(opts: GetOptions, callback: ActionIterator<LogMeta>): Promise<void> each(callback: ActionIterator<LogMeta>): Promise<void> /** * Change action metadata. You will remove action by setting `reasons: []`. * * ```js * await process(action) * log.changeMeta(action, { status: 'processed' }) * ``` * * @param id Action ID. * @param diff Object with values to change in action metadata. * @returns Promise with `true` if metadata was changed or `false` * on unknown ID. */ changeMeta(id: ID, diff: Partial<LogMeta>): Promise<boolean> /** * Remove reason tag from action’s metadata and remove actions without reason * from log. * * ```js * onSync(lastSent) { * log.removeReason('unsynchronized', { maxAdded: lastSent }) * } * ``` * * @param reason The reason name. * @param criteria Criteria to select action for reason removing. * @returns Promise when cleaning will be finished. */ removeReason(reason: string, criteria?: Criteria): Promise<void> /** * Does log already has action with this ID. * * ```js * if (action.type === 'logux/undo') { * const [undidAction, undidMeta] = await log.byId(action.id) * log.changeMeta(meta.id, { reasons: undidMeta.reasons }) * } * ``` * * @param id Action ID. * @returns Promise with array of action and metadata. */ byId(id: ID): Promise<[Action, LogMeta] | [null, null]> }
the_stack
import React, { useState, useMemo, useEffect, useContext, FC } from "react"; import { useTranslation } from "react-i18next"; import { useHistory, useRouteMatch } from "react-router-dom"; import { wethAddresses } from "@airswap/constants"; import { Registry, Wrapper } from "@airswap/libraries"; import { findTokensBySymbol } from "@airswap/metadata"; import { Pricing } from "@airswap/types"; import { LightOrder } from "@airswap/types"; import { Web3Provider } from "@ethersproject/providers"; import { unwrapResult } from "@reduxjs/toolkit"; import { UnsupportedChainIdError, useWeb3React } from "@web3-react/core"; import { BigNumber } from "bignumber.js"; import { formatUnits } from "ethers/lib/utils"; import { useAppSelector, useAppDispatch } from "../../app/hooks"; import { ADDITIONAL_QUOTE_BUFFER, RECEIVE_QUOTE_TIMEOUT_MS, } from "../../constants/configParams"; import nativeETH from "../../constants/nativeETH"; import { LastLookContext } from "../../contexts/lastLook/LastLook"; import { requestActiveTokenAllowancesLight, requestActiveTokenAllowancesWrapper, requestActiveTokenBalances, } from "../../features/balances/balancesSlice"; import { selectBalances, selectAllowances, } from "../../features/balances/balancesSlice"; import { selectActiveTokens, selectAllTokenInfo, addActiveToken, removeActiveToken, } from "../../features/metadata/metadataSlice"; import { approve, take, selectBestOrder, selectOrdersStatus, clear, selectBestOption, request, deposit, withdraw, resetOrders, } from "../../features/orders/ordersSlice"; import { selectAllSupportedTokens } from "../../features/registry/registrySlice"; import { clearTradeTerms, clearTradeTermsQuoteAmount, selectTradeTerms, setTradeTerms, setTradeTermsQuoteAmount, } from "../../features/tradeTerms/tradeTermsSlice"; import { declineTransaction, revertTransaction, } from "../../features/transactions/transactionActions"; import { ProtocolType, selectPendingApprovals, } from "../../features/transactions/transactionsSlice"; import { setActiveProvider } from "../../features/wallet/walletSlice"; import { Validator } from "../../helpers/Validator"; import findEthOrTokenByAddress from "../../helpers/findEthOrTokenByAddress"; import useReferencePriceSubscriber from "../../hooks/useReferencePriceSubscriber"; import { AppRoutes } from "../../routes"; import type { Error } from "../ErrorList/ErrorList"; import { ErrorList } from "../ErrorList/ErrorList"; import { InformationModalType } from "../InformationModals/InformationModals"; import GasFreeSwapsModal from "../InformationModals/subcomponents/GasFreeSwapsModal/GasFreeSwapsModal"; import JoinModal from "../InformationModals/subcomponents/JoinModal/JoinModal"; import ProtocolFeeDiscountModal from "../InformationModals/subcomponents/ProtocolFeeDiscountModal/ProtocolFeeDiscountModal"; import Overlay from "../Overlay/Overlay"; import { notifyError } from "../Toasts/ToastController"; import TokenList from "../TokenList/TokenList"; import InfoSection from "./InfoSection"; import StyledSwapWidget, { InfoContainer, ButtonContainer, HugeTicks, StyledWalletProviderList, } from "./SwapWidget.styles"; import ActionButtons, { ButtonActions, } from "./subcomponents/ActionButtons/ActionButtons"; import SwapInputs from "./subcomponents/SwapInputs/SwapInputs"; import SwapWidgetHeader from "./subcomponents/SwapWidgetHeader/SwapWidgetHeader"; type TokenSelectModalTypes = "base" | "quote" | null; type SwapType = "swap" | "swapWithWrap" | "wrapOrUnwrap"; const initialBaseAmount = ""; type SwapWidgetPropsType = { showWalletList: boolean; transactionsTabOpen: boolean; activeInformationModal: InformationModalType | null; setShowWalletList: (x: boolean) => void; onTrackTransactionClicked: () => void; afterInformationModalClose: () => void; }; const SwapWidget: FC<SwapWidgetPropsType> = ({ showWalletList, activeInformationModal, setShowWalletList, transactionsTabOpen, onTrackTransactionClicked, afterInformationModalClose, }) => { // Redux const dispatch = useAppDispatch(); const history = useHistory(); const balances = useAppSelector(selectBalances); const allowances = useAppSelector(selectAllowances); const bestRfqOrder = useAppSelector(selectBestOrder); const ordersStatus = useAppSelector(selectOrdersStatus); const bestTradeOption = useAppSelector(selectBestOption); const activeTokens = useAppSelector(selectActiveTokens); const allTokens = useAppSelector(selectAllTokenInfo); const supportedTokens = useAppSelector(selectAllSupportedTokens); const pendingApprovals = useAppSelector(selectPendingApprovals); const tradeTerms = useAppSelector(selectTradeTerms); // Contexts const LastLook = useContext(LastLookContext); // Input states let { tokenFrom, tokenTo } = useRouteMatch<AppRoutes>().params; const [baseAmount, setBaseAmount] = useState(initialBaseAmount); // Pricing const { subscribeToGasPrice, subscribeToTokenPrice, unsubscribeFromGasPrice, unsubscribeFromTokenPrice, } = useReferencePriceSubscriber(); // Modals const [showOrderSubmitted, setShowOrderSubmitted] = useState<boolean>(false); const [ showTokenSelectModalFor, setShowTokenSelectModalFor, ] = useState<TokenSelectModalTypes | null>(null); const [showGasFeeInfo, setShowGasFeeInfo] = useState(false); const [protocolFeeDiscountInfo, setProtocolFeeDiscountInfo] = useState(false); // Loading states const [isApproving, setIsApproving] = useState(false); const [isSwapping, setIsSwapping] = useState(false); const [isWrapping, setIsWrapping] = useState(false); const [isConnecting, setIsConnecting] = useState(false); const [isRequestingQuotes, setIsRequestingQuotes] = useState(false); // Error states const [pairUnavailable, setPairUnavailable] = useState(false); const [validatorErrors, setValidatorErrors] = useState<Error[]>([]); const [allowanceFetchFailed, setAllowanceFetchFailed] = useState<boolean>( false ); const { t } = useTranslation(); const { chainId, account, library, active, activate, error: web3Error, } = useWeb3React<Web3Provider>(); let defaultBaseTokenAddress: string | null = allTokens.length ? findTokensBySymbol("USDT", allTokens)[0].address : null; let defaultQuoteTokenAddress: string | null = allTokens.length ? findTokensBySymbol("WETH", allTokens)[0].address : null; // Use default tokens only if neither are specified in the URL. const baseToken = tokenFrom ? tokenFrom : tokenTo ? null : defaultBaseTokenAddress; const quoteToken = tokenTo ? tokenTo : tokenFrom ? null : defaultQuoteTokenAddress; const baseTokenInfo = useMemo( () => baseToken ? findEthOrTokenByAddress(baseToken, activeTokens, chainId!) : null, [baseToken, activeTokens, chainId] ); const quoteTokenInfo = useMemo( () => quoteToken ? findEthOrTokenByAddress(quoteToken, activeTokens, chainId!) : null, [quoteToken, activeTokens, chainId] ); const maxAmount = useMemo(() => { if ( !baseToken || !balances || !baseTokenInfo || !balances.values[baseToken] || balances.values[baseToken] === "0" ) { return null; } return formatUnits( balances.values[baseToken] || "0", baseTokenInfo.decimals ); }, [balances, baseToken, baseTokenInfo]); useEffect(() => { setAllowanceFetchFailed(false); setBaseAmount(initialBaseAmount); dispatch(clearTradeTerms()); unsubscribeFromGasPrice(); unsubscribeFromTokenPrice(); dispatch(clear()); LastLook.unsubscribeAllServers(); }, [ chainId, dispatch, LastLook, unsubscribeFromGasPrice, unsubscribeFromTokenPrice, ]); useEffect(() => { if (ordersStatus === "reset") { setIsApproving(false); setIsSwapping(false); setIsWrapping(false); setIsRequestingQuotes(false); setAllowanceFetchFailed(false); setPairUnavailable(false); setProtocolFeeDiscountInfo(false); setShowGasFeeInfo(false); setBaseAmount(initialBaseAmount); LastLook.unsubscribeAllServers(); } }, [ordersStatus, LastLook, dispatch]); // Reset when the chainId changes. useEffect(() => { if (chainId) { dispatch(resetOrders()); } }, [chainId, dispatch]); useEffect(() => { setAllowanceFetchFailed( allowances.light.status === "failed" || allowances.wrapper.status === "failed" ); }, [allowances.light.status, allowances.wrapper.status]); let swapType: SwapType = "swap"; if (chainId && baseToken && quoteToken) { const eth = nativeETH[chainId].address; const weth = wethAddresses[chainId]; if ([weth, eth].includes(baseToken) && [weth, eth].includes(quoteToken)) { swapType = "wrapOrUnwrap"; } else if ([quoteToken, baseToken].includes(eth)) { swapType = "swapWithWrap"; } } const quoteAmount = swapType === "wrapOrUnwrap" ? baseAmount : tradeTerms.quoteAmount || bestTradeOption?.quoteAmount || ""; const hasApprovalPending = (tokenId: string | undefined) => { if (tokenId === undefined) return false; return pendingApprovals.some((tx) => tx.tokenAddress === tokenId); }; const hasSufficientAllowance = (tokenAddress: string | undefined) => { if (tokenAddress === nativeETH[chainId || 1].address) return true; if (!tokenAddress) return false; if ( allowances[swapType === "swapWithWrap" ? "wrapper" : "light"].values[ tokenAddress ] === undefined ) { // We don't currently know what the user's allowance is, this is an error // state we shouldn't repeatedly hit, so we'll prompt a reload. if (!allowanceFetchFailed) setAllowanceFetchFailed(true); // safter to return true here (has allowance) as validator will catch the // missing allowance, so the user won't swap, and they won't pay // unnecessary gas for an approval they may not need. return true; } return new BigNumber( allowances[swapType === "swapWithWrap" ? "wrapper" : "light"].values[ tokenAddress ]! ) .div(10 ** (baseTokenInfo?.decimals || 18)) .gte(baseAmount); }; const handleSetToken = (type: TokenSelectModalTypes, value: string) => { if (type === "base") { value === quoteToken ? history.push({ pathname: `/${value}/${baseToken}` }) : history.push({ pathname: `/${value}/${quoteToken}` }); setBaseAmount(""); } else { value === baseToken ? history.push({ pathname: `/${quoteToken}/${value}` }) : history.push({ pathname: `/${baseToken}/${value}` }); } }; let insufficientBalance: boolean = false; if (baseAmount && baseToken && Object.keys(balances.values).length) { if (parseFloat(baseAmount) === 0 || baseAmount === ".") { insufficientBalance = false; } else { const baseDecimals = baseTokenInfo?.decimals; if (baseDecimals) { insufficientBalance = new BigNumber( balances.values[baseToken!] || "0" ).lt(new BigNumber(baseAmount).multipliedBy(10 ** baseDecimals)); } } } const handleAddActiveToken = (address: string) => { if (library) { dispatch(addActiveToken(address)); dispatch(requestActiveTokenBalances({ provider: library! })); dispatch(requestActiveTokenAllowancesLight({ provider: library! })); dispatch(requestActiveTokenAllowancesWrapper({ provider: library! })); } }; const handleRemoveActiveToken = (address: string) => { if (library) { if (address === baseToken) { history.push({ pathname: `/-/${quoteToken || "-"}` }); setBaseAmount(initialBaseAmount); } else if (address === quoteToken) { history.push({ pathname: `/${baseToken || "-"}/-` }); } dispatch(removeActiveToken(address)); dispatch(requestActiveTokenBalances({ provider: library! })); dispatch(requestActiveTokenAllowancesLight({ provider: library! })); dispatch(requestActiveTokenAllowancesWrapper({ provider: library! })); } }; const requestQuotes = async () => { if (swapType === "wrapOrUnwrap") { // This will re-render with a 1:1 price and a take button. setIsWrapping(true); return; } setIsRequestingQuotes(true); const usesWrapper = swapType === "swapWithWrap"; const weth = wethAddresses[chainId!]; const eth = nativeETH[chainId!]; const _quoteToken = quoteToken === eth.address ? weth : quoteToken!; const _baseToken = baseToken === eth.address ? weth : baseToken!; let rfqServers, lastLookServers; try { try { const servers = await new Registry( chainId, // @ts-ignore provider type mismatch library ).getServers(_quoteToken, _baseToken, { initializeTimeout: 10 * 1000, }); rfqServers = servers.filter((s) => s.supportsProtocol("request-for-quote") ); lastLookServers = servers.filter((s) => s.supportsProtocol("last-look") ); } catch (e) { console.error("Error requesting orders:", e); throw new Error("error requesting orders"); } let rfqPromise: Promise<LightOrder[]> | null = null, lastLookPromises: Promise<Pricing>[] | null = null; if (rfqServers.length) { let rfqDispatchResult = dispatch( request({ servers: rfqServers, senderToken: _baseToken, senderAmount: baseAmount, signerToken: _quoteToken, senderTokenDecimals: baseTokenInfo!.decimals, senderWallet: usesWrapper ? Wrapper.getAddress(chainId) : account!, }) ); rfqPromise = rfqDispatchResult .then((result) => { return unwrapResult(result); }) .then((orders) => { if (!orders.length) throw new Error("no valid orders"); return orders; }); } if (lastLookServers.length) { if (usesWrapper) { lastLookServers.forEach((s) => s.disconnect()); } else { lastLookPromises = LastLook.subscribeAllServers(lastLookServers, { baseToken: baseToken!, quoteToken: quoteToken!, }); } } let orderPromises: Promise<LightOrder[] | Pricing>[] = []; if (rfqPromise) orderPromises.push(rfqPromise); if (lastLookPromises) { orderPromises = orderPromises.concat(lastLookPromises); } // This promise times out if _no_ orders are received before the timeout // but resolves if _any_ are. const timeoutOnNoOrdersPromise = Promise.race<any>([ Promise.any(orderPromises), new Promise((_, reject) => setTimeout(() => { reject("no valid orders"); }, RECEIVE_QUOTE_TIMEOUT_MS) ), ]); // This promise resolves either when all orders are received or X seconds // after the first order is received. const waitExtraForAllOrdersPromise = Promise.race<any>([ Promise.allSettled(orderPromises), Promise.any(orderPromises).then( () => new Promise((resolve) => setTimeout(resolve, ADDITIONAL_QUOTE_BUFFER) ) ), ]); await Promise.all([ waitExtraForAllOrdersPromise, timeoutOnNoOrdersPromise, ]); } catch (e: any) { switch (e.message) { case "error requesting orders": { notifyError({ heading: t("orders.errorRequesting"), cta: t("orders.errorRequestingCta"), }); break; } default: { console.error(e); setPairUnavailable(true); } } } finally { setIsRequestingQuotes(false); } }; const takeBestOption = async () => { let order: LightOrder | null = null; try { setIsSwapping(true); // @ts-ignore // TODO: figure out type issues const validator = new Validator(chainId, library?.getSigner()); if (bestTradeOption!.protocol === "request-for-quote") { if (swapType !== "swapWithWrap") { const errors = (await validator.checkSwap( bestTradeOption!.order!, // NOTE: once new swap contract is used, this (senderAddress) needs // to be the wrapper address for wrapped swaps. account! )) as Error[]; if (errors.length) { setValidatorErrors(errors); setIsSwapping(false); return; } } LastLook.unsubscribeAllServers(); order = bestTradeOption!.order!; const result = await dispatch( take({ order: bestTradeOption!.order!, library, contractType: swapType === "swapWithWrap" ? "Wrapper" : "Light", onExpired: () => { notifyError({ heading: t("orders.swapExpired"), cta: t("orders.swapExpiredCallToAction"), }); }, }) ); setIsSwapping(false); await unwrapResult(result); setShowOrderSubmitted(true); } else { // Setting quote amount prevents the UI from updating if pricing changes dispatch(setTradeTermsQuoteAmount(bestTradeOption!.quoteAmount)); // Last look order. const { order: lastLookOrder, senderWallet, } = await LastLook.getSignedOrder({ locator: bestTradeOption!.pricing!.locator, terms: { ...tradeTerms, quoteAmount: bestTradeOption!.quoteAmount }, }); order = lastLookOrder; const errors = (await validator.checkSwap( order, senderWallet )) as Error[]; if (errors.length) { setValidatorErrors(errors); setIsSwapping(false); return; } const accepted = await LastLook.sendOrderForConsideration({ locator: bestTradeOption!.pricing!.locator, order: order, }); setIsSwapping(false); if (accepted) { setShowOrderSubmitted(true); LastLook.unsubscribeAllServers(); } else { notifyError({ heading: t("orders.swapRejected"), cta: t("orders.swapRejectedCallToAction"), }); dispatch( declineTransaction({ signerWallet: order.signerWallet, nonce: order.nonce, reason: "Pricing expired", }) ); } } } catch (e: any) { if (bestTradeOption!.protocol !== "request-for-quote") { setIsSwapping(false); dispatch(clearTradeTermsQuoteAmount()); } if (e.code && e.code === 4001) { // 4001 is metamask user declining transaction sig } else { notifyError({ heading: t("orders.swapFailed"), cta: t("orders.swapFailedCallToAction"), }); dispatch( revertTransaction({ signerWallet: order?.signerWallet, nonce: order?.nonce, reason: e.message, }) ); } } }; const doWrap = async () => { const method = baseTokenInfo === nativeETH[chainId!] ? deposit : withdraw; setIsSwapping(true); try { const result = await dispatch( method({ chainId: chainId!, senderAmount: baseAmount, senderTokenDecimals: baseTokenInfo!.decimals, provider: library!, }) ); await unwrapResult(result); setIsSwapping(false); setIsWrapping(false); setShowOrderSubmitted(true); } catch (e) { // user cancelled metamask dialog setIsSwapping(false); setIsWrapping(false); } }; const handleButtonClick = async (action: ButtonActions) => { switch (action) { case ButtonActions.goBack: setIsWrapping(false); setPairUnavailable(false); dispatch(clearTradeTerms()); dispatch(clear()); unsubscribeFromGasPrice(); unsubscribeFromTokenPrice(); LastLook.unsubscribeAllServers(); break; case ButtonActions.restart: setShowOrderSubmitted(false); dispatch(clearTradeTerms()); dispatch(clear()); unsubscribeFromGasPrice(); unsubscribeFromTokenPrice(); LastLook.unsubscribeAllServers(); setBaseAmount(initialBaseAmount); break; case ButtonActions.reloadPage: window.location.reload(); break; case ButtonActions.connectWallet: setShowWalletList(true); break; case ButtonActions.switchNetwork: try { (window as any).ethereum.request!({ method: "wallet_switchEthereumChain", params: [ { chainId: "0x1", }, ], }); } catch (e) { // unable to switch network, but doesn't matter too much as button // looks like a call to action in this case anyway. } break; case ButtonActions.requestQuotes: dispatch( setTradeTerms({ baseToken: { address: baseToken!, decimals: baseTokenInfo!.decimals, }, baseAmount: baseAmount, quoteToken: { address: quoteToken!, decimals: quoteTokenInfo!.decimals, }, quoteAmount: null, side: "sell", }) ); subscribeToGasPrice(); subscribeToTokenPrice( quoteTokenInfo!, // @ts-ignore library!, chainId ); await requestQuotes(); break; case ButtonActions.approve: setIsApproving(true); await dispatch( approve({ token: baseToken!, library, contractType: swapType === "swapWithWrap" ? "Wrapper" : "Light", chainId: chainId!, }) ); setIsApproving(false); break; case ButtonActions.takeQuote: if (["swap", "swapWithWrap"].includes(swapType)) { await takeBestOption(); } else if (swapType === "wrapOrUnwrap") { await doWrap(); } break; case ButtonActions.trackTransaction: onTrackTransactionClicked(); break; default: // Do nothing. } }; return ( <> <StyledSwapWidget> <SwapWidgetHeader title={isApproving ? t("orders.approve") : t("common.swap")} isQuote={!isRequestingQuotes && !showOrderSubmitted} onGasFreeTradeButtonClick={() => setShowGasFeeInfo(true)} protocol={bestTradeOption?.protocol as ProtocolType} expiry={bestTradeOption?.order?.expiry} /> {showOrderSubmitted ? ( <HugeTicks /> ) : isApproving || isSwapping ? ( <></> ) : ( <SwapInputs baseAmount={baseAmount} onBaseAmountChange={setBaseAmount} baseTokenInfo={baseTokenInfo} quoteTokenInfo={quoteTokenInfo} onChangeTokenClick={setShowTokenSelectModalFor} onMaxButtonClick={() => setBaseAmount(maxAmount || "0")} side="sell" tradeNotAllowed={pairUnavailable} isRequesting={isRequestingQuotes} // Note that using the quoteAmount from tradeTerms will stop this // updating when the user clicks the take button. quoteAmount={quoteAmount} disabled={!active || (!!quoteAmount && allowanceFetchFailed)} readOnly={ !!bestTradeOption || isWrapping || isRequestingQuotes || pairUnavailable || !active } showMaxButton={!!maxAmount && baseAmount !== maxAmount} /> )} <InfoContainer> <InfoSection orderSubmitted={showOrderSubmitted} isConnected={active} isPairUnavailable={pairUnavailable} isFetchingOrders={isRequestingQuotes} isApproving={isApproving} isSwapping={isSwapping} failedToFetchAllowances={allowanceFetchFailed} // @ts-ignore bestTradeOption={bestTradeOption} requiresApproval={ bestRfqOrder && !hasSufficientAllowance(baseToken!) } baseTokenInfo={baseTokenInfo} baseAmount={baseAmount} quoteTokenInfo={quoteTokenInfo} isWrapping={isWrapping} onFeeButtonClick={() => setProtocolFeeDiscountInfo(true)} /> </InfoContainer> <ButtonContainer> {!isApproving && !isSwapping && ( <ActionButtons walletIsActive={active} unsupportedNetwork={ !!web3Error && web3Error instanceof UnsupportedChainIdError } requiresReload={allowanceFetchFailed} orderComplete={showOrderSubmitted} baseTokenInfo={baseTokenInfo} quoteTokenInfo={quoteTokenInfo} hasAmount={ !!baseAmount.length && baseAmount !== "0" && baseAmount !== "." } hasQuote={ !isRequestingQuotes && (!!bestTradeOption || isWrapping) } hasSufficientBalance={!insufficientBalance} needsApproval={!!baseToken && !hasSufficientAllowance(baseToken)} pairUnavailable={pairUnavailable} onButtonClicked={handleButtonClick} isLoading={ isConnecting || isRequestingQuotes || ["approving", "taking"].includes(ordersStatus) || (!!baseToken && hasApprovalPending(baseToken)) } transactionsTabOpen={transactionsTabOpen} /> )} </ButtonContainer> </StyledSwapWidget> <Overlay onClose={() => setShowTokenSelectModalFor(null)} isHidden={!showTokenSelectModalFor} > <TokenList onSelectToken={(newTokenAddress) => { // e.g. handleSetToken("base", "0x123") handleSetToken(showTokenSelectModalFor, newTokenAddress); // Close the modal setShowTokenSelectModalFor(null); }} balances={balances} allTokens={allTokens} activeTokens={activeTokens} supportedTokenAddresses={supportedTokens} addActiveToken={handleAddActiveToken} removeActiveToken={handleRemoveActiveToken} chainId={chainId || 1} /> </Overlay> <Overlay title={t("wallet.selectWallet")} onClose={() => setShowWalletList(false)} isHidden={!showWalletList} > <StyledWalletProviderList onClose={() => setShowWalletList(false)} onProviderSelected={(provider) => { dispatch(setActiveProvider(provider.name)); setIsConnecting(true); activate(provider.getConnector()).finally(() => setIsConnecting(false) ); }} /> </Overlay> <Overlay title={t("validatorErrors.unableSwap")} subTitle={t("validatorErrors.swapFail")} onClose={async () => { await handleButtonClick(ButtonActions.restart); setValidatorErrors([]); }} isHidden={!validatorErrors.length} > <ErrorList errors={validatorErrors} handleClick={async () => { await handleButtonClick(ButtonActions.restart); setValidatorErrors([]); }} /> </Overlay> <Overlay title={t("information.gasFreeSwaps.title")} onClose={() => setShowGasFeeInfo(false)} isHidden={!showGasFeeInfo} > <GasFreeSwapsModal onCloseButtonClick={() => setShowGasFeeInfo(false)} /> </Overlay> <Overlay title={t("information.protocolFeeDiscount.title")} onClose={() => setProtocolFeeDiscountInfo(false)} isHidden={!protocolFeeDiscountInfo} > <ProtocolFeeDiscountModal /> </Overlay> <Overlay title={t("information.join.title")} onClose={afterInformationModalClose} isHidden={!activeInformationModal} > <JoinModal /> </Overlay> </> ); }; export default SwapWidget;
the_stack