text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
abstract class Layer { public readonly element: SVGGElement; public readonly tileWidth: number; // unit: px public readonly tileHeight: number; // unit: px public readonly mapWidth: number; // unit: tile public readonly mapHeight: number; // unit: tile constructor(element: SVGGElement, tileWidth: number, tileHeight: number, mapWidth: number, mapHeight: number) { this.element = element; this.mapWidth = mapWidth; this.mapHeight = mapHeight; this.tileWidth = tileWidth; this.tileHeight = tileHeight; } } class CursorLayer extends Layer { private readonly cursor: SVGRectElement; private anchors: Array<AnchorTile>; private cursorX: number = 0; private cursorY: number = 0; public readonly histories: Array<PathfindingHistory>; public showDetailDescription: (tile: SolutionTile) => any; constructor(element: SVGGElement, cursor: SVGRectElement, tileWidth: number, tileHeight: number, mapWidth: number, mapHeight: number) { super(element, tileWidth, tileHeight, mapWidth, mapHeight); this.anchors = new Array<AnchorTile>(); this.histories = new Array<PathfindingHistory>(); this.cursor = cursor; this.element.parentElement.addEventListener("mousemove", e => this.onLayerMouseMove(e)); this.element.parentElement.addEventListener("mouseleave", e => this.onLayerMouseLeave(e)); this.element.parentElement.addEventListener("mouseenter", e => this.onLayerMouseEnter(e)); } private onLayerMouseMove(event: MouseEvent) { var rect = this.element.parentElement.getBoundingClientRect(); var mouseX = Math.floor((event.clientX - rect.left) / this.tileWidth); var mouseY = Math.floor((event.clientY - rect.top) / this.tileHeight); var changed = false; if (this.cursorX != mouseX) { this.cursor.x.baseVal.value = mouseX * this.tileWidth; this.cursorX = mouseX; changed = true; } if (this.cursorY != mouseY) { this.cursor.y.baseVal.value = mouseY * this.tileHeight; this.cursorY = mouseY; changed = true; } if (changed) { this.cursor.getElementsByClassName("cursor-x")[0].textContent = `${this.cursorX}`; this.cursor.getElementsByClassName("cursor-y")[0].textContent = `${this.cursorY}`; } } private onLayerMouseLeave(event: MouseEvent) { this.cursor.style.visibility = "hidden"; } private onLayerMouseEnter(event: MouseEvent) { this.cursor.style.visibility = "inherit"; } public togglePath(index: number): boolean { var history = this.histories[index]; if (history == null) return; history.isVisible = !history.isVisible; if (history.isVisible) { var begin = 0.3; var tileElement = null as SVGElement; var callback = this.showDetailDescription; for (let step of history.path) { tileElement = step.visualize(this.tileWidth, this.tileHeight); step.updateAnimation(begin); if (callback != null) { tileElement.onmousemove = function (ev) { callback(step); }; } this.element.appendChild(tileElement); begin += 0.1; } for (let tile of history.unvisited) { var filtered = history.path.filter(p => p.x === tile.x && p.y === tile.y); if (filtered.length > 0) { tile.levels.forEach(level => filtered[0].updateLevels(level)); } else { tileElement = tile.visualize(this.tileWidth, this.tileHeight); if (callback != null) { tileElement.onmousemove = function (ev) { callback(tile); }; } this.element.appendChild(tileElement); } } } else { history.path.forEach(p => p.remove()); history.unvisited.forEach(d => d.remove()); } return history.isVisible; } public placeTile(x: number, y: number, color: string) { if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return; } let filtered = this.anchors.filter(a => a.x === x && a.y === y); if (filtered.length > 0) { filtered[0].updateColor(color); } else { var anchor = new AnchorTile(x, y, color); this.element.appendChild(anchor.visualize(this.tileWidth, this.tileHeight)); this.anchors.push(anchor); } } public removeTile(x: number, y: number) { if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return; } this.anchors.filter(a => a.x === x && a.y === y).forEach(a => a.remove()); this.anchors = this.anchors.filter(a => !a.isRemoved()); } public clearAnchors() { for (let anchor of this.anchors) { anchor.remove(); } this.anchors = new Array<AnchorTile>(); } public clearTiles() { for (let history of this.histories) { history.path.forEach(path => path.remove()); history.unvisited.forEach(detail => detail.remove()); } } } class ForegroundLayer extends Layer { private readonly assetIds: ReadonlyArray<string>; public obstacle: number; public isPathfindingOnly: boolean; public objectPracingPredicate: (i: number, j: number, obstacle: number) => boolean; public pathPlacingCallback: (i: number, j: number) => boolean; constructor(sourceLayer: Layer, element: SVGGElement, assetIds: ReadonlyArray<string>) { super(element, sourceLayer.tileWidth, sourceLayer.tileHeight, sourceLayer.mapWidth, sourceLayer.mapHeight); this.element.parentElement.addEventListener("mouseup", e => this.onSourceLayerMouseUp(e)); this.element.parentElement.addEventListener("contextmenu", e => e.preventDefault()); this.assetIds = assetIds; this.obstacle = 1; this.isPathfindingOnly = false; for (let obj of document.querySelectorAll("#obstacle-list > svg")) { obj.addEventListener("click", e => this.onChangeObstacle(e)); } } private onSourceLayerMouseUp(event: MouseEvent) { var rect = this.element.parentElement.getBoundingClientRect(); var i = Math.floor((event.clientX - rect.left) / this.tileWidth); var j = Math.floor((event.clientY - rect.top) / this.tileHeight); if (this.isPathfindingOnly) { if (this.pathPlacingCallback != null) { this.pathPlacingCallback(i, j); } return; } switch (event.button) { case 0: if (this.objectPracingPredicate != null && this.objectPracingPredicate(i, j, this.obstacle)) { this.placeObject(i, j); } else { this.removeObject(i, j); } break; case 2: if (this.pathPlacingCallback != null) { this.pathPlacingCallback(i, j); } break; } } private onChangeObstacle(event: Event) { this.obstacle = parseInt(event.srcElement.getAttribute("data-obstacle-value")); } public placePath(path: ReadonlyArray<Step>, assetIdSelector: (step: Step) => string) { for (let step of path) { var id = `step-x-${step.x}-y-${step.y}`; // "step-x-" + step.x.toString() + "-y-" + step.y.toString(); var existing = this.element.querySelector("#" + id); var assetId = assetIdSelector(step); if (existing != null) { existing.remove(); } if (assetId != null && assetId.length > 0) { this.placeImage(step.x, step.y, "path-" + assetId).id = id; } } } public removePath(path: ReadonlyArray<Step>, assetIdSelector: (step: Step) => string) { for (let step of path) { var id = this.removeStep(step.x, step.y); var assetId = assetIdSelector(step); if (assetId != null && assetId.length > 0) { this.placeImage(step.x, step.y, "path-" + assetId).id = id; } } } public removeStep(x: number, y: number): string { var id = `step-x-${x}-y-${y}` // "step-x-" + x.toString() + "-y-" + y.toString(); if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return id; } var existing = this.element.querySelector("#" + id); if (existing != null) { existing.remove(); } return id; } public placeStep(x: number, y: number, assertId: string) { if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return; } this.placeImage(x, y, assertId); } private placeImage(x: number, y: number, assertId: string): SVGUseElement { var img = document.createElementNS("http://www.w3.org/2000/svg", "use"); img.x.baseVal.value = x * this.tileWidth; img.y.baseVal.value = y * this.tileHeight; img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#" + assertId); img.classList.add(`image-x-${x}-y-${y}`/*"image-x-" + x.toString() + "-y-" + y.toString()*/); this.element.appendChild(img); return img; } public placeObject(x: number, y: number) { if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return; } var id = `object-x-${x}-y-${y}`;// "object-x-" + x.toString() + "-y-" + y.toString(); var existing = this.element.querySelector("#" + id); if (existing != null) { existing.remove(); } // Replace the path with obstacle. this.removeStep(x, y); // because the property is not an index so we need to substract the value by one. this.placeImage(x, y, this.assetIds[this.obstacle - 1]).id = id; } public removeObject(x: number, y: number) { if (x < 0 || y < 0 || x >= this.mapWidth || y >= this.mapHeight) { return; } var id = `object-x-${x}-y-${y}`;// "object-x-" + x.toString() + "-y-" + y.toString(); var existing = this.element.querySelector("#" + id); if (existing != null) { existing.remove(); } } public clearMap() { for (let img of this.element.querySelectorAll("use")) { img.remove(); } } }
the_stack
import { Settings, TestManager, Utils } from '@microsoft/windows-admin-center-sdk/e2e'; import { EventViewer } from '../ui/eventViewer'; TestManager.doTest<EventViewer>(new EventViewer('Tool'), (testManager, testSuite) => { let strings = require('../../assets/strings/strings.json'); testSuite.describe( 'Events', () => { testSuite.beforeEach(async () => { await testManager.goToConnectionAndToolAsync( Settings.connection, strings.Strings.MsftSmeEventViewer.title); // TODO: make it configurable. }); testSuite.it('Should be able to select a root node and show "No log channel selected"', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync(strings.Strings.MsftSmeEventViewer.windowsLogs); await testManager.tool.findElementAsync('sme-event-event-list > h3'); const result = await testManager.tool.getTextAsync(); expect(result.indexOf('No log channel selected.')).not.toEqual(-1); }); testSuite.it('Should be able to select a default channel (Administrative Logs) and show proper actions', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync(strings.Strings.MsftSmeEventViewer.administrativeLogs); await testManager.tool.dataTable.selectItemByIndexAsync(0); await testManager.tool.dataTable.waitForDataLoadedAsync(); await testManager.tool.navigationTabs.clickByTextAsync(strings.Strings.MsftSmeEventViewer.eventDetails); await testManager.tool.detailPane.waitForVisibleAsync(); const result = await testManager.tool.detailPane.propertyGrid.getValueByLabelAsync( strings.Strings.MsftSmeEventViewer.logName + ':'); expect(result).toContain('Admin'); }); testSuite.it( 'Should be able to select a default channel(Administrative Logs) and search by key word(information)', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync(strings.Strings.MsftSmeEventViewer.administrativeLogs); await testManager.tool.searchAsync(strings.Strings.MsftSmeEventViewer.information); await testManager.tool.dataTable.selectItemByIndexAsync(0); await testManager.tool.dataTable.waitForDataLoadedAsync(); await testManager.tool.navigationTabs.clickByTextAsync(strings.Strings.MsftSmeEventViewer.eventDetails); await testManager.tool.detailPane.waitForVisibleAsync(); const result = await testManager.tool.detailPane.propertyGrid.getValueByLabelAsync( strings.Strings.MsftSmeEventViewer.level + ':'); expect(result).toContain(strings.Strings.MsftSmeEventViewer.information); }); testSuite.it('should be able to select a default channel (Application), an event and show its detail', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Application'); await testManager.tool.dataTable.selectItemByIndexAsync(0); await testManager.tool.dataTable.waitForDataLoadedAsync(); await testManager.tool.navigationTabs.clickByTextAsync(strings.Strings.MsftSmeEventViewer.eventDetails); await testManager.tool.detailPane.waitForVisibleAsync(); const result = await testManager.tool.detailPane.propertyGrid.getValueByLabelAsync( strings.Strings.MsftSmeEventViewer.logName + ':'); expect(result).toBe('Application'); }); testSuite.it('Should be able to select a default channel (Application) and show proper actions', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Application'); const actionBarDropDown = testManager.tool.actionBar.getChildUIObject( { name: 'action bar dropdown', selector: 'sme-dropdown' }); if (await actionBarDropDown.isVisibleAsync()) { await actionBarDropDown.clickAsync(); } const buttons = await testManager.tool.actionBar.findElementsAsync('button.sme-button-align-left'); const button1Text = await Utils.getTextAsync(buttons[0]); const button2Text = await Utils.getTextAsync(buttons[1]); expect(button1Text).toBe(strings.Strings.MsftSmeEventViewer.clear); expect(button2Text).toBe(strings.Strings.MsftSmeEventViewer.export); }); testSuite.it('Should be able to select a default channel (Setup) and show proper actions', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Setup'); let result = await testManager.tool.actionBar.moreButton.getTextAsync(); if (result.length > 0) { await testManager.tool.actionBar.moreButton.clickAsync(); } result = await testManager.tool.actionBar.getTextAsync(); expect(result).toContain('Log'); }); testSuite.it('Should be able to sort by date and time', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Application'); await testManager.tool.dataTable.selectItemByIndexAsync(0); if (Settings.browser !== 'MicrosoftEdge') { const date1 = new Date(await testManager.tool.dataTable.getCellTextInSelectedItemAsync( strings.Strings.MsftSmeEventViewer.dateAndTime)); await testManager.tool.dataTable.clickByTextAsync(strings.Strings.MsftSmeEventViewer.dateAndTime); await testManager.tool.dataTable.selectItemByIndexAsync(0); const date2 = new Date(await testManager.tool.dataTable.getCellTextInSelectedItemAsync( strings.Strings.MsftSmeEventViewer.dateAndTime)); expect(date1.getTime()).toBeGreaterThan(date2.getTime()); } else { const date1 = await testManager.tool.dataTable.getCellTextInSelectedItemAsync( strings.Strings.MsftSmeEventViewer.dateAndTime); await testManager.tool.dataTable.clickByTextAsync(strings.Strings.MsftSmeEventViewer.dateAndTime); await testManager.tool.dataTable.selectItemByIndexAsync(0); const date2 = await testManager.tool.dataTable.getCellTextInSelectedItemAsync( strings.Strings.MsftSmeEventViewer.dateAndTime); expect(date1).not.toEqual(date2); } }); testSuite.it('Should be able to Clear channel and show inactive buttons', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Windows PowerShell'); await testManager.tool.actionBar.clickActionButtonAsync(strings.Strings.MsftSmeEventViewer.clear); await TestManager.shell.switchToTopFrameAsync() await TestManager.shell.confirmationDialog.noButton.clickAsync(); await TestManager.shell.switchToToolIFrameAsync() await testManager.tool.actionBar.clickActionButtonAsync(strings.Strings.MsftSmeEventViewer.clear); await TestManager.shell.switchToTopFrameAsync() await TestManager.shell.confirmationDialog.yesButton.clickAsync(); await TestManager.shell.switchToToolIFrameAsync() await Utils.waitAsync( async () => { let itemElement = await testManager.tool.dataTable.getTextAsync(); return itemElement.lastIndexOf('No records found') !== -1; }, 'Wait for the channel to be empty.'); await testManager.tool.actionBar.moreButton.clickAsync(); const button1 = await testManager.tool.actionBar.findElementAsync('button', strings.Strings.MsftSmeEventViewer.clear); const isButton1Disabled = await Utils.isDisabledAsync(button1); const button2 = await testManager.tool.actionBar.findElementAsync('button', strings.Strings.MsftSmeEventViewer.export); const isButton2Disabled = await Utils.isDisabledAsync(button2); expect(isButton1Disabled && isButton2Disabled).toBeTruthy(); }); // NOTE: this test requires the edge's property: "Ask me what to do with each download" is "Off" testSuite.it('Should be able to Export channel', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync('Setup'); await testManager.tool.actionBar.clickActionButtonAsync(strings.Strings.MsftSmeEventViewer.export); await TestManager.shell.switchToTopFrameAsync(); await TestManager.shell.alertBar.waitForAlertByTextAsync('Successfully downloaded \'Setup\''); await TestManager.shell.switchToToolIFrameAsync(); }); testSuite.it('Should be able to swap enable/disable a channel', async () => { const disableAction = async () => { await testManager.tool.actionBar.clickActionButtonAsync(strings.Strings.MsftSmeEventViewer.disableLog); await TestManager.shell.switchToTopFrameAsync(); await testManager.tool.alertBar.waitForAlertByTextAsync('Successfully disabled \'Setup\''); await TestManager.shell.switchToToolIFrameAsync(); } const enableAction = async () => { await testManager.tool.actionBar.clickActionButtonAsync(strings.Strings.MsftSmeEventViewer.enableLog); await TestManager.shell.switchToTopFrameAsync(); await testManager.tool.alertBar.waitForAlertByTextAsync('Successfully enabled \'Setup\''); await TestManager.shell.switchToToolIFrameAsync(); } await testManager.tool.treeTable.GoToNodeByPathAsync('Setup'); await testManager.tool.actionBar.moreButton.clickAsync(); const enableButton = await testManager.tool.actionBar.findElementAsync( 'button', strings.Strings.MsftSmeEventViewer.enableLog); if (enableButton) { // channel is disabled, enable it first await enableAction(); await disableAction(); } else { await disableAction(); await enableAction(); } }); testSuite.it( 'Should be able to select a default channel(Administrative Logs) and filter by Event Levels(information).', async () => { await testManager.tool.treeTable.GoToNodeByPathAsync( strings.Strings.MsftSmeEventViewer.administrativeLogs); const filterButton = testManager.tool.getChildUIObject( { name: 'Filter Button', selector: 'sme-master-view .sme-icon-filter' }); await filterButton.clickAsync(); const criticalCheckBox = testManager.tool.actionPane.getChildUIObject({ name: 'Critical checkBox', selector: '#component-2-checkbox0' }); await criticalCheckBox.clickAsync(); const infoCheckBox = testManager.tool.actionPane.getChildUIObject({ name: 'Error checkBox', selector: '#component-2-checkbox1' }); await infoCheckBox.clickAsync(); const warningCheckBox = testManager.tool.actionPane.getChildUIObject({ name: 'Warning checkBox', selector: '#component-2-checkbox2' }); await warningCheckBox.clickAsync(); const verboseCheckBox = testManager.tool.actionPane.getChildUIObject({ name: 'Verbose checkBox', selector: '#component-2-checkbox4' }); await verboseCheckBox.clickAsync(); await testManager.tool.actionPane.primaryButton.clickAsync(); await testManager.tool.treeTable.GoToNodeByPathAsync(strings.Strings.MsftSmeEventViewer.administrativeLogs); await testManager.tool.dataTable.selectItemByIndexAsync(0); await testManager.tool.dataTable.waitForDataLoadedAsync(); await testManager.tool.navigationTabs.clickByTextAsync(strings.Strings.MsftSmeEventViewer.eventDetails); await testManager.tool.detailPane.waitForVisibleAsync(); const result = await testManager.tool.detailPane.propertyGrid.getValueByLabelAsync( strings.Strings.MsftSmeEventViewer.level + ':'); expect(result).toContain(strings.Strings.MsftSmeEventViewer.information); }); }, ['servers']); });
the_stack
import React from 'react'; import {defineMessages} from 'react-intl'; import {FormattedMessage} from 'gatsby-plugin-intl'; export const PAGE = defineMessages({ TILE: { id: 'methodology.page.title.text', defaultMessage: 'Methodology & data', description: 'methodology page title text', }, HEADING: { id: 'methodology.page.header.text', defaultMessage: 'Methodology', description: 'methodology page header text', }, DESCRIPTION: { id: 'methodology.page.paragraph', defaultMessage: ` This tool identifies communities that are overburdened by pollution and other environmental exposures and disadvantaged by underinvestment. A community qualifies as disadvantaged when a census tract is at or above a certain threshold for a climate or environmental burden indicator and also above a certain threshold for a socioeconomic indicator. Census tract geographical boundaries are determined by the U.S. Census Bureau once every ten years. This tool untilizes the census tract boundaries from 2010. `, description: 'methodology page paragraph', }, FORMULA_INTRO: { id: 'methodology.page.formula.intro', defaultMessage: ` Under the current formula, a census tract will be considered disadvantaged: `, description: 'methodology page introducing the formula', }, CATEGORY_TEXT: { id: 'methodology.page.categories.title', defaultMessage: ` Communities will be defined as disadvantaged for the purposes of Justice40 if they meet the qualifications under one or more of the eight categories of criteria below. `, description: 'methodology page explanation of the categories', }, }); export const FORMULA = { IF: <FormattedMessage id={'methodology.page.formula.first'} defaultMessage={ `{if} it is above the threshold for one or more climate or environmental indicator`} description={'the first part of the formula used in the methodology'} values= {{ if: <span>IF</span>, }} />, AND: <FormattedMessage id={'methodology.page.formula.second'} defaultMessage={ `{and} it is above the threshold for one or more socioeconomic indicator`} description={'the second part of the formula used in the methodology'} values= {{ and: <span>AND</span>, }} />, THEN: <FormattedMessage id={'methodology.page.formula.second'} defaultMessage={ `{then} the community is considered disadvantaged.`} description={'the second part of the formula used in the methodology'} values= {{ then: <span>THEN</span>, }} />, }; // Download Package export const DOWNLOAD_FILE_SIZE = '73MB'; export const DOWNLOAD_LAST_UPDATED = '12/13/21'; export const DOWNLOAD_LAST_UPDATED_ES = '13/12/21'; export const VERSION_NUMBER = '0.1'; export const DOWNLOAD_ZIP_URL = [ process.env.GATSBY_CDN_TILES_BASE_URL, process.env.GATSBY_DATA_PIPELINE_SCORE_PATH, process.env.GATSBY_SCORE_DOWNLOAD_FILE_PATH, ].join('/'); export const DOWNLOAD_PACKAGE = { TITLE: <FormattedMessage id={'downloadPacket.header.text'} defaultMessage={`Draft communities list v{versionNumber} ({downloadFileSize})`} description={'download packet header text'} values= {{ versionNumber: VERSION_NUMBER, downloadFileSize: DOWNLOAD_FILE_SIZE, }} />, DESCRIPTION: <FormattedMessage id={ 'downloadPacket.info.text'} defaultMessage= {` The download package includes draft v{versionNumber} of the list of disadvantaged communities (.csv and .xlsx) and information (.pdf) about how to use the list. `} description= {'download packet info text'} values= {{ versionNumber: VERSION_NUMBER, }} />, LAST_UPDATED: <FormattedMessage id={ 'downloadPacket.info.last.updated'} defaultMessage= {`Last updated: {downloadLastUpdated} `} description= {'download packet info last updated'} values= {{ downloadLastUpdated: DOWNLOAD_LAST_UPDATED, }} />, BUTTON_TEXT: <FormattedMessage id={ 'downloadPacket.button.text'} defaultMessage= {'Download package'} description= {'download packet button text'} />, }; // Low Income section export const LOW_INCOME = defineMessages({ HEADING: { id: 'low.income.heading', defaultMessage: 'Low Income', description: 'title of section describing low income', }, INFO: { id: 'low.income.info', defaultMessage: ` At or above 65th percentile for percent of census tract population of households where household income is at or below 200% of the federal poverty level `, description: 'description of low income', }, }); export const CATEGORY= { HEADING: <FormattedMessage id={'indicator.categories.heading'} defaultMessage={'Categories'} description= {'category heading'} />, }; // Indicator Categories copy constants: export const CATEGORIES = { ALL: { METHODOLOGY: <FormattedMessage id= {'methodologies.all.used.in.text'} defaultMessage= {`All methodologies except for training and workforce development`} description= {'used in text for all methodologies'} />, }, CLIMATE_CHANGE: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.climate.change.methodology'} defaultMessage= {`Climate change methodology`} description= {'climate change methodology'} />, TITLE: <FormattedMessage id={'indicator.categories.climate.change.title'} defaultMessage={'Climate change'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.climate.change.if'} defaultMessage= {` {if} at or above 90th percentile for {expAgrLossRate} OR {expbuildLossRate} OR {expPopLossRate} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, expAgrLossRate: <a href="#exp-agr-loss-rate">expected agriculture loss rate</a>, expbuildLossRate: <a href="#exp-bld-loss-rate">expected building loss rate</a>, expPopLossRate: <a href="#exp-pop-loss-rate">expected population loss rate</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.climate.change.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.climate.change.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, CLEAN_ENERGY: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.climate.change.methodology'} defaultMessage= {`Clean energy and energy efficiency methodology`} description= {`Clean energy and energy efficiency methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.clean.energy.title'} defaultMessage={'Clean energy and energy efficiency'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.clean.energy.if'} defaultMessage= {` {if} at or above 90th percentile for {energyCostBur} score OR {pm25} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, energyCostBur: <a href='#energy-burden'>energy cost burden</a>, pm25: <a href='#pm-25'>PM2.5 in the air</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.clean.energy.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.clean.energy.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, CLEAN_TRANSPORT: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.clean.transport.methodology'} defaultMessage= {`Clean transportation methodology`} description= {`Clean transportation methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.clean.transport.title'} defaultMessage={'Clean transportation'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.clean.transport.if'} defaultMessage= {` {if} at or above 90th percentile for {dieselPM} or {traffic} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, dieselPM: <a href='#diesel-pm'>diesel particulate matter exposure</a>, traffic: <a href='#traffic-vol'>traffic proximity and volume</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.clean.transport.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.clean.transport.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, AFFORDABLE_HOUSING: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.afford.housing.methodology'} defaultMessage= {`Affordable and sustainable housing methodology`} description= {`Affordable and sustainable housing methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.afford.house.title'} defaultMessage={'Affordable and sustainable housing'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.afford.house.if'} defaultMessage= {` {if} at or above 90th percentile for {lead} AND {medianHomeVal} is at or less than 90th percentile OR at or above the 90th percentile for the {houseBur} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, lead: <a href='#lead-paint'>lead paint</a>, medianHomeVal: <a href='#median-home'>low median home value</a>, houseBur: <a href='#house-burden'>housing cost burden</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.afford.house.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.afford.house.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, LEGACY_POLLUTION: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.legacy.pollute.methodology'} defaultMessage= {`Reduction and remediation of legacy pollution methodology`} description= {`Reduction and remediation of legacy pollution methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.legacy.pollution.title'} defaultMessage={'Reduction and remediation of legacy pollution'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.legacy.pollution.if'} defaultMessage= {` {if} at or above 90th percentile for {proxHaz} OR {proxNPL} OR {proxRMP} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, proxHaz: <a href='#prox-haz'>proximity to hazardous waste facilities</a>, proxNPL: <a href='#prox-npl'>proximity to NPL sites</a>, proxRMP: <a href='#prox-rmp'>proximity to RMP facilities</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.legacy.pollution.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.legacy.pollution.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, CLEAN_WATER: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.clean.water.methodology'} defaultMessage= {`Critical clean water and waste infrastructure methodology`} description= {`Critical clean water and waste infrastructure methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.clean.water.title'} defaultMessage={'Critical clean water and waste infrastructure'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.clean.water.if'} defaultMessage= {` {if} at or above 90th percentile for {wasteWater} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, wasteWater: <a href='#waste-water'>wastewater discharge</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.clean.water.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.clean.water.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, HEALTH_BURDENS: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.health.burdens.methodology'} defaultMessage= {`Health burdens methodology`} description= {`Health burdens methodology`} />, TITLE: <FormattedMessage id={'indicator.categories.health.burdens.title'} defaultMessage={'Health burdens'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.health.burdens.if'} defaultMessage= {` {if} at or above 90th percentile for {asthma} OR {diabetes} OR {heart} OR {life} `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, diabetes: <a href='#diabetes'>diabetes</a>, asthma: <a href='#asthma'>asthma</a>, heart: <a href='#heart-disease'>heart disease</a>, life: <a href='#life-exp'>low life expectancy</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.health.burdens.and'} defaultMessage= {'{and} is low income{asterisk}'} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, asterisk: <sup>*</sup>, }} />, THEN: <FormattedMessage id= {'indicator.categories.health.burdens.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, WORKFORCE_DEV: { METHODOLOGY: <FormattedMessage id= {'indicator.categories.workforce.dev.methodology'} defaultMessage= {`Training and workforce development methodology`} description= {`Training and workforce development`} />, TITLE: <FormattedMessage id={'indicator.categories.work.dev.title'} defaultMessage={'Training and workforce development'} description= {'category title'} />, IF: <FormattedMessage id= {'indicator.categories.work.dev.if'} defaultMessage= {` {if} at or above the 90th percentile for {lowMedInc} as a percent of area median income OR {linIso} OR {unemploy} OR percent individuals in households at or below 100% federal {poverty} level `} description= {'if portion of the formula'} values= {{ if: <strong>IF</strong>, lowMedInc: <a href='#low-med-inc'>low median income</a>, linIso: <a href='#ling-iso'>linguistic isolation</a>, unemploy: <a href='#unemploy'>unemployment</a>, poverty: <a href='#poverty'>poverty</a>, }} />, AND: <FormattedMessage id= {'indicator.categories.work.dev.and'} defaultMessage= {` {and} where {highSchool} for adults 25 years and older is at or less than 90% `} description= {'and portion of the formula'} values= {{ and: <strong>AND</strong>, highSchool: <a href='#high-school'>the high school degree achievement rates</a>, }} />, THEN: <FormattedMessage id= {'indicator.categories.work.dev.then'} defaultMessage= {'{then} the community is disadvantaged.'} description= {'then portion of the formula'} values= {{ then: <strong>THEN</strong>, asterisk: <sup>*</sup>, }} />, }, }; // Dataset section export const DATASETS = defineMessages({ HEADING: { id: 'datasetContainer.heading', defaultMessage: 'Datasets used in methodology', description: 'section heading of which datasets are used in cumulative score', }, INFO: { id: 'datasetContainer.info', defaultMessage: 'The datasets come from a variety of sources and were selected' + ' based on relevance, availability, recency, and quality. The datasets seek to' + ' identify a range of human health, environmental, climate-related, and other' + ' cumulative impacts on communities.', description: 'description of the dataset section', }, ADDITIONAL_HEADING: { id: 'datasetContainer.additional.heading', defaultMessage: 'Additional Indicators', description: 'additional indicators heading', }, ADDITIONAL_INFO: { id: 'datasetContainer.additional.info', defaultMessage: 'These datasets provide additional information about each community.', description: 'additional indicator info', }, }); export const DATASET_CARD_LABELS = defineMessages({ USED_IN: { id: 'datasetCard.used.in', defaultMessage: 'Used in: ', description: 'label associated with explaining the card', }, RESP_PARTY: { id: 'datasetCard.responsible.party', defaultMessage: 'Responsible Party: ', description: 'label associated with explaining the card', }, DATE_RANGE: { id: 'datasetCard.date.range', defaultMessage: 'Date range: ', description: 'label associated with explaining the card', }, }); export const RESPONSIBLE_PARTIES = { CENSUS_ACS: <FormattedMessage id= {'category.resp.party.census.link'} defaultMessage= {'{resPartyCensusLink}'} description= {'responsible party link for Census ACS'} values= {{ resPartyCensusLink: <a href={`https://www.census.gov/programs-surveys/acs`} target={'_blank'} rel="noreferrer"> {`Census's American Community Survey`} </a>, }} />, FEMA: <FormattedMessage id= {'category.resp.party.fema.link'} defaultMessage= {`{resPartyFemaLink}`} description= {'responsible party link for FEMA'} values={{ resPartyFemaLink: <a href={`https://hazards.fema.gov/nri/expected-annual-loss`} target={'_blank'} rel="noreferrer"> {`Federal Emergency Management Agency (FEMA)`} </a>, }} />, DOE: <FormattedMessage id= {'category.resp.party.doe.link'} defaultMessage= {`{resPartyDoeLink}`} description= {'responsible party link for FEMA'} values={{ resPartyDoeLink: <a href={`https://www.energy.gov/eere/slsc/low-income-energy-affordability-data-lead-tool`} target={'_blank'} rel="noreferrer"> {`Department of Energy (DOE) LEAD Score`} </a>, }} />, EPA_OAR: <FormattedMessage id= {'category.resp.party.epa.oar.link'} defaultMessage= {`{resPartyEpaOarLink}`} description= {'responsible party link for EPA OAR'} values={{ resPartyEpaOarLink: <a href={`https://www.epa.gov/ejscreen/technical-documentation-ejscreen`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) Office of Air and Radiation (OAR) fusion of model and monitor data as compiled by EPA's EJSCREEN, sourced from EPA National Air Toxics Assessment (NATA), 2017 U.S. Department of Transportation (DOT) traffic data `} </a>, }} />, EPA_NATA: <FormattedMessage id= {'category.resp.party.epa.nata.link'} defaultMessage= {`{resPartyEpaOarLink}`} description= {'responsible party link for EPA NATA'} values={{ resPartyEpaOarLink: <a href={`https://www.epa.gov/ejscreen/technical-documentation-ejscreen`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) National Air Toxics Assessment (NATA) as compiled by EPA's EJSCREEN `} </a>, }} />, DOT_EPA: <FormattedMessage id= {'category.resp.party.dot.epa.link'} defaultMessage= {`{resPartyDotEpaLink}`} description= {'responsible party link for DOT EPA'} values={{ resPartyDotEpaLink: <a href={`https://www.epa.gov/ejscreen/technical-documentation-ejscreen`} target={'_blank'} rel="noreferrer"> {` Department of Transportation (DOT) traffic data as compiled by EPA's EJSCREEN `} </a>, }} />, HUD: <FormattedMessage id= {'category.resp.party.hud.link'} defaultMessage= {`{resPartyHudLink}`} description= {'responsible party link for HUD'} values={{ resPartyHudLink: <a href={`https://www.huduser.gov/portal/datasets/cp.html`} target={'_blank'} rel="noreferrer"> {` Department of Housing & Urban Development’s (HUD) Comprehensive Housing Affordability Strategy dataset `} </a>, }} />, EPA_TSDF: <FormattedMessage id= {'category.resp.party.epa.tsdf.link'} defaultMessage= {`{resPartyEpaTsdfLink}`} description= {'responsible party link for EPA TSDF'} values={{ resPartyEpaTsdfLink: <a href={`https://enviro.epa.gov/facts/rcrainfo/search.html`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) Treatment Storage, and Disposal Facilities (TSDF) data calculated from EPA RCRA info database as compiled by EPA’s EJSCREEN `} </a>, }} />, EPA_CERCLIS: <FormattedMessage id= {'category.resp.party.epa.cerclis.link'} defaultMessage= {`{resPartyEpaCerclisLink}`} description= {'responsible party link for EPA CERCLIS'} values={{ resPartyEpaCerclisLink: <a href={`https://enviro.epa.gov/facts/rcrainfo/search.html`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) CERCLIS database as compiled by EPA’s EJSCREEN `} </a>, }} />, EPA_RMP: <FormattedMessage id= {'category.resp.party.epa.rmp.link'} defaultMessage= {`{resPartyEpaRmpLink}`} description= {'responsible party link for EPA RMP'} values={{ resPartyEpaRmpLink: <a href={`https://www.epa.gov/ejscreen/technical-documentation-ejscreen`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) RMP database as compiled by EPA’s EJSCREEN `} </a>, }} />, EPA_RSEI: <FormattedMessage id= {'category.resp.party.epa.rsei.link'} defaultMessage= {`{resPartyEpaRseiLink}`} description= {'responsible party link for EPA RSEI'} values={{ resPartyEpaRseiLink: <a href={`https://www.epa.gov/ejscreen/technical-documentation-ejscreen`} target={'_blank'} rel="noreferrer"> {` Environmental Protection Agency (EPA) Risk-Screening Environmental Indicators (RSEI) Model as compiled by EPA's EJSCREEN `} </a>, }} />, CDC_PLACES: <FormattedMessage id= {'category.resp.party.cdc.places.link'} defaultMessage= {`{resPartyCdcPlacesLink}`} description= {'responsible party link for CDC Places'} values={{ resPartyCdcPlacesLink: <a href={`https://www.cdc.gov/places/index.html`} target={'_blank'} rel="noreferrer"> {` Centers for Disease Control and Prevention (CDC) PLACES `} </a>, }} />, CDC_SLEEP: <FormattedMessage id= {'category.resp.party.cdc.sleep.link'} defaultMessage= {`{resPartyCdcSleepLink}`} description= {'responsible party link for CDC Sleep'} values={{ resPartyCdcSleepLink: <a href={`https://www.cdc.gov/nchs/nvss/usaleep/usaleep.html#data`} target={'_blank'} rel="noreferrer"> {` CDC’s U.S. Small-area Life Expectancy Estimates Project (USALEEP) `} </a>, }} />, }; export const DATE_RANGE = { TEN_PLUS_5: '2010-2015', FOURTEEN: '2014', FOURTEEN_PLUS_4: '2014-2018', FOURTEEN_PLUS_7: '2014-2021', FIFETEEN_PLUS_4: '2015-2019', SIXTEEN_PLUS_3: '2016-2019', SIXTEEN_PLUS_4: '2016-2020', SEVENTEEN: '2017', EIGHTEEN: '2018', TWENTY: '2020', }; export const INDICATORS = [ { domID: 'low-income', indicator: 'Low income', description: <FormattedMessage id= {'category.low.income.description.text'} defaultMessage= {` Percent of a census tract's population in households where household income is at or below 200% of the federal poverty level. `} description= {'description text for low income'} />, usedIn: CATEGORIES.ALL.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'exp-agr-loss-rate', indicator: 'Expected agriculture loss rate', description: <FormattedMessage id= {'category.exp.agr.loss.rate.description.text'} defaultMessage= {` Percent of agriculture value at risk from losses due to natural hazards. Calculated by dividing the agriculture value at risk in a census tract by the total agriculture value in that census tract. Fourteen natural hazards that have some link to climate change include: avalanche, coastal flooding, cold wave, drought, hail, heat wave, hurricane, ice storm, landslide, riverine flooding, strong wind, tornado, wildfire, and winter weather. `} description= {'description text for exp agr loss rate'} />, usedIn: CATEGORIES.CLIMATE_CHANGE.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.FEMA, dateRange: DATE_RANGE.FOURTEEN_PLUS_7, }, { domID: 'exp-bld-loss-rate', indicator: 'Expected building loss rate', description: <FormattedMessage id= {'category.exp.bld.loss.rate.description.text'} defaultMessage= {` Percent of building value at risk from losses due to natural hazards. Calculated by dividing the building value at risk in a census tract by the total building value in that census tract. Fourteen natural hazards that have some link to climate change include: avalanche, coastal flooding, cold wave, drought, hail, heat wave, hurricane, ice storm, landslide, riverine flooding, strong wind, tornado, wildfire, and winter weather. `} description= {'description text for exp bld loss rate'} />, usedIn: CATEGORIES.CLIMATE_CHANGE.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.FEMA, dateRange: DATE_RANGE.FOURTEEN_PLUS_7, }, { domID: 'exp-pop-loss-rate', indicator: 'Expected population loss rate', description: <FormattedMessage id= {'category.exp.pop.loss.rate.description.text'} defaultMessage= {` Rate relative to the population in fatalities and injuries due to natural hazards each year. Fourteen natural hazards that have some link to climate change include: avalanche, coastal flooding, cold wave, drought, hail, heat wave, hurricane, ice storm, landslide, riverine flooding, strong wind, tornado, wildfire, and winter weather. Population loss is defined as the Spatial Hazard Events and Losses or National Centers for Environmental Information’s (NCEI) reported number of fatalities and injuries caused by the hazard occurrence. To combine fatalities and injuries for the computation of population loss value, an injury is counted as one-tenth (1/10) of a fatality. The NCEI Storm Events Database classifies injuries and fatalities as direct or indirect. Both direct and indirect injuries and fatalities are counted as population loss. This total number of injuries and fatalities is then divided by the population in the census tract to get a per-capita rate of population risk. `} description= {'description text for exp pop loss rate'} />, usedIn: CATEGORIES.CLIMATE_CHANGE.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.FEMA, dateRange: DATE_RANGE.FOURTEEN_PLUS_7, }, { domID: 'energy-burden', indicator: 'Energy cost burden', description: <FormattedMessage id= {'category.energy.burden.description.text'} defaultMessage= {`Average annual energy cost ($) divided by household income.`} description= {'description text for energy burden'} />, usedIn: CATEGORIES.CLEAN_ENERGY.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.DOE, dateRange: DATE_RANGE.EIGHTEEN, }, { domID: 'pm-25', indicator: 'PM2.5 in the air', description: <FormattedMessage id= {'category.pm2.5.description.text'} defaultMessage= {` Fine inhalable particles, with diameters that are generally 2.5 micrometers and smaller. `} description= {'description text for pm 2.5'} />, usedIn: CATEGORIES.CLEAN_ENERGY.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_OAR, dateRange: DATE_RANGE.SEVENTEEN, }, { domID: 'diesel-pm', indicator: 'Diesel particulate matter exposure', description: <FormattedMessage id= {'category.diesel.pm.description.text'} defaultMessage= {` Mixture of particles that is part of diesel exhaust in the air. `} description= {'description text for diesel pm'} />, usedIn: CATEGORIES.CLEAN_TRANSPORT.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_NATA, dateRange: DATE_RANGE.FOURTEEN, }, { domID: 'traffic-vol', indicator: 'Traffic proximity and volume', description: <FormattedMessage id= {'category.traffic.vol.description.text'} defaultMessage= {` Count of vehicles (average annual daily traffic) at major roads within 500 meters, divided by distance in meters (not km). `} description= {'description text for traffic volume'} />, usedIn: CATEGORIES.CLEAN_TRANSPORT.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.DOT_EPA, dateRange: DATE_RANGE.SEVENTEEN, }, { domID: 'house-burden', indicator: 'Housing cost burden', description: <FormattedMessage id= {'category.house.burden.description.text'} defaultMessage= {` The percent of households in a census tract that are both earning less than 80% of HUD Area Median Family Income by county and are paying greater than 30% of their income to housing costs. `} description= {'description text for housing burden'} />, usedIn: CATEGORIES.AFFORDABLE_HOUSING.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.HUD, dateRange: DATE_RANGE.FOURTEEN_PLUS_4, }, { domID: 'lead-paint', indicator: 'Lead paint', description: <FormattedMessage id= {'category.lead.paint.description.text'} defaultMessage= {` Percent of housing units built pre-1960, used as an indicator of potential lead paint exposure in tracts with median home values less than 90th percentile `} description= {'description text for lead paint'} />, usedIn: CATEGORIES.AFFORDABLE_HOUSING.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'median-home', indicator: 'Low median home value', description: <FormattedMessage id= {'category.lead.paint.description.text'} defaultMessage= {` Median home value of owner-occupied housing units in the census tract. `} description= {'description text for lead paint'} />, usedIn: CATEGORIES.AFFORDABLE_HOUSING.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'prox-haz', indicator: 'Proximity to hazardous waste facilities', description: <FormattedMessage id= {'category.prox.haz.description.text'} defaultMessage= {` Count of hazardous waste facilities (Treatment, Storage, and Disposal Facilities and Large Quantity Generators) within 5 km (or nearest beyond 5 km), each divided by distance in kilometers. `} description= {'description text for proximity to hazards'} />, usedIn: CATEGORIES.LEGACY_POLLUTION.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_TSDF, dateRange: DATE_RANGE.TWENTY, }, { domID: 'prox-npl', indicator: 'Proximity to National Priorities List (NPL) sites', description: <FormattedMessage id= {'category.prox.npl.description.text'} defaultMessage= {` Count of proposed or listed NPL - also known as superfund - sites within 5 km (or nearest one beyond 5 km), each divided by distance in kilometers. `} description= {'description text for proximity to npl'} />, usedIn: CATEGORIES.LEGACY_POLLUTION.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_CERCLIS, dateRange: DATE_RANGE.TWENTY, }, { domID: 'prox-rmp', indicator: 'Proximity to Risk Management Plan (RMP) facilities', description: <FormattedMessage id= {'category.prox.rmp.description.text'} defaultMessage= {` Count of RMP (potential chemical accident management plan) facilities within 5 km (or nearest one beyond 5 km), each divided by distance in kilometers. `} description= {'description text for proximity to rmp'} />, usedIn: CATEGORIES.LEGACY_POLLUTION.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_RMP, dateRange: DATE_RANGE.TWENTY, }, { domID: 'waste-water', indicator: 'Wastewater discharge', description: <FormattedMessage id= {'category.waste.water.description.text'} defaultMessage= {` Risk-Screening Environmental Indicators (RSEI) modeled Toxic Concentrations at stream segments within 500 meters, divided by distance in kilometers (km). `} description= {'description text for waste water'} />, usedIn: CATEGORIES.CLEAN_WATER.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.EPA_RSEI, dateRange: DATE_RANGE.TWENTY, }, { domID: 'asthma', indicator: 'Asthma', description: <FormattedMessage id= {'category.asthma.description.text'} defaultMessage= {` Weighted percent of people who answer “yes” to both of the following questions: “Have you ever been told by a doctor, nurse, or other health professional that you have asthma?” and the question “Do you still have asthma?” `} description= {'description text for asthma'} />, usedIn: CATEGORIES.HEALTH_BURDENS.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CDC_PLACES, dateRange: DATE_RANGE.SIXTEEN_PLUS_3, }, { domID: 'diabetes', indicator: 'Diabetes', description: <FormattedMessage id= {'category.diabetes.description.text'} defaultMessage= {` Weighted percent of people ages 18 years and older who report having ever been told by a doctor, nurse, or other health professionals that they have diabetes other than diabetes during pregnancy. `} description= {'description text for diabetes'} />, usedIn: CATEGORIES.HEALTH_BURDENS.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CDC_PLACES, dateRange: DATE_RANGE.SIXTEEN_PLUS_3, }, { domID: 'heart-disease', indicator: 'Heart disease', description: <FormattedMessage id= {'category.diabetes.description.text'} defaultMessage= {` Weighted percent of people ages 18 years and older who report ever having been told by a doctor, nurse, or other health professionals that they had angina or coronary heart disease. `} description= {'description text for diabetes'} />, usedIn: CATEGORIES.HEALTH_BURDENS.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CDC_PLACES, dateRange: DATE_RANGE.SIXTEEN_PLUS_3, }, { domID: 'life-exp', indicator: 'Low life expectancy', description: <FormattedMessage id= {'category.low.life.expectancy.description.text'} defaultMessage= {` Average number of years of life a person who has attained a given age can expect to live. {note} `} description= {'description text for low life expectancy'} values= {{ note: <p><strong>Note:</strong>{` Unlike most of the other datasets, high values of this indicator indicate low burdens. For percentile calculations, the percentile is calculated in reverse order, so that the tract with the highest median income relative to area median income (lowest burden on this measure) is at the 0th percentile, and the tract with the lowest median income relative to area median income (highest burden on this measure) is at the 100th percentile. `}</p>, }} />, usedIn: CATEGORIES.HEALTH_BURDENS.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CDC_SLEEP, dateRange: DATE_RANGE.TEN_PLUS_5, }, { domID: 'low-med-inc', indicator: 'Low median Income', description: <FormattedMessage id= {'category.workforce.dev.description.text'} defaultMessage= {` Median income of the census tract calculated as a percent of the area’s median income. `} description= {'description text for workforce dev'} />, usedIn: CATEGORIES.WORKFORCE_DEV.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'ling-iso', indicator: 'Linguistic Isolation', description: <FormattedMessage id= {'category.linguistic.iso.description.text'} defaultMessage= {` The percent of limited speaking households, which are households where no one over age 14 speaks English well. `} description= {'description text for linguistic isolation'} />, usedIn: CATEGORIES.WORKFORCE_DEV.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'unemploy', indicator: 'Unemployment', description: <FormattedMessage id= {'category.unemploy.description.text'} defaultMessage= {` Number of unemployed people as a percentage of the civilian labor force `} description= {'description text for unemployment'} />, usedIn: CATEGORIES.WORKFORCE_DEV.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'poverty', indicator: 'Poverty', description: <FormattedMessage id= {'category.poverty.description.text'} defaultMessage= {` Percent of a tract's population in households where the household income is at or below 100% of the federal poverty level. `} description= {'description text for poverty'} />, usedIn: CATEGORIES.WORKFORCE_DEV.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, }, { domID: 'high-school', indicator: 'High school degree achievement rate', description: <FormattedMessage id= {'category.highschool.description.text'} defaultMessage= {` Percent (not percentile) of people ages 25 years or older in a census tract whose education level is less than a high school diploma. `} description= {'description text for highschool'} />, usedIn: CATEGORIES.WORKFORCE_DEV.METHODOLOGY, responsibleParty: RESPONSIBLE_PARTIES.CENSUS_ACS, dateRange: DATE_RANGE.FIFETEEN_PLUS_4, isPercent: true, }, ]; export const RETURN_TO_TOP = { LINK: <FormattedMessage id={'methodology.page.return.to.top.link'} defaultMessage={'Return to top'} description= {'link text to return to top'} />, }; // Methodology Steps: // export const METHODOLOGY_STEPS = defineMessages({ // HEADING: { // id: 'methodology.steps.heading', // defaultMessage: `Methodology`, // description: 'heading of methodology section', // }, // DESCRIPTION_1: { // id: 'methodology.steps.description.1', // defaultMessage: 'The methodology for identifying communities of focus is'+ // ' calculated at the census block group level. Census block geographical boundaries'+ // ' are determined by the U.S. Census Bureau once every ten years. This tool utilizes'+ // ' the census block boundaries from 2010.', // description: 'first description text ', // }, // DESCRIPTION_2: { // id: 'methodology.steps.description.2', // defaultMessage: 'The following describes the process for identifying communities of focus.', // description: 'second description text', // }, // STEP_1_HEADING: { // id: 'methodology.step.1.heading', // defaultMessage: `Gather datasets`, // description: 'first step heading', // }, // STEP_1_INFO: { // id: 'methodology.step.1.info', // defaultMessage: `The methodology includes the following inputs that are equally weighted.`, // description: 'first step info', // }, // STEP_1_A_HEADING: { // id: 'methodology.step.1.a.heading', // defaultMessage: `Percent of Area Median Income`, // description: 'step 1 a heading', // }, // STEP_1_A_INFO_1: { // id: 'methodology.step.1.a.info.1', // defaultMessage: 'If a census block group is in a metropolitan area, this value is the'+ // ' median income of the census block group calculated as a percent of'+ // ' the metropolitan area’s median income.', // description: 'step 1 a info 1', // }, // STEP_1_A_INFO_2: { // id: 'methodology.step.1.a.info.2', // defaultMessage: 'If a census block group is not in a metropolitan area, this value is the'+ // ' median income of the census block group calculated as a percent of the state’s median'+ // ' income.', // description: 'step 1 a info 2', // }, // STEP_1_B_HEADING: { // id: 'methodology.step.1.b.heading', // defaultMessage: `Percent of households below or at 100% of the federal poverty line`, // description: 'step 1 b heading', // }, // STEP_1_C_HEADING: { // id: 'methodology.step.1.c.heading', // defaultMessage: `The high school degree achievement rate for adults 25 years and older`, // description: 'step 1 a heading', // }, // STEP_1_C_INFO: { // id: 'methodology.step.1.c.info', // defaultMessage: 'The percent of individuals who are 25 or older who have received a high school degree.', // description: 'step 1 c info', // }, // STEP_2_HEADING: { // id: 'methodology.step.2.heading', // defaultMessage: `Determine communites of focus`, // description: 'second step heading', // }, // STEP_2_INFO: { // id: 'methodology.step.2.info', // defaultMessage: `Under the existing formula, a census block group will be considered a community of focus if:`, // description: 'second step info', // }, // }); // const FED_POVERTY_LINE_URL = 'https://www.census.gov/topics/income-poverty/poverty/guidance/poverty-measures.html'; // // Copy that has links or other HTML tags in them // export const COMPLEX_METH_STEPS = { // STEP_2_B_INFO: <FormattedMessage // id={'methodology.steps.2.b.info'} // description={'Download the draft list of communities of focus and datasets used.'} // defaultMessage={`This is the percent of households in a state with a household income // below or at 100% of the {federalPovertyLine}. This federal poverty line is calculated // based on the composition of each household (e.g., based on household size), but it does // not vary geographically.`} // values={{ // federalPovertyLine: // <a href={FED_POVERTY_LINE_URL} target="_blank" rel="noreferrer"> // federal poverty line // </a>, // }} // />, // FORMULA: <FormattedMessage // id={'methodology.steps.2.formula'} // description={'Formala used to calculate communities of focus'} // defaultMessage={`{medianIncome} {or} {livingAtPovery} {and} {education}`} // values={{ // medianIncome: // <p> // (The median income is less than 80% of the area median income // </p>, // or: // <p className={'flush'}> // OR // </p>, // livingAtPovery: // <p className={'flush'}> // households living in poverty (at or below 100% of the federal poverty level) is greater than 20%) // </p>, // and: // <p className={'flush'}> // AND // </p>, // education: // <p className={'flush'}> // The high school degree achievement rate for adults 25 years and older is greater than 95% // </p>, // }} // />, // };
the_stack
import { ActionReducer } from '@ngrx/store'; import { camelCase } from '../../util/case'; import { iif, isUndefined, map, noop, pipe, throwError } from '../../util/func'; import { EntityActionTypes } from '../actions/action-types'; import { CreateManySuccess, CreateSuccess } from '../actions/create-actions'; import { DeleteManySuccess, DeleteSuccess } from '../actions/delete-actions'; import { DeleteByKeySuccess, DeleteManyByKeysSuccess } from '../actions/delete-by-key-actions'; import { DeselectMany, DeselectManyByKeys } from '../actions/deselection-actions'; import { Change, Edit, EditByKey, EditNew } from '../actions/edit-actions'; import { IEntityAction } from '../actions/entity-action'; import { EntityActions } from '../actions/entity-actions-union'; import { LoadSuccess } from '../actions/load-actions'; import { LoadAllSuccess } from '../actions/load-all-actions'; import { LoadManySuccess } from '../actions/load-many-actions'; import { LoadPageSuccess } from '../actions/load-page-actions'; import { LoadRangeSuccess } from '../actions/load-range-actions'; import { ReplaceManySuccess, ReplaceSuccess } from '../actions/replace-actions'; import { Select, SelectByKey, SelectMany, SelectManyByKeys, SelectMore, SelectMoreByKeys } from '../actions/selection-actions'; import { UpdateManySuccess, UpdateSuccess } from '../actions/update-actions'; import { UpsertManySuccess, UpsertSuccess } from '../actions/upsert-actions'; import { getKey } from '../decorators/key-util'; import { EntityIdentity } from '../types/entity-identity'; import { FEATURE_AFFINITY } from '../util/util-tokens'; // tslint:disable:no-redundant-jsdoc export function stateNameFromAction(action: IEntityAction): string { return camelCase(action.info.modelName); } export function featureNameFromAction(action: IEntityAction): string { return (action.info.modelType as any)[FEATURE_AFFINITY]; } export function setNewState(featureName: string, stateName: string, state, newState) { const nextState = featureName ? { ...state, [featureName]: { ...state[featureName], [stateName]: newState } } : { ...state, [stateName]: newState }; return nextState; } export const safeGetKey = <TModel>(action: IEntityAction, entity: TModel): EntityIdentity => pipe( map(() => getKey(action, entity)), iif( isUndefined, throwError( // tslint:disable-next-line:max-line-length `[NGRX-AE] ! Entity key for \'${action.info.modelName}\' could not be found on this entity instance! Make sure your entity is properly decorated with the necessary key metadata. State will NOT be updated due to misconfiguration of your entity.` ), key => key ) )(null); export const cloneEntities = (original: any | null) => (!!original ? { ...original } : {}); export const cloneIds = (ids: EntityIdentity[] | null) => (!!ids ? [...ids] : []); export const mergeSingle = (currentEntities, entityKey, newEntity) => ((currentEntities[entityKey] = newEntity), currentEntities); export const mergeMany = (currentEntities, newEntities, action) => newEntities.reduce((entities, entity) => ((entities[safeGetKey(action, entity)] = entity), entities), currentEntities); export const deleteSingle = (currentEntities, entityKey) => (delete currentEntities[entityKey], currentEntities); export const deleteMany = (currentEntities, entityKeys) => ( entityKeys.forEach(entityKey => delete currentEntities[entityKey]), currentEntities ); export const pushSingle = (currentIds, entityKey) => (currentIds.push(entityKey), currentIds); export const pushMany = (currentIds, newEntities, action) => ( currentIds.push.apply(currentIds, newEntities.map(entity => safeGetKey(action, entity))), currentIds ); export const combineUnique = (currentIds, currentEntities, modifiedEntities, action) => { const newIds = modifiedEntities.map(entity => safeGetKey(action, entity)).filter(key => !(key in currentEntities)); currentIds.push.apply(currentIds, newIds); return currentIds; }; export const has = (array, value) => array.indexOf(value) > -1; export const pushIfMissing = (currentEntities, currentIds, entityKey) => entityKey in currentEntities ? noop() : currentIds.push(entityKey); export const pushUnique = (currentEntities, currentIds, entityKey) => (pushIfMissing(currentEntities, currentIds, entityKey), currentIds); export const pushManyUnique = (currentEntities, currentIds, entityKeys) => ( entityKeys.forEach(entityKey => pushIfMissing(currentEntities, currentIds, entityKey)), currentIds ); export const warnMissingPageInfo = (action: IEntityAction) => console.log( // tslint:disable-next-line:max-line-length `[NGRX-AE] Page information for '${action.info.modelName}' was not provided! Page info should be returned from your entity service's loadPage() method. State WILL be updated, however the current page and total entity count information will be incorrect.` ); export const warnMissingRangeInfo = (action: IEntityAction) => console.log( // tslint:disable-next-line:max-line-length `[NGRX-AE] Range information for '${action.info.modelName}' was not provided! Range info should be returned from your entity service's loadPage() method. State WILL be updated, however the current page and total entity count information will be incorrect.` ); export const reduceAutoEntityAction = (state, entityState: any, action: EntityActions<any>, stateName: string, featureName: string) => { try { switch (action.actionType) { case EntityActionTypes.Create: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.CreateFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.CreateSuccess: { const createEntity = (action as CreateSuccess<any>).entity; const createKey = safeGetKey(action, createEntity); const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, entities: mergeSingle(entities, createKey, createEntity), ids: pushSingle(ids, createKey), isSaving: false, createdAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.CreateMany: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.CreateManyFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.CreateManySuccess: { const createdEntities = (action as CreateManySuccess<any>).entities; const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, entities: mergeMany(entities, createdEntities, action), ids: pushMany(ids, createdEntities, action), isSaving: false, createdAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Load: { const newState = { ...entityState, isLoading: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadFailure: { const newState = { ...entityState, isLoading: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadSuccess: { const loadEntity = (action as LoadSuccess<any>).entity; const loadKey = safeGetKey(action, loadEntity); const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, ids: pushUnique(entities, ids, loadKey), // ALERT: IDS FIRST!!! entities: mergeSingle(entities, loadKey, loadEntity), // ALERT: Then entities! isLoading: false, loadedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadMany: { const newState = { ...entityState, isLoading: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadManyFailure: { const newState = { ...entityState, isLoading: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadManySuccess: { const loadManyEntities = (action as LoadManySuccess<any>).entities; const loadedIds = loadManyEntities.map(entity => safeGetKey(action, entity)); const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, ids: pushManyUnique(entities, ids, loadedIds), // ALERT: IDS FIRST!! entities: mergeMany(entities, loadManyEntities, action), // ALERT: Then entities! isLoading: false, loadedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadAll: { const newState = { ...entityState, isLoading: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadAllFailure: { const newState = { ...entityState, isLoading: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadAllSuccess: { const loadAllEntities = (action as LoadAllSuccess<any>).entities; const loadedIds = loadAllEntities.map(entity => safeGetKey(action, entity)); const newState = { ...entityState, entities: mergeMany({}, loadAllEntities, action), ids: loadedIds, isLoading: false, loadedAt: Date.now(), currentPage: 1, totalPageableCount: loadAllEntities.length }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadPage: { const newState = { ...entityState, isLoading: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadPageFailure: { const newState = { ...entityState, isLoading: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadPageSuccess: { const loadPageEntities = (action as LoadPageSuccess<any>).entities; const loadedIds = loadPageEntities.map(entity => safeGetKey(action, entity)); const pageInfo = (action as LoadPageSuccess<any>).pageInfo; if (!pageInfo) { warnMissingPageInfo(action); } const newState = { ...entityState, entities: mergeMany({}, loadPageEntities, action), ids: loadedIds, currentPage: pageInfo.page, totalPageableCount: pageInfo.totalCount, isLoading: false, loadedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadRange: { const newState = { ...entityState, isLoading: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadRangeFailure: { const newState = { ...entityState, isLoading: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.LoadRangeSuccess: { const loadRangeEntities = (action as LoadRangeSuccess<any>).entities; const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const rangeInfo = (action as LoadRangeSuccess<any>).rangeInfo; if (!rangeInfo) { warnMissingRangeInfo(action); } const newState = { ...entityState, entities: mergeMany(entities, loadRangeEntities, action), ids: pushMany(ids, loadRangeEntities, action), currentRange: rangeInfo.range, totalPageableCount: rangeInfo.totalCount, isLoading: false, loadedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Update: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpdateFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpdateSuccess: { const updateEntity = (action as UpdateSuccess<any>).entity; const updateKey = safeGetKey(action, updateEntity); const entities = cloneEntities(entityState.entities); const newState = { ...entityState, entities: mergeSingle(entities, updateKey, updateEntity), isSaving: false, savedAt: Date.now(), updatedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpdateMany: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpdateManyFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpdateManySuccess: { const updateManyEntities = (action as UpdateManySuccess<any>).entities; const entities = cloneEntities(entityState.entities); const newState = { ...entityState, entities: mergeMany(entities, updateManyEntities, action), isSaving: false, savedAt: Date.now(), updatedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Upsert: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpsertFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpsertSuccess: { const upsertEntity = (action as UpsertSuccess<any>).entity; const upsertKey = safeGetKey(action, upsertEntity); const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, ids: combineUnique(ids, entities, [upsertEntity], action), entities: mergeSingle(entities, upsertKey, upsertEntity), isSaving: false, savedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpsertMany: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpsertManyFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.UpsertManySuccess: { const upsertManyEntities = (action as UpsertManySuccess<any>).entities; const entities = cloneEntities(entityState.entities); const ids = cloneIds(entityState.ids); const newState = { ...entityState, ids: combineUnique(ids, entities, upsertManyEntities, action), entities: mergeMany(entities, upsertManyEntities, action), isSaving: false, savedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Replace: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.ReplaceFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.ReplaceSuccess: { const replaceEntity = (action as ReplaceSuccess<any>).entity; const replaceKey = safeGetKey(action, replaceEntity); const entities = cloneEntities(entityState.entities); const newState = { ...entityState, entities: mergeSingle(entities, replaceKey, replaceEntity), isSaving: false, savedAt: Date.now(), replacedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.ReplaceMany: { const newState = { ...entityState, isSaving: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.ReplaceManyFailure: { const newState = { ...entityState, isSaving: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.ReplaceManySuccess: { const replaceManyEntities = (action as ReplaceManySuccess<any>).entities; const entities = cloneEntities(entityState.entities); const newState = { ...entityState, entities: mergeMany(entities, replaceManyEntities, action), isSaving: false, savedAt: Date.now(), replacedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Delete: { const newState = { ...entityState, isDeleting: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteFailure: { const newState = { ...entityState, isDeleting: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteSuccess: { const deleteEntity = (action as DeleteSuccess<any>).entity; const deleteKey = safeGetKey(action, deleteEntity); const entities = cloneEntities(entityState.entities); const ids = entityState.ids.filter(eid => eid !== deleteKey); // Better to NOT delete the entity key, but set it to undefined, // to avoid re-generating the underlying runtime class (TODO: find and add link to V8 jit and runtime) const newState = { ...entityState, entities: deleteSingle(entities || {}, deleteKey), ids, isDeleting: false, deletedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteMany: { const newState = { ...entityState, isDeleting: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteManyFailure: { const newState = { ...entityState, isDeleting: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteManySuccess: { const deleteManyEntities = (action as DeleteManySuccess<any>).entities; const deletedIds = deleteManyEntities.map(entity => safeGetKey(action, entity)); const clonedEntities = cloneEntities(entityState.entities); const entities = deleteMany(clonedEntities, deletedIds); const ids = entityState.ids.filter(eid => eid in entities); const newState = { ...entityState, entities, ids, isDeleting: false, deletedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteByKey: { const newState = { ...entityState, isDeleting: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteByKeyFailure: { const newState = { ...entityState, isDeleting: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteByKeySuccess: { const deleteKey = (action as DeleteByKeySuccess<any>).key; const clonedEntities = cloneEntities(entityState.entities); const entities = deleteSingle(clonedEntities || {}, deleteKey); const ids = entityState.ids.filter(eid => eid in entities); // Better to NOT delete the entity key, but set it to undefined, // to avoid re-generating the underlying runtime class (TODO: find and add link to V8 jit and runtime) const newState = { ...entityState, entities, ids, isDeleting: false, deletedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteManyByKeys: { const newState = { ...entityState, isDeleting: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteManyByKeysFailure: { const newState = { ...entityState, isDeleting: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeleteManyByKeysSuccess: { const deleteKeys = (action as DeleteManyByKeysSuccess<any>).keys; const clonedEntities = cloneEntities(entityState.entities); const entities = deleteMany(clonedEntities, deleteKeys); const ids = entityState.ids.filter(eid => eid in entities); const newState = { ...entityState, entities, ids, isDeleting: false, deletedAt: Date.now() }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Clear: { const newState = { // If the developer has included their own extra state properties with buildState(Entity, { /* custom */ }) // then we don't want to mess with it. We want to leave any custom developer state as-is! // Spread in the current state to ensure we KEEP custom developer-defined extra state properties: ...entityState, // Now reset the auto-entity managed properties to their default states: entities: {}, ids: [], currentEntityKey: undefined, currentEntitiesKeys: undefined, editedEntity: undefined, isDirty: undefined, currentPage: undefined, currentRange: undefined, totalPageableCount: undefined, isLoading: undefined, isSaving: undefined, isDeleting: undefined, loadedAt: undefined, savedAt: undefined, deletedAt: undefined }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Select: { const selectEntity = (action as Select<any>).entity; if (!selectEntity) { return state; } const selectKey = safeGetKey(action, selectEntity); const newState = { ...entityState, currentEntityKey: selectKey }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.SelectByKey: { const selectByKeyKey = (action as SelectByKey<any>).entityKey; if (!selectByKeyKey) { return state; } const newState = { ...entityState, currentEntityKey: selectByKeyKey }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.SelectMany: { const selectManyEntities = (action as SelectMany<any>).entities || []; const selectingEntities = Array.isArray(selectManyEntities) ? selectManyEntities : []; const selectManyKeys = selectingEntities.map(entity => safeGetKey(action, entity)); const newState = { ...entityState, currentEntitiesKeys: selectManyKeys }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.SelectMore: { const selectMoreEntities = (action as SelectMore<any>).entities || []; const selectingEntities = Array.isArray(selectMoreEntities) ? selectMoreEntities : []; const selectMoreKeys = selectingEntities.map(entity => safeGetKey(action, entity)); const selectMoreCurrentKeys = entityState.currentEntitiesKeys || []; const selectMoreCombinedKeys = new Set([...selectMoreCurrentKeys, ...selectMoreKeys]); const newState = { ...entityState, currentEntitiesKeys: [...selectMoreCombinedKeys] }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.SelectManyByKeys: { const selectManyByKeysKeys = (action as SelectManyByKeys<any>).entitiesKeys || []; const selectManyByKeysGuaranteedKeys = Array.isArray(selectManyByKeysKeys) ? selectManyByKeysKeys : []; const newState = { ...entityState, currentEntitiesKeys: selectManyByKeysGuaranteedKeys }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.SelectMoreByKeys: { const selectMoreByKeysKeys = (action as SelectMoreByKeys<any>).entitiesKeys || []; const selectMoreByKeysGuaranteedKeys = Array.isArray(selectMoreByKeysKeys) ? selectMoreByKeysKeys : []; const selectMoreByKeysCurrentKeys = entityState.currentEntitiesKeys || []; const selectMoreByKeysCombinedKeys = new Set([...selectMoreByKeysCurrentKeys, ...selectMoreByKeysGuaranteedKeys]); const newState = { ...entityState, currentEntitiesKeys: [...selectMoreByKeysCombinedKeys] }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Deselect: { const newState = { ...entityState, currentEntityKey: undefined }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeselectMany: { const deselectManyEntities = (action as DeselectMany<any>).entities || []; const deselectingEntities = Array.isArray(deselectManyEntities) ? deselectManyEntities : []; const deselectManyEntityKeys = deselectingEntities.map(entity => safeGetKey(action, entity)); const deselectManyCurrentKeys = entityState.currentEntitiesKeys || []; const newState = { ...entityState, currentEntitiesKeys: deselectManyCurrentKeys.filter(key => !deselectManyEntityKeys.some(k => k === key)) }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeselectManyByKeys: { const deselectManyByKeysKeys = (action as DeselectManyByKeys<any>).entitiesKeys || []; const deselectManyByKeysGuaranteedKeys = Array.isArray(deselectManyByKeysKeys) ? deselectManyByKeysKeys : []; const deselectManyByKeysCurrentKeys = entityState.currentEntitiesKeys || []; const newState = { ...entityState, currentEntitiesKeys: deselectManyByKeysCurrentKeys.filter(key => !deselectManyByKeysGuaranteedKeys.some(k => k === key)) }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.DeselectAll: { const newState = { ...entityState, currentEntitiesKeys: undefined }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.EditNew: { const editEntity = (action as EditNew<any>).entity || {}; if (!editEntity) { return state; } const newState = { ...entityState, editedEntity: { ...editEntity }, isDirty: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Edit: { const editEntity = (action as Edit<any>).entity; if (!editEntity) { return state; } const editedKey = safeGetKey(action, editEntity); const prevEditedKey = entityState.editedEntity && getKey(action, entityState.editedEntity); if (editedKey === prevEditedKey) { return state; } const newState = { ...entityState, editedEntity: { ...editEntity }, isDirty: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.EditByKey: { const editedKey = (action as EditByKey<any>).key; const prevEditedKey = entityState.editedEntity && getKey(action, entityState.editedEntity); if (!editedKey || editedKey === prevEditedKey) { return state; } const editEntity = entityState.entities[editedKey]; if (!editEntity) { return state; } const newState = { ...entityState, editedEntity: { ...editEntity }, isDirty: false }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.Change: { const changeEntity = (action as Change<any>).entity; if (!changeEntity || !entityState.editedEntity) { return state; } const newState = { ...entityState, editedEntity: { ...changeEntity }, isDirty: true }; const next = setNewState(featureName, stateName, state, newState); return next; } case EntityActionTypes.EndEdit: { if (entityState.editedEntity === undefined) { return state; } const newState = { ...entityState, editedEntity: undefined, isDirty: undefined }; const next = setNewState(featureName, stateName, state, newState); return next; } default: { return state; } } } catch (err) { if (err.message && err.message.startsWith('[NGRX-AE]')) { console.error(err.message); return state; } throw err; } }; export function autoEntityReducer(reducer: ActionReducer<any>, state, action: EntityActions<any>) { let stateName: string; let featureName: string; let entityState: any; if (Object.values(EntityActionTypes).includes(action.actionType)) { stateName = stateNameFromAction(action); featureName = featureNameFromAction(action); entityState = featureName ? state[featureName][stateName] : state[stateName]; } const nextState = reduceAutoEntityAction(state, entityState, action, stateName, featureName); return reducer(nextState || state, action); } /** * Provides standard reducer functions to support entity store structure * * @param reducer */ export function autoEntityMetaReducer(reducer: ActionReducer<any>): ActionReducer<any> { return (state, action: EntityActions<any>) => { return autoEntityReducer(reducer, state, action); }; }
the_stack
import type { Action, // BrowserHistory, // HashHistory, History, Location, LocationDescriptor, LocationDescriptorObject, MemoryHistory, // Path, // PartialPath, // State, // To, // Update, } from 'history'; import type { ComponentType } from 'react'; import type { SuspenseResource } from './utils/SuspenseResource'; // HISTORY TYPES // -------------------------------------------------- // In v5, State is `object | null`, not `undefined`. export type State = object | undefined; export type BrowserHistory<S extends State = State> = History<S>; export type HashHistory<S extends State = State> = History<S>; // In History v5 this is just called "Path". export interface HistoryPath { hash: string; pathname: string; search: string; } export type PartialPath = LocationDescriptorObject; export interface Update { action: Action; location: Location; } export type To<S extends State = State> = LocationDescriptor<S>; /** * This type takes a given path and returns a union containing the path parameters. * * The conditional case logic is as follows: * 1. First case matches parameters at the start or middle of the path (ie `':username/projects/:projectId/edit'`). * 2. Second case matches parameters at the end of the path (ie `':projectId'`). * 3. The third matches strings with some other content before a parameter and strips it away (ie `'/project/:projectId'`). * 4. The last case returns `never` if none of the three previous cases match (which causes it behave like an empty set when used in a union). * * The first and third cases are called recursively with a shorter section of the string. */ export type PathParameters<Path extends string> = Path extends `:${infer Parameter}/${infer Rest}` ? Parameter | PathParameters<Rest> : Path extends `:${infer Parameter}` ? Parameter : Path extends `${string}:${infer Rest}` ? PathParameters<`:${Rest}`> : never; /** * Given a path this type returns a object whose * keys are the path parameter names. */ export type RouteParameters<Path extends string> = { [K in PathParameters<Path>]: string; }; export type AssistedPreloadFunction = () => Promise<unknown>; export interface AssistedPreloadConfig { data: AssistedPreloadFunction; defer?: boolean; } export type AssistedPreloadData = Record< string, AssistedPreloadConfig | AssistedPreloadFunction >; export type UnassistedPreloadData = Record<string, unknown>; /** * A single route configuration object. */ export interface RouteConfig< ParentPath extends string = string, Path extends string = string, Props extends PreparedRouteEntryProps = { params: {}; search: {} }, AssistMode extends boolean = boolean > { /** * An array of child routes whose paths are relative to the parent path. */ children?: ReadonlyArray<RouteConfig<`${ParentPath}${Path}`>>; /** * The component to be rendered when the route path matches. * * This is a function that returns a promise to dynamically load the component. * * It is recommended to use dynamic import syntax (e.g. `import('./MyComponent')`) to load the component. * * @example `() => import('./MyComponent').then(m => m.default)` */ component: () => Promise<ComponentType<Props>>; /** * A string that sets the pathname which the route will be matched against. * * Children routes will prefix their paths with this pathname. */ path: Path; /** * A function that returns an object whose keys are preload entities that are * mapped to the `preloaded` prop on the rendered route component. * * Each value is a function that returns a promise to dynamically load any needed data. * * Requests are initialized concurrently and allows components to suspend. * * @example * ``` * () => ({ * data: () => fetch('https://api.example.com/data'), * }) * ``` */ preload?: ( routeParameters: RouteParameters<`${ParentPath}${Path}`>, searchParameters: Record<string, string[] | string> ) => AssistMode extends true ? AssistedPreloadData : UnassistedPreloadData; /** * A function where you can perform logic to conditionally determine * if the router should redirect the user to another route. * * This redirect logic is run before any preload logic or component render. * * The function should return the full pathname of the route to redirect to, * or `null` if no redirect should occur. * * NOTE: redirect rules apply to children routes unless overridden. */ redirectRules?: ( namedParameters: RouteParameters<`${ParentPath}${Path}`>, searchParameters: Record<string, string[] | string> ) => string | null; } export type RoutesConfig = readonly RouteConfig[]; export type RouteEntry<AssistMode extends boolean = boolean> = Omit< RouteConfig<string, string, PreparedRouteEntryProps<AssistMode>, AssistMode>, 'component' | 'path' > & { component: SuspenseResource<ComponentType<PreparedRouteEntryProps>>; }; export type RoutesEntryMap = Map<string, RouteEntry>; export interface RouterOptions<Routes extends RoutesConfig> { /** * Indicates to the router whether it should * transform preload requests into Suspense resources. * * @default false */ assistPreload?: boolean; /** * Tells the router whether or not to continue rendering a * previous route component until the new requested route * component code has fully loaded. * * @default false */ awaitComponent?: boolean; /** * Tells the router whether or not to continue rendering a * previous route component until the newly requested routes * preload data as loaded. * * @default false */ awaitPreload?: boolean; /** * A function that is called with logging information from the router. */ logger?: LoggerFunction; /** * An array of route configuration objects */ routes: Routes; } export type LoggerFunction = (details: { context?: object; level: 'debug' | 'error' | 'info' | 'trace' | 'warn'; message: string; scope: string; }) => void; export interface CreateRouterOptions<Routes extends RoutesConfig> extends RouterOptions<Routes> { history: History<State>; } export type RouterSubscriptionHistoryCallback = ( nextEntry: PreparedEntryWithAssist | PreparedEntryWithoutAssist, locationUpdate: Update ) => unknown; export type RouterSubscriptionDispose = () => void; export type RouterSubscriptionTransitionCallback = ( historyUpdate: Update ) => unknown; export interface RouterProps<S extends State = State> { /** * When true, tells the router that route preloads should be made into suspense resources. */ readonly assistPreload: boolean; /** * When true, tells the router will continue to render a previous route component * until the new route component is fully loaded and ready to use. */ readonly awaitComponent: boolean; /** * Returns the current route entry for the current history location. */ readonly get: () => PreparedEntryWithAssist | PreparedEntryWithoutAssist; /** * Returns the current matched route key. * * This is equivalent to the full canonical path pattern string. * * @example `/users/:id` */ readonly getCurrentRouteKey: () => string; readonly history: BrowserHistory<S> | HashHistory<S> | MemoryHistory<S>; /** * Returns true if the given pathname matches the current history location. * * Setting `exact` optional argument will take both * the location search query and hash into account in the comparison. */ readonly isActive: (path: PartialPath | string, exact?: boolean) => boolean; /** * The logger function that is called with logging information from the router. */ readonly logger: LoggerFunction; /** * Preloads the component code for a given route. */ readonly preloadCode: (to: To) => void; /** * This function gets called when the route entry has changed * and any assist preload data and component awaiting has finished. */ readonly routeTransitionCompleted: (historyUpdate: Update) => void; /** * Allows you to subscribe to both history changes and transition completion. * * Returns a dispose function that you can call to unsubscribe from the events. * * NOTE: Just because the history has changed, doesn't mean the new route is rendered. * In `awaitComponent` mode, the new route is rendered once the component is resolved. * Likewise, in `awaitPreload` mode, the new route is rendered once the preload data is loaded. */ readonly subscribe: (callbacks: { onTransitionComplete?: RouterSubscriptionTransitionCallback; onTransitionStart?: RouterSubscriptionHistoryCallback; }) => RouterSubscriptionDispose; /** * Preloads both the component code and data for a given route. */ readonly warmRoute: (to: To) => void; } export interface RouterContextProps<S extends State = State> extends RouterProps<S> { rendererInitialized: boolean; setRendererInitialized: (value: boolean) => void; } export interface MatchedRoute { /** * Represents the route pattern that was matched. */ key: string; location: HistoryPath; params: Record<string, string>; route: RouteEntry; search: Record<string, string[] | string>; } export interface AssistedMatchedRoute extends MatchedRoute { route: RouteEntry<true>; } export type PreloadedMap = Map< string, { data: SuspenseResource<unknown>; defer: boolean } >; export interface PreparedEntryFragment { component: SuspenseResource<ComponentType<PreparedRouteEntryProps>>; location: HistoryPath; params: Record<string, string>; search: Record<string, string[] | string>; } export interface PreparedEntryWithAssist extends PreparedEntryFragment { preloaded?: PreloadedMap; } export interface PreparedEntryWithoutAssist extends PreparedEntryFragment { preloaded?: UnassistedPreloadData; } /* eslint-disable unicorn/prevent-abbreviations */ export type AssistedPreloadedProp = Record<string, SuspenseResource<unknown>>; export type UnassistedPreloadedProp = Record<string, unknown>; /* eslint-enable unicorn/prevent-abbreviations */ export interface PreparedRouteEntryProps<AssistMode extends boolean = boolean> { params: Record<string, string>; preloaded?: AssistMode extends true ? AssistedPreloadedProp : UnassistedPreloadedProp; search: Record<string, string[] | string>; } export interface PreparedRouteEntry { component: SuspenseResource<ComponentType<PreparedRouteEntryProps>>; location: HistoryPath; props: PreparedRouteEntryProps; } /** * This is the type your route components should extend from. * * @example * ``` * import type { RouteProps } from 'yarr'; * * export interface MyRouteComponentProps extends RouteProps<'/some/path/:id'> { * preloaded: { * query: () => Promise<{ id: string }>; * }; * } * ``` */ export interface RouteProps< Path extends string, AssistMode extends boolean = false > extends PreparedRouteEntryProps<AssistMode> { params: RouteParameters<Path>; }
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, Dimensions, TouchableNativeFeedback, InteractionManager, ActivityIndicator, Animated, FlatList, Button } from 'react-native' import Values from 'values.js' import Ionicons from 'react-native-vector-icons/Ionicons' import colorConfig, { standardColor, idColor, getLevelColorFromProgress, getContentFromTrophy } from '../../constant/colorConfig' import { getGameAPI } from '../../dao' let toolbarActions = [] export default class GamePage extends Component<any, any> { constructor(props) { super(props) const { navigation } = this.props const { params } = navigation.state const { selections = [] } = params this.state = { data: false, isLoading: true, mainContent: false, rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), topicMarginTop: new Animated.Value(0), selections } } componentWillMount() { this.preFetch() } preFetch = () => { const { params } = this.props.navigation.state this.setState({ isLoading: true }) InteractionManager.runAfterInteractions(() => { getGameAPI(params.URL).then(data => { this.hasPlayer = !!data.playerInfo.psnid this.setState({ data, isLoading: false }) }) }) } handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) renderHeader = (rowData) => { const { modeInfo } = this.props.screenProps return ( <View key={rowData.id} style={{ backgroundColor: modeInfo.backgroundColor }}> <TouchableNativeFeedback onPress={() => { }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 91 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column', alignContent: 'center' }}> <View style={{ flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between' }}> <Text ellipsizeMode={'tail'} style={{ flex: -1, color: modeInfo.titleTextColor }}> {rowData.title} </Text> <Text selectable={false} style={{ flex: -1, marginLeft: 5, color: idColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.tip || rowData.platform && rowData.platform.join(' ')}</Text> </View> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{getContentFromTrophy(rowData.trophyArr.join('')).map((item, index) => { return ( <Text key={index} style={{color: colorConfig['trophyColor' + (index + 1)]}}> {item} </Text> ) })}</Text> <Text selectable={false} style={{ flex: -1, color: getLevelColorFromProgress(rowData.rare), textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{rowData.alert}</Text> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{rowData.rare}</Text> </View> </View> </View> </TouchableNativeFeedback> </View> ) } hasPlayer = false renderPlayer = (rowData) => { const { modeInfo } = this.props.screenProps return ( <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12, backgroundColor: modeInfo.backgroundColor }}> <View style={{ flex: 1 }}> <Text style={{ color: modeInfo.titleTextColor, textAlign: 'center' }}>{rowData.psnid}</Text> <Text style={{ color: modeInfo.standardTextColor, textAlign: 'center' }}>{rowData.total}</Text> </View> <View style={{ flex: 1 }}> <Text style={{ color: modeInfo.titleTextColor, textAlign: 'center' }}>{rowData.first}</Text> <Text style={{ color: modeInfo.standardTextColor, textAlign: 'center', fontSize: 12 }}>首个杯</Text> </View> <View style={{ flex: 1 }}> <Text style={{ color: modeInfo.titleTextColor, textAlign: 'center' }}>{rowData.last}</Text> <Text style={{ color: modeInfo.standardTextColor, textAlign: 'center', fontSize: 12 }}>最后杯</Text> </View> { rowData.time && (<View style={{ flex: 1 }}> <Text style={{ color: modeInfo.titleTextColor, textAlign: 'center' }}>{rowData.time}</Text> <Text style={{ color: modeInfo.standardTextColor, textAlign: 'center', fontSize: 12 }}>总耗时</Text> </View>)} </View> ) } renderToolbar = (list) => { const { modeInfo } = this.props.screenProps let screen = Dimensions.get('window') const { width: SCREEN_WIDTH } = screen return ( <View style={{ flex: 0, flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', backgroundColor: modeInfo.backgroundColor }}> {list.map((item, index) => /*['讨论', '评论'].includes(item.text) && */( <TouchableNativeFeedback key={index} onPress={() => { if (item.text === '主题') { this.props.navigation.navigate('GameTopic', { URL: `${item.url}?page=1` }) } else if (item.text === '评论') { this.props.navigation.navigate('GamePoint', { URL: `${item.url}`, rowData: { id: (item.url.match(/\/psngame\/(\d+)\/comment/) || [0, -1])[1] } }) } else if (item.text === '问答') { this.props.navigation.navigate('GameQa', { URL: `${item.url}?page=1` }) } else if (item.text === '约战') { this.props.navigation.navigate('GameBattle', { URL: `${item.url}?page=1` }) } else if (item.text === '游列') { this.props.navigation.navigate('GameList', { URL: `${item.url}?page=1` }) } else if (item.text === '排行') { this.props.navigation.navigate('GameRank', { URL: `${item.url}?page=1` }) } }}> <View pointerEvents={'box-only'} style={{ flex: 1, alignItems: 'center', justifyContent: 'center', height: 55, width: SCREEN_WIDTH / (list.length) }} key={index}> <Text style={{ color: idColor, textAlign: 'left', fontSize: 12 }}>{item.text}</Text> </View> </TouchableNativeFeedback> ) || undefined )} </View> ) } hasContent = false renderGameHeader = (rowData, index) => { const { modeInfo } = this.props.screenProps return ( <View key={rowData.id || index} style={{ backgroundColor: modeInfo.backgroundColor, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: modeInfo.brighterLevelOne, padding: 2 }}> <TouchableNativeFeedback onPress={() => { }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 91 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column', alignContent: 'center' }}> <View style={{ flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between' }}> <Text ellipsizeMode={'tail'} style={{ flex: -1, color: modeInfo.titleTextColor }}> {rowData.title} </Text> </View> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{getContentFromTrophy(rowData.trophyArr.join('')).map((item, index) => { return ( <Text key={index} style={{color: colorConfig['trophyColor' + (index + 1)]}}> {item} </Text> ) })}</Text> </View> </View> </View> </TouchableNativeFeedback> </View> ) } renderTrophy = (rowData, index) => { const { modeInfo } = this.props.screenProps const { selections } = this.state // console.log(this.props.navigation) const { callbackAfterAll } = this.props.navigation.state.params const isChecked = selections.includes(rowData.indexID) const targetColor = isChecked ? modeInfo.tintColor : (rowData.backgroundColor || modeInfo.backgroundColor) const backgroundColor = modeInfo.isNightMode ? new Values(targetColor).shade(60).hexString() : targetColor return ( <TouchableNativeFeedback key={rowData.id || index} onPress={ () => { if (callbackAfterAll) { const target = this.state.selections.includes(rowData.indexID) ? this.state.selections.filter(item => item !== rowData.indexID) : this.state.selections.slice().concat(rowData.indexID) this.setState({ selections: target }) } else { this.props.navigation.navigate('Trophy', { URL: rowData.href, title: rowData.title, rowData, type: 'trophy' }) } } }> <View key={rowData.id || index} pointerEvents={'box-only'} style={{ backgroundColor: backgroundColor, flexDirection: 'row', padding: 0 }}> <View pointerEvents='box-only' style={{ flex: -1, flexDirection: 'row', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 54, height: 54 }]} /> </View> <View style={{ justifyContent: 'space-around', flex: 3, padding: 4 }}> <Text ellipsizeMode={'tail'} style={{ flex: -1, color: modeInfo.titleTextColor }}> {rowData.title} { rowData.translate && <Text style={{ color: modeInfo.standardTextColor, marginLeft: 2 }}>{' ' + rowData.translate}</Text> } { rowData.tip && <Text style={{ color: modeInfo.standardColor , fontSize: 12, marginLeft: 2 }}>{' ' + rowData.tip}</Text> } </Text> <Text ellipsizeMode={'tail'} style={{ flex: -1, color: modeInfo.titleTextColor }}> {rowData.translateText || rowData.text} </Text> </View> { rowData.time && ( <View style={{ flex: 1, justifyContent: 'center', padding: 2 }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.okColor, textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{rowData.time}</Text> </View> ) } <View style={{ flex: 0.8, justifyContent: 'center', padding: 2 }}> <Text selectable={false} style={{ flex: -1, textAlign: 'center', textAlignVertical: 'center', color: modeInfo.titleTextColor }}>{rowData.rare}</Text> <Text ellipsizeMode={'tail'} style={{ flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center', fontSize: 10 }}>{rowData.rare ? '珍稀度' : ''}</Text> </View> </View> </TouchableNativeFeedback> ) } renderOneProfile = (rowData, index) => { const { modeInfo } = this.props.screenProps return ( <View key={index} style={{ backgroundColor: modeInfo.backgroundColor }}> { index !== 0 && <Text style={{ textAlign: 'left', color: modeInfo.standardTextColor, padding: 5, paddingLeft: 10, paddingBottom: 0, fontSize: 15}}>第{index}个DLC</Text>} <View> { index !== 0 && this.renderGameHeader(rowData.banner, index) } { rowData.list.map((item , index) => this.renderTrophy(item , index)) } </View> </View> ) } renderAllProfiles = (rowData, index) => { return ( <View key={index}> { rowData.map((item , index) => this.renderOneProfile(item, index)) } </View> ) } renderLinkHeader = (url) => { const { modeInfo } = this.props.screenProps const { navigation } = this.props const onPress = () => navigation.navigate('NewGame', { URL: url }) return ( <View style={{margin: 5, backgroundColor: modeInfo.backgroundColor}}> <Button onPress={onPress} title='关联游戏' color={modeInfo.accentColor}/> </View> ) } render() { const { params } = this.props.navigation.state // console.log('GamePage.js rendered'); const { modeInfo } = this.props.screenProps const { data: source } = this.state const data: any[] = [] const renderFuncArr: any[] = [] const shouldPushData = !this.state.isLoading if (shouldPushData) { data.push(source.gameInfo) renderFuncArr.push(this.renderHeader) if (source.gameInfo.linkGame) { data.push(`${source.gameInfo.linkGame}?page=1`) renderFuncArr.push(this.renderLinkHeader) } } if (shouldPushData && this.hasPlayer) { data.push(source.playerInfo) renderFuncArr.push(this.renderPlayer) } if (shouldPushData) { data.push(source.toolbarInfo) renderFuncArr.push(this.renderToolbar) data.push(source.trophyArr) renderFuncArr.push(this.renderAllProfiles) } const title = params.rowData.id ? `No.${params.rowData.id}` : (params.title || params.rowData.title) const targetToolbar: any = toolbarActions.slice() const { navigation } = this.props if (params.callbackAfterAll) { targetToolbar.push({ title: '确定', iconName: 'md-done-all', show: 'always', onPress: () => { const { params } = navigation.state params.callbackAfterAll && params.callbackAfterAll(this.state.selections) navigation.goBack() } }) } return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={title} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]} actions={targetToolbar} onIconClicked={() => { this.props.navigation.goBack() }} onActionSelected={(index) => targetToolbar[index].onPress()} /> {this.state.isLoading && ( <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> )} {!this.state.isLoading && <FlatList style={{ flex: -1, backgroundColor: modeInfo.backgroundColor }} ref={flatlist => this.flatlist = flatlist} data={data} keyExtractor={(item, index) => item.id || index} renderItem={({ item, index }) => { return renderFuncArr[index](item) }} extraData={this.state} windowSize={999} disableVirtualization={true} viewabilityConfig={{ minimumViewTime: 3000, viewAreaCoveragePercentThreshold: 100, waitForInteraction: true }} > </FlatList> } </View> ) } isValueChanged = false flatlist: any = false refreshControl: any = false } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor // make links coloured pink } })
the_stack
import * as Atk from '@gi-types/atk'; import * as cairo from '@gi-types/cairo'; import * as Clutter from '@gi-types/clutter'; import * as Cogl from '@gi-types/cogl'; import * as GDesktopEnums from '@gi-types/gdesktopenums'; import * as Gio from '@gi-types/gio'; import * as GLib from '@gi-types/glib'; import * as GObject from '@gi-types/gobject'; import * as Gtk from '@gi-types/gtk'; import * as Json from '@gi-types/json'; import * as Pango from '@gi-types/pango'; import * as xlib from '@gi-types/xlib'; export const CURRENT_TIME: number; export const DEFAULT_ICON_NAME: string; export const ICON_HEIGHT: number; export const ICON_WIDTH: number; export const MAJOR_VERSION: number; export const MICRO_VERSION: number; export const MINI_ICON_HEIGHT: number; export const MINI_ICON_WIDTH: number; export const MINOR_VERSION: number; export const PLUGIN_API_VERSION: number; export const PRIORITY_BEFORE_REDRAW: number; export const PRIORITY_PREFS_NOTIFY: number; export const PRIORITY_REDRAW: number; export const PRIORITY_RESIZE: number; export const VIRTUAL_CORE_KEYBOARD_ID: number; export const VIRTUAL_CORE_POINTER_ID: number; export function activate_session(): boolean; export function add_clutter_debug_flags( debug_flags: Clutter.DebugFlag, draw_flags: Clutter.DrawDebugFlag, pick_flags: Clutter.PickDebugFlag ): void; export function add_debug_paint_flag(flag: DebugPaintFlag): void; export function add_verbose_topic(topic: DebugTopic): void; export function clutter_init(): void; export function disable_unredirect_for_display(display: Display): void; export function enable_unredirect_for_display(display: Display): void; export function exit(code: ExitCode): void; export function external_binding_name_for_action( keybinding_action: number ): string; export function focus_stage_window(display: Display, timestamp: number): void; export function frame_type_to_string(type: FrameType): string; export function g_utf8_strndup(src: string, n: number): string; export function get_backend(): Backend; export function get_debug_paint_flags(): DebugPaintFlag; export function get_feedback_group_for_display(display: Display): Clutter.Actor; export function get_locale_direction(): LocaleDirection; export function get_replace_current_wm(): boolean; export function get_stage_for_display(display: Display): Clutter.Actor; export function get_top_window_group_for_display( display: Display ): Clutter.Actor; export function get_window_actors(display: Display): Clutter.Actor[]; export function get_window_group_for_display(display: Display): Clutter.Actor; export function gravity_to_string(gravity: Gravity): string; export function is_debugging(): boolean; export function is_restart(): boolean; export function is_syncing(): boolean; export function is_verbose(): boolean; export function is_wayland_compositor(): boolean; export function keybindings_set_custom_handler( name: string, handler?: KeyHandlerFunc | null ): boolean; export function later_add(when: LaterType, func: GLib.SourceFunc): number; export function later_remove(later_id: number): void; export function pop_no_msg_prefix(): void; export function preference_to_string(pref: Preference): string; export function prefs_bell_is_audible(): boolean; export function prefs_change_workspace_name(i: number, name: string): void; export function prefs_get_action_double_click_titlebar(): GDesktopEnums.TitlebarAction; export function prefs_get_action_middle_click_titlebar(): GDesktopEnums.TitlebarAction; export function prefs_get_action_right_click_titlebar(): GDesktopEnums.TitlebarAction; export function prefs_get_attach_modal_dialogs(): boolean; export function prefs_get_auto_maximize(): boolean; export function prefs_get_auto_raise(): boolean; export function prefs_get_auto_raise_delay(): number; export function prefs_get_button_layout(): ButtonLayout; export function prefs_get_center_new_windows(): boolean; export function prefs_get_check_alive_timeout(): number; export function prefs_get_compositing_manager(): boolean; export function prefs_get_cursor_size(): number; export function prefs_get_cursor_theme(): string; export function prefs_get_disable_workarounds(): boolean; export function prefs_get_drag_threshold(): number; export function prefs_get_draggable_border_width(): number; export function prefs_get_dynamic_workspaces(): boolean; export function prefs_get_edge_tiling(): boolean; export function prefs_get_focus_change_on_pointer_rest(): boolean; export function prefs_get_focus_mode(): GDesktopEnums.FocusMode; export function prefs_get_focus_new_windows(): GDesktopEnums.FocusNewWindows; export function prefs_get_force_fullscreen(): boolean; export function prefs_get_gnome_accessibility(): boolean; export function prefs_get_gnome_animations(): boolean; export function prefs_get_keybinding_action(name: string): KeyBindingAction; export function prefs_get_mouse_button_menu(): number; export function prefs_get_mouse_button_mods(): VirtualModifier; export function prefs_get_mouse_button_resize(): number; export function prefs_get_num_workspaces(): number; export function prefs_get_raise_on_click(): boolean; export function prefs_get_show_fallback_app_menu(): boolean; export function prefs_get_titlebar_font(): Pango.FontDescription; export function prefs_get_visual_bell(): boolean; export function prefs_get_visual_bell_type(): GDesktopEnums.VisualBellType; export function prefs_get_workspace_name(i: number): string; export function prefs_get_workspaces_only_on_primary(): boolean; export function prefs_init(): void; export function prefs_set_force_fullscreen(whether: boolean): void; export function prefs_set_num_workspaces(n_workspaces: number): void; export function prefs_set_show_fallback_app_menu(whether: boolean): void; export function push_no_msg_prefix(): void; export function quit(code: ExitCode): void; export function rect( x: number, y: number, width: number, height: number ): Rectangle; export function register_with_session(): void; export function remove_clutter_debug_flags( debug_flags: Clutter.DebugFlag, draw_flags: Clutter.DrawDebugFlag, pick_flags: Clutter.PickDebugFlag ): void; export function remove_debug_paint_flag(flag: DebugPaintFlag): void; export function remove_verbose_topic(topic: DebugTopic): void; export function restart(message?: string | null): void; export function test_init(): void; export function unsigned_long_equal(v1?: any | null, v2?: any | null): number; export function unsigned_long_hash(v?: any | null): number; export function x11_error_trap_pop(x11_display: X11Display): void; export function x11_error_trap_pop_with_return(x11_display: X11Display): number; export function x11_error_trap_push(x11_display: X11Display): void; export function x11_init_gdk_display(): boolean; export type IdleMonitorWatchFunc = ( monitor: IdleMonitor, watch_id: number ) => void; export type KeyHandlerFunc = ( display: Display, window: Window, event: any | null, binding: KeyBinding ) => void; export type PrefsChangedFunc = (pref: Preference) => void; export type WindowForeachFunc = (window: Window) => boolean; export namespace ButtonFunction { export const $gtype: GObject.GType<ButtonFunction>; } export enum ButtonFunction { MENU = 0, MINIMIZE = 1, MAXIMIZE = 2, CLOSE = 3, LAST = 4, } export namespace CloseDialogResponse { export const $gtype: GObject.GType<CloseDialogResponse>; } export enum CloseDialogResponse { WAIT = 0, FORCE_CLOSE = 1, } export namespace CompEffect { export const $gtype: GObject.GType<CompEffect>; } export enum CompEffect { CREATE = 0, UNMINIMIZE = 1, DESTROY = 2, MINIMIZE = 3, NONE = 4, } export namespace Cursor { export const $gtype: GObject.GType<Cursor>; } export enum Cursor { NONE = 0, DEFAULT = 1, NORTH_RESIZE = 2, SOUTH_RESIZE = 3, WEST_RESIZE = 4, EAST_RESIZE = 5, SE_RESIZE = 6, SW_RESIZE = 7, NE_RESIZE = 8, NW_RESIZE = 9, MOVE_OR_RESIZE_WINDOW = 10, BUSY = 11, DND_IN_DRAG = 12, DND_MOVE = 13, DND_COPY = 14, DND_UNSUPPORTED_TARGET = 15, POINTING_HAND = 16, CROSSHAIR = 17, IBEAM = 18, BLANK = 19, LAST = 20, } export namespace DisplayCorner { export const $gtype: GObject.GType<DisplayCorner>; } export enum DisplayCorner { TOPLEFT = 0, TOPRIGHT = 1, BOTTOMLEFT = 2, BOTTOMRIGHT = 3, } export namespace DisplayDirection { export const $gtype: GObject.GType<DisplayDirection>; } export enum DisplayDirection { UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, } export namespace EdgeType { export const $gtype: GObject.GType<EdgeType>; } export enum EdgeType { WINDOW = 0, MONITOR = 1, SCREEN = 2, } export namespace ExitCode { export const $gtype: GObject.GType<ExitCode>; } export enum ExitCode { SUCCESS = 0, ERROR = 1, } export namespace FrameType { export const $gtype: GObject.GType<FrameType>; } export enum FrameType { NORMAL = 0, DIALOG = 1, MODAL_DIALOG = 2, UTILITY = 3, MENU = 4, BORDER = 5, ATTACHED = 6, LAST = 7, } export namespace GrabOp { export const $gtype: GObject.GType<GrabOp>; } export enum GrabOp { NONE = 0, WINDOW_BASE = 1, COMPOSITOR = 2, WAYLAND_POPUP = 3, FRAME_BUTTON = 4, MOVING = 1, RESIZING_NW = 36865, RESIZING_N = 32769, RESIZING_NE = 40961, RESIZING_E = 8193, RESIZING_SW = 20481, RESIZING_S = 16385, RESIZING_SE = 24577, RESIZING_W = 4097, KEYBOARD_MOVING = 257, KEYBOARD_RESIZING_UNKNOWN = 769, KEYBOARD_RESIZING_NW = 37121, KEYBOARD_RESIZING_N = 33025, KEYBOARD_RESIZING_NE = 41217, KEYBOARD_RESIZING_E = 8449, KEYBOARD_RESIZING_SW = 20737, KEYBOARD_RESIZING_S = 16641, KEYBOARD_RESIZING_SE = 24833, KEYBOARD_RESIZING_W = 4353, } export namespace Gravity { export const $gtype: GObject.GType<Gravity>; } export enum Gravity { NONE = 0, NORTH_WEST = 1, NORTH = 2, NORTH_EAST = 3, WEST = 4, CENTER = 5, EAST = 6, SOUTH_WEST = 7, SOUTH = 8, SOUTH_EAST = 9, STATIC = 10, } export namespace InhibitShortcutsDialogResponse { export const $gtype: GObject.GType<InhibitShortcutsDialogResponse>; } export enum InhibitShortcutsDialogResponse { ALLOW = 0, DENY = 1, } export namespace KeyBindingAction { export const $gtype: GObject.GType<KeyBindingAction>; } export enum KeyBindingAction { NONE = 0, WORKSPACE_1 = 1, WORKSPACE_2 = 2, WORKSPACE_3 = 3, WORKSPACE_4 = 4, WORKSPACE_5 = 5, WORKSPACE_6 = 6, WORKSPACE_7 = 7, WORKSPACE_8 = 8, WORKSPACE_9 = 9, WORKSPACE_10 = 10, WORKSPACE_11 = 11, WORKSPACE_12 = 12, WORKSPACE_LEFT = 13, WORKSPACE_RIGHT = 14, WORKSPACE_UP = 15, WORKSPACE_DOWN = 16, WORKSPACE_LAST = 17, SWITCH_APPLICATIONS = 18, SWITCH_APPLICATIONS_BACKWARD = 19, SWITCH_GROUP = 20, SWITCH_GROUP_BACKWARD = 21, SWITCH_WINDOWS = 22, SWITCH_WINDOWS_BACKWARD = 23, SWITCH_PANELS = 24, SWITCH_PANELS_BACKWARD = 25, CYCLE_GROUP = 26, CYCLE_GROUP_BACKWARD = 27, CYCLE_WINDOWS = 28, CYCLE_WINDOWS_BACKWARD = 29, CYCLE_PANELS = 30, CYCLE_PANELS_BACKWARD = 31, SHOW_DESKTOP = 32, PANEL_MAIN_MENU = 33, PANEL_RUN_DIALOG = 34, TOGGLE_RECORDING = 35, SET_SPEW_MARK = 36, ACTIVATE_WINDOW_MENU = 37, TOGGLE_FULLSCREEN = 38, TOGGLE_MAXIMIZED = 39, TOGGLE_TILED_LEFT = 40, TOGGLE_TILED_RIGHT = 41, TOGGLE_ABOVE = 42, MAXIMIZE = 43, UNMAXIMIZE = 44, TOGGLE_SHADED = 45, MINIMIZE = 46, CLOSE = 47, BEGIN_MOVE = 48, BEGIN_RESIZE = 49, TOGGLE_ON_ALL_WORKSPACES = 50, MOVE_TO_WORKSPACE_1 = 51, MOVE_TO_WORKSPACE_2 = 52, MOVE_TO_WORKSPACE_3 = 53, MOVE_TO_WORKSPACE_4 = 54, MOVE_TO_WORKSPACE_5 = 55, MOVE_TO_WORKSPACE_6 = 56, MOVE_TO_WORKSPACE_7 = 57, MOVE_TO_WORKSPACE_8 = 58, MOVE_TO_WORKSPACE_9 = 59, MOVE_TO_WORKSPACE_10 = 60, MOVE_TO_WORKSPACE_11 = 61, MOVE_TO_WORKSPACE_12 = 62, MOVE_TO_WORKSPACE_LEFT = 63, MOVE_TO_WORKSPACE_RIGHT = 64, MOVE_TO_WORKSPACE_UP = 65, MOVE_TO_WORKSPACE_DOWN = 66, MOVE_TO_WORKSPACE_LAST = 67, MOVE_TO_MONITOR_LEFT = 68, MOVE_TO_MONITOR_RIGHT = 69, MOVE_TO_MONITOR_UP = 70, MOVE_TO_MONITOR_DOWN = 71, RAISE_OR_LOWER = 72, RAISE = 73, LOWER = 74, MAXIMIZE_VERTICALLY = 75, MAXIMIZE_HORIZONTALLY = 76, MOVE_TO_CORNER_NW = 77, MOVE_TO_CORNER_NE = 78, MOVE_TO_CORNER_SW = 79, MOVE_TO_CORNER_SE = 80, MOVE_TO_SIDE_N = 81, MOVE_TO_SIDE_S = 82, MOVE_TO_SIDE_E = 83, MOVE_TO_SIDE_W = 84, MOVE_TO_CENTER = 85, OVERLAY_KEY = 86, LOCATE_POINTER_KEY = 87, ISO_NEXT_GROUP = 88, ALWAYS_ON_TOP = 89, SWITCH_MONITOR = 90, ROTATE_MONITOR = 91, LAST = 92, } export namespace LaterType { export const $gtype: GObject.GType<LaterType>; } export enum LaterType { RESIZE = 0, CALC_SHOWING = 1, CHECK_FULLSCREEN = 2, SYNC_STACK = 3, BEFORE_REDRAW = 4, IDLE = 5, } export namespace LocaleDirection { export const $gtype: GObject.GType<LocaleDirection>; } export enum LocaleDirection { LTR = 0, RTL = 1, } export namespace MonitorSwitchConfigType { export const $gtype: GObject.GType<MonitorSwitchConfigType>; } export enum MonitorSwitchConfigType { ALL_MIRROR = 0, ALL_LINEAR = 1, EXTERNAL = 2, BUILTIN = 3, UNKNOWN = 4, } export namespace MotionDirection { export const $gtype: GObject.GType<MotionDirection>; } export enum MotionDirection { UP = -1, DOWN = -2, LEFT = -3, RIGHT = -4, UP_LEFT = -5, UP_RIGHT = -6, DOWN_LEFT = -7, DOWN_RIGHT = -8, } export namespace PadActionType { export const $gtype: GObject.GType<PadActionType>; } export enum PadActionType { BUTTON = 0, RING = 1, STRIP = 2, } export namespace Preference { export const $gtype: GObject.GType<Preference>; } export enum Preference { MOUSE_BUTTON_MODS = 0, FOCUS_MODE = 1, FOCUS_NEW_WINDOWS = 2, ATTACH_MODAL_DIALOGS = 3, RAISE_ON_CLICK = 4, ACTION_DOUBLE_CLICK_TITLEBAR = 5, ACTION_MIDDLE_CLICK_TITLEBAR = 6, ACTION_RIGHT_CLICK_TITLEBAR = 7, AUTO_RAISE = 8, AUTO_RAISE_DELAY = 9, FOCUS_CHANGE_ON_POINTER_REST = 10, TITLEBAR_FONT = 11, NUM_WORKSPACES = 12, DYNAMIC_WORKSPACES = 13, KEYBINDINGS = 14, DISABLE_WORKAROUNDS = 15, BUTTON_LAYOUT = 16, WORKSPACE_NAMES = 17, VISUAL_BELL = 18, AUDIBLE_BELL = 19, VISUAL_BELL_TYPE = 20, GNOME_ACCESSIBILITY = 21, GNOME_ANIMATIONS = 22, CURSOR_THEME = 23, CURSOR_SIZE = 24, RESIZE_WITH_RIGHT_BUTTON = 25, EDGE_TILING = 26, FORCE_FULLSCREEN = 27, WORKSPACES_ONLY_ON_PRIMARY = 28, DRAGGABLE_BORDER_WIDTH = 29, AUTO_MAXIMIZE = 30, CENTER_NEW_WINDOWS = 31, DRAG_THRESHOLD = 32, LOCATE_POINTER = 33, CHECK_ALIVE_TIMEOUT = 34, } export namespace SelectionType { export const $gtype: GObject.GType<SelectionType>; } export enum SelectionType { SELECTION_PRIMARY = 0, SELECTION_CLIPBOARD = 1, SELECTION_DND = 2, N_SELECTION_TYPES = 3, } export namespace ShadowMode { export const $gtype: GObject.GType<ShadowMode>; } export enum ShadowMode { AUTO = 0, FORCED_OFF = 1, FORCED_ON = 2, } export namespace Side { export const $gtype: GObject.GType<Side>; } export enum Side { LEFT = 1, RIGHT = 2, TOP = 4, BOTTOM = 8, } export namespace SizeChange { export const $gtype: GObject.GType<SizeChange>; } export enum SizeChange { MAXIMIZE = 0, UNMAXIMIZE = 1, FULLSCREEN = 2, UNFULLSCREEN = 3, } export namespace StackLayer { export const $gtype: GObject.GType<StackLayer>; } export enum StackLayer { DESKTOP = 0, BOTTOM = 1, NORMAL = 2, TOP = 4, DOCK = 4, OVERRIDE_REDIRECT = 7, LAST = 8, } export namespace TabList { export const $gtype: GObject.GType<TabList>; } export enum TabList { NORMAL = 0, DOCKS = 1, GROUP = 2, NORMAL_ALL = 3, } export namespace TabShowType { export const $gtype: GObject.GType<TabShowType>; } export enum TabShowType { ICON = 0, INSTANTLY = 1, } export namespace WindowClientType { export const $gtype: GObject.GType<WindowClientType>; } export enum WindowClientType { WAYLAND = 0, X11 = 1, } export namespace WindowMenuType { export const $gtype: GObject.GType<WindowMenuType>; } export enum WindowMenuType { WM = 0, APP = 1, } export namespace WindowType { export const $gtype: GObject.GType<WindowType>; } export enum WindowType { NORMAL = 0, DESKTOP = 1, DOCK = 2, DIALOG = 3, MODAL_DIALOG = 4, TOOLBAR = 5, MENU = 6, UTILITY = 7, SPLASHSCREEN = 8, DROPDOWN_MENU = 9, POPUP_MENU = 10, TOOLTIP = 11, NOTIFICATION = 12, COMBO = 13, DND = 14, OVERRIDE_OTHER = 15, } export namespace BarrierDirection { export const $gtype: GObject.GType<BarrierDirection>; } export enum BarrierDirection { POSITIVE_X = 1, POSITIVE_Y = 2, NEGATIVE_X = 4, NEGATIVE_Y = 8, } export namespace DebugPaintFlag { export const $gtype: GObject.GType<DebugPaintFlag>; } export enum DebugPaintFlag { NONE = 0, OPAQUE_REGION = 1, } export namespace DebugTopic { export const $gtype: GObject.GType<DebugTopic>; } export enum DebugTopic { VERBOSE = -1, FOCUS = 1, WORKAREA = 2, STACK = 4, THEMES = 8, SM = 16, EVENTS = 32, WINDOW_STATE = 64, WINDOW_OPS = 128, GEOMETRY = 256, PLACEMENT = 512, PING = 1024, XINERAMA = 2048, KEYBINDINGS = 4096, SYNC = 8192, ERRORS = 16384, STARTUP = 32768, PREFS = 65536, GROUPS = 131072, RESIZING = 262144, SHAPES = 524288, COMPOSITOR = 1048576, EDGE_RESISTANCE = 2097152, DBUS = 4194304, INPUT = 8388608, } export namespace Direction { export const $gtype: GObject.GType<Direction>; } export enum Direction { LEFT = 1, RIGHT = 2, TOP = 4, BOTTOM = 8, UP = 4, DOWN = 8, HORIZONTAL = 3, VERTICAL = 12, } export namespace FrameFlags { export const $gtype: GObject.GType<FrameFlags>; } export enum FrameFlags { ALLOWS_DELETE = 1, ALLOWS_MENU = 2, ALLOWS_MINIMIZE = 4, ALLOWS_MAXIMIZE = 8, ALLOWS_VERTICAL_RESIZE = 16, ALLOWS_HORIZONTAL_RESIZE = 32, HAS_FOCUS = 64, SHADED = 128, STUCK = 256, MAXIMIZED = 512, ALLOWS_SHADE = 1024, ALLOWS_MOVE = 2048, FULLSCREEN = 4096, ABOVE = 8192, TILED_LEFT = 16384, TILED_RIGHT = 32768, } export namespace KeyBindingFlags { export const $gtype: GObject.GType<KeyBindingFlags>; } export enum KeyBindingFlags { NONE = 0, PER_WINDOW = 1, BUILTIN = 2, IS_REVERSED = 4, NON_MASKABLE = 8, IGNORE_AUTOREPEAT = 16, NO_AUTO_GRAB = 32, } export namespace MaximizeFlags { export const $gtype: GObject.GType<MaximizeFlags>; } export enum MaximizeFlags { HORIZONTAL = 1, VERTICAL = 2, BOTH = 3, } export namespace ModalOptions { export const $gtype: GObject.GType<ModalOptions>; } export enum ModalOptions { POINTER_ALREADY_GRABBED = 1, KEYBOARD_ALREADY_GRABBED = 2, } export namespace VirtualModifier { export const $gtype: GObject.GType<VirtualModifier>; } export enum VirtualModifier { SHIFT_MASK = 32, CONTROL_MASK = 64, ALT_MASK = 128, META_MASK = 256, SUPER_MASK = 512, HYPER_MASK = 1024, MOD2_MASK = 2048, MOD3_MASK = 4096, MOD4_MASK = 8192, MOD5_MASK = 16384, } export namespace Backend { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class Backend extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<Backend>; constructor( properties?: Partial<Backend.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Backend.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'gpu-added', callback: (_source: this, gpu: unknown) => void ): number; connect_after( signal: 'gpu-added', callback: (_source: this, gpu: unknown) => void ): number; emit(signal: 'gpu-added', gpu: unknown): void; connect( signal: 'keymap-changed', callback: (_source: this) => void ): number; connect_after( signal: 'keymap-changed', callback: (_source: this) => void ): number; emit(signal: 'keymap-changed'): void; connect( signal: 'keymap-layout-group-changed', callback: (_source: this, object: number) => void ): number; connect_after( signal: 'keymap-layout-group-changed', callback: (_source: this, object: number) => void ): number; emit(signal: 'keymap-layout-group-changed', object: number): void; connect( signal: 'last-device-changed', callback: (_source: this, object: Clutter.InputDevice) => void ): number; connect_after( signal: 'last-device-changed', callback: (_source: this, object: Clutter.InputDevice) => void ): number; emit(signal: 'last-device-changed', object: Clutter.InputDevice): void; connect( signal: 'lid-is-closed-changed', callback: (_source: this, object: boolean) => void ): number; connect_after( signal: 'lid-is-closed-changed', callback: (_source: this, object: boolean) => void ): number; emit(signal: 'lid-is-closed-changed', object: boolean): void; // Members get_dnd(): Dnd; get_remote_access_controller(): RemoteAccessController; get_stage(): Clutter.Actor; is_rendering_hardware_accelerated(): boolean; lock_layout_group(idx: number): void; set_keymap(layouts: string, variants: string, options: string): void; set_numlock(numlock_state: boolean): void; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export namespace Background { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; meta_display: Display; metaDisplay: Display; } } export class Background extends GObject.Object { static $gtype: GObject.GType<Background>; constructor( properties?: Partial<Background.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Background.ConstructorProperties>, ...args: any[] ): void; // Properties meta_display: Display; metaDisplay: Display; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; // Constructors static ['new'](display: Display): Background; // Members set_blend( file1: Gio.File, file2: Gio.File, blend_factor: number, style: GDesktopEnums.BackgroundStyle ): void; set_color(color: Clutter.Color): void; set_file(file: Gio.File | null, style: GDesktopEnums.BackgroundStyle): void; set_gradient( shading_direction: GDesktopEnums.BackgroundShading, color: Clutter.Color, second_color: Clutter.Color ): void; static refresh_all(): void; } export namespace BackgroundActor { export interface ConstructorProperties< A extends Clutter.Actor = Clutter.Actor > extends Clutter.Actor.ConstructorProperties { [key: string]: any; meta_display: Display; metaDisplay: Display; monitor: number; } } export class BackgroundActor<A extends Clutter.Actor = Clutter.Actor> extends Clutter.Actor implements Atk.ImplementorIface, Clutter.Animatable, Clutter.Container<A>, Clutter.Scriptable { static $gtype: GObject.GType<BackgroundActor>; constructor( properties?: Partial<BackgroundActor.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<BackgroundActor.ConstructorProperties<A>>, ...args: any[] ): void; // Properties meta_display: Display; metaDisplay: Display; monitor: number; // Constructors static ['new'](display: Display, monitor: number): BackgroundActor; static ['new'](...args: never[]): never; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Clutter.Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Clutter.Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): Clutter.ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): Clutter.ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Clutter.Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property( script: Clutter.Script, name: string, value: any ): void; vfunc_set_id(id_: string): void; } export namespace BackgroundContent { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; background: Background; brightness: number; gradient: boolean; gradient_height: number; gradientHeight: number; gradient_max_darkness: number; gradientMaxDarkness: number; meta_display: Display; metaDisplay: Display; monitor: number; vignette: boolean; vignette_sharpness: number; vignetteSharpness: number; } } export class BackgroundContent extends GObject.Object implements Clutter.Content { static $gtype: GObject.GType<BackgroundContent>; constructor( properties?: Partial<BackgroundContent.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BackgroundContent.ConstructorProperties>, ...args: any[] ): void; // Properties background: Background; brightness: number; gradient: boolean; gradient_height: number; gradientHeight: number; gradient_max_darkness: number; gradientMaxDarkness: number; meta_display: Display; metaDisplay: Display; monitor: number; vignette: boolean; vignette_sharpness: number; vignetteSharpness: number; // Members set_background(background: Background): void; set_gradient(enabled: boolean, height: number, tone_start: number): void; set_vignette(enabled: boolean, brightness: number, sharpness: number): void; static new(display: Display, monitor: number): Clutter.Content; // Implemented Members get_preferred_size(): [boolean, number, number]; invalidate(): void; invalidate_size(): void; vfunc_attached(actor: Clutter.Actor): void; vfunc_detached(actor: Clutter.Actor): void; vfunc_get_preferred_size(): [boolean, number, number]; vfunc_invalidate(): void; vfunc_invalidate_size(): void; vfunc_paint_content( actor: Clutter.Actor, node: Clutter.PaintNode, paint_context: Clutter.PaintContext ): void; } export namespace BackgroundGroup { export interface ConstructorProperties< A extends Clutter.Actor = Clutter.Actor > extends Clutter.Actor.ConstructorProperties { [key: string]: any; } } export class BackgroundGroup<A extends Clutter.Actor = Clutter.Actor> extends Clutter.Actor implements Atk.ImplementorIface, Clutter.Animatable, Clutter.Container<A>, Clutter.Scriptable { static $gtype: GObject.GType<BackgroundGroup>; constructor( properties?: Partial<BackgroundGroup.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<BackgroundGroup.ConstructorProperties<A>>, ...args: any[] ): void; // Constructors static ['new'](): BackgroundGroup; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Clutter.Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Clutter.Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): Clutter.ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): Clutter.ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Clutter.Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property( script: Clutter.Script, name: string, value: any ): void; vfunc_set_id(id_: string): void; } export namespace BackgroundImage { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class BackgroundImage extends GObject.Object { static $gtype: GObject.GType<BackgroundImage>; constructor( properties?: Partial<BackgroundImage.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BackgroundImage.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'loaded', callback: (_source: this) => void): number; connect_after(signal: 'loaded', callback: (_source: this) => void): number; emit(signal: 'loaded'): void; // Members get_success(): boolean; get_texture(): Cogl.Texture; is_loaded(): boolean; } export namespace BackgroundImageCache { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class BackgroundImageCache extends GObject.Object { static $gtype: GObject.GType<BackgroundImageCache>; constructor( properties?: Partial<BackgroundImageCache.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<BackgroundImageCache.ConstructorProperties>, ...args: any[] ): void; // Members load(file: Gio.File): BackgroundImage; purge(file: Gio.File): void; static get_default(): BackgroundImageCache; } export namespace Barrier { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; directions: BarrierDirection; display: Display; x1: number; x2: number; y1: number; y2: number; } } export class Barrier extends GObject.Object { static $gtype: GObject.GType<Barrier>; constructor( properties?: Partial<Barrier.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Barrier.ConstructorProperties>, ...args: any[] ): void; // Properties directions: BarrierDirection; display: Display; x1: number; x2: number; y1: number; y2: number; // Fields priv: BarrierPrivate; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'hit', callback: (_source: this, event: BarrierEvent) => void ): number; connect_after( signal: 'hit', callback: (_source: this, event: BarrierEvent) => void ): number; emit(signal: 'hit', event: BarrierEvent): void; connect( signal: 'left', callback: (_source: this, event: BarrierEvent) => void ): number; connect_after( signal: 'left', callback: (_source: this, event: BarrierEvent) => void ): number; emit(signal: 'left', event: BarrierEvent): void; // Members destroy(): void; is_active(): boolean; release(event: BarrierEvent): void; } export namespace CursorTracker { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: Backend; } } export class CursorTracker extends GObject.Object { static $gtype: GObject.GType<CursorTracker>; constructor( properties?: Partial<CursorTracker.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<CursorTracker.ConstructorProperties>, ...args: any[] ): void; // Properties backend: Backend; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'cursor-changed', callback: (_source: this) => void ): number; connect_after( signal: 'cursor-changed', callback: (_source: this) => void ): number; emit(signal: 'cursor-changed'): void; connect( signal: 'cursor-moved', callback: (_source: this, x: number, y: number) => void ): number; connect_after( signal: 'cursor-moved', callback: (_source: this, x: number, y: number) => void ): number; emit(signal: 'cursor-moved', x: number, y: number): void; connect( signal: 'visibility-changed', callback: (_source: this) => void ): number; connect_after( signal: 'visibility-changed', callback: (_source: this) => void ): number; emit(signal: 'visibility-changed'): void; // Members get_hot(): [number, number]; get_pointer(x: number, y: number, mods: Clutter.ModifierType): void; get_pointer_visible(): boolean; get_sprite(): Cogl.Texture; set_pointer_visible(visible: boolean): void; static get_for_display(display: Display): CursorTracker; } export namespace Display { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; focus_window: Window; focusWindow: Window; } } export class Display extends GObject.Object { static $gtype: GObject.GType<Display>; constructor( properties?: Partial<Display.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Display.ConstructorProperties>, ...args: any[] ): void; // Properties focus_window: Window; focusWindow: Window; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'accelerator-activated', callback: ( _source: this, object: number, p0: Clutter.InputDevice, p1: number ) => void ): number; connect_after( signal: 'accelerator-activated', callback: ( _source: this, object: number, p0: Clutter.InputDevice, p1: number ) => void ): number; emit( signal: 'accelerator-activated', object: number, p0: Clutter.InputDevice, p1: number ): void; connect(signal: 'closing', callback: (_source: this) => void): number; connect_after(signal: 'closing', callback: (_source: this) => void): number; emit(signal: 'closing'): void; connect( signal: 'cursor-updated', callback: (_source: this) => void ): number; connect_after( signal: 'cursor-updated', callback: (_source: this) => void ): number; emit(signal: 'cursor-updated'): void; connect( signal: 'gl-video-memory-purged', callback: (_source: this) => void ): number; connect_after( signal: 'gl-video-memory-purged', callback: (_source: this) => void ): number; emit(signal: 'gl-video-memory-purged'): void; connect( signal: 'grab-op-begin', callback: ( _source: this, object: Display, p0: Window, p1: GrabOp ) => void ): number; connect_after( signal: 'grab-op-begin', callback: ( _source: this, object: Display, p0: Window, p1: GrabOp ) => void ): number; emit( signal: 'grab-op-begin', object: Display, p0: Window, p1: GrabOp ): void; connect( signal: 'grab-op-end', callback: ( _source: this, object: Display, p0: Window, p1: GrabOp ) => void ): number; connect_after( signal: 'grab-op-end', callback: ( _source: this, object: Display, p0: Window, p1: GrabOp ) => void ): number; emit(signal: 'grab-op-end', object: Display, p0: Window, p1: GrabOp): void; connect( signal: 'in-fullscreen-changed', callback: (_source: this) => void ): number; connect_after( signal: 'in-fullscreen-changed', callback: (_source: this) => void ): number; emit(signal: 'in-fullscreen-changed'): void; connect( signal: 'init-xserver', callback: (_source: this, object: Gio.Task) => boolean ): number; connect_after( signal: 'init-xserver', callback: (_source: this, object: Gio.Task) => boolean ): number; emit(signal: 'init-xserver', object: Gio.Task): void; connect( signal: 'modifiers-accelerator-activated', callback: (_source: this) => boolean ): number; connect_after( signal: 'modifiers-accelerator-activated', callback: (_source: this) => boolean ): number; emit(signal: 'modifiers-accelerator-activated'): void; connect(signal: 'overlay-key', callback: (_source: this) => void): number; connect_after( signal: 'overlay-key', callback: (_source: this) => void ): number; emit(signal: 'overlay-key'): void; connect( signal: 'pad-mode-switch', callback: ( _source: this, object: Clutter.InputDevice, p0: number, p1: number ) => void ): number; connect_after( signal: 'pad-mode-switch', callback: ( _source: this, object: Clutter.InputDevice, p0: number, p1: number ) => void ): number; emit( signal: 'pad-mode-switch', object: Clutter.InputDevice, p0: number, p1: number ): void; connect(signal: 'restacked', callback: (_source: this) => void): number; connect_after( signal: 'restacked', callback: (_source: this) => void ): number; emit(signal: 'restacked'): void; connect(signal: 'restart', callback: (_source: this) => boolean): number; connect_after( signal: 'restart', callback: (_source: this) => boolean ): number; emit(signal: 'restart'): void; connect( signal: 'show-osd', callback: ( _source: this, object: number, p0: string, p1: string ) => void ): number; connect_after( signal: 'show-osd', callback: ( _source: this, object: number, p0: string, p1: string ) => void ): number; emit(signal: 'show-osd', object: number, p0: string, p1: string): void; connect( signal: 'show-pad-osd', callback: ( _source: this, pad: Clutter.InputDevice, settings: Gio.Settings, layout_path: string, edition_mode: boolean, monitor_idx: number ) => Clutter.Actor | null ): number; connect_after( signal: 'show-pad-osd', callback: ( _source: this, pad: Clutter.InputDevice, settings: Gio.Settings, layout_path: string, edition_mode: boolean, monitor_idx: number ) => Clutter.Actor | null ): number; emit( signal: 'show-pad-osd', pad: Clutter.InputDevice, settings: Gio.Settings, layout_path: string, edition_mode: boolean, monitor_idx: number ): void; connect( signal: 'show-resize-popup', callback: ( _source: this, object: boolean, p0: Rectangle, p1: number, p2: number ) => boolean ): number; connect_after( signal: 'show-resize-popup', callback: ( _source: this, object: boolean, p0: Rectangle, p1: number, p2: number ) => boolean ): number; emit( signal: 'show-resize-popup', object: boolean, p0: Rectangle, p1: number, p2: number ): void; connect( signal: 'show-restart-message', callback: (_source: this, message: string | null) => boolean ): number; connect_after( signal: 'show-restart-message', callback: (_source: this, message: string | null) => boolean ): number; emit(signal: 'show-restart-message', message: string | null): void; connect( signal: 'showing-desktop-changed', callback: (_source: this) => void ): number; connect_after( signal: 'showing-desktop-changed', callback: (_source: this) => void ): number; emit(signal: 'showing-desktop-changed'): void; connect( signal: 'window-created', callback: (_source: this, object: Window) => void ): number; connect_after( signal: 'window-created', callback: (_source: this, object: Window) => void ): number; emit(signal: 'window-created', object: Window): void; connect( signal: 'window-demands-attention', callback: (_source: this, object: Window) => void ): number; connect_after( signal: 'window-demands-attention', callback: (_source: this, object: Window) => void ): number; emit(signal: 'window-demands-attention', object: Window): void; connect( signal: 'window-entered-monitor', callback: (_source: this, object: number, p0: Window) => void ): number; connect_after( signal: 'window-entered-monitor', callback: (_source: this, object: number, p0: Window) => void ): number; emit(signal: 'window-entered-monitor', object: number, p0: Window): void; connect( signal: 'window-left-monitor', callback: (_source: this, object: number, p0: Window) => void ): number; connect_after( signal: 'window-left-monitor', callback: (_source: this, object: number, p0: Window) => void ): number; emit(signal: 'window-left-monitor', object: number, p0: Window): void; connect( signal: 'window-marked-urgent', callback: (_source: this, object: Window) => void ): number; connect_after( signal: 'window-marked-urgent', callback: (_source: this, object: Window) => void ): number; emit(signal: 'window-marked-urgent', object: Window): void; connect( signal: 'workareas-changed', callback: (_source: this) => void ): number; connect_after( signal: 'workareas-changed', callback: (_source: this) => void ): number; emit(signal: 'workareas-changed'): void; connect( signal: 'x11-display-closing', callback: (_source: this) => void ): number; connect_after( signal: 'x11-display-closing', callback: (_source: this) => void ): number; emit(signal: 'x11-display-closing'): void; connect( signal: 'x11-display-opened', callback: (_source: this) => void ): number; connect_after( signal: 'x11-display-opened', callback: (_source: this) => void ): number; emit(signal: 'x11-display-opened'): void; connect( signal: 'x11-display-setup', callback: (_source: this) => void ): number; connect_after( signal: 'x11-display-setup', callback: (_source: this) => void ): number; emit(signal: 'x11-display-setup'): void; // Members add_ignored_crossing_serial(serial: number): void; add_keybinding( name: string, settings: Gio.Settings, flags: KeyBindingFlags, handler: KeyHandlerFunc ): number; begin_grab_op( window: Window, op: GrabOp, pointer_already_grabbed: boolean, frame_action: boolean, button: number, modmask: number, timestamp: number, root_x: number, root_y: number ): boolean; clear_mouse_mode(): void; close(timestamp: number): void; end_grab_op(timestamp: number): void; focus_default_window(timestamp: number): void; freeze_keyboard(timestamp: number): void; get_current_monitor(): number; get_current_time(): number; get_current_time_roundtrip(): number; get_focus_window(): Window; get_grab_op(): GrabOp; get_keybinding_action(keycode: number, mask: number): number; get_last_user_time(): number; get_monitor_geometry(monitor: number): Rectangle; get_monitor_in_fullscreen(monitor: number): boolean; get_monitor_index_for_rect(rect: Rectangle): number; get_monitor_neighbor_index( which_monitor: number, dir: DisplayDirection ): number; get_monitor_scale(monitor: number): number; get_n_monitors(): number; get_pad_action_label( pad: Clutter.InputDevice, action_type: PadActionType, action_number: number ): string; get_primary_monitor(): number; get_selection(): Selection; get_size(): [number, number]; get_sound_player(): SoundPlayer; get_tab_current(type: TabList, workspace: Workspace): Window; get_tab_list(type: TabList, workspace?: Workspace | null): Window[]; get_tab_next( type: TabList, workspace: Workspace, window: Window | null, backward: boolean ): Window; get_workspace_manager(): WorkspaceManager; grab_accelerator(accelerator: string, flags: KeyBindingFlags): number; is_pointer_emulating_sequence( sequence?: Clutter.EventSequence | null ): boolean; remove_keybinding(name: string): boolean; request_pad_osd(pad: Clutter.InputDevice, edition_mode: boolean): void; set_cursor(cursor: Cursor): void; set_input_focus( window: Window, focus_frame: boolean, timestamp: number ): void; sort_windows_by_stacking(windows: Window[]): Window[]; supports_extended_barriers(): boolean; unfreeze_keyboard(timestamp: number): void; ungrab_accelerator(action_id: number): boolean; ungrab_keyboard(timestamp: number): void; unset_input_focus(timestamp: number): void; xserver_time_is_before(time1: number, time2: number): boolean; } export namespace Dnd { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Dnd extends GObject.Object { static $gtype: GObject.GType<Dnd>; constructor( properties?: Partial<Dnd.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Dnd.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'dnd-enter', callback: (_source: this) => void): number; connect_after( signal: 'dnd-enter', callback: (_source: this) => void ): number; emit(signal: 'dnd-enter'): void; connect(signal: 'dnd-leave', callback: (_source: this) => void): number; connect_after( signal: 'dnd-leave', callback: (_source: this) => void ): number; emit(signal: 'dnd-leave'): void; connect( signal: 'dnd-position-change', callback: (_source: this, object: number, p0: number) => void ): number; connect_after( signal: 'dnd-position-change', callback: (_source: this, object: number, p0: number) => void ): number; emit(signal: 'dnd-position-change', object: number, p0: number): void; } export namespace IdleMonitor { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; device: Clutter.InputDevice; } } export class IdleMonitor extends GObject.Object { static $gtype: GObject.GType<IdleMonitor>; constructor( properties?: Partial<IdleMonitor.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<IdleMonitor.ConstructorProperties>, ...args: any[] ): void; // Properties device: Clutter.InputDevice; // Members add_idle_watch( interval_msec: number, callback?: IdleMonitorWatchFunc | null ): number; add_user_active_watch(callback?: IdleMonitorWatchFunc | null): number; get_idletime(): number; remove_watch(id: number): void; static get_core(): IdleMonitor; } export namespace LaunchContext { export interface ConstructorProperties extends Gio.AppLaunchContext.ConstructorProperties { [key: string]: any; display: Display; timestamp: number; workspace: Workspace; } } export class LaunchContext extends Gio.AppLaunchContext { static $gtype: GObject.GType<LaunchContext>; constructor( properties?: Partial<LaunchContext.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<LaunchContext.ConstructorProperties>, ...args: any[] ): void; // Properties display: Display; timestamp: number; workspace: Workspace; // Members set_timestamp(timestamp: number): void; set_workspace(workspace: Workspace): void; } export namespace MonitorManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; backend: Backend; panel_orientation_managed: boolean; panelOrientationManaged: boolean; } } export class MonitorManager extends GObject.Object { static $gtype: GObject.GType<MonitorManager>; constructor( properties?: Partial<MonitorManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<MonitorManager.ConstructorProperties>, ...args: any[] ): void; // Properties backend: Backend; panel_orientation_managed: boolean; panelOrientationManaged: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'confirm-display-change', callback: (_source: this) => void ): number; connect_after( signal: 'confirm-display-change', callback: (_source: this) => void ): number; emit(signal: 'confirm-display-change'): void; connect( signal: 'monitors-changed', callback: (_source: this) => void ): number; connect_after( signal: 'monitors-changed', callback: (_source: this) => void ): number; emit(signal: 'monitors-changed'): void; connect( signal: 'monitors-changed-internal', callback: (_source: this) => void ): number; connect_after( signal: 'monitors-changed-internal', callback: (_source: this) => void ): number; emit(signal: 'monitors-changed-internal'): void; connect( signal: 'power-save-mode-changed', callback: (_source: this) => void ): number; connect_after( signal: 'power-save-mode-changed', callback: (_source: this) => void ): number; emit(signal: 'power-save-mode-changed'): void; // Members can_switch_config(): boolean; get_is_builtin_display_on(): boolean; get_monitor_for_connector(connector: string): number; get_panel_orientation_managed(): boolean; get_switch_config(): MonitorSwitchConfigType; switch_config(config_type: MonitorSwitchConfigType): void; static get(): MonitorManager; static get_display_configuration_timeout(): number; } export namespace Plugin { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export abstract class Plugin extends GObject.Object { static $gtype: GObject.GType<Plugin>; constructor( properties?: Partial<Plugin.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Plugin.ConstructorProperties>, ...args: any[] ): void; // Members begin_modal(options: ModalOptions, timestamp: number): boolean; complete_display_change(ok: boolean): void; destroy_completed(actor: WindowActor): void; end_modal(timestamp: number): void; get_display(): Display; get_info(): PluginInfo; map_completed(actor: WindowActor): void; minimize_completed(actor: WindowActor): void; size_change_completed(actor: WindowActor): void; switch_workspace_completed(): void; unminimize_completed(actor: WindowActor): void; vfunc_confirm_display_change(): void; vfunc_destroy(actor: WindowActor): void; vfunc_hide_tile_preview(): void; vfunc_keybinding_filter(binding: KeyBinding): boolean; vfunc_kill_switch_workspace(): void; vfunc_kill_window_effects(actor: WindowActor): void; vfunc_locate_pointer(): void; vfunc_map(actor: WindowActor): void; vfunc_minimize(actor: WindowActor): void; vfunc_plugin_info(): PluginInfo; vfunc_show_tile_preview( window: Window, tile_rect: Rectangle, tile_monitor_number: number ): void; vfunc_show_window_menu( window: Window, menu: WindowMenuType, x: number, y: number ): void; vfunc_show_window_menu_for_rect( window: Window, menu: WindowMenuType, rect: Rectangle ): void; vfunc_size_change( actor: WindowActor, which_change: SizeChange, old_frame_rect: Rectangle, old_buffer_rect: Rectangle ): void; vfunc_size_changed(actor: WindowActor): void; vfunc_start(): void; vfunc_switch_workspace( from: number, to: number, direction: MotionDirection ): void; vfunc_unminimize(actor: WindowActor): void; vfunc_xevent_filter(event: xlib.XEvent): boolean; static manager_set_plugin_type(gtype: GObject.GType): void; } export namespace RemoteAccessController { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class RemoteAccessController extends GObject.Object { static $gtype: GObject.GType<RemoteAccessController>; constructor( properties?: Partial<RemoteAccessController.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<RemoteAccessController.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'new-handle', callback: (_source: this, object: RemoteAccessHandle) => void ): number; connect_after( signal: 'new-handle', callback: (_source: this, object: RemoteAccessHandle) => void ): number; emit(signal: 'new-handle', object: RemoteAccessHandle): void; // Members inhibit_remote_access(): void; uninhibit_remote_access(): void; } export namespace RemoteAccessHandle { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; is_recording: boolean; isRecording: boolean; } } export class RemoteAccessHandle extends GObject.Object { static $gtype: GObject.GType<RemoteAccessHandle>; constructor( properties?: Partial<RemoteAccessHandle.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<RemoteAccessHandle.ConstructorProperties>, ...args: any[] ): void; // Properties is_recording: boolean; isRecording: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'stopped', callback: (_source: this) => void): number; connect_after(signal: 'stopped', callback: (_source: this) => void): number; emit(signal: 'stopped'): void; // Members get_disable_animations(): boolean; stop(): void; vfunc_stop(): void; } export namespace Selection { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Selection extends GObject.Object { static $gtype: GObject.GType<Selection>; constructor( properties?: Partial<Selection.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Selection.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'owner-changed', callback: (_source: this, object: number, p0: SelectionSource) => void ): number; connect_after( signal: 'owner-changed', callback: (_source: this, object: number, p0: SelectionSource) => void ): number; emit(signal: 'owner-changed', object: number, p0: SelectionSource): void; // Constructors static ['new'](display: Display): Selection; // Members get_mimetypes(selection_type: SelectionType): string[]; set_owner(selection_type: SelectionType, owner: SelectionSource): void; transfer_async( selection_type: SelectionType, mimetype: string, size: number, output: Gio.OutputStream, cancellable?: Gio.Cancellable | null ): Promise<boolean>; transfer_async( selection_type: SelectionType, mimetype: string, size: number, output: Gio.OutputStream, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; transfer_async( selection_type: SelectionType, mimetype: string, size: number, output: Gio.OutputStream, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; transfer_finish(result: Gio.AsyncResult): boolean; unset_owner(selection_type: SelectionType, owner: SelectionSource): void; } export namespace SelectionSource { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class SelectionSource extends GObject.Object { static $gtype: GObject.GType<SelectionSource>; constructor( properties?: Partial<SelectionSource.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SelectionSource.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'activated', callback: (_source: this) => void): number; connect_after( signal: 'activated', callback: (_source: this) => void ): number; emit(signal: 'activated'): void; connect(signal: 'deactivated', callback: (_source: this) => void): number; connect_after( signal: 'deactivated', callback: (_source: this) => void ): number; emit(signal: 'deactivated'): void; // Members get_mimetypes(): string[]; is_active(): boolean; read_async( mimetype: string, cancellable?: Gio.Cancellable | null ): Promise<Gio.InputStream>; read_async( mimetype: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; read_async( mimetype: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream> | void; read_finish(result: Gio.AsyncResult): Gio.InputStream; vfunc_activated(): void; vfunc_deactivated(): void; vfunc_get_mimetypes(): string[]; vfunc_read_async( mimetype: string, cancellable?: Gio.Cancellable | null ): Promise<Gio.InputStream>; vfunc_read_async( mimetype: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_read_async( mimetype: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Gio.InputStream> | void; vfunc_read_finish(result: Gio.AsyncResult): Gio.InputStream; } export namespace SelectionSourceMemory { export interface ConstructorProperties extends SelectionSource.ConstructorProperties { [key: string]: any; } } export class SelectionSourceMemory extends SelectionSource { static $gtype: GObject.GType<SelectionSourceMemory>; constructor( properties?: Partial<SelectionSourceMemory.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SelectionSourceMemory.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new']( mimetype: string, content: GLib.Bytes | Uint8Array ): SelectionSourceMemory; } export namespace ShadowFactory { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ShadowFactory extends GObject.Object { static $gtype: GObject.GType<ShadowFactory>; constructor( properties?: Partial<ShadowFactory.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShadowFactory.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'changed', callback: (_source: this) => void): number; connect_after(signal: 'changed', callback: (_source: this) => void): number; emit(signal: 'changed'): void; // Constructors static ['new'](): ShadowFactory; // Members get_params(class_name: string, focused: boolean): ShadowParams; get_shadow( shape: WindowShape, width: number, height: number, class_name: string, focused: boolean ): Shadow; set_params( class_name: string, focused: boolean, params: ShadowParams ): void; static get_default(): ShadowFactory; } export namespace ShapedTexture { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ShapedTexture extends GObject.Object implements Clutter.Content { static $gtype: GObject.GType<ShapedTexture>; constructor( properties?: Partial<ShapedTexture.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<ShapedTexture.ConstructorProperties>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'size-changed', callback: (_source: this) => void): number; connect_after( signal: 'size-changed', callback: (_source: this) => void ): number; emit(signal: 'size-changed'): void; // Members get_image(clip?: cairo.RectangleInt | null): cairo.Surface | null; get_texture(): Cogl.Texture; set_create_mipmaps(create_mipmaps: boolean): void; set_mask_texture(mask_texture: Cogl.Texture): void; // Implemented Members get_preferred_size(): [boolean, number, number]; invalidate(): void; invalidate_size(): void; vfunc_attached(actor: Clutter.Actor): void; vfunc_detached(actor: Clutter.Actor): void; vfunc_get_preferred_size(): [boolean, number, number]; vfunc_invalidate(): void; vfunc_invalidate_size(): void; vfunc_paint_content( actor: Clutter.Actor, node: Clutter.PaintNode, paint_context: Clutter.PaintContext ): void; } export namespace SoundPlayer { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class SoundPlayer extends GObject.Object { static $gtype: GObject.GType<SoundPlayer>; constructor( properties?: Partial<SoundPlayer.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<SoundPlayer.ConstructorProperties>, ...args: any[] ): void; // Members play_from_file( file: Gio.File, description: string, cancellable?: Gio.Cancellable | null ): void; play_from_theme( name: string, description: string, cancellable?: Gio.Cancellable | null ): void; } export namespace Stage { export interface ConstructorProperties< A extends Clutter.Actor = Clutter.Actor > extends Clutter.Stage.ConstructorProperties<A> { [key: string]: any; } } export class Stage<A extends Clutter.Actor = Clutter.Actor> extends Clutter.Stage<A> implements Atk.ImplementorIface, Clutter.Animatable, Clutter.Container<A>, Clutter.Scriptable { static $gtype: GObject.GType<Stage>; constructor( properties?: Partial<Stage.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<Stage.ConstructorProperties<A>>, ...args: any[] ): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'actors-painted', callback: (_source: this) => void ): number; connect_after( signal: 'actors-painted', callback: (_source: this) => void ): number; emit(signal: 'actors-painted'): void; // Members static is_focused(display: Display): boolean; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Clutter.Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Clutter.Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): Clutter.ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): Clutter.ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Clutter.Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property( script: Clutter.Script, name: string, value: any ): void; vfunc_set_id(id_: string): void; } export namespace StartupNotification { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; display: Display; } } export class StartupNotification extends GObject.Object { static $gtype: GObject.GType<StartupNotification>; constructor( properties?: Partial<StartupNotification.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StartupNotification.ConstructorProperties>, ...args: any[] ): void; // Properties display: Display; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'changed', callback: (_source: this, object: any | null) => void ): number; connect_after( signal: 'changed', callback: (_source: this, object: any | null) => void ): number; emit(signal: 'changed', object: any | null): void; // Members create_launcher(): LaunchContext; } export namespace StartupSequence { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; application_id: string; applicationId: string; icon_name: string; iconName: string; id: string; name: string; timestamp: number; wmclass: string; workspace: number; } } export class StartupSequence extends GObject.Object { static $gtype: GObject.GType<StartupSequence>; constructor( properties?: Partial<StartupSequence.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<StartupSequence.ConstructorProperties>, ...args: any[] ): void; // Properties application_id: string; applicationId: string; icon_name: string; iconName: string; id: string; name: string; timestamp: number; wmclass: string; workspace: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'complete', callback: (_source: this) => void): number; connect_after( signal: 'complete', callback: (_source: this) => void ): number; emit(signal: 'complete'): void; // Members complete(): void; get_application_id(): string; get_completed(): boolean; get_icon_name(): string; get_id(): string; get_name(): string; get_timestamp(): number; get_wmclass(): string; get_workspace(): number; } export namespace WaylandClient { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class WaylandClient extends GObject.Object { static $gtype: GObject.GType<WaylandClient>; constructor( properties?: Partial<WaylandClient.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WaylandClient.ConstructorProperties>, ...args: any[] ): void; // Constructors static ['new'](launcher: Gio.SubprocessLauncher): WaylandClient; // Members hide_from_window_list(window: Window): void; owns_window(window: Window): boolean; show_in_window_list(window: Window): void; spawnv(display: Display, argv: string[]): Gio.Subprocess; } export namespace Window { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; above: boolean; appears_focused: boolean; appearsFocused: boolean; decorated: boolean; demands_attention: boolean; demandsAttention: boolean; fullscreen: boolean; gtk_app_menu_object_path: string; gtkAppMenuObjectPath: string; gtk_application_id: string; gtkApplicationId: string; gtk_application_object_path: string; gtkApplicationObjectPath: string; gtk_menubar_object_path: string; gtkMenubarObjectPath: string; gtk_unique_bus_name: string; gtkUniqueBusName: string; gtk_window_object_path: string; gtkWindowObjectPath: string; icon: any; maximized_horizontally: boolean; maximizedHorizontally: boolean; maximized_vertically: boolean; maximizedVertically: boolean; mini_icon: any; miniIcon: any; minimized: boolean; mutter_hints: string; mutterHints: string; on_all_workspaces: boolean; onAllWorkspaces: boolean; resizeable: boolean; skip_taskbar: boolean; skipTaskbar: boolean; title: string; urgent: boolean; user_time: number; userTime: number; window_type: WindowType; windowType: WindowType; wm_class: string; wmClass: string; } } export abstract class Window extends GObject.Object { static $gtype: GObject.GType<Window>; constructor( properties?: Partial<Window.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Window.ConstructorProperties>, ...args: any[] ): void; // Properties above: boolean; appears_focused: boolean; appearsFocused: boolean; decorated: boolean; demands_attention: boolean; demandsAttention: boolean; fullscreen: boolean; gtk_app_menu_object_path: string; gtkAppMenuObjectPath: string; gtk_application_id: string; gtkApplicationId: string; gtk_application_object_path: string; gtkApplicationObjectPath: string; gtk_menubar_object_path: string; gtkMenubarObjectPath: string; gtk_unique_bus_name: string; gtkUniqueBusName: string; gtk_window_object_path: string; gtkWindowObjectPath: string; icon: any; maximized_horizontally: boolean; maximizedHorizontally: boolean; maximized_vertically: boolean; maximizedVertically: boolean; mini_icon: any; miniIcon: any; minimized: boolean; mutter_hints: string; mutterHints: string; on_all_workspaces: boolean; onAllWorkspaces: boolean; resizeable: boolean; skip_taskbar: boolean; skipTaskbar: boolean; title: string; urgent: boolean; user_time: number; userTime: number; window_type: WindowType; windowType: WindowType; wm_class: string; wmClass: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'focus', callback: (_source: this) => void): number; connect_after(signal: 'focus', callback: (_source: this) => void): number; emit(signal: 'focus'): void; connect( signal: 'position-changed', callback: (_source: this) => void ): number; connect_after( signal: 'position-changed', callback: (_source: this) => void ): number; emit(signal: 'position-changed'): void; connect(signal: 'raised', callback: (_source: this) => void): number; connect_after(signal: 'raised', callback: (_source: this) => void): number; emit(signal: 'raised'): void; connect(signal: 'shown', callback: (_source: this) => void): number; connect_after(signal: 'shown', callback: (_source: this) => void): number; emit(signal: 'shown'): void; connect(signal: 'size-changed', callback: (_source: this) => void): number; connect_after( signal: 'size-changed', callback: (_source: this) => void ): number; emit(signal: 'size-changed'): void; connect(signal: 'unmanaged', callback: (_source: this) => void): number; connect_after( signal: 'unmanaged', callback: (_source: this) => void ): number; emit(signal: 'unmanaged'): void; connect(signal: 'unmanaging', callback: (_source: this) => void): number; connect_after( signal: 'unmanaging', callback: (_source: this) => void ): number; emit(signal: 'unmanaging'): void; connect( signal: 'workspace-changed', callback: (_source: this) => void ): number; connect_after( signal: 'workspace-changed', callback: (_source: this) => void ): number; emit(signal: 'workspace-changed'): void; // Members activate(current_time: number): void; activate_with_workspace(current_time: number, workspace: Workspace): void; allows_move(): boolean; allows_resize(): boolean; begin_grab_op(op: GrabOp, frame_action: boolean, timestamp: number): void; can_close(): boolean; can_maximize(): boolean; can_minimize(): boolean; can_shade(): boolean; change_workspace(workspace: Workspace): void; change_workspace_by_index(space_index: number, append: boolean): void; check_alive(timestamp: number): void; client_rect_to_frame_rect(client_rect: Rectangle): Rectangle; compute_group(): void; ['delete'](timestamp: number): void; find_root_ancestor(): Window; focus(timestamp: number): void; foreach_ancestor(func: WindowForeachFunc): void; foreach_transient(func: WindowForeachFunc): void; frame_rect_to_client_rect(frame_rect: Rectangle): Rectangle; get_buffer_rect(): Rectangle; get_client_machine(): string; get_client_type(): WindowClientType; get_compositor_private<T = GObject.Object>(): T; get_description(): string; get_display(): Display; get_frame_bounds(): cairo.Region | null; get_frame_rect(): Rectangle; get_frame_type(): FrameType; get_gtk_app_menu_object_path(): string; get_gtk_application_id(): string; get_gtk_application_object_path(): string; get_gtk_menubar_object_path(): string; get_gtk_theme_variant(): string; get_gtk_unique_bus_name(): string; get_gtk_window_object_path(): string; get_icon_geometry(): [boolean, Rectangle]; get_id(): number; get_layer(): StackLayer; get_maximized(): MaximizeFlags; get_monitor(): number; get_mutter_hints(): string; get_pid(): number; get_role(): string; get_sandboxed_app_id(): string; get_stable_sequence(): number; get_startup_id(): string; get_tile_match(): Window | null; get_title(): string; get_transient_for(): Window; get_user_time(): number; get_window_type(): WindowType; get_wm_class(): string; get_wm_class_instance(): string; get_work_area_all_monitors(): Rectangle; get_work_area_current_monitor(): Rectangle; get_work_area_for_monitor(which_monitor: number): Rectangle; get_workspace(): Workspace; group_leader_changed(): void; has_focus(): boolean; is_above(): boolean; is_always_on_all_workspaces(): boolean; is_ancestor_of_transient(_transient: Window): boolean; is_attached_dialog(): boolean; is_client_decorated(): boolean; is_fullscreen(): boolean; is_hidden(): boolean; is_monitor_sized(): boolean; is_on_all_workspaces(): boolean; is_on_primary_monitor(): boolean; is_override_redirect(): boolean; is_remote(): boolean; is_screen_sized(): boolean; is_shaded(): boolean; is_skip_taskbar(): boolean; kill(): void; located_on_workspace(workspace: Workspace): boolean; lower(): void; make_above(): void; make_fullscreen(): void; maximize(directions: MaximizeFlags): void; minimize(): void; move_frame(user_op: boolean, root_x_nw: number, root_y_nw: number): void; move_resize_frame( user_op: boolean, root_x_nw: number, root_y_nw: number, w: number, h: number ): void; move_to_monitor(monitor: number): void; raise(): void; set_compositor_private(priv: GObject.Object): void; set_demands_attention(): void; set_icon_geometry(rect?: Rectangle | null): void; shade(timestamp: number): void; shove_titlebar_onscreen(): void; showing_on_its_workspace(): boolean; shutdown_group(): void; stick(): void; titlebar_is_onscreen(): boolean; unmake_above(): void; unmake_fullscreen(): void; unmaximize(directions: MaximizeFlags): void; unminimize(): void; unset_demands_attention(): void; unshade(timestamp: number): void; unstick(): void; } export namespace WindowActor { export interface ConstructorProperties< A extends Clutter.Actor = Clutter.Actor > extends Clutter.Actor.ConstructorProperties { [key: string]: any; meta_window: Window; metaWindow: Window; } } export abstract class WindowActor<A extends Clutter.Actor = Clutter.Actor> extends Clutter.Actor implements Atk.ImplementorIface, Clutter.Animatable, Clutter.Container<A>, Clutter.Scriptable { static $gtype: GObject.GType<WindowActor>; constructor( properties?: Partial<WindowActor.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<WindowActor.ConstructorProperties<A>>, ...args: any[] ): void; // Properties meta_window: Window; metaWindow: Window; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: 'damaged', callback: (_source: this) => void): number; connect_after(signal: 'damaged', callback: (_source: this) => void): number; emit(signal: 'damaged'): void; connect( signal: 'effects-completed', callback: (_source: this) => void ): number; connect_after( signal: 'effects-completed', callback: (_source: this) => void ): number; emit(signal: 'effects-completed'): void; connect(signal: 'first-frame', callback: (_source: this) => void): number; connect_after( signal: 'first-frame', callback: (_source: this) => void ): number; emit(signal: 'first-frame'): void; connect(signal: 'thawed', callback: (_source: this) => void): number; connect_after(signal: 'thawed', callback: (_source: this) => void): number; emit(signal: 'thawed'): void; // Members freeze(): void; get_image(clip?: cairo.RectangleInt | null): cairo.Surface | null; get_meta_window(): Window; get_texture(): ShapedTexture; is_destroyed(): boolean; sync_visibility(): void; thaw(): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Clutter.Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Clutter.Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): Clutter.ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): Clutter.ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Clutter.Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property( script: Clutter.Script, name: string, value: any ): void; vfunc_set_id(id_: string): void; } export namespace WindowGroup { export interface ConstructorProperties< A extends Clutter.Actor = Clutter.Actor > extends Clutter.Actor.ConstructorProperties { [key: string]: any; } } export class WindowGroup<A extends Clutter.Actor = Clutter.Actor> extends Clutter.Actor implements Atk.ImplementorIface, Clutter.Animatable, Clutter.Container<A>, Clutter.Scriptable { static $gtype: GObject.GType<WindowGroup>; constructor( properties?: Partial<WindowGroup.ConstructorProperties<A>>, ...args: any[] ); _init( properties?: Partial<WindowGroup.ConstructorProperties<A>>, ...args: any[] ): void; // Implemented Members find_property(property_name: string): GObject.ParamSpec; get_actor(): Clutter.Actor; get_initial_state(property_name: string, value: any): void; interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; set_final_state(property_name: string, value: any): void; vfunc_find_property(property_name: string): GObject.ParamSpec; vfunc_get_actor(): Clutter.Actor; vfunc_get_initial_state(property_name: string, value: any): void; vfunc_interpolate_value( property_name: string, interval: Clutter.Interval, progress: number ): [boolean, unknown]; vfunc_set_final_state(property_name: string, value: any): void; add_actor(actor: A): void; child_get_property(child: A, property: string, value: any): void; child_notify(child: A, pspec: GObject.ParamSpec): void; child_set_property(child: A, property: string, value: any): void; create_child_meta(actor: A): void; destroy_child_meta(actor: A): void; find_child_by_name(child_name: string): A; get_child_meta(actor: A): Clutter.ChildMeta; get_children(): A[]; get_children(...args: never[]): never; lower_child(actor: A, sibling?: A | null): void; raise_child(actor: A, sibling?: A | null): void; remove_actor(actor: A): void; sort_depth_order(): void; vfunc_actor_added(actor: A): void; vfunc_actor_removed(actor: A): void; vfunc_add(actor: A): void; vfunc_child_notify(child: A, pspec: GObject.ParamSpec): void; vfunc_create_child_meta(actor: A): void; vfunc_destroy_child_meta(actor: A): void; vfunc_get_child_meta(actor: A): Clutter.ChildMeta; vfunc_lower(actor: A, sibling?: A | null): void; vfunc_raise(actor: A, sibling?: A | null): void; vfunc_remove(actor: A): void; vfunc_sort_depth_order(): void; get_id(): string; parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; set_custom_property(script: Clutter.Script, name: string, value: any): void; set_id(id_: string): void; vfunc_get_id(): string; vfunc_parse_custom_node( script: Clutter.Script, value: any, name: string, node: Json.Node ): boolean; vfunc_set_custom_property( script: Clutter.Script, name: string, value: any ): void; vfunc_set_id(id_: string): void; } export namespace Workspace { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; active: boolean; n_windows: number; nWindows: number; workspace_index: number; workspaceIndex: number; } } export class Workspace extends GObject.Object { static $gtype: GObject.GType<Workspace>; constructor( properties?: Partial<Workspace.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<Workspace.ConstructorProperties>, ...args: any[] ): void; // Properties active: boolean; n_windows: number; nWindows: number; workspace_index: number; workspaceIndex: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'window-added', callback: (_source: this, object: Window) => void ): number; connect_after( signal: 'window-added', callback: (_source: this, object: Window) => void ): number; emit(signal: 'window-added', object: Window): void; connect( signal: 'window-removed', callback: (_source: this, object: Window) => void ): number; connect_after( signal: 'window-removed', callback: (_source: this, object: Window) => void ): number; emit(signal: 'window-removed', object: Window): void; // Members activate(timestamp: number): void; activate_with_focus(focus_this: Window, timestamp: number): void; get_display(): Display; get_neighbor(direction: MotionDirection): Workspace; get_work_area_all_monitors(): Rectangle; get_work_area_for_monitor(which_monitor: number): Rectangle; index(): number; list_windows(): Window[]; set_builtin_struts(struts: Strut[]): void; } export namespace WorkspaceManager { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; layout_columns: number; layoutColumns: number; layout_rows: number; layoutRows: number; n_workspaces: number; nWorkspaces: number; } } export class WorkspaceManager extends GObject.Object { static $gtype: GObject.GType<WorkspaceManager>; constructor( properties?: Partial<WorkspaceManager.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<WorkspaceManager.ConstructorProperties>, ...args: any[] ): void; // Properties layout_columns: number; layoutColumns: number; layout_rows: number; layoutRows: number; n_workspaces: number; nWorkspaces: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: 'active-workspace-changed', callback: (_source: this) => void ): number; connect_after( signal: 'active-workspace-changed', callback: (_source: this) => void ): number; emit(signal: 'active-workspace-changed'): void; connect( signal: 'showing-desktop-changed', callback: (_source: this) => void ): number; connect_after( signal: 'showing-desktop-changed', callback: (_source: this) => void ): number; emit(signal: 'showing-desktop-changed'): void; connect( signal: 'workspace-added', callback: (_source: this, object: number) => void ): number; connect_after( signal: 'workspace-added', callback: (_source: this, object: number) => void ): number; emit(signal: 'workspace-added', object: number): void; connect( signal: 'workspace-removed', callback: (_source: this, object: number) => void ): number; connect_after( signal: 'workspace-removed', callback: (_source: this, object: number) => void ): number; emit(signal: 'workspace-removed', object: number): void; connect( signal: 'workspace-switched', callback: ( _source: this, object: number, p0: number, p1: MotionDirection ) => void ): number; connect_after( signal: 'workspace-switched', callback: ( _source: this, object: number, p0: number, p1: MotionDirection ) => void ): number; emit( signal: 'workspace-switched', object: number, p0: number, p1: MotionDirection ): void; connect( signal: 'workspaces-reordered', callback: (_source: this) => void ): number; connect_after( signal: 'workspaces-reordered', callback: (_source: this) => void ): number; emit(signal: 'workspaces-reordered'): void; // Members append_new_workspace(activate: boolean, timestamp: number): Workspace; get_active_workspace(): Workspace; get_active_workspace_index(): number; get_n_workspaces(): number; get_workspace_by_index(index: number): Workspace | null; override_workspace_layout( starting_corner: DisplayCorner, vertical_layout: boolean, n_rows: number, n_columns: number ): void; remove_workspace(workspace: Workspace, timestamp: number): void; reorder_workspace(workspace: Workspace, new_index: number): void; } export namespace X11Display { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class X11Display extends GObject.Object { static $gtype: GObject.GType<X11Display>; constructor( properties?: Partial<X11Display.ConstructorProperties>, ...args: any[] ); _init( properties?: Partial<X11Display.ConstructorProperties>, ...args: any[] ): void; // Members clear_stage_input_region(): void; get_damage_event_base(): number; get_screen_number(): number; get_shape_event_base(): number; has_shape(): boolean; set_cm_selection(): void; set_stage_input_region(region: any): void; xwindow_is_a_no_focus_window(xwindow: xlib.Window): boolean; } export class BarrierEvent { static $gtype: GObject.GType<BarrierEvent>; constructor( properties?: Partial<{ ref_count?: number; event_id?: number; dt?: number; time?: number; x?: number; y?: number; dx?: number; dy?: number; released?: boolean; grabbed?: boolean; }> ); constructor(copy: BarrierEvent); // Fields ref_count: number; event_id: number; dt: number; time: number; x: number; y: number; dx: number; dy: number; released: boolean; grabbed: boolean; } export class BarrierPrivate { static $gtype: GObject.GType<BarrierPrivate>; constructor(copy: BarrierPrivate); } export class ButtonLayout { static $gtype: GObject.GType<ButtonLayout>; constructor(copy: ButtonLayout); // Fields left_buttons: ButtonFunction[]; left_buttons_has_spacer: boolean[]; right_buttons: ButtonFunction[]; right_buttons_has_spacer: boolean[]; } export class Edge { static $gtype: GObject.GType<Edge>; constructor(copy: Edge); // Fields rect: Rectangle; side_type: Side; edge_type: EdgeType; } export class Frame { static $gtype: GObject.GType<Frame>; constructor(copy: Frame); } export class FrameBorders { static $gtype: GObject.GType<FrameBorders>; constructor( properties?: Partial<{ visible?: Gtk.Border; invisible?: Gtk.Border; total?: Gtk.Border; }> ); constructor(copy: FrameBorders); // Fields visible: Gtk.Border; invisible: Gtk.Border; total: Gtk.Border; // Members clear(): void; } export class KeyBinding { static $gtype: GObject.GType<KeyBinding>; constructor(copy: KeyBinding); // Members get_mask(): number; get_modifiers(): VirtualModifier; get_name(): string; is_builtin(): boolean; is_reversed(): boolean; } export class PluginInfo { static $gtype: GObject.GType<PluginInfo>; constructor( properties?: Partial<{ name?: string; version?: string; author?: string; license?: string; description?: string; }> ); constructor(copy: PluginInfo); // Fields name: string; version: string; author: string; license: string; description: string; } export class PluginVersion { static $gtype: GObject.GType<PluginVersion>; constructor( properties?: Partial<{ version_major?: number; version_minor?: number; version_micro?: number; version_api?: number; }> ); constructor(copy: PluginVersion); // Fields version_major: number; version_minor: number; version_micro: number; version_api: number; } export class Rectangle { static $gtype: GObject.GType<Rectangle>; constructor( properties?: Partial<{ x?: number; y?: number; width?: number; height?: number; }> ); constructor(copy: Rectangle); // Fields x: number; y: number; width: number; height: number; // Members area(): number; contains_rect(inner_rect: Rectangle): boolean; copy(): Rectangle; could_fit_rect(inner_rect: Rectangle): boolean; equal(src2: Rectangle): boolean; free(): void; horiz_overlap(rect2: Rectangle): boolean; intersect(src2: Rectangle): [boolean, Rectangle]; overlap(rect2: Rectangle): boolean; union(rect2: Rectangle): Rectangle; vert_overlap(rect2: Rectangle): boolean; } export class Settings { static $gtype: GObject.GType<Settings>; constructor(copy: Settings); // Members get_font_dpi(): number; get_ui_scaling_factor(): number; } export class Shadow { static $gtype: GObject.GType<Shadow>; constructor(copy: Shadow); // Members get_bounds( window_x: number, window_y: number, window_width: number, window_height: number, bounds: cairo.RectangleInt ): void; paint( framebuffer: Cogl.Framebuffer, window_x: number, window_y: number, window_width: number, window_height: number, opacity: number, clip: cairo.Region | null, clip_strictly: boolean ): void; ref(): Shadow; unref(): void; } export class ShadowParams { static $gtype: GObject.GType<ShadowParams>; constructor( properties?: Partial<{ radius?: number; top_fade?: number; x_offset?: number; y_offset?: number; opacity?: number; }> ); constructor(copy: ShadowParams); // Fields radius: number; top_fade: number; x_offset: number; y_offset: number; opacity: number; } export class Strut { static $gtype: GObject.GType<Strut>; constructor(copy: Strut); // Fields rect: Rectangle; side: Side; } export class Theme { static $gtype: GObject.GType<Theme>; constructor(copy: Theme); // Members free(): void; } export class WindowShape { static $gtype: GObject.GType<WindowShape>; constructor(region: cairo.Region); constructor(copy: WindowShape); // Constructors static ['new'](region: cairo.Region): WindowShape; // Members equal(shape_b: WindowShape): boolean; get_borders( border_top: number, border_right: number, border_bottom: number, border_left: number ): void; hash(): number; ref(): WindowShape; to_region(center_width: number, center_height: number): cairo.Region; unref(): void; } export interface CloseDialogNamespace { $gtype: GObject.GType<CloseDialog>; prototype: CloseDialogPrototype; } export type CloseDialog = CloseDialogPrototype; export interface CloseDialogPrototype extends GObject.Object { // Properties window: Window; // Members focus(): void; hide(): void; is_visible(): boolean; response(response: CloseDialogResponse): void; show(): void; vfunc_focus(): void; vfunc_hide(): void; vfunc_show(): void; } export const CloseDialog: CloseDialogNamespace; export interface InhibitShortcutsDialogNamespace { $gtype: GObject.GType<InhibitShortcutsDialog>; prototype: InhibitShortcutsDialogPrototype; } export type InhibitShortcutsDialog = InhibitShortcutsDialogPrototype; export interface InhibitShortcutsDialogPrototype extends GObject.Object { // Properties window: Window; // Members hide(): void; response(response: InhibitShortcutsDialogResponse): void; show(): void; vfunc_hide(): void; vfunc_show(): void; } export const InhibitShortcutsDialog: InhibitShortcutsDialogNamespace;
the_stack
import * as React from "react"; export interface BaseProps { /** * Additional CSS ui classes */ className?: string; /** * Use other component for composing results: <DropdownMenu component={Button}> */ component?: React.ReactType; /** * Apply default semantic UI classes for component, for example ui button * @default true */ defaultClasses?: boolean; /** * Apply style. If using semantic-react/radium you can apply array of styles too */ style?: React.CSSProperties | React.CSSProperties[]; /** * Allows to pass default html attributes. * Not inheriting from React.DOMAttributes to prevent annoying onAnything handlers in completion popup */ [key: string]: any; } /** * Base animation properties */ export interface AnimationProps { /** * Enter/Appear animation name */ enter?: string; /** * Leave animation name */ leave?: string; /** * Enter/Appear animation duration in ms */ enterDuration?: number; /** * Leave/Appear animation duration in ms */ leaveDuration?: number; } export type SizeType = "mini" | "tiny" | "small" | "medium" | "large" | "big" | "huge" | "massive"; export type PositionType = "top" | "bottom" | "top right" | "top left" | "bottom left" | "bottom right"; export type ColorType = "red" | "orange" | "yellow" | "olive" | "green" | "teal" | "blue" | "violet" | "purple" | "pink" | "brown" | "grey" | "black"; // <Label /> export interface LabelProps extends BaseProps { /** * A label can attach to a content segment */ attached?: PositionType; /** * A label can reduce its complexity */ basic?: boolean; /** * A label can be circular */ circular?: boolean; /** * A label can have different colors */ color?: ColorType; /** * A label can position itself in the corner of an element * @default false */ corner?: "left" | "right" | boolean; /** * Empty label */ empty?: boolean; /** * A label can float above another element */ floating?: boolean; /** * A horizontal label is formatted to label content along-side it horizontally */ horizontal?: boolean; /** * Add image to the label */ image?: string; /** * Format label as link (uses <a> tag) */ link?: boolean; /** * A label can point to content next to it * @default false */ pointing?: "top" | "bottom" | "left" | "right" | boolean; /** * A label can appear as a ribbon attaching itself to an element. * @default false */ ribbon?: "right" | boolean; /** * A label can be small or large */ size?: SizeType; /** * A label can appear as a tag */ tag?: boolean; } export class Label extends React.Component<LabelProps, any> { } // <Detail /> export interface DetailProps extends BaseProps { } export class Detail extends React.Component<DetailProps, any> { } // <Labels /> export interface LabelsProps extends BaseProps { /** * Labels can share shapes */ circular?: boolean; /** * Labels can share colors together */ color?: ColorType; /** * Labels can share sizes together */ size?: SizeType; /** * Labels can share tag formatting */ tag?: boolean; } export class Labels extends React.Component<LabelsProps, any> { } export interface ButtonProps extends BaseProps { /** * Html type */ type?: string; /** * Adds a fade or slide animation on hover. */ animated?: "fade" | "vertical" | boolean; /** * It's attached to some other attachable component. */ attached?: "left" | "right" | "bottom" | "top" | boolean; /** * Adds simple styling to the component. */ basic?: boolean; /** * Gives a circular shape to the component. */ circular?: boolean; /** * Adds a SemanticUI color class. */ color?: ColorType; /** * Reduces the padding on the component. */ compact?: boolean; /** * A button can be formatted to show different levels of emphasis */ emphasis?: "primary" | "secondary" | "positive" | "negative" | string; /** * Forces to component to float left or right. */ floated?: "right" | "left"; /** * The component fills the parent components horizontal space. */ fluid?: boolean; /** * Styles the component for a dark background. */ inverted?: boolean; /** * Adds a SemanticUI size class. */ size?: SizeType; /** * Indicates whether the button is currently highlighted or disabled. */ state?: "active" | "disabled" | "loading" | string; /** * A button can be formatted to toggle on and off */ toggle?: boolean; } export class Button extends React.Component<ButtonProps, any> { } // <Buttons /> export interface ButtonsProps extends BaseProps { /** * It's attached to some other attachable component. */ attached?: "bottom" | "top"; /** * Adds simple styling to the component. */ basic?: boolean; /** * Adds a SemanticUI color class. */ color?: ColorType; /** * Reduces the padding on the component. */ compact?: boolean; /** * Forces all children to an equal width. */ equal?: boolean; /** * Forces to component to float left or right. */ floated?: "left" | "right" | string; /** * Styles the component for a dark background. */ inverted?: boolean; /** * Adds a SemanticUI size class. */ size?: SizeType; /** * Forces child components to render vertically. */ vertical?: boolean; } export class Buttons extends React.Component<ButtonsProps, any> { } // <IconButton /> export interface IconButtonProps extends ButtonProps { /** * Adds a SemanticUI color class to the icon. */ iconColor?: ColorType; /** * Icon component */ iconComponent?: any; /** * Adds a SemanticUI name class to the icon. */ name: string; } export class IconButton extends React.Component<IconButtonProps, any> { } // <LabeledButton /> export interface LabeledButtonProps extends ButtonProps { /** * Label position, default to right * @default "right" */ labeled?: "left" | "right" | string; /** * Type of label, could be text label or icon * @default "text" */ labelType?: "text" | "icon" | string; /** * Label, if given string will be used as label text or icon name (if labelType is icon). */ label: string; /** * Label component. Default will be Icon for labelType icon and Label for labelType label */ labelComponent?: any; } export class LabeledButton extends React.Component<LabeledButtonProps, any> { } // <SocialButton /> export interface SocialButtonProps extends ButtonProps { /** * Adds a SemanticUI name class to the icon. */ name: string; } export class SocialButton extends React.Component<SocialButtonProps, any> { } // <Divider /> export interface DividerProps extends BaseProps { /** * Content segment vertically or horizontally */ aligned?: "horizontal" | "vertical"; /** * A divider can clear the contents above it */ clearing?: boolean; /** * Formats divider as header-like (taking less space and don't capitalize content) */ header?: boolean; /** * A hidden divider divides content without creating a dividing line */ hidden?: boolean; /** * A divider can have its colors inverted */ inverted?: boolean; /** * Divider spacing */ spacing?: "fitted" | "padded"; } export class Divider extends React.Component<DividerProps, any> { } // <Flag /> export interface FlagProps extends BaseProps { /** * The country code, name or alias of the flag */ name: string; } export class Flag extends React.Component<FlagProps, any> { } // <Header /> export interface HeaderProps extends BaseProps { /** * A header can have its text aligned to a side */ aligned?: "right" | "left" | "justified" | "center"; /** * A header can be attached to other content, like a segment */ attached?: "bottom" | "top" | boolean; /** * A header can be formatted with different colors */ color?: ColorType; /** * A header can show that it is inactive */ disabled?: boolean; /** * Header may be used as divider */ divider?: boolean; /** * dividing: can be formatted to divide itself from the content below it * block: can be formatted to appear inside a content block */ emphasis?: "dividing" | "block"; /** * A header can sit to the left or right of other content */ floated?: "right" | "left"; /** * Icon name for header. This will turn header into icon header (ui icon header) */ icon?: string; /** * Override icon component */ iconComponent?: any; /** * A header can have its colors inverted for contrast */ inverted?: boolean; /** * May be used as menu item */ item?: boolean; /** * May have various sizes */ size?: SizeType; } export class Header extends React.Component<HeaderProps, any> { } // <SubHeader /> export interface SubHeaderProps extends HeaderProps { } export class SubHeader extends React.Component<SubHeaderProps, any> { } // <Icon /> export interface IconProps extends BaseProps { /** * An icon can be formatted to appear bordered */ bordered?: boolean; /** * An icon can be formatted to appear circular */ circular?: boolean; /** * An icon can be formatted with different colors */ color?: ColorType; /** * Render as corner icon if used in <Icons/> */ corner?: boolean; /** * Icon could be disabled or used as simple loader */ state?: "disabled" | "loading"; /** * An icon can be fitted, without any space to the left or right of it. */ fitted?: boolean; /** * An icon can be flipped */ flipped?: "horizontally" | "vertically"; /** * An icon can have its colors inverted for contrast */ inverted?: boolean; /** * Could be formatted as link */ link?: boolean; /** * Icon name */ name?: string; /** * An icon can be rotated */ rotated?: "clockwise" | "counterclockwise"; /** * Icon size */ size?: SizeType; } export class Icon extends React.Component<IconProps, any> { } export interface IconsProps extends BaseProps { /** * Size of icon group */ size?: SizeType; } export class Icons extends React.Component<IconsProps, any> { } // <Image /> export interface ImageProps extends BaseProps { // Standard image html attributes /** * Specifies an alternate text for an image */ alt?: string; /** * Specifies the height of an image */ height?: number; /** * Specifies the width of an image */ width?: number; /** * An image can specify its vertical alignment */ aligned?: "top" | "middle" | "bottom"; /** * An image may be formatted to appear inline with text as an avatar */ avatar?: boolean; /** * An image may include a border to emphasize the edges of white or transparent content */ bordered?: boolean; /** * An image can appear centered in a content block */ centered?: boolean; /** * An image can take up the width of its container */ fluid?: boolean; /** * An image can sit to the left or right of other content */ floated?: "right" | "left"; /** * An image may appear at different sizes */ size?: SizeType; /** * An image can specify that it needs an additional spacing to separate it from nearby content */ spaced?: "right" | "left" | boolean; /** * Image src */ src: string; /** * Image shape */ shape?: "circular" | "rounded"; /** * Image state, could be disabled or hidden */ state?: "disabled" | "hidden" | "visible"; /** * Wrap image component under other component, for example <a/> or <div/> * In this case this component will receive image classes instead * @default false */ wrapComponent?: boolean | any; } export class Image extends React.Component<ImageProps, any> { } // <Images /> export interface ImagesProps extends BaseProps { /** * Images size */ size?: SizeType; } export class Images extends React.Component<ImagesProps, any> { } // <Input /> export interface InputProps extends BaseProps { // Standard <input> html attributes /** * Specifies whether an <input> element should have autocomplete enabled */ autoComplete?: "on" | "off"; /** * Specifies that an <input> element should automatically get focus when the page loads */ autoFocus?: boolean; /** * Specifies the maximum value for an <input> element */ max?: number | string; /** * Specifies the maximum number of characters allowed in an <input> element */ maxLength?: number; /** * Specifies a minimum value for an <input> element */ min?: number | string; /** * Specifies the name of an <input> element */ name?: string; /** * Specifies a regular expression that an <input> element's value is checked against */ pattern?: string; /** * Specifies the type <input> element to display */ type?: string; // React-specific stuff /** * Default value */ defaultValue?: any; /** * Read only */ readOnly?: boolean; /** * Action component */ actionComponent?: any; /** * Action position */ actionPosition?: "left" | "right"; /** * An input can take the size of its container */ fluid?: boolean; /** * Render icon */ icon?: string | boolean; /** * Icon position */ iconPosition?: "left" | "right"; /** * Pass custom icon component */ iconComponent?: any; /** * Inverted input */ inverted?: boolean; /** * Render label for input */ label?: string; /** * Pass custom label component */ labelComponent?: any; /** * Label position */ labelPosition?: "left" | "right" | "left corner" | "right corner"; /** * Input placeholder */ placeholder?: string; /** * Input size */ size?: SizeType; /** * Input state */ state?: "focus" | "loading" | "disabled" | "error" | Array<"focus" | "loading" | "disabled" | "error">; /** * Render transparent input */ transparent?: boolean; /** * Input value */ value?: string; } export class Input extends React.Component<InputProps, any> { } // <List /> export interface ListProps extends BaseProps { /** * Controls content alignment for all items in list */ aligned?: "top" | "middle" | "bottom"; /** * A list can animate to set the current item apart from the list */ animated?: boolean; /** * Cell type */ celled?: "divided" | boolean; /** * Controls content floating for all items in list */ floated?: "right" | "left"; /** * A list can be formatted to have items appear horizontally */ horizontal?: boolean; /** * A list can be inverted to appear on a dark background */ inverted?: boolean; /** * A list can be specially formatted for navigation links */ link?: boolean; /** * A list can relax its padding to provide more negative space */ relaxed?: boolean; /** * A selection list formats list items as possible choices */ selection?: boolean; /** * A list can vary in size */ size?: SizeType; /** * Type of the list * Bulleted: mark items with a bullet * Ordered: mark items with a number */ type?: "bulleted" | "ordered"; } export class List extends React.Component<ListProps, any> { } export interface ListItemProps extends BaseProps { /** * Mark item as active. Valid only for link list */ active?: boolean; /** * Content alignment */ contentAligned?: "top" | "middle" | "bottom"; /** * Image/Icon name */ image?: string; /** * Type of image/icon */ imageType?: "image" | "icon"; /** * Image/Icon component. Override to tune */ imageComponent?: any; /** * Right floated content component. If not provided, then right floated content will not be rendered */ rightFloatedComponent?: any; } export class ListItem extends React.Component<ListItemProps, any> {} // <Loader /> export interface LoaderProps extends BaseProps { /** * Loaders can appear inline centered with content */ centered?: boolean; /** * Loaders can appear inline with content */ inline?: boolean; /** * Loaders can have their colors inverted. */ inverted?: boolean; /** * Loaders can have different sizes */ size?: SizeType; /** * Loader state */ state?: "active" | "indeterminate" | "disabled"; /** * A loader can contain text */ text?: boolean; } export class Loader extends React.Component<LoaderProps, any> { } // <Rail /> export interface RailProps extends BaseProps { /** * A rail can appear attached to the main viewport */ attached?: boolean; /** * A rail can appear closer to the main viewport */ close?: boolean | "very"; /** * A rail can create a division between itself and a container */ dividing?: boolean; /** * A rail can be presented on the left or right side of a container */ floated: "right" | "left"; /** * A rail can attach itself to the inside of a container */ internal?: boolean; /** * A rail can have different sizes */ size?: SizeType; } export class Rail extends React.Component<RailProps, any> { } // <Reveal /> export interface RevealProps extends BaseProps { active?: boolean; circular?: boolean; disabled?: boolean; fade?: boolean; image?: boolean; instant?: boolean; move?: "right" | "up" | "down" | boolean; rotate?: "left" | boolean; size?: SizeType; type?: string; } export class Reveal extends React.Component<RevealProps, any> { } // <Segment /> export interface SegmentProps extends BaseProps { /** * A segment can have its text aligned to a side */ aligned?: "right" | "left" | "center"; /** * A segment can be attached to other content on a page */ attached?: "bottom" | "top" | boolean; /** * A basic segment has no special formatting */ basic?: boolean; /** * Blurring segment when used with dimmer */ blurring?: boolean; /** * A segment can clear floated content */ clearing?: boolean; /** * A segment can be colored */ color?: ColorType; /** * Container segment */ container?: boolean; /** * A segment may show its content is disabled */ disabled?: boolean; /** * A segment can be formatted to appear more or less noticeable */ emphasis?: "primary" | "secondary" | "tertiary"; /** * A segment can appear to the left or right of other content */ floated?: "right" | "left"; /** * A segment can have its colors inverted for contrast */ inverted?: boolean; /** * A segment may show its content is being loaded */ loading?: boolean; /** * Segment spacing */ spacing?: "fitted" | "padded"; /** * Segment type */ type?: "raised" | "stacked" | "piled"; /** * A vertical segment formats content to be aligned as part of a vertical group */ vertical?: boolean; /** * Segment zIndex */ zIndex?: number; } export class Segment extends React.Component<SegmentProps, any> { } // <Segments /> interface SegmentsProps extends BaseProps { /** * Compact segments */ compact?: boolean; /** * Horizontal segments */ horizontal?: boolean; /** * Inverted segments */ inverted?: boolean; /** * Type of segments */ type?: "raised" | "piled" | "stacked"; } export class Segments extends React.Component<SegmentsProps, any> { } // <Actions /> export interface ActionsProps extends BaseProps { } export class Actions extends React.Component<ActionsProps, any> { } // <Author /> export interface AuthorProps extends BaseProps { } export class Author extends React.Component<AuthorProps, any> { } // <Container /> export interface ContainerProps extends BaseProps { fluid?: boolean; aligned?: "right" | "left" | "justified" | "center"; } export class Container extends React.Component<ContainerProps, any> { } // <Content /> export interface ContentProps extends BaseProps { active?: boolean; aligned?: string; extra?: boolean; floated?: string | boolean; hidden?: boolean; meta?: boolean; visible?: boolean; image?: boolean; } export class Content extends React.Component<ContentProps, any> { } // <Date /> export interface DateProps extends BaseProps { } export class Date extends React.Component<DateProps, any> { } // <Description /> export interface DescriptionProps extends BaseProps { hidden?: boolean; visible?: boolean; } export class Description extends React.Component<DescriptionProps, any> { } // <Meta /> export interface MetaProps extends BaseProps { } export class Meta extends React.Component<MetaProps, any> { } // <Summary /> export interface SummaryProps extends BaseProps { } export class Summary extends React.Component<SummaryProps, any> { } // <Text /> export interface TextProps extends BaseProps { extra?: boolean; } export class Text extends React.Component<TextProps, any> { } // <Field /> export interface FieldProps extends BaseProps { /** * Grouped field */ grouped?: boolean; /** * A field can have its label next to instead of above it. */ inline?: boolean; /** * Field label */ label?: string; /** * A field can show that input is mandatory */ required?: boolean; /** * Field state */ state?: "disabled" | "error"; /** * Field width in columns */ width?: number; } export class Field extends React.Component<FieldProps, any> { } // <Fields /> export interface FieldsProps extends BaseProps { /** * Fields can have their widths divided evenly */ fluid?: boolean; /** * Multiple fields may be inline in a row */ inline?: boolean; /** * Fields can show related choices */ grouped?: boolean; /** * Fields can automatically divide fields to be equal width */ equalWidth?: boolean; } export class Fields extends React.Component<FieldsProps, any> { } // <Form /> export interface FormProps extends BaseProps { /** * A form on a dark background may have to invert its color scheme */ inverted?: boolean; /** * If a form is in loading state, it will automatically show a loading indicator. */ loading?: boolean; /** * A form can vary in size */ size?: SizeType | any; /** * Form state */ state?: "success" | "error" | "warning"; /** * Forms can automatically divide fields to be equal width */ equalWidth?: boolean; } export class Form extends React.Component<FormProps, any> { } // <Grid /> export interface GridProps extends BaseProps { /** * Horizontal content alignment */ aligned?: "right" | "left" | "center"; /** * Center columns */ centered?: boolean; /** * Divide rows into cells */ celled?: "internally" | boolean; /** * Grid column count */ columns?: number; /** * Add container class, i.e. ui grid container */ container?: boolean; /** * Add dividers between ros */ divided?: "vertically" | "internally" | boolean; /** * Double column width on tablet and mobile sizes */ doubling?: boolean; /** * Automatically resize elements to split the available width evently */ equal?: boolean; /** * Preserve gutters on first and las columns */ padded?: "horizontally" | "vertically" | boolean; /** * Increase size of gutters */ relaxed?: "very" | boolean; /** * Reverse the order of columns or rows by device */ reversed?: "mobile" | "mobile vertically" | "tablet" | "tablet vertically" | "computer" | "computer vertically"; /** * Automatically stack rows into single columns on mobile devices */ stackable?: boolean; /** * Vertical content alignment */ valigned?: "top" | "middle" | "bottom"; } export class Grid extends React.Component<GridProps, any> { } type DeviceVisibility = "mobile" | "tablet" | "computer" | "large screen" | "widescreen"; // <Column /> export interface ColumnProps extends BaseProps { /** * Horizontal content alignment */ aligned?: "right" | "left" | "center"; /** * Float to the right or left edge of the row */ floated?: "right" | "left"; /** * Only visible for types. Could be single type string or array, i.e. only={["mobile","tablet"]} */ only?: DeviceVisibility | DeviceVisibility[]; /** * Column color */ color?: ColorType; /** * Column width for all device types */ width?: number; /** * Column width for mobile */ mobileWidth?: number; /** * Column width for tablet */ tabletWidth?: number; /** * Column width for computer */ computerWidth?: number; /** * Column width for large screens */ largeScreenWidth?: number; /** * Column width for wide screens */ wideScreenWidth?: number; /** * Vertical content alignment */ valigned?: "top" | "middle" | "bottom"; } export class Column extends React.Component<ColumnProps, any> { } // <Row /> export interface RowProps extends BaseProps { /** * Horizontal content alignment */ aligned?: "right" | "left" | "justified" | "center"; /** * Center columns in row */ centered?: boolean; /** * Double column width on tablet and mobile sizes */ doubling?: boolean; /** * Automatically resize elements to split the available width evently */ equal?: boolean; /** * Only visible for types. Could be single type string or array, i.e. only={["mobile","tablet"]} */ only?: DeviceVisibility | DeviceVisibility[]; /** * Specify row columns count */ columns?: number; /** * Stretch content to take up the entire column height */ stretched?: boolean; /** * Row color */ color?: ColorType; /** * Justified content fits exactly inside the grid column, taking up the entire width from one side to the other */ justified?: boolean; /** * Vertical content alignment */ valigned?: "top" | "middle" | "bottom"; } export class Row extends React.Component<RowProps, any> { } // <Message /> export interface MessageProps extends BaseProps { /** * A message can be formatted to attach itself to other content */ attached?: "bottom" | "top" | boolean; /** * A message can be formatted to be different colors */ color?: ColorType; /** * A message can only take up the width of its content. */ compact?: boolean; /** * A message can float above content that it is related to */ floating?: boolean; /** * A message can be hidden */ hidden?: boolean; /** * A message can contain an icon. If message contain icon as first child then it will be set automatically, * unless you provide it explicitly */ icon?: boolean; /** * A message can have different sizes */ size?: SizeType; /** * Emphasis */ emphasis?: "success" | "error" | "info" | "warning" | "positive" | "negative"; /** * Message is visible */ visible?: boolean; } export class Message extends React.Component<MessageProps, any> { } // <Table /> export interface TableProps extends BaseProps { /** * A table header, row, or cell can adjust its text alignment */ aligned?: "top" | "bottom"; /** * A table can reduce its complexity to increase readability. */ basic?: "very" | boolean; /** * A table may be divided each row into separate cells */ celled?: boolean; /** * A cell can be collapsing so that it only uses as much space as required */ collapsing?: boolean; /** * A table can be given a color to distinguish it from other tables. */ color?: ColorType; /** * A table can specify its column count to divide its content evenly */ columns?: number; /** * A table may sometimes need to be more compact to make more rows visible at a time */ compact?: boolean | "very"; definition?: boolean; /** * A table can use table-layout: fixed a special faster form of table rendering that does not resize table cells based on content. */ fixed?: boolean; /** * A table's colors can be inverted */ inverted?: boolean; /** * A table may sometimes need to be more padded for legibility */ padded?: "very" | boolean; /** * A table can have its rows appear selectable */ selectable?: boolean; /** * A table can specify that its cell contents should remain on a single line, and not wrap. */ singleLine?: boolean; /** * A table can also be small or large */ size?: SizeType; /** * A table may allow a user to sort contents by clicking on a table header. * NOTE: You need to set "sorted descending"/"sorted ascending" class names for corresponding <th> element */ sortable?: boolean; /** * A table can specify how it stacks table content responsively */ stackable?: { computer?: boolean; mobile?: boolean; tablet?: boolean; }; /** * A table can stripe alternate rows of content with a darker color to increase contrast */ striped?: boolean; /** * A table can be formatted to display complex structured data */ structured?: boolean; /** * Reverse of stackable */ unstackable?: { computer?: boolean; mobile?: boolean; tablet?: boolean; }; /** * A table header, row, or cell can adjust its vertical alignment */ valigned?: "center" | "right"; /** * Table width in grid columns */ width?: number; } export class Table extends React.Component<TableProps, any> { } // <Td /> export interface TdProps extends BaseProps { // Default HTML5 attributes /** * Specifies the number of columns a cell should span */ colSpan?: number; /** * Sets the number of rows a cell should span */ rowSpan?: number; /** * Cell text alignment */ aligned?: "right" | "left" | "center"; /** * A cell can be collapsing so that it only uses as much space as required */ collapsing?: boolean; /** * A table cell can be selectable */ selectable?: boolean; /** * Content should remain on a single line, and not wrap. */ singleLine?: boolean; /** * Cell emphasis */ emphasis?: "negative" | "positive" | "error" | "warning"; /** * Vertical cell alignment */ valigned?: "top" | "bottom" | "middle"; } export class Td extends React.Component<TdProps, any> { } // <Tr /> export interface TrProps extends TdProps { } export class Tr extends React.Component<TrProps, any> { } // <BreadcrumbDivider/> export interface BreadcrumbDividerProps extends BaseProps { /** * Icon divider */ icon?: string; } export class BreadcrumbDivider extends React.Component<BreadcrumbDividerProps, any> {} // <BreadcrumbSection /> export interface BreadcrumbSectionProps extends BaseProps { /** * Section may be active */ active?: boolean; } export class BreadcrumbSection extends React.Component<BreadcrumbSectionProps, any> {} // <Breadcrumb /> export interface BreadcrumbProps extends BaseProps { /** * A breadcrumb can vary in size */ size?: SizeType; } export class Breadcrumb extends React.Component<BreadcrumbProps, any> {} // <Card /> export interface CardProps extends BaseProps { centered?: boolean; col?: string; color?: ColorType; doubling?: string; fluid?: boolean; link?: boolean; } export class Card extends React.Component<CardProps, any> { } // <Cards /> export interface CardsProps extends BaseProps { link?: boolean; } export class Cards extends React.Component<CardsProps, any> { } // <Comment /> export interface CommentProps extends BaseProps { } export class Comment extends React.Component<CommentProps, any> { } // <Comments /> export interface CommentsProps extends BaseProps { collapsed?: boolean; minimal?: boolean; threaded?: boolean; } export class Comments extends React.Component<CommentsProps, any> { } // <Feed /> export interface FeedProps extends BaseProps { size?: SizeType; } export class Feed extends React.Component<FeedProps, any> { } // <Event /> export interface EventProps extends BaseProps { } export class Event extends React.Component<EventProps, any> { } // <Item /> export interface ItemProps extends BaseProps { /** * Item image */ image?: string; /** * Vertical alignment of content */ contentAligned?: "top" | "middle" | "bottom"; } export class Item extends React.Component<ItemProps, any> { } // <Items /> export interface ItemsProps extends BaseProps { /** * Items can be divided to better distinguish between grouped content */ divided?: boolean; /** * An item can be formatted so that the entire contents link to another page */ link?: boolean; /** * A group of items can relax its padding to provide more negative space */ relaxed?: any; } export class Items extends React.Component<ItemsProps, any> { } // <Menu /> export interface MenuProps extends BaseProps { /** * A menu may be attached to other content segments */ attached?: "top" | "bottom"; /** * A menu item or menu can have no borders */ borderless?: boolean; /** * Use equal width for menu items */ even?: boolean; /** * A menu item or menu can remove element padding, vertically or horizontally */ fitted?: "horizontally" | "vertically" | boolean; /** * A menu can be fixed to a side of its context */ fixed?: "top" | "bottom" | "left" | "right" | boolean; /** * A vertical menu may take the size of its container. (A horizontal menu does this by default) */ fluid?: boolean; /** * Float left or right */ floated?: "right" | "left"; /** * A menu can have colors */ color?: ColorType; /** * A menu may have its colors inverted to show greater contrast */ inverted?: boolean; /** * Current menu active value. */ menuValue?: number | string | Array<number | string>; /** * Callback for menu item click (regardless active or not active) * @param value * @param event */ onMenuItemClick?: (value: string | number, event: React.MouseEvent<any>) => void; /** * Callback for active item change. Will not be fired if menuValue was omitted * Will pass new menuValue or array of new menuValue * If all items were unselected would pass null if menuValue is single value or empty array if menuValue is array * @param value */ onMenuChange?: (value: string | number | Array<string | number> | null) => void; /** * A pagination menu is specially formatted to present links to pages of content */ pagination?: boolean; /** * A menu can point to show its relationship to nearby content */ pointing?: boolean; /** * A menu can adjust its appearance to de-emphasize its contents */ secondary?: boolean; /** * A menu can be formatted to show tabs of information */ tabular?: boolean; /** * A menu can be formatted for text content */ text?: boolean; /** * Menu active value */ vertical?: boolean; } export class Menu extends React.Component<MenuProps, any> { } // <MenuItem /> export interface MenuItemProps extends BaseProps { /** * Is item active */ active?: boolean; /** * Is item disabled */ disabled?: boolean; /** * Item color */ color?: ColorType; /** * Item value */ menuValue?: number | string; /** * Click callback */ onClick?: (menuValue: number | string, event: React.MouseEvent<any>) => void; } export class MenuItem extends React.Component<MenuItemProps, any> { } // <Statistic /> export interface StatisticProps extends BaseProps { /** * A string or number that represents the value of statistic */ value?: string | number; /** * A string or number that represents the label of a statistic */ label?: string | number; /** * A statistic can present its measurement horizontally */ horizontal?: boolean; /** * A SemanticUI color class. */ color?: ColorType; /** * Styles the component for a dark background. */ inverted?: boolean; /** * Forces to component to float left or right. */ floated?: "right" | "left"; /** * Adds a SemanticUI size class. */ size?: SizeType; } export class Statistic extends React.Component<StatisticProps, any> {} export interface StatisticsProps extends BaseProps { even?: boolean; color?: ColorType; size?: SizeType; } export class Statistics extends React.Component<StatisticsProps, any> {} export interface ValueProps extends BaseProps { text?: boolean; } export class Value extends React.Component<ValueProps, any> {} // Dropdown base interface export interface DropdownBaseProps extends BaseProps { /** * Indicates status of dropdown. true for opened, false for closed */ active?: boolean; /** * A compact dropdown has no minimum width */ compact?: boolean; /** * A disabled dropdown menu or item does not allow user interaction */ disabled?: boolean; /** * An errored dropdown can alert a user to a problem */ error?: boolean; /** * A dropdown can take the full width of its parent */ fluid?: boolean; /** * A dropdown can be formatted to appear inline in other content */ inline?: boolean; /** * A dropdown menu can appear to be floating below an element. */ floating?: boolean; /** * A dropdown can show that it is currently loading data */ loading?: boolean; /** * A dropdown can be formatted so that its menu is pointing */ pointing?: "left" | "right" | "top left" | "top right" | "bottom left" | "bottom right" | boolean; /** * A dropdown can have its menu scroll */ scrolling?: boolean; } // <Dropdown /> export interface DropdownProps extends DropdownBaseProps { } export class Dropdown extends React.Component<DropdownProps, any> { } // <DropdownMenu /> export interface DropdownMenuProps extends DropdownBaseProps, AnimationProps { /** * Active/Close menu */ active?: boolean; /** * Menu icon */ icon?: string; /** * Menu label */ label?: string; /** * Specify component to be used as Menu. * Usually is should be menu but with custom options applied (for example inverted). * DropdownMenu will pass some props to your Menu component, so you're responsive for passing it down to the level */ menuComponent?: any; /** * Menu active value */ menuValue?: number | string | Array<number | string>; /** * Callback for active item change. Will not be fired if menuValue was omitted * Will pass new menuValue or array of new menuValue * If all items were unselected would pass null if menuValue is single value or empty array if menuValue is array */ onMenuChange?: (value?: number | string | Array<number | string> | null) => void; /** * Callback for menu item click */ onMenuItemClick?: (value?: number | string) => void; /** * Callback will be called when menu wants to be closed (for ex. from outside click) */ onRequestClose?: () => void; } export class DropdownMenu extends React.Component<DropdownMenuProps, any> { } // <Option /> export interface OptionProps extends ItemProps { value: string|number; selected?: boolean; } export class Option extends React.Component<OptionProps, any> { } // <Select /> export interface SelectProps extends DropdownBaseProps, AnimationProps { /** * Should be dropdown opened */ active?: boolean; /** * Name for dropdown input */ name?: string; /** * Icon name for dropdown */ icon?: string; /** * String used as placeholder if dropdown has no selected value * Will be grayed (<div class="default text">) if dropdown is selection * or normally displayed (<div class="text">) otherwise */ placeholder?: string; /** * Searchable dropdown */ search?: boolean; /** * Search glyph width */ searchGlyphWidth?: number; /** * Ignore case when performing search */ searchIgnoreCase?: boolean; /** * Search box position */ searchPosition?: "dropdown" | "menu"; /** * Search header, valid only for searchPosition="menu" */ searchHeader?: string; /** * Specify message which will be displayed when search has no results */ searchNoResultsMessage?: string; /** * Specify message which will be displayed when search has no results and allowAdditions enabled */ allowAdditionsMessage?: string; /** * Search string */ searchString?: string; /** * Selected value */ selected?: Array<string | number>; /** * Behave dropdown as HTML select * @default true */ selection?: boolean; /** * Allow multiple selection */ multiple?: boolean; /** * Allow to add custom options */ allowAdditions?: boolean, /** * Callback will be called when current selected value was changed. * Will pass array of new selected values as first param and total options count as second */ onSelectChange?: (newValue: Array<string | number>, totalOptionsCount: number) => void; /** * Callback will be called when selection dropdown wants to be closed. For now only for outside of dropdown clicks */ onRequestClose?: () => void; /** * Callback will be called when search string is being changed. You probably just need to pass it back to component */ onSearchStringChange?: (newSearch: string) => void; } export class Select extends React.Component<SelectProps, any> { } // <Checkbox /> export interface CheckboxProps extends BaseProps { /** * Apply additional class name to to the label */ labelClassName?: string; /** * State checked */ checked?: boolean; /** * A fitted checkbox does not leave padding for a label */ fitted?: boolean; /** * Does not allow user interaction */ disabled?: boolean; /** * Attr name */ name?: string; /** * Callback handler to click checkbox */ onClick?: React.MouseEventHandler<HTMLElement>; /** * It does disabled, but does not allow user interaction */ readOnly?: boolean; /** * Checkbox - appearance */ type?: "default" | "radio" | "toggle" | "slider"; } export class Checkbox extends React.Component<CheckboxProps, any> { } // <CheckboxFields /> export interface CheckboxFieldsProps extends BaseProps { disabled?: boolean; name: string; radio?: boolean; readOnly?: boolean; type: "grouped" | "inline" } export class CheckboxFields extends React.Component<CheckboxFieldsProps, any> { } // <Dimmer /> export interface DimmerProps extends BaseProps, AnimationProps { /** * Hide/Display dimmer */ active?: boolean; /** * Inverted dimmer */ inverted?: boolean; /** * Page dimmer. Doesn't require dimmable section */ page?: boolean; /** * Disables auto-wrapping child contents into <Content> */ noWrapChildren?: boolean; } export class Dimmer extends React.Component<DimmerProps, any> { } // <Dimmable /> export interface DimmableProps extends BaseProps { blurring?: boolean; dimmed?: boolean; } export class Dimmable extends React.Component<DimmableProps, any> { } // <Popup /> export interface PopupProps extends BaseProps, AnimationProps { /** * Basic popup variation */ basic?: boolean; /** * True to display the popup. If false will be hidden */ active?: boolean; /** * Auto position popup when needed */ autoPosition?: boolean; /** * Fluid popup */ fluid?: boolean; /** * No maximum width and continue to flow to fit its content */ flowing?: boolean; /** * Offset for distance of popup from element */ distanceAway?: number; /** * Use this position when element fails to fit on screen in all tried positions * If omitted, the last tried position will be used instead */ lastResortPosition?: string; /** * Inverted popup */ inverted?: boolean; /** * Offset in pixels from calculated position */ offset?: number; /** * Callback when popup wants to be closed (i.e. when offscreen or clicked outside) */ onRequestClose?: () => void; /** * When auto-positioning popup use opposite direction or adjacent as next position */ prefer?: "adjacent|opposite"; /** * If true will prevent clicking on the other elements */ preventElementClicks?: boolean; /** * Hide popup when target element scrolls off the screen */ requestCloseWhenOffScreen?: boolean; /** * Target element to apply popup */ target: any; /** * Popup position */ position?: "top left" | "top center" | "top right" | "right center" | "bottom right" | "bottom center" | "bottom left" | "left center"; /** * Popup size */ size?: "mini" | "tiny" | "small" | "large" | "huge"; /** * Make content of popup wide */ wide?: boolean | string; /** * Overlay zIndex * @default 1000 */ zIndex?: number; } export class Popup extends React.Component<PopupProps, any> { } // <AccordionTitle /> export interface AccordionTitleProps extends BaseProps { /** * True for active (visible) accordion section. This is being set by Accordion itself */ active?: boolean; /** * Icon name */ icon?: string; /** * Allows to override icon component */ iconComponent?: any; /** * Accordion index. Used by Accordion component to control which content should be hidden/displayed */ index: number | string; } export class AccordionTitle extends React.Component<AccordionTitleProps, any> { } // <AccordionBody /> export interface AccordionBodyProps extends BaseProps { /** * True for active (visible) accordion section. This is being set by Accordion itself */ active?: boolean; } export class AccordionBody extends React.Component<AccordionBodyProps, any> { } // <Accordion /> export interface AccordionProps extends BaseProps { /** * Current visible content. Strings and numbers are accepted */ activeIndexes?: number[] | string[]; /** * Fluid accordion */ fluid?: boolean; /** * An accordion can be formatted to appear on dark backgrounds */ inverted?: boolean; /** * A styled accordion adds basic formatting */ styled?: boolean; /** * Callback when accordion wants to be changed */ onAccordionChange: (index: number | string) => void; } export class Accordion extends React.Component<AccordionProps, any> { } export interface ModalProps extends BaseProps, AnimationProps { /** * Should be modal visible */ active?: boolean; /** * A modal can reduce its complexity */ basic?: boolean; /** * A modal can use the entire size of the screen (width) */ fullscreen?: boolean; /** * Scrolling content. This flag will be set automatically if modal's content is too big */ scrolling?: boolean; /** * A modal can vary in size */ size?: string; /** * Dimmer variations */ dimmed?: "blurring" | "inverted" | "blurring inverted"; /** * Callback from outside modal click */ onRequestClose?: () => void; /** * Callback for modal opening */ onModalOpened?: () => void; /** * Callback for modal closing */ onModalClosed?: () => void; /** * Overlay zIndex * @default 1000 */ zIndex?: number; } export class Modal extends React.Component<ModalProps, any> { } // <TabMenu/> export interface TabMenuProps extends MenuProps {} export class TabMenu extends React.Component<TabMenuProps, any> {} // <Tab> export interface TabProps extends SegmentProps { /** * True if tab is active. Being set automatically */ active?: boolean; /** * True if display loading spinner */ loading?: boolean; /** * Tab index value. Should be equal to one of MenuItem value */ value: string | number; } export class Tab extends React.Component<TabProps, any> {} // <Tabs/> export interface TabsProps extends BaseProps { /** * Active tab value */ activeTab: string | number; /** * Current tab want's to be changed * @param tabValue */ onTabChange?: (tabValue: string | number) => void; } export class Tabs extends React.Component<TabsProps, any> {} // <Rating /> export interface RatingProps extends BaseProps { /** * Rating type */ type?: "default" | "star" | "heart"; /** * Rating size */ size?: SizeType; /** * Rating max value */ max?: number; /** * Rating value */ value?: number; /* * Rating change value callback */ onChange: (val: number) => void; } export class Rating extends React.Component<RatingProps, any> {}
the_stack
export interface OAuth2PopupFlowOptions<TokenPayload extends { exp: number }> { /** * REQUIRED * The full URI of the authorization endpoint provided by the authorization server. * * e.g. `https://example.com/oauth/authorize` */ authorizationUri: string; /** * REQUIRED * The client ID of your application provided by the authorization server. * * This client ID is sent to the authorization server using `authorizationUrl` endpoint in the * query portion of the URL along with the other parameters. * This value will be URL encoded like so: * * `https://example.com/oauth/authorize?client_id=SOME_CLIENT_ID_VALUE...` */ clientId: string; /** * REQUIRED * The URI that the authorization server will to redirect after the user has been authenticated. * This redirect URI *must* be a URI from *your application* and it must also be registered with * the authorization server. Some authorities call this a "callback URLs" or "login URLs" etc. * * > e.g. `http://localhost:4200/redirect` for local testing * > * > or `https://my-application.com/redirect` for prod * * This redirect URI is sent to the authorization server using `authorizationUrl` endpoint in the * query portion of the URL along with the other parameters. * This value will be URL encoded like so: * * `https://example.com/oauth/authorize?redirect_URI=http%3A%2F%2Flocalhost%2Fredirect...` */ redirectUri: string; /** * REQUIRED * A list permission separated by spaces that is the scope of permissions your application is * requesting from the authorization server. If the user is logging in the first time, it may ask * them to approve those permission before authorizing your application. * * > e.g. `openid profile` * * The scopes are sent to the authorization server using `authorizationUrl` endpoint in the * query portion of the URL along with the other parameters. * This value will be URL encoded like so: * * `https://example.com/oauth/authorize?scope=openid%20profile...` */ scope: string; /** * OPTIONAL * `response_type` is an argument to be passed to the authorization server via the * `authorizationUri` endpoint in the query portion of the URL. * * Most implementations of oauth2 use the default value of `token` to tell the authorization * server to start the implicit grant flow but you may override that value with this option. * * For example, Auth0--an OAuth2 authority/authorization server--requires the value `id_token` * instead of `token` for the implicit flow. * * The response type is sent to the authorization server using `authorizationUrl` endpoint in the * query portion of the URL along with the other parameters. * This value will be URL encoded like so: * * `https://example.com/oauth/authorize?response_type=token...` */ responseType?: string; /** * OPTIONAL * The key used to save the token in the given storage. The default key is `token` so the token * would be persisted in `localStorage.getItem('token')` if `localStorage` was the configured * `Storage`. */ accessTokenStorageKey?: string; /** * OPTIONAL * During `handleRedirect`, the method will try to parse `window.location.hash` to an object using * `OAuth2PopupFlow.decodeUriToObject`. After that object has been decoded, this property * determines the key to use that will retrieve the token from that object. * * By default it is `access_token` but you you may need to change that e.g. Auth0 uses `id_token`. */ accessTokenResponseKey?: string; /** * OPTIONAL * The storage implementation of choice. It can be `localStorage` or `sessionStorage` or something * else. By default, this is `localStorage` and `localStorage` is the preferred `Storage`. */ storage?: Storage; /** * OPTIONAL * The `authenticated` method periodically checks `loggedIn()` and resolves when `loggedIn()` * returns `true`. * * This property is how long it will wait between checks. By default it is `200`. */ pollingTime?: number; /** * OPTIONAL * Some oauth authorities require additional parameters to be passed to the `authorizationUri` * URL in order for the implicit grant flow to work. * * For example: [Auth0--an OAuth2 authority/authorization server--requires the parameters * `nonce`][0] * be passed along with every call to the `authorizationUri`. You can do that like so: * * ```ts * const auth = new OAuth2PopupFlow({ * authorizationUri: 'https://example.com/oauth/authorize', * clientId: 'foo_client', * redirectUri: 'http://localhost:8080/redirect', * scope: 'openid profile', * // this can be a function or static object * additionalAuthorizationParameters: () => { * // in prod, consider something more cryptographic * const nonce = Math.floor(Math.random() * 1000).toString(); * localStorage.setItem('nonce', nonce); * return { nonce }; * // `nonce` will now be encoded in the URL like so: * // https://example.com/oauth/authorize?client_id=foo_client...nonce=1234 * }, * // the token returned by Auth0, has the `nonce` in the payload * // you can add this additional check now * tokenValidator: ({ payload }) => { * const storageNonce = parseInt(localStorage.getItem('nonce'), 10); * const payloadNonce = parseInt(payload.nonce, 10); * return storageNonce === payloadNonce; * }, * }); * ``` * * [0]: https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce */ additionalAuthorizationParameters?: | (() => { [key: string]: string }) | { [key: string]: string }; /** * OPTIONAL * This function intercepts the `loggedIn` method and causes it to return early with `false` if * this function itself returns `false`. Use this function to validate claims in the token payload * or token. * * [For example: validating the `nonce`:][0] * * ```ts * const auth = new OAuth2PopupFlow({ * authorizationUri: 'https://example.com/oauth/authorize', * clientId: 'foo_client', * redirectUri: 'http://localhost:8080/redirect', * scope: 'openid profile', * // this can be a function or static object * additionalAuthorizationParameters: () => { * // in prod, consider something more cryptographic * const nonce = Math.floor(Math.random() * 1000).toString(); * localStorage.setItem('nonce', nonce); * return { nonce }; * // `nonce` will now be encoded in the URL like so: * // https://example.com/oauth/authorize?client_id=foo_client...nonce=1234 * }, * // the token returned by Auth0, has the `nonce` in the payload * // you can add this additional check now * tokenValidator: ({ payload }) => { * const storageNonce = parseInt(localStorage.getItem('nonce'), 10); * const payloadNonce = parseInt(payload.nonce, 10); * return storageNonce === payloadNonce; * }, * }); * ``` * * [0]: https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce */ tokenValidator?: (options: { payload: TokenPayload; token: string; }) => boolean; /** * OPTIONAL * A hook that runs in `tryLoginPopup` before any popup is opened. This function can return a * `Promise` and the popup will not open until it resolves. * * A typical use case would be to wait a certain amount of time before opening the popup to let * the user see why the popup is happening. */ beforePopup?: () => any | Promise<any>; /** * OPTIONAL * A hook that runs in `handleRedirect` that takes in the result of the hash payload from the * authorization server. Use this hook to grab more from the response or to debug the response * from the authorization URL. */ afterResponse?: (authorizationResponse: { [key: string]: string | undefined; }) => void; } export class OAuth2PopupFlow<TokenPayload extends { exp: number }> implements EventTarget { authorizationUri: string; clientId: string; redirectUri: string; scope: string; responseType: string; accessTokenStorageKey: string; accessTokenResponseKey: string; storage: Storage; pollingTime: number; additionalAuthorizationParameters?: | (() => { [key: string]: string }) | { [key: string]: string }; tokenValidator?: (options: { payload: TokenPayload; token: string; }) => boolean; beforePopup?: () => any | Promise<any>; afterResponse?: (authorizationResponse: { [key: string]: string | undefined; }) => void; private _eventListeners: { [type: string]: EventListenerOrEventListenerObject[]; }; constructor(options: OAuth2PopupFlowOptions<TokenPayload>) { this.authorizationUri = options.authorizationUri; this.clientId = options.clientId; this.redirectUri = options.redirectUri; this.scope = options.scope; this.responseType = options.responseType || 'token'; this.accessTokenStorageKey = options.accessTokenStorageKey || 'token'; this.accessTokenResponseKey = options.accessTokenResponseKey || 'access_token'; this.storage = options.storage || window.localStorage; this.pollingTime = options.pollingTime || 200; this.additionalAuthorizationParameters = options.additionalAuthorizationParameters; this.tokenValidator = options.tokenValidator; this.beforePopup = options.beforePopup; this.afterResponse = options.afterResponse; this._eventListeners = {}; } private get _rawToken() { return this.storage.getItem(this.accessTokenStorageKey) || undefined; } private set _rawToken(value: string | undefined) { if (value === null) return; if (value === undefined) return; this.storage.setItem(this.accessTokenStorageKey, value); } private get _rawTokenPayload() { const rawToken = this._rawToken; if (!rawToken) return undefined; const tokenSplit = rawToken.split('.'); const encodedPayload = tokenSplit[1]; if (!encodedPayload) return undefined; const decodedPayloadJson = window.atob( encodedPayload.replace('-', '+').replace('_', '/'), ); const decodedPayload = OAuth2PopupFlow.jsonParseOrUndefined<TokenPayload>( decodedPayloadJson, ); return decodedPayload; } /** * A simple synchronous method that returns whether or not the user is logged in by checking * whether or not their token is present and not expired. */ loggedIn() { const decodedPayload = this._rawTokenPayload; if (!decodedPayload) return false; if (this.tokenValidator) { const token = this._rawToken!; if (!this.tokenValidator({ payload: decodedPayload, token })) return false; } const exp = decodedPayload.exp; if (!exp) return false; if (new Date().getTime() > exp * 1000) return false; return true; } /** * Returns true only if there is a token in storage and that token is expired. Use this to method * in conjunction with `loggedIn` to display a message like "you need to *re*login" vs "you need * to login". */ tokenExpired() { const decodedPayload = this._rawTokenPayload; if (!decodedPayload) return false; const exp = decodedPayload.exp; if (!exp) return false; if (new Date().getTime() <= exp * 1000) return false; return true; } /** * Deletes the token from the given storage causing `loggedIn` to return false on its next call. * Also dispatches `logout` event */ logout() { this.storage.removeItem(this.accessTokenStorageKey); this.dispatchEvent(new Event('logout')); } /** * Call this method in a route of the `redirectUri`. This method takes the value of the hash at * `window.location.hash` and attempts to grab the token from the URL. * * If the method was able to grab the token, it will return `'SUCCESS'` else it will return a * different string. */ handleRedirect() { const locationHref = window.location.href; if (!locationHref.startsWith(this.redirectUri)) return 'REDIRECT_URI_MISMATCH'; const rawHash = window.location.hash; if (!rawHash) return 'FALSY_HASH'; const hashMatch = /#(.*)/.exec(rawHash); // this case won't happen because the browser typically adds the `#` always if (!hashMatch) return 'NO_HASH_MATCH'; const hash = hashMatch[1]; const authorizationResponse = OAuth2PopupFlow.decodeUriToObject(hash); if (this.afterResponse) { this.afterResponse(authorizationResponse); } const rawToken = authorizationResponse[this.accessTokenResponseKey]; if (!rawToken) return 'FALSY_TOKEN'; this._rawToken = rawToken; window.location.hash = ''; return 'SUCCESS'; } /** * supported events are: * * 1. `logout`–fired when the `logout()` method is called and * 2. `login`–fired during the `tryLoginPopup()` method is called and succeeds */ addEventListener(type: string, listener: EventListenerOrEventListenerObject) { const listeners = this._eventListeners[type] || []; listeners.push(listener); this._eventListeners[type] = listeners; } /** * Use this to dispatch an event to the internal `EventTarget` */ dispatchEvent(event: Event) { const listeners = this._eventListeners[event.type] || []; for (const listener of listeners) { const dispatch = typeof listener === 'function' ? listener : typeof listener === 'object' && typeof listener.handleEvent === 'function' ? listener.handleEvent.bind(listener) : () => {}; dispatch(event); } return true; } /** * Removes the event listener in target's event listener list with the same type, callback, and options. */ removeEventListener( type: string, listener: EventListenerOrEventListenerObject, ) { const listeners = this._eventListeners[type] || []; this._eventListeners[type] = listeners.filter((l) => l !== listener); } /** * Tries to open a popup to login the user in. If the user is already `loggedIn()` it will * immediately return `'ALREADY_LOGGED_IN'`. If the popup fails to open, it will immediately * return `'POPUP_FAILED'` else it will wait for `loggedIn()` to be `true` and eventually * return `'SUCCESS'`. * * Also dispatches `login` event */ async tryLoginPopup() { if (this.loggedIn()) return 'ALREADY_LOGGED_IN'; if (this.beforePopup) { await Promise.resolve(this.beforePopup()); } const additionalParams = typeof this.additionalAuthorizationParameters === 'function' ? this.additionalAuthorizationParameters() : typeof this.additionalAuthorizationParameters === 'object' ? this.additionalAuthorizationParameters : {}; const popup = window.open( `${this.authorizationUri}?${OAuth2PopupFlow.encodeObjectToUri({ client_id: this.clientId, response_type: this.responseType, redirect_uri: this.redirectUri, scope: this.scope, ...additionalParams, })}`, ); if (!popup) return 'POPUP_FAILED'; await this.authenticated(); popup.close(); this.dispatchEvent(new Event('login')); return 'SUCCESS'; } /** * A promise that does not resolve until `loggedIn()` is true. This uses the `pollingTime` * to wait until checking if `loggedIn()` is `true`. */ async authenticated() { while (!this.loggedIn()) { await OAuth2PopupFlow.time(this.pollingTime); } } /** * If the user is `loggedIn()`, the token will be returned immediate, else it will open a popup * and wait until the user is `loggedIn()` (i.e. a new token has been added). */ async token() { await this.authenticated(); const token = this._rawToken; if (!token) throw new Error('Token was falsy after being authenticated.'); return token; } /** * If the user is `loggedIn()`, the token payload will be returned immediate, else it will open a * popup and wait until the user is `loggedIn()` (i.e. a new token has been added). */ async tokenPayload() { await this.authenticated(); const payload = this._rawTokenPayload; if (!payload) throw new Error('Token payload was falsy after being authenticated.'); return payload; } /** * wraps `JSON.parse` and return `undefined` if the parsing failed */ static jsonParseOrUndefined<T = {}>(json: string) { try { return JSON.parse(json) as T; } catch (e) { return undefined; } } /** * wraps `setTimeout` in a `Promise` that resolves to `'TIMER'` */ static time(milliseconds: number) { return new Promise<'TIMER'>((resolve) => window.setTimeout(() => resolve('TIMER'), milliseconds), ); } /** * wraps `decodeURIComponent` and returns the original string if it cannot be decoded */ static decodeUri(str: string) { try { return decodeURIComponent(str); } catch { return str; } } /** * Encodes an object of strings to a URL * * `{one: 'two', buckle: 'shoes or something'}` ==> `one=two&buckle=shoes%20or%20something` */ static encodeObjectToUri(obj: { [key: string]: string }) { return Object.keys(obj) .map((key) => ({ key, value: obj[key] })) .map( ({ key, value }) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`, ) .join('&'); } /** * Decodes a URL string to an object of string * * `one=two&buckle=shoes%20or%20something` ==> `{one: 'two', buckle: 'shoes or something'}` */ static decodeUriToObject(str: string) { return str.split('&').reduce((decoded, keyValuePair) => { const [keyEncoded, valueEncoded] = keyValuePair.split('='); const key = this.decodeUri(keyEncoded); const value = this.decodeUri(valueEncoded); decoded[key] = value; return decoded; }, {} as { [key: string]: string | undefined }); } } export default OAuth2PopupFlow;
the_stack
import * as React from 'react'; import styles from './Minesweeper.module.scss'; import { IMinesweeperProps } from './IMinesweeperProps'; import { IMinesweeperState } from './IMinesweeperState'; import Tile from '../Tile/Tile'; import { FieldType as FieldType } from '../../../../enums/FieldType'; import { Coords } from '../../../../models/Coords'; import { TileInfo } from '../../../../models/TileInfo'; import { GameStatus } from '../../../../enums/GameStatus'; import Globals from '../../../../data/Globals'; import {IconButton, Icon, Callout, Dropdown, IDropdownOption} from 'office-ui-fabric-react'; import { GameMode } from '../../../../enums/GameMode'; import { GameDifficulty } from '../../../../enums/GameDifficulty'; import { DifficultySettings } from '../../../../models/DifficultySettings'; export default class Minesweeper extends React.Component<IMinesweeperProps, IMinesweeperState> { //#region Init private _timerRef: any = null; constructor(props) { super(props); const settings = Globals.DifficultySettings.Beginner; let highScoreMs = Number(localStorage.getItem(this.getHighScoreCacheKey(settings))); if(highScoreMs === 0){ highScoreMs = undefined; } let grid = this.initGrid(settings); this.state = { gameDifficulty: GameDifficulty.Beginner, gameMode: GameMode.Mine, gameStatus: GameStatus.Idle, grid, highScoreMs, nrMinesLeft: settings.nrMines, showHighScore: false, settings, timeMs: 0 }; } //#endregion //#region Render public render(): React.ReactElement<IMinesweeperProps> { return ( <div className={ styles.minesweeper }> {this.renderGameInfo()} {this.renderGrid()} {this.state.showHighScore && <Callout target={"#minesweeper_highScore"} onDismiss={this.toggleHighScore} ><div style={{padding: '5px'}}>{isNaN(this.state.highScoreMs) ? `No high score yet` : `Best time: ${this.state.highScoreMs / 1000}s`}</div></Callout>} </div> ); } private renderGameInfo(){ return( <div className={`${styles.grid} ${styles.gameInfo} ${styles[`difficulty_${GameDifficulty[this.state.gameDifficulty]}`]}`} dir={'ltr'}> <div className={styles.row} > <div className={styles.col}> <Dropdown options={[{key: GameDifficulty.Beginner, text: 'Beginner'}, {key: GameDifficulty.Intermediate, text: 'Intermediate'}, {key: GameDifficulty.Expert, text: 'Expert'}]} onChange={(e, d) => this.selectDifficulty(e, d)} selectedKey={this.state.gameDifficulty} styles={{root: {minWidth: '150px'}}}></Dropdown> </div> </div> <div className={styles.row} > <div className={styles.col}> <span className={styles.gameInfoSpans} title={"Time"}>{(this.state.timeMs / 1000).toFixed(1)} <Icon iconName={'clock'}/></span> <span className={styles.gameInfoSpans} title={"Mines left"}>{this.state.nrMinesLeft} <Icon iconName={'StarburstSolid'}/></span> </div> <div className={styles.col} dir={'rtl'}> <IconButton iconProps={Globals.Icons.Reset} onClick={this.reset} title={"Reset"}/> <IconButton iconProps={this.state.gameStatus === GameStatus.Won ? Globals.Icons.PlayerWon : Globals.Icons.HighScore} onClick={this.toggleHighScore} id={"minesweeper_highScore"} title={"High score"}/> <IconButton iconProps={this.state.gameMode === GameMode.Mine ? Globals.Icons.Mine: Globals.Icons.Flag} onClick={this.toggleMode} title={this.state.gameMode === GameMode.Mine ? "Mine mode":"Flag mode"}/> </div> </div> </div> ); } private renderGrid(){ return( <table className={styles.table}> <tbody> {this.state.grid.map((row: TileInfo[], rowIndex) =>{ return ( <tr key={rowIndex}> {row.map((tileInfo: TileInfo, colIndex) => { return ( <td key={`${rowIndex}_${colIndex}`}> <Tile tileInfo={tileInfo} onClick={this.tileClick} onContextMenu={this.tileRightClick} /> </td> ); })} </tr> ); })} </tbody> </table> ); } //#endregion //#region Events private tileClick = (coord: Coords): void => { if(this.shouldDiscoverSurrounding(coord)){ this.discoverSurrounding(coord); } else if(this.state.gameMode === GameMode.Flag){ this.plantFlag(coord); } else{ this.discover(coord); } } private tileRightClick = (coord: Coords, e: React.MouseEvent): void =>{ e.preventDefault(); if(this.shouldDiscoverSurrounding(coord)){ this.discoverSurrounding(coord); } else if(this.state.gameMode === GameMode.Flag){ this.discover(coord); } else{ this.plantFlag(coord); } } private toggleMode = (): void => { this.setState({ gameMode: this.state.gameMode === GameMode.Mine ? GameMode.Flag : GameMode.Mine }); } private selectDifficulty = (e: React.FormEvent, option: IDropdownOption): void => { let settings = Globals.DifficultySettings.Beginner; switch(option.key){ case GameDifficulty.Intermediate: settings = Globals.DifficultySettings.InterMediate; break; case GameDifficulty.Expert: settings = Globals.DifficultySettings.Expert; break; } let highScoreMs = Number(localStorage.getItem(this.getHighScoreCacheKey(settings))); if(highScoreMs === 0){ highScoreMs = undefined; } this.setState({ gameDifficulty: +option.key, highScoreMs, settings, }, () => this.reset()); } private reset = (): void => { let executeReset = true; if(this.state.gameStatus === GameStatus.Playing){ executeReset = window.confirm('Are you sure you want to reset the game?'); } if(executeReset){ clearInterval(this._timerRef); this.setState({ gameStatus: GameStatus.Idle, timeMs: 0, nrMinesLeft: this.state.settings.nrMines, grid: this.initGrid(this.state.settings) }); } } private toggleHighScore = (): void => { this.setState({ showHighScore: !this.state.showHighScore }); } private updateTimer(): void{ this.setState({ timeMs: this.state.timeMs + Globals.GeneralSettings.TimerIntervalMs }); } //#endregion //#region Game logic private initGrid(settings: DifficultySettings): TileInfo[][]{ let grid: TileInfo [][] = []; let minePositions: number [] = []; while(minePositions.length < settings.nrMines){ let pos = this.getRandomInt(settings.rows*settings.cols); if(minePositions.indexOf(pos) < 0){ minePositions.push(pos); } } for(let i = 0; i < settings.rows; i++){ grid[i] = []; for(let j = 0; j < settings.cols; j++){ let pos = i*settings.rows + j; let hasMine = minePositions.indexOf(pos) > -1; grid[i][j] = {coords: {row: i, col: j}, fieldType: FieldType.Unknown, hasMine}; } } return grid; } private discover(coord: Coords){ let grid = this.state.grid; let tile = grid[coord.row][coord.col]; let highScoreMs = this.state.highScoreMs; let nrMinesLeft = this.state.nrMinesLeft; switch(this.state.gameStatus){ case GameStatus.Idle: // first click starting the game while(tile.hasMine){ grid = this.initGrid(this.state.settings); tile = grid[coord.row][coord.col]; } this.setState({ gameStatus: GameStatus.Playing }, () => this._timerRef = setInterval(() => this.updateTimer(), Globals.GeneralSettings.TimerIntervalMs)); break; case GameStatus.GameOver: case GameStatus.Won: return; } if(tile.fieldType === FieldType.Number || tile.fieldType === FieldType.Empty || tile.fieldType === FieldType.Flag){ return; } if(tile.hasMine){ this.gameOver(grid, tile); return; } let closeMines = this.getSurroundingMines(grid, coord); if(closeMines > 0){ tile.closeMines = closeMines; tile.fieldType = FieldType.Number; } else{ tile.fieldType = FieldType.Empty; this.traverseEmptyTiles(grid, coord); } let playerWon = this.checkPlayerWon(grid); if(playerWon){ highScoreMs = this.playerWon(); } this.setState({ grid, gameStatus: playerWon ? GameStatus.Won : GameStatus.Playing, highScoreMs, nrMinesLeft, showHighScore: playerWon }); } private plantFlag(coord: Coords){ let grid = this.state.grid; let tile = grid[coord.row][coord.col]; let nrMinesLeft = this.state.nrMinesLeft; if( this.state.gameStatus !== GameStatus.Playing || (tile.fieldType !== FieldType.Unknown && tile.fieldType !== FieldType.Flag) ) { return; } if(tile.fieldType === FieldType.Flag){ tile.fieldType = FieldType.Unknown; nrMinesLeft++; } else{ if(nrMinesLeft === 0){ return; } tile.fieldType = FieldType.Flag; nrMinesLeft--; } this.setState({ grid, nrMinesLeft }); } private discoverSurrounding(coord){ let coordsToDiscover: Coords[] = []; let gameOver = false; Globals.GeneralSettings.DeltaCoords.forEach(deltaCoord => { if(this.isValidCoord(coord, deltaCoord)){ if(this.state.grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col].fieldType === FieldType.Unknown){ if(this.state.grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col].hasMine){ this.gameOver(this.state.grid, this.state.grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col]); gameOver = true; } coordsToDiscover.push({row: coord.row + deltaCoord.row, col: coord.col + deltaCoord.col}); } } }); if(!gameOver){ coordsToDiscover.forEach(c => { this.discover(c); }); } } private traverseEmptyTiles(grid: TileInfo[][], coord: Coords){ Globals.GeneralSettings.DeltaCoords.forEach(deltaCoord => { if(this.isValidCoord(coord, deltaCoord)){ let tile = grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col]; if(tile.fieldType === FieldType.Unknown || tile.fieldType === FieldType.Flag){ let closeMines = this.getSurroundingMines(grid, {row: coord.row + deltaCoord.row, col: coord.col + deltaCoord.col}); if(closeMines === 0){ tile.fieldType = FieldType.Empty; this.traverseEmptyTiles(grid, {row: coord.row + deltaCoord.row, col: coord.col + deltaCoord.col}); } else{ tile.fieldType = FieldType.Number; tile.closeMines = closeMines; } } } }); } private getSurroundingMines(grid: TileInfo[][], coord: Coords): number{ let surroundingMines = 0; Globals.GeneralSettings.DeltaCoords.forEach(deltaCoord => { if(this.isValidCoord(coord, deltaCoord)){ if(grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col].hasMine){ surroundingMines++; } } }); return surroundingMines; } private getSurroundingFlags(grid: TileInfo[][], coord: Coords): number{ let surroundingFlags = 0; Globals.GeneralSettings.DeltaCoords.forEach(deltaCoord => { if(this.isValidCoord(coord, deltaCoord)){ if(grid[coord.row + deltaCoord.row][coord.col + deltaCoord.col].fieldType === FieldType.Flag){ surroundingFlags++; } } }); return surroundingFlags; } private isValidCoord(coord: Coords, deltaCoord: Coords): boolean { let validCoords = true; if(coord.row + deltaCoord.row < 0 || coord.row + deltaCoord.row >= this.state.settings.rows){ validCoords = false; } if(coord.col + deltaCoord.col < 0 || coord.col + deltaCoord.col >= this.state.settings.cols){ validCoords = false; } return validCoords; } private shouldDiscoverSurrounding(coord: Coords): boolean{ let grid = this.state.grid; let tile = grid[coord.row][coord.col]; return tile.fieldType === FieldType.Number && this.getSurroundingMines(grid, coord) === this.getSurroundingFlags(grid, coord); } private checkPlayerWon(grid: TileInfo[][]): boolean{ let playerWon = true; grid.forEach(row => { row.forEach(t => { if(t.fieldType === FieldType.Unknown && t.hasMine === false){ playerWon = false; } }); }); return playerWon; } private playerWon(): number{ clearInterval(this._timerRef); let highScoreMs = this.state.highScoreMs; let timeMs = this.state.timeMs; if(this.state.highScoreMs && this.state.highScoreMs < timeMs){ // nothing } else{ localStorage.setItem(this.getHighScoreCacheKey(this.state.settings), timeMs.toString()); highScoreMs = timeMs; } return highScoreMs; } private gameOver(grid: TileInfo[][], tile: TileInfo){ grid.forEach(row => { row.forEach(t => { if(t.hasMine && t.fieldType !== FieldType.Flag){ t.fieldType = FieldType.Mine; } else if (!t.hasMine && t.fieldType === FieldType.Flag){ t.fieldType = FieldType.FlagMistake; } }); }); tile.fieldType = FieldType.MineExploded; clearInterval(this._timerRef); this.setState({ gameStatus: GameStatus.GameOver, grid }); } //#endregion //#region Helpers private getRandomInt(max: number): number{ return Math.floor(Math.random() * Math.floor(max)); } private getHighScoreCacheKey(settings: DifficultySettings): string{ return `${Globals.CacheKey.HighScore}_${settings.cols}x${settings.rows}`; } //#endregion }
the_stack
import React, { ReactElement, PropsWithChildren, PropsWithoutRef, RefAttributes, WeakValidationMap, ValidationMap } from 'react'; declare type Func = (...args: any) => any; interface Noop { (): any; [key: string]: any; } declare const templateElement: Noop; declare type Obj = Record<string, unknown>; declare type FuncMap = Record<string, Func | Obj | undefined>; declare type JSXElements = ReactElement<any, any> | null; declare function isTemplate(templateElement: any): templateElement is Template.EL; declare const Template: <Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any, T extends Template.Render<Arg1, Arg2, Arg3, Arg4, Arg5> = Template.Render>(props: { name?: T; children: T['__required']; }) => JSXElements; interface TemplateRender<Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any> { (arg1?: Arg1, arg2?: Arg2, arg3?: Arg3, arg4?: Arg4, arg5?: Arg5, ...args: any[]): JSXElements; render: (arg1?: Arg1, arg2?: Arg2, arg3?: Arg3, arg4?: Arg4, arg5?: Arg5, ...args: any[]) => JSXElements; __required(arg1: Arg1, arg2: Arg2, arg3: Arg3, arg4: Arg4, arg5: Arg5, ...args: any[]): JSXElements; /** * @deprecated Please use `render` */ template: (arg1?: Arg1, arg2?: Arg2, arg3?: Arg3, arg4?: Arg4, arg5?: Arg5, ...args: any[]) => JSXElements; } declare namespace Template { type Render<Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any> = TemplateRender<Arg1, Arg2, Arg3, Arg4, Arg5>; /** * @deprecated Please use `Template.Render` */ type Func<Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any> = Render<Arg1, Arg2, Arg3, Arg4, Arg5>; type EL = typeof templateElement; } declare const createTemplate: <U extends string[]>(...names: U) => (<Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any, T extends Template.Render<Arg1, Arg2, Arg3, Arg4, Arg5> = Template.Render<any, any, any, any, any>>(props: { name?: T | undefined; children: T["__required"]; }) => JSXElements) & Record<U[number], <Arg1 = any, Arg2 = any, Arg3 = any, Arg4 = any, Arg5 = any, T extends Template.Render<Arg1, Arg2, Arg3, Arg4, Arg5> = Template.Render<any, any, any, any, any>>(props: { name?: T | undefined; children: T["__required"]; }) => JSXElements>; declare type NoRef = 'noRef'; declare type SFCProps<Props = {}, EX = {}> = PropsWithChildren<Props> & { props: PropsWithChildren<Props>; /** * @deprecated Please use `props` */ originalProps: PropsWithChildren<Props>; } & EX; declare type PresetStatic<Props = {}> = Obj & { propTypes?: WeakValidationMap<Props>; contextTypes?: ValidationMap<any>; defaultProps?: Partial<Props>; displayName?: string; }; declare type ExtractOptions<T, Props = null> = T extends () => infer R ? R extends (Props extends null ? Obj : PresetStatic<Props>) ? R : never : T extends (Props extends null ? Obj : PresetStatic<Props>) ? T : unknown; declare type DefineComponent<Ref = NoRef, Props = {}, ReturnComponent = Ref extends NoRef ? React.FC<Props> : React.ForwardRefExoticComponent<PropsWithoutRef<Props> & RefAttributes<Ref>>, Origin = { Component: ReturnComponent; }> = { <Data extends Obj, InferStyles extends ExtractOptions<Styles>, InferStatic extends ExtractOptions<Static, Props>, InferEX extends ExtractOptions<EX, Props>, FR extends { styles: InferStyles; } & InferStatic & InferEX, Styles = {}, Static = {}, EX = {}>(options: { /** * Using the `Component function` to define actual component, example: * ```tsx * const App = sfc<{ user: string }>()({ * Component: (props) => { * useEffect(() => console.log(props.user), []); * return { user: props.user }; * }, * render: ({ data, styles: { Wrapper } }) => <Wrapper>{data.user}</Wrapper>, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ Component: Ref extends NoRef ? (props: SFCProps<Props, FR>, context?: any) => Data : (props: SFCProps<Props, FR>, ref: React.Ref<Ref>) => Data; /** * Using the `template function` to return JSX elements, example: * ```tsx * const App = sfc<{ user: string }>()({ * template: ({ data, styles: { Wrapper } }) => <Wrapper>{data.user}</Wrapper>, * Component: (props) => { * useEffect(() => console.log(props.user), []); * return { user: props.user }; * }, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ template?: <U extends Data>(args: { data: U; props: PropsWithChildren<Props>; } & FR, ...tmpls: Template.Render[]) => JSXElements; /** * Using the `render function` to return JSX elements, example: * ```tsx * const App = sfc<{ user: string }>()({ * Component: (props) => { * useEffect(() => console.log(props.user), []); * return { user: props.user }; * }, * render: ({ data, styles: { Wrapper } }) => <Wrapper>{data.user}</Wrapper>, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ render?: <U extends Data>(args: { data: U; props: PropsWithChildren<Props>; } & FR, ...tmpls: Template.Render[]) => JSXElements; /** * Using the `styles property or function` to define styles, you can use the most popular `CSS in JS` solutions. (e.g. `styled-components`, `Emotion`) */ styles?: Styles; /** * Using the `static property or function` to define any static members of a component, example: * ```tsx * const App = sfc<{ user: string }>()({ * Component: (props) => { * useEffect(() => console.log(props.user), []); * return { user: props.user || props.initialValue }; * }, * static: { initialValue: 'test user', defaultProps: { user: 'test' } }, * render: ({ data, styles: { Wrapper } }) => <Wrapper>{data.user}</Wrapper>, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ static?: Static; /** * @deprecated Please use `static` */ options?: Static; }, extensions?: EX): ReturnComponent & Origin & { template: { (data?: Partial<Data>): JSXElements; __componentData: Data; }; Render: (data?: Partial<Data>) => JSXElements; styles: InferStyles; } & ExtractOptions<Static, Props> & ExtractOptions<EX, Props>; <InferStyles extends ExtractOptions<Styles>, InferStatic extends ExtractOptions<Static, Props>, InferEX extends ExtractOptions<EX, Props>, FR extends { styles: InferStyles; } & InferStatic & InferEX, Styles = {}, Static = {}, EX = {}>(options: { /** * Using the `Component function` to define actual component, example: * ```tsx * const App = sfc<{ user: string }>()({ * Component: ({ user, styles: { Wrapper } }) => { * useEffect(() => console.log(user), []); * return <Wrapper>{user}</Wrapper>; * }, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ Component: Ref extends NoRef ? (props: SFCProps<Props, FR>, context?: any) => JSXElements : (props: SFCProps<Props, FR>, ref: React.Ref<Ref>) => JSXElements; /** * Using the `styles property or function` to define styles, you can use the most popular `CSS in JS` solutions. (e.g. `styled-components`, `emotion`) */ styles?: Styles; /** * Using the `static property or function` to define any static members of a component, example: * ```tsx * const App = sfc<{ user: string }>()({ * Component: (props) => { * useEffect(() => console.log(props.user), []); * return { user: props.user || props.initialValue }; * }, * static: { initialValue: 'test user', defaultProps: { user: 'test' } }, * render: ({ data, styles: { Wrapper } }) => <Wrapper>{data.user}</Wrapper>, * styles: { Wrapper: styled.div`font-size:14px` } * }); * ``` */ static?: Static; /** * @deprecated Please use `static` */ options?: Static; }, extensions?: EX): ReturnComponent & Origin & { styles: InferStyles; } & ExtractOptions<Static, Props> & ExtractOptions<EX, Props>; <InferEX extends ExtractOptions<EX, Props>, EX = {}>(component: Ref extends NoRef ? (props: SFCProps<Props, InferEX>, context?: any) => JSXElements : (props: SFCProps<Props, InferEX>, ref: React.Ref<Ref>) => JSXElements, extensions?: EX): ReturnComponent & Origin & ExtractOptions<EX, Props>; }; interface ForwardRefSFC<Ref = unknown> extends DefineComponent<Ref> { <Ref = unknown, Props = {}>(): DefineComponent<Ref, Props>; } interface SFC extends DefineComponent { <Props = {}>(): DefineComponent<NoRef, Props>; forwardRef: ForwardRefSFC; createOptions: (options: FuncMap, extensions?: Func | Obj, isRuntime?: boolean) => Obj; } interface SFCOptions { template?: Func; render?: Func; Component: Func; styles?: Func | Obj; static?: Func | Obj; /** * @deprecated Please use `static` */ options?: Func | Obj; } declare type SFCExtensions = Func | Obj; declare type ComponentDataType<C> = C extends { template: infer T; } ? T extends { (...args: any): any; __componentData: infer D; } ? D : never : never; declare function createOptions(options: FuncMap, extensions?: SFCExtensions): Obj; declare const sfc: SFC; declare const forwardRef: ForwardRefSFC; export default sfc; export { ComponentDataType, DefineComponent, ForwardRefSFC, SFC, SFCExtensions, SFCOptions, SFCProps, Template, TemplateRender, createOptions, createTemplate, forwardRef, isTemplate };
the_stack
import * as ws from 'ws'; import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; import { MuSessionId, MuSocket, MuSocketState, MuSocketSpec, MuSocketServer, MuSocketServerState, MuSocketServerSpec, } from '../socket'; import { MuScheduler } from '../../scheduler/scheduler'; import { MuSystemScheduler } from '../../scheduler/system'; import { MuLogger, MuDefaultLogger } from '../../logger'; import { makeError } from '../../util/error'; import { allocBuffer, freeBuffer } from '../../stream'; const error = makeError('socket/web/server'); export interface WSSocket { onmessage:(message:{ data:Buffer[]|string }) => void; binaryType:string; onclose:() => void; onerror:(e:any) => void; send:(data:Uint8Array|string) => void; close:() => void; ping:(() => void); bufferedAmount:number; } function noop () { } function coallesceFragments (frags:Buffer[]) { let size = 0; for (let i = 0; i < frags.length; ++i) { size += frags[i].length; } const result = new Uint8Array(size); let offset = 0; for (let i = 0; i < frags.length; ++i) { result.set(frags[i], offset); offset += frags[i].length; } return result; } export class MuWebSocketConnection { public readonly sessionId:string; public started = false; public closed = false; // every client communicates through one reliable and several unreliable sockets public reliableSocket:WSSocket; public unreliableSockets:WSSocket[] = []; public lastReliablePing:number = 0; public lastUnreliablePing:number[] = []; private _logger:MuLogger; public pendingMessages:(Uint8Array|string)[] = []; // for onmessage handler public onMessage:(data:Uint8Array|string, unreliable:boolean) => void = noop; // both for onclose handler public onClose:() => void = noop; public serverClose:() => void; constructor (sessionId:string, reliableSocket:WSSocket, serverClose:() => void, logger:MuLogger, public bufferLimit:number) { this.sessionId = sessionId; this.reliableSocket = reliableSocket; this.serverClose = serverClose; this._logger = logger; this.reliableSocket.onmessage = ({ data }) => { if (this.closed) { return; } if (this.started) { if (typeof data === 'string') { this.onMessage(data, false); } else if (data.length === 1) { this.onMessage(data[0], false); } else if (data.length > 1) { let size = 0; for (let i = 0; i < data.length; ++i) { size += data[i].length; } const buffer = allocBuffer(size); const result = buffer.uint8; let offset = 0; for (let i = 0; i < data.length; ++i) { result.set(data[i], offset); offset += data[i].length; } this.onMessage(result.subarray(0, offset), false); freeBuffer(buffer); } } else { if (typeof data === 'string') { this.pendingMessages.push(data); } else { this.pendingMessages.push(coallesceFragments(data)); } } }; this.reliableSocket.onclose = () => { if (!this.closed) { this._logger.log(`unexpectedly closed websocket connection for ${this.sessionId}`); } else { this._logger.log(`closing websocket connection for ${this.sessionId}`); } this.closed = true; for (let i = 0; i < this.unreliableSockets.length; ++i) { this.unreliableSockets[i].close(); } this.onClose(); // remove connection from server this.serverClose(); }; this.reliableSocket.onerror = (e) => { this._logger.error(`error on reliable socket ${this.sessionId}. reason ${e} ${e.stack ? e.stack : ''}`); }; } public addUnreliableSocket (socket:WSSocket) { if (this.closed) { return; } this.unreliableSockets.push(socket); this.lastUnreliablePing.push(0); socket.onmessage = ({ data }) => { if (this.closed) { return; } if (this.started) { if (typeof data === 'string') { this.onMessage(data, true); } else if (data.length === 1) { this.onMessage(data[0], true); } else if (data.length > 1) { let size = 0; for (let i = 0; i < data.length; ++i) { size += data[i].length; } const buffer = allocBuffer(size); const result = buffer.uint8; let offset = 0; for (let i = 0; i < data.length; ++i) { result.set(data[i], offset); offset += data[i].length; } this.onMessage(result.subarray(0, offset), true); freeBuffer(buffer); } } }; socket.onclose = () => { const idx = this.unreliableSockets.indexOf(socket); this.unreliableSockets.splice(idx, 1); this.lastUnreliablePing.splice(idx, 1); if (!this.closed) { this._logger.error(`unreliable socket closed unexpectedly: ${this.sessionId}`); } }; socket.onerror = (e) => { this._logger.error(`unreliable socket ${this.sessionId} error: ${e} ${e.stack ? e.stack : ''}`); }; } public send (data:Uint8Array, unreliable:boolean) { if (this.closed) { return; } if (unreliable) { const sockets = this.unreliableSockets; if (sockets.length > 0) { // find socket with least buffered data let socket = sockets[0]; let bufferedAmount = socket.bufferedAmount || 0; let idx = 0; for (let i = 1; i < sockets.length; ++i) { const s = sockets[i]; const b = s.bufferedAmount || 0; if (b < bufferedAmount) { socket = s; bufferedAmount = b; idx = i; } } // only send packet if socket is not blocked if (bufferedAmount < this.bufferLimit) { // send data socket.send(typeof data === 'string' ? data : new Uint8Array(data)); // move socket to back of queue sockets.splice(idx, 1); sockets.push(socket); } } } else { this.reliableSocket.send(typeof data === 'string' ? data : new Uint8Array(data)); } } public close () { this.reliableSocket.close(); } public doPing (now:number, pingCutoff:number) { if (this.closed) { return; } if (this.lastReliablePing < pingCutoff) { this.lastReliablePing = now; this.reliableSocket.ping(); } for (let i = 0; i < this.unreliableSockets.length; ++i) { if (this.lastUnreliablePing[i] < pingCutoff) { this.lastUnreliablePing[i] = now; this.unreliableSockets[i].ping(); } } } } export class MuWebSocketClient implements MuSocket { private _state = MuSocketState.INIT; public readonly sessionId:MuSessionId; public state () { return this._state; } private _connection:MuWebSocketConnection; private _logger:MuLogger; public scheduler:MuScheduler; constructor (connection:MuWebSocketConnection, scheduler:MuScheduler, logger:MuLogger) { this.sessionId = connection.sessionId; this._connection = connection; this._logger = logger; this.scheduler = scheduler; } public open (spec:MuSocketSpec) { if (this._state !== MuSocketState.INIT) { throw error(`socket had been opened`); } this.scheduler.setTimeout( () => { if (this._state !== MuSocketState.INIT) { return; } // set state to open this._state = MuSocketState.OPEN; // fire ready handler spec.ready(); // process all pending messages for (let i = 0; i < this._connection.pendingMessages.length; ++i) { if (this._connection.closed) { break; } try { spec.message(this._connection.pendingMessages[i], false); } catch (e) { this._logger.exception(e); } } this._connection.pendingMessages.length = 0; // if socket already closed, then fire close event immediately if (this._connection.closed) { this._state = MuSocketState.CLOSED; spec.close(); } else { // hook started message on socket this._connection.started = true; this._connection.onMessage = spec.message; // hook close handler this._connection.onClose = () => { this._state = MuSocketState.CLOSED; spec.close(); }; } }, 0); } public send (data:Uint8Array, unreliable?:boolean) { this._connection.send(data, !!unreliable); } public close () { this._logger.log(`close called on websocket ${this.sessionId}`); if (this._state !== MuSocketState.CLOSED) { this._state = MuSocketState.CLOSED; this._connection.close(); } } public reliableBufferedAmount () { return this._connection.reliableSocket.bufferedAmount; } public unreliableBufferedAmount () { let amount = Infinity; for (let i = 0; i < this._connection.unreliableSockets.length; ++i) { amount = Math.min(amount, this._connection.unreliableSockets[i].bufferedAmount); } return amount; } } export class MuWebSocketServer implements MuSocketServer { private _state = MuSocketServerState.INIT; public state () { return this._state; } private _connections:MuWebSocketConnection[] = []; public clients:MuWebSocketClient[] = []; private _options:object; private _wsServer; private _logger:MuLogger; private _onClose:() => void = noop; private _pingInterval:number = 10000; private _pingIntervalId:any; public scheduler:MuScheduler; public bufferLimit:number; constructor (spec:{ server:http.Server|https.Server, bufferLimit?:number, backlog?:number, handleProtocols?:(protocols:any[], request:http.IncomingMessage) => any, path?:string, perMessageDeflate?:boolean|object, maxPayload?:number, scheduler?:MuScheduler, logger?:MuLogger; pingInterval?:number, }) { this._logger = spec.logger || MuDefaultLogger; this.bufferLimit = spec.bufferLimit || 1024; this._options = { server: spec.server, clientTracking: false, }; spec.backlog && (this._options['backlog'] = spec.backlog); spec.maxPayload && (this._options['maxPayload'] = spec.maxPayload); spec.handleProtocols && (this._options['handleProtocols'] = spec.handleProtocols); spec.path && (this._options['path'] = spec.path); spec.perMessageDeflate && (this._options['perMessageDeflate'] = spec.perMessageDeflate); this.scheduler = spec.scheduler || MuSystemScheduler; if ('pingInterval' in spec) { this._pingInterval = spec.pingInterval || 0; } } private _findConnection (sessionId:string) : MuWebSocketConnection | null { for (let i = 0; i < this._connections.length; ++i) { if (this._connections[i].sessionId === sessionId) { return this._connections[i]; } } return null; } public start (spec:MuSocketServerSpec) { if (this._state !== MuSocketServerState.INIT) { throw error(`server had been started`); } if (this._pingInterval) { this._pingIntervalId = this.scheduler.setInterval(() => { const now = Date.now(); const pingCutoff = now - this._pingInterval; for (let i = 0; i < this._connections.length; ++i) { this._connections[i].doPing(now, pingCutoff); } }, this._pingInterval * 0.5); } this.scheduler.setTimeout( () => { this._wsServer = new (<any>ws).Server(this._options) .on('connection', (socket, req) => { if (this._state === MuSocketServerState.SHUTDOWN) { this._logger.error('connection attempt from closed socket server'); socket.terminate(); return; } this._logger.log(`muwebsocket connection received: extensions ${socket.extensions} protocol ${socket.protocol}`); const query = url.parse(req.url, true).query; const sessionId = query['sid']; if (typeof sessionId !== 'string') { this._logger.error(`no session id`); return; } socket.binaryType = 'fragments'; socket.onerror = (e) => { this._logger.error(`socket error in opening state: ${e}`); }; socket.onopen = () => this._logger.log('socket opened'); let connection = this._findConnection(sessionId); if (connection) { socket.send(JSON.stringify({ reliable: false, })); connection.addUnreliableSocket(socket); } else { socket.send(JSON.stringify({ reliable: true, })); connection = new MuWebSocketConnection(sessionId, socket, () => { if (connection) { this._connections.splice(this._connections.indexOf(connection), 1); for (let i = this.clients.length - 1; i >= 0; --i) { if (this.clients[i].sessionId === connection.sessionId) { this.clients.splice(i, 1); } } } }, this._logger, this.bufferLimit); this._connections.push(connection); const client = new MuWebSocketClient(connection, this.scheduler, this._logger); this.clients.push(client); spec.connection(client); } }) .on('error', (e) => { this._logger.error(`internal websocket error ${e}. ${e.stack ? e.stack : ''}`); }) .on('listening', () => this._logger.log(`muwebsocket server listening: ${JSON.stringify(this._wsServer.address())}`)) .on('close', () => { if (this._pingIntervalId) { this.scheduler.clearInterval(this._pingIntervalId); } this._logger.log('muwebsocket server closing'); }) .on('headers', (headers) => this._logger.log(`muwebsocket: headers ${headers}`)); this._onClose = spec.close; this._state = MuSocketServerState.RUNNING; spec.ready(); }, 0); } public close () { if (this._state === MuSocketServerState.SHUTDOWN) { return; } this._state = MuSocketServerState.SHUTDOWN; if (this._wsServer) { this._wsServer.close(this._onClose); } } }
the_stack
describe('URLSearchParams', () => { [ {"input": "test", "output": [["test", ""]]}, {"input": "\uFEFFtest=\uFEFF", "output": [["\uFEFFtest", "\uFEFF"]]}, {"input": "%EF%BB%BFtest=%EF%BB%BF", "output": [["\uFEFFtest", "\uFEFF"]]}, {"input": '', "output": []}, {"input": 'a', "output": [['a', '']]}, {"input": 'a=b', "output": [['a', 'b']]}, {"input": 'a=', "output": [['a', '']]}, {"input": '=b', "output": [['', 'b']]}, {"input": '&', "output": []}, {"input": '&a', "output": [['a', '']]}, {"input": 'a&', "output": [['a', '']]}, {"input": 'a&a', "output": [['a', ''], ['a', '']]}, {"input": 'a&b&c', "output": [['a', ''], ['b', ''], ['c', '']]}, {"input": 'a=b&c=d', "output": [['a', 'b'], ['c', 'd']]}, {"input": 'a=b&c=d&', "output": [['a', 'b'], ['c', 'd']]}, {"input": '&&&a=b&&&&c=d&', "output": [['a', 'b'], ['c', 'd']]}, {"input": 'a=a&a=b&a=c', "output": [['a', 'a'], ['a', 'b'], ['a', 'c']]}, {"input": 'a==a', "output": [['a', '=a']]}, {"input": 'a=a+b+c+d', "output": [['a', 'a b c d']]}, {"input": '%61=a', "output": [['a', 'a']]}, {"input": '%61+%4d%4D=', "output": [['a MM', '']]} ].forEach((val) => { it('URLSearchParams constructed with: ' + val.input, () => { let sp = new URLSearchParams(val.input); let i = 0; sp.forEach((value, key) => { expect([key, value]).toEqual(val.output[i]); i++; }); }); }); it('constructor', () => { var a = new URLSearchParams('b=1&a=2&c=3'); expect(a.toString()).toBe('b=1&a=2&c=3'); var b = new URLSearchParams(a); expect(b.toString()).toBe('b=1&a=2&c=3'); // @ts-ignore var c = new URLSearchParams([['b', 1], ['a', 2], ['c', 3]]); expect(c.toString()).toBe('b=1&a=2&c=3'); // @ts-ignore var d = new URLSearchParams({ 'b': 1, 'a': 2, 'c': 3 }); expect(d.toString()).toBe('b=1&a=2&c=3'); }); it('basics', ()=>{ var usp = new URLSearchParams('a=1&b=2&c'); expect(usp.has('a') && usp.has('b') && usp.has('c')).toBe(true); expect(usp.get('a') === '1').toBe(true); expect(usp.get('b') === '2').toBe(true); expect(usp.get('c') === '').toBe(true); expect(usp.getAll('a').join(',') === '1').toBe(true); expect(usp.getAll('b').join(',') === '2').toBe(true); expect(usp.getAll('c').join(',') === '').toBe(true); usp.append('a', '3'); expect(usp.getAll('a').join(',') === '1,3').toBe(true); expect(usp.get('a') === '1').toBe(true); expect(usp.getAll('b').join(',') === '2' && usp.getAll('c').join(',') === '').toBe(true); usp.set('a', '4'); expect(usp.getAll('a').join(',') === '4').toBe(true); usp.delete('a'); expect(usp.has('a') === false).toBe(true); expect(usp.get('a') === null).toBe(true); expect(usp.toString() === 'b=2&c=').toBe(true); }); it('append same name', () => { let params = new URLSearchParams(); params.append('a', 'b'); expect(params + '').toBe('a=b'); params.append('a', 'b'); expect(params + '', ).toBe('a=b&a=b'); params.append('a', 'c'); expect(params + '').toBe('a=b&a=b&a=c'); }); it('append empty strings', () => { var params = new URLSearchParams(); params.append('', ''); expect(params + '').toBe('='); params.append('', ''); expect(params + '').toBe('=&='); }); it('append null', () => { var params = new URLSearchParams(); // @ts-ignore params.append(null, null); expect(params + '').toBe('null=null'); // @ts-ignore params.append(null, null); expect(params + '').toBe( 'null=null&null=null'); }); it('append multiple', () => { var params = new URLSearchParams(); // @ts-ignore params.append('first', 1); // @ts-ignore params.append('second', 2); // @ts-ignore params.append('third', ''); // @ts-ignore params.append('first', 10); expect(params.has('first')).toBe(true); expect(params.get('first')).toBe('1'); expect(params.get('second')).toBe('2'); expect(params.get('third')).toBe(''); // @ts-ignore params.append('first', 10); expect(params.get('first')).toBe('1'); }); it('Set basics', function () { var params = new URLSearchParams('a=b&c=d'); params.set('a', 'B'); expect(params + '').toBe('a=B&c=d'); params = new URLSearchParams('a=b&c=d&a=e'); params.set('a', 'B'); expect(params + '').toBe('a=B&c=d'); params.set('e', 'f'); expect(params + '').toBe('a=B&c=d&e=f'); }); it('URLSearchParams.set', function () { var params = new URLSearchParams('a=1&a=2&a=3'); expect(params.has('a')).toBeTrue(); expect(params.get('a')).toBe( '1', 'Search params object has name "a" with value "1"' ); // @ts-ignore params.set('first', 4); expect(params.has('a')).toBeTrue(); expect(params.get('a')).toBe( '1', 'Search params object has name "a" with value "1"' ); // @ts-ignore params.set('a', 4); expect(params.has('a')).toBeTrue(); expect(params.get('a')).toBe( '4', 'Search params object has name "a" with value "4"' ); }); [ { input: 'z=b&a=b&z=a&a=a', output: [ ['a', 'b'], ['a', 'a'], ['z', 'b'], ['z', 'a'], ], }, { input: '\uFFFD=x&\uFFFC&\uFFFD=a', output: [ ['\uFFFC', ''], ['\uFFFD', 'x'], ['\uFFFD', 'a'], ], }, { input: 'ffi&\uD83C\uDF08', output: [ ['\uD83C\uDF08', ''], ['ffi', ''], ], }, { input: 'é&e\uFFFD&é', output: [ ['é', ''], ['e\uFFFD', ''], ['é', ''], ], }, { input: 'z=z&a=a&z=y&a=b&z=x&a=c&z=w&a=d&z=v&a=e&z=u&a=f&z=t&a=g', output: [ ['a', 'a'], ['a', 'b'], ['a', 'c'], ['a', 'd'], ['a', 'e'], ['a', 'f'], ['a', 'g'], ['z', 'z'], ['z', 'y'], ['z', 'x'], ['z', 'w'], ['z', 'v'], ['z', 'u'], ['z', 't'], ], }, { input: 'bbb&bb&aaa&aa=x&aa=y', output: [ ['aa', 'x'], ['aa', 'y'], ['aaa', ''], ['bb', ''], ['bbb', ''], ], }, { input: 'z=z&=f&=t&=x', output: [ ['', 'f'], ['', 't'], ['', 'x'], ['z', 'z'], ], }, { input: 'a\uD83C\uDF08&a\uD83D\uDCA9', output: [ ['a\uD83C\uDF08', ''], ['a\uD83D\uDCA9', ''], ], }, ].forEach((val) => { xit('Parse and sort: ' + val.input, () => { let params = new URLSearchParams(val.input), i = 0; params.sort(); // @ts-ignore for (let param of params) { expect(param).toEqual(val.output[i]); i++; } }); xit('URL parse and sort: ' + val.input, () => { let url = new URL('?' + val.input, 'https://example/'); url.searchParams.sort(); let params = new URLSearchParams(url.search), i = 0; // @ts-ignore for (let param of params) { expect(param).toEqual(val.output[i]); i++; } }); }); xit('Sorting non-existent params removes ? from URL', function () { const url = new URL('http://example.com/?'); url.searchParams.sort(); expect(url.href).toBe('http://example.com/'); expect(url.search).toBe(''); }); it('Serialize space', function () { var params = new URLSearchParams(); params.append('a', 'b c'); expect(params + '').toBe('a=b+c'); params.delete('a'); params.append('a b', 'c'); expect(params + '').toBe('a+b=c'); }); it('Serialize empty value', function () { var params = new URLSearchParams(); params.append('a', ''); expect(params + '').toBe('a='); params.append('a', ''); expect(params + '').toBe('a=&a='); params.append('', 'b'); expect(params + '').toBe('a=&a=&=b'); params.append('', ''); expect(params + '').toBe('a=&a=&=b&='); params.append('', ''); expect(params + '').toBe('a=&a=&=b&=&='); }); it('Serialize empty name', function () { var params = new URLSearchParams(); params.append('', 'b'); expect(params + '').toBe('=b'); params.append('', 'b'); expect(params + '').toBe('=b&=b'); }); it('Serialize empty name and value', function () { var params = new URLSearchParams(); params.append('', ''); expect(params + '').toBe('='); params.append('', ''); expect(params + '').toBe('=&='); }); it('Serialize +', function () { var params = new URLSearchParams(); params.append('a', 'b+c'); expect(params + '').toBe('a=b%2Bc'); params.delete('a'); params.append('a+b', 'c'); expect(params + '').toBe('a%2Bb=c'); }); it('Serialize =', function () { var params = new URLSearchParams(); params.append('=', 'a'); expect(params + '').toBe('%3D=a'); params.append('b', '='); expect(params + '').toBe('%3D=a&b=%3D'); }); it('Serialize &', function () { var params = new URLSearchParams(); params.append('&', 'a'); expect(params + '').toBe('%26=a'); params.append('b', '&'); expect(params + '').toBe('%26=a&b=%26'); }); it('Serialize *-._', function () { var params = new URLSearchParams(); params.append('a', '*-._'); expect(params + '').toBe('a=*-._'); params.delete('a'); params.append('*-._', 'c'); expect(params + '').toBe('*-._=c'); }); it('Serialize %', function () { var params = new URLSearchParams(); params.append('a', 'b%c'); expect(params + '').toBe('a=b%25c'); params.delete('a'); params.append('a%b', 'c'); expect(params + '').toBe('a%25b=c'); }); xit('Serialize \\0', function () { var params = new URLSearchParams(); params.append('a', 'b\0c'); expect(params + '').toBe('a=b%00c'); params.delete('a'); params.append('a\0b', 'c'); expect(params + '').toBe('a%00b=c'); }); it('Serialize \uD83D\uDCA9', function () { var params = new URLSearchParams(); params.append('a', 'b\uD83D\uDCA9c'); expect(params + '').toBe('a=b%F0%9F%92%A9c'); params.delete('a'); params.append('a\uD83D\uDCA9b', 'c'); expect(params + '').toBe('a%F0%9F%92%A9b=c'); }); it('URLSearchParams.toString', function () { var params; params = new URLSearchParams('a=b&c=d&&e&&'); expect(params.toString()).toBe('a=b&c=d&e='); params = new URLSearchParams('a = b &a=b&c=d%20'); expect(params.toString()).toBe('a+=+b+&a=b&c=d+'); params = new URLSearchParams('a=&a=b'); expect(params.toString()).toBe('a=&a=b'); }); it('URLSearchParams connected to URL', () => { const url = new URL('http://www.example.com/?a=b,c'); const params = url.searchParams; expect(url.toString()).toBe('http://www.example.com/?a=b,c'); expect(params.toString()).toBe('a=b%2Cc'); params.append('x', 'y'); expect(url.toString()).toBe('http://www.example.com/?a=b%2Cc&x=y'); expect(params.toString()).toBe('a=b%2Cc&x=y'); }); it('should encoding/decoding special char', () => { var params = new URLSearchParams('a=2018-12-19T09:14:35%2B09:00'); expect(params.get('a')).toBe('2018-12-19T09:14:35+09:00'); var params2 = new URLSearchParams('a=one+two'); expect(params2.get('a')).toBe('one two'); }); });
the_stack
import * as functions from 'firebase-functions' import * as admin from 'firebase-admin' import { map } from 'lodash' import { copyFromRTDBToFirestore, copyFromFirestoreToRTDB, copyBetweenFirestoreInstances, copyFromStorageToRTDB, copyBetweenRTDBInstances, copyFromRTDBToStorage, batchCopyBetweenRTDBInstances } from './actions' import { to, promiseWaterfall } from '../utils/async' import { hasAll } from '../utils/index' import { getAppFromServiceAccount } from '../utils/serviceAccounts' import { updateResponseOnRTDB, updateResponseWithProgress, updateResponseWithError, updateResponseWithActionError } from './utils' import { ActionRunnerEventData, ActionStep } from './types' /** * Data action using Service account stored on Firestore * @param snap - Data snapshot from cloud function * @param context - The context in which an event occurred * @returns Resolves with results */ export async function runStepsFromEvent( snap: admin.database.DataSnapshot, context: functions.EventContext ) { const eventData = snap.val() if (!eventData?.template?.steps) { throw new Error('Valid Action Template is required to run steps') } const { inputValues, environments, template: { steps, inputs } } = eventData if (!Array.isArray(steps)) { await updateResponseWithError(context.params.pushId) throw new Error('Steps array was not provided to action request') } if (!Array.isArray(inputs)) { await updateResponseWithError(context.params.pushId) throw new Error('Inputs array was not provided to action request') } if (!Array.isArray(inputValues)) { await updateResponseWithError(context.params.pushId) throw new Error('Input values array was not provided to action request') } const convertedEnvs = await validateAndConvertEnvironments( eventData, environments ) // Convert inputs into their values const convertedInputValues = eventData.inputValues.map((inputValue, inputIdx) => validateAndConvertInputValues(inputs[inputIdx], inputValue) ) const totalNumSteps = steps.length console.log(`Running ${totalNumSteps} steps(s)`) // Run all action promises const [actionErr, actionResponse] = await to( promiseWaterfall( map( steps, createStepRunner({ inputs, convertedInputValues, convertedEnvs, context, eventData, totalNumSteps }) ) ) ) // Handle errors running action if (actionErr) { // Write error back to RTDB response object await updateResponseWithError(context.params.pushId) throw actionErr } // Write response to RTDB await updateResponseOnRTDB(snap, context) return actionResponse } /** * Data action using Service account stored on Firestore * @param snap - Data snapshot from cloud function * @param context - The context in which an event occurred * @returns Resolves with results */ export async function runBackupsFromEvent(snap: admin.database.DataSnapshot, context: functions.EventContext) { const eventData = snap.val() const { inputValues, template: { backups, inputs } } = eventData if (!Array.isArray(backups)) { await updateResponseWithError(context.params.pushId) throw new Error('Backups array was not provided to action request') } if (!Array.isArray(inputs)) { await updateResponseWithError(context.params.pushId) throw new Error('Inputs array was not provided to action request') } if (!Array.isArray(inputValues)) { await updateResponseWithError(context.params.pushId) throw new Error('Input values array was not provided to action request') } const convertedInputValues = eventData.inputValues.map((inputValue, inputIdx) => validateAndConvertInputValues(inputs[inputIdx], inputValue) ) const totalNumSteps = backups.length console.log(`Running ${totalNumSteps} backup(s)`) // Run all action promises in a waterfall const [actionErr, actionResponse] = await to( promiseWaterfall( map( backups, createStepRunner({ inputs, convertedInputValues, context, eventData, totalNumSteps }) ) ) ) if (actionErr) { await updateResponseWithError(context.params.pushId) throw actionErr } // Write response to RTDB await updateResponseOnRTDB(snap, context) return actionResponse } /** * Validate and convert list of inputs to relevant types (i.e. serviceAccount * data replaced with app) * @param eventData - Data from event * @param envsMetas - Meta data for environments * @returns Resolves with an array of results of converting inputs */ function validateAndConvertEnvironments(eventData: ActionRunnerEventData, envsMetas: any[]): Promise<admin.app.App[]> { if (!eventData.environments) { return Promise.resolve([]) } return Promise.all( eventData.environments.map((envValue, envIdx) => validateAndConvertEnvironment(eventData, envsMetas[envIdx], envValue) ) ) } interface InputMetadata { required?: boolean } /** * Validate and convert a single input to relevant type * (i.e. serviceAccount data replaced with app) * @param eventData - Data from event * @param inputMeta - Metadata for input * @param inputValue - Value of input * @returns Resolves with firebase app if service account type */ async function validateAndConvertEnvironment( eventData: ActionRunnerEventData, inputMeta: InputMetadata, inputValue: any ): Promise<admin.app.App> { // Throw if input is required and is missing serviceAccountPath or databaseURL const varsNeededForStorageType = ['fullPath', 'databaseURL'] const varsNeededForFirstoreType = ['credential', 'databaseURL'] if ( inputMeta?.required && !hasAll(inputValue, varsNeededForStorageType) && !hasAll(inputValue, varsNeededForFirstoreType) ) { throw new Error( 'Environment input is required and does not contain required parameters' ) } return getAppFromServiceAccount(inputValue, eventData) } /** * Validate and convert a single input to relevant type * (i.e. serviceAccount data replaced with app) * @param inputMeta - Metadat for input * @param inputValue - Value for input * @returns Validates/coverts input value */ function validateAndConvertInputValues(inputMeta, inputValue) { // Handle no longer supported input type "serviceAccount" if (inputMeta?.type === 'serviceAccount') { console.error('serviceAccount inputMeta type still being used: ', inputMeta) throw new Error( 'serviceAccount input type is no longer supported. Please update your action template' ) } // Confirm required inputs have a value if (inputMeta?.required && !inputValue) { throw new Error('Input is required and does not contain a value') } // Return input's value (assuming userInput type) return inputValue } interface CreateStepRunnerParams { inputs: any convertedInputValues: any convertedEnvs?: any context: functions.EventContext eventData: any totalNumSteps: number } /** * Builds an action runner function which accepts an action config object * and the stepIdx. Action runner function runs action then updates * response with progress and/or error. * @param params - Params object * @param params.eventData - Data from event (contains settings for * @param params.inputs - List of inputs * @param params.convertedInputValues - List of inputs converted to relevant types * @param params.totalNumSteps - Total number of actions * @param params.convertedEnvs - List of converted envs * @param params.snap - Snap from event * @param params.context - Context from event * @returns Which accepts action and stepIdx (used in Promise.all map) */ function createStepRunner({ inputs, convertedInputValues, convertedEnvs, context, eventData, totalNumSteps }: CreateStepRunnerParams): Function { /** * Run action based on provided settings and update response with progress * @param step - Step object * @param stepIdx - Index of the action (from actions array) * @returns Resolves with results of progress update call */ return function runStepAndUpdateProgress(step: ActionStep, stepIdx: number) { /** * Receives results of previous action and calls next action * @returns Accepts action and stepIdx (used in Promise.all map) */ return async function runNextStep() { const [err, stepResponse] = await to( runStep({ step, inputs, convertedInputValues, convertedEnvs, eventData }) ) // Handle errors running step if (err) { // Write error back to response object await updateResponseWithActionError(context.params.pushId, { totalNumSteps, stepIdx }) throw new Error(`Error running step: ${stepIdx} : ${err.message}`) } // Update response with step complete progress await updateResponseWithProgress(context.params.pushId, { totalNumSteps, stepIdx }) return stepResponse } } } interface RunStepParams { inputs: any[] convertedInputValues: any[] convertedEnvs: any[] step: ActionStep eventData: ActionRunnerEventData } /** * Data action using Service account stored on Firestore * @param params - Params object * @param params.step - Object containing settings for step * @param params.inputs - Inputs provided to the action * @param params.convertedInputValues - Inputs provided to the action converted * to relevant data (i.e. service accounts) * @param params.eventData - Data from event (contains settings for * action request) * @param params.convertedEnvs - Converted environments * @returns Resolves with results of running the provided action */ export async function runStep({ inputs, convertedInputValues, convertedEnvs, step, eventData }: RunStepParams): Promise<any> { // Handle step or step type not existing if (!step?.type) { throw new Error('Step object is invalid (i.e. does not contain a type)') } if (!convertedEnvs) { throw new Error('Environments are required to run step') } const { type, src, dest } = step // Run custom action type (i.e. Code written within Firepad) if (type === 'custom') { console.error('Step type is "Custom", returning error') throw new Error('Custom action type not currently supported') } // Service accounts come from converted version of what is selected for inputs const [app1, app2] = convertedEnvs // Require src and dest for all other step types if (!src || !dest || !src.resource || !dest.resource) { throw new Error('src, dest and src.resource are required to run step') } switch (src.resource) { case 'firestore': if (dest.resource === 'firestore') { return copyBetweenFirestoreInstances( app1, app2, step, convertedInputValues ) } else if (dest.resource === 'rtdb') { return copyFromFirestoreToRTDB(app1, app2, step, convertedInputValues) } else { throw new Error( `Invalid dest.resource: ${dest.resource} for step: ${step}` ) } case 'rtdb': if (dest.resource === 'firestore') { return copyFromRTDBToFirestore(app1, app2, step, convertedInputValues) } else if (dest.resource === 'rtdb') { // Run normal copy if batching is disabled if (step.disableBatching) { return copyBetweenRTDBInstances( app1, app2, step, convertedInputValues ) } // Batch copy by default return batchCopyBetweenRTDBInstances( app1, app2, step, convertedInputValues, eventData ).catch((batchErr) => { // Fallback to copying without batching console.error('Batch copy error:', batchErr) console.error('Batch copy error info', { inputs, step, eventData }) console.log('Falling back to normal copy....') return copyBetweenRTDBInstances( app1, app2, step, convertedInputValues ) }) } else if (dest.resource === 'storage') { return copyFromRTDBToStorage(app1, app2, step) } else { throw new Error( `Invalid dest.resource: ${dest.resource} for step: ${step}` ) } case 'storage': if (dest.resource === 'rtdb') { return copyFromStorageToRTDB(app1, app2, step) } else { throw new Error( `Invalid dest.resource: ${dest.resource} for step: ${step}` ) } default: throw new Error( 'src.resource type not supported. Try firestore, rtdb, or storage' ) } }
the_stack
import { ApiDefinition, ApiSharedValueConsumers, ArgsType, EnvelopeBusMessage, EnvelopeBusMessagePurpose, FunctionPropertyNames, MessageBusClientApi, MessageBusServer, NotificationCallback, NotificationConsumer, NotificationPropertyNames, RequestConsumer, RequestPropertyNames, SharedValueConsumer, SharedValueProviderPropertyNames, } from "../api"; type Func = (...args: any[]) => any; interface StoredPromise { resolve: (arg: unknown) => void; reject: (arg: unknown) => void; } export class EnvelopeBusMessageManager< ApiToProvide extends ApiDefinition<ApiToProvide>, ApiToConsume extends ApiDefinition<ApiToConsume> > { private readonly requestHandlers = new Map<string, StoredPromise>(); private readonly localNotificationsSubscriptions = new Map<NotificationPropertyNames<ApiToConsume>, Func[]>(); private readonly remoteNotificationsSubscriptions: Array<NotificationPropertyNames<ApiToProvide>> = []; private readonly localSharedValueSubscriptions = new Map< SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume>, Func[] >(); private readonly localSharedValuesStore = new Map< SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume>, ApiToProvide[keyof ApiToProvide] | ApiToConsume[keyof ApiToConsume] >(); private requestIdCounter: number; public currentApiImpl?: ApiToProvide; public clientApi: MessageBusClientApi<ApiToConsume> = { requests: cachedProxy( new Map<RequestPropertyNames<ApiToConsume>, RequestConsumer<ApiToConsume[keyof ApiToConsume]>>(), { get: (target, name) => { return (...args) => this.request(name, ...args); }, } ), notifications: cachedProxy( new Map<NotificationPropertyNames<ApiToConsume>, NotificationConsumer<ApiToConsume[keyof ApiToConsume]>>(), { get: (target, name) => ({ subscribe: (callback) => this.subscribeToNotification(name, callback), unsubscribe: (callback) => this.unsubscribeFromNotification(name, callback), send: (...args) => this.notify(name, ...args), }), } ), shared: cachedProxy( new Map<SharedValueProviderPropertyNames<ApiToConsume>, SharedValueConsumer<ApiToConsume[keyof ApiToConsume]>>(), { get: (target, name) => ({ set: (value) => this.setSharedValue(name, value), subscribe: (callback) => this.subscribeToSharedValue(name, callback, { owned: false }), unsubscribe: (callback) => this.unsubscribeFromSharedValue(name, callback), }), } ), }; public shared: ApiSharedValueConsumers<ApiToProvide> = cachedProxy( new Map<SharedValueProviderPropertyNames<ApiToProvide>, SharedValueConsumer<ApiToProvide[keyof ApiToProvide]>>(), { get: (target, name) => ({ set: (value) => this.setSharedValue(name, value), subscribe: (callback) => this.subscribeToSharedValue(name, callback, { owned: true }), unsubscribe: (callback) => this.unsubscribeFromSharedValue(name, callback), }), } ); public get server(): MessageBusServer<ApiToProvide, ApiToConsume> { return { receive: (m, apiImpl) => { console.debug(m); this.receive(m, apiImpl); }, }; } constructor( private readonly send: ( // We can send messages for both the APIs we provide and consume message: EnvelopeBusMessage<unknown, FunctionPropertyNames<ApiToConsume> | FunctionPropertyNames<ApiToProvide>> ) => void, private readonly name: string = `${new Date().getMilliseconds()}` ) { this.requestIdCounter = 0; } private setSharedValue< M extends SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume> >(method: M, value: any) { this.localSharedValuesStore.set(method, value); this.localSharedValueSubscriptions.get(method)?.forEach((callback) => callback(value)); this.send({ type: method, purpose: EnvelopeBusMessagePurpose.SHARED_VALUE_UPDATE, data: value, }); } private subscribeToSharedValue< M extends SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume> >(method: M, callback: Func, config: { owned: boolean }) { const activeSubscriptions = this.localSharedValueSubscriptions.get(method) ?? []; this.localSharedValueSubscriptions.set(method, [...activeSubscriptions, callback]); if (config.owned || this.localSharedValuesStore.get(method)) { callback(this.getCurrentStoredSharedValueOrDefault(method, this.currentApiImpl)); } else { this.send({ type: method, purpose: EnvelopeBusMessagePurpose.SHARED_VALUE_GET_DEFAULT, data: [], }); } return callback; } private unsubscribeFromSharedValue< M extends SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume> >(name: M, callback: any) { const activeSubscriptions = this.localSharedValueSubscriptions.get(name); if (!activeSubscriptions) { return; } const index = activeSubscriptions.indexOf(callback); if (index < 0) { return; } activeSubscriptions.splice(index, 1); } private getCurrentStoredSharedValueOrDefault< M extends SharedValueProviderPropertyNames<ApiToProvide> | SharedValueProviderPropertyNames<ApiToConsume> >(method: M, apiImpl?: ApiToProvide) { const m = method as SharedValueProviderPropertyNames<ApiToProvide>; return ( this.localSharedValuesStore.get(m) ?? this.localSharedValuesStore.set(m, apiImpl?.[m]?.apply(apiImpl).defaultValue).get(method) ); } private subscribeToNotification<M extends NotificationPropertyNames<ApiToConsume>>( method: M, callback: (...args: ArgsType<ApiToConsume[M]>) => void ) { const activeSubscriptions = this.localNotificationsSubscriptions.get(method) ?? []; this.localNotificationsSubscriptions.set(method, [...activeSubscriptions, callback]); this.send({ type: method, purpose: EnvelopeBusMessagePurpose.NOTIFICATION_SUBSCRIPTION, data: [], }); return callback; } private unsubscribeFromNotification<M extends NotificationPropertyNames<ApiToConsume>>( method: M, callback: NotificationCallback<ApiToConsume, M> ) { const activeSubscriptions = this.localNotificationsSubscriptions.get(method); if (!activeSubscriptions) { return; } const index = activeSubscriptions.indexOf(callback); if (index < 0) { return; } activeSubscriptions.splice(index, 1); this.send({ type: method, purpose: EnvelopeBusMessagePurpose.NOTIFICATION_UNSUBSCRIPTION, data: [], }); } private request<M extends RequestPropertyNames<ApiToConsume>>(method: M, ...args: ArgsType<ApiToConsume[M]>) { const requestId = this.getNextRequestId(); this.send({ requestId: requestId, type: method, data: args, purpose: EnvelopeBusMessagePurpose.REQUEST, }); return new Promise<any>((resolve, reject) => { this.requestHandlers.set(requestId, { resolve, reject }); }) as ReturnType<ApiToConsume[M]>; //TODO: Setup timeout to avoid memory leaks } private notify<M extends NotificationPropertyNames<ApiToConsume>>(method: M, ...args: ArgsType<ApiToConsume[M]>) { this.send({ type: method, data: args, purpose: EnvelopeBusMessagePurpose.NOTIFICATION, }); } private respond<T>( request: EnvelopeBusMessage<unknown, FunctionPropertyNames<ApiToProvide>>, data: T, error?: any ): void { if (request.purpose !== EnvelopeBusMessagePurpose.REQUEST) { throw new Error("Cannot respond a message that is not a request"); } if (!request.requestId) { throw new Error("Cannot respond a request without a requestId"); } this.send({ requestId: request.requestId, purpose: EnvelopeBusMessagePurpose.RESPONSE, type: request.type as FunctionPropertyNames<ApiToProvide>, data: data, error: error instanceof Error ? error.message : JSON.stringify(error), }); } private callback(response: EnvelopeBusMessage<unknown, FunctionPropertyNames<ApiToConsume>>) { if (response.purpose !== EnvelopeBusMessagePurpose.RESPONSE) { throw new Error("Cannot invoke callback with a message that is not a response"); } if (!response.requestId) { throw new Error("Cannot acknowledge a response without a requestId"); } const callback = this.requestHandlers.get(response.requestId); if (!callback) { throw new Error("Callback not found for " + response); } this.requestHandlers.delete(response.requestId); if (!response.error) { callback.resolve(response.data); } else { callback.reject(new Error(response.error)); } } private receive( // We can receive messages from both the APIs we provide and consume. message: EnvelopeBusMessage<unknown, FunctionPropertyNames<ApiToConsume> | FunctionPropertyNames<ApiToProvide>>, apiImpl: ApiToProvide ) { this.currentApiImpl = apiImpl; if (message.purpose === EnvelopeBusMessagePurpose.RESPONSE) { // We can only receive responses for the API we consume. this.callback(message as EnvelopeBusMessage<unknown, RequestPropertyNames<ApiToConsume>>); return; } if (message.purpose === EnvelopeBusMessagePurpose.REQUEST) { // We can only receive requests for the API we provide. const request = message as EnvelopeBusMessage<unknown, RequestPropertyNames<ApiToProvide>>; let response; try { response = apiImpl[request.type].apply(apiImpl, request.data); } catch (err) { this.respond(request, undefined, err); return; } if (!(response instanceof Promise)) { throw new Error(`Cannot make a request to '${request.type}' because it does not return a Promise`); } response.then((data) => this.respond(request, data)).catch((err) => this.respond(request, undefined, err)); return; } if (message.purpose === EnvelopeBusMessagePurpose.NOTIFICATION) { // We can only receive notifications for methods of the API we provide. const method = message.type as NotificationPropertyNames<ApiToProvide>; apiImpl[method]?.apply(apiImpl, message.data); if (this.remoteNotificationsSubscriptions.indexOf(method) >= 0) { this.send({ type: method, purpose: EnvelopeBusMessagePurpose.NOTIFICATION, data: message.data, }); } // We can only receive notifications from subscriptions of the API we consume. const localSubscriptionMethod = message.type as NotificationPropertyNames<ApiToConsume>; this.localNotificationsSubscriptions.get(localSubscriptionMethod)?.forEach((callback) => { callback(...(message.data as any[])); }); return; } if (message.purpose === EnvelopeBusMessagePurpose.NOTIFICATION_SUBSCRIPTION) { // We can only receive subscriptions for methods of the API we provide. const method = message.type as NotificationPropertyNames<ApiToProvide>; if (this.remoteNotificationsSubscriptions.indexOf(method) < 0) { this.remoteNotificationsSubscriptions.push(method); } return; } if (message.purpose === EnvelopeBusMessagePurpose.NOTIFICATION_UNSUBSCRIPTION) { // We can only receive unsubscriptions for methods of the API we provide. const method = message.type as NotificationPropertyNames<ApiToProvide>; const index = this.remoteNotificationsSubscriptions.indexOf(method); if (index >= 0) { this.remoteNotificationsSubscriptions.splice(index, 1); } return; } if (message.purpose === EnvelopeBusMessagePurpose.SHARED_VALUE_GET_DEFAULT) { const method = message.type as SharedValueProviderPropertyNames<ApiToProvide>; this.send({ type: method, purpose: EnvelopeBusMessagePurpose.SHARED_VALUE_UPDATE, data: this.getCurrentStoredSharedValueOrDefault(method, apiImpl), }); return; } if (message.purpose === EnvelopeBusMessagePurpose.SHARED_VALUE_UPDATE) { const method = message.type as SharedValueProviderPropertyNames<ApiToProvide>; const subscriptions = this.localSharedValueSubscriptions.get(method); this.localSharedValuesStore.set(method, message.data as any); subscriptions?.forEach((callback) => callback(message.data)); return; } } public getNextRequestId() { return `${this.name}_${this.requestIdCounter++}`; } } function cachedProxy<T extends object, K extends keyof T, V>(cache: Map<K, V>, p: { get(target: T, p: keyof T): V }) { return new Proxy<T>({} as T, { set: (target, name, value) => { cache.set(name as K, value); return true; }, get: (target, name) => { return cache.get(name as K) ?? cache.set(name as K, p.get?.(target, name as K)).get(name as K); }, }); }
the_stack
import { ChangeDataType, CreateDocumentMarkerPermalinkRequestType } from "@codestream/protocols/agent"; import { CodemarkType } from "@codestream/protocols/api"; import { CompositeDisposable, Disposable } from "atom"; import { FileLogger, LOG_DIR } from "logger"; import { SplitDiffService } from "types/package-services/split-diff"; import { Debug, Echo, Editor, Listener } from "utils"; import { CODESTREAM_VIEW_URI } from "views/codestream-view"; import { Container } from "workspace/container"; import { Environment, EnvironmentConfig, PD_CONFIG, PRODUCTION_CONFIG, QA_CONFIG } from "./env-utils"; import { PackageState } from "./types/package"; import { StatusBar } from "./types/package-services/status-bar"; import { SessionStatus } from "./workspace/workspace-session"; class CodestreamPackage { subscriptions = new CompositeDisposable(); sessionStatusCommand?: Disposable; loggedInCommandsSubscription?: CompositeDisposable; private environmentChangeEmitter = new Echo<EnvironmentConfig>(); constructor() { this.initialize(); } // Package lifecyle 1 async initialize() { const session = Container.session; this.subscriptions.add( session.observeSessionStatus(status => { this.sessionStatusCommand && this.sessionStatusCommand.dispose(); if (status === SessionStatus.SignedIn) { this.registerLoggedInCommands(); this.sessionStatusCommand = atom.commands.add( "atom-workspace", "codestream:sign-out", async () => { Container.viewController.destroyView(CODESTREAM_VIEW_URI); await session.signOut(); } ); } if (status === SessionStatus.SignedOut) { this.loggedInCommandsSubscription && this.loggedInCommandsSubscription.dispose(); this.sessionStatusCommand = atom.commands.add( "atom-workspace", "codestream:sign-in", () => {} ); } }) ); const hiddenInCommandPalette = !atom.inDevMode(); this.subscriptions.add( atom.commands.add("atom-workspace", "codestream:open-logs", () => { atom.project.addPath(LOG_DIR); atom.notifications.addInfo("The CodeStream log directory has been added to workspace"); }), // Dev mode goodies atom.commands.add("atom-workspace", "codestream:reload-webview", { didDispatch: () => { Container.viewController.reload(CODESTREAM_VIEW_URI); }, hiddenInCommandPalette }), atom.commands.add("atom-workspace", "codestream:point-to-qa", { didDispatch: async () => { Container.configs.set("serverUrl", QA_CONFIG.serverUrl); await session.signOut(); this.environmentChangeEmitter.push(QA_CONFIG); Container.viewController.reload(CODESTREAM_VIEW_URI); }, hiddenInCommandPalette }), atom.commands.add("atom-workspace", "codestream:point-to-dev", { didDispatch: async () => { Container.configs.set("serverUrl", PD_CONFIG.serverUrl); await session.signOut(); this.environmentChangeEmitter.push(PD_CONFIG); Container.viewController.reload(CODESTREAM_VIEW_URI); }, hiddenInCommandPalette }), atom.commands.add("atom-workspace", "codestream:point-to-production", { didDispatch: async () => { Container.configs.set("serverUrl", PRODUCTION_CONFIG.serverUrl); await session.signOut(); this.environmentChangeEmitter.push(PRODUCTION_CONFIG); Container.viewController.reload(CODESTREAM_VIEW_URI); }, hiddenInCommandPalette }) ); } // Package lifecyle deserializeCodestreamView() { return Container.viewController.getMainView(); } // Package lifecyle // activate() {} handleURI(parsedUri: { href: string }) { Container.viewController.handleProtocolRequest(parsedUri.href); } // Package lifecyle serialize(): PackageState { return { ...Container.session.serialize(), views: Container.viewController.serialize(), debug: Debug.isDebugging() }; } // Package lifecyle async deactivate() { this.environmentChangeEmitter.dispose(); Container.session.dispose(); this.subscriptions.dispose(); this.sessionStatusCommand!.dispose(); Container.viewController.dispose(); Container.markerDecorationProvider.dispose(); Container.styles.dispose(); Container.editorManipulator.dispose(); this.loggedInCommandsSubscription && this.loggedInCommandsSubscription.dispose(); await FileLogger.nuke(); } provideEnvironmentConfig() { return { get: () => Container.session.environment, onDidChange: (cb: Listener<EnvironmentConfig>) => this.environmentChangeEmitter.add(cb) }; } provideDebugConfig() { return { set: (enable: boolean) => { Debug.setDebugging(enable); atom.reload(); }, get: () => Debug.isDebugging() }; } private registerLoggedInCommands() { const sendNewCodemarkRequest = (type: CodemarkType, entry: "Context Menu" | "Shortcut") => { const view = Container.viewController.getMainView(); view.show().then(() => { view.newCodemarkRequest(type, entry); }); }; const sendStartWorkRequest = (entry: "Context Menu" | "Shortcut") => { const view = Container.viewController.getMainView(); view.show().then(() => { view.startWorkRequest(entry); }); }; this.loggedInCommandsSubscription = new CompositeDisposable( // context menu options atom.commands.add("atom-workspace", "codestream:context-create-comment", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Comment, "Context Menu") }), atom.commands.add("atom-workspace", "codestream:context-create-issue", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Issue, "Context Menu") }), atom.commands.add("atom-workspace", "codestream:context-get-permalink", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Link, "Context Menu") }), // keymappings atom.commands.add("atom-workspace", "codestream:keymap-create-comment", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Comment, "Shortcut") }), atom.commands.add("atom-workspace", "codestream:keymap-create-issue", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Issue, "Shortcut") }), atom.commands.add("atom-workspace", "codestream:keymap-get-permalink", { hiddenInCommandPalette: true, didDispatch: () => sendNewCodemarkRequest(CodemarkType.Link, "Shortcut") }), atom.commands.add("atom-workspace", "codestream:start-work", { hiddenInCommandPalette: true, didDispatch: () => sendStartWorkRequest("Shortcut") }), atom.commands.add("atom-workspace", "codestream:keymap-copy-permalink", { hiddenInCommandPalette: true, didDispatch: async () => { const editor = atom.workspace.getActiveTextEditor(); if (!editor) { return; } const response = await Container.session.agent.request( CreateDocumentMarkerPermalinkRequestType, { uri: Editor.getUri(editor), range: Editor.getCurrentSelectionRange(editor), privacy: "private" } ); atom.clipboard.write(response.linkUrl); atom.notifications.addInfo("Permalink copied to clipboard!"); } }) ); } async consumeStatusBar(statusBar: StatusBar) { const createStatusBarTitle = ( status: SessionStatus, unreads?: { totalMentions: number; totalUnreads: number } ) => { const environmentLabel = (() => { const env = Container.session.environment.name; switch (env) { case Environment.PD: case Environment.QA: return `${env}:`; default: return ""; } })(); const unreadsLabel = (() => { if (unreads) { if (unreads.totalMentions > 0) return `(${unreads.totalMentions})`; if (unreads.totalUnreads > 0) return "\u00a0\u2022"; } return ""; })(); switch (status) { case SessionStatus.SignedIn: return `${environmentLabel} ${Container.session.user!.username} ${unreadsLabel}`.trim(); case SessionStatus.SigningIn: return `Signing in...${environmentLabel}`.replace(":", ""); default: return `${environmentLabel} CodeStream`.trim(); } }; const getStatusBarIconClasses = ( status: SessionStatus, _unreads?: { totalMentions: number } ) => { if (status === SessionStatus.SigningIn) { return "icon loading loading-spinner-tiny inline-block".split(" "); } return "icon icon-comment-discussion".split(" "); }; const tileRoot = document.createElement("div"); tileRoot.classList.add("inline-block", "codestream-session-status"); tileRoot.onclick = event => { event.stopPropagation(); atom.commands.dispatch(document.querySelector("atom-workspace")!, "codestream:toggle"); }; const icon = document.createElement("span"); icon.classList.add(...getStatusBarIconClasses(Container.session.status)); tileRoot.appendChild(icon); atom.tooltips.add(tileRoot, { title: "Toggle CodeStream" }); const text = document.createElement("span"); tileRoot.appendChild(text); const statusBarTile = statusBar.addRightTile({ item: tileRoot, priority: 400 }); const sessionStatusSubscription = Container.session.observeSessionStatus(status => { text.innerText = createStatusBarTitle(status); icon.classList.remove(...icon.classList.values()); icon.classList.add(...getStatusBarIconClasses(Container.session.status)); }); this.environmentChangeEmitter.add(() => { text.innerText = createStatusBarTitle(Container.session.status); }); const dataChangeSubscription = Container.session.agent.onDidChangeData(event => { if (event.type === ChangeDataType.Unreads) { text.innerText = createStatusBarTitle(Container.session.status, event.data); } }); const statusBarDisposable = new Disposable(() => { sessionStatusSubscription.dispose(); dataChangeSubscription.dispose(); if (statusBarTile) { statusBarTile.destroy(); } }); this.subscriptions.add(statusBarDisposable); return statusBarDisposable; } consumeSplitDiff(splitDiff: SplitDiffService) { Container.diffController.splitDiffService = splitDiff; return new Disposable(() => { splitDiff.disable(); Container.diffController.splitDiffService = undefined; }); } } let codestream: CodestreamPackage | undefined; const packageWrapper = { // These methods will be favored over the ones in CodestreamPackage and they will delegate accordingly initialize(state: PackageState) { Container.initialize(state); if (Debug.isDebugging()) { console.debug("CodeStream package initialized with state:", state); } codestream = new CodestreamPackage(); }, async deactivate() { await codestream!.deactivate(); codestream = undefined; } }; // we need to export default for compatibilit with atom because it expects packages to be commonjs modules // eslint-disable-next-line import/no-default-export export default new Proxy(packageWrapper, { get(target: any, name: any) { if (Reflect.has(target, name)) { return target[name]; } if (codestream != null && Reflect.has(codestream, name)) { let property = codestream[name]; if (typeof property === "function") { property = property.bind(codestream); } return property; } return undefined; } });
the_stack
import {Expression} from "estree"; import {ParseException} from "../../wrangler/parse-exception"; import {SparkConstants} from "./spark-constants"; import {SparkExpressionType} from "./spark-expression-type"; declare const angular: angular.IAngularStatic; /** * Context for formatting a Spark conversion string. */ interface FormatContext { /** * Format parameters */ args: SparkExpression[]; /** * Current position within {@code args} */ index: number; } /** * An expression in a Spark script. */ export class SparkExpression { /** Constants that calculate the min and max value of an integer in Scala or Java */ static SCALA_MIN_INT: number = (-1) * Math.pow(2, 31); static SCALA_MAX_INT: number = Math.pow(2, 31) - 1; /** Regular expression for conversion strings */ static FORMAT_REGEX = /%([?*,@]*)([bcdfors])/g; /** TernJS directive for the Spark code */ static SPARK_DIRECTIVE = "!spark"; /** TernJS directive for the return type */ static TYPE_DIRECTIVE = "!sparkType"; /** * Constructs a {@code SparkExpression} * * @param source - Spark source code * @param type - result type * @param start - column of the first character in the original expression * @param end - column of the last character in the original expression */ constructor(public source: string | SparkExpression[], public type: SparkExpressionType, public start: number, public end: number) { } /** * Formats the specified string by replacing the type specifiers with the specified parameters. * * @param str - the Spark conversion string to be formatted * @param args - the format parameters * @returns the formatted string * @throws {Error} if the conversion string is not valid * @throws {ParseException} if a format parameter cannot be converted to the specified type */ static format(str: string, ...args: SparkExpression[]): string { // Convert arguments let context = { args: Array.prototype.slice.call(arguments, 1), index: 0 } as FormatContext; let result = str.replace(SparkExpression.FORMAT_REGEX, angular.bind(str, SparkExpression.replace, context) as any); // Verify all arguments converted if (context.index >= context.args.length) { return result; } else { throw new ParseException("Too many arguments for conversion."); } } /** * Creates a Spark expression from a function definition. * * @param definition - the function definition * @param node - the source abstract syntax tree * @param var_args - the format parameters * @returns the Spark expression * @throws {Error} if the function definition is not valid * @throws {ParseException} if a format parameter cannot be converted to the required type */ static fromDefinition(definition: any, node: acorn.Node, ...var_args: SparkExpression[]): SparkExpression { // Convert Spark string to code const args = [definition[SparkExpression.SPARK_DIRECTIVE]]; Array.prototype.push.apply(args, Array.prototype.slice.call(arguments, 2)); const source = SparkExpression.format.apply(SparkExpression, args); // Return expression return new SparkExpression(source, SparkExpressionType.valueOf(definition[SparkExpression.TYPE_DIRECTIVE]), node.start, node.end); } /** * Converts the next argument to the specified type for a Spark conversion string. * * @param context - the format context * @param match - the conversion specification * @param flags - the conversion flags * @param type - the type specifier * @returns the converted Spark code * @throws {Error} if the type specifier is not supported * @throws {ParseException} if the format parameter cannot be converted to the specified type */ private static replace(context: FormatContext, match: string, flags: string, type: string): string { // Parse flags let arrayType = null; let comma = false; let end = context.index + 1; for (let i = 0; i < flags.length; ++i) { switch (flags.charAt(i)) { case ",": comma = true; break; case "?": end = (context.index < context.args.length) ? end : 0; break; case "*": end = context.args.length; break; case "@": arrayType = type; type = "@"; break; default: throw new Error("Unsupported conversion flag: " + flags.charAt(i)); } } // Validate arguments if (end > context.args.length) { throw new ParseException("Not enough arguments for conversion"); } // Convert to requested type let first = true; let result = ""; for (; context.index < end; ++context.index) { // Argument separator if (comma || !first) { result += ", "; } else { first = false; } // Conversion let arg = context.args[context.index]; switch (type) { case "b": result += SparkExpression.toBoolean(arg); break; case "c": result += SparkExpression.toColumn(arg); break; case "d": result += SparkExpression.toInteger(arg); break; case "f": result += SparkExpression.toDouble(arg); break; case "o": result += SparkExpression.toObject(arg); break; case "r": result += SparkExpression.toDataFrame(arg); break; case "s": result += SparkExpression.toString(arg); break; case "@": result += SparkExpression.toArray(arg, arrayType); break; default: throw new Error("Not a recognized conversion type: " + type); } } return result; } /** * Converts the specified Spark expression to an array. * * @param expression - the Spark expression * @param type - the type specifier * @returns the Spark code for the array * @throws {ParseException} if the expression cannot be converted to an array */ private static toArray(expression: SparkExpression, type: string): string { if (SparkExpressionType.ARRAY.equals(expression.type)) { let source = expression.source as SparkExpression[]; return "Array(" + source .map(function (e) { return SparkExpression.format("%" + type, e); }) .join(", ") + ")"; } else { throw new ParseException("Expression cannot be converted to an array: " + expression.type, expression.start); } } /** * Converts the specified Spark expression to a boolean literal. * * @param expression - the Spark expression * @returns the Spark code for the boolean * @throws {ParseException} if the expression cannot be converted to a boolean */ private static toBoolean(expression: SparkExpression): string { if (SparkExpressionType.LITERAL.equals(expression.type) && (expression.source === "true" || expression.source === "false")) { return expression.source; } else { throw new ParseException("Expression cannot be converted to a boolean: " + expression.type, expression.start); } } /** * Converts the specified Spark expression to a Column type. * * @param expression - the Spark expression * @returns the Spark code for the new type * @throws {ParseException} if the expression cannot be converted to a column */ private static toColumn(expression: SparkExpression): string { if (SparkExpressionType.COLUMN.equals(expression.type)) { return expression.source as string; } if (SparkExpressionType.LITERAL.equals(expression.type)) { let literal : string; if ((expression.source as string).charAt(0) === "\"" || (expression.source as string).charAt(0) === "'") { literal = SparkExpression.toString(expression); } else { literal = expression.source as string; let nLiteral : number = parseInt(expression.source as string); if( !isNaN(nLiteral) ) { if (nLiteral < SparkExpression.SCALA_MIN_INT || nLiteral > SparkExpression.SCALA_MAX_INT) { literal = literal + "L"; } } } return "functions.lit(" + literal + ")"; } throw new ParseException("Expression cannot be converted to a column: " + expression.type, expression.start); } /** * Converts the specified Spark expression to a DataFrame type. * * @param expression - the Spark expression * @returns the Spark code for the new type * @throws {ParseException} if the expression cannot be converted to a DataFrame */ private static toDataFrame(expression: SparkExpression): string { if (SparkExpressionType.DATA_FRAME.equals(expression.type)) { return SparkConstants.DATA_FRAME_VARIABLE + expression.source; } throw new ParseException("Expression cannot be converted to a DataFrame: " + expression.type, expression.start); } /** * Converts the specified Spark expression to a double. * * @param expression - the Spark expression * @returns the Spark code for the double * @throws {ParseException} if the expression cannot be converted to a double */ private static toDouble(expression: SparkExpression): string { if (SparkExpressionType.LITERAL.equals(expression.type) && (expression.source as string).match(/^(0|-?[1-9][0-9]*)(\.[0-9]+)?$/) !== null) { return expression.source as string; } else { throw new ParseException("Expression cannot be converted to an integer: " + expression.type, expression.start); } } /** * Converts the specified Spark expression to an integer. * * @param expression - the Spark expression * @returns the Spark code for the integer * @throws {ParseException} if the expression cannot be converted to a number */ private static toInteger(expression: SparkExpression): string { if (SparkExpressionType.LITERAL.equals(expression.type) && (expression.source as string).match(/^(0|-?[1-9][0-9]*)$/) !== null) { return expression.source as string; } else { throw new ParseException("Expression cannot be converted to an integer: " + expression.type, expression.start); } } /** * Converts the specified Spark expression to an object. * * @param expression - the Spark expression * @returns the Spark code for the object * @throws {ParseException} if the expression cannot be converted to an object */ private static toObject(expression: SparkExpression): string { if (SparkExpressionType.isObject(expression.type.toString())) { return expression.source as string; } else if (SparkExpressionType.LITERAL.equals(expression.type)) { if ((expression.source as string).charAt(0) === "\"" || (expression.source as string).charAt(0) === "'") { return SparkExpression.toString(expression); } else { return expression.source as string; } } else { throw new ParseException("Expression cannot be converted to an object: " + expression.type, expression.start); } } /** * Converts the specified Spark expression to a string literal. * * @param expression - the Spark expression * @returns the Spark code for the string literal * @throws {ParseException} if the expression cannot be converted to a string */ private static toString(expression: SparkExpression): string { if (!SparkExpressionType.LITERAL.equals(expression.type)) { throw new ParseException("Expression cannot be converted to a string: " + expression.type, expression.start); } if ((expression.source as string).charAt(0) === "\"") { return expression.source as string; } if ((expression.source as string).charAt(0) === "'") { return "\"" + (expression.source as string).substr(1, expression.source.length - 2).replace(/"/g, "\\\"") + "\""; } return "\"" + expression.source + "\""; } }
the_stack
import {LOCALES} from '../locales'; export default { property: { weight: 'painotus', label: 'nimiö', fillColor: 'täyttöväri', color: 'väri', strokeColor: 'viivan väri', radius: 'säde', outline: 'ääriviiva', stroke: 'viiva', density: 'tiheys', coverage: 'kattavuus', sum: 'summa', pointCount: 'pisteiden lukumäärä' }, placeholder: { search: 'Etsi', selectField: 'Valitse kenttä', yAxis: 'Y-akseli', selectType: 'Valitse tyyppi', selectValue: 'Valitse arvo', enterValue: 'Anna arvo', empty: 'tyhjä' }, misc: { by: '', valuesIn: 'Arvot joukossa:', valueEquals: 'Arvo on yhtäsuuri kuin', dataSource: 'Aineistolähde', brushRadius: 'Harjan säde (km)', empty: ' ' }, mapLayers: { title: 'Kartan tasot', label: 'Nimiöt', road: 'Tiet', border: 'Rajat', building: 'Rakennukset', water: 'Vesi', land: 'Maa', '3dBuilding': '3d-rakennukset' }, panel: { text: { label: 'Nimiö', labelWithId: 'Nimiö {labelId}', fontSize: 'Fontin koko', fontColor: 'Fontin väri', textAnchor: 'Tekstin ankkuri', alignment: 'Sijoittelu', addMoreLabel: 'Lisää uusia nimiöitä' } }, sidebar: { panels: { layer: 'Tasot', filter: 'Suodattimet', interaction: 'Interaktiot', basemap: 'Taustakartta' } }, layer: { required: 'Pakollinen*', radius: 'Säde', weight: 'Painotus', propertyBasedOn: '{property} perustuen arvoon', color: 'Väri', fillColor: 'Täytön väri', outline: 'ääriviiva', coverage: 'Kattavuus', stroke: 'Viiva', strokeWidth: 'Viivan paksuus', strokeColor: 'Viivan väri', basic: 'Perus', trailLength: 'Jäljen pituus', trailLengthDescription: 'Jäljen kesto sekunteina, ennenkuin se himmenee näkyvistä', newLayer: 'uusi taso', elevationByDescription: 'Kun asetus on pois päältä, korkeus perustuu pisteiden määrään', colorByDescription: 'Kun asetus on pois päältä, väri perustuu pisteiden määrään', aggregateBy: 'Aggregoi kenttä {field} by', '3DModel': '3D-malli', '3DModelOptions': '3D-mallin asetukset', type: { point: 'piste', arc: 'kaari', line: 'viiva', grid: 'ruudukko', hexbin: 'hexbin', polygon: 'polygoni', geojson: 'geojson', cluster: 'klusteri', icon: 'kuva', heatmap: 'lämpökartta', hexagon: 'kuusikulmio', hexagonid: 'H3', trip: 'matka', s2: 'S2', '3d': '3D' } }, layerVisConfigs: { strokeWidth: 'Viivan paksuus', strokeWidthRange: 'Viivan paksuuden rajat', radius: 'Säde', fixedRadius: 'Vakiosäde metreinä', fixedRadiusDescription: 'Kartan säde absoluuttiseksi säteeksi metreinä, esim. 5 -> 5 metriin', radiusRange: 'Säteen rajat', clusterRadius: 'Klusterien säde pikseleinä', radiusRangePixels: 'Säteen rajat pikseleinä', opacity: 'Läpinäkyvyys', coverage: 'Kattavuus', outline: 'Ääriviiva', colorRange: 'Värien rajat', stroke: 'Viiva', strokeColor: 'Viivan väri', strokeColorRange: 'Viivan värin rajat', targetColor: 'Kohteen väri', colorAggregation: 'Värien aggregointi', heightAggregation: 'Korkeuden aggregointi', resolutionRange: 'Resoluution rajat', sizeScale: 'Koon skaala', worldUnitSize: 'Yksikkö', elevationScale: 'Korottamisen skaala', enableElevationZoomFactor: 'Käytä korkeuden zoomauskerrointa', enableElevationZoomFactorDescription: 'Säädä korkeus / korkeus nykyisen zoomauskertoimen perusteella', enableHeightZoomFactor: 'Käytä korkeuden zoomauskerrointa', heightScale: 'Korkeuden skaala', coverageRange: 'Peittävyyden rajat', highPrecisionRendering: 'Tarkka renderöinti', highPrecisionRenderingDescription: 'Tarkka renderöinti johtaa hitaampaan suorittamiseen', height: 'Korkeus', heightDescription: 'Klikkaa oikeasta ylänurkasta nappia vaihtaaksesi 3D-näkymään', fill: 'Täyttö', enablePolygonHeight: 'Salli polygonien korkeus', showWireframe: 'Näytä rautalankamalli', weightIntensity: 'Painotuksen intensiteetti', zoomScale: 'Zoomausskaala', heightRange: 'Korkeuden rajat', heightMultiplier: 'Korkeuskerroin' }, layerManager: { addData: 'Lisää aineisto', addLayer: 'Lisää taso', layerBlending: 'Tasojen sekoittuvuus' }, mapManager: { mapStyle: 'Kartan tyyli', addMapStyle: 'Lisää tyyli kartalle', '3dBuildingColor': '3D-rakennusten väri' }, layerConfiguration: { defaultDescription: 'Laske suureen {property} arvo valitun kentän perusteella', howTo: 'Miten toimii' }, filterManager: { addFilter: 'Lisää suodatin' }, datasetTitle: { showDataTable: 'Näytä attribuuttitaulu', removeDataset: 'Poista aineisto' }, datasetInfo: { rowCount: '{rowCount} riviä' }, tooltip: { hideLayer: 'Piilota taso', showLayer: 'Näytä taso', hideFeature: 'Piilota kohde', showFeature: 'Näytä kohde', hide: 'piilota', show: 'näytä', removeLayer: 'Poista taso', layerSettings: 'Tason asetukset', closePanel: 'Sulje paneeli', switchToDualView: 'Vaihda kaksoiskarrtanäkymään', showLegend: 'Näytä selite', disable3DMap: 'Poistu 3D-näkymästä', DrawOnMap: 'Piirrä kartalle', selectLocale: 'Valitse kielisyys', hideLayerPanel: 'Piilota tasopaneeli', showLayerPanel: 'Näytä tasopaneeli', moveToTop: 'Siirrä tasojen päällimmäiseksi', selectBaseMapStyle: 'Valitse taustakarttatyyli', delete: 'Poista', timePlayback: 'Ajan animointi', cloudStorage: 'Pilvitallennus', '3DMap': '3D-näkymä' }, toolbar: { exportImage: 'Vie kuva', exportData: 'Vie aineistot', exportMap: 'Vie kartta', shareMapURL: 'Jaa kartan URL', saveMap: 'Tallenna kartta', select: 'valitse', polygon: 'polygoni', rectangle: 'nelikulmio', hide: 'piilota', show: 'näytä', ...LOCALES }, modal: { title: { deleteDataset: 'Poista aineisto', addDataToMap: 'Lisää aineistoja kartalle', exportImage: 'Vie kuva', exportData: 'Vie aineistot', exportMap: 'Vie kartta', addCustomMapboxStyle: 'Lisää oma Mapbox-tyyli', saveMap: 'Tallenna kartta', shareURL: 'Jaa URL' }, button: { delete: 'Poista', download: 'Lataa', export: 'Vie', addStyle: 'Lisää tyyli', save: 'Tallenna', defaultCancel: 'Peru', defaultConfirm: 'Vahvista' }, exportImage: { ratioTitle: 'Kuvasuhde', ratioDescription: 'Valitse sopiva kuvasuhde käyttötapaustasi varten.', ratioOriginalScreen: 'Alkuperäinen näyttö', ratioCustom: 'Kustomoitu', ratio4_3: '4:3', ratio16_9: '16:9', resolutionTitle: 'Resoluutio', resolutionDescription: 'Korkea resoluutio on parempi tulostamista varten.', mapLegendTitle: 'Kartan selite', mapLegendAdd: 'Lisää selite karttaan' }, exportData: { datasetTitle: 'Aineistot', datasetSubtitle: 'Valitse aineisto, jonka aiot viedä', allDatasets: 'Kaikki', dataTypeTitle: 'Aineistojen formaatti', dataTypeSubtitle: 'Valitse aineistoformaatti valitsemillesi aineistoille', filterDataTitle: 'Suodata aineistoja', filterDataSubtitle: 'Voit viedä joko alkuperäiset aineistot tai suodatetut aineistot', filteredData: 'Suodatetut aineistot', unfilteredData: 'Suodattamattomat aineistot', fileCount: '{fileCount} tiedostoa', rowCount: '{rowCount} riviä' }, deleteData: { warning: 'aiot poistaa tämän aineiston. Aineostoa käyttävien tasojen lukumäärä: {length}' }, addStyle: { publishTitle: '1. Julkaise tyylisi Mapboxissa tai anna tunniste', publishSubtitle1: 'Voit luoda oman karttatyylisi sivulla', publishSubtitle2: 'ja', publishSubtitle3: 'julkaista', publishSubtitle4: 'sen.', publishSubtitle5: 'Käyttääksesi yksityistä tyyliä, liitä', publishSubtitle6: 'tunnisteesi', publishSubtitle7: 'tänne. *kepler.gl on client-side sovellus, data pysyy vain selaimessasi...', exampleToken: 'esim. pk.abcdefg.xxxxxx', pasteTitle: '2. Liitä tyyli-URL', pasteSubtitle1: 'Mikä on', pasteSubtitle2: 'tyyli-URL?', namingTitle: '3. Nimeä tyylisi' }, shareMap: { shareUriTitle: 'Jaa kartan URL', shareUriSubtitle: 'Luo kartalle URL, jonka voit jakaa muiden kanssa', cloudTitle: 'Pilvitallennus', cloudSubtitle: 'Kirjaudu sisään ja lataa kartta ja aineistot henkilökohtaiseen pilvipalveluun', shareDisclaimer: 'kepler.gl tallentaa kartan datan henkilökohtaiseen pilvitallennustilaasi, vain ihmiset, joilla on URL, voivat päästä käsiksi karttaan ja aineistoihin. ' + 'Voit muokata tiedostoja tai poistaa ne pilvipalvelustasi milloin vain.', gotoPage: 'Mene Kepler.gl {currentProvider} sivullesi' }, statusPanel: { mapUploading: 'Karttaa ladataan', error: 'Virhe' }, saveMap: { title: 'Pilvitallennus', subtitle: 'Kirjaudu sisään pilvipalveluusi tallentaaksesi kartan' }, exportMap: { formatTitle: 'Kartan formaatti', formatSubtitle: 'Valitse formaatti, jossa viet kartan', html: { selection: 'Vie kartta interaktiivisena html-tiedostona', tokenTitle: 'Mapbox-tunniste', tokenSubtitle: 'Käytä omaa Mapbox-tunnistettasi html-tiedostossa (valinnainen)', tokenPlaceholder: 'Liitä Mapbox-tunnisteesi', tokenMisuseWarning: '* Jos et käytä omaa tunnistettasi, kartta voi lakata toimimasta milloin vain kun vaihdamme omaa tunnistettamme väärinkäytön estämiseksi. ', tokenDisclaimer: 'Voit vaihtaa Mapbox-tunnisteesi näiden ohjeiden avulla: ', tokenUpdate: 'Kuinka vaihtaa olemassaoleva Mapbox-tunniste', modeTitle: 'Kartan tila', modeSubtitle1: 'Valitse kartan tila.', modeSubtitle2: 'Lisätietoja', modeDescription: 'Anna käyttäjien {mode} karttaa', read: 'lukea', edit: 'muokata' }, json: { configTitle: 'Kartan asetukset', configDisclaimer: 'Kartan asetukset sisältyvät Json-tiedostoon. Jos käytät kirjastoa kepler.gl omassa sovelluksessasi. Voit kopioida asetukset ja antaa ne funktiolle: ', selection: 'Vie kyseisen kartan aineistot ja asetukset yhdessä json-tiedostossa. Voit myöhemmin avata saman kartan lataamalla tiedoston kepler.gl:n', disclaimer: '* Kartan asetukset ovat sidoksissa ladattuihin aineistoihin. Arvoa ‘dataId’ käytetään tasojen, suodattimien ja vihjeiden liittämiseksi tiettyyn aineistoon. ' + 'Varmista, että aineiston dataId:t vastaavat asetusten arvoja jos lataat asetukset käyttäen `addDataToMap`-funktiolle.' } }, loadingDialog: { loading: 'Ladataan...' }, loadData: { upload: 'Lataa tiedostot', storage: 'Lataa tallennustilasta' }, tripInfo: { title: 'Kuinka käyttää matka-animaatiota', description1: 'Reitin animoimiseksi geoJSON-aineiston täytyy olla geometriatyypiltään `LineString`, LineString-koordinaattien täytyy sisältää 4 elementtiä formaatissa:', code: ' [pituusaste, leveysaste, korkeus, aikaleima] ', description2: 'siten, että viimeinen elementti on aikaleima. Aikaleima voi olla muodoltaan unix-sekunteja, kuten `1564184363` tai millisekunteja, kuten `1564184363000`.', example: 'Esimerkki:' }, iconInfo: { title: 'Miten piirtää kuvia', description1: 'csv-tiedostossasi, luo sarake nimeltä icon. Voit jättää sen tyhjäksi jos et halua piirtää kuvaa joillain pisteillä. Kun sarakkeen nimi on ', code: 'icon', description2: ' kepler.gl luo automaattisesti kuvatason sinua varten.', example: 'Esimerkki:', icons: 'Kuvat' }, storageMapViewer: { lastModified: 'Viimeksi muokattu {lastUpdated} sitten', back: 'Takaisin' }, overwriteMap: { title: 'Tallennetaan karttaa...', alreadyExists: 'on jo {mapSaved}:ssa. Haluatko ylikirjoittaa sen?' }, loadStorageMap: { back: 'Takaisin', goToPage: 'Mene Kepler.gl {displayName} sivullesi', storageMaps: 'Tallennus / Kartat', noSavedMaps: 'Ei tallennettuja karttoja vielä' } }, header: { visibleLayers: 'Näkyvissä olevat tasot', layerLegend: 'Tason selite' }, interactions: { tooltip: 'Vihje', brush: 'Harja', coordinate: 'Koordinaatit' }, layerBlending: { title: 'Tasojen sekoittuvuus', additive: 'lisäävä', normal: 'normaali', subtractive: 'vähentävä' }, columns: { title: 'Sarakkeet', lat: 'lat', lng: 'lng', altitude: 'korkeus', icon: 'kuva', geojson: 'geojson', arc: { lat0: 'lähdön lat', lng0: 'lähdön lng', lat1: 'kohteen lat', lng1: 'kohteen lng' }, line: { alt0: 'lähteen korkeus', alt1: 'kohde korkeus' }, grid: { worldUnitSize: 'Ruutujen koko (km)' }, hexagon: { worldUnitSize: 'Hexagonien säde (km)' } }, color: { customPalette: 'Mukautettu paletti', steps: 'askeleet', type: 'tyyppi', reversed: 'käänteinen' }, scale: { colorScale: 'Värin skaala', sizeScale: 'Koon skaala', strokeScale: 'Viivan paksuuden skaala', scale: 'Skaala' }, fileUploader: { message: 'Raahaa ja pudota tiedostosi tänne', chromeMessage: '*Chromen käyttäjä: Rajoita tiedostokokosi 250Mb:hen. Jos haluat suurempia tiedostoja, kokeile Safaria', disclaimer: '*kepler.gl on client-side sovellus, data pysyy vain selaimessasi...' + 'Tietoja ei lähetetä palvelimelle.', configUploadMessage: 'Lisää {fileFormatNames} tai tallennettu kartta **Json**. Lue lisää [**tuetuista formaateista**]', browseFiles: 'selaa tiedostojasi', uploading: 'ladataan', fileNotSupported: 'Tiedosto {errorFiles} ei ole tuettu.', or: 'tai' }, density: 'tiheys', 'Bug Report': 'Bugiraportointi', 'User Guide': 'Opas', Save: 'Tallenna', Share: 'Jaa' };
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version } from '@microsoft/sp-core-library'; import { IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-property-pane'; import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base'; import * as strings from 'HelloTailwindCssWebPartStrings'; import HelloTailwindCss from './components/HelloTailwindCss'; import { IHelloTailwindCssProps } from './components/IHelloTailwindCssProps'; import { ThemeProvider, ThemeChangedEventArgs, IReadonlyTheme } from '@microsoft/sp-component-base'; export interface IHelloTailwindCssWebPartProps { description: string; } export default class HelloTailwindCssWebPart extends BaseClientSideWebPart<IHelloTailwindCssWebPartProps> { private _themeProvider: ThemeProvider; private _themeVariant: IReadonlyTheme | undefined; protected onInit(): Promise<void> { // Consume the new ThemeProvider service this._themeProvider = this.context.serviceScope.consume(ThemeProvider.serviceKey); // If it exists, get the theme variant this._themeVariant = this._themeProvider.tryGetTheme(); // Register a handler to be notified if the theme variant changes this._themeProvider.themeChangedEvent.add(this, this._handleThemeChangedEvent); // Apply theme variant as CSS Variables at current DOM node this._applyThemeVariant(); return super.onInit(); } private _handleThemeChangedEvent(args: ThemeChangedEventArgs): void { this._themeVariant = args.theme; this._applyThemeVariant(); this.render(); } private _applyThemeVariant() { let style = this.domElement.style; style.setProperty('--tw-fui-themeDarker', this._themeVariant.palette.themeDarker); style.setProperty('--tw-fui-themeDark', this._themeVariant.palette.themeDark); style.setProperty('--tw-fui-themeDarkAlt', this._themeVariant.palette.themeDarkAlt); style.setProperty('--tw-fui-themePrimary', this._themeVariant.palette.themePrimary); style.setProperty('--tw-fui-themeSecondary', this._themeVariant.palette.themeSecondary); style.setProperty('--tw-fui-themeTertiary', this._themeVariant.palette.themeTertiary); style.setProperty('--tw-fui-themeLight', this._themeVariant.palette.themeLight); style.setProperty('--tw-fui-themeLighter', this._themeVariant.palette.themeLighter); style.setProperty('--tw-fui-themeLighterAlt', this._themeVariant.palette.themeLighterAlt); style.setProperty('--tw-fui-black', this._themeVariant.palette.black); style.setProperty('--tw-fui-blackTranslucent40', this._themeVariant.palette.blackTranslucent40); style.setProperty('--tw-fui-neutralDark', this._themeVariant.palette.neutralDark); style.setProperty('--tw-fui-neutralPrimary', this._themeVariant.palette.neutralPrimary); style.setProperty('--tw-fui-neutralPrimaryAlt', this._themeVariant.palette.neutralPrimaryAlt); style.setProperty('--tw-fui-neutralSecondary', this._themeVariant.palette.neutralSecondary); style.setProperty('--tw-fui-neutralSecondaryAlt', this._themeVariant.palette.neutralSecondaryAlt); style.setProperty('--tw-fui-neutralTertiary', this._themeVariant.palette.neutralTertiary); style.setProperty('--tw-fui-neutralTertiaryAlt', this._themeVariant.palette.neutralTertiaryAlt); style.setProperty('--tw-fui-neutralQuaternary', this._themeVariant.palette.neutralQuaternary); style.setProperty('--tw-fui-neutralQuaternaryAlt', this._themeVariant.palette.neutralQuaternaryAlt); style.setProperty('--tw-fui-neutralLight', this._themeVariant.palette.neutralLight); style.setProperty('--tw-fui-neutralLighter', this._themeVariant.palette.neutralLighter); style.setProperty('--tw-fui-neutralLighterAlt', this._themeVariant.palette.neutralLighterAlt); style.setProperty('--tw-fui-accent', this._themeVariant.palette.accent); style.setProperty('--tw-fui-white', this._themeVariant.palette.white); style.setProperty('--tw-fui-whiteTranslucent40', this._themeVariant.palette.whiteTranslucent40); style.setProperty('--tw-fui-yellow', this._themeVariant.palette.yellow); style.setProperty('--tw-fui-yellowLight', this._themeVariant.palette.yellowLight); style.setProperty('--tw-fui-orange', this._themeVariant.palette.orange); style.setProperty('--tw-fui-orangeLight', this._themeVariant.palette.orangeLight); style.setProperty('--tw-fui-orangeLighter', this._themeVariant.palette.orangeLighter); style.setProperty('--tw-fui-redDark', this._themeVariant.palette.redDark); style.setProperty('--tw-fui-red', this._themeVariant.palette.red); style.setProperty('--tw-fui-magentaDark', this._themeVariant.palette.magentaDark); style.setProperty('--tw-fui-magenta', this._themeVariant.palette.magenta); style.setProperty('--tw-fui-magentaLight', this._themeVariant.palette.magentaLight); style.setProperty('--tw-fui-purpleDark', this._themeVariant.palette.purpleDark); style.setProperty('--tw-fui-purple', this._themeVariant.palette.purple); style.setProperty('--tw-fui-purpleLight', this._themeVariant.palette.purpleLight); style.setProperty('--tw-fui-blueDark', this._themeVariant.palette.blueDark); style.setProperty('--tw-fui-blueMid', this._themeVariant.palette.blueMid); style.setProperty('--tw-fui-blue', this._themeVariant.palette.blue); style.setProperty('--tw-fui-blueLight', this._themeVariant.palette.blueLight); style.setProperty('--tw-fui-tealDark', this._themeVariant.palette.tealDark); style.setProperty('--tw-fui-teal', this._themeVariant.palette.teal); style.setProperty('--tw-fui-tealLight', this._themeVariant.palette.tealLight); style.setProperty('--tw-fui-greenDark', this._themeVariant.palette.greenDark); style.setProperty('--tw-fui-green', this._themeVariant.palette.green); style.setProperty('--tw-fui-greenLight', this._themeVariant.palette.greenLight); style.setProperty('--tw-fui-bodyBackground', this._themeVariant.semanticColors.bodyBackground); style.setProperty('--tw-fui-bodyStandoutBackground', this._themeVariant.semanticColors.bodyStandoutBackground); style.setProperty('--tw-fui-bodyFrameBackground', this._themeVariant.semanticColors.bodyFrameBackground); style.setProperty('--tw-fui-bodyFrameDivider', this._themeVariant.semanticColors.bodyFrameDivider); style.setProperty('--tw-fui-bodyText', this._themeVariant.semanticColors.bodyText); style.setProperty('--tw-fui-bodyTextChecked', this._themeVariant.semanticColors.bodyTextChecked); style.setProperty('--tw-fui-bodySubtext', this._themeVariant.semanticColors.bodySubtext); style.setProperty('--tw-fui-bodyDivider', this._themeVariant.semanticColors.bodyDivider); style.setProperty('--tw-fui-disabledBackground', this._themeVariant.semanticColors.disabledBackground); style.setProperty('--tw-fui-disabledText', this._themeVariant.semanticColors.disabledText); style.setProperty('--tw-fui-disabledSubtext', this._themeVariant.semanticColors.disabledSubtext); style.setProperty('--tw-fui-disabledBodyText', this._themeVariant.semanticColors.disabledBodyText); style.setProperty('--tw-fui-disabledBodySubtext', this._themeVariant.semanticColors.disabledBodySubtext); style.setProperty('--tw-fui-focusBorder', this._themeVariant.semanticColors.focusBorder); style.setProperty('--tw-fui-variantBorder', this._themeVariant.semanticColors.variantBorder); style.setProperty('--tw-fui-variantBorderHovered', this._themeVariant.semanticColors.variantBorderHovered); style.setProperty('--tw-fui-defaultStateBackground', this._themeVariant.semanticColors.defaultStateBackground); style.setProperty('--tw-fui-errorText', this._themeVariant.semanticColors.errorText); style.setProperty('--tw-fui-warningText', this._themeVariant.semanticColors.warningText); style.setProperty('--tw-fui-errorBackground', this._themeVariant.semanticColors.errorBackground); style.setProperty('--tw-fui-blockingBackground', this._themeVariant.semanticColors.blockingBackground); style.setProperty('--tw-fui-warningBackground', this._themeVariant.semanticColors.warningBackground); style.setProperty('--tw-fui-warningHighlight', this._themeVariant.semanticColors.warningHighlight); style.setProperty('--tw-fui-successBackground', this._themeVariant.semanticColors.successBackground); style.setProperty('--tw-fui-inputBorder', this._themeVariant.semanticColors.inputBorder); style.setProperty('--tw-fui-inputBorderHovered', this._themeVariant.semanticColors.inputBorderHovered); style.setProperty('--tw-fui-inputBackground', this._themeVariant.semanticColors.inputBackground); style.setProperty('--tw-fui-inputBackgroundChecked', this._themeVariant.semanticColors.inputBackgroundChecked); style.setProperty('--tw-fui-inputBackgroundCheckedHovered', this._themeVariant.semanticColors.inputBackgroundCheckedHovered); style.setProperty('--tw-fui-inputForegroundChecked', this._themeVariant.semanticColors.inputForegroundChecked); style.setProperty('--tw-fui-inputFocusBorderAlt', this._themeVariant.semanticColors.inputFocusBorderAlt); style.setProperty('--tw-fui-smallInputBorder', this._themeVariant.semanticColors.smallInputBorder); style.setProperty('--tw-fui-inputText', this._themeVariant.semanticColors.inputText); style.setProperty('--tw-fui-inputTextHovered', this._themeVariant.semanticColors.inputTextHovered); style.setProperty('--tw-fui-inputPlaceholderText', this._themeVariant.semanticColors.inputPlaceholderText); style.setProperty('--tw-fui-buttonBackground', this._themeVariant.semanticColors.buttonBackground); style.setProperty('--tw-fui-buttonBackgroundChecked', this._themeVariant.semanticColors.buttonBackgroundChecked); style.setProperty('--tw-fui-buttonBackgroundHovered', this._themeVariant.semanticColors.buttonBackgroundHovered); style.setProperty('--tw-fui-buttonBackgroundCheckedHovered', this._themeVariant.semanticColors.buttonBackgroundCheckedHovered); style.setProperty('--tw-fui-buttonBackgroundPressed', this._themeVariant.semanticColors.buttonBackgroundPressed); style.setProperty('--tw-fui-buttonBackgroundDisabled', this._themeVariant.semanticColors.buttonBackgroundDisabled); style.setProperty('--tw-fui-buttonBorder', this._themeVariant.semanticColors.buttonBorder); style.setProperty('--tw-fui-buttonText', this._themeVariant.semanticColors.buttonText); style.setProperty('--tw-fui-buttonTextHovered', this._themeVariant.semanticColors.buttonTextHovered); style.setProperty('--tw-fui-buttonTextChecked', this._themeVariant.semanticColors.buttonTextChecked); style.setProperty('--tw-fui-buttonTextCheckedHovered', this._themeVariant.semanticColors.buttonTextCheckedHovered); style.setProperty('--tw-fui-buttonTextPressed', this._themeVariant.semanticColors.buttonTextPressed); style.setProperty('--tw-fui-buttonTextDisabled', this._themeVariant.semanticColors.buttonTextDisabled); style.setProperty('--tw-fui-buttonBorderDisabled', this._themeVariant.semanticColors.buttonBorderDisabled); style.setProperty('--tw-fui-primaryButtonBackground', this._themeVariant.semanticColors.primaryButtonBackground); style.setProperty('--tw-fui-primaryButtonBackgroundHovered', this._themeVariant.semanticColors.primaryButtonBackgroundHovered); style.setProperty('--tw-fui-primaryButtonBackgroundPressed', this._themeVariant.semanticColors.primaryButtonBackgroundPressed); style.setProperty('--tw-fui-primaryButtonBackgroundDisabled', this._themeVariant.semanticColors.primaryButtonBackgroundDisabled); style.setProperty('--tw-fui-primaryButtonBorder', this._themeVariant.semanticColors.primaryButtonBorder); style.setProperty('--tw-fui-primaryButtonText', this._themeVariant.semanticColors.primaryButtonText); style.setProperty('--tw-fui-primaryButtonTextHovered', this._themeVariant.semanticColors.primaryButtonTextHovered); style.setProperty('--tw-fui-primaryButtonTextPressed', this._themeVariant.semanticColors.primaryButtonTextPressed); style.setProperty('--tw-fui-primaryButtonTextDisabled', this._themeVariant.semanticColors.primaryButtonTextDisabled); style.setProperty('--tw-fui-accentButtonBackground', this._themeVariant.semanticColors.accentButtonBackground); style.setProperty('--tw-fui-accentButtonText', this._themeVariant.semanticColors.accentButtonText); style.setProperty('--tw-fui-menuBackground', this._themeVariant.semanticColors.menuBackground); style.setProperty('--tw-fui-menuDivider', this._themeVariant.semanticColors.menuDivider); style.setProperty('--tw-fui-menuIcon', this._themeVariant.semanticColors.menuIcon); style.setProperty('--tw-fui-menuHeader', this._themeVariant.semanticColors.menuHeader); style.setProperty('--tw-fui-menuItemBackgroundHovered', this._themeVariant.semanticColors.menuItemBackgroundHovered); style.setProperty('--tw-fui-menuItemBackgroundPressed', this._themeVariant.semanticColors.menuItemBackgroundPressed); style.setProperty('--tw-fui-menuItemText', this._themeVariant.semanticColors.menuItemText); style.setProperty('--tw-fui-menuItemTextHovered', this._themeVariant.semanticColors.menuItemTextHovered); style.setProperty('--tw-fui-listBackground', this._themeVariant.semanticColors.listBackground); style.setProperty('--tw-fui-listText', this._themeVariant.semanticColors.listText); style.setProperty('--tw-fui-listItemBackgroundHovered', this._themeVariant.semanticColors.listItemBackgroundHovered); style.setProperty('--tw-fui-listItemBackgroundChecked', this._themeVariant.semanticColors.listItemBackgroundChecked); style.setProperty('--tw-fui-listItemBackgroundCheckedHovered', this._themeVariant.semanticColors.listItemBackgroundCheckedHovered); style.setProperty('--tw-fui-listHeaderBackgroundHovered', this._themeVariant.semanticColors.listHeaderBackgroundHovered); style.setProperty('--tw-fui-listHeaderBackgroundPressed', this._themeVariant.semanticColors.listHeaderBackgroundPressed); style.setProperty('--tw-fui-actionLink', this._themeVariant.semanticColors.actionLink); style.setProperty('--tw-fui-actionLinkHovered', this._themeVariant.semanticColors.actionLinkHovered); style.setProperty('--tw-fui-link', this._themeVariant.semanticColors.link); style.setProperty('--tw-fui-linkHovered', this._themeVariant.semanticColors.linkHovered); style.setProperty('--tw-fui-listTextColor', this._themeVariant.semanticColors.listTextColor); style.setProperty('--tw-fui-menuItemBackgroundChecked', this._themeVariant.semanticColors.menuItemBackgroundChecked); } public render(): void { const element: React.ReactElement<IHelloTailwindCssProps> = React.createElement( HelloTailwindCss, { description: this.properties.description } ); ReactDom.render(element, this.domElement); } protected onDispose(): void { ReactDom.unmountComponentAtNode(this.domElement); } protected get dataVersion(): Version { return Version.parse('1.0'); } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { header: { description: strings.PropertyPaneDescription }, groups: [ { groupName: strings.BasicGroupName, groupFields: [ PropertyPaneTextField('description', { label: strings.DescriptionFieldLabel }) ] } ] } ] }; } }
the_stack
import assert from 'assert'; import Node, { SourceRange } from './base'; import { FunctionDef } from './function_def'; import { Invocation, DeviceSelector, InputParam, } from './invocation'; import { BooleanExpression } from './boolean_expression'; import { Expression, FunctionCallExpression, InvocationExpression, FilterExpression, ProjectionExpression, AliasExpression, SortExpression, IndexExpression, SliceExpression, AggregationExpression, MonitorExpression, ChainExpression } from './expression'; import { Value } from './values'; import { iterateSlots2InputParams, recursiveYieldArraySlots, makeScope, ArrayIndexSlot, FieldSlot, AbstractSlot, OldSlot, ScopeMap, InvocationLike, } from './slots'; import Type from '../type'; import NodeVisitor from './visitor'; import { TokenStream } from '../new-syntax/tokenstream'; import List from '../utils/list'; /** * The base class of all ThingTalk query expressions. * * @deprecated This class is part of ThingTalk 1.0. Use {@link Ast.Expression} in ThingTalk 2.0. */ export abstract class Table extends Node { static VarRef : typeof VarRefTable; isVarRef ! : boolean; static Invocation : typeof InvocationTable; isInvocation ! : boolean; static Filter : typeof FilteredTable; isFilter ! : boolean; static Projection : typeof ProjectionTable; isProjection ! : boolean; static Compute : typeof ComputeTable; isCompute ! : boolean; static Alias : typeof AliasTable; isAlias ! : boolean; static Aggregation : typeof AggregationTable; isAggregation ! : boolean; static Sort : typeof SortedTable; isSort ! : boolean; static Index : typeof IndexTable; isIndex ! : boolean; static Slice : typeof SlicedTable; isSlice ! : boolean; static Join : typeof JoinTable; isJoin ! : boolean; schema : FunctionDef|null; /** * Construct a new table node. * * @param location - the position of this node in the source code * @param schema - type signature of the invoked function */ constructor(location : SourceRange | null, schema : FunctionDef|null) { super(location); assert(schema === null || schema instanceof FunctionDef); this.schema = schema; } toSource() : TokenStream { throw new Error(`Legacy AST node cannot be converted to source, convert to Expression first`); } abstract toExpression(extra_in_params : InputParam[]) : Expression; abstract clone() : Table; /** * Iterate all slots (scalar value nodes) in this table. * * @param scope - available names for parameter passing * @deprecated Use {@link Table.iterateSlots2} instead. */ abstract iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]>; /** * Iterate all slots (scalar value nodes) in this table. * * @param scope - available names for parameter passing */ abstract iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]>; } Table.prototype.isVarRef = false; Table.prototype.isInvocation = false; Table.prototype.isFilter = false; Table.prototype.isProjection = false; Table.prototype.isCompute = false; Table.prototype.isAlias = false; Table.prototype.isAggregation = false; Table.prototype.isSort = false; Table.prototype.isIndex = false; Table.prototype.isSlice = false; Table.prototype.isJoin = false; export class VarRefTable extends Table { name : string; in_params : InputParam[]; constructor(location : SourceRange|null, name : string, in_params : InputParam[], schema : FunctionDef|null) { super(location, schema); assert(typeof name === 'string'); this.name = name; assert(Array.isArray(in_params)); this.in_params = in_params; } toExpression(extra_in_params : InputParam[]) { return new FunctionCallExpression(this.location, this.name, this.in_params.concat(extra_in_params), this.schema); } toSource() : TokenStream { return List.concat(this.name, '(', List.join(this.in_params.map((ip) => ip.toSource()), ','), ')'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitVarRefTable(this)) { for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } clone() : VarRefTable { return new VarRefTable( this.location, this.name, this.in_params.map((p) => p.clone()), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { for (const in_param of this.in_params) yield [this.schema, in_param, this, scope]; return [this, makeScope(this)]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* iterateSlots2InputParams(this, scope); } } Table.VarRef = VarRefTable; Table.VarRef.prototype.isVarRef = true; export class InvocationTable extends Table { invocation : Invocation; constructor(location : SourceRange|null, invocation : Invocation, schema : FunctionDef|null) { super(location, schema); assert(invocation instanceof Invocation); this.invocation = invocation; } toExpression(extra_in_params : InputParam[]) { const invocation = this.invocation.clone(); invocation.in_params.push(...extra_in_params); return new InvocationExpression(this.location, invocation, this.schema); } toSource() : TokenStream { return this.invocation.toSource(); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitInvocationTable(this)) this.invocation.visit(visitor); visitor.exit(this); } clone() : InvocationTable { return new InvocationTable( this.location, this.invocation.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.invocation.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.invocation.iterateSlots2(scope); } } Table.Invocation = InvocationTable; Table.Invocation.prototype.isInvocation = true; export class FilteredTable extends Table { table : Table; filter : BooleanExpression; constructor(location : SourceRange|null, table : Table, filter : BooleanExpression, schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(filter instanceof BooleanExpression); this.filter = filter; } toExpression(extra_in_params : InputParam[]) { return new FilterExpression(this.location, this.table.toExpression(extra_in_params), this.filter, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitFilteredTable(this)) { this.table.visit(visitor); this.filter.visit(visitor); } visitor.exit(this); } clone() : FilteredTable { return new FilteredTable( this.location, this.table.clone(), this.filter.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.table.iterateSlots(scope); yield* this.filter.iterateSlots(this.table.schema, prim, newScope); return [prim, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.table.iterateSlots2(scope); yield* this.filter.iterateSlots2(this.table.schema, prim, newScope); return [prim, newScope]; } } Table.Filter = FilteredTable; Table.Filter.prototype.isFilter = true; export class ProjectionTable extends Table { table : Table; args : string[]; constructor(location : SourceRange|null, table : Table, args : string[], schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(Array.isArray(args)); this.args = args; } toExpression(extra_in_params : InputParam[]) { return new ProjectionExpression(this.location, this.table.toExpression(extra_in_params), this.args, [], [], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitProjectionTable(this)) this.table.visit(visitor); visitor.exit(this); } clone() : ProjectionTable { return new ProjectionTable( this.location, this.table.clone(), this.args.map((a) => (a)), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [prim, nestedScope] = yield* this.table.iterateSlots(scope); const newScope : ScopeMap = {}; for (const name of this.args) newScope[name] = nestedScope[name]; return [prim, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, nestedScope] = yield* this.table.iterateSlots2(scope); const newScope : ScopeMap = {}; for (const name of this.args) newScope[name] = nestedScope[name]; return [prim, newScope]; } } Table.Projection = ProjectionTable; Table.Projection.prototype.isProjection = true; export class ComputeTable extends Table { table : Table; expression : Value; alias : string|null; type : Type|null; constructor(location : SourceRange|null, table : Table, expression : Value, alias : string|null, schema : FunctionDef|null, type : Type|null = null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(expression instanceof Value); this.expression = expression; assert(alias === null || typeof alias === 'string'); this.alias = alias; this.type = type; } toExpression(extra_in_params : InputParam[]) { return new ProjectionExpression(this.location, this.table.toExpression(extra_in_params), ['*'], [this.expression], [this.alias], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitComputeTable(this)) { this.table.visit(visitor); this.expression.visit(visitor); } visitor.exit(this); } clone() : ComputeTable { return new ComputeTable( this.location, this.table.clone(), this.expression.clone(), this.alias, this.schema ? this.schema.clone() : null, this.type ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, innerScope] = yield* this.table.iterateSlots2(scope); yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, this.type as Type, this, 'compute', 'expression')); return [prim, innerScope]; } } Table.Compute = ComputeTable; Table.Compute.prototype.isCompute = true; export class AliasTable extends Table { table : Table; name : string; constructor(location : SourceRange|null, table : Table, name : string, schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(typeof name === 'string'); this.name = name; } toExpression(extra_in_params : InputParam[]) { return new AliasExpression(this.location, this.table.toExpression(extra_in_params), this.name, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitAliasTable(this)) this.table.visit(visitor); visitor.exit(this); } clone() : AliasTable { return new AliasTable( this.location, this.table.clone(), this.name, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots2(scope); } } Table.Alias = AliasTable; Table.Alias.prototype.isAlias = true; export class AggregationTable extends Table { table : Table; field : string; operator : string; alias : string|null; overload : Type[]|null; constructor(location : SourceRange|null, table : Table, field : string, operator : string, alias : string|null, schema : FunctionDef|null, overload : Type[]|null = null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(typeof field === 'string'); this.field = field; assert(typeof operator === 'string'); this.operator = operator; assert(alias === null || typeof alias === 'string'); this.alias = alias; this.overload = overload; } toExpression(extra_in_params : InputParam[]) { return new AggregationExpression(this.location, this.table.toExpression(extra_in_params), this.field, this.operator, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitAggregationTable(this)) this.table.visit(visitor); visitor.exit(this); } clone() : AggregationTable { return new AggregationTable( this.location, this.table.clone(), this.field, this.operator, this.alias, this.schema ? this.schema.clone() : null, this.overload ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots2(scope); } } Table.Aggregation = AggregationTable; Table.Aggregation.prototype.isAggregation = true; export class SortedTable extends Table { table : Table; field : string; direction : 'asc'|'desc'; constructor(location : SourceRange|null, table : Table, field : string, direction : 'asc'|'desc', schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(typeof field === 'string'); this.field = field; assert(direction === 'asc' || direction === 'desc'); this.direction = direction; } toExpression(extra_in_params : InputParam[]) { return new SortExpression(this.location, this.table.toExpression(extra_in_params), new Value.VarRef(this.field), this.direction, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitSortedTable(this)) this.table.visit(visitor); visitor.exit(this); } clone() : SortedTable { return new SortedTable( this.location, this.table.clone(), this.field, this.direction, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots2(scope); } } Table.Sort = SortedTable; Table.Sort.prototype.isSort = true; export class IndexTable extends Table { table : Table; indices : Value[]; constructor(location : SourceRange|null, table : Table, indices : Value[], schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(Array.isArray(indices)); this.indices = indices; } toExpression(extra_in_params : InputParam[]) { return new IndexExpression(this.location, this.table.toExpression(extra_in_params), this.indices, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitIndexTable(this)) { this.table.visit(visitor); for (const index of this.indices) index.visit(visitor); } visitor.exit(this); } clone() : IndexTable { return new IndexTable( this.location, this.table.clone(), this.indices.map((i) => i.clone()), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, innerScope] = yield* this.table.iterateSlots2(scope); for (let i = 0; i < this.indices.length; i++) yield* recursiveYieldArraySlots(new ArrayIndexSlot(prim, innerScope, Type.Number, this.indices, 'table.index', i)); return [prim, innerScope]; } } Table.Index = IndexTable; Table.Index.prototype.isIndex = true; export class SlicedTable extends Table { table : Table; base : Value; limit : Value; constructor(location : SourceRange|null, table : Table, base : Value, limit : Value, schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(base instanceof Value); this.base = base; assert(limit instanceof Value); this.limit = limit; } toExpression(extra_in_params : InputParam[]) { return new SliceExpression(this.location, this.table.toExpression(extra_in_params), this.base, this.limit, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitSlicedTable(this)) { this.table.visit(visitor); this.base.visit(visitor); this.limit.visit(visitor); } visitor.exit(this); } clone() : SlicedTable { return new SlicedTable( this.location, this.table.clone(), this.base.clone(), this.limit.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, innerScope] = yield* this.table.iterateSlots2(scope); yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, Type.Number, this, 'slice', 'base')); yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, Type.Number, this, 'slice', 'limit')); return [prim, innerScope]; } } Table.Slice = SlicedTable; Table.Slice.prototype.isSlice = true; export class JoinTable extends Table { lhs : Table; rhs : Table; in_params : InputParam[]; constructor(location : SourceRange|null, lhs : Table, rhs : Table, in_params : InputParam[], schema : FunctionDef|null) { super(location, schema); assert(lhs instanceof Table); this.lhs = lhs; assert(rhs instanceof Table); this.rhs = rhs; assert(Array.isArray(in_params)); this.in_params = in_params; } toExpression(extra_in_params : InputParam[]) { // we need typechecking to implement this correctly, but typechecking // happens after the conversion so it is too late if (extra_in_params.length > 0) throw new Error(`Cannot carry extra_in_params across a join`); return new ChainExpression(this.location, [this.lhs.toExpression([]), this.rhs.toExpression(this.in_params)], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitJoinTable(this)) { this.lhs.visit(visitor); this.rhs.visit(visitor); for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } clone() : JoinTable { return new JoinTable( this.location, this.lhs.clone(), this.rhs.clone(), this.in_params.map((p) => p.clone()), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [, leftScope] = yield* this.lhs.iterateSlots(scope); const [, rightScope] = yield* this.rhs.iterateSlots(scope); const newScope : ScopeMap = {}; Object.assign(newScope, leftScope, rightScope); return [null, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [, leftScope] = yield* this.lhs.iterateSlots2(scope); const [, rightScope] = yield* this.rhs.iterateSlots2(scope); const newScope : ScopeMap = {}; Object.assign(newScope, leftScope, rightScope); return [null, newScope]; } } Table.Join = JoinTable; Table.Join.prototype.isJoin = true; /** * The base class of all ThingTalk stream expressions. * * @deprecated This class is part of ThingTalk 1.0. Use {@link Ast.Expression} in ThingTalk 2.0. */ export abstract class Stream extends Node { static VarRef : typeof VarRefStream; isVarRef ! : boolean; static Timer : typeof TimerStream; isTimer ! : boolean; static AtTimer : typeof AtTimerStream; isAtTimer ! : boolean; static Monitor : typeof MonitorStream; isMonitor ! : boolean; static EdgeNew : typeof EdgeNewStream; isEdgeNew ! : boolean; static EdgeFilter : typeof EdgeFilterStream; isEdgeFilter ! : boolean; static Filter : typeof FilteredStream; isFilter ! : boolean; static Projection : typeof ProjectionStream; isProjection ! : boolean; static Compute : typeof ComputeStream; isCompute ! : boolean; static Alias : typeof AliasStream; isAlias ! : boolean; static Join : typeof JoinStream; isJoin ! : boolean; schema : FunctionDef|null; /** * Construct a new stream node. * * @param location - the position of this node in the source code * @param schema - type signature of the stream expression */ constructor(location : SourceRange|null, schema : FunctionDef|null) { super(location); assert(schema === null || schema instanceof FunctionDef); this.schema = schema; } toSource() : TokenStream { throw new Error(`Legacy AST node cannot be converted to source, convert to Expression first`); } abstract toExpression() : Expression; abstract clone() : Stream; /** * Iterate all slots (scalar value nodes) in this stream. * * @param scope - available names for parameter passing * @deprecated Use {@link Ast.Stream.iterateSlots2} instead. */ abstract iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]>; /** * Iterate all slots (scalar value nodes) in this stream. * * @param scope - available names for parameter passing */ abstract iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]>; } Stream.prototype.isVarRef = false; Stream.prototype.isTimer = false; Stream.prototype.isAtTimer = false; Stream.prototype.isMonitor = false; Stream.prototype.isEdgeNew = false; Stream.prototype.isEdgeFilter = false; Stream.prototype.isFilter = false; Stream.prototype.isProjection = false; Stream.prototype.isCompute = false; Stream.prototype.isAlias = false; Stream.prototype.isJoin = false; export class VarRefStream extends Stream { name : string; in_params : InputParam[]; constructor(location : SourceRange|null, name : string, in_params : InputParam[], schema : FunctionDef|null) { super(location, schema); assert(typeof name === 'string'); this.name = name; assert(Array.isArray(in_params)); this.in_params = in_params; } toExpression() { return new FunctionCallExpression(this.location, this.name, this.in_params, this.schema); } toSource() : TokenStream { return List.concat(this.name, '(', List.join(this.in_params.map((ip) => ip.toSource()), ','), ')'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitVarRefStream(this)) { for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } clone() : VarRefStream { return new VarRefStream( this.location, this.name, this.in_params.map((p) => p.clone()), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { for (const in_param of this.in_params) yield [this.schema, in_param, this, scope]; return [this, makeScope(this)]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* iterateSlots2InputParams(this, scope); } } Stream.VarRef = VarRefStream; Stream.VarRef.prototype.isVarRef = true; export class TimerStream extends Stream { base : Value; interval : Value; frequency : Value|null; constructor(location : SourceRange|null, base : Value, interval : Value, frequency : Value|null, schema : FunctionDef|null) { super(location, schema); assert(base instanceof Value); this.base = base; assert(interval instanceof Value); this.interval = interval; assert(frequency === null || frequency instanceof Value); this.frequency = frequency; } toExpression() { const args = [new InputParam(null, 'base', this.base), new InputParam(null, 'interval', this.interval)]; if (this.frequency) args.push(new InputParam(null, 'frequency', this.frequency)); return new FunctionCallExpression(this.location, 'timer', args, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitTimerStream(this)) { this.base.visit(visitor); this.interval.visit(visitor); if (this.frequency !== null) this.frequency.visit(visitor); } visitor.exit(this); } clone() : TimerStream { return new TimerStream( this.location, this.base.clone(), this.interval.clone(), this.frequency ? this.frequency.clone() : null, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { // no primitive here return [null, {}]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { // no primitive here yield* recursiveYieldArraySlots(new FieldSlot(null, scope, Type.Date, this, 'timer', 'base')); yield* recursiveYieldArraySlots(new FieldSlot(null, scope, new Type.Measure('ms'), this, 'timer', 'interval')); return [null, {}]; } } Stream.Timer = TimerStream; Stream.Timer.prototype.isTimer = true; export class AtTimerStream extends Stream { time : Value[]; expiration_date : Value|null; constructor(location : SourceRange|null, time : Value[], expiration_date : Value|null, schema : FunctionDef|null) { super(location, schema); assert(Array.isArray(time)); this.time = time; assert(expiration_date === null || expiration_date instanceof Value); this.expiration_date = expiration_date; } toExpression() { const in_params = [new InputParam(null, 'time', new Value.Array(this.time))]; if (this.expiration_date) in_params.push(new InputParam(null, 'expiration_date', this.expiration_date)); return new FunctionCallExpression(this.location, 'attimer', in_params, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitAtTimerStream(this)) { for (const time of this.time) time.visit(visitor); if (this.expiration_date !== null) this.expiration_date.visit(visitor); } visitor.exit(this); } clone() : AtTimerStream { return new AtTimerStream( this.location, this.time.map((t) => t.clone()), this.expiration_date ? this.expiration_date.clone() : null, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { // no primitive here return [null, {}]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { for (let i = 0; i < this.time.length; i++) yield* recursiveYieldArraySlots(new ArrayIndexSlot(null, scope, Type.Time, this.time, 'attimer.time', i)); if (this.expiration_date !== null) yield* recursiveYieldArraySlots(new FieldSlot(null, scope, Type.Date, this, 'attimer', 'expiration_date')); return [null, {}]; } } Stream.AtTimer = AtTimerStream; Stream.AtTimer.prototype.isAtTimer = true; export class MonitorStream extends Stream { table : Table; args : string[]|null; constructor(location : SourceRange|null, table : Table, args : string[]|null, schema : FunctionDef|null) { super(location, schema); assert(table instanceof Table); this.table = table; assert(args === null || Array.isArray(args)); this.args = args; } toExpression() { return new MonitorExpression(this.location, this.table.toExpression([]), this.args, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitMonitorStream(this)) this.table.visit(visitor); visitor.exit(this); } clone() : MonitorStream { return new MonitorStream( this.location, this.table.clone(), this.args ? this.args.map((a) => a) : null, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.table.iterateSlots2(scope); } } Stream.Monitor = MonitorStream; Stream.Monitor.prototype.isMonitor = true; export class EdgeNewStream extends Stream { stream : Stream; constructor(location : SourceRange|null, stream : Stream, schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; } toExpression() : never { throw new Error('`edge on new` is not supported in the new syntax'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitEdgeNewStream(this)) this.stream.visit(visitor); visitor.exit(this); } clone() : EdgeNewStream { return new EdgeNewStream( this.location, this.stream.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.stream.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.stream.iterateSlots2(scope); } } Stream.EdgeNew = EdgeNewStream; Stream.EdgeNew.prototype.isEdgeNew = true; export class EdgeFilterStream extends Stream { stream : Stream; filter : BooleanExpression; constructor(location : SourceRange|null, stream : Stream, filter : BooleanExpression, schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(filter instanceof BooleanExpression); this.filter = filter; } toExpression() { return new FilterExpression(this.location, this.stream.toExpression(), this.filter, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitEdgeFilterStream(this)) { this.stream.visit(visitor); this.filter.visit(visitor); } visitor.exit(this); } clone() : EdgeFilterStream { return new EdgeFilterStream( this.location, this.stream.clone(), this.filter.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.stream.iterateSlots(scope); yield* this.filter.iterateSlots(this.stream.schema, prim, newScope); return [prim, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.stream.iterateSlots2(scope); yield* this.filter.iterateSlots2(this.stream.schema, prim, newScope); return [prim, newScope]; } } Stream.EdgeFilter = EdgeFilterStream; Stream.EdgeFilter.prototype.isEdgeFilter = true; export class FilteredStream extends Stream { stream : Stream; filter : BooleanExpression; constructor(location : SourceRange|null, stream : Stream, filter : BooleanExpression, schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(filter instanceof BooleanExpression); this.filter = filter; } toExpression() : Expression { // catch a common case that we can handle before bailing if (this.stream instanceof MonitorStream) { return new MonitorExpression(this.location, new FilterExpression(this.location, this.stream.table.toExpression([]), this.filter, this.schema), this.stream.args, this.stream.schema); } throw new Error('stream filter is not supported in the new syntax (push the filter down inside the monitor)'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitFilteredStream(this)) { this.stream.visit(visitor); this.filter.visit(visitor); } visitor.exit(this); } clone() : FilteredStream { return new FilteredStream( this.location, this.stream.clone(), this.filter.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.stream.iterateSlots(scope); yield* this.filter.iterateSlots(this.stream.schema, prim, newScope); return [prim, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, newScope] = yield* this.stream.iterateSlots2(scope); yield* this.filter.iterateSlots2(this.stream.schema, prim, newScope); return [prim, newScope]; } } Stream.Filter = FilteredStream; Stream.Filter.prototype.isFilter = true; export class ProjectionStream extends Stream { stream : Stream; args : string[]; constructor(location : SourceRange|null, stream : Stream, args : string[], schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(Array.isArray(args)); this.args = args; } toExpression() { return new ProjectionExpression(this.location, this.stream.toExpression(), this.args, [], [], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitProjectionStream(this)) this.stream.visit(visitor); visitor.exit(this); } clone() : ProjectionStream { return new ProjectionStream( this.location, this.stream.clone(), this.args.map((a) => a), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [prim, nestedScope] = yield* this.stream.iterateSlots(scope); const newScope : ScopeMap = {}; for (const name of this.args) newScope[name] = nestedScope[name]; return [prim, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, nestedScope] = yield* this.stream.iterateSlots2(scope); const newScope : ScopeMap = {}; for (const name of this.args) newScope[name] = nestedScope[name]; return [prim, newScope]; } } Stream.Projection = ProjectionStream; Stream.Projection.prototype.isProjection = true; export class ComputeStream extends Stream { stream : Stream; expression : Value; alias : string|null; type : Type|null; constructor(location : SourceRange|null, stream : Stream, expression : Value, alias : string|null, schema : FunctionDef|null, type : Type|null = null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(expression instanceof Value); this.expression = expression; assert(alias === null || typeof alias === 'string'); this.alias = alias; this.type = type; } toExpression() { return new ProjectionExpression(this.location, this.stream.toExpression(), [], [this.expression], [this.alias], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitComputeStream(this)) { this.stream.visit(visitor); this.expression.visit(visitor); } visitor.exit(this); } clone() : ComputeStream { return new ComputeStream( this.location, this.stream.clone(), this.expression.clone(), this.alias, this.schema ? this.schema.clone() : null, this.type ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.stream.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [prim, innerScope] = yield* this.stream.iterateSlots2(scope); yield* recursiveYieldArraySlots(new FieldSlot(prim, innerScope, this.type as Type, this, 'compute', 'expression')); return [prim, innerScope]; } } Stream.Compute = ComputeStream; Stream.Compute.prototype.isCompute = true; export class AliasStream extends Stream { stream : Stream; name : string; constructor(location : SourceRange|null, stream : Stream, name : string, schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(typeof name === 'string'); this.name = name; } toExpression() { return new AliasExpression(this.location, this.stream.toExpression(), this.name, this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitAliasStream(this)) this.stream.visit(visitor); visitor.exit(this); } clone() : AliasStream { return new AliasStream( this.location, this.stream.clone(), this.name, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { return yield* this.stream.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { return yield* this.stream.iterateSlots2(scope); } } Stream.Alias = AliasStream; Stream.Alias.prototype.isAlias = true; export class JoinStream extends Stream { stream : Stream; table : Table in_params : InputParam[]; constructor(location : SourceRange|null, stream : Stream, table : Table, in_params : InputParam[], schema : FunctionDef|null) { super(location, schema); assert(stream instanceof Stream); this.stream = stream; assert(table instanceof Table); this.table = table; assert(Array.isArray(in_params)); this.in_params = in_params; } toExpression() { const lhs = this.stream.toExpression(); // flatten chain expressions, or typechecking will fail if (lhs instanceof ChainExpression) return new ChainExpression(this.location, [...lhs.expressions, this.table.toExpression(this.in_params)], this.schema); else return new ChainExpression(this.location, [lhs, this.table.toExpression(this.in_params)], this.schema); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitJoinStream(this)) { this.stream.visit(visitor); this.table.visit(visitor); for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } clone() : JoinStream { return new JoinStream( this.location, this.stream.clone(), this.table.clone(), this.in_params.map((p) => p.clone()), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, [InvocationLike|null, ScopeMap]> { const [, leftScope] = yield* this.stream.iterateSlots(scope); const [, rightScope] = yield* this.table.iterateSlots(scope); const newScope = {}; Object.assign(newScope, leftScope, rightScope); return [null, newScope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, [InvocationLike|null, ScopeMap]> { const [, leftScope] = yield* this.stream.iterateSlots2(scope); const [, rightScope] = yield* this.table.iterateSlots2(scope); const newScope = {}; Object.assign(newScope, leftScope, rightScope); return [null, newScope]; } } Stream.Join = JoinStream; Stream.Join.prototype.isJoin = true; /** * Base class for all expressions that invoke an action. * * @deprecated This class is part of ThingTalk 1.0. Use {@link Ast.Expression} in ThingTalk 2.0. */ export abstract class Action extends Node { static VarRef : typeof VarRefAction; isVarRef ! : boolean; static Invocation : typeof InvocationAction; isInvocation ! : boolean; static Notify : typeof NotifyAction; isNotify ! : boolean; /** * Type signature of this action. * This property is guaranteed not `null` after type-checking. */ schema : FunctionDef|null; /** * Construct a new action expression node. * * @param location - the position of this node in the source code * @param schema - type signature of this action */ constructor(location : SourceRange|null, schema : FunctionDef|null) { super(location); assert(schema === null || schema instanceof FunctionDef); this.schema = schema; } /** * Utility function to create a `notify` or `return` action. * * @param {string} [what=notify] - what action to create * @return {Ast.Action} the action node */ static notifyAction(what : 'notify' = 'notify') : NotifyAction { return new NotifyAction(null, what, null); } abstract toExpression() : Expression; abstract clone() : Action; /** * Iterate all slots (scalar value nodes) in this action. * * @param scope - available names for parameter passing * @deprecated Use {@link Ast.Action.iterateSlots2} instead. */ abstract iterateSlots(scope : ScopeMap) : Generator<OldSlot, void>; /** * Iterate all slots (scalar value nodes) in this action. * * @param scope - available names for parameter passing */ abstract iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void>; } Action.prototype.isVarRef = false; Action.prototype.isInvocation = false; Action.prototype.isNotify = false; /** * An invocation of a locally defined action (i.e. one defined with * a `let` statement). * */ export class VarRefAction extends Action { /** * The name of the action to invoke. */ name : string; /** * The input parameters to pass. */ in_params : InputParam[]; /** * Construct a new var ref action. * * @param location - the position of this node in the source code * @param name - the name of the action to invoke * @param in_params - the input parameters to pass * @param schema - type signature of this action */ constructor(location : SourceRange|null, name : string, in_params : InputParam[], schema : FunctionDef|null) { super(location, schema); assert(typeof name === 'string'); this.name = name; assert(Array.isArray(in_params)); this.in_params = in_params; } toExpression() { return new FunctionCallExpression(this.location, this.name, this.in_params, this.schema); } toSource() : TokenStream { return List.concat(this.name, '(', List.join(this.in_params.map((ip) => ip.toSource()), ','), ')'); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitVarRefAction(this)) { for (const in_param of this.in_params) in_param.visit(visitor); } visitor.exit(this); } clone() : VarRefAction { return new VarRefAction( this.location, this.name, this.in_params.map((p) => p.clone()), this.schema ? this.schema.clone() : null ); } toString() : string { return `VarRef(${this.name}, ${this.in_params.toString()}, )`; } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, void> { for (const in_param of this.in_params) yield [this.schema, in_param, this, scope]; } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> { yield* iterateSlots2InputParams(this, scope); } } Action.VarRef = VarRefAction; Action.VarRef.prototype.isVarRef = true; /** * An invocation of an action in Thingpedia. * */ export class InvocationAction extends Action { /** * The actual invocation expression. */ invocation : Invocation; /** * Construct a new invocation action. * * @param location - the position of this node in the source code * @param invocation - the function invocation * @param schema - type signature of this action */ constructor(location : SourceRange|null, invocation : Invocation, schema : FunctionDef|null) { super(location, schema); assert(invocation instanceof Invocation); this.invocation = invocation; } toExpression() { return new InvocationExpression(this.location, this.invocation, this.schema); } toSource() : TokenStream { return this.invocation.toSource(); } visit(visitor : NodeVisitor) : void { visitor.enter(this); if (visitor.visitInvocationAction(this)) this.invocation.visit(visitor); visitor.exit(this); } clone() : InvocationAction { return new InvocationAction( this.location, this.invocation.clone(), this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, void> { yield* this.invocation.iterateSlots(scope); } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> { yield* this.invocation.iterateSlots2(scope); } } Action.Invocation = InvocationAction; Action.Invocation.prototype.isInvocation = true; /** * A `notify`, `return` or `save` clause. * */ export class NotifyAction extends Action { name : 'notify'; /** * Construct a new notify action. * * @param location - the position of this node in the source code * @param name - the clause name * @param schema - type signature of this action */ constructor(location : SourceRange|null, name : 'notify', schema : FunctionDef|null = null) { super(location, schema); // we used to support "return" and "save", but those are gone // in new syntax so let's make sure we don't create ASTs for them // (or we'll lose information when we convert) assert(name === 'notify'); this.name = name; } toExpression() : never { throw new Error(`notify actions no longer exist`); } toSource() : TokenStream { return List.singleton(this.name); } visit(visitor : NodeVisitor) : void { visitor.enter(this); visitor.visitNotifyAction(this); visitor.exit(this); } clone() : NotifyAction { return new NotifyAction( this.location, this.name, this.schema ? this.schema.clone() : null ); } *iterateSlots(scope : ScopeMap) : Generator<OldSlot, void> { } *iterateSlots2(scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> { } } Action.Notify = NotifyAction; Action.Notify.prototype.isNotify = true;
the_stack
import { Accessibility, toolbarBehavior, ToolbarBehaviorProps, toggleButtonBehavior, IS_FOCUSABLE_ATTRIBUTE, } from '@fluentui/accessibility'; import { ComponentWithAs, compose, getElementType, getFirstFocusable, useFluentContext, useAccessibility, useStyles, useTelemetry, useUnhandledProps, } from '@fluentui/react-bindings'; import { EventListener } from '@fluentui/react-component-event-listener'; import { handleRef, Ref } from '@fluentui/react-component-ref'; import { MoreIcon } from '@fluentui/react-icons-northstar'; import * as customPropTypes from '@fluentui/react-proptypes'; import * as _ from 'lodash'; import * as PropTypes from 'prop-types'; import * as React from 'react'; import { ComponentEventHandler, ShorthandCollection, ShorthandValue, ObjectShorthandValue } from '../../types'; import { childrenExist, createShorthand, UIComponentProps, ContentComponentProps, ChildrenComponentProps, commonPropTypes, ColorComponentProps, } from '../../utils'; import { ToolbarCustomItem, ToolbarCustomItemProps } from './ToolbarCustomItem'; import { ToolbarDivider, ToolbarDividerProps } from './ToolbarDivider'; import { ToolbarItem, ToolbarItemProps } from './ToolbarItem'; import { ToolbarItemWrapper } from './ToolbarItemWrapper'; import { ToolbarItemIcon } from './ToolbarItemIcon'; import { ToolbarMenu, ToolbarMenuProps } from './ToolbarMenu'; import { ToolbarMenuDivider } from './ToolbarMenuDivider'; import { ToolbarMenuItem } from './ToolbarMenuItem'; import { ToolbarMenuRadioGroup, ToolbarMenuRadioGroupProps } from './ToolbarMenuRadioGroup'; import { ToolbarMenuRadioGroupWrapper } from './ToolbarMenuRadioGroupWrapper'; import { ToolbarRadioGroup } from './ToolbarRadioGroup'; import { ToolbarVariablesProvider } from './toolbarVariablesContext'; import { ToolbarMenuItemSubmenuIndicator } from './ToolbarMenuItemSubmenuIndicator'; import { ToolbarMenuItemIcon } from './ToolbarMenuItemIcon'; import { ToolbarMenuItemActiveIndicator } from './ToolbarMenuItemActiveIndicator'; import { ToolbarMenuContextProvider } from './toolbarMenuContext'; import { PopperShorthandProps } from '../../utils/positioner'; import { BoxProps, Box } from '../Box/Box'; export type ToolbarItemShorthandKinds = { item: ToolbarItemProps; divider: ToolbarDividerProps; group: ToolbarMenuRadioGroupProps; toggle: ToolbarItemProps; custom: ToolbarCustomItemProps; }; type PositionOffset = { vertical: number; horizontal: number; }; const WAS_FOCUSABLE_ATTRIBUTE = 'data-was-focusable'; type ToolbarOverflowItemProps = Omit<ToolbarItemProps, 'menu'> & { menu?: ObjectShorthandValue<ToolbarMenuProps & { popper?: PopperShorthandProps }>; }; export interface ToolbarProps extends UIComponentProps, ContentComponentProps, ChildrenComponentProps, ColorComponentProps { /** Accessibility behavior if overridden by the user. */ accessibility?: Accessibility<ToolbarBehaviorProps>; /** Shorthand array of props for Toolbar. */ items?: ShorthandCollection<ToolbarItemProps, ToolbarItemShorthandKinds>; /** * Automatically move overflow items to overflow menu. * For automatic overflow to work correctly, toolbar items including overflowMenuItem * must NOT change their size! If you need to change item's size, rerender the Toolbar. */ overflow?: boolean; /** Indicates if the overflow menu is open. Only valid if `overflow` is enabled and regular items do not fit. */ overflowOpen?: boolean; /** * Shorthand for the overflow item which is displayed when `overflow` is enabled and regular toolbar items do not fit. * Do not set any menu on this item, Toolbar overrides it. */ overflowItem?: ShorthandValue<ToolbarOverflowItemProps>; /** * Renders a sentinel node when the overflow menu is open to stop the width of the toolbar changing * Only needed if the container hosting the toolbar does not have a fixed/min width * * @default null */ overflowSentinel?: ShorthandValue<BoxProps>; /** * Called when overflow is recomputed (after render, update or window resize). Even if all items fit. * @param itemsVisible - number of items visible */ onOverflow?: (itemsVisible: number) => void; /** * Event for request to change 'overflowOpen' value. * @param event - React's original SyntheticEvent. * @param data - All props and proposed value. */ onOverflowOpenChange?: ComponentEventHandler<ToolbarProps>; /** * Callback to get items to be rendered in overflow menu. * Called when overflow menu is rendered opened. * @param startIndex - Index of the first item to be displayed in the overflow menu (the first item which does not fit the toolbar). */ getOverflowItems?: (startIndex: number) => ToolbarItemProps['menu']; } export type ToolbarStylesProps = Pick<ToolbarProps, 'overflowOpen'>; export const toolbarClassName = 'ui-toolbar'; /** * A Toolbar is a container for grouping a set of controls, often action controls (e.g. buttons) or input controls (e.g. checkboxes). * * @accessibility * * Implements [ARIA Toolbar](https://www.w3.org/TR/wai-aria-practices-1.1/#toolbar) design pattern. * @accessibilityIssues * [Issue 988424: VoiceOver narrates selected for button in toolbar](https://bugs.chromium.org/p/chromium/issues/detail?id=988424) * [In toolbars that can toggle items in a menu, VoiceOver narrates "1" for menuitemcheckbox/radio when checked.](https://github.com/microsoft/fluentui/issues/14064) * [NVDA could narrate "checked" stated for radiogroup in toolbar #12678](https://github.com/nvaccess/nvda/issues/12678) * [JAWS narrates wrong instruction message for radiogroup in toolbar #556](https://github.com/FreedomScientific/VFO-standards-support/issues/556) * [JAWS could narrate "checked" stated for radiogroup in toolbar #557](https://github.com/FreedomScientific/VFO-standards-support/issues/557) */ export const Toolbar = compose<'div', ToolbarProps, ToolbarStylesProps, {}, {}>( (props, ref, composeOptions) => { const context = useFluentContext(); const { setStart, setEnd } = useTelemetry(composeOptions.displayName, context.telemetry); setStart(); const { accessibility, className, children, design, getOverflowItems, items, overflow, overflowItem, overflowOpen, overflowSentinel, styles, variables, } = props; const overflowContainerRef = React.useRef<HTMLDivElement>(); const overflowItemWrapperRef = React.useRef<HTMLElement>(); const overflowSentinelRef = React.useRef<HTMLDivElement>(); const offsetMeasureRef = React.useRef<HTMLDivElement>(); const containerRef = React.useRef<HTMLElement>(); // index of the last visible item in Toolbar, the rest goes to overflow menu const lastVisibleItemIndex = React.useRef<number>(); const animationFrameId = React.useRef<number>(); const getA11Props = useAccessibility(accessibility, { debugName: composeOptions.displayName, rtl: context.rtl, }); const { classes } = useStyles<ToolbarStylesProps>(composeOptions.displayName, { className: toolbarClassName, composeOptions, mapPropsToStyles: () => ({ overflowOpen, }), mapPropsToInlineStyles: () => ({ className, design, styles, variables, }), rtl: context.rtl, unstable_props: props, }); const ElementType = getElementType(props); const slotProps = composeOptions.resolveSlotProps<ToolbarProps>(props); const unhandledProps = useUnhandledProps(composeOptions.handledProps, props); const hide = (el: HTMLElement) => { if (el.style.visibility === 'hidden') { return; } if (context.target.activeElement === el || el.contains(context.target.activeElement)) { if (containerRef.current) { const firstFocusableItem = getFirstFocusable( containerRef.current, containerRef.current.firstElementChild as HTMLElement, ); if (firstFocusableItem) { firstFocusableItem.focus(); } } } el.style.visibility = 'hidden'; const wasFocusable = el.getAttribute(IS_FOCUSABLE_ATTRIBUTE); if (wasFocusable) { el.setAttribute(WAS_FOCUSABLE_ATTRIBUTE, wasFocusable); } el.setAttribute(IS_FOCUSABLE_ATTRIBUTE, 'false'); }; const show = (el: HTMLElement) => { if (el.style.visibility !== 'hidden') { return false; } el.style.visibility = ''; const wasFocusable = el.getAttribute(WAS_FOCUSABLE_ATTRIBUTE); if (wasFocusable) { el.setAttribute(IS_FOCUSABLE_ATTRIBUTE, wasFocusable); el.removeAttribute(WAS_FOCUSABLE_ATTRIBUTE); } else { el.removeAttribute(IS_FOCUSABLE_ATTRIBUTE); } return true; }; /** * Checks if `item` overflows a `container`. * TODO: check and fix all margin combination */ const isItemOverflowing = (itemBoundingRect: ClientRect, containerBoundingRect: ClientRect) => { return itemBoundingRect.right > containerBoundingRect.right || itemBoundingRect.left < containerBoundingRect.left; }; /** * Checks if `item` would collide with eventual position of `overflowItem`. */ const wouldItemCollide = ( $item: Element, itemBoundingRect: ClientRect, overflowItemBoundingRect: ClientRect, containerBoundingRect: ClientRect, ) => { const actualWindow: Window = context.target.defaultView; let wouldCollide; if (context.rtl) { const itemLeftMargin = parseFloat(actualWindow.getComputedStyle($item).marginLeft) || 0; wouldCollide = itemBoundingRect.left - overflowItemBoundingRect.width - itemLeftMargin < containerBoundingRect.left; // console.log('Collision [RTL]', { // wouldCollide, // 'itemBoundingRect.left': itemBoundingRect.left, // 'overflowItemBoundingRect.width': overflowItemBoundingRect.width, // itemRightMargin: itemLeftMargin, // sum: itemBoundingRect.left - overflowItemBoundingRect.width - itemLeftMargin, // 'overflowContainerBoundingRect.left': containerBoundingRect.left, // }) } else { const itemRightMargin = parseFloat(actualWindow.getComputedStyle($item).marginRight) || 0; wouldCollide = itemBoundingRect.right + overflowItemBoundingRect.width + itemRightMargin > containerBoundingRect.right; // console.log('Collision', { // wouldCollide, // 'itemBoundingRect.right': itemBoundingRect.right, // 'overflowItemBoundingRect.width': overflowItemBoundingRect.width, // itemRightMargin, // sum: itemBoundingRect.right + overflowItemBoundingRect.width + itemRightMargin, // 'overflowContainerBoundingRect.right': containerBoundingRect.right, // }) } return wouldCollide; }; /** * Positions overflowItem next to lastVisible item * TODO: consider overflowItem margin */ const setOverflowPosition = ( $overflowItem: HTMLElement, $lastVisibleItem: HTMLElement | undefined, lastVisibleItemRect: ClientRect | undefined, containerBoundingRect: ClientRect, absolutePositioningOffset: PositionOffset, ) => { const actualWindow: Window = context.target.defaultView; if ($lastVisibleItem) { if (context.rtl) { const lastVisibleItemMarginLeft = parseFloat(actualWindow.getComputedStyle($lastVisibleItem).marginLeft) || 0; $overflowItem.style.right = `${ containerBoundingRect.right - lastVisibleItemRect.left + lastVisibleItemMarginLeft + absolutePositioningOffset.horizontal }px`; } else { const lastVisibleItemRightMargin = parseFloat(actualWindow.getComputedStyle($lastVisibleItem).marginRight) || 0; $overflowItem.style.left = `${ lastVisibleItemRect.right - containerBoundingRect.left + lastVisibleItemRightMargin + absolutePositioningOffset.horizontal }px`; } } else { // there is no last visible item -> position the overflow as the first item lastVisibleItemIndex.current = -1; if (context.rtl) { $overflowItem.style.right = `${absolutePositioningOffset.horizontal}px`; } else { $overflowItem.style.left = `${absolutePositioningOffset.horizontal}px`; } } }; const hideOverflowItems = () => { const $overflowContainer = overflowContainerRef.current; const $overflowItem = overflowItemWrapperRef.current; const $overflowSentinel = overflowSentinelRef.current; const $offsetMeasure = offsetMeasureRef.current; if (!$overflowContainer || !$overflowItem || !$offsetMeasure) { return; } // workaround: when resizing window with popup opened the container contents scroll for some reason if (context.rtl) { $overflowContainer.scrollTo(Number.MAX_SAFE_INTEGER, 0); } else { $overflowContainer.scrollTop = 0; $overflowContainer.scrollLeft = 0; } const $items = $overflowContainer.children; const overflowContainerBoundingRect = $overflowContainer.getBoundingClientRect(); const overflowItemBoundingRect = $overflowItem.getBoundingClientRect(); const offsetMeasureBoundingRect = $offsetMeasure.getBoundingClientRect(); // Absolute positioning offset // Overflow menu is absolutely positioned relative to root slot // If there is padding set on the root slot boundingClientRect computations use inner content box, // but absolute position is relative to root slot's PADDING box. // We compute absolute positioning offset // By measuring position of an offsetMeasure element absolutely positioned to 0,0. // TODO: replace by getComputedStyle('padding') const absolutePositioningOffset: PositionOffset = { horizontal: context.rtl ? offsetMeasureBoundingRect.right - overflowContainerBoundingRect.right : overflowContainerBoundingRect.left - offsetMeasureBoundingRect.left, vertical: overflowContainerBoundingRect.top - offsetMeasureBoundingRect.top, }; let isOverflowing = false; let $lastVisibleItem; let lastVisibleItemRect; // check all items from the last one back _.forEachRight($items, ($item: HTMLElement, i: number) => { if ($item === $overflowItem || $item === $overflowSentinel) { return true; } const itemBoundingRect = $item.getBoundingClientRect(); // if the item is out of the crop rectangle, hide it if (isItemOverflowing(itemBoundingRect, overflowContainerBoundingRect)) { isOverflowing = true; // console.log('Overflow', i, { // item: [itemBoundingRect.left, itemBoundingRect.right], // crop: [ // overflowContainerBoundingRect.left, // overflowContainerBoundingRect.right, // overflowContainerBoundingRect.width, // ], // container: $overflowContainer, // }) hide($item); return true; } // if there is an overflow, check collision of remaining items with eventual overflow position if ( isOverflowing && !$lastVisibleItem && wouldItemCollide($item, itemBoundingRect, overflowItemBoundingRect, overflowContainerBoundingRect) ) { hide($item); return true; } // Remember the last visible item if (!$lastVisibleItem) { $lastVisibleItem = $item; lastVisibleItemRect = itemBoundingRect; lastVisibleItemIndex.current = i; } return show($item); // exit the loop when first visible item is found }); // if there is an overflow, position and show overflow item, otherwise hide it if (isOverflowing || overflowOpen) { $overflowItem.style.position = 'absolute'; setOverflowPosition( $overflowItem, $lastVisibleItem, lastVisibleItemRect, overflowContainerBoundingRect, absolutePositioningOffset, ); show($overflowItem); } else { lastVisibleItemIndex.current = items.length - 1; hide($overflowItem); } _.invoke(props, 'onOverflow', lastVisibleItemIndex.current + 1); }; const collectOverflowItems = (): ToolbarItemProps['menu'] => { // console.log('getOverflowItems()', items.slice(lastVisibleItemIndex.current + 1)) return getOverflowItems ? getOverflowItems(lastVisibleItemIndex.current + 1) : items.slice(lastVisibleItemIndex.current + 1); }; const getVisibleItems = () => { // console.log('allItems()', items) const end = overflowOpen ? lastVisibleItemIndex.current + 1 : items.length; // console.log('getVisibleItems()', items.slice(0, end)) return items.slice(0, end); }; const handleWindowResize = _.debounce((e: UIEvent) => { hideOverflowItems(); if (overflowOpen) { _.invoke(props, 'onOverflowOpenChange', e, { ...props, overflowOpen: false }); } }, 16); const renderItems = (items: ToolbarProps['items']) => _.map(items, item => { const kind = _.get(item, 'kind', 'item'); switch (kind) { case 'divider': return createShorthand(composeOptions.slots.divider, item, { defaultProps: () => slotProps.divider, }); case 'group': return createShorthand(composeOptions.slots.group, item, { defaultProps: () => slotProps.group, }); case 'toggle': return createShorthand(composeOptions.slots.toggle, item, { defaultProps: () => slotProps.toggle, }); case 'custom': return createShorthand(composeOptions.slots.customItem, item, { defaultProps: () => slotProps.customItem, }); default: return createShorthand(composeOptions.slots.item, item, { defaultProps: () => slotProps.item, }); } }); const renderOverflowItem = overflowItem => createShorthand(composeOptions.slots.overflowItem, overflowItem, { defaultProps: () => slotProps.overflowItem, overrideProps: (predefinedProps: ToolbarOverflowItemProps) => ({ menu: { items: overflowOpen ? (collectOverflowItems() as ToolbarMenuProps['items']) : [], popper: { positionFixed: true, ...predefinedProps.menu?.popper }, }, menuOpen: overflowOpen, onMenuOpenChange: (e, { menuOpen }) => { _.invoke(props, 'onOverflowOpenChange', e, { ...props, overflowOpen: menuOpen }); }, wrapper: { ref: overflowItemWrapperRef, }, }), }); // renders a sentinel div that maintains the toolbar dimensions when the the overflow menu is open // hidden elements are removed from the DOM const renderOverflowSentinel = () => ( <Ref innerRef={(element: HTMLDivElement) => { overflowSentinelRef.current = element; }} > {Box.create(overflowSentinel, { defaultProps: () => ({ id: 'sentinel', className: classes.overflowSentinel, }), })} </Ref> ); React.useEffect(() => { const actualWindow: Window = context.target.defaultView; actualWindow.cancelAnimationFrame(animationFrameId.current); // Heads up! There are cases (like opening a portal and rendering the Toolbar there immediately) when rAF is necessary animationFrameId.current = actualWindow.requestAnimationFrame(() => { hideOverflowItems(); }); return () => { if (animationFrameId.current !== undefined) { context.target.defaultView?.cancelAnimationFrame(animationFrameId.current); animationFrameId.current = undefined; } }; }); const element = overflow ? ( <> <Ref innerRef={(node: HTMLDivElement) => { containerRef.current = node; handleRef(ref, node); }} > {getA11Props.unstable_wrapWithFocusZone( <ElementType {...getA11Props('root', { className: classes.root, ...unhandledProps })}> <div className={classes.overflowContainer} ref={overflowContainerRef}> <ToolbarMenuContextProvider value={{ slots: { menu: composeOptions.slots.menu } }}> <ToolbarVariablesProvider value={variables}> {childrenExist(children) ? children : renderItems(getVisibleItems())} {overflowSentinel && renderOverflowSentinel()} {renderOverflowItem(overflowItem)} </ToolbarVariablesProvider> </ToolbarMenuContextProvider> </div> <div className={classes.offsetMeasure} ref={offsetMeasureRef} /> </ElementType>, )} </Ref> <EventListener listener={handleWindowResize} target={context.target.defaultView} type="resize" /> </> ) : ( <Ref innerRef={(node: HTMLDivElement) => { containerRef.current = node; handleRef(ref, node); }} > {getA11Props.unstable_wrapWithFocusZone( <ElementType {...getA11Props('root', { className: classes.root, ...unhandledProps })}> <ToolbarMenuContextProvider value={{ slots: { menu: composeOptions.slots.menu } }}> <ToolbarVariablesProvider value={variables}> {childrenExist(children) ? children : renderItems(items)} </ToolbarVariablesProvider> </ToolbarMenuContextProvider> </ElementType>, )} </Ref> ); setEnd(); return element; }, { className: toolbarClassName, displayName: 'Toolbar', slots: { customItem: ToolbarCustomItem, divider: ToolbarDivider, item: ToolbarItem, group: ToolbarRadioGroup, toggle: ToolbarItem, overflowItem: ToolbarItem, menu: ToolbarMenu, }, slotProps: () => ({ toggle: { accessibility: toggleButtonBehavior, }, overflowItem: { icon: <MoreIcon outline />, }, }), shorthandConfig: { mappedProp: 'content' }, handledProps: [ 'accessibility', 'as', 'children', 'className', 'content', 'design', 'getOverflowItems', 'items', 'onOverflow', 'onOverflowOpenChange', 'overflow', 'overflowItem', 'overflowOpen', 'overflowSentinel', 'styles', 'variables', ], }, ) as ComponentWithAs<'div', ToolbarProps> & { CustomItem: typeof ToolbarCustomItem; Divider: typeof ToolbarDivider; Item: typeof ToolbarItem; ItemWrapper: typeof ToolbarItemWrapper; ItemIcon: typeof ToolbarItemIcon; Menu: typeof ToolbarMenu; MenuDivider: typeof ToolbarMenuDivider; MenuItem: typeof ToolbarMenuItem; MenuItemIcon: typeof ToolbarMenuItemIcon; MenuItemSubmenuIndicator: typeof ToolbarMenuItemSubmenuIndicator; MenuItemActiveIndicator: typeof ToolbarMenuItemActiveIndicator; MenuRadioGroup: typeof ToolbarMenuRadioGroup; MenuRadioGroupWrapper: typeof ToolbarMenuRadioGroupWrapper; RadioGroup: typeof ToolbarRadioGroup; }; Toolbar.propTypes = { ...commonPropTypes.createCommon(), items: customPropTypes.collectionShorthandWithKindProp(['divider', 'item', 'group', 'toggle', 'custom']), overflow: PropTypes.bool, overflowOpen: PropTypes.bool, overflowSentinel: customPropTypes.shorthandAllowingChildren, overflowItem: customPropTypes.shorthandAllowingChildren, onOverflow: PropTypes.func, onOverflowOpenChange: PropTypes.func, getOverflowItems: PropTypes.func, }; Toolbar.defaultProps = { accessibility: toolbarBehavior, items: [], overflowItem: {}, overflowSentinel: {}, }; Toolbar.CustomItem = ToolbarCustomItem; Toolbar.Divider = ToolbarDivider; Toolbar.Item = ToolbarItem; Toolbar.ItemWrapper = ToolbarItemWrapper; Toolbar.ItemIcon = ToolbarItemIcon; Toolbar.Menu = ToolbarMenu; Toolbar.MenuDivider = ToolbarMenuDivider; Toolbar.MenuItem = ToolbarMenuItem; Toolbar.MenuItemIcon = ToolbarMenuItemIcon; Toolbar.MenuItemSubmenuIndicator = ToolbarMenuItemSubmenuIndicator; Toolbar.MenuItemActiveIndicator = ToolbarMenuItemActiveIndicator; Toolbar.MenuRadioGroup = ToolbarMenuRadioGroup; Toolbar.MenuRadioGroupWrapper = ToolbarMenuRadioGroupWrapper; Toolbar.RadioGroup = ToolbarRadioGroup;
the_stack
import { JavaArrayList, JavaBigDecimal, JavaBigInteger, JavaBoolean, JavaByte, JavaDate, JavaDouble, JavaFloat, JavaHashMap, JavaHashSet, JavaInteger, JavaLong, JavaOptional, JavaShort, JavaString } from "../../../../java-wrappers"; import { GenericsTypeMarshallingUtils } from "../GenericsTypeMarshallingUtils"; import { MarshallingContext } from "../../../MarshallingContext"; import { JavaArrayListMarshaller, JavaHashSetMarshaller } from "../../JavaCollectionMarshaller"; import { ErraiObjectConstants } from "../../../model/ErraiObjectConstants"; import { MarshallerProvider } from "../../../MarshallerProvider"; import { JavaBigDecimalMarshaller } from "../../JavaBigDecimalMarshaller"; import { JavaBigIntegerMarshaller } from "../../JavaBigIntegerMarshaller"; import { JavaHashMapMarshaller } from "../../JavaHashMapMarshaller"; import { JavaLongMarshaller } from "../../JavaLongMarshaller"; import { JavaStringMarshaller } from "../../JavaStringMarshaller"; import { JavaDateMarshaller } from "../../JavaDateMarshaller"; import { DefaultMarshaller } from "../../DefaultMarshaller"; import { Portable } from "../../../Portable"; import { JavaOptionalMarshaller } from "../../JavaOptionalMarshaller"; import { NumValBasedErraiObject } from "../../../model/NumValBasedErraiObject"; import { JavaType } from "../../../../java-wrappers/JavaType"; describe("marshallGenericsTypeElement", () => { const objectId = ErraiObjectConstants.OBJECT_ID; beforeEach(() => { MarshallerProvider.initialize(); }); test("with array input, should marshall with regular marshalling", () => { const baseArray = ["str1", "str2"]; const arrayInput = { input: baseArray, inputAsJavaArrayList: new JavaArrayList(baseArray) }; const javaArrayListInput = { input: new JavaArrayList(baseArray), inputAsJavaArrayList: new JavaArrayList(baseArray) }; [arrayInput, javaArrayListInput].forEach(({ input, inputAsJavaArrayList }) => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaArrayListMarshaller().marshall(inputAsJavaArrayList, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); }); test("with Set input, should marshall with regular marshalling", () => { const baseSet = new Set(["str1", "str2"]); const setInput = { input: baseSet, inputAsJavaHashSet: new JavaHashSet(baseSet) }; const javaHashSetInput = { input: new JavaHashSet(baseSet), inputAsJavaHashSet: new JavaHashSet(baseSet) }; [setInput, javaHashSetInput].forEach(({ input, inputAsJavaHashSet }) => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaHashSetMarshaller().marshall(inputAsJavaHashSet, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); }); test("with JavaBigDecimal input, should marshall with regular marshalling", () => { const input = new JavaBigDecimal("1.1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaBigDecimalMarshaller().marshall(input, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); test("with JavaBigInteger input, should marshall with regular marshalling", () => { const input = new JavaBigInteger("1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaBigIntegerMarshaller().marshall(input, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); test("with map input, should marshall with regular marshalling", () => { const baseMap = new Map([["foo1", "bar1"], ["foo2", "bar2"]]); const mapInput = { input: baseMap, inputAsJavaHashMap: new JavaHashMap(baseMap) }; const javaHashMapInput = { input: new JavaHashMap(baseMap), inputAsJavaHashMap: new JavaHashMap(baseMap) }; [mapInput, javaHashMapInput].forEach(({ input, inputAsJavaHashMap }) => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaHashMapMarshaller().marshall(inputAsJavaHashMap, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); }); test("with JavaLong input, should marshall with regular marshalling", () => { const input = new JavaLong("1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaLongMarshaller().marshall(input, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); test("with string input, should marshall with regular marshalling", () => { const stringInput = { input: "str", inputAsJavaString: new JavaString("str") }; const javaStringInput = { input: new JavaString("str"), inputAsJavaString: new JavaString("str") }; [stringInput, javaStringInput].forEach(({ input, inputAsJavaString }) => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaStringMarshaller().marshall(inputAsJavaString, new MarshallingContext())!; expect(output).toStrictEqual(expected); }); }); test("with date input, should marshall with regular marshalling", () => { const baseDate = new Date(); const dateInput = { input: baseDate, inputAsJavaDate: new JavaDate(baseDate) }; const javaDateInput = { input: new JavaDate(baseDate), inputAsJavaDate: new JavaDate(baseDate) }; [dateInput, javaDateInput].forEach(({ input, inputAsJavaDate }) => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaDateMarshaller().marshall(inputAsJavaDate, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); }); test("with JavaOptional input, should marshall with regular marshalling", () => { const input = new JavaOptional<string>("str"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new JavaOptionalMarshaller().marshall(input, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); test("with custom portable input, should marshall with regular marshalling", () => { const input = new Pojo("bar"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); const expected = new DefaultMarshaller().marshall(input, new MarshallingContext())!; // don't care about the ids delete output[objectId]; delete expected[objectId]; expect(output).toStrictEqual(expected); }); test("with boolean input, should return input wrapped as an ErraiObject", () => { const booleanInput = false; const javaBooleanInput = new JavaBoolean(false); [booleanInput, javaBooleanInput].forEach(input => { const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.BOOLEAN, false).asErraiObject()); }); }); test("with JavaByte input, should return input wrapped as an ErraiObject", () => { const input = new JavaByte("1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.BYTE, 1).asErraiObject()); }); test("with JavaDouble input, should return input wrapped as an ErraiObject", () => { const input = new JavaDouble("1.1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.DOUBLE, 1.1).asErraiObject()); }); test("with JavaFloat input, should return input wrapped as an ErraiObject", () => { const input = new JavaFloat("1.1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.FLOAT, 1.1).asErraiObject()); }); test("with JavaInteger input, should return input wrapped as an ErraiObject", () => { const input = new JavaInteger("1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.INTEGER, 1).asErraiObject()); }); test("with JavaShort input, should return input wrapped as an ErraiObject", () => { const input = new JavaShort("1"); const output = GenericsTypeMarshallingUtils.marshallGenericsTypeElement(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.SHORT, 1).asErraiObject()); }); class Pojo implements Portable<Pojo> { private readonly _fqcn = "com.app.my.Pojo"; public foo: string; constructor(foo: string) { this.foo = foo; } } });
the_stack
import * as assert from 'assert'; import { join } from 'vs/base/common/path'; import { isLinux, isWindows } from 'vs/base/common/platform'; import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IRawFileWorkspaceFolder, Workspace, WorkspaceFolder } from 'vs/platform/workspace/common/workspace'; import { toWorkspaceFolders } from 'vs/platform/workspaces/common/workspaces'; suite('Workspace', () => { const fileFolder = isWindows ? 'c:\\src' : '/src'; const abcFolder = isWindows ? 'c:\\abc' : '/abc'; const testFolderUri = URI.file(join(fileFolder, 'test')); const mainFolderUri = URI.file(join(fileFolder, 'main')); const test1FolderUri = URI.file(join(fileFolder, 'test1')); const test2FolderUri = URI.file(join(fileFolder, 'test2')); const test3FolderUri = URI.file(join(fileFolder, 'test3')); const abcTest1FolderUri = URI.file(join(abcFolder, 'test1')); const abcTest3FolderUri = URI.file(join(abcFolder, 'test3')); const workspaceConfigUri = URI.file(join(fileFolder, 'test.code-workspace')); test('getFolder returns the folder with given uri', () => { const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 }); let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), expected, new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })], false, null, () => !isLinux); const actual = testObject.getFolder(expected.uri); assert.strictEqual(actual, expected); }); test('getFolder returns the folder if the uri is sub', () => { const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 }); let testObject = new Workspace('', [expected, new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 1 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })], false, null, () => !isLinux); const actual = testObject.getFolder(URI.file(join(fileFolder, 'test/a'))); assert.strictEqual(actual, expected); }); test('getFolder returns the closest folder if the uri is sub', () => { const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 }); let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected], false, null, () => !isLinux); const actual = testObject.getFolder(URI.file(join(fileFolder, 'test/a'))); assert.strictEqual(actual, expected); }); test('getFolder returns the folder even if the uri has query path', () => { const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 }); let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected], false, null, () => !isLinux); const actual = testObject.getFolder(URI.file(join(fileFolder, 'test/a')).with({ query: 'somequery' })); assert.strictEqual(actual, expected); }); test('getFolder returns null if the uri is not sub', () => { let testObject = new Workspace('', [new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 })], false, null, () => !isLinux); const actual = testObject.getFolder(URI.file(join(fileFolder, 'main/a'))); assert.strictEqual(actual, null); }); test('toWorkspaceFolders with single absolute folder', () => { const actual = toWorkspaceFolders([{ path: '/src/test' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 1); assert.strictEqual(actual[0].uri.fsPath, testFolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test'); }); test('toWorkspaceFolders with single relative folder', () => { const actual = toWorkspaceFolders([{ path: './test' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 1); assert.strictEqual(actual[0].uri.fsPath, testFolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, './test'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test'); }); test('toWorkspaceFolders with single absolute folder with name', () => { const actual = toWorkspaceFolders([{ path: '/src/test', name: 'hello' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 1); assert.strictEqual(actual[0].uri.fsPath, testFolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'hello'); }); test('toWorkspaceFolders with multiple unique absolute folders', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3' }, { path: '/src/test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 3); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, test3FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'test3'); assert.strictEqual(actual[2].uri.fsPath, test1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1'); assert.strictEqual(actual[2].index, 2); assert.strictEqual(actual[2].name, 'test1'); }); test('toWorkspaceFolders with multiple unique absolute folders with names', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 3); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, test3FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'noName'); assert.strictEqual(actual[2].uri.fsPath, test1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1'); assert.strictEqual(actual[2].index, 2); assert.strictEqual(actual[2].name, 'test1'); }); test('toWorkspaceFolders with multiple unique absolute and relative folders', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/abc/test3', name: 'noName' }, { path: './test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 3); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, abcTest3FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, '/abc/test3'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'noName'); assert.strictEqual(actual[2].uri.fsPath, test1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[2].raw).path, './test1'); assert.strictEqual(actual[2].index, 2); assert.strictEqual(actual[2].name, 'test1'); }); test('toWorkspaceFolders with multiple absolute folders with duplicates', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test2', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 2); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, test1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test1'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'test1'); }); test('toWorkspaceFolders with multiple absolute and relative folders with duplicates', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 3); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, test3FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'noName'); assert.strictEqual(actual[2].uri.fsPath, abcTest1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1'); assert.strictEqual(actual[2].index, 2); assert.strictEqual(actual[2].name, 'test1'); }); test('toWorkspaceFolders with multiple absolute and relative folders with invalid paths', () => { const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri, extUriBiasedIgnorePathCase); assert.strictEqual(actual.length, 3); assert.strictEqual(actual[0].uri.fsPath, test2FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2'); assert.strictEqual(actual[0].index, 0); assert.strictEqual(actual[0].name, 'test2'); assert.strictEqual(actual[1].uri.fsPath, test3FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[1].raw).path, './test3'); assert.strictEqual(actual[1].index, 1); assert.strictEqual(actual[1].name, 'test3'); assert.strictEqual(actual[2].uri.fsPath, abcTest1FolderUri.fsPath); assert.strictEqual((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1'); assert.strictEqual(actual[2].index, 2); assert.strictEqual(actual[2].name, 'test1'); }); });
the_stack
import { GaxiosPromise } from 'gaxios'; import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library'; import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common'; export declare namespace admin_directory_v1 { interface Options extends GlobalOptions { version: 'directory_v1'; } interface StandardParameters { /** * Data format for the response. */ alt?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API * access, quota, and reports. Required unless you provide an OAuth 2.0 * token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * An opaque string that represents a user for quota purposes. Must not * exceed 40 characters. */ quotaUser?: string; /** * Deprecated. Please use quotaUser instead. */ userIp?: string; } /** * Admin Directory API * * Manages enterprise resources such as users and groups, administrative * notifications, security features, and more. * * @example * const {google} = require('googleapis'); * const admin = google.admin('directory_v1'); * * @namespace admin * @type {Function} * @version directory_v1 * @variation directory_v1 * @param {object=} options Options for Admin */ class Admin { context: APIRequestContext; asps: Resource$Asps; channels: Resource$Channels; chromeosdevices: Resource$Chromeosdevices; customers: Resource$Customers; domainAliases: Resource$Domainaliases; domains: Resource$Domains; groups: Resource$Groups; members: Resource$Members; mobiledevices: Resource$Mobiledevices; notifications: Resource$Notifications; orgunits: Resource$Orgunits; privileges: Resource$Privileges; resolvedAppAccessSettings: Resource$Resolvedappaccesssettings; resources: Resource$Resources; roleAssignments: Resource$Roleassignments; roles: Resource$Roles; schemas: Resource$Schemas; tokens: Resource$Tokens; users: Resource$Users; verificationCodes: Resource$Verificationcodes; constructor(options: GlobalOptions, google?: GoogleConfigurable); } /** * JSON template for Alias object in Directory API. */ interface Schema$Alias { /** * A alias email */ alias?: string; /** * ETag of the resource. */ etag?: string; /** * Unique id of the group (Read-only) Unique id of the user (Read-only) */ id?: string; /** * Kind of resource this is. */ kind?: string; /** * Group&#39;s primary email (Read-only) User&#39;s primary email * (Read-only) */ primaryEmail?: string; } /** * JSON response template to list aliases in Directory API. */ interface Schema$Aliases { /** * List of alias objects. */ aliases?: any[]; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; } /** * JSON template for App Access Collections Resource object in Directory API. */ interface Schema$AppAccessCollections { /** * List of blocked api access buckets. */ blockedApiAccessBuckets?: string[]; /** * Boolean to indicate whether to enforce app access settings on Android * Drive or not. */ enforceSettingsForAndroidDrive?: boolean; /** * Error message provided by the Admin that will be shown to the user when * an app is blocked. */ errorMessage?: string; /** * ETag of the resource. */ etag?: string; /** * Identifies the resource as an app access collection. Value: * admin#directory#appaccesscollection */ kind?: string; /** * Unique ID of app access collection. (Readonly) */ resourceId?: string; /** * Resource name given by the customer while creating/updating. Should be * unique under given customer. */ resourceName?: string; /** * Boolean that indicates whether to trust domain owned apps. */ trustDomainOwnedApps?: boolean; } /** * The template that returns individual ASP (Access Code) data. */ interface Schema$Asp { /** * The unique ID of the ASP. */ codeId?: number; /** * The time when the ASP was created. Expressed in Unix time format. */ creationTime?: string; /** * ETag of the ASP. */ etag?: string; /** * The type of the API resource. This is always admin#directory#asp. */ kind?: string; /** * The time when the ASP was last used. Expressed in Unix time format. */ lastTimeUsed?: string; /** * The name of the application that the user, represented by their userId, * entered when the ASP was created. */ name?: string; /** * The unique ID of the user who issued the ASP. */ userKey?: string; } interface Schema$Asps { /** * ETag of the resource. */ etag?: string; /** * A list of ASP resources. */ items?: Schema$Asp[]; /** * The type of the API resource. This is always admin#directory#aspList. */ kind?: string; } /** * JSON template for Building object in Directory API. */ interface Schema$Building { /** * The postal address of the building. See PostalAddress for details. Note * that only a single address line and region code are required. */ address?: Schema$BuildingAddress; /** * Unique identifier for the building. The maximum length is 100 characters. */ buildingId?: string; /** * The building name as seen by users in Calendar. Must be unique for the * customer. For example, &quot;NYC-CHEL&quot;. The maximum length is 100 * characters. */ buildingName?: string; /** * The geographic coordinates of the center of the building, expressed as * latitude and longitude in decimal degrees. */ coordinates?: Schema$BuildingCoordinates; /** * A brief description of the building. For example, &quot;Chelsea * Market&quot;. */ description?: string; /** * ETag of the resource. */ etags?: string; /** * The display names for all floors in this building. The floors are * expected to be sorted in ascending order, from lowest floor to highest * floor. For example, [&quot;B2&quot;, &quot;B1&quot;, &quot;L&quot;, * &quot;1&quot;, &quot;2&quot;, &quot;2M&quot;, &quot;3&quot;, * &quot;PH&quot;] Must contain at least one entry. */ floorNames?: string[]; /** * Kind of resource this is. */ kind?: string; } /** * JSON template for the postal address of a building in Directory API. */ interface Schema$BuildingAddress { /** * Unstructured address lines describing the lower levels of an address. */ addressLines?: string[]; /** * Optional. Highest administrative subdivision which is used for postal * addresses of a country or region. */ administrativeArea?: string; /** * Optional. BCP-47 language code of the contents of this address (if * known). */ languageCode?: string; /** * Optional. Generally refers to the city/town portion of the address. * Examples: US city, IT comune, UK post town. In regions of the world where * localities are not well defined or do not fit into this structure well, * leave locality empty and use addressLines. */ locality?: string; /** * Optional. Postal code of the address. */ postalCode?: string; /** * Required. CLDR region code of the country/region of the address. */ regionCode?: string; /** * Optional. Sublocality of the address. */ sublocality?: string; } /** * JSON template for coordinates of a building in Directory API. */ interface Schema$BuildingCoordinates { /** * Latitude in decimal degrees. */ latitude?: number; /** * Longitude in decimal degrees. */ longitude?: number; } /** * JSON template for Building List Response object in Directory API. */ interface Schema$Buildings { /** * The Buildings in this page of results. */ buildings?: Schema$Building[]; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * The continuation token, used to page through large result sets. Provide * this value in a subsequent request to return the next page of results. */ nextPageToken?: string; } /** * JSON template for Calendar Resource object in Directory API. */ interface Schema$CalendarResource { /** * Unique ID for the building a resource is located in. */ buildingId?: string; /** * Capacity of a resource, number of seats in a room. */ capacity?: number; /** * ETag of the resource. */ etags?: string; featureInstances?: any; /** * Name of the floor a resource is located on. */ floorName?: string; /** * Name of the section within a floor a resource is located in. */ floorSection?: string; /** * The read-only auto-generated name of the calendar resource which includes * metadata about the resource such as building name, floor, capacity, etc. * For example, &quot;NYC-2-Training Room 1A (16)&quot;. */ generatedResourceName?: string; /** * The type of the resource. For calendar resources, the value is * admin#directory#resources#calendars#CalendarResource. */ kind?: string; /** * The category of the calendar resource. Either CONFERENCE_ROOM or OTHER. * Legacy data is set to CATEGORY_UNKNOWN. */ resourceCategory?: string; /** * Description of the resource, visible only to admins. */ resourceDescription?: string; /** * The read-only email for the calendar resource. Generated as part of * creating a new calendar resource. */ resourceEmail?: string; /** * The unique ID for the calendar resource. */ resourceId?: string; /** * The name of the calendar resource. For example, &quot;Training Room * 1A&quot;. */ resourceName?: string; /** * The type of the calendar resource, intended for non-room resources. */ resourceType?: string; /** * Description of the resource, visible to users and admins. */ userVisibleDescription?: string; } /** * JSON template for Calendar Resource List Response object in Directory API. */ interface Schema$CalendarResources { /** * ETag of the resource. */ etag?: string; /** * The CalendarResources in this page of results. */ items?: Schema$CalendarResource[]; /** * Identifies this as a collection of CalendarResources. This is always * admin#directory#resources#calendars#calendarResourcesList. */ kind?: string; /** * The continuation token, used to page through large result sets. Provide * this value in a subsequent request to return the next page of results. */ nextPageToken?: string; } /** * An notification channel used to watch for resource changes. */ interface Schema$Channel { /** * The address where notifications are delivered for this channel. */ address?: string; /** * Date and time of notification channel expiration, expressed as a Unix * timestamp, in milliseconds. Optional. */ expiration?: string; /** * A UUID or similar unique string that identifies this channel. */ id?: string; /** * Identifies this as a notification channel used to watch for changes to a * resource. Value: the fixed string &quot;api#channel&quot;. */ kind?: string; /** * Additional parameters controlling delivery channel behavior. Optional. */ params?: { [key: string]: string; }; /** * A Boolean value to indicate whether payload is wanted. Optional. */ payload?: boolean; /** * An opaque ID that identifies the resource being watched on this channel. * Stable across different API versions. */ resourceId?: string; /** * A version-specific identifier for the watched resource. */ resourceUri?: string; /** * An arbitrary string delivered to the target address with each * notification delivered over this channel. Optional. */ token?: string; /** * The type of delivery mechanism used for this channel. */ type?: string; } /** * JSON template for Chrome Os Device resource in Directory API. */ interface Schema$ChromeOsDevice { /** * List of active time ranges (Read-only) */ activeTimeRanges?: Array<{ activeTime?: number; date?: string; }>; /** * AssetId specified during enrollment or through later annotation */ annotatedAssetId?: string; /** * Address or location of the device as noted by the administrator */ annotatedLocation?: string; /** * User of the device */ annotatedUser?: string; /** * Chromebook boot mode (Read-only) */ bootMode?: string; /** * Reports of CPU utilization and temperature (Read-only) */ cpuStatusReports?: Array<{ cpuTemperatureInfo?: Array<{ label?: string; temperature?: number; }>; cpuUtilizationPercentageInfo?: number[]; reportTime?: string; }>; /** * List of device files to download (Read-only) */ deviceFiles?: Array<{ createTime?: string; downloadUrl?: string; name?: string; type?: string; }>; /** * Unique identifier of Chrome OS Device (Read-only) */ deviceId?: string; /** * Reports of disk space and other info about mounted/connected volumes. */ diskVolumeReports?: Array<{ volumeInfo?: Array<{ storageFree?: string; storageTotal?: string; volumeId?: string; }>; }>; /** * ETag of the resource. */ etag?: string; /** * Chromebook Mac Address on ethernet network interface (Read-only) */ ethernetMacAddress?: string; /** * Chromebook firmware version (Read-only) */ firmwareVersion?: string; /** * Kind of resource this is. */ kind?: string; /** * Date and time the device was last enrolled (Read-only) */ lastEnrollmentTime?: string; /** * Date and time the device was last synchronized with the policy settings * in the G Suite administrator control panel (Read-only) */ lastSync?: string; /** * Chromebook Mac Address on wifi network interface (Read-only) */ macAddress?: string; /** * Mobile Equipment identifier for the 3G mobile card in the Chromebook * (Read-only) */ meid?: string; /** * Chromebook Model (Read-only) */ model?: string; /** * Notes added by the administrator */ notes?: string; /** * Chromebook order number (Read-only) */ orderNumber?: string; /** * OrgUnit of the device */ orgUnitPath?: string; /** * Chromebook Os Version (Read-only) */ osVersion?: string; /** * Chromebook platform version (Read-only) */ platformVersion?: string; /** * List of recent device users, in descending order by last login time * (Read-only) */ recentUsers?: Array<{ email?: string; type?: string; }>; /** * Chromebook serial number (Read-only) */ serialNumber?: string; /** * status of the device (Read-only) */ status?: string; /** * Final date the device will be supported (Read-only) */ supportEndDate?: string; /** * Reports of amounts of available RAM memory (Read-only) */ systemRamFreeReports?: Array<{ reportTime?: string; systemRamFreeInfo?: string[]; }>; /** * Total RAM on the device [in bytes] (Read-only) */ systemRamTotal?: string; /** * Trusted Platform Module (TPM) (Read-only) */ tpmVersionInfo?: { family?: string; firmwareVersion?: string; manufacturer?: string; specLevel?: string; tpmModel?: string; vendorSpecific?: string; }; /** * Will Chromebook auto renew after support end date (Read-only) */ willAutoRenew?: boolean; } /** * JSON request template for firing actions on ChromeOs Device in Directory * Devices API. */ interface Schema$ChromeOsDeviceAction { /** * Action to be taken on the ChromeOs Device */ action?: string; deprovisionReason?: string; } /** * JSON response template for List Chrome OS Devices operation in Directory * API. */ interface Schema$ChromeOsDevices { /** * List of Chrome OS Device objects. */ chromeosdevices?: Schema$ChromeOsDevice[]; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * Token used to access next page of this result. */ nextPageToken?: string; } /** * JSON request template for moving ChromeOs Device to given OU in Directory * Devices API. */ interface Schema$ChromeOsMoveDevicesToOu { /** * ChromeOs Devices to be moved to OU */ deviceIds?: string[]; } /** * JSON template for Customer Resource object in Directory API. */ interface Schema$Customer { /** * The customer&#39;s secondary contact email address. This email address * cannot be on the same domain as the customerDomain */ alternateEmail?: string; /** * The customer&#39;s creation time (Readonly) */ customerCreationTime?: string; /** * The customer&#39;s primary domain name string. Do not include the www * prefix when creating a new customer. */ customerDomain?: string; /** * ETag of the resource. */ etag?: string; /** * The unique ID for the customer&#39;s G Suite account. (Readonly) */ id?: string; /** * Identifies the resource as a customer. Value: admin#directory#customer */ kind?: string; /** * The customer&#39;s ISO 639-2 language code. The default value is en-US */ language?: string; /** * The customer&#39;s contact phone number in E.164 format. */ phoneNumber?: string; /** * The customer&#39;s postal address information. */ postalAddress?: Schema$CustomerPostalAddress; } /** * JSON template for postal address of a customer. */ interface Schema$CustomerPostalAddress { /** * A customer&#39;s physical address. The address can be composed of one to * three lines. */ addressLine1?: string; /** * Address line 2 of the address. */ addressLine2?: string; /** * Address line 3 of the address. */ addressLine3?: string; /** * The customer contact&#39;s name. */ contactName?: string; /** * This is a required property. For countryCode information see the ISO 3166 * country code elements. */ countryCode?: string; /** * Name of the locality. An example of a locality value is the city of San * Francisco. */ locality?: string; /** * The company or company division name. */ organizationName?: string; /** * The postal code. A postalCode example is a postal zip code such as 10009. * This is in accordance with - * http://portablecontacts.net/draft-spec.html#address_element. */ postalCode?: string; /** * Name of the region. An example of a region value is NY for the state of * New York. */ region?: string; } /** * JSON template for Domain Alias object in Directory API. */ interface Schema$DomainAlias { /** * The creation time of the domain alias. (Read-only). */ creationTime?: string; /** * The domain alias name. */ domainAliasName?: string; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * The parent domain name that the domain alias is associated with. This can * either be a primary or secondary domain name within a customer. */ parentDomainName?: string; /** * Indicates the verification state of a domain alias. (Read-only) */ verified?: boolean; } /** * JSON response template to list domain aliases in Directory API. */ interface Schema$DomainAliases { /** * List of domain alias objects. */ domainAliases?: Schema$DomainAlias[]; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; } /** * JSON template for Domain object in Directory API. */ interface Schema$Domains { /** * Creation time of the domain. (Read-only). */ creationTime?: string; /** * List of domain alias objects. (Read-only) */ domainAliases?: Schema$DomainAlias[]; /** * The domain name of the customer. */ domainName?: string; /** * ETag of the resource. */ etag?: string; /** * Indicates if the domain is a primary domain (Read-only). */ isPrimary?: boolean; /** * Kind of resource this is. */ kind?: string; /** * Indicates the verification state of a domain. (Read-only). */ verified?: boolean; } /** * JSON response template to list Domains in Directory API. */ interface Schema$Domains2 { /** * List of domain objects. */ domains?: Schema$Domains[]; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; } /** * JSON template for Feature object in Directory API. */ interface Schema$Feature { /** * ETag of the resource. */ etags?: string; /** * Kind of resource this is. */ kind?: string; /** * The name of the feature. */ name?: string; } /** * JSON template for a &quot;feature instance&quot;. */ interface Schema$FeatureInstance { /** * The feature that this is an instance of. A calendar resource may have * multiple instances of a feature. */ feature?: Schema$Feature; } /** * JSON request template for renaming a feature. */ interface Schema$FeatureRename { /** * New name of the feature. */ newName?: string; } /** * JSON template for Feature List Response object in Directory API. */ interface Schema$Features { /** * ETag of the resource. */ etag?: string; /** * The Features in this page of results. */ features?: Schema$Feature[]; /** * Kind of resource this is. */ kind?: string; /** * The continuation token, used to page through large result sets. Provide * this value in a subsequent request to return the next page of results. */ nextPageToken?: string; } /** * JSON template for Group resource in Directory API. */ interface Schema$Group { /** * Is the group created by admin (Read-only) * */ adminCreated?: boolean; /** * List of aliases (Read-only) */ aliases?: string[]; /** * Description of the group */ description?: string; /** * Group direct members count */ directMembersCount?: string; /** * Email of Group */ email?: string; /** * ETag of the resource. */ etag?: string; /** * Unique identifier of Group (Read-only) */ id?: string; /** * Kind of resource this is. */ kind?: string; /** * Group name */ name?: string; /** * List of non editable aliases (Read-only) */ nonEditableAliases?: string[]; } /** * JSON response template for List Groups operation in Directory API. */ interface Schema$Groups { /** * ETag of the resource. */ etag?: string; /** * List of group objects. */ groups?: Schema$Group[]; /** * Kind of resource this is. */ kind?: string; /** * Token used to access next page of this result. */ nextPageToken?: string; } /** * JSON template for Member resource in Directory API. */ interface Schema$Member { /** * Delivery settings of member */ delivery_settings?: string; /** * Email of member (Read-only) */ email?: string; /** * ETag of the resource. */ etag?: string; /** * Unique identifier of customer member (Read-only) Unique identifier of * group (Read-only) Unique identifier of member (Read-only) */ id?: string; /** * Kind of resource this is. */ kind?: string; /** * Role of member */ role?: string; /** * Status of member (Immutable) */ status?: string; /** * Type of member (Immutable) */ type?: string; } /** * JSON response template for List Members operation in Directory API. */ interface Schema$Members { /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * List of member objects. */ members?: Schema$Member[]; /** * Token used to access next page of this result. */ nextPageToken?: string; } /** * JSON template for Has Member response in Directory API. */ interface Schema$MembersHasMember { /** * Identifies whether the given user is a member of the group. Membership * can be direct or nested. */ isMember?: boolean; } /** * JSON template for Mobile Device resource in Directory API. */ interface Schema$MobileDevice { /** * Adb (USB debugging) enabled or disabled on device (Read-only) */ adbStatus?: boolean; /** * List of applications installed on Mobile Device */ applications?: Array<{ displayName?: string; packageName?: string; permission?: string[]; versionCode?: number; versionName?: string; }>; /** * Mobile Device Baseband version (Read-only) */ basebandVersion?: string; /** * Mobile Device Bootloader version (Read-only) */ bootloaderVersion?: string; /** * Mobile Device Brand (Read-only) */ brand?: string; /** * Mobile Device Build number (Read-only) */ buildNumber?: string; /** * The default locale used on the Mobile Device (Read-only) */ defaultLanguage?: string; /** * Developer options enabled or disabled on device (Read-only) */ developerOptionsStatus?: boolean; /** * Mobile Device compromised status (Read-only) */ deviceCompromisedStatus?: string; /** * Mobile Device serial number (Read-only) */ deviceId?: string; /** * DevicePasswordStatus (Read-only) */ devicePasswordStatus?: string; /** * List of owner user&#39;s email addresses (Read-only) */ email?: string[]; /** * Mobile Device Encryption Status (Read-only) */ encryptionStatus?: string; /** * ETag of the resource. */ etag?: string; /** * Date and time the device was first synchronized with the policy settings * in the G Suite administrator control panel (Read-only) */ firstSync?: string; /** * Mobile Device Hardware (Read-only) */ hardware?: string; /** * Mobile Device Hardware Id (Read-only) */ hardwareId?: string; /** * Mobile Device IMEI number (Read-only) */ imei?: string; /** * Mobile Device Kernel version (Read-only) */ kernelVersion?: string; /** * Kind of resource this is. */ kind?: string; /** * Date and time the device was last synchronized with the policy settings * in the G Suite administrator control panel (Read-only) */ lastSync?: string; /** * Boolean indicating if this account is on owner/primary profile or not * (Read-only) */ managedAccountIsOnOwnerProfile?: boolean; /** * Mobile Device manufacturer (Read-only) */ manufacturer?: string; /** * Mobile Device MEID number (Read-only) */ meid?: string; /** * Name of the model of the device */ model?: string; /** * List of owner user&#39;s names (Read-only) */ name?: string[]; /** * Mobile Device mobile or network operator (if available) (Read-only) */ networkOperator?: string; /** * Name of the mobile operating system */ os?: string; /** * List of accounts added on device (Read-only) */ otherAccountsInfo?: string[]; /** * DMAgentPermission (Read-only) */ privilege?: string; /** * Mobile Device release version version (Read-only) */ releaseVersion?: string; /** * Unique identifier of Mobile Device (Read-only) */ resourceId?: string; /** * Mobile Device Security patch level (Read-only) */ securityPatchLevel?: string; /** * Mobile Device SSN or Serial Number (Read-only) */ serialNumber?: string; /** * Status of the device (Read-only) */ status?: string; /** * Work profile supported on device (Read-only) */ supportsWorkProfile?: boolean; /** * The type of device (Read-only) */ type?: string; /** * Unknown sources enabled or disabled on device (Read-only) */ unknownSourcesStatus?: boolean; /** * Mobile Device user agent */ userAgent?: string; /** * Mobile Device WiFi MAC address (Read-only) */ wifiMacAddress?: string; } /** * JSON request template for firing commands on Mobile Device in Directory * Devices API. */ interface Schema$MobileDeviceAction { /** * Action to be taken on the Mobile Device */ action?: string; } /** * JSON response template for List Mobile Devices operation in Directory API. */ interface Schema$MobileDevices { /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * List of Mobile Device objects. */ mobiledevices?: Schema$MobileDevice[]; /** * Token used to access next page of this result. */ nextPageToken?: string; } /** * Template for a notification resource. */ interface Schema$Notification { /** * Body of the notification (Read-only) */ body?: string; /** * ETag of the resource. */ etag?: string; /** * Address from which the notification is received (Read-only) */ fromAddress?: string; /** * Boolean indicating whether the notification is unread or not. */ isUnread?: boolean; /** * The type of the resource. */ kind?: string; notificationId?: string; /** * Time at which notification was sent (Read-only) */ sendTime?: string; /** * Subject of the notification (Read-only) */ subject?: string; } /** * Template for notifications list response. */ interface Schema$Notifications { /** * ETag of the resource. */ etag?: string; /** * List of notifications in this page. */ items?: Schema$Notification[]; /** * The type of the resource. */ kind?: string; /** * Token for fetching the next page of notifications. */ nextPageToken?: string; /** * Number of unread notification for the domain. */ unreadNotificationsCount?: number; } /** * JSON template for Org Unit resource in Directory API. */ interface Schema$OrgUnit { /** * Should block inheritance */ blockInheritance?: boolean; /** * Description of OrgUnit */ description?: string; /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * Name of OrgUnit */ name?: string; /** * Id of OrgUnit */ orgUnitId?: string; /** * Path of OrgUnit */ orgUnitPath?: string; /** * Id of parent OrgUnit */ parentOrgUnitId?: string; /** * Path of parent OrgUnit */ parentOrgUnitPath?: string; } /** * JSON response template for List Organization Units operation in Directory * API. */ interface Schema$OrgUnits { /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * List of user objects. */ organizationUnits?: Schema$OrgUnit[]; } /** * JSON template for privilege resource in Directory API. */ interface Schema$Privilege { /** * A list of child privileges. Privileges for a service form a tree. Each * privilege can have a list of child privileges; this list is empty for a * leaf privilege. */ childPrivileges?: Schema$Privilege[]; /** * ETag of the resource. */ etag?: string; /** * If the privilege can be restricted to an organization unit. */ isOuScopable?: boolean; /** * The type of the API resource. This is always admin#directory#privilege. */ kind?: string; /** * The name of the privilege. */ privilegeName?: string; /** * The obfuscated ID of the service this privilege is for. */ serviceId?: string; /** * The name of the service this privilege is for. */ serviceName?: string; } /** * JSON response template for List privileges operation in Directory API. */ interface Schema$Privileges { /** * ETag of the resource. */ etag?: string; /** * A list of Privilege resources. */ items?: Schema$Privilege[]; /** * The type of the API resource. This is always admin#directory#privileges. */ kind?: string; } /** * JSON template for role resource in Directory API. */ interface Schema$Role { /** * ETag of the resource. */ etag?: string; /** * Returns true if the role is a super admin role. */ isSuperAdminRole?: boolean; /** * Returns true if this is a pre-defined system role. */ isSystemRole?: boolean; /** * The type of the API resource. This is always admin#directory#role. */ kind?: string; /** * A short description of the role. */ roleDescription?: string; /** * ID of the role. */ roleId?: string; /** * Name of the role. */ roleName?: string; /** * The set of privileges that are granted to this role. */ rolePrivileges?: Array<{ privilegeName?: string; serviceId?: string; }>; } /** * JSON template for roleAssignment resource in Directory API. */ interface Schema$RoleAssignment { /** * The unique ID of the user this role is assigned to. */ assignedTo?: string; /** * ETag of the resource. */ etag?: string; /** * The type of the API resource. This is always * admin#directory#roleAssignment. */ kind?: string; /** * If the role is restricted to an organization unit, this contains the ID * for the organization unit the exercise of this role is restricted to. */ orgUnitId?: string; /** * ID of this roleAssignment. */ roleAssignmentId?: string; /** * The ID of the role that is assigned. */ roleId?: string; /** * The scope in which this role is assigned. Possible values are: - * CUSTOMER - ORG_UNIT */ scopeType?: string; } /** * JSON response template for List roleAssignments operation in Directory API. */ interface Schema$RoleAssignments { /** * ETag of the resource. */ etag?: string; /** * A list of RoleAssignment resources. */ items?: Schema$RoleAssignment[]; /** * The type of the API resource. This is always * admin#directory#roleAssignments. */ kind?: string; nextPageToken?: string; } /** * JSON response template for List roles operation in Directory API. */ interface Schema$Roles { /** * ETag of the resource. */ etag?: string; /** * A list of Role resources. */ items?: Schema$Role[]; /** * The type of the API resource. This is always admin#directory#roles. */ kind?: string; nextPageToken?: string; } /** * JSON template for Schema resource in Directory API. */ interface Schema$Schema { /** * Display name for the schema. */ displayName?: string; /** * ETag of the resource. */ etag?: string; /** * Fields of Schema */ fields?: Schema$SchemaFieldSpec[]; /** * Kind of resource this is. */ kind?: string; /** * Unique identifier of Schema (Read-only) */ schemaId?: string; /** * Schema name */ schemaName?: string; } /** * JSON template for FieldSpec resource for Schemas in Directory API. */ interface Schema$SchemaFieldSpec { /** * Display Name of the field. */ displayName?: string; /** * ETag of the resource. */ etag?: string; /** * Unique identifier of Field (Read-only) */ fieldId?: string; /** * Name of the field. */ fieldName?: string; /** * Type of the field. */ fieldType?: string; /** * Boolean specifying whether the field is indexed or not. */ indexed?: boolean; /** * Kind of resource this is. */ kind?: string; /** * Boolean specifying whether this is a multi-valued field or not. */ multiValued?: boolean; /** * Indexing spec for a numeric field. By default, only exact match queries * will be supported for numeric fields. Setting the numericIndexingSpec * allows range queries to be supported. */ numericIndexingSpec?: { maxValue?: number; minValue?: number; }; /** * Read ACLs on the field specifying who can view values of this field. * Valid values are &quot;ALL_DOMAIN_USERS&quot; and * &quot;ADMINS_AND_SELF&quot;. */ readAccessType?: string; } /** * JSON response template for List Schema operation in Directory API. */ interface Schema$Schemas { /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * List of UserSchema objects. */ schemas?: Schema$Schema[]; } /** * JSON template for token resource in Directory API. */ interface Schema$Token { /** * Whether the application is registered with Google. The value is true if * the application has an anonymous Client ID. */ anonymous?: boolean; /** * The Client ID of the application the token is issued to. */ clientId?: string; /** * The displayable name of the application the token is issued to. */ displayText?: string; /** * ETag of the resource. */ etag?: string; /** * The type of the API resource. This is always admin#directory#token. */ kind?: string; /** * Whether the token is issued to an installed application. The value is * true if the application is installed to a desktop or mobile device. */ nativeApp?: boolean; /** * A list of authorization scopes the application is granted. */ scopes?: string[]; /** * The unique ID of the user that issued the token. */ userKey?: string; } /** * JSON response template for List tokens operation in Directory API. */ interface Schema$Tokens { /** * ETag of the resource. */ etag?: string; /** * A list of Token resources. */ items?: Schema$Token[]; /** * The type of the API resource. This is always admin#directory#tokenList. */ kind?: string; } /** * JSON template for Trusted App Ids Resource object in Directory API. */ interface Schema$TrustedAppId { /** * Android package name. */ androidPackageName?: string; /** * SHA1 signature of the app certificate. */ certificateHashSHA1?: string; /** * SHA256 signature of the app certificate. */ certificateHashSHA256?: string; etag?: string; /** * Identifies the resource as a trusted AppId. */ kind?: string; } /** * JSON template for Trusted Apps response object of a user in Directory API. */ interface Schema$TrustedApps { /** * ETag of the resource. */ etag?: string; /** * Identifies the resource as trusted apps response. */ kind?: string; nextPageToken?: string; /** * Trusted Apps list. */ trustedApps?: Schema$TrustedAppId[]; } /** * JSON template for User object in Directory API. */ interface Schema$User { addresses?: any; /** * Indicates if user has agreed to terms (Read-only) */ agreedToTerms?: boolean; /** * List of aliases (Read-only) */ aliases?: string[]; /** * Indicates if user is archived. */ archived?: boolean; /** * Boolean indicating if the user should change password in next login */ changePasswordAtNextLogin?: boolean; /** * User&#39;s G Suite account creation time. (Read-only) */ creationTime?: string; /** * CustomerId of User (Read-only) */ customerId?: string; /** * Custom fields of the user. */ customSchemas?: { [key: string]: Schema$UserCustomProperties; }; deletionTime?: string; emails?: any; /** * ETag of the resource. */ etag?: string; externalIds?: any; gender?: any; /** * Hash function name for password. Supported are MD5, SHA-1 and crypt */ hashFunction?: string; /** * Unique identifier of User (Read-only) */ id?: string; ims?: any; /** * Boolean indicating if user is included in Global Address List */ includeInGlobalAddressList?: boolean; /** * Boolean indicating if ip is whitelisted */ ipWhitelisted?: boolean; /** * Boolean indicating if the user is admin (Read-only) */ isAdmin?: boolean; /** * Boolean indicating if the user is delegated admin (Read-only) */ isDelegatedAdmin?: boolean; /** * Is 2-step verification enforced (Read-only) */ isEnforcedIn2Sv?: boolean; /** * Is enrolled in 2-step verification (Read-only) */ isEnrolledIn2Sv?: boolean; /** * Is mailbox setup (Read-only) */ isMailboxSetup?: boolean; keywords?: any; /** * Kind of resource this is. */ kind?: string; languages?: any; /** * User&#39;s last login time. (Read-only) */ lastLoginTime?: string; locations?: any; /** * User&#39;s name */ name?: Schema$UserName; /** * List of non editable aliases (Read-only) */ nonEditableAliases?: string[]; notes?: any; organizations?: any; /** * OrgUnit of User */ orgUnitPath?: string; /** * User&#39;s password */ password?: string; phones?: any; posixAccounts?: any; /** * username of User */ primaryEmail?: string; relations?: any; sshPublicKeys?: any; /** * Indicates if user is suspended. */ suspended?: boolean; /** * Suspension reason if user is suspended (Read-only) */ suspensionReason?: string; /** * ETag of the user&#39;s photo (Read-only) */ thumbnailPhotoEtag?: string; /** * Photo Url of the user (Read-only) */ thumbnailPhotoUrl?: string; websites?: any; } /** * JSON template for About (notes) of a user in Directory API. */ interface Schema$UserAbout { /** * About entry can have a type which indicates the content type. It can * either be plain or html. By default, notes contents are assumed to * contain plain text. */ contentType?: string; /** * Actual value of notes. */ value?: string; } /** * JSON template for address. */ interface Schema$UserAddress { /** * Country. */ country?: string; /** * Country code. */ countryCode?: string; /** * Custom type. */ customType?: string; /** * Extended Address. */ extendedAddress?: string; /** * Formatted address. */ formatted?: string; /** * Locality. */ locality?: string; /** * Other parts of address. */ poBox?: string; /** * Postal code. */ postalCode?: string; /** * If this is user&#39;s primary address. Only one entry could be marked as * primary. */ primary?: boolean; /** * Region. */ region?: string; /** * User supplied address was structured. Structured addresses are NOT * supported at this time. You might be able to write structured addresses, * but any values will eventually be clobbered. */ sourceIsStructured?: boolean; /** * Street. */ streetAddress?: string; /** * Each entry can have a type which indicates standard values of that entry. * For example address could be of home, work etc. In addition to the * standard type, an entry can have a custom type and can take any value. * Such type should have the CUSTOM value as type and also have a customType * value. */ type?: string; } /** * JSON template for a set of custom properties (i.e. all fields in a * particular schema) */ interface Schema$UserCustomProperties { } /** * JSON template for an email. */ interface Schema$UserEmail { /** * Email id of the user. */ address?: string; /** * Custom Type. */ customType?: string; /** * If this is user&#39;s primary email. Only one entry could be marked as * primary. */ primary?: boolean; /** * Each entry can have a type which indicates standard types of that entry. * For example email could be of home, work etc. In addition to the standard * type, an entry can have a custom type and can take any value Such types * should have the CUSTOM value as type and also have a customType value. */ type?: string; } /** * JSON template for an externalId entry. */ interface Schema$UserExternalId { /** * Custom type. */ customType?: string; /** * The type of the Id. */ type?: string; /** * The value of the id. */ value?: string; } interface Schema$UserGender { /** * AddressMeAs. A human-readable string containing the proper way to refer * to the profile owner by humans, for example &quot;he/him/his&quot; or * &quot;they/them/their&quot;. */ addressMeAs?: string; /** * Custom gender. */ customGender?: string; /** * Gender. */ type?: string; } /** * JSON template for instant messenger of an user. */ interface Schema$UserIm { /** * Custom protocol. */ customProtocol?: string; /** * Custom type. */ customType?: string; /** * Instant messenger id. */ im?: string; /** * If this is user&#39;s primary im. Only one entry could be marked as * primary. */ primary?: boolean; /** * Protocol used in the instant messenger. It should be one of the values * from ImProtocolTypes map. Similar to type, it can take a CUSTOM value and * specify the custom name in customProtocol field. */ protocol?: string; /** * Each entry can have a type which indicates standard types of that entry. * For example instant messengers could be of home, work etc. In addition to * the standard type, an entry can have a custom type and can take any * value. Such types should have the CUSTOM value as type and also have a * customType value. */ type?: string; } /** * JSON template for a keyword entry. */ interface Schema$UserKeyword { /** * Custom Type. */ customType?: string; /** * Each entry can have a type which indicates standard type of that entry. * For example, keyword could be of type occupation or outlook. In addition * to the standard type, an entry can have a custom type and can give it any * name. Such types should have the CUSTOM value as type and also have a * customType value. */ type?: string; /** * Keyword. */ value?: string; } /** * JSON template for a language entry. */ interface Schema$UserLanguage { /** * Other language. User can provide own language name if there is no * corresponding Google III language code. If this is set LanguageCode * can&#39;t be set */ customLanguage?: string; /** * Language Code. Should be used for storing Google III LanguageCode string * representation for language. Illegal values cause SchemaException. */ languageCode?: string; } /** * JSON template for a location entry. */ interface Schema$UserLocation { /** * Textual location. This is most useful for display purposes to concisely * describe the location. For example, &quot;Mountain View, CA&quot;, * &quot;Near Seattle&quot;, &quot;US-NYC-9TH 9A209A&quot;. */ area?: string; /** * Building Identifier. */ buildingId?: string; /** * Custom Type. */ customType?: string; /** * Most specific textual code of individual desk location. */ deskCode?: string; /** * Floor name/number. */ floorName?: string; /** * Floor section. More specific location within the floor. For example, if a * floor is divided into sections &quot;A&quot;, &quot;B&quot;, and * &quot;C&quot;, this field would identify one of those values. */ floorSection?: string; /** * Each entry can have a type which indicates standard types of that entry. * For example location could be of types default and desk. In addition to * standard type, an entry can have a custom type and can give it any name. * Such types should have &quot;custom&quot; as type and also have a * customType value. */ type?: string; } /** * JSON request template for setting/revoking admin status of a user in * Directory API. */ interface Schema$UserMakeAdmin { /** * Boolean indicating new admin status of the user */ status?: boolean; } /** * JSON template for name of a user in Directory API. */ interface Schema$UserName { /** * Last Name */ familyName?: string; /** * Full Name */ fullName?: string; /** * First Name */ givenName?: string; } /** * JSON template for an organization entry. */ interface Schema$UserOrganization { /** * The cost center of the users department. */ costCenter?: string; /** * Custom type. */ customType?: string; /** * Department within the organization. */ department?: string; /** * Description of the organization. */ description?: string; /** * The domain to which the organization belongs to. */ domain?: string; /** * The full-time equivalent percent within the organization (100000 = 100%). */ fullTimeEquivalent?: number; /** * Location of the organization. This need not be fully qualified address. */ location?: string; /** * Name of the organization */ name?: string; /** * If it user&#39;s primary organization. */ primary?: boolean; /** * Symbol of the organization. */ symbol?: string; /** * Title (designation) of the user in the organization. */ title?: string; /** * Each entry can have a type which indicates standard types of that entry. * For example organization could be of school, work etc. In addition to the * standard type, an entry can have a custom type and can give it any name. * Such types should have the CUSTOM value as type and also have a * CustomType value. */ type?: string; } /** * JSON template for a phone entry. */ interface Schema$UserPhone { /** * Custom Type. */ customType?: string; /** * If this is user&#39;s primary phone or not. */ primary?: boolean; /** * Each entry can have a type which indicates standard types of that entry. * For example phone could be of home_fax, work, mobile etc. In addition to * the standard type, an entry can have a custom type and can give it any * name. Such types should have the CUSTOM value as type and also have a * customType value. */ type?: string; /** * Phone number. */ value?: string; } /** * JSON template for Photo object in Directory API. */ interface Schema$UserPhoto { /** * ETag of the resource. */ etag?: string; /** * Height in pixels of the photo */ height?: number; /** * Unique identifier of User (Read-only) */ id?: string; /** * Kind of resource this is. */ kind?: string; /** * Mime Type of the photo */ mimeType?: string; /** * Base64 encoded photo data */ photoData?: string; /** * Primary email of User (Read-only) */ primaryEmail?: string; /** * Width in pixels of the photo */ width?: number; } /** * JSON template for a POSIX account entry. Description of the field family: * go/fbs-posix. */ interface Schema$UserPosixAccount { /** * A POSIX account field identifier. */ accountId?: string; /** * The GECOS (user information) for this account. */ gecos?: string; /** * The default group ID. */ gid?: string; /** * The path to the home directory for this account. */ homeDirectory?: string; /** * The operating system type for this account. */ operatingSystemType?: string; /** * If this is user&#39;s primary account within the SystemId. */ primary?: boolean; /** * The path to the login shell for this account. */ shell?: string; /** * System identifier for which account Username or Uid apply to. */ systemId?: string; /** * The POSIX compliant user ID. */ uid?: string; /** * The username of the account. */ username?: string; } /** * JSON template for a relation entry. */ interface Schema$UserRelation { /** * Custom Type. */ customType?: string; /** * The relation of the user. Some of the possible values are mother, father, * sister, brother, manager, assistant, partner. */ type?: string; /** * The name of the relation. */ value?: string; } /** * JSON response template for List Users operation in Apps Directory API. */ interface Schema$Users { /** * ETag of the resource. */ etag?: string; /** * Kind of resource this is. */ kind?: string; /** * Token used to access next page of this result. */ nextPageToken?: string; /** * Event that triggered this response (only used in case of Push Response) */ trigger_event?: string; /** * List of user objects. */ users?: Schema$User[]; } /** * JSON template for a POSIX account entry. */ interface Schema$UserSshPublicKey { /** * An expiration time in microseconds since epoch. */ expirationTimeUsec?: string; /** * A SHA-256 fingerprint of the SSH public key. (Read-only) */ fingerprint?: string; /** * An SSH public key. */ key?: string; } /** * JSON request template to undelete a user in Directory API. */ interface Schema$UserUndelete { /** * OrgUnit of User */ orgUnitPath?: string; } /** * JSON template for a website entry. */ interface Schema$UserWebsite { /** * Custom Type. */ customType?: string; /** * If this is user&#39;s primary website or not. */ primary?: boolean; /** * Each entry can have a type which indicates standard types of that entry. * For example website could be of home, work, blog etc. In addition to the * standard type, an entry can have a custom type and can give it any name. * Such types should have the CUSTOM value as type and also have a * customType value. */ type?: string; /** * Website. */ value?: string; } /** * JSON template for verification codes in Directory API. */ interface Schema$VerificationCode { /** * ETag of the resource. */ etag?: string; /** * The type of the resource. This is always * admin#directory#verificationCode. */ kind?: string; /** * The obfuscated unique ID of the user. */ userId?: string; /** * A current verification code for the user. Invalidated or used * verification codes are not returned as part of the result. */ verificationCode?: string; } /** * JSON response template for List verification codes operation in Directory * API. */ interface Schema$VerificationCodes { /** * ETag of the resource. */ etag?: string; /** * A list of verification code resources. */ items?: Schema$VerificationCode[]; /** * The type of the resource. This is always * admin#directory#verificationCodesList. */ kind?: string; } class Resource$Asps { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.asps.delete * @desc Delete an ASP issued by a user. * @alias directory.asps.delete * @memberOf! () * * @param {object} params Parameters for request * @param {integer} params.codeId The unique ID of the ASP to be deleted. * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Asps$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Asps$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Asps$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.asps.get * @desc Get information about an ASP issued by a user. * @alias directory.asps.get * @memberOf! () * * @param {object} params Parameters for request * @param {integer} params.codeId The unique ID of the ASP. * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Asps$Get, options?: MethodOptions): GaxiosPromise<Schema$Asp>; get(params: Params$Resource$Asps$Get, options: MethodOptions | BodyResponseCallback<Schema$Asp>, callback: BodyResponseCallback<Schema$Asp>): void; get(params: Params$Resource$Asps$Get, callback: BodyResponseCallback<Schema$Asp>): void; get(callback: BodyResponseCallback<Schema$Asp>): void; /** * directory.asps.list * @desc List the ASPs issued by a user. * @alias directory.asps.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Asps$List, options?: MethodOptions): GaxiosPromise<Schema$Asps>; list(params: Params$Resource$Asps$List, options: MethodOptions | BodyResponseCallback<Schema$Asps>, callback: BodyResponseCallback<Schema$Asps>): void; list(params: Params$Resource$Asps$List, callback: BodyResponseCallback<Schema$Asps>): void; list(callback: BodyResponseCallback<Schema$Asps>): void; } interface Params$Resource$Asps$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the ASP to be deleted. */ codeId?: number; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } interface Params$Resource$Asps$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the ASP. */ codeId?: number; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } interface Params$Resource$Asps$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } class Resource$Channels { context: APIRequestContext; constructor(context: APIRequestContext); /** * admin.channels.stop * @desc Stop watching resources through this channel * @alias admin.channels.stop * @memberOf! () * * @param {object} params Parameters for request * @param {().Channel} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ stop(params?: Params$Resource$Channels$Stop, options?: MethodOptions): GaxiosPromise<void>; stop(params: Params$Resource$Channels$Stop, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; stop(params: Params$Resource$Channels$Stop, callback: BodyResponseCallback<void>): void; stop(callback: BodyResponseCallback<void>): void; } interface Params$Resource$Channels$Stop extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$Channel; } class Resource$Chromeosdevices { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.chromeosdevices.action * @desc Take action on Chrome OS Device * @alias directory.chromeosdevices.action * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.resourceId Immutable ID of Chrome OS Device * @param {().ChromeOsDeviceAction} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ action(params?: Params$Resource$Chromeosdevices$Action, options?: MethodOptions): GaxiosPromise<void>; action(params: Params$Resource$Chromeosdevices$Action, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; action(params: Params$Resource$Chromeosdevices$Action, callback: BodyResponseCallback<void>): void; action(callback: BodyResponseCallback<void>): void; /** * directory.chromeosdevices.get * @desc Retrieve Chrome OS Device * @alias directory.chromeosdevices.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.deviceId Immutable ID of Chrome OS Device * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Chromeosdevices$Get, options?: MethodOptions): GaxiosPromise<Schema$ChromeOsDevice>; get(params: Params$Resource$Chromeosdevices$Get, options: MethodOptions | BodyResponseCallback<Schema$ChromeOsDevice>, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; get(params: Params$Resource$Chromeosdevices$Get, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; get(callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; /** * directory.chromeosdevices.list * @desc Retrieve all Chrome OS Devices of a customer (paginated) * @alias directory.chromeosdevices.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {integer=} params.maxResults Maximum number of results to return. Default is 100 * @param {string=} params.orderBy Column to use for sorting results * @param {string=} params.orgUnitPath Full path of the organizational unit or its ID * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {string=} params.query Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?answer=1698333 * @param {string=} params.sortOrder Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Chromeosdevices$List, options?: MethodOptions): GaxiosPromise<Schema$ChromeOsDevices>; list(params: Params$Resource$Chromeosdevices$List, options: MethodOptions | BodyResponseCallback<Schema$ChromeOsDevices>, callback: BodyResponseCallback<Schema$ChromeOsDevices>): void; list(params: Params$Resource$Chromeosdevices$List, callback: BodyResponseCallback<Schema$ChromeOsDevices>): void; list(callback: BodyResponseCallback<Schema$ChromeOsDevices>): void; /** * directory.chromeosdevices.moveDevicesToOu * @desc Move or insert multiple Chrome OS Devices to organizational unit * @alias directory.chromeosdevices.moveDevicesToOu * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.orgUnitPath Full path of the target organizational unit or its ID * @param {().ChromeOsMoveDevicesToOu} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ moveDevicesToOu(params?: Params$Resource$Chromeosdevices$Movedevicestoou, options?: MethodOptions): GaxiosPromise<void>; moveDevicesToOu(params: Params$Resource$Chromeosdevices$Movedevicestoou, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; moveDevicesToOu(params: Params$Resource$Chromeosdevices$Movedevicestoou, callback: BodyResponseCallback<void>): void; moveDevicesToOu(callback: BodyResponseCallback<void>): void; /** * directory.chromeosdevices.patch * @desc Update Chrome OS Device. This method supports patch semantics. * @alias directory.chromeosdevices.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.deviceId Immutable ID of Chrome OS Device * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {().ChromeOsDevice} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Chromeosdevices$Patch, options?: MethodOptions): GaxiosPromise<Schema$ChromeOsDevice>; patch(params: Params$Resource$Chromeosdevices$Patch, options: MethodOptions | BodyResponseCallback<Schema$ChromeOsDevice>, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; patch(params: Params$Resource$Chromeosdevices$Patch, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; patch(callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; /** * directory.chromeosdevices.update * @desc Update Chrome OS Device * @alias directory.chromeosdevices.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.deviceId Immutable ID of Chrome OS Device * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {().ChromeOsDevice} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Chromeosdevices$Update, options?: MethodOptions): GaxiosPromise<Schema$ChromeOsDevice>; update(params: Params$Resource$Chromeosdevices$Update, options: MethodOptions | BodyResponseCallback<Schema$ChromeOsDevice>, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; update(params: Params$Resource$Chromeosdevices$Update, callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; update(callback: BodyResponseCallback<Schema$ChromeOsDevice>): void; } interface Params$Resource$Chromeosdevices$Action extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Chrome OS Device */ resourceId?: string; /** * Request body metadata */ requestBody?: Schema$ChromeOsDeviceAction; } interface Params$Resource$Chromeosdevices$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Chrome OS Device */ deviceId?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; } interface Params$Resource$Chromeosdevices$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Maximum number of results to return. Default is 100 */ maxResults?: number; /** * Column to use for sorting results */ orderBy?: string; /** * Full path of the organizational unit or its ID */ orgUnitPath?: string; /** * Token to specify next page in the list */ pageToken?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; /** * Search string in the format given at * http://support.google.com/chromeos/a/bin/answer.py?answer=1698333 */ query?: string; /** * Whether to return results in ascending or descending order. Only of use * when orderBy is also used */ sortOrder?: string; } interface Params$Resource$Chromeosdevices$Movedevicestoou extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Full path of the target organizational unit or its ID */ orgUnitPath?: string; /** * Request body metadata */ requestBody?: Schema$ChromeOsMoveDevicesToOu; } interface Params$Resource$Chromeosdevices$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Chrome OS Device */ deviceId?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; /** * Request body metadata */ requestBody?: Schema$ChromeOsDevice; } interface Params$Resource$Chromeosdevices$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Chrome OS Device */ deviceId?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; /** * Request body metadata */ requestBody?: Schema$ChromeOsDevice; } class Resource$Customers { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.customers.get * @desc Retrieves a customer. * @alias directory.customers.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerKey Id of the customer to be retrieved * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Customers$Get, options?: MethodOptions): GaxiosPromise<Schema$Customer>; get(params: Params$Resource$Customers$Get, options: MethodOptions | BodyResponseCallback<Schema$Customer>, callback: BodyResponseCallback<Schema$Customer>): void; get(params: Params$Resource$Customers$Get, callback: BodyResponseCallback<Schema$Customer>): void; get(callback: BodyResponseCallback<Schema$Customer>): void; /** * directory.customers.patch * @desc Updates a customer. This method supports patch semantics. * @alias directory.customers.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerKey Id of the customer to be updated * @param {().Customer} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Customers$Patch, options?: MethodOptions): GaxiosPromise<Schema$Customer>; patch(params: Params$Resource$Customers$Patch, options: MethodOptions | BodyResponseCallback<Schema$Customer>, callback: BodyResponseCallback<Schema$Customer>): void; patch(params: Params$Resource$Customers$Patch, callback: BodyResponseCallback<Schema$Customer>): void; patch(callback: BodyResponseCallback<Schema$Customer>): void; /** * directory.customers.update * @desc Updates a customer. * @alias directory.customers.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerKey Id of the customer to be updated * @param {().Customer} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Customers$Update, options?: MethodOptions): GaxiosPromise<Schema$Customer>; update(params: Params$Resource$Customers$Update, options: MethodOptions | BodyResponseCallback<Schema$Customer>, callback: BodyResponseCallback<Schema$Customer>): void; update(params: Params$Resource$Customers$Update, callback: BodyResponseCallback<Schema$Customer>): void; update(callback: BodyResponseCallback<Schema$Customer>): void; } interface Params$Resource$Customers$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Id of the customer to be retrieved */ customerKey?: string; } interface Params$Resource$Customers$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Id of the customer to be updated */ customerKey?: string; /** * Request body metadata */ requestBody?: Schema$Customer; } interface Params$Resource$Customers$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Id of the customer to be updated */ customerKey?: string; /** * Request body metadata */ requestBody?: Schema$Customer; } class Resource$Domainaliases { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.domainAliases.delete * @desc Deletes a Domain Alias of the customer. * @alias directory.domainAliases.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.domainAliasName Name of domain alias to be retrieved. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Domainaliases$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Domainaliases$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Domainaliases$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.domainAliases.get * @desc Retrieves a domain alias of the customer. * @alias directory.domainAliases.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.domainAliasName Name of domain alias to be retrieved. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Domainaliases$Get, options?: MethodOptions): GaxiosPromise<Schema$DomainAlias>; get(params: Params$Resource$Domainaliases$Get, options: MethodOptions | BodyResponseCallback<Schema$DomainAlias>, callback: BodyResponseCallback<Schema$DomainAlias>): void; get(params: Params$Resource$Domainaliases$Get, callback: BodyResponseCallback<Schema$DomainAlias>): void; get(callback: BodyResponseCallback<Schema$DomainAlias>): void; /** * directory.domainAliases.insert * @desc Inserts a Domain alias of the customer. * @alias directory.domainAliases.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {().DomainAlias} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Domainaliases$Insert, options?: MethodOptions): GaxiosPromise<Schema$DomainAlias>; insert(params: Params$Resource$Domainaliases$Insert, options: MethodOptions | BodyResponseCallback<Schema$DomainAlias>, callback: BodyResponseCallback<Schema$DomainAlias>): void; insert(params: Params$Resource$Domainaliases$Insert, callback: BodyResponseCallback<Schema$DomainAlias>): void; insert(callback: BodyResponseCallback<Schema$DomainAlias>): void; /** * directory.domainAliases.list * @desc Lists the domain aliases of the customer. * @alias directory.domainAliases.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string=} params.parentDomainName Name of the parent domain for which domain aliases are to be fetched. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Domainaliases$List, options?: MethodOptions): GaxiosPromise<Schema$DomainAliases>; list(params: Params$Resource$Domainaliases$List, options: MethodOptions | BodyResponseCallback<Schema$DomainAliases>, callback: BodyResponseCallback<Schema$DomainAliases>): void; list(params: Params$Resource$Domainaliases$List, callback: BodyResponseCallback<Schema$DomainAliases>): void; list(callback: BodyResponseCallback<Schema$DomainAliases>): void; } interface Params$Resource$Domainaliases$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Name of domain alias to be retrieved. */ domainAliasName?: string; } interface Params$Resource$Domainaliases$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Name of domain alias to be retrieved. */ domainAliasName?: string; } interface Params$Resource$Domainaliases$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$DomainAlias; } interface Params$Resource$Domainaliases$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Name of the parent domain for which domain aliases are to be fetched. */ parentDomainName?: string; } class Resource$Domains { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.domains.delete * @desc Deletes a domain of the customer. * @alias directory.domains.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.domainName Name of domain to be deleted * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Domains$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Domains$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Domains$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.domains.get * @desc Retrieves a domain of the customer. * @alias directory.domains.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.domainName Name of domain to be retrieved * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Domains$Get, options?: MethodOptions): GaxiosPromise<Schema$Domains>; get(params: Params$Resource$Domains$Get, options: MethodOptions | BodyResponseCallback<Schema$Domains>, callback: BodyResponseCallback<Schema$Domains>): void; get(params: Params$Resource$Domains$Get, callback: BodyResponseCallback<Schema$Domains>): void; get(callback: BodyResponseCallback<Schema$Domains>): void; /** * directory.domains.insert * @desc Inserts a domain of the customer. * @alias directory.domains.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {().Domains} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Domains$Insert, options?: MethodOptions): GaxiosPromise<Schema$Domains>; insert(params: Params$Resource$Domains$Insert, options: MethodOptions | BodyResponseCallback<Schema$Domains>, callback: BodyResponseCallback<Schema$Domains>): void; insert(params: Params$Resource$Domains$Insert, callback: BodyResponseCallback<Schema$Domains>): void; insert(callback: BodyResponseCallback<Schema$Domains>): void; /** * directory.domains.list * @desc Lists the domains of the customer. * @alias directory.domains.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Domains$List, options?: MethodOptions): GaxiosPromise<Schema$Domains2>; list(params: Params$Resource$Domains$List, options: MethodOptions | BodyResponseCallback<Schema$Domains2>, callback: BodyResponseCallback<Schema$Domains2>): void; list(params: Params$Resource$Domains$List, callback: BodyResponseCallback<Schema$Domains2>): void; list(callback: BodyResponseCallback<Schema$Domains2>): void; } interface Params$Resource$Domains$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Name of domain to be deleted */ domainName?: string; } interface Params$Resource$Domains$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Name of domain to be retrieved */ domainName?: string; } interface Params$Resource$Domains$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Domains; } interface Params$Resource$Domains$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; } class Resource$Groups { context: APIRequestContext; aliases: Resource$Groups$Aliases; constructor(context: APIRequestContext); /** * directory.groups.delete * @desc Delete Group * @alias directory.groups.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Groups$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Groups$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Groups$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.groups.get * @desc Retrieve Group * @alias directory.groups.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Groups$Get, options?: MethodOptions): GaxiosPromise<Schema$Group>; get(params: Params$Resource$Groups$Get, options: MethodOptions | BodyResponseCallback<Schema$Group>, callback: BodyResponseCallback<Schema$Group>): void; get(params: Params$Resource$Groups$Get, callback: BodyResponseCallback<Schema$Group>): void; get(callback: BodyResponseCallback<Schema$Group>): void; /** * directory.groups.insert * @desc Create Group * @alias directory.groups.insert * @memberOf! () * * @param {object} params Parameters for request * @param {().Group} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Groups$Insert, options?: MethodOptions): GaxiosPromise<Schema$Group>; insert(params: Params$Resource$Groups$Insert, options: MethodOptions | BodyResponseCallback<Schema$Group>, callback: BodyResponseCallback<Schema$Group>): void; insert(params: Params$Resource$Groups$Insert, callback: BodyResponseCallback<Schema$Group>): void; insert(callback: BodyResponseCallback<Schema$Group>): void; /** * directory.groups.list * @desc Retrieve all groups of a domain or of a user given a userKey * (paginated) * @alias directory.groups.list * @memberOf! () * * @param {object=} params Parameters for request * @param {string=} params.customer Immutable ID of the G Suite account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain. * @param {string=} params.domain Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead. * @param {integer=} params.maxResults Maximum number of results to return. Default is 200 * @param {string=} params.orderBy Column to use for sorting results * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.query Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-groups * @param {string=} params.sortOrder Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {string=} params.userKey Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Groups$List, options?: MethodOptions): GaxiosPromise<Schema$Groups>; list(params: Params$Resource$Groups$List, options: MethodOptions | BodyResponseCallback<Schema$Groups>, callback: BodyResponseCallback<Schema$Groups>): void; list(params: Params$Resource$Groups$List, callback: BodyResponseCallback<Schema$Groups>): void; list(callback: BodyResponseCallback<Schema$Groups>): void; /** * directory.groups.patch * @desc Update Group. This method supports patch semantics. * @alias directory.groups.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group. If ID, it should match with id of group object * @param {().Group} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Groups$Patch, options?: MethodOptions): GaxiosPromise<Schema$Group>; patch(params: Params$Resource$Groups$Patch, options: MethodOptions | BodyResponseCallback<Schema$Group>, callback: BodyResponseCallback<Schema$Group>): void; patch(params: Params$Resource$Groups$Patch, callback: BodyResponseCallback<Schema$Group>): void; patch(callback: BodyResponseCallback<Schema$Group>): void; /** * directory.groups.update * @desc Update Group * @alias directory.groups.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group. If ID, it should match with id of group object * @param {().Group} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Groups$Update, options?: MethodOptions): GaxiosPromise<Schema$Group>; update(params: Params$Resource$Groups$Update, options: MethodOptions | BodyResponseCallback<Schema$Group>, callback: BodyResponseCallback<Schema$Group>): void; update(params: Params$Resource$Groups$Update, callback: BodyResponseCallback<Schema$Group>): void; update(callback: BodyResponseCallback<Schema$Group>): void; } interface Params$Resource$Groups$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; } interface Params$Resource$Groups$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; } interface Params$Resource$Groups$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$Group; } interface Params$Resource$Groups$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. In case of multi-domain, to fetch * all groups for a customer, fill this field instead of domain. */ customer?: string; /** * Name of the domain. Fill this field to get groups from only this domain. * To return all groups in a multi-domain fill customer field instead. */ domain?: string; /** * Maximum number of results to return. Default is 200 */ maxResults?: number; /** * Column to use for sorting results */ orderBy?: string; /** * Token to specify next page in the list */ pageToken?: string; /** * Query string search. Should be of the form "". Complete documentation is * at * https://developers.google.com/admin-sdk/directory/v1/guides/search-groups */ query?: string; /** * Whether to return results in ascending or descending order. Only of use * when orderBy is also used */ sortOrder?: string; /** * Email or immutable Id of the user if only those groups are to be listed, * the given user is a member of. If Id, it should match with id of user * object */ userKey?: string; } interface Params$Resource$Groups$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group. If ID, it should match with id of * group object */ groupKey?: string; /** * Request body metadata */ requestBody?: Schema$Group; } interface Params$Resource$Groups$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group. If ID, it should match with id of * group object */ groupKey?: string; /** * Request body metadata */ requestBody?: Schema$Group; } class Resource$Groups$Aliases { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.groups.aliases.delete * @desc Remove a alias for the group * @alias directory.groups.aliases.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.alias The alias to be removed * @param {string} params.groupKey Email or immutable ID of the group * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Groups$Aliases$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Groups$Aliases$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Groups$Aliases$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.groups.aliases.insert * @desc Add a alias for the group * @alias directory.groups.aliases.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {().Alias} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Groups$Aliases$Insert, options?: MethodOptions): GaxiosPromise<Schema$Alias>; insert(params: Params$Resource$Groups$Aliases$Insert, options: MethodOptions | BodyResponseCallback<Schema$Alias>, callback: BodyResponseCallback<Schema$Alias>): void; insert(params: Params$Resource$Groups$Aliases$Insert, callback: BodyResponseCallback<Schema$Alias>): void; insert(callback: BodyResponseCallback<Schema$Alias>): void; /** * directory.groups.aliases.list * @desc List all aliases for a group * @alias directory.groups.aliases.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Groups$Aliases$List, options?: MethodOptions): GaxiosPromise<Schema$Aliases>; list(params: Params$Resource$Groups$Aliases$List, options: MethodOptions | BodyResponseCallback<Schema$Aliases>, callback: BodyResponseCallback<Schema$Aliases>): void; list(params: Params$Resource$Groups$Aliases$List, callback: BodyResponseCallback<Schema$Aliases>): void; list(callback: BodyResponseCallback<Schema$Aliases>): void; } interface Params$Resource$Groups$Aliases$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The alias to be removed */ alias?: string; /** * Email or immutable ID of the group */ groupKey?: string; } interface Params$Resource$Groups$Aliases$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; /** * Request body metadata */ requestBody?: Schema$Alias; } interface Params$Resource$Groups$Aliases$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; } class Resource$Members { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.members.delete * @desc Remove membership. * @alias directory.members.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {string} params.memberKey Email or immutable ID of the member * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Members$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Members$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Members$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.members.get * @desc Retrieve Group Member * @alias directory.members.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {string} params.memberKey Email or immutable ID of the member * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Members$Get, options?: MethodOptions): GaxiosPromise<Schema$Member>; get(params: Params$Resource$Members$Get, options: MethodOptions | BodyResponseCallback<Schema$Member>, callback: BodyResponseCallback<Schema$Member>): void; get(params: Params$Resource$Members$Get, callback: BodyResponseCallback<Schema$Member>): void; get(callback: BodyResponseCallback<Schema$Member>): void; /** * directory.members.hasMember * @desc Checks whether the given user is a member of the group. Membership * can be direct or nested. * @alias directory.members.hasMember * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Identifies the group in the API request. The value can be the group's email address, group alias, or the unique group ID. * @param {string} params.memberKey Identifies the user member in the API request. The value can be the user's primary email address, alias, or unique ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ hasMember(params?: Params$Resource$Members$Hasmember, options?: MethodOptions): GaxiosPromise<Schema$MembersHasMember>; hasMember(params: Params$Resource$Members$Hasmember, options: MethodOptions | BodyResponseCallback<Schema$MembersHasMember>, callback: BodyResponseCallback<Schema$MembersHasMember>): void; hasMember(params: Params$Resource$Members$Hasmember, callback: BodyResponseCallback<Schema$MembersHasMember>): void; hasMember(callback: BodyResponseCallback<Schema$MembersHasMember>): void; /** * directory.members.insert * @desc Add user to the specified group. * @alias directory.members.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {().Member} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Members$Insert, options?: MethodOptions): GaxiosPromise<Schema$Member>; insert(params: Params$Resource$Members$Insert, options: MethodOptions | BodyResponseCallback<Schema$Member>, callback: BodyResponseCallback<Schema$Member>): void; insert(params: Params$Resource$Members$Insert, callback: BodyResponseCallback<Schema$Member>): void; insert(callback: BodyResponseCallback<Schema$Member>): void; /** * directory.members.list * @desc Retrieve all members in a group (paginated) * @alias directory.members.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group * @param {boolean=} params.includeDerivedMembership Whether to list indirect memberships. Default: false. * @param {integer=} params.maxResults Maximum number of results to return. Default is 200 * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.roles Comma separated role values to filter list results on. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Members$List, options?: MethodOptions): GaxiosPromise<Schema$Members>; list(params: Params$Resource$Members$List, options: MethodOptions | BodyResponseCallback<Schema$Members>, callback: BodyResponseCallback<Schema$Members>): void; list(params: Params$Resource$Members$List, callback: BodyResponseCallback<Schema$Members>): void; list(callback: BodyResponseCallback<Schema$Members>): void; /** * directory.members.patch * @desc Update membership of a user in the specified group. This method * supports patch semantics. * @alias directory.members.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group. If ID, it should match with id of group object * @param {string} params.memberKey Email or immutable ID of the user. If ID, it should match with id of member object * @param {().Member} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Members$Patch, options?: MethodOptions): GaxiosPromise<Schema$Member>; patch(params: Params$Resource$Members$Patch, options: MethodOptions | BodyResponseCallback<Schema$Member>, callback: BodyResponseCallback<Schema$Member>): void; patch(params: Params$Resource$Members$Patch, callback: BodyResponseCallback<Schema$Member>): void; patch(callback: BodyResponseCallback<Schema$Member>): void; /** * directory.members.update * @desc Update membership of a user in the specified group. * @alias directory.members.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.groupKey Email or immutable ID of the group. If ID, it should match with id of group object * @param {string} params.memberKey Email or immutable ID of the user. If ID, it should match with id of member object * @param {().Member} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Members$Update, options?: MethodOptions): GaxiosPromise<Schema$Member>; update(params: Params$Resource$Members$Update, options: MethodOptions | BodyResponseCallback<Schema$Member>, callback: BodyResponseCallback<Schema$Member>): void; update(params: Params$Resource$Members$Update, callback: BodyResponseCallback<Schema$Member>): void; update(callback: BodyResponseCallback<Schema$Member>): void; } interface Params$Resource$Members$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; /** * Email or immutable ID of the member */ memberKey?: string; } interface Params$Resource$Members$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; /** * Email or immutable ID of the member */ memberKey?: string; } interface Params$Resource$Members$Hasmember extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Identifies the group in the API request. The value can be the group's * email address, group alias, or the unique group ID. */ groupKey?: string; /** * Identifies the user member in the API request. The value can be the * user's primary email address, alias, or unique ID. */ memberKey?: string; } interface Params$Resource$Members$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; /** * Request body metadata */ requestBody?: Schema$Member; } interface Params$Resource$Members$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group */ groupKey?: string; /** * Whether to list indirect memberships. Default: false. */ includeDerivedMembership?: boolean; /** * Maximum number of results to return. Default is 200 */ maxResults?: number; /** * Token to specify next page in the list */ pageToken?: string; /** * Comma separated role values to filter list results on. */ roles?: string; } interface Params$Resource$Members$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group. If ID, it should match with id of * group object */ groupKey?: string; /** * Email or immutable ID of the user. If ID, it should match with id of * member object */ memberKey?: string; /** * Request body metadata */ requestBody?: Schema$Member; } interface Params$Resource$Members$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the group. If ID, it should match with id of * group object */ groupKey?: string; /** * Email or immutable ID of the user. If ID, it should match with id of * member object */ memberKey?: string; /** * Request body metadata */ requestBody?: Schema$Member; } class Resource$Mobiledevices { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.mobiledevices.action * @desc Take action on Mobile Device * @alias directory.mobiledevices.action * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.resourceId Immutable ID of Mobile Device * @param {().MobileDeviceAction} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ action(params?: Params$Resource$Mobiledevices$Action, options?: MethodOptions): GaxiosPromise<void>; action(params: Params$Resource$Mobiledevices$Action, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; action(params: Params$Resource$Mobiledevices$Action, callback: BodyResponseCallback<void>): void; action(callback: BodyResponseCallback<void>): void; /** * directory.mobiledevices.delete * @desc Delete Mobile Device * @alias directory.mobiledevices.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.resourceId Immutable ID of Mobile Device * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Mobiledevices$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Mobiledevices$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Mobiledevices$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.mobiledevices.get * @desc Retrieve Mobile Device * @alias directory.mobiledevices.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {string} params.resourceId Immutable ID of Mobile Device * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Mobiledevices$Get, options?: MethodOptions): GaxiosPromise<Schema$MobileDevice>; get(params: Params$Resource$Mobiledevices$Get, options: MethodOptions | BodyResponseCallback<Schema$MobileDevice>, callback: BodyResponseCallback<Schema$MobileDevice>): void; get(params: Params$Resource$Mobiledevices$Get, callback: BodyResponseCallback<Schema$MobileDevice>): void; get(callback: BodyResponseCallback<Schema$MobileDevice>): void; /** * directory.mobiledevices.list * @desc Retrieve all Mobile Devices of a customer (paginated) * @alias directory.mobiledevices.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {integer=} params.maxResults Maximum number of results to return. Default is 100 * @param {string=} params.orderBy Column to use for sorting results * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.projection Restrict information returned to a set of selected fields. * @param {string=} params.query Search string in the format given at http://support.google.com/a/bin/answer.py?answer=1408863#search * @param {string=} params.sortOrder Whether to return results in ascending or descending order. Only of use when orderBy is also used * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Mobiledevices$List, options?: MethodOptions): GaxiosPromise<Schema$MobileDevices>; list(params: Params$Resource$Mobiledevices$List, options: MethodOptions | BodyResponseCallback<Schema$MobileDevices>, callback: BodyResponseCallback<Schema$MobileDevices>): void; list(params: Params$Resource$Mobiledevices$List, callback: BodyResponseCallback<Schema$MobileDevices>): void; list(callback: BodyResponseCallback<Schema$MobileDevices>): void; } interface Params$Resource$Mobiledevices$Action extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Mobile Device */ resourceId?: string; /** * Request body metadata */ requestBody?: Schema$MobileDeviceAction; } interface Params$Resource$Mobiledevices$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Immutable ID of Mobile Device */ resourceId?: string; } interface Params$Resource$Mobiledevices$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; /** * Immutable ID of Mobile Device */ resourceId?: string; } interface Params$Resource$Mobiledevices$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Maximum number of results to return. Default is 100 */ maxResults?: number; /** * Column to use for sorting results */ orderBy?: string; /** * Token to specify next page in the list */ pageToken?: string; /** * Restrict information returned to a set of selected fields. */ projection?: string; /** * Search string in the format given at * http://support.google.com/a/bin/answer.py?answer=1408863#search */ query?: string; /** * Whether to return results in ascending or descending order. Only of use * when orderBy is also used */ sortOrder?: string; } class Resource$Notifications { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.notifications.delete * @desc Deletes a notification * @alias directory.notifications.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId The unique ID of the notification. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Notifications$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Notifications$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Notifications$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.notifications.get * @desc Retrieves a notification. * @alias directory.notifications.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. The customerId is also returned as part of the Users resource. * @param {string} params.notificationId The unique ID of the notification. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Notifications$Get, options?: MethodOptions): GaxiosPromise<Schema$Notification>; get(params: Params$Resource$Notifications$Get, options: MethodOptions | BodyResponseCallback<Schema$Notification>, callback: BodyResponseCallback<Schema$Notification>): void; get(params: Params$Resource$Notifications$Get, callback: BodyResponseCallback<Schema$Notification>): void; get(callback: BodyResponseCallback<Schema$Notification>): void; /** * directory.notifications.list * @desc Retrieves a list of notifications. * @alias directory.notifications.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. * @param {string=} params.language The ISO 639-1 code of the language notifications are returned in. The default is English (en). * @param {integer=} params.maxResults Maximum number of notifications to return per page. The default is 100. * @param {string=} params.pageToken The token to specify the page of results to retrieve. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Notifications$List, options?: MethodOptions): GaxiosPromise<Schema$Notifications>; list(params: Params$Resource$Notifications$List, options: MethodOptions | BodyResponseCallback<Schema$Notifications>, callback: BodyResponseCallback<Schema$Notifications>): void; list(params: Params$Resource$Notifications$List, callback: BodyResponseCallback<Schema$Notifications>): void; list(callback: BodyResponseCallback<Schema$Notifications>): void; /** * directory.notifications.patch * @desc Updates a notification. This method supports patch semantics. * @alias directory.notifications.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. * @param {string} params.notificationId The unique ID of the notification. * @param {().Notification} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Notifications$Patch, options?: MethodOptions): GaxiosPromise<Schema$Notification>; patch(params: Params$Resource$Notifications$Patch, options: MethodOptions | BodyResponseCallback<Schema$Notification>, callback: BodyResponseCallback<Schema$Notification>): void; patch(params: Params$Resource$Notifications$Patch, callback: BodyResponseCallback<Schema$Notification>): void; patch(callback: BodyResponseCallback<Schema$Notification>): void; /** * directory.notifications.update * @desc Updates a notification. * @alias directory.notifications.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. * @param {string} params.notificationId The unique ID of the notification. * @param {().Notification} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Notifications$Update, options?: MethodOptions): GaxiosPromise<Schema$Notification>; update(params: Params$Resource$Notifications$Update, options: MethodOptions | BodyResponseCallback<Schema$Notification>, callback: BodyResponseCallback<Schema$Notification>): void; update(params: Params$Resource$Notifications$Update, callback: BodyResponseCallback<Schema$Notification>): void; update(callback: BodyResponseCallback<Schema$Notification>): void; } interface Params$Resource$Notifications$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. The customerId is also * returned as part of the Users resource. */ customer?: string; /** * The unique ID of the notification. */ notificationId?: string; } interface Params$Resource$Notifications$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. The customerId is also * returned as part of the Users resource. */ customer?: string; /** * The unique ID of the notification. */ notificationId?: string; } interface Params$Resource$Notifications$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. */ customer?: string; /** * The ISO 639-1 code of the language notifications are returned in. The * default is English (en). */ language?: string; /** * Maximum number of notifications to return per page. The default is 100. */ maxResults?: number; /** * The token to specify the page of results to retrieve. */ pageToken?: string; } interface Params$Resource$Notifications$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. */ customer?: string; /** * The unique ID of the notification. */ notificationId?: string; /** * Request body metadata */ requestBody?: Schema$Notification; } interface Params$Resource$Notifications$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. */ customer?: string; /** * The unique ID of the notification. */ notificationId?: string; /** * Request body metadata */ requestBody?: Schema$Notification; } class Resource$Orgunits { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.orgunits.delete * @desc Remove organizational unit * @alias directory.orgunits.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.orgUnitPath Full path of the organizational unit or its ID * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Orgunits$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Orgunits$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Orgunits$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.orgunits.get * @desc Retrieve organizational unit * @alias directory.orgunits.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.orgUnitPath Full path of the organizational unit or its ID * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Orgunits$Get, options?: MethodOptions): GaxiosPromise<Schema$OrgUnit>; get(params: Params$Resource$Orgunits$Get, options: MethodOptions | BodyResponseCallback<Schema$OrgUnit>, callback: BodyResponseCallback<Schema$OrgUnit>): void; get(params: Params$Resource$Orgunits$Get, callback: BodyResponseCallback<Schema$OrgUnit>): void; get(callback: BodyResponseCallback<Schema$OrgUnit>): void; /** * directory.orgunits.insert * @desc Add organizational unit * @alias directory.orgunits.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {().OrgUnit} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Orgunits$Insert, options?: MethodOptions): GaxiosPromise<Schema$OrgUnit>; insert(params: Params$Resource$Orgunits$Insert, options: MethodOptions | BodyResponseCallback<Schema$OrgUnit>, callback: BodyResponseCallback<Schema$OrgUnit>): void; insert(params: Params$Resource$Orgunits$Insert, callback: BodyResponseCallback<Schema$OrgUnit>): void; insert(callback: BodyResponseCallback<Schema$OrgUnit>): void; /** * directory.orgunits.list * @desc Retrieve all organizational units * @alias directory.orgunits.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string=} params.orgUnitPath the URL-encoded organizational unit's path or its ID * @param {string=} params.type Whether to return all sub-organizations or just immediate children * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Orgunits$List, options?: MethodOptions): GaxiosPromise<Schema$OrgUnits>; list(params: Params$Resource$Orgunits$List, options: MethodOptions | BodyResponseCallback<Schema$OrgUnits>, callback: BodyResponseCallback<Schema$OrgUnits>): void; list(params: Params$Resource$Orgunits$List, callback: BodyResponseCallback<Schema$OrgUnits>): void; list(callback: BodyResponseCallback<Schema$OrgUnits>): void; /** * directory.orgunits.patch * @desc Update organizational unit. This method supports patch semantics. * @alias directory.orgunits.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.orgUnitPath Full path of the organizational unit or its ID * @param {().OrgUnit} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Orgunits$Patch, options?: MethodOptions): GaxiosPromise<Schema$OrgUnit>; patch(params: Params$Resource$Orgunits$Patch, options: MethodOptions | BodyResponseCallback<Schema$OrgUnit>, callback: BodyResponseCallback<Schema$OrgUnit>): void; patch(params: Params$Resource$Orgunits$Patch, callback: BodyResponseCallback<Schema$OrgUnit>): void; patch(callback: BodyResponseCallback<Schema$OrgUnit>): void; /** * directory.orgunits.update * @desc Update organizational unit * @alias directory.orgunits.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.orgUnitPath Full path of the organizational unit or its ID * @param {().OrgUnit} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Orgunits$Update, options?: MethodOptions): GaxiosPromise<Schema$OrgUnit>; update(params: Params$Resource$Orgunits$Update, options: MethodOptions | BodyResponseCallback<Schema$OrgUnit>, callback: BodyResponseCallback<Schema$OrgUnit>): void; update(params: Params$Resource$Orgunits$Update, callback: BodyResponseCallback<Schema$OrgUnit>): void; update(callback: BodyResponseCallback<Schema$OrgUnit>): void; } interface Params$Resource$Orgunits$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Full path of the organizational unit or its ID */ orgUnitPath?: string[]; } interface Params$Resource$Orgunits$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Full path of the organizational unit or its ID */ orgUnitPath?: string[]; } interface Params$Resource$Orgunits$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Request body metadata */ requestBody?: Schema$OrgUnit; } interface Params$Resource$Orgunits$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * the URL-encoded organizational unit's path or its ID */ orgUnitPath?: string; /** * Whether to return all sub-organizations or just immediate children */ type?: string; } interface Params$Resource$Orgunits$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Full path of the organizational unit or its ID */ orgUnitPath?: string[]; /** * Request body metadata */ requestBody?: Schema$OrgUnit; } interface Params$Resource$Orgunits$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Full path of the organizational unit or its ID */ orgUnitPath?: string[]; /** * Request body metadata */ requestBody?: Schema$OrgUnit; } class Resource$Privileges { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.privileges.list * @desc Retrieves a paginated list of all privileges for a customer. * @alias directory.privileges.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Privileges$List, options?: MethodOptions): GaxiosPromise<Schema$Privileges>; list(params: Params$Resource$Privileges$List, options: MethodOptions | BodyResponseCallback<Schema$Privileges>, callback: BodyResponseCallback<Schema$Privileges>): void; list(params: Params$Resource$Privileges$List, callback: BodyResponseCallback<Schema$Privileges>): void; list(callback: BodyResponseCallback<Schema$Privileges>): void; } interface Params$Resource$Privileges$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; } class Resource$Resolvedappaccesssettings { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.resolvedAppAccessSettings.GetSettings * @desc Retrieves resolved app access settings of the logged in user. * @alias directory.resolvedAppAccessSettings.GetSettings * @memberOf! () * * @param {object=} params Parameters for request * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ GetSettings(params?: Params$Resource$Resolvedappaccesssettings$Getsettings, options?: MethodOptions): GaxiosPromise<Schema$AppAccessCollections>; GetSettings(params: Params$Resource$Resolvedappaccesssettings$Getsettings, options: MethodOptions | BodyResponseCallback<Schema$AppAccessCollections>, callback: BodyResponseCallback<Schema$AppAccessCollections>): void; GetSettings(params: Params$Resource$Resolvedappaccesssettings$Getsettings, callback: BodyResponseCallback<Schema$AppAccessCollections>): void; GetSettings(callback: BodyResponseCallback<Schema$AppAccessCollections>): void; /** * directory.resolvedAppAccessSettings.ListTrustedApps * @desc Retrieves the list of apps trusted by the admin of the logged in * user. * @alias directory.resolvedAppAccessSettings.ListTrustedApps * @memberOf! () * * @param {object=} params Parameters for request * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ ListTrustedApps(params?: Params$Resource$Resolvedappaccesssettings$Listtrustedapps, options?: MethodOptions): GaxiosPromise<Schema$TrustedApps>; ListTrustedApps(params: Params$Resource$Resolvedappaccesssettings$Listtrustedapps, options: MethodOptions | BodyResponseCallback<Schema$TrustedApps>, callback: BodyResponseCallback<Schema$TrustedApps>): void; ListTrustedApps(params: Params$Resource$Resolvedappaccesssettings$Listtrustedapps, callback: BodyResponseCallback<Schema$TrustedApps>): void; ListTrustedApps(callback: BodyResponseCallback<Schema$TrustedApps>): void; } interface Params$Resource$Resolvedappaccesssettings$Getsettings extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; } interface Params$Resource$Resolvedappaccesssettings$Listtrustedapps extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; } class Resource$Resources { context: APIRequestContext; buildings: Resource$Resources$Buildings; calendars: Resource$Resources$Calendars; features: Resource$Resources$Features; constructor(context: APIRequestContext); } class Resource$Resources$Buildings { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.resources.buildings.delete * @desc Deletes a building. * @alias directory.resources.buildings.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.buildingId The ID of the building to delete. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Resources$Buildings$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Resources$Buildings$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Resources$Buildings$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.resources.buildings.get * @desc Retrieves a building. * @alias directory.resources.buildings.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.buildingId The unique ID of the building to retrieve. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Resources$Buildings$Get, options?: MethodOptions): GaxiosPromise<Schema$Building>; get(params: Params$Resource$Resources$Buildings$Get, options: MethodOptions | BodyResponseCallback<Schema$Building>, callback: BodyResponseCallback<Schema$Building>): void; get(params: Params$Resource$Resources$Buildings$Get, callback: BodyResponseCallback<Schema$Building>): void; get(callback: BodyResponseCallback<Schema$Building>): void; /** * directory.resources.buildings.insert * @desc Inserts a building. * @alias directory.resources.buildings.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.coordinatesSource Source from which Building.coordinates are derived. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().Building} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Resources$Buildings$Insert, options?: MethodOptions): GaxiosPromise<Schema$Building>; insert(params: Params$Resource$Resources$Buildings$Insert, options: MethodOptions | BodyResponseCallback<Schema$Building>, callback: BodyResponseCallback<Schema$Building>): void; insert(params: Params$Resource$Resources$Buildings$Insert, callback: BodyResponseCallback<Schema$Building>): void; insert(callback: BodyResponseCallback<Schema$Building>): void; /** * directory.resources.buildings.list * @desc Retrieves a list of buildings for an account. * @alias directory.resources.buildings.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {integer=} params.maxResults Maximum number of results to return. * @param {string=} params.pageToken Token to specify the next page in the list. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Resources$Buildings$List, options?: MethodOptions): GaxiosPromise<Schema$Buildings>; list(params: Params$Resource$Resources$Buildings$List, options: MethodOptions | BodyResponseCallback<Schema$Buildings>, callback: BodyResponseCallback<Schema$Buildings>): void; list(params: Params$Resource$Resources$Buildings$List, callback: BodyResponseCallback<Schema$Buildings>): void; list(callback: BodyResponseCallback<Schema$Buildings>): void; /** * directory.resources.buildings.patch * @desc Updates a building. This method supports patch semantics. * @alias directory.resources.buildings.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.buildingId The ID of the building to update. * @param {string=} params.coordinatesSource Source from which Building.coordinates are derived. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().Building} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Resources$Buildings$Patch, options?: MethodOptions): GaxiosPromise<Schema$Building>; patch(params: Params$Resource$Resources$Buildings$Patch, options: MethodOptions | BodyResponseCallback<Schema$Building>, callback: BodyResponseCallback<Schema$Building>): void; patch(params: Params$Resource$Resources$Buildings$Patch, callback: BodyResponseCallback<Schema$Building>): void; patch(callback: BodyResponseCallback<Schema$Building>): void; /** * directory.resources.buildings.update * @desc Updates a building. * @alias directory.resources.buildings.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.buildingId The ID of the building to update. * @param {string=} params.coordinatesSource Source from which Building.coordinates are derived. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().Building} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Resources$Buildings$Update, options?: MethodOptions): GaxiosPromise<Schema$Building>; update(params: Params$Resource$Resources$Buildings$Update, options: MethodOptions | BodyResponseCallback<Schema$Building>, callback: BodyResponseCallback<Schema$Building>): void; update(params: Params$Resource$Resources$Buildings$Update, callback: BodyResponseCallback<Schema$Building>): void; update(callback: BodyResponseCallback<Schema$Building>): void; } interface Params$Resource$Resources$Buildings$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the building to delete. */ buildingId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; } interface Params$Resource$Resources$Buildings$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the building to retrieve. */ buildingId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; } interface Params$Resource$Resources$Buildings$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Source from which Building.coordinates are derived. */ coordinatesSource?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Building; } interface Params$Resource$Resources$Buildings$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Maximum number of results to return. */ maxResults?: number; /** * Token to specify the next page in the list. */ pageToken?: string; } interface Params$Resource$Resources$Buildings$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the building to update. */ buildingId?: string; /** * Source from which Building.coordinates are derived. */ coordinatesSource?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Building; } interface Params$Resource$Resources$Buildings$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The ID of the building to update. */ buildingId?: string; /** * Source from which Building.coordinates are derived. */ coordinatesSource?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Building; } class Resource$Resources$Calendars { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.resources.calendars.delete * @desc Deletes a calendar resource. * @alias directory.resources.calendars.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.calendarResourceId The unique ID of the calendar resource to delete. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Resources$Calendars$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Resources$Calendars$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Resources$Calendars$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.resources.calendars.get * @desc Retrieves a calendar resource. * @alias directory.resources.calendars.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.calendarResourceId The unique ID of the calendar resource to retrieve. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Resources$Calendars$Get, options?: MethodOptions): GaxiosPromise<Schema$CalendarResource>; get(params: Params$Resource$Resources$Calendars$Get, options: MethodOptions | BodyResponseCallback<Schema$CalendarResource>, callback: BodyResponseCallback<Schema$CalendarResource>): void; get(params: Params$Resource$Resources$Calendars$Get, callback: BodyResponseCallback<Schema$CalendarResource>): void; get(callback: BodyResponseCallback<Schema$CalendarResource>): void; /** * directory.resources.calendars.insert * @desc Inserts a calendar resource. * @alias directory.resources.calendars.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().CalendarResource} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Resources$Calendars$Insert, options?: MethodOptions): GaxiosPromise<Schema$CalendarResource>; insert(params: Params$Resource$Resources$Calendars$Insert, options: MethodOptions | BodyResponseCallback<Schema$CalendarResource>, callback: BodyResponseCallback<Schema$CalendarResource>): void; insert(params: Params$Resource$Resources$Calendars$Insert, callback: BodyResponseCallback<Schema$CalendarResource>): void; insert(callback: BodyResponseCallback<Schema$CalendarResource>): void; /** * directory.resources.calendars.list * @desc Retrieves a list of calendar resources for an account. * @alias directory.resources.calendars.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {integer=} params.maxResults Maximum number of results to return. * @param {string=} params.orderBy Field(s) to sort results by in either ascending or descending order. Supported fields include resourceId, resourceName, capacity, buildingId, and floorName. If no order is specified, defaults to ascending. Should be of the form "field [asc|desc], field [asc|desc], ...". For example buildingId, capacity desc would return results sorted first by buildingId in ascending order then by capacity in descending order. * @param {string=} params.pageToken Token to specify the next page in the list. * @param {string=} params.query String query used to filter results. Should be of the form "field operator value" where field can be any of supported fields and operators can be any of supported operations. Operators include '=' for exact match and ':' for prefix match or HAS match where applicable. For prefix match, the value should always be followed by a *. Supported fields include generatedResourceName, name, buildingId, featureInstances.feature.name. For example buildingId=US-NYC-9TH AND featureInstances.feature.name:Phone. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Resources$Calendars$List, options?: MethodOptions): GaxiosPromise<Schema$CalendarResources>; list(params: Params$Resource$Resources$Calendars$List, options: MethodOptions | BodyResponseCallback<Schema$CalendarResources>, callback: BodyResponseCallback<Schema$CalendarResources>): void; list(params: Params$Resource$Resources$Calendars$List, callback: BodyResponseCallback<Schema$CalendarResources>): void; list(callback: BodyResponseCallback<Schema$CalendarResources>): void; /** * directory.resources.calendars.patch * @desc Updates a calendar resource. This method supports patch semantics, * meaning you only need to include the fields you wish to update. Fields * that are not present in the request will be preserved. This method * supports patch semantics. * @alias directory.resources.calendars.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.calendarResourceId The unique ID of the calendar resource to update. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().CalendarResource} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Resources$Calendars$Patch, options?: MethodOptions): GaxiosPromise<Schema$CalendarResource>; patch(params: Params$Resource$Resources$Calendars$Patch, options: MethodOptions | BodyResponseCallback<Schema$CalendarResource>, callback: BodyResponseCallback<Schema$CalendarResource>): void; patch(params: Params$Resource$Resources$Calendars$Patch, callback: BodyResponseCallback<Schema$CalendarResource>): void; patch(callback: BodyResponseCallback<Schema$CalendarResource>): void; /** * directory.resources.calendars.update * @desc Updates a calendar resource. This method supports patch semantics, * meaning you only need to include the fields you wish to update. Fields * that are not present in the request will be preserved. * @alias directory.resources.calendars.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.calendarResourceId The unique ID of the calendar resource to update. * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().CalendarResource} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Resources$Calendars$Update, options?: MethodOptions): GaxiosPromise<Schema$CalendarResource>; update(params: Params$Resource$Resources$Calendars$Update, options: MethodOptions | BodyResponseCallback<Schema$CalendarResource>, callback: BodyResponseCallback<Schema$CalendarResource>): void; update(params: Params$Resource$Resources$Calendars$Update, callback: BodyResponseCallback<Schema$CalendarResource>): void; update(callback: BodyResponseCallback<Schema$CalendarResource>): void; } interface Params$Resource$Resources$Calendars$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the calendar resource to delete. */ calendarResourceId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; } interface Params$Resource$Resources$Calendars$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the calendar resource to retrieve. */ calendarResourceId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; } interface Params$Resource$Resources$Calendars$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$CalendarResource; } interface Params$Resource$Resources$Calendars$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Maximum number of results to return. */ maxResults?: number; /** * Field(s) to sort results by in either ascending or descending order. * Supported fields include resourceId, resourceName, capacity, buildingId, * and floorName. If no order is specified, defaults to ascending. Should be * of the form "field [asc|desc], field [asc|desc], ...". For example * buildingId, capacity desc would return results sorted first by buildingId * in ascending order then by capacity in descending order. */ orderBy?: string; /** * Token to specify the next page in the list. */ pageToken?: string; /** * String query used to filter results. Should be of the form "field * operator value" where field can be any of supported fields and operators * can be any of supported operations. Operators include '=' for exact match * and ':' for prefix match or HAS match where applicable. For prefix match, * the value should always be followed by a *. Supported fields include * generatedResourceName, name, buildingId, featureInstances.feature.name. * For example buildingId=US-NYC-9TH AND * featureInstances.feature.name:Phone. */ query?: string; } interface Params$Resource$Resources$Calendars$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the calendar resource to update. */ calendarResourceId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$CalendarResource; } interface Params$Resource$Resources$Calendars$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID of the calendar resource to update. */ calendarResourceId?: string; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$CalendarResource; } class Resource$Resources$Features { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.resources.features.delete * @desc Deletes a feature. * @alias directory.resources.features.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {string} params.featureKey The unique ID of the feature to delete. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Resources$Features$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Resources$Features$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Resources$Features$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.resources.features.get * @desc Retrieves a feature. * @alias directory.resources.features.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {string} params.featureKey The unique ID of the feature to retrieve. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Resources$Features$Get, options?: MethodOptions): GaxiosPromise<Schema$Feature>; get(params: Params$Resource$Resources$Features$Get, options: MethodOptions | BodyResponseCallback<Schema$Feature>, callback: BodyResponseCallback<Schema$Feature>): void; get(params: Params$Resource$Resources$Features$Get, callback: BodyResponseCallback<Schema$Feature>): void; get(callback: BodyResponseCallback<Schema$Feature>): void; /** * directory.resources.features.insert * @desc Inserts a feature. * @alias directory.resources.features.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {().Feature} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Resources$Features$Insert, options?: MethodOptions): GaxiosPromise<Schema$Feature>; insert(params: Params$Resource$Resources$Features$Insert, options: MethodOptions | BodyResponseCallback<Schema$Feature>, callback: BodyResponseCallback<Schema$Feature>): void; insert(params: Params$Resource$Resources$Features$Insert, callback: BodyResponseCallback<Schema$Feature>): void; insert(callback: BodyResponseCallback<Schema$Feature>): void; /** * directory.resources.features.list * @desc Retrieves a list of features for an account. * @alias directory.resources.features.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {integer=} params.maxResults Maximum number of results to return. * @param {string=} params.pageToken Token to specify the next page in the list. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Resources$Features$List, options?: MethodOptions): GaxiosPromise<Schema$Features>; list(params: Params$Resource$Resources$Features$List, options: MethodOptions | BodyResponseCallback<Schema$Features>, callback: BodyResponseCallback<Schema$Features>): void; list(params: Params$Resource$Resources$Features$List, callback: BodyResponseCallback<Schema$Features>): void; list(callback: BodyResponseCallback<Schema$Features>): void; /** * directory.resources.features.patch * @desc Updates a feature. This method supports patch semantics. * @alias directory.resources.features.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {string} params.featureKey The unique ID of the feature to update. * @param {().Feature} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Resources$Features$Patch, options?: MethodOptions): GaxiosPromise<Schema$Feature>; patch(params: Params$Resource$Resources$Features$Patch, options: MethodOptions | BodyResponseCallback<Schema$Feature>, callback: BodyResponseCallback<Schema$Feature>): void; patch(params: Params$Resource$Resources$Features$Patch, callback: BodyResponseCallback<Schema$Feature>): void; patch(callback: BodyResponseCallback<Schema$Feature>): void; /** * directory.resources.features.rename * @desc Renames a feature. * @alias directory.resources.features.rename * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {string} params.oldName The unique ID of the feature to rename. * @param {().FeatureRename} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ rename(params?: Params$Resource$Resources$Features$Rename, options?: MethodOptions): GaxiosPromise<void>; rename(params: Params$Resource$Resources$Features$Rename, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; rename(params: Params$Resource$Resources$Features$Rename, callback: BodyResponseCallback<void>): void; rename(callback: BodyResponseCallback<void>): void; /** * directory.resources.features.update * @desc Updates a feature. * @alias directory.resources.features.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer The unique ID for the customer's G Suite account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID. * @param {string} params.featureKey The unique ID of the feature to update. * @param {().Feature} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Resources$Features$Update, options?: MethodOptions): GaxiosPromise<Schema$Feature>; update(params: Params$Resource$Resources$Features$Update, options: MethodOptions | BodyResponseCallback<Schema$Feature>, callback: BodyResponseCallback<Schema$Feature>): void; update(params: Params$Resource$Resources$Features$Update, callback: BodyResponseCallback<Schema$Feature>): void; update(callback: BodyResponseCallback<Schema$Feature>): void; } interface Params$Resource$Resources$Features$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * The unique ID of the feature to delete. */ featureKey?: string; } interface Params$Resource$Resources$Features$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * The unique ID of the feature to retrieve. */ featureKey?: string; } interface Params$Resource$Resources$Features$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Feature; } interface Params$Resource$Resources$Features$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * Maximum number of results to return. */ maxResults?: number; /** * Token to specify the next page in the list. */ pageToken?: string; } interface Params$Resource$Resources$Features$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * The unique ID of the feature to update. */ featureKey?: string; /** * Request body metadata */ requestBody?: Schema$Feature; } interface Params$Resource$Resources$Features$Rename extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * The unique ID of the feature to rename. */ oldName?: string; /** * Request body metadata */ requestBody?: Schema$FeatureRename; } interface Params$Resource$Resources$Features$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The unique ID for the customer's G Suite account. As an account * administrator, you can also use the my_customer alias to represent your * account's customer ID. */ customer?: string; /** * The unique ID of the feature to update. */ featureKey?: string; /** * Request body metadata */ requestBody?: Schema$Feature; } class Resource$Roleassignments { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.roleAssignments.delete * @desc Deletes a role assignment. * @alias directory.roleAssignments.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleAssignmentId Immutable ID of the role assignment. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Roleassignments$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Roleassignments$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Roleassignments$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.roleAssignments.get * @desc Retrieve a role assignment. * @alias directory.roleAssignments.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleAssignmentId Immutable ID of the role assignment. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Roleassignments$Get, options?: MethodOptions): GaxiosPromise<Schema$RoleAssignment>; get(params: Params$Resource$Roleassignments$Get, options: MethodOptions | BodyResponseCallback<Schema$RoleAssignment>, callback: BodyResponseCallback<Schema$RoleAssignment>): void; get(params: Params$Resource$Roleassignments$Get, callback: BodyResponseCallback<Schema$RoleAssignment>): void; get(callback: BodyResponseCallback<Schema$RoleAssignment>): void; /** * directory.roleAssignments.insert * @desc Creates a role assignment. * @alias directory.roleAssignments.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {().RoleAssignment} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Roleassignments$Insert, options?: MethodOptions): GaxiosPromise<Schema$RoleAssignment>; insert(params: Params$Resource$Roleassignments$Insert, options: MethodOptions | BodyResponseCallback<Schema$RoleAssignment>, callback: BodyResponseCallback<Schema$RoleAssignment>): void; insert(params: Params$Resource$Roleassignments$Insert, callback: BodyResponseCallback<Schema$RoleAssignment>): void; insert(callback: BodyResponseCallback<Schema$RoleAssignment>): void; /** * directory.roleAssignments.list * @desc Retrieves a paginated list of all roleAssignments. * @alias directory.roleAssignments.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {integer=} params.maxResults Maximum number of results to return. * @param {string=} params.pageToken Token to specify the next page in the list. * @param {string=} params.roleId Immutable ID of a role. If included in the request, returns only role assignments containing this role ID. * @param {string=} params.userKey The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Roleassignments$List, options?: MethodOptions): GaxiosPromise<Schema$RoleAssignments>; list(params: Params$Resource$Roleassignments$List, options: MethodOptions | BodyResponseCallback<Schema$RoleAssignments>, callback: BodyResponseCallback<Schema$RoleAssignments>): void; list(params: Params$Resource$Roleassignments$List, callback: BodyResponseCallback<Schema$RoleAssignments>): void; list(callback: BodyResponseCallback<Schema$RoleAssignments>): void; } interface Params$Resource$Roleassignments$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role assignment. */ roleAssignmentId?: string; } interface Params$Resource$Roleassignments$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role assignment. */ roleAssignmentId?: string; } interface Params$Resource$Roleassignments$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$RoleAssignment; } interface Params$Resource$Roleassignments$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Maximum number of results to return. */ maxResults?: number; /** * Token to specify the next page in the list. */ pageToken?: string; /** * Immutable ID of a role. If included in the request, returns only role * assignments containing this role ID. */ roleId?: string; /** * The user's primary email address, alias email address, or unique user ID. * If included in the request, returns role assignments only for this user. */ userKey?: string; } class Resource$Roles { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.roles.delete * @desc Deletes a role. * @alias directory.roles.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleId Immutable ID of the role. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Roles$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Roles$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Roles$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.roles.get * @desc Retrieves a role. * @alias directory.roles.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleId Immutable ID of the role. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Roles$Get, options?: MethodOptions): GaxiosPromise<Schema$Role>; get(params: Params$Resource$Roles$Get, options: MethodOptions | BodyResponseCallback<Schema$Role>, callback: BodyResponseCallback<Schema$Role>): void; get(params: Params$Resource$Roles$Get, callback: BodyResponseCallback<Schema$Role>): void; get(callback: BodyResponseCallback<Schema$Role>): void; /** * directory.roles.insert * @desc Creates a role. * @alias directory.roles.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {().Role} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Roles$Insert, options?: MethodOptions): GaxiosPromise<Schema$Role>; insert(params: Params$Resource$Roles$Insert, options: MethodOptions | BodyResponseCallback<Schema$Role>, callback: BodyResponseCallback<Schema$Role>): void; insert(params: Params$Resource$Roles$Insert, callback: BodyResponseCallback<Schema$Role>): void; insert(callback: BodyResponseCallback<Schema$Role>): void; /** * directory.roles.list * @desc Retrieves a paginated list of all the roles in a domain. * @alias directory.roles.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {integer=} params.maxResults Maximum number of results to return. * @param {string=} params.pageToken Token to specify the next page in the list. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Roles$List, options?: MethodOptions): GaxiosPromise<Schema$Roles>; list(params: Params$Resource$Roles$List, options: MethodOptions | BodyResponseCallback<Schema$Roles>, callback: BodyResponseCallback<Schema$Roles>): void; list(params: Params$Resource$Roles$List, callback: BodyResponseCallback<Schema$Roles>): void; list(callback: BodyResponseCallback<Schema$Roles>): void; /** * directory.roles.patch * @desc Updates a role. This method supports patch semantics. * @alias directory.roles.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleId Immutable ID of the role. * @param {().Role} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Roles$Patch, options?: MethodOptions): GaxiosPromise<Schema$Role>; patch(params: Params$Resource$Roles$Patch, options: MethodOptions | BodyResponseCallback<Schema$Role>, callback: BodyResponseCallback<Schema$Role>): void; patch(params: Params$Resource$Roles$Patch, callback: BodyResponseCallback<Schema$Role>): void; patch(callback: BodyResponseCallback<Schema$Role>): void; /** * directory.roles.update * @desc Updates a role. * @alias directory.roles.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customer Immutable ID of the G Suite account. * @param {string} params.roleId Immutable ID of the role. * @param {().Role} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Roles$Update, options?: MethodOptions): GaxiosPromise<Schema$Role>; update(params: Params$Resource$Roles$Update, options: MethodOptions | BodyResponseCallback<Schema$Role>, callback: BodyResponseCallback<Schema$Role>): void; update(params: Params$Resource$Roles$Update, callback: BodyResponseCallback<Schema$Role>): void; update(callback: BodyResponseCallback<Schema$Role>): void; } interface Params$Resource$Roles$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role. */ roleId?: string; } interface Params$Resource$Roles$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role. */ roleId?: string; } interface Params$Resource$Roles$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Request body metadata */ requestBody?: Schema$Role; } interface Params$Resource$Roles$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Maximum number of results to return. */ maxResults?: number; /** * Token to specify the next page in the list. */ pageToken?: string; } interface Params$Resource$Roles$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role. */ roleId?: string; /** * Request body metadata */ requestBody?: Schema$Role; } interface Params$Resource$Roles$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. */ customer?: string; /** * Immutable ID of the role. */ roleId?: string; /** * Request body metadata */ requestBody?: Schema$Role; } class Resource$Schemas { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.schemas.delete * @desc Delete schema * @alias directory.schemas.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.schemaKey Name or immutable ID of the schema * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Schemas$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Schemas$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Schemas$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.schemas.get * @desc Retrieve schema * @alias directory.schemas.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.schemaKey Name or immutable ID of the schema * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Schemas$Get, options?: MethodOptions): GaxiosPromise<Schema$Schema>; get(params: Params$Resource$Schemas$Get, options: MethodOptions | BodyResponseCallback<Schema$Schema>, callback: BodyResponseCallback<Schema$Schema>): void; get(params: Params$Resource$Schemas$Get, callback: BodyResponseCallback<Schema$Schema>): void; get(callback: BodyResponseCallback<Schema$Schema>): void; /** * directory.schemas.insert * @desc Create schema. * @alias directory.schemas.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {().Schema} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Schemas$Insert, options?: MethodOptions): GaxiosPromise<Schema$Schema>; insert(params: Params$Resource$Schemas$Insert, options: MethodOptions | BodyResponseCallback<Schema$Schema>, callback: BodyResponseCallback<Schema$Schema>): void; insert(params: Params$Resource$Schemas$Insert, callback: BodyResponseCallback<Schema$Schema>): void; insert(callback: BodyResponseCallback<Schema$Schema>): void; /** * directory.schemas.list * @desc Retrieve all schemas for a customer * @alias directory.schemas.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Schemas$List, options?: MethodOptions): GaxiosPromise<Schema$Schemas>; list(params: Params$Resource$Schemas$List, options: MethodOptions | BodyResponseCallback<Schema$Schemas>, callback: BodyResponseCallback<Schema$Schemas>): void; list(params: Params$Resource$Schemas$List, callback: BodyResponseCallback<Schema$Schemas>): void; list(callback: BodyResponseCallback<Schema$Schemas>): void; /** * directory.schemas.patch * @desc Update schema. This method supports patch semantics. * @alias directory.schemas.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.schemaKey Name or immutable ID of the schema. * @param {().Schema} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Schemas$Patch, options?: MethodOptions): GaxiosPromise<Schema$Schema>; patch(params: Params$Resource$Schemas$Patch, options: MethodOptions | BodyResponseCallback<Schema$Schema>, callback: BodyResponseCallback<Schema$Schema>): void; patch(params: Params$Resource$Schemas$Patch, callback: BodyResponseCallback<Schema$Schema>): void; patch(callback: BodyResponseCallback<Schema$Schema>): void; /** * directory.schemas.update * @desc Update schema * @alias directory.schemas.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.customerId Immutable ID of the G Suite account * @param {string} params.schemaKey Name or immutable ID of the schema. * @param {().Schema} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Schemas$Update, options?: MethodOptions): GaxiosPromise<Schema$Schema>; update(params: Params$Resource$Schemas$Update, options: MethodOptions | BodyResponseCallback<Schema$Schema>, callback: BodyResponseCallback<Schema$Schema>): void; update(params: Params$Resource$Schemas$Update, callback: BodyResponseCallback<Schema$Schema>): void; update(callback: BodyResponseCallback<Schema$Schema>): void; } interface Params$Resource$Schemas$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Name or immutable ID of the schema */ schemaKey?: string; } interface Params$Resource$Schemas$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Name or immutable ID of the schema */ schemaKey?: string; } interface Params$Resource$Schemas$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Request body metadata */ requestBody?: Schema$Schema; } interface Params$Resource$Schemas$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; } interface Params$Resource$Schemas$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Name or immutable ID of the schema. */ schemaKey?: string; /** * Request body metadata */ requestBody?: Schema$Schema; } interface Params$Resource$Schemas$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account */ customerId?: string; /** * Name or immutable ID of the schema. */ schemaKey?: string; /** * Request body metadata */ requestBody?: Schema$Schema; } class Resource$Tokens { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.tokens.delete * @desc Delete all access tokens issued by a user for an application. * @alias directory.tokens.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.clientId The Client ID of the application the token is issued to. * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Tokens$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Tokens$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Tokens$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.tokens.get * @desc Get information about an access token issued by a user. * @alias directory.tokens.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.clientId The Client ID of the application the token is issued to. * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Tokens$Get, options?: MethodOptions): GaxiosPromise<Schema$Token>; get(params: Params$Resource$Tokens$Get, options: MethodOptions | BodyResponseCallback<Schema$Token>, callback: BodyResponseCallback<Schema$Token>): void; get(params: Params$Resource$Tokens$Get, callback: BodyResponseCallback<Schema$Token>): void; get(callback: BodyResponseCallback<Schema$Token>): void; /** * directory.tokens.list * @desc Returns the set of tokens specified user has issued to 3rd party * applications. * @alias directory.tokens.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Tokens$List, options?: MethodOptions): GaxiosPromise<Schema$Tokens>; list(params: Params$Resource$Tokens$List, options: MethodOptions | BodyResponseCallback<Schema$Tokens>, callback: BodyResponseCallback<Schema$Tokens>): void; list(params: Params$Resource$Tokens$List, callback: BodyResponseCallback<Schema$Tokens>): void; list(callback: BodyResponseCallback<Schema$Tokens>): void; } interface Params$Resource$Tokens$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The Client ID of the application the token is issued to. */ clientId?: string; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } interface Params$Resource$Tokens$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The Client ID of the application the token is issued to. */ clientId?: string; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } interface Params$Resource$Tokens$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } class Resource$Users { context: APIRequestContext; aliases: Resource$Users$Aliases; photos: Resource$Users$Photos; constructor(context: APIRequestContext); /** * directory.users.delete * @desc Delete user * @alias directory.users.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Users$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Users$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Users$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.users.get * @desc retrieve user * @alias directory.users.get * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.customFieldMask Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.projection What subset of fields to fetch for this user. * @param {string} params.userKey Email or immutable ID of the user * @param {string=} params.viewType Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Users$Get, options?: MethodOptions): GaxiosPromise<Schema$User>; get(params: Params$Resource$Users$Get, options: MethodOptions | BodyResponseCallback<Schema$User>, callback: BodyResponseCallback<Schema$User>): void; get(params: Params$Resource$Users$Get, callback: BodyResponseCallback<Schema$User>): void; get(callback: BodyResponseCallback<Schema$User>): void; /** * directory.users.insert * @desc create user. * @alias directory.users.insert * @memberOf! () * * @param {object} params Parameters for request * @param {().User} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Users$Insert, options?: MethodOptions): GaxiosPromise<Schema$User>; insert(params: Params$Resource$Users$Insert, options: MethodOptions | BodyResponseCallback<Schema$User>, callback: BodyResponseCallback<Schema$User>): void; insert(params: Params$Resource$Users$Insert, callback: BodyResponseCallback<Schema$User>): void; insert(callback: BodyResponseCallback<Schema$User>): void; /** * directory.users.list * @desc Retrieve either deleted users or all users in a domain (paginated) * @alias directory.users.list * @memberOf! () * * @param {object=} params Parameters for request * @param {string=} params.customer Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.customFieldMask Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.domain Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy Column to use for sorting results * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.projection What subset of fields to fetch for this user. * @param {string=} params.query Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder Whether to return results in ascending or descending order. * @param {string=} params.viewType Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Users$List, options?: MethodOptions): GaxiosPromise<Schema$Users>; list(params: Params$Resource$Users$List, options: MethodOptions | BodyResponseCallback<Schema$Users>, callback: BodyResponseCallback<Schema$Users>): void; list(params: Params$Resource$Users$List, callback: BodyResponseCallback<Schema$Users>): void; list(callback: BodyResponseCallback<Schema$Users>): void; /** * directory.users.makeAdmin * @desc change admin status of a user * @alias directory.users.makeAdmin * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user as admin * @param {().UserMakeAdmin} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ makeAdmin(params?: Params$Resource$Users$Makeadmin, options?: MethodOptions): GaxiosPromise<void>; makeAdmin(params: Params$Resource$Users$Makeadmin, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; makeAdmin(params: Params$Resource$Users$Makeadmin, callback: BodyResponseCallback<void>): void; makeAdmin(callback: BodyResponseCallback<void>): void; /** * directory.users.patch * @desc update user. This method supports patch semantics. * @alias directory.users.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user. If ID, it should match with id of user object * @param {().User} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Users$Patch, options?: MethodOptions): GaxiosPromise<Schema$User>; patch(params: Params$Resource$Users$Patch, options: MethodOptions | BodyResponseCallback<Schema$User>, callback: BodyResponseCallback<Schema$User>): void; patch(params: Params$Resource$Users$Patch, callback: BodyResponseCallback<Schema$User>): void; patch(callback: BodyResponseCallback<Schema$User>): void; /** * directory.users.undelete * @desc Undelete a deleted user * @alias directory.users.undelete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey The immutable id of the user * @param {().UserUndelete} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ undelete(params?: Params$Resource$Users$Undelete, options?: MethodOptions): GaxiosPromise<void>; undelete(params: Params$Resource$Users$Undelete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; undelete(params: Params$Resource$Users$Undelete, callback: BodyResponseCallback<void>): void; undelete(callback: BodyResponseCallback<void>): void; /** * directory.users.update * @desc update user * @alias directory.users.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user. If ID, it should match with id of user object * @param {().User} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Users$Update, options?: MethodOptions): GaxiosPromise<Schema$User>; update(params: Params$Resource$Users$Update, options: MethodOptions | BodyResponseCallback<Schema$User>, callback: BodyResponseCallback<Schema$User>): void; update(params: Params$Resource$Users$Update, callback: BodyResponseCallback<Schema$User>): void; update(callback: BodyResponseCallback<Schema$User>): void; /** * directory.users.watch * @desc Watch for changes in users list * @alias directory.users.watch * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.customer Immutable ID of the G Suite account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain. * @param {string=} params.customFieldMask Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom. * @param {string=} params.domain Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead. * @param {string=} params.event Event on which subscription is intended (if subscribing) * @param {integer=} params.maxResults Maximum number of results to return. Default is 100. Max allowed is 500 * @param {string=} params.orderBy Column to use for sorting results * @param {string=} params.pageToken Token to specify next page in the list * @param {string=} params.projection What subset of fields to fetch for this user. * @param {string=} params.query Query string search. Should be of the form "". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users * @param {string=} params.showDeleted If set to true retrieves the list of deleted users. Default is false * @param {string=} params.sortOrder Whether to return results in ascending or descending order. * @param {string=} params.viewType Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. * @param {().Channel} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ watch(params?: Params$Resource$Users$Watch, options?: MethodOptions): GaxiosPromise<Schema$Channel>; watch(params: Params$Resource$Users$Watch, options: MethodOptions | BodyResponseCallback<Schema$Channel>, callback: BodyResponseCallback<Schema$Channel>): void; watch(params: Params$Resource$Users$Watch, callback: BodyResponseCallback<Schema$Channel>): void; watch(callback: BodyResponseCallback<Schema$Channel>): void; } interface Params$Resource$Users$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Users$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Comma-separated list of schema names. All fields from these schemas are * fetched. This should only be set when projection=custom. */ customFieldMask?: string; /** * What subset of fields to fetch for this user. */ projection?: string; /** * Email or immutable ID of the user */ userKey?: string; /** * Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. */ viewType?: string; } interface Params$Resource$Users$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Request body metadata */ requestBody?: Schema$User; } interface Params$Resource$Users$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. In case of multi-domain, to fetch * all users for a customer, fill this field instead of domain. */ customer?: string; /** * Comma-separated list of schema names. All fields from these schemas are * fetched. This should only be set when projection=custom. */ customFieldMask?: string; /** * Name of the domain. Fill this field to get users from only this domain. * To return all users in a multi-domain fill customer field instead. */ domain?: string; /** * Event on which subscription is intended (if subscribing) */ event?: string; /** * Maximum number of results to return. Default is 100. Max allowed is 500 */ maxResults?: number; /** * Column to use for sorting results */ orderBy?: string; /** * Token to specify next page in the list */ pageToken?: string; /** * What subset of fields to fetch for this user. */ projection?: string; /** * Query string search. Should be of the form "". Complete documentation is * at * https://developers.google.com/admin-sdk/directory/v1/guides/search-users */ query?: string; /** * If set to true retrieves the list of deleted users. Default is false */ showDeleted?: string; /** * Whether to return results in ascending or descending order. */ sortOrder?: string; /** * Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. */ viewType?: string; } interface Params$Resource$Users$Makeadmin extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user as admin */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$UserMakeAdmin; } interface Params$Resource$Users$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user. If ID, it should match with id of user * object */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$User; } interface Params$Resource$Users$Undelete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The immutable id of the user */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$UserUndelete; } interface Params$Resource$Users$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user. If ID, it should match with id of user * object */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$User; } interface Params$Resource$Users$Watch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Immutable ID of the G Suite account. In case of multi-domain, to fetch * all users for a customer, fill this field instead of domain. */ customer?: string; /** * Comma-separated list of schema names. All fields from these schemas are * fetched. This should only be set when projection=custom. */ customFieldMask?: string; /** * Name of the domain. Fill this field to get users from only this domain. * To return all users in a multi-domain fill customer field instead. */ domain?: string; /** * Event on which subscription is intended (if subscribing) */ event?: string; /** * Maximum number of results to return. Default is 100. Max allowed is 500 */ maxResults?: number; /** * Column to use for sorting results */ orderBy?: string; /** * Token to specify next page in the list */ pageToken?: string; /** * What subset of fields to fetch for this user. */ projection?: string; /** * Query string search. Should be of the form "". Complete documentation is * at * https://developers.google.com/admin-sdk/directory/v1/guides/search-users */ query?: string; /** * If set to true retrieves the list of deleted users. Default is false */ showDeleted?: string; /** * Whether to return results in ascending or descending order. */ sortOrder?: string; /** * Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user. */ viewType?: string; /** * Request body metadata */ requestBody?: Schema$Channel; } class Resource$Users$Aliases { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.users.aliases.delete * @desc Remove a alias for the user * @alias directory.users.aliases.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.alias The alias to be removed * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Users$Aliases$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Users$Aliases$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Users$Aliases$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.users.aliases.insert * @desc Add a alias for the user * @alias directory.users.aliases.insert * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {().Alias} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ insert(params?: Params$Resource$Users$Aliases$Insert, options?: MethodOptions): GaxiosPromise<Schema$Alias>; insert(params: Params$Resource$Users$Aliases$Insert, options: MethodOptions | BodyResponseCallback<Schema$Alias>, callback: BodyResponseCallback<Schema$Alias>): void; insert(params: Params$Resource$Users$Aliases$Insert, callback: BodyResponseCallback<Schema$Alias>): void; insert(callback: BodyResponseCallback<Schema$Alias>): void; /** * directory.users.aliases.list * @desc List all aliases for a user * @alias directory.users.aliases.list * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.event Event on which subscription is intended (if subscribing) * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Users$Aliases$List, options?: MethodOptions): GaxiosPromise<Schema$Aliases>; list(params: Params$Resource$Users$Aliases$List, options: MethodOptions | BodyResponseCallback<Schema$Aliases>, callback: BodyResponseCallback<Schema$Aliases>): void; list(params: Params$Resource$Users$Aliases$List, callback: BodyResponseCallback<Schema$Aliases>): void; list(callback: BodyResponseCallback<Schema$Aliases>): void; /** * directory.users.aliases.watch * @desc Watch for changes in user aliases list * @alias directory.users.aliases.watch * @memberOf! () * * @param {object} params Parameters for request * @param {string=} params.event Event on which subscription is intended (if subscribing) * @param {string} params.userKey Email or immutable ID of the user * @param {().Channel} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ watch(params?: Params$Resource$Users$Aliases$Watch, options?: MethodOptions): GaxiosPromise<Schema$Channel>; watch(params: Params$Resource$Users$Aliases$Watch, options: MethodOptions | BodyResponseCallback<Schema$Channel>, callback: BodyResponseCallback<Schema$Channel>): void; watch(params: Params$Resource$Users$Aliases$Watch, callback: BodyResponseCallback<Schema$Channel>): void; watch(callback: BodyResponseCallback<Schema$Channel>): void; } interface Params$Resource$Users$Aliases$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * The alias to be removed */ alias?: string; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Users$Aliases$Insert extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$Alias; } interface Params$Resource$Users$Aliases$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Event on which subscription is intended (if subscribing) */ event?: string; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Users$Aliases$Watch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Event on which subscription is intended (if subscribing) */ event?: string; /** * Email or immutable ID of the user */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$Channel; } class Resource$Users$Photos { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.users.photos.delete * @desc Remove photos for the user * @alias directory.users.photos.delete * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ delete(params?: Params$Resource$Users$Photos$Delete, options?: MethodOptions): GaxiosPromise<void>; delete(params: Params$Resource$Users$Photos$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; delete(params: Params$Resource$Users$Photos$Delete, callback: BodyResponseCallback<void>): void; delete(callback: BodyResponseCallback<void>): void; /** * directory.users.photos.get * @desc Retrieve photo of a user * @alias directory.users.photos.get * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ get(params?: Params$Resource$Users$Photos$Get, options?: MethodOptions): GaxiosPromise<Schema$UserPhoto>; get(params: Params$Resource$Users$Photos$Get, options: MethodOptions | BodyResponseCallback<Schema$UserPhoto>, callback: BodyResponseCallback<Schema$UserPhoto>): void; get(params: Params$Resource$Users$Photos$Get, callback: BodyResponseCallback<Schema$UserPhoto>): void; get(callback: BodyResponseCallback<Schema$UserPhoto>): void; /** * directory.users.photos.patch * @desc Add a photo for the user. This method supports patch semantics. * @alias directory.users.photos.patch * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {().UserPhoto} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ patch(params?: Params$Resource$Users$Photos$Patch, options?: MethodOptions): GaxiosPromise<Schema$UserPhoto>; patch(params: Params$Resource$Users$Photos$Patch, options: MethodOptions | BodyResponseCallback<Schema$UserPhoto>, callback: BodyResponseCallback<Schema$UserPhoto>): void; patch(params: Params$Resource$Users$Photos$Patch, callback: BodyResponseCallback<Schema$UserPhoto>): void; patch(callback: BodyResponseCallback<Schema$UserPhoto>): void; /** * directory.users.photos.update * @desc Add a photo for the user * @alias directory.users.photos.update * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {().UserPhoto} params.resource Request body data * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ update(params?: Params$Resource$Users$Photos$Update, options?: MethodOptions): GaxiosPromise<Schema$UserPhoto>; update(params: Params$Resource$Users$Photos$Update, options: MethodOptions | BodyResponseCallback<Schema$UserPhoto>, callback: BodyResponseCallback<Schema$UserPhoto>): void; update(params: Params$Resource$Users$Photos$Update, callback: BodyResponseCallback<Schema$UserPhoto>): void; update(callback: BodyResponseCallback<Schema$UserPhoto>): void; } interface Params$Resource$Users$Photos$Delete extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Users$Photos$Get extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Users$Photos$Patch extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$UserPhoto; } interface Params$Resource$Users$Photos$Update extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; /** * Request body metadata */ requestBody?: Schema$UserPhoto; } class Resource$Verificationcodes { context: APIRequestContext; constructor(context: APIRequestContext); /** * directory.verificationCodes.generate * @desc Generate new backup verification codes for the user. * @alias directory.verificationCodes.generate * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ generate(params?: Params$Resource$Verificationcodes$Generate, options?: MethodOptions): GaxiosPromise<void>; generate(params: Params$Resource$Verificationcodes$Generate, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; generate(params: Params$Resource$Verificationcodes$Generate, callback: BodyResponseCallback<void>): void; generate(callback: BodyResponseCallback<void>): void; /** * directory.verificationCodes.invalidate * @desc Invalidate the current backup verification codes for the user. * @alias directory.verificationCodes.invalidate * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Email or immutable ID of the user * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ invalidate(params?: Params$Resource$Verificationcodes$Invalidate, options?: MethodOptions): GaxiosPromise<void>; invalidate(params: Params$Resource$Verificationcodes$Invalidate, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void; invalidate(params: Params$Resource$Verificationcodes$Invalidate, callback: BodyResponseCallback<void>): void; invalidate(callback: BodyResponseCallback<void>): void; /** * directory.verificationCodes.list * @desc Returns the current set of valid backup verification codes for the * specified user. * @alias directory.verificationCodes.list * @memberOf! () * * @param {object} params Parameters for request * @param {string} params.userKey Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID. * @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`. * @param {callback} callback The callback that handles the response. * @return {object} Request object */ list(params?: Params$Resource$Verificationcodes$List, options?: MethodOptions): GaxiosPromise<Schema$VerificationCodes>; list(params: Params$Resource$Verificationcodes$List, options: MethodOptions | BodyResponseCallback<Schema$VerificationCodes>, callback: BodyResponseCallback<Schema$VerificationCodes>): void; list(params: Params$Resource$Verificationcodes$List, callback: BodyResponseCallback<Schema$VerificationCodes>): void; list(callback: BodyResponseCallback<Schema$VerificationCodes>): void; } interface Params$Resource$Verificationcodes$Generate extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Verificationcodes$Invalidate extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Email or immutable ID of the user */ userKey?: string; } interface Params$Resource$Verificationcodes$List extends StandardParameters { /** * Auth client or API Key for the request */ auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient; /** * Identifies the user in the API request. The value can be the user's * primary email address, alias email address, or unique user ID. */ userKey?: string; } }
the_stack
import assert = require("assert"); import { AppSoftmaxRegressionSparse } from "../../../../../../src/model/supervised/classifier/neural_network/learner/AppSoftmaxRegressionSparse"; import { SoftmaxRegressionSparse } from "../../../../../../src/model/supervised/classifier/neural_network/learner/SoftmaxRegressionSparse"; import { NgramSubwordFeaturizer } from "../../../../../../src/model/language_understanding/featurizer/NgramSubwordFeaturizer"; // import { LearnerUtility } // from "../../../../../../src/model/supervised/classifier/neural_network/learner/UtilityLearner"; import { Utility } from "../../../../../../src/utility/Utility"; import { UnitTestHelper } from "../../../../../utility/Utility.test"; function getFeaturizerAndLearner(): { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse } { const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); // const featurizer: NgramSubwordFeaturizer = // result.featurizer; // const learner: SoftmaxRegressionSparse = // result.learner; return result; } describe("Test Suite - model/supervised/classifier/neural_network/learner/softmax_regression_sparse", () => { it("Test.0000 constructor()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); // const featurizer: NgramSubwordFeaturizer = // result.featurizer; // const learner: SoftmaxRegressionSparse = // result.learner; }); it("Test.0100 getModelWeights()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const modelWeights: number[][] = learner.getModelWeights(); const numberOutputUnits: number = learner.getNumberOutputUnits(); const numberInputUnits: number = learner.getNumberInputUnits(); assert.ok(modelWeights.length === numberOutputUnits, `modelWeights.length=${modelWeights.length}` + `, numberOutputUnits=${numberOutputUnits}`); assert.ok(modelWeights[0].length === numberInputUnits, `modelWeights[0].length=${modelWeights[0].length}` + `, numberInputUnits=${numberInputUnits}`); }); it("Test.0101 getModelBiases()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const modelBiases: number[] = learner.getModelBiases(); const numberOutputUnits: number = learner.getNumberOutputUnits(); assert.ok(modelBiases.length === numberOutputUnits, `modelBiases.length=${modelBiases.length}` + `, numberOutputUnits=${numberOutputUnits}`); }); it("Test.0200 getNumberInputUnits()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const numberLabels: number = featurizer.getNumberLabels(); const numberFeatures: number = featurizer.getNumberFeatures(); const numberOutputUnits: number = learner.getNumberOutputUnits(); const numberInputUnits: number = learner.getNumberInputUnits(); assert.ok(numberLabels === numberOutputUnits, `numberLabels=${numberLabels}` + `, numberOutputUnits=${numberOutputUnits}`); assert.ok(numberFeatures === numberInputUnits, `numberFeatures=${numberFeatures}` + `, numberInputUnits=${numberInputUnits}`); }); it("Test.0201 getNumberOutputUnits()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const numberLabels: number = featurizer.getNumberLabels(); const numberFeatures: number = featurizer.getNumberFeatures(); const numberOutputUnits: number = learner.getNumberOutputUnits(); const numberInputUnits: number = learner.getNumberInputUnits(); assert.ok(numberLabels === numberOutputUnits, `numberLabels=${numberLabels}` + `, numberOutputUnits=${numberOutputUnits}`); assert.ok(numberFeatures === numberInputUnits, `numberFeatures=${numberFeatures}` + `, numberInputUnits=${numberInputUnits}`); }); it("Test.0300 getL1Regularization()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const l1Regularization: number = learner.getL1Regularization(); Utility.debuggingLog( `l1Regularization=${l1Regularization}`); }); it("Test.0301 getL2Regularization()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const l2Regularization: number = learner.getL2Regularization(); Utility.debuggingLog( `l2Regularization=${l2Regularization}`); }); it("Test.0400 getLossEarlyStopRatio()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = getFeaturizerAndLearner(); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const lossEarlyStopRatio: number = learner.getLossEarlyStopRatio(); Utility.debuggingLog( `lossEarlyStopRatio=${lossEarlyStopRatio}`); }); it("Test.0500 fit()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, 0, // ---- AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); // const featurizer: NgramSubwordFeaturizer = // result.featurizer; // const learner: SoftmaxRegressionSparse = // result.learner; }); it("Test.0600 fitMinibatching()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); // const featurizer: NgramSubwordFeaturizer = // result.featurizer; // const learner: SoftmaxRegressionSparse = // result.learner; }); it("Test.0700 predict()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, 0, // ---- AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); // const featurizer: NgramSubwordFeaturizer = // result.featurizer; // const learner: SoftmaxRegressionSparse = // result.learner; }); it("Test.0800 serializeToJsonString()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, 0, // ---- AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const serialized: string = learner.serializeToJsonString(undefined, 4); Utility.debuggingLog( `serialized=${serialized}`); }); it("Test.0900 deserializeFromJsonString()", function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const result: { "featurizer": NgramSubwordFeaturizer, "learner": SoftmaxRegressionSparse, } = AppSoftmaxRegressionSparse.exampleFunctionSoftmaxRegressionSparseMinibatching( "resources/data/Columnar/Email.tsv", "resources/data/Columnar/EmailTest.tsv", 0, 2, 1, 100, 0, // ---- AppSoftmaxRegressionSparse.defaultMiniBatchSize, 0.00, 0.00); const featurizer: NgramSubwordFeaturizer = result.featurizer; const learner: SoftmaxRegressionSparse = result.learner; const serializedJsonString: string = learner.serializeToJsonString(undefined, 4); Utility.debuggingLog( `serializedJsonString=${serializedJsonString}`); const numberFeatures: number = featurizer.getNumberFeatures(); // ==== featurizer.getNumberHashingFeatures(); const numberLabels: number = featurizer.getNumberLabels(); const numberInputUnits: number = numberFeatures; const numberOutputUnits: number = numberLabels; const learnerDeserialized: SoftmaxRegressionSparse = new SoftmaxRegressionSparse( numberInputUnits, numberOutputUnits, learner.getL1Regularization(), learner.getL2Regularization(), learner.getLossEarlyStopRatio()); learnerDeserialized.deserializeFromJsonString(serializedJsonString); const modelBiases: number[] = learner.getModelBiases(); const modelBiasesDeserialized: number[] = learnerDeserialized.getModelBiases(); assert.ok(modelBiases.length === modelBiasesDeserialized.length, `modelBiases.length=${modelBiases.length}` + `, modelBiasesDeserialized.length=${modelBiasesDeserialized.length}`); assert.ok(modelBiases[0] === modelBiasesDeserialized[0], `modelBiases[0]=${modelBiases[0]}` + `, modelBiasesDeserialized[0]=${modelBiasesDeserialized[0]}`); const modelWeights: number[][] = learner.getModelWeights(); const modelWeightsDeserialized: number[][] = learnerDeserialized.getModelWeights(); assert.ok(modelWeights.length === modelWeightsDeserialized.length, `modelWeights.length=${modelWeights.length}` + `, modelWeightsDeserialized.length=${modelWeightsDeserialized.length}`); assert.ok(modelWeights[0][0] === modelWeightsDeserialized[0][0], `modelWeights[0][0]=${modelWeights[0][0]}` + `, modelWeightsDeserialized[0][0]=${modelWeightsDeserialized[0][0]}`); }); });
the_stack
import { DialogOptions, ConfirmOptions, PromptOptions, PromptResult, LoginOptions, LoginResult, ActionOptions } from './dialogs-common'; import { getLabelColor, getButtonColors, isDialogOptions, inputType, capitalizationType, DialogStrings, parseLoginOptions } from './dialogs-common'; import { android as androidApp } from '../../application'; export * from './dialogs-common'; function isString(value): value is string { return typeof value === 'string'; } function createAlertDialog(options?: DialogOptions): android.app.AlertDialog.Builder { const alert = new android.app.AlertDialog.Builder(androidApp.foregroundActivity, options.theme ? options.theme : -1); alert.setTitle(options && isString(options.title) ? options.title : ''); alert.setMessage(options && isString(options.message) ? options.message : ''); if (options && options.cancelable === false) { alert.setCancelable(false); } return alert; } function showDialog(builder: android.app.AlertDialog.Builder) { const dlg = builder.show(); const labelColor = getLabelColor(); if (labelColor) { const textViewId = dlg.getContext().getResources().getIdentifier('android:id/alertTitle', null, null); if (textViewId) { const tv = <android.widget.TextView>dlg.findViewById(textViewId); if (tv) { tv.setTextColor(labelColor.android); } } const messageTextViewId = dlg.getContext().getResources().getIdentifier('android:id/message', null, null); if (messageTextViewId) { const messageTextView = <android.widget.TextView>dlg.findViewById(messageTextViewId); if (messageTextView) { messageTextView.setTextColor(labelColor.android); } } } const { color, backgroundColor } = getButtonColors(); if (color) { const buttons: android.widget.Button[] = []; for (let i = 0; i < 3; i++) { const id = dlg .getContext() .getResources() .getIdentifier('android:id/button' + i, null, null); buttons[i] = <android.widget.Button>dlg.findViewById(id); } buttons.forEach((button) => { if (button) { if (color) { button.setTextColor(color.android); } if (backgroundColor) { button.setBackgroundColor(backgroundColor.android); } } }); } } function addButtonsToAlertDialog(alert: android.app.AlertDialog.Builder, options: ConfirmOptions, callback: Function): void { if (!options) { return; } if (options.okButtonText) { alert.setPositiveButton( options.okButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, id: number) { dialog.cancel(); callback(true); }, }) ); } if (options.cancelButtonText) { alert.setNegativeButton( options.cancelButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, id: number) { dialog.cancel(); callback(false); }, }) ); } if (options.neutralButtonText) { alert.setNeutralButton( options.neutralButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, id: number) { dialog.cancel(); callback(undefined); }, }) ); } alert.setOnDismissListener( new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { callback(false); }, }) ); } export function alert(arg: any): Promise<void> { return new Promise<void>((resolve, reject) => { try { const options = !isDialogOptions(arg) ? { title: DialogStrings.ALERT, okButtonText: DialogStrings.OK, message: arg + '' } : arg; const alert = createAlertDialog(options); alert.setPositiveButton( options.okButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, id: number) { dialog.cancel(); resolve(); }, }) ); alert.setOnDismissListener( new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { resolve(); }, }) ); showDialog(alert); } catch (ex) { reject(ex); } }); } export function confirm(arg: any): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { try { const options = !isDialogOptions(arg) ? { title: DialogStrings.CONFIRM, okButtonText: DialogStrings.OK, cancelButtonText: DialogStrings.CANCEL, message: arg + '', } : arg; const alert = createAlertDialog(options); addButtonsToAlertDialog(alert, options, function (result) { resolve(result); }); showDialog(alert); } catch (ex) { reject(ex); } }); } export function prompt(...args): Promise<PromptResult> { let options: PromptOptions; const defaultOptions = { title: DialogStrings.PROMPT, okButtonText: DialogStrings.OK, cancelButtonText: DialogStrings.CANCEL, inputType: inputType.text, }; const arg = args[0]; if (args.length === 1) { if (isString(arg)) { options = defaultOptions; options.message = arg; } else { options = arg; } } else if (args.length === 2) { if (isString(arg) && isString(args[1])) { options = defaultOptions; options.message = arg; options.defaultText = args[1]; } } return new Promise<PromptResult>((resolve, reject) => { try { const alert = createAlertDialog(options); const input = new android.widget.EditText(androidApp.foregroundActivity); if (options) { if (options.inputType === inputType.password) { input.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); } else if (options.inputType === inputType.email) { input.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS); } else if (options.inputType === inputType.number) { input.setInputType(android.text.InputType.TYPE_CLASS_NUMBER); } else if (options.inputType === inputType.decimal) { input.setInputType(android.text.InputType.TYPE_CLASS_NUMBER | android.text.InputType.TYPE_NUMBER_FLAG_DECIMAL); } else if (options.inputType === inputType.phone) { input.setInputType(android.text.InputType.TYPE_CLASS_PHONE); } switch (options.capitalizationType) { case capitalizationType.all: { input.setInputType(input.getInputType() | android.text.InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS); break; } case capitalizationType.sentences: { input.setInputType(input.getInputType() | android.text.InputType.TYPE_TEXT_FLAG_CAP_SENTENCES); break; } case capitalizationType.words: { input.setInputType(input.getInputType() | android.text.InputType.TYPE_TEXT_FLAG_CAP_WORDS); break; } } } input.setText((options && options.defaultText) || ''); alert.setView(input); const getText = function () { return input.getText().toString(); }; addButtonsToAlertDialog(alert, options, function (r) { resolve({ result: r, text: getText() }); }); showDialog(alert); } catch (ex) { reject(ex); } }); } export function login(...args: any[]): Promise<LoginResult> { const options: LoginOptions = parseLoginOptions(args); return new Promise<LoginResult>((resolve, reject) => { try { const context = androidApp.foregroundActivity; const alert = createAlertDialog(options); const userNameInput = new android.widget.EditText(context); userNameInput.setHint(options.userNameHint ? options.userNameHint : ''); userNameInput.setText(options.userName ? options.userName : ''); const passwordInput = new android.widget.EditText(context); passwordInput.setInputType(android.text.InputType.TYPE_CLASS_TEXT | android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD); passwordInput.setTypeface(android.graphics.Typeface.DEFAULT); passwordInput.setHint(options.passwordHint ? options.passwordHint : ''); passwordInput.setText(options.password ? options.password : ''); const layout = new android.widget.LinearLayout(context); layout.setOrientation(1); layout.addView(userNameInput); layout.addView(passwordInput); alert.setView(layout); addButtonsToAlertDialog(alert, options, function (r) { resolve({ result: r, userName: userNameInput.getText().toString(), password: passwordInput.getText().toString(), }); }); showDialog(alert); } catch (ex) { reject(ex); } }); } export function action(...args): Promise<string> { let options: ActionOptions; const defaultOptions = { title: null, cancelButtonText: DialogStrings.CANCEL }; if (args.length === 1) { if (isString(args[0])) { options = defaultOptions; options.message = args[0]; } else { options = args[0]; } } else if (args.length === 2) { if (isString(args[0]) && isString(args[1])) { options = defaultOptions; options.message = args[0]; options.cancelButtonText = args[1]; } } else if (args.length === 3) { if (isString(args[0]) && isString(args[1]) && typeof args[2] !== 'undefined') { options = defaultOptions; options.message = args[0]; options.cancelButtonText = args[1]; options.actions = args[2]; } } return new Promise<string>((resolve, reject) => { try { const activity = androidApp.foregroundActivity || androidApp.startActivity; const alert = new android.app.AlertDialog.Builder(activity, options.theme ? options.theme : -1); const message = options && isString(options.message) ? options.message : ''; const title = options && isString(options.title) ? options.title : ''; if (options && options.cancelable === false) { alert.setCancelable(false); } if (title) { alert.setTitle(title); if (!options.actions) { alert.setMessage(message); } } else { alert.setTitle(message); } if (options.actions) { alert.setItems( options.actions, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, which: number) { resolve(options.actions[which]); }, }) ); } if (isString(options.cancelButtonText)) { alert.setNegativeButton( options.cancelButtonText, new android.content.DialogInterface.OnClickListener({ onClick: function (dialog: android.content.DialogInterface, id: number) { dialog.cancel(); resolve(options.cancelButtonText); }, }) ); } alert.setOnDismissListener( new android.content.DialogInterface.OnDismissListener({ onDismiss: function () { if (isString(options.cancelButtonText)) { resolve(options.cancelButtonText); } else { resolve(''); } }, }) ); showDialog(alert); } catch (ex) { reject(ex); } }); } /** * Singular rollup for convenience of all dialog methods */ export const Dialogs = { alert, confirm, prompt, login, action, };
the_stack
import {BoundingBox, CollisionGrid} from './label'; import {DataSet, Mode, OnHoverListener, OnSelectionListener, Point3D, Scatter} from './scatter'; import {shuffle} from './util'; const FONT_SIZE = 10; // Colors (in various necessary formats). const BACKGROUND_COLOR_DAY = 0xffffff; const BACKGROUND_COLOR_NIGHT = 0x000000; const AXIS_COLOR = 0xb3b3b3; const LABEL_COLOR_DAY = 0x000000; const LABEL_COLOR_NIGHT = 0xffffff; const LABEL_STROKE_DAY = 0xffffff; const LABEL_STROKE_NIGHT = 0x000000; const POINT_COLOR = 0x7575D9; const POINT_COLOR_GRAYED = 0x888888; const BLENDING_DAY = THREE.MultiplyBlending; const BLENDING_NIGHT = THREE.AdditiveBlending; const TRACE_START_HUE = 60; const TRACE_END_HUE = 360; const TRACE_SATURATION = 1; const TRACE_LIGHTNESS = .3; const TRACE_DEFAULT_OPACITY = .2; const TRACE_DEFAULT_LINEWIDTH = 2; const TRACE_SELECTED_OPACITY = .9; const TRACE_SELECTED_LINEWIDTH = 3; const TRACE_DESELECTED_OPACITY = .05; // Various distance bounds. const MAX_ZOOM = 10; const MIN_ZOOM = .05; const NUM_POINTS_FOG_THRESHOLD = 5000; const MIN_POINT_SIZE = 5.0; const IMAGE_SIZE = 30; // Constants relating to the camera parameters. /** Camera frustum vertical field of view. */ const FOV = 70; const NEAR = 0.01; const FAR = 100; // Constants relating to the indices of buffer arrays. /** Item size of a single point in a bufferArray representing colors */ const RGB_NUM_BYTES = 3; /** Item size of a single point in a bufferArray representing indices */ const INDEX_NUM_BYTES = 1; /** Item size of a single point in a bufferArray representing locations */ const XYZ_NUM_BYTES = 3; // Key presses. const SHIFT_KEY = 16; const CTRL_KEY = 17; // Original positions of camera and camera target, in 2d and 3d const POS_3D = { x: 1.5, y: 1.5, z: 1.5 }; // Target for the camera in 3D is the center of the 1, 1, 1 square, as all our // data is scaled to this. const TAR_3D = { x: 0, y: 0, z: 0 }; const POS_2D = { x: 0, y: 0, z: 2 }; // In 3D, the target is the center of the xy plane. const TAR_2D = { x: 0, y: 0, z: 0 }; // The maximum number of labels to draw to keep the frame rate up. const SAMPLE_SIZE = 10000; // Shaders for images. const VERTEX_SHADER = ` // Index of the specific vertex (passed in as bufferAttribute), and the // variable that will be used to pass it to the fragment shader. attribute float vertexIndex; varying vec2 xyIndex; // Similar to above, but for colors. attribute vec3 color; varying vec3 vColor; // If the point is highlighted, this will be 1.0 (else 0.0). attribute float isHighlight; // Uniform passed in as a property from THREE.ShaderMaterial. uniform bool sizeAttenuation; uniform float pointSize; uniform float imageWidth; uniform float imageHeight; void main() { // Pass index and color values to fragment shader. vColor = color; xyIndex = vec2(mod(vertexIndex, imageWidth), floor(vertexIndex / imageWidth)); // Transform current vertex by modelViewMatrix (model world position and // camera world position matrix). vec4 mvPosition = modelViewMatrix * vec4(position, 1.0); // Project vertex in camera-space to screen coordinates using the camera's // projection matrix. gl_Position = projectionMatrix * mvPosition; // Create size attenuation (if we're in 3D mode) by making the size of // each point inversly proportional to its distance to the camera. float attenuatedSize = - pointSize / mvPosition.z; gl_PointSize = sizeAttenuation ? attenuatedSize : pointSize; // If the point is a highlight, make it slightly bigger than the other // points, and also don't let it get smaller than some threshold. if (isHighlight == 1.0) { gl_PointSize = max(gl_PointSize * 1.2, ${MIN_POINT_SIZE.toFixed(1)}); }; }`; const FRAGMENT_SHADER = ` // Values passed in from the vertex shader. varying vec2 xyIndex; varying vec3 vColor; // Adding in the THREEjs shader chunks for fog. ${THREE.ShaderChunk['common']} ${THREE.ShaderChunk['fog_pars_fragment']} // Uniforms passed in as properties from THREE.ShaderMaterial. uniform sampler2D texture; uniform float imageWidth; uniform float imageHeight; uniform bool isImage; void main() { // A mystery variable that is required to make the THREE shaderchunk for fog // work correctly. vec3 outgoingLight = vec3(0.0); if (isImage) { // Coordinates of the vertex within the entire sprite image. vec2 coords = (gl_PointCoord + xyIndex) / vec2(imageWidth, imageHeight); // Determine the color of the spritesheet at the calculate spot. vec4 fromTexture = texture2D(texture, coords); // Finally, set the fragment color. gl_FragColor = vec4(vColor, 1.0) * fromTexture; } else { // Discard pixels outside the radius so points are rendered as circles. vec2 uv = gl_PointCoord.xy - 0.5; if (length(uv) > 0.5) discard; // If the point is not an image, just color it. gl_FragColor = vec4(vColor, 1.0); } ${THREE.ShaderChunk['fog_fragment']} }`; export class ScatterWebGL implements Scatter { // MISC UNINITIALIZED VARIABLES. // Colors and options that are changed between Day and Night modes. private backgroundColor: number; private labelColor: number; private labelStroke: number; private blending: THREE.Blending; private isNight: boolean; // THREE.js necessities. private scene: THREE.Scene; private perspCamera: THREE.PerspectiveCamera; private renderer: THREE.WebGLRenderer; private cameraControls: any; private light: THREE.PointLight; private fog: THREE.Fog; // Data structures (and THREE.js objects) associated with points. private geometry: THREE.BufferGeometry; /** Texture for rendering offscreen in order to enable interactive hover. */ private pickingTexture: THREE.WebGLRenderTarget; /** Array of unique colors for each point used in detecting hover. */ private uniqueColArr: Float32Array; private materialOptions: THREE.ShaderMaterialParameters; private points: THREE.Points; private traces: THREE.Line[]; private dataSet: DataSet; private shuffledData: number[]; /** Holds the indexes of the points to be labeled. */ private labeledPoints: number[] = []; private highlightedPoints: number[] = []; private nearestPoint: number; private pointSize2D: number; private pointSize3D: number; /** The buffer attribute that holds the positions of the points. */ private positionBufferArray: THREE.BufferAttribute; // Accessors for rendering and labeling the points. private xAccessor: (index: number) => number; private yAccessor: (index: number) => number; private zAccessor: (index: number) => number; private labelAccessor: (index: number) => string; private colorAccessor: (index: number) => string; private highlightStroke: (i: number) => string; private favorLabels: (i: number) => boolean; // Scaling functions for each axis. private xScale: d3.scale.Linear<number, number>; private yScale: d3.scale.Linear<number, number>; private zScale: d3.scale.Linear<number, number>; // Listeners private onHoverListeners: OnHoverListener[] = []; private onSelectionListeners: OnSelectionListener[] = []; private lazySusanAnimation: number; // Other variables associated with layout and interaction. private height: number; private width: number; private mode: Mode; /** Whether the user has turned labels on or off. */ private labelsAreOn = true; /** Whether the label canvas has been already cleared. */ private labelCanvasIsCleared = true; private animating: boolean; private axis3D: THREE.AxisHelper; private axis2D: THREE.LineSegments; private dpr: number; // The device pixelratio private selecting = false; // whether or not we are selecting points. private mouseIsDown = false; // Whether the current click sequence contains a drag, so we can determine // whether to update the selection. private isDragSequence = false; private selectionSphere: THREE.Mesh; private image: HTMLImageElement; private animationID: number; /** Color of any point not selected (or NN of selected) */ private defaultPointColor = POINT_COLOR; // HTML elements. private gc: CanvasRenderingContext2D; private containerNode: HTMLElement; private canvas: HTMLCanvasElement; /** Get things started up! */ constructor( container: d3.Selection<any>, labelAccessor: (index: number) => string) { this.labelAccessor = labelAccessor; this.xScale = d3.scale.linear(); this.yScale = d3.scale.linear(); this.zScale = d3.scale.linear(); // Set up non-THREEjs layout. this.containerNode = container.node() as HTMLElement; this.getLayoutValues(); // For now, labels are drawn on this transparent canvas with no touch events // rather than being rendered in webGL. this.canvas = container.append('canvas').node() as HTMLCanvasElement; this.gc = this.canvas.getContext('2d'); d3.select(this.canvas).style({position: 'absolute', left: 0, top: 0}); this.canvas.style.pointerEvents = 'none'; // Set up THREE.js. this.createSceneAndRenderer(); this.setDayNightMode(false); this.createLight(); this.makeCamera(); this.resize(false); // Render now so no black background appears during startup. this.renderer.render(this.scene, this.perspCamera); // Add interaction listeners. this.addInteractionListeners(); } // SET UP private addInteractionListeners() { this.containerNode.addEventListener( 'mousemove', this.onMouseMove.bind(this)); this.containerNode.addEventListener( 'mousedown', this.onMouseDown.bind(this)); this.containerNode.addEventListener('mouseup', this.onMouseUp.bind(this)); this.containerNode.addEventListener('click', this.onClick.bind(this)); window.addEventListener('keydown', this.onKeyDown.bind(this), false); window.addEventListener('keyup', this.onKeyUp.bind(this), false); } /** Updates the positions buffer array to reflect the actual data. */ private updatePositionsArray() { for (let i = 0; i < this.dataSet.points.length; i++) { // Set position based on projected point. let pp = this.dataSet.points[i].projectedPoint; this.positionBufferArray.setXYZ(i, pp.x, pp.y, pp.z); } if (this.geometry) { this.positionBufferArray.needsUpdate = true; } } /** * Returns an x, y, z value for each item of our data based on the accessor * methods. */ private getPointsCoordinates() { // Determine max and min of each axis of our data. let xExtent = d3.extent(this.dataSet.points, (p, i) => this.xAccessor(i)); let yExtent = d3.extent(this.dataSet.points, (p, i) => this.yAccessor(i)); this.xScale.domain(xExtent).range([-1, 1]); this.yScale.domain(yExtent).range([-1, 1]); if (this.zAccessor) { let zExtent = d3.extent(this.dataSet.points, (p, i) => this.zAccessor(i)); this.zScale.domain(zExtent).range([-1, 1]); } // Determine 3d coordinates of each data point. this.dataSet.points.forEach((d, i) => { d.projectedPoint.x = this.xScale(this.xAccessor(i)); d.projectedPoint.y = this.yScale(this.yAccessor(i)); d.projectedPoint.z = (this.zAccessor ? this.zScale(this.zAccessor(i)) : 0); }); } private createLight() { this.light = new THREE.PointLight(0xFFECBF, 1, 0); this.scene.add(this.light); } /** General setup of scene and renderer. */ private createSceneAndRenderer() { this.scene = new THREE.Scene(); this.renderer = new THREE.WebGLRenderer(); // Accouting for retina displays. this.renderer.setPixelRatio(window.devicePixelRatio || 1); this.renderer.setSize(this.width, this.height); this.containerNode.appendChild(this.renderer.domElement); this.pickingTexture = new THREE.WebGLRenderTarget(this.width, this.height); this.pickingTexture.texture.minFilter = THREE.LinearFilter; } /** Set up camera and camera's controller. */ private makeCamera() { this.perspCamera = new THREE.PerspectiveCamera(FOV, this.width / this.height, NEAR, FAR); this.cameraControls = new (THREE as any) .OrbitControls(this.perspCamera, this.renderer.domElement); this.cameraControls.mouseButtons.ORBIT = THREE.MOUSE.LEFT; this.cameraControls.mouseButtons.PAN = THREE.MOUSE.RIGHT; // Start is called when the user stars interacting with // orbit controls. this.cameraControls.addEventListener('start', () => { this.cameraControls.autoRotate = false; cancelAnimationFrame(this.lazySusanAnimation); }); // Change is called everytime the user interacts with the // orbit controls. this.cameraControls.addEventListener('change', () => { this.removeAllLabels(); this.render(); }); // End is called when the user stops interacting with the // orbit controls (e.g. on mouse up, after dragging). this.cameraControls.addEventListener('end', () => { this.makeLabels(); }); } /** Sets up camera to work in 3D (called after makeCamera()). */ private makeCamera3D() { // Set up the camera position at a skewed angle from the xy plane, looking // toward the origin this.cameraControls.position0.set(POS_3D.x, POS_3D.y, POS_3D.z); this.cameraControls.target0.set(TAR_3D.x, TAR_3D.y, TAR_3D.z); this.cameraControls.enableRotate = true; let position = new THREE.Vector3(POS_3D.x, POS_3D.y, POS_3D.z); let target = new THREE.Vector3(TAR_3D.x, TAR_3D.y, TAR_3D.z); this.animate(position, target, () => { // Start lazy susan after the animation is done. this.startLazySusanAnimation(); }); } /** Sets up camera to work in 2D (called after makeCamera()). */ private makeCamera2D(animate?: boolean) { // Set the camera position in the middle of the screen, looking directly // toward the middle of the xy plane this.cameraControls.position0.set(POS_2D.x, POS_2D.y, POS_2D.z); this.cameraControls.target0.set(TAR_2D.x, TAR_2D.y, TAR_2D.z); let position = new THREE.Vector3(POS_2D.x, POS_2D.y, POS_2D.z); let target = new THREE.Vector3(TAR_2D.x, TAR_2D.y, TAR_2D.z); this.animate(position, target); this.cameraControls.enableRotate = false; } /** * Set up buffer attributes to be used for the points/images. */ private createBufferAttributes() { // Set up buffer attribute arrays. let numPoints = this.dataSet.points.length; let colArr = new Float32Array(numPoints * RGB_NUM_BYTES); this.uniqueColArr = new Float32Array(numPoints * RGB_NUM_BYTES); let colors = new THREE.BufferAttribute(this.uniqueColArr, RGB_NUM_BYTES); // Assign each point a unique color in order to identify when the user // hovers over a point. for (let i = 0; i < numPoints; i++) { let color = new THREE.Color(i); colors.setXYZ(i, color.r, color.g, color.b); } colors.array = colArr; let hiArr = new Float32Array(numPoints); /** Indices cooresponding to highlighted points. */ let highlights = new THREE.BufferAttribute(hiArr, INDEX_NUM_BYTES); // Note that we need two index arrays. /** * The actual indices of the points which we use for sizeAttenuation in * the shader. */ let indicesShader = new THREE.BufferAttribute(new Float32Array(numPoints), 1); for (let i = 0; i < numPoints; i++) { // Create the array of indices. indicesShader.setX(i, this.dataSet.points[i].dataSourceIndex); } // Finally, add all attributes to the geometry. this.geometry.addAttribute('position', this.positionBufferArray); this.positionBufferArray.needsUpdate = true; this.geometry.addAttribute('color', colors); this.geometry.addAttribute('vertexIndex', indicesShader); this.geometry.addAttribute('isHighlight', highlights); // For now, nothing is highlighted. this.colorSprites(null); } /** * Generate a texture for the points/images and sets some initial params */ private createTexture(image: HTMLImageElement| HTMLCanvasElement): THREE.Texture { let tex = new THREE.Texture(image); tex.needsUpdate = true; // Used if the texture isn't a power of 2. tex.minFilter = THREE.LinearFilter; tex.generateMipmaps = false; tex.flipY = false; return tex; } /** * Create points, set their locations and actually instantiate the * geometry. */ private addSprites() { // Create geometry. this.geometry = new THREE.BufferGeometry(); this.createBufferAttributes(); let canvas = document.createElement('canvas'); let image = this.image || canvas; // TODO(smilkov): Pass sprite dim to the renderer. let spriteDim = 28.0; let tex = this.createTexture(image); let pointSize = (this.zAccessor ? this.pointSize3D : this.pointSize2D); if (this.image) { pointSize = IMAGE_SIZE; } let uniforms = { texture: {type: 't', value: tex}, imageWidth: {type: 'f', value: image.width / spriteDim}, imageHeight: {type: 'f', value: image.height / spriteDim}, fogColor: {type: 'c', value: this.fog.color}, fogNear: {type: 'f', value: this.fog.near}, fogFar: {type: 'f', value: this.fog.far}, sizeAttenuation: {type: 'bool', value: !!this.zAccessor}, isImage: {type: 'bool', value: !!this.image}, pointSize: {type: 'f', value: pointSize} }; this.materialOptions = { uniforms: uniforms, vertexShader: VERTEX_SHADER, fragmentShader: FRAGMENT_SHADER, transparent: (this.image ? false : true), // When rendering points with blending, we want depthTest/Write // turned off. depthTest: (this.image ? true : false), depthWrite: (this.image ? true : false), fog: true, blending: (this.image ? THREE.NormalBlending : this.blending), }; // Give it some material. let material = new THREE.ShaderMaterial(this.materialOptions); // And finally initialize it and add it to the scene. this.points = new THREE.Points(this.geometry, material); this.scene.add(this.points); } /** * Create line traces between connected points and instantiate the geometry. */ private addTraces() { if (!this.dataSet || !this.dataSet.traces) { return; } this.traces = []; for (let i = 0; i < this.dataSet.traces.length; i++) { let dataTrace = this.dataSet.traces[i]; let geometry = new THREE.BufferGeometry(); let vertices: number[] = []; let colors: number[] = []; for (let j = 0; j < dataTrace.pointIndices.length - 1; j++) { this.dataSet.points[dataTrace.pointIndices[j]].traceIndex = i; this.dataSet.points[dataTrace.pointIndices[j + 1]].traceIndex = i; let point1 = this.dataSet.points[dataTrace.pointIndices[j]]; let point2 = this.dataSet.points[dataTrace.pointIndices[j + 1]]; vertices.push( point1.projectedPoint.x, point1.projectedPoint.y, point1.projectedPoint.z); vertices.push( point2.projectedPoint.x, point2.projectedPoint.y, point2.projectedPoint.z); let color1 = this.getPointInTraceColor(j, dataTrace.pointIndices.length); let color2 = this.getPointInTraceColor(j + 1, dataTrace.pointIndices.length); colors.push( color1.r / 255, color1.g / 255, color1.b / 255, color2.r / 255, color2.g / 255, color2.b / 255); } geometry.addAttribute( 'position', new THREE.BufferAttribute(new Float32Array(vertices), XYZ_NUM_BYTES)); geometry.addAttribute( 'color', new THREE.BufferAttribute(new Float32Array(colors), RGB_NUM_BYTES)); // We use the same material for every line. let material = new THREE.LineBasicMaterial({ linewidth: TRACE_DEFAULT_LINEWIDTH, opacity: TRACE_DEFAULT_OPACITY, transparent: true, vertexColors: THREE.VertexColors }); let trace = new THREE.LineSegments(geometry, material); this.traces.push(trace); this.scene.add(trace); } } /** * Returns the color of a point along a trace. */ private getPointInTraceColor(index: number, totalPoints: number) { let hue = TRACE_START_HUE + (TRACE_END_HUE - TRACE_START_HUE) * index / totalPoints; return d3.hsl(hue, TRACE_SATURATION, TRACE_LIGHTNESS).rgb(); } /** Clean up any old axes that we may have made previously. */ private removeOldAxes() { if (this.axis3D) { this.scene.remove(this.axis3D); } if (this.axis2D) { this.scene.remove(this.axis2D); } } /** Add axis. */ private addAxis3D() { this.axis3D = new THREE.AxisHelper(); this.scene.add(this.axis3D); } /** Manually make axis if we're in 2d. */ private addAxis2D() { let vertices = new Float32Array([ 0, 0, 0, this.xScale(1), 0, 0, 0, 0, 0, 0, this.yScale(1), 0, ]); let axisColor = new THREE.Color(AXIS_COLOR); let axisColors = new Float32Array([ axisColor.r, axisColor.b, axisColor.g, axisColor.r, axisColor.b, axisColor.g, axisColor.r, axisColor.b, axisColor.g, axisColor.r, axisColor.b, axisColor.g, ]); // Create line geometry based on above position and color. let lineGeometry = new THREE.BufferGeometry(); lineGeometry.addAttribute( 'position', new THREE.BufferAttribute(vertices, XYZ_NUM_BYTES)); lineGeometry.addAttribute( 'color', new THREE.BufferAttribute(axisColors, RGB_NUM_BYTES)); // And use it to create the actual object and add this new axis to the // scene! let axesMaterial = new THREE.LineBasicMaterial({vertexColors: THREE.VertexColors}); this.axis2D = new THREE.LineSegments(lineGeometry, axesMaterial); this.scene.add(this.axis2D); } // DYNAMIC (post-load) CHANGES /** When we stop dragging/zooming, return to normal behavior. */ private onClick(e?: MouseEvent) { if (e && this.selecting || !this.points) { this.resetTraces(); return; } let selection = this.nearestPoint || null; this.defaultPointColor = (selection ? POINT_COLOR_GRAYED : POINT_COLOR); // Only call event handlers if the click originated from the scatter plot. if (e && !this.isDragSequence) { this.onSelectionListeners.forEach(l => l(selection ? [selection] : [])); } this.isDragSequence = false; this.labeledPoints = this.highlightedPoints.filter((id, i) => this.favorLabels(i)); this.resetTraces(); if (selection && this.dataSet.points[selection].traceIndex) { for (let i = 0; i < this.traces.length; i++) { this.traces[i].material.opacity = TRACE_DESELECTED_OPACITY; this.traces[i].material.needsUpdate = true; } this.traces[this.dataSet.points[selection].traceIndex].material.opacity = TRACE_SELECTED_OPACITY; (this.traces[this.dataSet.points[selection].traceIndex].material as THREE.LineBasicMaterial) .linewidth = TRACE_SELECTED_LINEWIDTH; this.traces[this.dataSet.points[selection].traceIndex] .material.needsUpdate = true; } this.render(); this.makeLabels(); } private resetTraces() { if (!this.traces) { return; } for (let i = 0; i < this.traces.length; i++) { this.traces[i].material.opacity = TRACE_DEFAULT_OPACITY; (this.traces[i].material as THREE.LineBasicMaterial).linewidth = TRACE_DEFAULT_LINEWIDTH; this.traces[i].material.needsUpdate = true; } } /** When dragging, do not redraw labels. */ private onMouseDown(e: MouseEvent) { this.animating = false; this.isDragSequence = false; this.mouseIsDown = true; // If we are in selection mode, and we have in fact clicked a valid point, // create a sphere so we can select things if (this.selecting) { this.cameraControls.enabled = false; this.setNearestPointToMouse(e); if (this.nearestPoint) { this.createSelectionSphere(); } } else if ( !e.ctrlKey && this.cameraControls.mouseButtons.ORBIT == THREE.MOUSE.RIGHT) { // The user happened to press the ctrl key when the tab was active, // unpressed the ctrl when the tab was inactive, and now he/she // is back to the projector tab. this.cameraControls.mouseButtons.ORBIT = THREE.MOUSE.LEFT; this.cameraControls.mouseButtons.PAN = THREE.MOUSE.RIGHT; } else if ( e.ctrlKey && this.cameraControls.mouseButtons.ORBIT == THREE.MOUSE.LEFT) { // Similarly to the situation above. this.cameraControls.mouseButtons.ORBIT = THREE.MOUSE.RIGHT; this.cameraControls.mouseButtons.PAN = THREE.MOUSE.LEFT; } } /** When we stop dragging/zooming, return to normal behavior. */ private onMouseUp(e: any) { if (this.selecting) { this.cameraControls.enabled = true; this.scene.remove(this.selectionSphere); this.selectionSphere = null; this.render(); } this.mouseIsDown = false; } /** * When the mouse moves, find the nearest point (if any) and send it to the * hoverlisteners (usually called from embedding.ts) */ private onMouseMove(e: MouseEvent) { if (this.cameraControls.autoRotate) { // Cancel the lazy susan. this.cameraControls.autoRotate = false; cancelAnimationFrame(this.lazySusanAnimation); this.makeLabels(); } // A quick check to make sure data has come in. if (!this.points) { return; } this.isDragSequence = this.mouseIsDown; // Depending if we're selecting or just navigating, handle accordingly. if (this.selecting && this.mouseIsDown) { if (this.selectionSphere) { this.adjustSelectionSphere(e); } this.render(); } else if (!this.mouseIsDown) { let lastNearestPoint = this.nearestPoint; this.setNearestPointToMouse(e); if (lastNearestPoint != this.nearestPoint) { this.onHoverListeners.forEach(l => l(this.nearestPoint)); } } } /** For using ctrl + left click as right click, and for circle select */ private onKeyDown(e: any) { // If ctrl is pressed, use left click to orbit if (e.keyCode === CTRL_KEY) { this.cameraControls.mouseButtons.ORBIT = THREE.MOUSE.RIGHT; this.cameraControls.mouseButtons.PAN = THREE.MOUSE.LEFT; } // If shift is pressed, start selecting if (e.keyCode === SHIFT_KEY) { this.selecting = true; this.containerNode.style.cursor = 'crosshair'; } } /** For using ctrl + left click as right click, and for circle select */ private onKeyUp(e: any) { if (e.keyCode === CTRL_KEY) { this.cameraControls.mouseButtons.ORBIT = THREE.MOUSE.LEFT; this.cameraControls.mouseButtons.PAN = THREE.MOUSE.RIGHT; } // If shift is released, stop selecting if (e.keyCode === SHIFT_KEY) { this.selecting = (this.getMode() === Mode.SELECT); if (!this.selecting) { this.containerNode.style.cursor = 'default'; } this.scene.remove(this.selectionSphere); this.selectionSphere = null; this.render(); } } private setNearestPointToMouse(e: MouseEvent) { // Create buffer for reading a single pixel. let pixelBuffer = new Uint8Array(4); // No need to account for dpr (device pixel ratio) since the pickingTexture // has the same coordinates as the mouse (flipped on y). let x = e.offsetX; let y = e.offsetY; // Read the pixel under the mouse from the texture. this.renderer.readRenderTargetPixels( this.pickingTexture, x, this.pickingTexture.height - y, 1, 1, pixelBuffer); // Interpret the pixel as an ID. let id = (pixelBuffer[0] << 16) | (pixelBuffer[1] << 8) | pixelBuffer[2]; this.nearestPoint = id != 0xffffff && id < this.dataSet.points.length ? id : null; } /** Returns the squared distance to the mouse for the i-th point. */ private getDist2ToMouse(i: number, e: MouseEvent) { let point = this.getProjectedPointFromIndex(i); let screenCoords = this.vector3DToScreenCoords(point); return this.dist2D( [e.offsetX * this.dpr, e.offsetY * this.dpr], [screenCoords.x, screenCoords.y]); } private adjustSelectionSphere(e: MouseEvent) { let dist2 = this.getDist2ToMouse(this.nearestPoint, e) / 100; this.selectionSphere.scale.set(dist2, dist2, dist2); this.selectPoints(dist2); } private getProjectedPointFromIndex(i: number): THREE.Vector3 { return new THREE.Vector3( this.dataSet.points[i].projectedPoint.x, this.dataSet.points[i].projectedPoint.y, this.dataSet.points[i].projectedPoint.z); } private calibratePointSize() { let numPts = this.dataSet.points.length; let scaleConstant = 200; let logBase = 8; // Scale point size inverse-logarithmically to the number of points. this.pointSize3D = scaleConstant / Math.log(numPts) / Math.log(logBase); this.pointSize2D = this.pointSize3D / 1.5; } private setFogDistances() { let dists = this.getNearFarPoints(); this.fog.near = dists.shortestDist; // If there are fewer points we want less fog. We do this // by making the "far" value (that is, the distance from the camera to the // far edge of the fog) proportional to the number of points. let multiplier = 2 - Math.min(this.dataSet.points.length, NUM_POINTS_FOG_THRESHOLD) / NUM_POINTS_FOG_THRESHOLD; this.fog.far = dists.furthestDist * multiplier; } private getNearFarPoints() { let shortestDist: number = Infinity; let furthestDist: number = 0; for (let i = 0; i < this.dataSet.points.length; i++) { let point = this.getProjectedPointFromIndex(i); if (!this.isPointWithinCameraView(point)) { continue; }; let distToCam = this.dist3D(point, this.perspCamera.position); furthestDist = Math.max(furthestDist, distToCam); shortestDist = Math.min(shortestDist, distToCam); } return {shortestDist, furthestDist}; } /** * Renders the scene and updates the label for the point, which is rendered * as a div on top of WebGL. */ private render() { if (!this.dataSet) { return; } let lightPos = new THREE.Vector3().copy(this.perspCamera.position); lightPos.x += 1; lightPos.y += 1; this.light.position.set(lightPos.x, lightPos.y, lightPos.z); // We want to determine which point the user is hovering over. So, rather // than linearly iterating through each point to see if it is under the // mouse, we render another set of the points offscreen, where each point is // at full opacity and has its id encoded in its color. Then, we see the // color of the pixel under the mouse, decode the color, and get the id of // of the point. let shaderMaterial = this.points.material as THREE.ShaderMaterial; let colors = this.geometry.getAttribute('color') as THREE.BufferAttribute; // Make shallow copy of the shader options and modify the necessary values. let offscreenOptions = Object.create(this.materialOptions) as THREE.ShaderMaterialParameters; // Since THREE.js errors if we remove the fog, the workaround is to set the // near value to very far, so no points have fog. this.fog.near = 1000; this.fog.far = 10000; // Render offscreen as non transparent points (even when we have images). offscreenOptions.uniforms.isImage.value = false; offscreenOptions.transparent = false; offscreenOptions.depthTest = true; offscreenOptions.depthWrite = true; shaderMaterial.setValues(offscreenOptions); // Give each point a unique color. let origColArr = colors.array; colors.array = this.uniqueColArr; colors.needsUpdate = true; this.renderer.render(this.scene, this.perspCamera, this.pickingTexture); // Now render onscreen. // Change to original color array. colors.array = origColArr; colors.needsUpdate = true; // Bring back the fog. if (this.zAccessor && this.geometry) { this.setFogDistances(); } offscreenOptions.uniforms.isImage.value = !!this.image; // Bring back the standard shader material options. shaderMaterial.setValues(this.materialOptions); // Render onscreen. this.renderer.render(this.scene, this.perspCamera); } /** * Make sure that the point is in view of the camera (as opposed to behind * this is a problem because we are projecting to the camera) */ private isPointWithinCameraView(point: THREE.Vector3): boolean { let camToTarget = new THREE.Vector3() .copy(this.perspCamera.position) .sub(this.cameraControls.target); let camToPoint = new THREE.Vector3().copy(this.perspCamera.position).sub(point); // If the angle between the camera-target and camera-point vectors is more // than 90, the point is behind the camera if (camToPoint.angleTo(camToTarget) > Math.PI / 2) { return false; }; return true; } private vector3DToScreenCoords(v: THREE.Vector3) { let vector = new THREE.Vector3().copy(v).project(this.perspCamera); let coords = { // project() returns the point in perspCamera's coordinates, with the // origin in the center and a positive upward y. To get it into screen // coordinates, normalize by adding 1 and dividing by 2. x: ((vector.x + 1) / 2 * this.width) * this.dpr, y: -((vector.y - 1) / 2 * this.height) * this.dpr }; return coords; } /** Checks if a given label will be within the screen's bounds. */ private isLabelInBounds(labelWidth: number, coords: {x: number, y: number}) { let padding = 7; if ((coords.x < 0) || (coords.y < 0) || (coords.x > this.width * this.dpr - labelWidth - padding) || (coords.y > this.height * this.dpr)) { return false; }; return true; } /** Add a specific label to the canvas. */ private formatLabel( text: string, point: {x: number, y: number}, opacity: number) { let ls = new THREE.Color(this.labelStroke); let lc = new THREE.Color(this.labelColor); this.gc.strokeStyle = 'rgba(' + ls.r * 255 + ',' + ls.g * 255 + ',' + ls.b * 255 + ',' + opacity + ')'; this.gc.fillStyle = 'rgba(' + lc.r * 255 + ',' + lc.g * 255 + ',' + lc.b * 255 + ',' + opacity + ')'; this.gc.strokeText(text, point.x + 4, point.y); this.gc.fillText(text, point.x + 4, point.y); } /** * Reset the positions of all labels, and check for overlapps using the * collision grid. */ private makeLabels() { // Don't make labels if they are turned off. if (!this.labelsAreOn || this.points == null) { return; } // First, remove all old labels. this.removeAllLabels(); this.labelCanvasIsCleared = false; // If we are passed no points to label (that is, not mousing over any // points) then want to label ALL the points that we can. if (!this.labeledPoints.length) { this.labeledPoints = this.shuffledData; } // We never render more than ~500 labels, so when we get much past that // point, just break. let numRenderedLabels: number = 0; let labelHeight = parseInt(this.gc.font, 10); // Bounding box for collision grid. let boundingBox: BoundingBox = { loX: 0, hiX: this.width * this.dpr, loY: 0, hiY: this.height * this.dpr }; // Make collision grid with cells proportional to window dimensions. let grid = new CollisionGrid(boundingBox, this.width / 25, this.height / 50); let dists = this.getNearFarPoints(); let opacityRange = dists.furthestDist - dists.shortestDist; // Setting styles for the labeled font. this.gc.lineWidth = 6; this.gc.textBaseline = 'middle'; this.gc.font = (FONT_SIZE * this.dpr).toString() + 'px roboto'; for (let i = 0; (i < this.labeledPoints.length) && !(numRenderedLabels > SAMPLE_SIZE); i++) { let index = this.labeledPoints[i]; let point = this.getProjectedPointFromIndex(index); if (!this.isPointWithinCameraView(point)) { continue; }; let screenCoords = this.vector3DToScreenCoords(point); // Have extra space between neighboring labels. Don't pack too tightly. let labelMargin = 2; // Shift the label to the right of the point circle. let xShift = 3; let textBoundingBox = { loX: screenCoords.x + xShift - labelMargin, // Computing the width of the font is expensive, // so we assume width of 1 at first. Then, if the label doesn't // conflict with other labels, we measure the actual width. hiX: screenCoords.x + xShift + /* labelWidth - 1 */ +1 + labelMargin, loY: screenCoords.y - labelHeight / 2 - labelMargin, hiY: screenCoords.y + labelHeight / 2 + labelMargin }; if (grid.insert(textBoundingBox, true)) { let dataSet = this.dataSet; let text = this.labelAccessor(index); let labelWidth = this.gc.measureText(text).width; // Now, check with properly computed width. textBoundingBox.hiX += labelWidth - 1; if (grid.insert(textBoundingBox) && this.isLabelInBounds(labelWidth, screenCoords)) { let lenToCamera = this.dist3D(point, this.perspCamera.position); // Opacity is scaled between 0.2 and 1, based on how far a label is // from the camera (Unless we are in 2d mode, in which case opacity is // just 1!) let opacity = this.zAccessor ? 1.2 - (lenToCamera - dists.shortestDist) / opacityRange : 1; this.formatLabel(text, screenCoords, opacity); numRenderedLabels++; } } } if (this.highlightedPoints.length > 0) { // Force-draw the first favored point with increased font size. let index = this.highlightedPoints[0]; let point = this.dataSet.points[index]; this.gc.font = (FONT_SIZE * this.dpr * 1.7).toString() + 'px roboto'; let coords = new THREE.Vector3( point.projectedPoint.x, point.projectedPoint.y, point.projectedPoint.z); let screenCoords = this.vector3DToScreenCoords(coords); let text = this.labelAccessor(index); this.formatLabel(text, screenCoords, 255); } } /** Returns the distance between two points in 3d space */ private dist3D(a: Point3D, b: Point3D): number { let dx = a.x - b.x; let dy = a.y - b.y; let dz = a.z - b.z; return Math.sqrt(dx * dx + dy * dy + dz * dz); } private dist2D(a: [number, number], b: [number, number]): number { let dX = a[0] - b[0]; let dY = a[1] - b[1]; return Math.sqrt(dX * dX + dY * dY); } /** Cancels current animation */ private cancelAnimation() { if (this.animationID) { cancelAnimationFrame(this.animationID); } } private startLazySusanAnimation() { this.cameraControls.autoRotate = true; this.cameraControls.update(); this.lazySusanAnimation = requestAnimationFrame(() => this.startLazySusanAnimation()); } /** * Animates the camera between one location and another. * If callback is specified, it gets called when the animation is done. */ private animate( pos: THREE.Vector3, target: THREE.Vector3, callback?: () => void) { this.cameraControls.autoRotate = false; cancelAnimationFrame(this.lazySusanAnimation); let currPos = this.perspCamera.position; let currTarget = this.cameraControls.target; let speed = 3; this.animating = true; let interp = (a: THREE.Vector3, b: THREE.Vector3) => { let x = (a.x - b.x) / speed + b.x; let y = (a.y - b.y) / speed + b.y; let z = (a.z - b.z) / speed + b.z; return {x: x, y: y, z: z}; }; // If we're still relatively far away from the target, go closer if (this.dist3D(currPos, pos) > .03) { let newTar = interp(target, currTarget); this.cameraControls.target.set(newTar.x, newTar.y, newTar.z); let newPos = interp(pos, currPos); this.perspCamera.position.set(newPos.x, newPos.y, newPos.z); this.cameraControls.update(); this.render(); this.animationID = requestAnimationFrame(() => this.animate(pos, target, callback)); } else { // Once we get close enough, update flags and stop moving this.animating = false; this.cameraControls.target.set(target.x, target.y, target.z); this.cameraControls.update(); this.makeLabels(); this.render(); if (callback) { callback(); } } } /** Removes all points geometry from the scene. */ private removeAll() { this.scene.remove(this.points); this.removeOldAxes(); this.removeAllLabels(); this.removeAllTraces(); } /** Removes all traces from the scene. */ private removeAllTraces() { if (!this.traces) { return; } for (let i = 0; i < this.traces.length; i++) { this.scene.remove(this.traces[i]); } this.traces = []; } /** Removes all the labels. */ private removeAllLabels() { // If labels are already removed, do not spend compute power to clear the // canvas. if (!this.labelCanvasIsCleared) { this.gc.clearRect(0, 0, this.width * this.dpr, this.height * this.dpr); this.labelCanvasIsCleared = true; } } private colorSprites(highlightStroke: ((index: number) => string)) { // Update attributes to change colors let colors = this.geometry.getAttribute('color') as THREE.BufferAttribute; let highlights = this.geometry.getAttribute('isHighlight') as THREE.BufferAttribute; for (let i = 0; i < this.dataSet.points.length; i++) { let unhighlightedColor = this.image ? new THREE.Color() : new THREE.Color( this.colorAccessor ? this.colorAccessor(i) : (this.defaultPointColor as any)); colors.setXYZ( i, unhighlightedColor.r, unhighlightedColor.g, unhighlightedColor.b); highlights.setX(i, 0.0); } if (highlightStroke) { // Traverse in reverse so that the point we are hovering over // (highlightedPoints[0]) is painted last. for (let i = this.highlightedPoints.length - 1; i >= 0; i--) { let assocPoint = this.highlightedPoints[i]; let color = new THREE.Color(highlightStroke(i)); // Fill colors array (single array of numPoints*3 elements, // triples of which refer to the rgb values of a single vertex). colors.setXYZ(assocPoint, color.r, color.g, color.b); highlights.setX(assocPoint, 1.0); } } colors.needsUpdate = true; highlights.needsUpdate = true; } /** * This is called when we update the data to make sure we don't have stale * data lying around. */ private cleanVariables() { this.removeAll(); if (this.geometry) { this.geometry.dispose(); } this.geometry = null; this.points = null; this.labeledPoints = []; this.highlightedPoints = []; } /** Select the points inside the sphere of radius dist */ private selectPoints(dist: number) { let selectedPoints: Array<number> = new Array(); this.dataSet.points.forEach(point => { let pt = point.projectedPoint; let pointVect = new THREE.Vector3(pt.x, pt.y, pt.z); let distPointToSphereOrigin = new THREE.Vector3() .copy(this.selectionSphere.position) .sub(pointVect) .length(); if (distPointToSphereOrigin < dist) { selectedPoints.push(this.dataSet.points.indexOf(point)); } }); this.labeledPoints = selectedPoints; // Whenever anything is selected, we want to set the corect point color. this.defaultPointColor = POINT_COLOR_GRAYED; this.onSelectionListeners.forEach(l => l(selectedPoints)); } private createSelectionSphere() { let geometry = new THREE.SphereGeometry(1, 300, 100); let material = new THREE.MeshPhongMaterial({ color: 0x000000, specular: (this.zAccessor && 0xffffff), // In 2d, make sphere look flat. emissive: 0x000000, shininess: 10, shading: THREE.SmoothShading, opacity: 0.125, transparent: true, }); this.selectionSphere = new THREE.Mesh(geometry, material); this.selectionSphere.scale.set(0, 0, 0); let pos = this.dataSet.points[this.nearestPoint].projectedPoint; this.scene.add(this.selectionSphere); this.selectionSphere.position.set(pos.x, pos.y, pos.z); } private getLayoutValues() { this.width = this.containerNode.offsetWidth; this.height = Math.max(1, this.containerNode.offsetHeight); this.dpr = window.devicePixelRatio; } // PUBLIC API /** Sets the data for the scatter plot. */ setDataSet(dataSet: DataSet, spriteImage: HTMLImageElement) { this.dataSet = dataSet; this.calibratePointSize(); let positions = new Float32Array(this.dataSet.points.length * XYZ_NUM_BYTES); this.positionBufferArray = new THREE.BufferAttribute(positions, XYZ_NUM_BYTES); this.image = spriteImage; this.shuffledData = new Array(this.dataSet.points.length); for (let i = 0; i < this.dataSet.points.length; i++) { this.shuffledData[i] = i; } shuffle(this.shuffledData); this.cleanVariables(); } setColorAccessor(colorAccessor: (index: number) => string) { this.colorAccessor = colorAccessor; // Render only if there is a geometry. if (this.geometry) { this.colorSprites(this.highlightStroke); this.render(); } } setXAccessor(xAccessor: (index: number) => number) { this.xAccessor = xAccessor; } setYAccessor(yAccessor: (index: number) => number) { this.yAccessor = yAccessor; } setZAccessor(zAccessor: (index: number) => number) { this.zAccessor = zAccessor; } setLabelAccessor(labelAccessor: (index: number) => string) { this.labelAccessor = labelAccessor; this.render(); } setMode(mode: Mode) { this.mode = mode; if (mode === Mode.SELECT) { this.selecting = true; this.containerNode.style.cursor = 'crosshair'; } else { this.selecting = false; this.containerNode.style.cursor = 'default'; } } getMode(): Mode { return this.mode; } resetZoom() { if (this.animating) { return; } let resetPos = this.cameraControls.position0; let resetTarget = this.cameraControls.target0; this.removeAllLabels(); this.animate(resetPos, resetTarget, () => { // Start rotating when the animation is done, if we are in 3D mode. if (this.zAccessor) { this.startLazySusanAnimation(); } }); } /** Zoom by moving the camera toward the target. */ zoomStep(multiplier: number) { let additiveZoom = Math.log(multiplier); if (this.animating) { return; } // Zoomvect is the vector along which we want to move the camera // It is the (normalized) vector from the camera to its target let zoomVect = new THREE.Vector3() .copy(this.cameraControls.target) .sub(this.perspCamera.position) .multiplyScalar(additiveZoom); let position = new THREE.Vector3().copy(this.perspCamera.position).add(zoomVect); // Make sure that we're not too far zoomed in. If not, zoom! if ((this.dist3D(position, this.cameraControls.target) > MIN_ZOOM) && (this.dist3D(position, this.cameraControls.target) < MAX_ZOOM)) { this.removeAllLabels(); this.animate(position, this.cameraControls.target); } } highlightPoints( pointIndexes: number[], highlightStroke: (i: number) => string, favorLabels: (i: number) => boolean): void { this.favorLabels = favorLabels; this.highlightedPoints = pointIndexes; this.labeledPoints = pointIndexes; this.highlightStroke = highlightStroke; this.colorSprites(highlightStroke); this.render(); this.makeLabels(); } getHighlightedPoints(): number[] { return this.highlightedPoints; } showLabels(show: boolean) { this.labelsAreOn = show; if (this.labelsAreOn) { this.makeLabels(); } else { this.removeAllLabels(); } } /** * Toggles between day and night mode (resets corresponding variables for * color, etc.) */ setDayNightMode(isNight: boolean) { this.isNight = isNight; this.labelColor = (isNight ? LABEL_COLOR_NIGHT : LABEL_COLOR_DAY); this.labelStroke = (isNight ? LABEL_STROKE_NIGHT : LABEL_STROKE_DAY); this.backgroundColor = (isNight ? BACKGROUND_COLOR_NIGHT : BACKGROUND_COLOR_DAY); this.blending = (isNight ? BLENDING_NIGHT : BLENDING_DAY); this.renderer.setClearColor(this.backgroundColor); } showAxes(show: boolean) { // TODO(ereif): implement } setAxisLabels(xLabel: string, yLabel: string) { // TODO(ereif): implement } /** * Recreates the scene in its entirety, not only resetting the point * locations but also demolishing and recreating the THREEjs structures. */ recreateScene() { this.removeAll(); this.cancelAnimation(); this.fog = this.zAccessor ? new THREE.Fog(this.backgroundColor) : new THREE.Fog(this.backgroundColor, Infinity, Infinity); this.scene.fog = this.fog; this.addSprites(); this.addTraces(); if (this.zAccessor) { this.addAxis3D(); this.makeCamera3D(); } else { this.addAxis2D(); this.makeCamera2D(); } this.render(); } /** * Redraws the data. Should be called anytime the accessor method * for x and y coordinates changes, which means a new projection * exists and the scatter plot should repaint the points. */ update() { this.cancelAnimation(); this.getPointsCoordinates(); this.updatePositionsArray(); if (this.geometry) { this.makeLabels(); this.render(); } } resize(render = true) { this.getLayoutValues(); this.perspCamera.aspect = this.width / this.height; this.perspCamera.updateProjectionMatrix(); d3.select(this.canvas) .attr('width', this.width * this.dpr) .attr('height', this.height * this.dpr) .style({width: this.width + 'px', height: this.height + 'px'}); this.renderer.setSize(this.width, this.height); this.pickingTexture = new THREE.WebGLRenderTarget(this.width, this.height); this.pickingTexture.texture.minFilter = THREE.LinearFilter; if (render) { this.render(); }; } showTickLabels(show: boolean) { // TODO(ereif): implement } onSelection(listener: OnSelectionListener) { this.onSelectionListeners.push(listener); } onHover(listener: OnHoverListener) { this.onHoverListeners.push(listener); } clickOnPoint(pointIndex: number) { this.nearestPoint = pointIndex; this.onClick(); } }
the_stack
import * as StellarSdk from 'stellar-base'; const masterKey = StellarSdk.Keypair.master(StellarSdk.Networks.TESTNET); // $ExpectType Keypair const sourceKey = StellarSdk.Keypair.random(); // $ExpectType Keypair const destKey = StellarSdk.Keypair.random(); const usd = new StellarSdk.Asset('USD', 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7'); // $ExpectType Asset const account = new StellarSdk.Account(sourceKey.publicKey(), '1'); // $ExpectType Account const muxedAccount = new StellarSdk.MuxedAccount(account, '123'); // $ExpectType MuxedAccount const muxedConforms = muxedAccount as StellarSdk.Account; // $ExpectType Account const transaction = new StellarSdk.TransactionBuilder(account, { fee: "100", networkPassphrase: StellarSdk.Networks.TESTNET }) .addOperation( StellarSdk.Operation.beginSponsoringFutureReserves({ sponsoredId: account.accountId(), source: masterKey.publicKey(), withMuxing: false, // ensures source can always be muxed }) ).addOperation( StellarSdk.Operation.accountMerge({ destination: destKey.publicKey() }), ).addOperation( StellarSdk.Operation.payment({ source: account.accountId(), destination: muxedAccount.accountId(), amount: "100", asset: usd, withMuxing: false, // ensure muxed ops also allow the flag }) ).addOperation( StellarSdk.Operation.createClaimableBalance({ amount: "10", asset: StellarSdk.Asset.native(), claimants: [ new StellarSdk.Claimant(account.accountId()) ] }), ).addOperation( StellarSdk.Operation.claimClaimableBalance({ balanceId: "00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be", }), ).addOperation( StellarSdk.Operation.endSponsoringFutureReserves({ }) ).addOperation( StellarSdk.Operation.endSponsoringFutureReserves({}) ).addOperation( StellarSdk.Operation.revokeAccountSponsorship({ account: account.accountId(), }) ).addOperation( StellarSdk.Operation.revokeTrustlineSponsorship({ account: account.accountId(), asset: usd, }) ).addOperation( StellarSdk.Operation.revokeOfferSponsorship({ seller: account.accountId(), offerId: '12345' }) ).addOperation( StellarSdk.Operation.revokeDataSponsorship({ account: account.accountId(), name: 'foo' }) ).addOperation( StellarSdk.Operation.revokeClaimableBalanceSponsorship({ balanceId: "00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be", }) ).addOperation( StellarSdk.Operation.revokeLiquidityPoolSponsorship({ liquidityPoolId: "dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7", }) ).addOperation( StellarSdk.Operation.revokeSignerSponsorship({ account: account.accountId(), signer: { ed25519PublicKey: sourceKey.publicKey() } }) ).addOperation( StellarSdk.Operation.revokeSignerSponsorship({ account: account.accountId(), signer: { sha256Hash: "da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be" } }) ).addOperation( StellarSdk.Operation.revokeSignerSponsorship({ account: account.accountId(), signer: { preAuthTx: "da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be" } }) ).addOperation( StellarSdk.Operation.clawback({ from: account.accountId(), amount: "1000", asset: usd, }) ).addOperation( StellarSdk.Operation.clawbackClaimableBalance({ balanceId: "00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be", }) ).addOperation( StellarSdk.Operation.setTrustLineFlags({ trustor: account.accountId(), asset: usd, flags: { authorized: true, authorizedToMaintainLiabilities: true, clawbackEnabled: true, }, }) ).addOperation( StellarSdk.Operation.setTrustLineFlags({ trustor: account.accountId(), asset: usd, flags: { authorized: true, }, }) ).addOperation( StellarSdk.Operation.liquidityPoolDeposit({ liquidityPoolId: "dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7", maxAmountA: "10000", maxAmountB: "20000", minPrice: "0.45", maxPrice: "0.55", }) ).addOperation( StellarSdk.Operation.liquidityPoolWithdraw({ liquidityPoolId: "dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7", amount: "100", minAmountA: "10000", minAmountB: "20000", }) ).addOperation( StellarSdk.Operation.setOptions({ setFlags: (StellarSdk.AuthImmutableFlag | StellarSdk.AuthRequiredFlag) as StellarSdk.AuthFlag, clearFlags: (StellarSdk.AuthRevocableFlag | StellarSdk.AuthClawbackEnabledFlag) as StellarSdk.AuthFlag, }) ).addMemo(new StellarSdk.Memo(StellarSdk.MemoText, 'memo')) .setTimeout(5) .build(); // $ExpectType () => Transaction<Memo<MemoType>, Operation[]> const transactionFromXDR = new StellarSdk.Transaction(transaction.toEnvelope(), StellarSdk.Networks.TESTNET); // $ExpectType Transaction<Memo<MemoType>, Operation[]> transactionFromXDR.networkPassphrase; // $ExpectType string transactionFromXDR.networkPassphrase = "SDF"; StellarSdk.TransactionBuilder.fromXDR(transaction.toXDR(), StellarSdk.Networks.TESTNET); // $ExpectType Transaction<Memo<MemoType>, Operation[]> | FeeBumpTransaction StellarSdk.TransactionBuilder.fromXDR(transaction.toEnvelope(), StellarSdk.Networks.TESTNET); // $ExpectType Transaction<Memo<MemoType>, Operation[]> | FeeBumpTransaction const sig = StellarSdk.xdr.DecoratedSignature.fromXDR(Buffer.of(1, 2)); // $ExpectType DecoratedSignature sig.hint(); // $ExpectType Buffer sig.signature(); // $ExpectType Buffer StellarSdk.Memo.none(); // $ExpectType Memo<"none"> StellarSdk.Memo.text('asdf'); // $ExpectType Memo<"text"> StellarSdk.Memo.id('asdf'); // $ExpectType Memo<"id"> StellarSdk.Memo.return('asdf'); // $ExpectType Memo<"return"> StellarSdk.Memo.hash('asdf'); // $ExpectType Memo<"hash"> StellarSdk.Memo.none().value; // $ExpectType null StellarSdk.Memo.id('asdf').value; // $ExpectType string StellarSdk.Memo.text('asdf').value; // $ExpectType string | Buffer StellarSdk.Memo.return('asdf').value; // $ExpectType Buffer StellarSdk.Memo.hash('asdf').value; // $ExpectType Buffer const feeBumptransaction = StellarSdk.TransactionBuilder.buildFeeBumpTransaction(masterKey, "120", transaction, StellarSdk.Networks.TESTNET); // $ExpectType FeeBumpTransaction feeBumptransaction.feeSource; // $ExpectType string feeBumptransaction.innerTransaction; // $ExpectType Transaction<Memo<MemoType>, Operation[]> feeBumptransaction.fee; // $ExpectType string feeBumptransaction.toXDR(); // $ExpectType string feeBumptransaction.toEnvelope(); // $ExpectType TransactionEnvelope feeBumptransaction.hash(); // $ExpectType Buffer StellarSdk.TransactionBuilder.fromXDR(feeBumptransaction.toXDR(), StellarSdk.Networks.TESTNET); // $ExpectType Transaction<Memo<MemoType>, Operation[]> | FeeBumpTransaction StellarSdk.TransactionBuilder.fromXDR(feeBumptransaction.toEnvelope(), StellarSdk.Networks.TESTNET); // $ExpectType Transaction<Memo<MemoType>, Operation[]> | FeeBumpTransaction // P.S. You shouldn't be using the Memo constructor // // Unfortunately, it appears that type aliases aren't unwrapped by the linter, // causing the following lines to fail unnecessarily: // // new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf').value; // $ExpectType MemoValue // new StellarSdk.Memo(StellarSdk.MemoHash, 'asdf').type; // $ExpectType MemoType // // This is because the linter just does a raw string comparison on type names: // https://github.com/Microsoft/dtslint/issues/57#issuecomment-451666294 const noSignerXDR = StellarSdk.Operation.setOptions({ lowThreshold: 1 }); StellarSdk.Operation.fromXDRObject(noSignerXDR).signer; // $ExpectType never const newSignerXDR1 = StellarSdk.Operation.setOptions({ signer: { ed25519PublicKey: sourceKey.publicKey(), weight: '1' } }); StellarSdk.Operation.fromXDRObject(newSignerXDR1).signer; // $ExpectType Ed25519PublicKey const newSignerXDR2 = StellarSdk.Operation.setOptions({ signer: { sha256Hash: Buffer.from(''), weight: '1' } }); StellarSdk.Operation.fromXDRObject(newSignerXDR2).signer; // $ExpectType Sha256Hash const newSignerXDR3 = StellarSdk.Operation.setOptions({ signer: { preAuthTx: '', weight: 1 } }); StellarSdk.Operation.fromXDRObject(newSignerXDR3).signer; // $ExpectType PreAuthTx StellarSdk.TimeoutInfinite; // $ExpectType 0 const envelope = feeBumptransaction.toEnvelope(); // $ExpectType TransactionEnvelope envelope.v0(); // $ExpectType TransactionV0Envelope envelope.v1(); // $ExpectType TransactionV1Envelope envelope.feeBump(); // $ExpectType FeeBumpTransactionEnvelope const meta = StellarSdk.xdr.TransactionMeta.fromXDR( // tslint:disable:max-line-length 'AAAAAQAAAAIAAAADAcEsRAAAAAAAAAAArZu2SrdQ9krkyj7RBqTx1txDNZBfcS+wGjuEUizV9hkAAAAAAKXgdAGig34AADuDAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAABAcEsRAAAAAAAAAAArZu2SrdQ9krkyj7RBqTx1txDNZBfcS+wGjuEUizV9hkAAAAAAKXgdAGig34AADuEAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAA==', 'base64' ); meta; // $ExpectType TransactionMeta meta.v1().txChanges(); // $ExpectType LedgerEntryChange[] const op = StellarSdk.xdr.AllowTrustOp.fromXDR( 'AAAAAMNQvnFVCnBnEVzd8ZaKUvsI/mECPGV8cnBszuftCmWYAAAAAUNPUAAAAAAC', 'base64' ); op; // $ExpectType AllowTrustOp op.authorize(); // $ExpectType number op.trustor().ed25519(); // $ExpectType Buffer op.trustor(); // $ExpectedType AccountId const e = StellarSdk.xdr.LedgerEntry.fromXDR( "AAAAAAAAAAC2LgFRDBZ3J52nLm30kq2iMgrO7dYzYAN3hvjtf1IHWg==", 'base64' ); e; // $ExpectType LedgerEntry const a = StellarSdk.xdr.AccountEntry.fromXDR( // tslint:disable:max-line-length 'AAAAALYuAVEMFncnnacubfSSraIyCs7t1jNgA3eG+O1/UgdaAAAAAAAAA+gAAAAAGc1zDAAAAAIAAAABAAAAAEB9GCtIe8SCLk7LV3MzmlKN3U4M2JdktE7ofCKtTNaaAAAABAAAAAtzdGVsbGFyLm9yZwABAQEBAAAAAQAAAACEKm+WHjUQThNzoKx6WbU8no3NxzUrGtoSLmtxaBAM2AAAAAEAAAABAAAAAAAAAAoAAAAAAAAAFAAAAAA=', 'base64' ); a; // $ExpectType AccountEntry a.homeDomain(); // $ExpectType string | Buffer const t = StellarSdk.xdr.TransactionV0.fromXDR( // tslint:disable:max-line-length '1bzMAeuKubyXUug/Xnyj1KYkv+cSUtCSvAczI2b459kAAABkAS/5cwAAABMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAsBL/lzAAAAFAAAAAA=', 'base64' ); t; // $ExpectType TransactionV0 t.timeBounds(); // $ExpectType TimeBounds | null StellarSdk.xdr.Uint64.fromString("12"); // $ExpectType UnsignedHyper StellarSdk.xdr.Int32.toXDR(-1); // $ExpectType Buffer StellarSdk.xdr.Uint32.toXDR(1); // $ExpectType Buffer StellarSdk.xdr.String32.toXDR("hellow world"); // $ExpectedType Buffer StellarSdk.xdr.Hash.toXDR(Buffer.alloc(32)); // $ExpectedType Buffer StellarSdk.xdr.Signature.toXDR(Buffer.alloc(9, 'a')); // $ExpectedType Buffer const change = StellarSdk.xdr.LedgerEntryChange.fromXDR( // tslint:disable:max-line-length 'AAAAAwHBW0UAAAAAAAAAADwkQ23EX6ohsRsGoCynHl5R8D7RXcgVD4Y92uUigLooAAAAAIitVMABlM5gABTlLwAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA', 'base64' ); change; // $ExpectType LedgerEntryChange const raw = StellarSdk.xdr.LedgerEntryChanges.toXDR([change]); // $ExpectType Buffer StellarSdk.xdr.LedgerEntryChanges.fromXDR(raw); // $ExpectType LedgerEntryChange[] StellarSdk.xdr.Asset.assetTypeNative(); // $ExpectType Asset StellarSdk.xdr.InnerTransactionResultResult.txInternalError(); // $ExpectType InnerTransactionResultResult StellarSdk.xdr.TransactionV0Ext[0](); // $ExpectedType TransactionV0Ext StellarSdk.Claimant.predicateUnconditional(); // $ExpectType ClaimPredicate const claimant = new StellarSdk.Claimant(sourceKey.publicKey()); // $ExpectType Claimant claimant.toXDRObject(); // $ExpectType Claimant claimant.destination; // $ExpectType string claimant.predicate; // $ExpectType ClaimPredicate const claw = StellarSdk.xdr.ClawbackOp.fromXDR( // tslint:disable:max-line-length 'AAAAAAAAABMAAAABVVNEAAAAAADNTrgPO19O0EsnYjSc333yWGLKEVxLyu1kfKjCKOz9ewAAAADFTYDKyTn2O0DVUEycHKfvsnFWj91TVl0ut1kwg5nLigAAAAJUC+QA', 'base64' ); claw; // $ExpectType ClawbackOp const clawCb = StellarSdk.xdr.ClawbackClaimableBalanceOp.fromXDR( // tslint:disable:max-line-length 'AAAAAAAAABUAAAAAxU2Aysk59jtA1VBMnByn77JxVo/dU1ZdLrdZMIOZy4oAAAABVVNEAAAAAADNTrgPO19O0EsnYjSc333yWGLKEVxLyu1kfKjCKOz9ewAAAAAAAAAH', 'base64' ); clawCb; // $ExpectType ClawbackClaimableBalanceOp const trust = StellarSdk.xdr.SetTrustLineFlagsOp.fromXDR( // tslint:disable:max-line-length 'AAAAAAAAABUAAAAAF1frB6QZRDTYW4dheEA3ZZLCjSWs9eQgzsyvqdUy2rgAAAABVVNEAAAAAADNTrgPO19O0EsnYjSc333yWGLKEVxLyu1kfKjCKOz9ewAAAAAAAAAB', 'base64' ); trust; // $ExpectType SetTrustLineFlagsOp const lpDeposit = StellarSdk.xdr.LiquidityPoolDepositOp.fromXDR( // tslint:disable:max-line-length '3XsauDHCczEN2+xvl4cKqDwvvXjOIq3tN+y/TzOA+scAAAAABfXhAAAAAAAL68IAAAAACQAAABQAAAALAAAAFA==', 'base64' ); lpDeposit; // $ExpectType LiquidityPoolDepositOp const lpWithdraw = StellarSdk.xdr.LiquidityPoolWithdrawOp.fromXDR( // tslint:disable:max-line-length '3XsauDHCczEN2+xvl4cKqDwvvXjOIq3tN+y/TzOA+scAAAAAAvrwgAAAAAAF9eEAAAAAAAvrwgA=', 'base64' ); lpWithdraw; // $ExpectType LiquidityPoolWithdrawOp
the_stack
import { ThemeColorDefinition } from '@fluentui-react-native/theme-types'; import { ApplePalette } from './appleColors.types.ios'; function getFluentUIAppleLightPalette(): ApplePalette { return { blue10: '#4F6BED', blueMagenta20: '#8764B8', blueMagenta30: '#5C2E91', communicationBlue: '#0078D4', communicationBlueShade10: '#106EBE', communicationBlueShade20: '#005A9E', communicationBlueShade30: '#004578', communicationBlueTint10: '#2B88D8', communicationBlueTint20: '#C7E0F4', communicationBlueTint30: '#DEECF9', communicationBlueTint40: '#EFF6FC', cyan20: '#038387', cyan30: '#005B70', cyanBlue10: '#0078D4', cyanBlue20: '#004E8C', dangerPrimary: '#D92C2C', dangerShade10: '#C32727', dangerShade20: '#A52121', dangerShade30: '#791818', dangerTint10: '#DD4242', dangerTint20: '#E87979', dangerTint30: '#F4B9B9', dangerTint40: '#F9D9D9', gray20: '#69797E', gray25: '#F8F8F8', gray30: '#7A7574', gray40: '#393939', gray50: '#F1F1F1', gray100: '#E1E1E1', gray200: '#C8C8C8', gray300: '#ACACAC', gray400: '#919191', gray500: '#6E6E6E', gray600: '#404040', gray700: '#303030', gray800: '#292929', gray900: '#212121', gray950: '#141414', green10: '#498205', green20: '#0B6A0B', magenta10: '#C239B3', magenta20: '#881798', magentaPink10: '#E3008C', orange20: '#CA5010', orange30: '#8E562E', orangeYellow20: '#986F0B', pinkRed10: '#750B1C', presenceAvailable: '#6BB700', presenceAway: '#FFAA44', presenceBlocked: '#C50F1F', presenceBusy: '#C50F1F', presenceDnd: '#C50F1F', presenceOffline: '#8A8886', presenceOof: '#B4009E', presenceUnknown: '#8A8886', red10: '#D13438', red20: '#A4262C', successPrimary: '#13A10E', successShade10: '#11910D', successShade20: '#0F7A0B', successShade30: '#0B5A08', successTint10: '#27AC22', successTint20: '#5EC65A', successTint30: '#A7E3A5', successTint40: '#CEF0CD', warningPrimary: '#FFD335', warningShade10: '#E6BE30', warningShade20: '#C2A129', warningShade30: '#8F761E', warningTint10: '#FFD94E', warningTint20: '#FFE586', warningTint30: '#FFF2C3', warningTint40: '#FFF8DF', textDominant: '#212121', //= UIColor(light: gray900, lightHighContrast: .black, dark: .white) textPrimary: '#212121', //= UIColor(light: gray900, lightHighContrast: .black, dark: gray100, darkHighContrast: .white) textSecondary: '#6E6E6E', //= UIColor(light: gray500, lightHighContrast: gray700, dark: gray400, darkHighContrast: gray200) textDisabled: '#ACACAC', //= UIColor(light: gray300, lightHighContrast: gray500, dark: gray600, darkHighContrast: gray400) textOnAccent: 'white', //= UIColor(light: .white, dark: .black) iconPrimary: '#6E6E6E', //= UIColor(light: gray500, lightHighContrast: gray700, dark: .white) iconSecondary: '#919191', //= UIColor(light: gray400, lightHighContrast: gray600, dark: gray500, darkHighContrast: gray300, darkElevated: gray400) iconDisabled: '#ACACAC', //= UIColor(light: gray300, lightHighContrast: gray500, dark: gray600, darkHighContrast: gray400) iconOnAccent: 'white', //= UIColor(light: .white, dark: .black) surfacePrimary: 'white', //= UIColor(light: .white, dark: .black, darkElevated: gray950) surfaceSecondary: '#F8F8F8', //= UIColor(light: gray25, dark: gray950, darkElevated: gray900) surfaceTertiary: '#F1F1F1', //= UIColor(light: gray50, dark: gray900, darkElevated: gray800) surfaceQuaternary: '#E1E1E1', //= UIColor(light: gray100, dark: gray600) dividerOnPrimary: '#E1E1E1', //= UIColor(light: gray100, dark: gray800, darkElevated: gray700) dividerOnSecondary: '#C8C8C8', //= UIColor(light: gray200, dark: gray700, darkElevated: gray600) dividerOnTertiary: '#C8C8C8', //= UIColor(light: gray200, dark: gray700, darkElevated: gray600) buttonBackground: 'transparent', buttonBackgroundFilledPressed: '#2B88D8', //UIColor(light: Colors.primaryTint10(for: window), dark: Colors.primaryTint20(for: window)) buttonBackgroundFilledDisabled: '#E1E1E1', //surfaceQuaternary buttonBorderDisabled: '#E1E1E1', //surfaceQuaternary buttonTitleDisabled: '#ACACAC', //textDisabled buttonTitleWithFilledBackground: 'white', //textOnAccent }; } function getFluentUIAppleDarkPalette(): ApplePalette { return { blue10: '#4F6BED', blueMagenta20: '#8764B8', blueMagenta30: '#5C2E91', communicationBlue: '#0086F0', communicationBlueShade10: '#1890F1', communicationBlueShade20: '#3AA0F3', communicationBlueShade30: '#6CB8F6', communicationBlueTint10: '#0078D4', communicationBlueTint20: '#004C87', communicationBlueTint30: '#043862', communicationBlueTint40: '#092C47', cyan20: '#038387', cyan30: '#005B70', cyanBlue10: '#0078D4', cyanBlue20: '#004E8C', dangerPrimary: '#E83A3A', dangerShade10: '#EA4C4C', dangerShade20: '#EE6666', dangerShade30: '#F28C8C', dangerTint10: '#CC3333', dangerTint20: '#8B2323', dangerTint30: '#461111', dangerTint40: '#250909', gray20: '#69797E', gray25: '#F8F8F8', gray30: '#7A7574', gray40: '#393939', gray50: '#F1F1F1', gray100: '#E1E1E1', gray200: '#C8C8C8', gray300: '#ACACAC', gray400: '#919191', gray500: '#6E6E6E', gray600: '#404040', gray700: '#303030', gray800: '#292929', gray900: '#212121', gray950: '#141414', green10: '#498205', green20: '#0B6A0B', magenta10: '#C239B3', magenta20: '#881798', magentaPink10: '#E3008C', orange20: '#CA5010', orange30: '#8E562E', orangeYellow20: '#986F0B', pinkRed10: '#750B1C', presenceAvailable: '#92C353', presenceAway: '#F8D22A', presenceBlocked: '#D74553', presenceBusy: '#D74553', presenceDnd: '#D74553', presenceOffline: '#979593', presenceOof: '#E959D9', presenceUnknown: '#979593', red10: '#D13438', red20: '#A4262C', successPrimary: '#979593', successShade10: '#20BA53', successShade20: '#3BC569', successShade30: '#67D48B', successTint10: '#0D9D3D', successTint20: '#096B29', successTint30: '#043615', successTint40: '#021D0B', warningPrimary: '#FFC328', warningShade10: '#FFC83E', warningShade20: '#FFDD15', warningShade30: '#FFDD87', warningTint10: '#E0AB24', warningTint20: '#997518', warningTint30: '#4D3A0C', warningTint40: '#291F07', textDominant: 'white', //= UIColor(light: gray900, lightHighContrast: .black, dark: .white) textPrimary: '#E1E1E1', //= UIColor(light: gray900, lightHighContrast: .black, dark: gray100, darkHighContrast: .white) textSecondary: '#919191', //= UIColor(light: gray500, lightHighContrast: gray700, dark: gray400, darkHighContrast: gray200) textDisabled: '#404040', //= UIColor(light: gray300, lightHighContrast: gray500, dark: gray600, darkHighContrast: gray400) textOnAccent: 'black', //= UIColor(light: .white, dark: .black) iconPrimary: '#303030', //= UIColor(light: gray500, lightHighContrast: gray700, dark: .white) iconSecondary: '#404040', //= UIColor(light: gray400, lightHighContrast: gray600, dark: gray500, darkHighContrast: gray300, darkElevated: gray400) iconDisabled: '#6E6E6E', //= UIColor(light: gray300, lightHighContrast: gray500, dark: gray600, darkHighContrast: gray400) iconOnAccent: 'black', //= UIColor(light: .white, dark: .black) surfacePrimary: 'black', //= UIColor(light: .white, dark: .black, darkElevated: gray950) surfaceSecondary: '#141414', //= UIColor(light: gray25, dark: gray950, darkElevated: gray900) surfaceTertiary: '#212121', //= UIColor(light: gray50, dark: gray900, darkElevated: gray800) surfaceQuaternary: '#404040', //= UIColor(light: gray100, dark: gray600) dividerOnPrimary: '#292929', //= UIColor(light: gray100, dark: gray800, darkElevated: gray700) dividerOnSecondary: '#303030', //= UIColor(light: gray200, dark: gray700, darkElevated: gray600) dividerOnTertiary: '#303030', //= UIColor(light: gray200, dark: gray700, darkElevated: gray600) buttonBackground: 'transparent', buttonBackgroundFilledPressed: '#004C87', //UIColor(light: Colors.primaryTint10(for: window), dark: Colors.primaryTint20(for: window)) buttonBackgroundFilledDisabled: '#404040', //surfaceQuaternary buttonBorderDisabled: '#404040', //surfaceQuaternary buttonTitleDisabled: '#404040', //textDisabled buttonTitleWithFilledBackground: 'black', //textOnAccent }; } /** Creates a palette of colors for the apple theme, using the appropriate FluentUI Apple Palette based on appearance */ export function paletteFromAppleColors(isDark: boolean): ThemeColorDefinition { const fluentApple = isDark ? getFluentUIAppleDarkPalette() : getFluentUIAppleLightPalette(); return { /* PaletteBackgroundColors & PaletteTextColors */ background: fluentApple.surfacePrimary, bodyStandoutBackground: fluentApple.surfaceSecondary, bodyFrameBackground: fluentApple.surfacePrimary, bodyFrameDivider: fluentApple.dividerOnPrimary, bodyText: fluentApple.textPrimary, bodyTextChecked: fluentApple.textPrimary, subText: fluentApple.textSecondary, bodyDivider: fluentApple.dividerOnSecondary, disabledBackground: fluentApple.gray100, disabledText: fluentApple.textDisabled, disabledBodyText: fluentApple.textDisabled, disabledSubtext: fluentApple.textDisabled, disabledBodySubtext: fluentApple.textDisabled, focusBorder: 'transparent', variantBorder: fluentApple.dividerOnPrimary, variantBorderHovered: fluentApple.dividerOnPrimary, defaultStateBackground: fluentApple.surfacePrimary, errorText: fluentApple.dangerPrimary, warningText: fluentApple.warningPrimary, errorBackground: fluentApple.dangerTint10, blockingBackground: fluentApple.dangerTint10, warningBackground: fluentApple.warningPrimary, warningHighlight: fluentApple.warningTint10, successBackground: fluentApple.successTint10, inputBorder: fluentApple.dividerOnPrimary, inputBorderHovered: fluentApple.dividerOnPrimary, inputBackground: fluentApple.surfacePrimary, inputBackgroundChecked: fluentApple.surfacePrimary, inputBackgroundCheckedHovered: fluentApple.surfacePrimary, inputForegroundChecked: fluentApple.communicationBlue, inputFocusBorderAlt: fluentApple.dividerOnSecondary, smallInputBorder: fluentApple.dividerOnSecondary, inputText: fluentApple.textPrimary, inputTextHovered: fluentApple.textPrimary, inputPlaceholderText: fluentApple.textSecondary, // Default values without any style // on FluentUI Apple iOS, this is the buttonStyle "Secondary Outline" buttonBackground: 'transparent', buttonBackgroundChecked: 'transparent', buttonBackgroundHovered: 'transparent', buttonBackgroundCheckedHovered: 'transparent', buttonBackgroundPressed: 'transparent', buttonBackgroundDisabled: 'transparent', buttonBorder: fluentApple.communicationBlueTint10, buttonText: fluentApple.communicationBlue, buttonTextHovered: fluentApple.communicationBlue, buttonTextChecked: fluentApple.communicationBlue, buttonTextCheckedHovered: fluentApple.communicationBlue, buttonTextPressed: fluentApple.communicationBlueTint20, buttonTextDisabled: fluentApple.buttonTitleDisabled, buttonBorderDisabled: fluentApple.buttonBorderDisabled, buttonBorderFocused: fluentApple.communicationBlueTint10, primaryButtonBackground: fluentApple.communicationBlue, primaryButtonBackgroundHovered: fluentApple.communicationBlue, primaryButtonBackgroundPressed: fluentApple.buttonBackgroundFilledPressed, primaryButtonBackgroundDisabled: fluentApple.buttonBackgroundFilledDisabled, primaryButtonBorder: 'transparent', primaryButtonBorderFocused: 'transparent', primaryButtonText: fluentApple.buttonTitleWithFilledBackground, primaryButtonTextHovered: fluentApple.buttonTitleWithFilledBackground, primaryButtonTextPressed: fluentApple.buttonTitleWithFilledBackground, primaryButtonTextDisabled: fluentApple.buttonTitleWithFilledBackground, accentButtonBackground: fluentApple.communicationBlue, accentButtonText: fluentApple.buttonTitleWithFilledBackground, menuBackground: fluentApple.surfacePrimary, menuDivider: fluentApple.dividerOnPrimary, menuIcon: fluentApple.iconPrimary, menuHeader: fluentApple.textDominant, menuItemBackgroundHovered: fluentApple.surfacePrimary, menuItemBackgroundPressed: fluentApple.surfacePrimary, menuItemText: fluentApple.textPrimary, menuItemTextHovered: fluentApple.textPrimary, listBackground: fluentApple.surfacePrimary, listText: fluentApple.textPrimary, listItemBackgroundHovered: fluentApple.surfacePrimary, listItemBackgroundChecked: fluentApple.surfacePrimary, listItemBackgroundCheckedHovered: fluentApple.surfacePrimary, listHeaderBackgroundHovered: fluentApple.textDominant, listHeaderBackgroundPressed: fluentApple.textDominant, actionLink: fluentApple.communicationBlue, actionLinkHovered: fluentApple.communicationBlue, link: fluentApple.communicationBlue, linkHovered: fluentApple.communicationBlue, linkPressed: fluentApple.communicationBlueTint10, /* ControlColorTokens */ // Default values without any style // on FluentUI Apple iOS, this is the buttonStyle "Secondary Outline" defaultBackground: 'transparent', defaultBorder: fluentApple.communicationBlueTint10, defaultContent: fluentApple.communicationBlue, defaultIcon: fluentApple.communicationBlue, defaultHoveredBackground: 'transparent', defaultHoveredBorder: fluentApple.communicationBlueTint10, defaultHoveredContent: fluentApple.communicationBlue, defaultHoveredIcon: fluentApple.communicationBlue, defaultFocusedBackground: 'transparent', defaultFocusedBorder: fluentApple.communicationBlueTint10, defaultFocusedContent: fluentApple.communicationBlue, defaultFocusedIcon: fluentApple.communicationBlue, defaultPressedBackground: 'transparent', defaultPressedBorder: fluentApple.communicationBlueTint30, defaultPressedContent: fluentApple.communicationBlueTint20, defaultPressedIcon: fluentApple.communicationBlueTint20, defaultDisabledBackground: 'transparent', defaultDisabledBorder: fluentApple.buttonBorderDisabled, defaultDisabledContent: fluentApple.buttonTitleDisabled, defaultDisabledIcon: fluentApple.buttonTitleDisabled, ghostBackground: 'transparent', ghostBorder: 'transparent', ghostContent: fluentApple.communicationBlue, ghostIcon: fluentApple.communicationBlue, ghostHoveredBackground: 'transparent', ghostHoveredBorder: 'transparent', ghostHoveredContent: fluentApple.communicationBlue, ghostHoveredIcon: fluentApple.communicationBlue, ghostFocusedBackground: 'transparent', ghostFocusedBorder: 'transparent', ghostFocusedContent: fluentApple.communicationBlue, ghostFocusedIcon: fluentApple.communicationBlue, ghostPressedBackground: 'transparent', ghostPressedBorder: 'transparent', ghostPressedContent: fluentApple.communicationBlueTint20, ghostPressedIcon: fluentApple.communicationBlueTint20, ghostDisabledBackground: 'transparent', ghostDisabledBorder: 'transparent', ghostDisabledContent: fluentApple.buttonTitleDisabled, ghostDisabledIcon: fluentApple.buttonTitleDisabled, brandedBackground: fluentApple.communicationBlue, brandedBorder: 'transparent', brandedContent: fluentApple.buttonTitleWithFilledBackground, brandedIcon: fluentApple.buttonTitleWithFilledBackground, brandedHoveredBackground: fluentApple.communicationBlue, brandedHoveredBorder: 'transparent', brandedHoveredContent: fluentApple.buttonTitleWithFilledBackground, brandedHoveredIcon: fluentApple.buttonTitleWithFilledBackground, brandedFocusedBackground: fluentApple.communicationBlue, brandedFocusedBorder: 'transparent', brandedFocusedContent: fluentApple.buttonTitleWithFilledBackground, brandedFocusedIcon: fluentApple.buttonTitleWithFilledBackground, brandedPressedBackground: fluentApple.buttonBackgroundFilledPressed, brandedPressedBorder: 'transparent', brandedPressedContent: fluentApple.buttonTitleWithFilledBackground, brandedPressedIcon: fluentApple.buttonTitleWithFilledBackground, brandedDisabledBackground: fluentApple.buttonBackgroundFilledDisabled, brandedDisabledBorder: 'transparent', brandedDisabledContent: fluentApple.buttonTitleWithFilledBackground, brandedDisabledIcon: fluentApple.buttonTitleWithFilledBackground, defaultCheckedBackground: 'transparent', defaultCheckedContent: fluentApple.communicationBlue, defaultCheckedHoveredBackground: 'transparent', defaultCheckedHoveredContent: fluentApple.communicationBlue, brandedCheckedBackground: fluentApple.communicationBlue, brandedCheckedContent: fluentApple.buttonTitleWithFilledBackground, brandedCheckedHoveredBackground: fluentApple.buttonTitleWithFilledBackground, brandedCheckedHoveredContent: fluentApple.buttonTitleWithFilledBackground, ghostCheckedBackground: 'transparent', ghostCheckedContent: fluentApple.communicationBlue, ghostCheckedHoveredBackground: 'transparent', ghostCheckedHoveredContent: fluentApple.communicationBlue, ghostCheckedHoveredBorder: 'transparent', // Buttons on iOS don't have secondary text, so map these to be the same as the normal content ghostSecondaryContent: fluentApple.communicationBlue, ghostFocusedSecondaryContent: fluentApple.communicationBlue, ghostHoveredSecondaryContent: fluentApple.communicationBlue, ghostPressedSecondaryContent: fluentApple.communicationBlueTint20, brandedSecondaryContent: fluentApple.buttonTitleWithFilledBackground, brandedFocusedSecondaryContent: fluentApple.buttonTitleWithFilledBackground, brandedHoveredSecondaryContent: fluentApple.buttonTitleWithFilledBackground, brandedPressedSecondaryContent: fluentApple.buttonTitleWithFilledBackground, defaultDisabledSecondaryContent: fluentApple.buttonTitleDisabled, defaultHoveredSecondaryContent: fluentApple.communicationBlue, defaultPressedSecondaryContent: fluentApple.communicationBlueTint20, checkboxBackground: fluentApple.communicationBlue, checkboxBackgroundDisabled: fluentApple.surfacePrimary, checkboxBorderColor: fluentApple.gray600, checkmarkColor: fluentApple.iconOnAccent, personaActivityGlow: fluentApple.buttonBackground, personaActivityRing: fluentApple.surfacePrimary, }; }
the_stack
import ez = require("TypeScript/ez") import EZ_TEST = require("./TestFramework") function mul(m: ez.Mat3, v: ez.Vec3): ez.Vec3 { let r = v.Clone(); m.TransformDirection(r); return r; } export class TestMat3 extends ez.TypescriptComponent { /* BEGIN AUTO-GENERATED: VARIABLES */ /* END AUTO-GENERATED: VARIABLES */ constructor() { super() } static RegisterMessageHandlers() { ez.TypescriptComponent.RegisterMessageHandler(ez.MsgGenericEvent, "OnMsgGenericEvent"); } ExecuteTests(): void { // Constructor (default) { let m = new ez.Mat3(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0.001); EZ_TEST.BOOL(m.IsIdentity()); } // Constructor (Elements) { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 9, 0.001); } // Clone { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m = m0.Clone(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 9, 0.001); } // SetMat3 { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m = new ez.Mat3(); m.SetMat3(m0); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 0), 2, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 0), 3, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 1), 4, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 1), 5, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 1), 6, 0.001); EZ_TEST.FLOAT(m.GetElement(0, 2), 7, 0.001); EZ_TEST.FLOAT(m.GetElement(1, 2), 8, 0.001); EZ_TEST.FLOAT(m.GetElement(2, 2), 9, 0.001); } // SetElement { let m = ez.Mat3.ZeroMatrix(); m.SetElement(0, 0, 1); m.SetElement(1, 0, 2); m.SetElement(2, 0, 3); m.SetElement(0, 1, 4); m.SetElement(1, 1, 5); m.SetElement(2, 1, 6); m.SetElement(0, 2, 7); m.SetElement(1, 2, 8); m.SetElement(2, 2, 9); let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.BOOL(m.IsIdentical(m0)); } // SetElements { let m = ez.Mat3.ZeroMatrix(); m.SetElements(1, 2, 3, 4, 5, 6, 7, 8, 9); let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.BOOL(m.IsIdentical(m0)); } // SetFromArray { const data = [1, 2, 3, 4, 5, 6, 7, 8, 9]; { let m = new ez.Mat3(); m.SetFromArray(data, true); EZ_TEST.BOOL(m.m_ElementsCM[0] == 1.0 && m.m_ElementsCM[1] == 2.0 && m.m_ElementsCM[2] == 3.0 && m.m_ElementsCM[3] == 4.0 && m.m_ElementsCM[4] == 5.0 && m.m_ElementsCM[5] == 6.0 && m.m_ElementsCM[6] == 7.0 && m.m_ElementsCM[7] == 8.0 && m.m_ElementsCM[8] == 9.0); } { let m = new ez.Mat3(); m.SetFromArray(data, false); EZ_TEST.BOOL(m.m_ElementsCM[0] == 1.0 && m.m_ElementsCM[1] == 4.0 && m.m_ElementsCM[2] == 7.0 && m.m_ElementsCM[3] == 2.0 && m.m_ElementsCM[4] == 5.0 && m.m_ElementsCM[5] == 8.0 && m.m_ElementsCM[6] == 3.0 && m.m_ElementsCM[7] == 6.0 && m.m_ElementsCM[8] == 9.0); } } // GetAsArray { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let data = m.GetAsArray(true); EZ_TEST.FLOAT(data[0], 1, 0.0001); EZ_TEST.FLOAT(data[1], 4, 0.0001); EZ_TEST.FLOAT(data[2], 7, 0.0001); EZ_TEST.FLOAT(data[3], 2, 0.0001); EZ_TEST.FLOAT(data[4], 5, 0.0001); EZ_TEST.FLOAT(data[5], 8, 0.0001); EZ_TEST.FLOAT(data[6], 3, 0.0001); EZ_TEST.FLOAT(data[7], 6, 0.0001); EZ_TEST.FLOAT(data[8], 9, 0.0001); data = m.GetAsArray(false); EZ_TEST.FLOAT(data[0], 1, 0.0001); EZ_TEST.FLOAT(data[1], 2, 0.0001); EZ_TEST.FLOAT(data[2], 3, 0.0001); EZ_TEST.FLOAT(data[3], 4, 0.0001); EZ_TEST.FLOAT(data[4], 5, 0.0001); EZ_TEST.FLOAT(data[5], 6, 0.0001); EZ_TEST.FLOAT(data[6], 7, 0.0001); EZ_TEST.FLOAT(data[7], 8, 0.0001); EZ_TEST.FLOAT(data[8], 9, 0.0001); } // SetZero { let m = new ez.Mat3(); m.SetZero(); for (let i = 0; i < 9; ++i) EZ_TEST.FLOAT(m.m_ElementsCM[i], 0.0, 0.0); } // SetIdentity { let m = new ez.Mat3(); m.SetIdentity(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0); } // SetScalingMatrix { let m = new ez.Mat3(); m.SetScalingMatrix(new ez.Vec3(2, 3, 4)); EZ_TEST.FLOAT(m.GetElement(0, 0), 2, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 3, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 4, 0); } // SetRotationMatrixX { let m = new ez.Mat3(); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -3, 2), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -2, -3), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 3, -2), 0.0001)); m.SetRotationMatrixX(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrixY { let m = new ez.Mat3(); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(3, 2, -1), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, 2, -3), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-3, 2, 1), 0.0001)); m.SetRotationMatrixY(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrixZ { let m = new ez.Mat3(); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-2, 1, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, -2, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(2, -1, 3), 0.0001)); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(360)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 2, 3), 0.0001)); } // SetRotationMatrix { let m = new ez.Mat3(); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -3, 2), 0.001)); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, -2, -3), 0.001)); m.SetRotationMatrix(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(1, 3, -2), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(3, 2, -1), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, 2, -3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-3, 2, 1), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-2, 1, 3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(180)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(-1, -2, 3), 0.001)); m.SetRotationMatrix(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(270)); EZ_TEST.BOOL(mul(m, new ez.Vec3(1, 2, 3)).IsEqual(new ez.Vec3(2, -1, 3), 0.001)); } // IdentityMatrix { let m = ez.Mat3.IdentityMatrix(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 1, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 1, 0); } // ZeroMatrix { let m = ez.Mat3.ZeroMatrix(); EZ_TEST.FLOAT(m.GetElement(0, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 0, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 0, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 0, 0); } // Transpose { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); m.Transpose(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1, 0); EZ_TEST.FLOAT(m.GetElement(1, 0), 4, 0); EZ_TEST.FLOAT(m.GetElement(2, 0), 7, 0); EZ_TEST.FLOAT(m.GetElement(0, 1), 2, 0); EZ_TEST.FLOAT(m.GetElement(1, 1), 5, 0); EZ_TEST.FLOAT(m.GetElement(2, 1), 8, 0); EZ_TEST.FLOAT(m.GetElement(0, 2), 3, 0); EZ_TEST.FLOAT(m.GetElement(1, 2), 6, 0); EZ_TEST.FLOAT(m.GetElement(2, 2), 9, 0); } // GetTranspose { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m = m0.GetTranspose(); EZ_TEST.FLOAT(m.GetElement(0, 0), 1); EZ_TEST.FLOAT(m.GetElement(1, 0), 4); EZ_TEST.FLOAT(m.GetElement(2, 0), 7); EZ_TEST.FLOAT(m.GetElement(0, 1), 2); EZ_TEST.FLOAT(m.GetElement(1, 1), 5); EZ_TEST.FLOAT(m.GetElement(2, 1), 8); EZ_TEST.FLOAT(m.GetElement(0, 2), 3); EZ_TEST.FLOAT(m.GetElement(1, 2), 6); EZ_TEST.FLOAT(m.GetElement(2, 2), 9); } // Invert { for (let x = 1.0; x < 360.0; x += 40.0) { for (let y = 2.0; y < 360.0; y += 37.0) { for (let z = 3.0; z < 360.0; z += 53.0) { let m = new ez.Mat3(); m.SetRotationMatrix(new ez.Vec3(x, y, z).GetNormalized(), ez.Angle.DegreeToRadian(19.0)); let inv = m.Clone(); EZ_TEST.BOOL(inv.Invert()); let v = mul(m, new ez.Vec3(1, 1, 1)); let vinv = mul(inv, v); EZ_TEST.VEC3(vinv, new ez.Vec3(1, 1, 1), 0.001); } } } } // GetInverse { for (let x = 1.0; x < 360.0; x += 39.0) { for (let y = 2.0; y < 360.0; y += 29.0) { for (let z = 3.0; z < 360.0; z += 51.0) { let m = new ez.Mat3(); m.SetRotationMatrix(new ez.Vec3(x, y, z).GetNormalized(), ez.Angle.DegreeToRadian(83.0)); let inv = m.GetInverse(); let v = mul(m, new ez.Vec3(1, 1, 1)); let vinv = mul(inv, v); EZ_TEST.VEC3(vinv, new ez.Vec3(1, 1, 1), 0.001); } } } } // IsZero { let m = new ez.Mat3(); m.SetIdentity(); EZ_TEST.BOOL(!m.IsZero()); m.SetZero(); EZ_TEST.BOOL(m.IsZero()); } // IsIdentity { let m = new ez.Mat3(); m.SetIdentity(); EZ_TEST.BOOL(m.IsIdentity()); m.SetZero(); EZ_TEST.BOOL(!m.IsIdentity()); } // GetRow { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.ARRAY(3, m.GetRow(0), [1, 2, 3], 0.0); EZ_TEST.ARRAY(3, m.GetRow(1), [4, 5, 6], 0.0); EZ_TEST.ARRAY(3, m.GetRow(2), [7, 8, 9], 0.0); } // SetRow { let m = new ez.Mat3(); m.SetZero(); m.SetRow(0, 1, 2, 3); EZ_TEST.ARRAY(3, m.GetRow(0), [1, 2, 3], 0.0); m.SetRow(1, 5, 6, 7); EZ_TEST.ARRAY(3, m.GetRow(1), [5, 6, 7], 0.0); m.SetRow(2, 9, 10, 11); EZ_TEST.ARRAY(3, m.GetRow(2), [9, 10, 11], 0.0); m.SetRow(3, 13, 14, 15); EZ_TEST.ARRAY(3, m.GetRow(3), [13, 14, 15], 0.0); } // GetColumn { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.ARRAY(3, m.GetColumn(0), [1, 4, 7], 0.0); EZ_TEST.ARRAY(3, m.GetColumn(1), [2, 5, 8], 0.0); EZ_TEST.ARRAY(3, m.GetColumn(2), [3, 6, 9], 0.0); } // SetColumn { let m = new ez.Mat3(); m.SetZero(); m.SetColumn(0, 1, 2, 3); EZ_TEST.ARRAY(3, m.GetColumn(0), [1, 2, 3], 0.0); m.SetColumn(1, 5, 6, 7); EZ_TEST.ARRAY(3, m.GetColumn(1), [5, 6, 7], 0.0); m.SetColumn(2, 9, 10, 11); EZ_TEST.ARRAY(3, m.GetColumn(2), [9, 10, 11], 0.0); m.SetColumn(3, 13, 14, 15); EZ_TEST.ARRAY(3, m.GetColumn(3), [13, 14, 15], 0.0); } // GetDiagonal { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.ARRAY(3, m.GetDiagonal(), [1, 5, 9], 0.0); } // SetDiagonal { let m = new ez.Mat3(); m.SetZero(); m.SetDiagonal(1, 2, 3); EZ_TEST.ARRAY(3, m.GetColumn(0), [1, 0, 0], 0.0); EZ_TEST.ARRAY(3, m.GetColumn(1), [0, 2, 0], 0.0); EZ_TEST.ARRAY(3, m.GetColumn(2), [0, 0, 3], 0.0); } // GetScalingFactors { let m = new ez.Mat3(1, 2, 3, 5, 6, 7, 9, 10, 11); let s = m.GetScalingFactors(); EZ_TEST.VEC3(s, new ez.Vec3(Math.sqrt((1 * 1 + 5 * 5 + 9 * 9)), Math.sqrt((2 * 2 + 6 * 6 + 10 * 10)), Math.sqrt((3 * 3 + 7 * 7 + 11 * 11))), 0.0001); } // SetScalingFactors { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); EZ_TEST.BOOL(m.SetScalingFactors(1, 2, 3)); let s = m.GetScalingFactors(); EZ_TEST.VEC3(s, new ez.Vec3(1, 2, 3), 0.0001); } // TransformDirection { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let r = new ez.Vec3(1, 2, 3); m.TransformDirection(r); EZ_TEST.VEC3(r, new ez.Vec3(1 * 1 + 2 * 2 + 3 * 3, 1 * 4 + 2 * 5 + 3 * 6, 1 * 7 + 2 * 8 + 3 * 9), 0.0001); } // IsIdentical { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsIdentical(m2)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(!m.IsIdentical(m2)); } // IsEqual { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsEqual(m2, 0.0001)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(m.IsEqual(m2, 0.001)); EZ_TEST.BOOL(!m.IsEqual(m2, 0.0001)); } // SetMulMat3 { let m1 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m2 = new ez.Mat3(-1, -2, -3, -4, -5, -6, -7, -8, -9); let r = new ez.Mat3(); r.SetMulMat3(m1, m2); EZ_TEST.ARRAY(3, r.GetColumn(0), [-1 * 1 + -4 * 2 + -7 * 3, -1 * 4 + -4 * 5 + -7 * 6, -1 * 7 + -4 * 8 + -7 * 9], 0.001); EZ_TEST.ARRAY(3, r.GetColumn(1), [-2 * 1 + -5 * 2 + -8 * 3, -2 * 4 + -5 * 5 + -8 * 6, -2 * 7 + -5 * 8 + -8 * 9], 0.001); EZ_TEST.ARRAY(3, r.GetColumn(2), [-3 * 1 + -6 * 2 + -9 * 3, -3 * 4 + -6 * 5 + -9 * 6, -3 * 7 + -6 * 8 + -9 * 9], 0.001); } // MulNumber { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m = m0.Clone(); m.MulNumber(2); EZ_TEST.ARRAY(3, m.GetRow(0), [2, 4, 6], 0.0001); EZ_TEST.ARRAY(3, m.GetRow(1), [8, 10, 12], 0.0001); EZ_TEST.ARRAY(3, m.GetRow(2), [14, 16, 18], 0.0001); } // DivNumber { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); m0.MulNumber(4); let m = m0.Clone(); m.DivNumber(2); EZ_TEST.ARRAY(3, m.GetRow(0), [2, 4, 6], 0.0001); EZ_TEST.ARRAY(3, m.GetRow(1), [8, 10, 12], 0.0001); EZ_TEST.ARRAY(3, m.GetRow(2), [14, 16, 18], 0.0001); } // AddMat3 / SubMat3 { let m0 = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m1 = new ez.Mat3(-1, -2, -3, -4, -5, -6, -7, -8, -9); let r1 = m0.Clone(); r1.AddMat3(m1); let r2 = m0.Clone(); r2.SubMat3(m1); let c2 = m0.Clone(); c2.MulNumber(2); EZ_TEST.BOOL(r1.IsZero()); EZ_TEST.BOOL(r2.IsEqual(c2, 0.0001)); } // IsIdentical { let m = new ez.Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); let m2 = m.Clone(); EZ_TEST.BOOL(m.IsIdentical(m2)); m2.m_ElementsCM[0] += 0.001; EZ_TEST.BOOL(!m.IsIdentical(m2)); } } OnMsgGenericEvent(msg: ez.MsgGenericEvent): void { if (msg.Message == "TestMat3") { this.ExecuteTests(); msg.Message = "done"; } } }
the_stack
/* eslint-disable */ import * as jspb from "google-protobuf"; import * as google_protobuf_empty_pb from "google-protobuf/google/protobuf/empty_pb"; import * as dapr_proto_common_v1_common_pb from "../../../../dapr/proto/common/v1/common_pb"; export class TopicEventRequest extends jspb.Message { getId(): string; setId(value: string): TopicEventRequest; getSource(): string; setSource(value: string): TopicEventRequest; getType(): string; setType(value: string): TopicEventRequest; getSpecVersion(): string; setSpecVersion(value: string): TopicEventRequest; getDataContentType(): string; setDataContentType(value: string): TopicEventRequest; getData(): Uint8Array | string; getData_asU8(): Uint8Array; getData_asB64(): string; setData(value: Uint8Array | string): TopicEventRequest; getTopic(): string; setTopic(value: string): TopicEventRequest; getPubsubName(): string; setPubsubName(value: string): TopicEventRequest; getPath(): string; setPath(value: string): TopicEventRequest; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): TopicEventRequest.AsObject; static toObject(includeInstance: boolean, msg: TopicEventRequest): TopicEventRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: TopicEventRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): TopicEventRequest; static deserializeBinaryFromReader(message: TopicEventRequest, reader: jspb.BinaryReader): TopicEventRequest; } export namespace TopicEventRequest { export type AsObject = { id: string, source: string, type: string, specVersion: string, dataContentType: string, data: Uint8Array | string, topic: string, pubsubName: string, path: string, } } export class TopicEventResponse extends jspb.Message { getStatus(): TopicEventResponse.TopicEventResponseStatus; setStatus(value: TopicEventResponse.TopicEventResponseStatus): TopicEventResponse; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): TopicEventResponse.AsObject; static toObject(includeInstance: boolean, msg: TopicEventResponse): TopicEventResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: TopicEventResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): TopicEventResponse; static deserializeBinaryFromReader(message: TopicEventResponse, reader: jspb.BinaryReader): TopicEventResponse; } export namespace TopicEventResponse { export type AsObject = { status: TopicEventResponse.TopicEventResponseStatus, } export enum TopicEventResponseStatus { SUCCESS = 0, RETRY = 1, DROP = 2, } } export class BindingEventRequest extends jspb.Message { getName(): string; setName(value: string): BindingEventRequest; getData(): Uint8Array | string; getData_asU8(): Uint8Array; getData_asB64(): string; setData(value: Uint8Array | string): BindingEventRequest; getMetadataMap(): jspb.Map<string, string>; clearMetadataMap(): void; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): BindingEventRequest.AsObject; static toObject(includeInstance: boolean, msg: BindingEventRequest): BindingEventRequest.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: BindingEventRequest, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): BindingEventRequest; static deserializeBinaryFromReader(message: BindingEventRequest, reader: jspb.BinaryReader): BindingEventRequest; } export namespace BindingEventRequest { export type AsObject = { name: string, data: Uint8Array | string, metadataMap: Array<[string, string]>, } } export class BindingEventResponse extends jspb.Message { getStoreName(): string; setStoreName(value: string): BindingEventResponse; clearStatesList(): void; getStatesList(): Array<dapr_proto_common_v1_common_pb.StateItem>; setStatesList(value: Array<dapr_proto_common_v1_common_pb.StateItem>): BindingEventResponse; addStates(value?: dapr_proto_common_v1_common_pb.StateItem, index?: number): dapr_proto_common_v1_common_pb.StateItem; clearToList(): void; getToList(): Array<string>; setToList(value: Array<string>): BindingEventResponse; addTo(value: string, index?: number): string; getData(): Uint8Array | string; getData_asU8(): Uint8Array; getData_asB64(): string; setData(value: Uint8Array | string): BindingEventResponse; getConcurrency(): BindingEventResponse.BindingEventConcurrency; setConcurrency(value: BindingEventResponse.BindingEventConcurrency): BindingEventResponse; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): BindingEventResponse.AsObject; static toObject(includeInstance: boolean, msg: BindingEventResponse): BindingEventResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: BindingEventResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): BindingEventResponse; static deserializeBinaryFromReader(message: BindingEventResponse, reader: jspb.BinaryReader): BindingEventResponse; } export namespace BindingEventResponse { export type AsObject = { storeName: string, statesList: Array<dapr_proto_common_v1_common_pb.StateItem.AsObject>, toList: Array<string>, data: Uint8Array | string, concurrency: BindingEventResponse.BindingEventConcurrency, } export enum BindingEventConcurrency { SEQUENTIAL = 0, PARALLEL = 1, } } export class ListTopicSubscriptionsResponse extends jspb.Message { clearSubscriptionsList(): void; getSubscriptionsList(): Array<TopicSubscription>; setSubscriptionsList(value: Array<TopicSubscription>): ListTopicSubscriptionsResponse; addSubscriptions(value?: TopicSubscription, index?: number): TopicSubscription; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ListTopicSubscriptionsResponse.AsObject; static toObject(includeInstance: boolean, msg: ListTopicSubscriptionsResponse): ListTopicSubscriptionsResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ListTopicSubscriptionsResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ListTopicSubscriptionsResponse; static deserializeBinaryFromReader(message: ListTopicSubscriptionsResponse, reader: jspb.BinaryReader): ListTopicSubscriptionsResponse; } export namespace ListTopicSubscriptionsResponse { export type AsObject = { subscriptionsList: Array<TopicSubscription.AsObject>, } } export class TopicSubscription extends jspb.Message { getPubsubName(): string; setPubsubName(value: string): TopicSubscription; getTopic(): string; setTopic(value: string): TopicSubscription; getMetadataMap(): jspb.Map<string, string>; clearMetadataMap(): void; hasRoutes(): boolean; clearRoutes(): void; getRoutes(): TopicRoutes | undefined; setRoutes(value?: TopicRoutes): TopicSubscription; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): TopicSubscription.AsObject; static toObject(includeInstance: boolean, msg: TopicSubscription): TopicSubscription.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: TopicSubscription, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): TopicSubscription; static deserializeBinaryFromReader(message: TopicSubscription, reader: jspb.BinaryReader): TopicSubscription; } export namespace TopicSubscription { export type AsObject = { pubsubName: string, topic: string, metadataMap: Array<[string, string]>, routes?: TopicRoutes.AsObject, } } export class TopicRoutes extends jspb.Message { clearRulesList(): void; getRulesList(): Array<TopicRule>; setRulesList(value: Array<TopicRule>): TopicRoutes; addRules(value?: TopicRule, index?: number): TopicRule; getDefault(): string; setDefault(value: string): TopicRoutes; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): TopicRoutes.AsObject; static toObject(includeInstance: boolean, msg: TopicRoutes): TopicRoutes.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: TopicRoutes, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): TopicRoutes; static deserializeBinaryFromReader(message: TopicRoutes, reader: jspb.BinaryReader): TopicRoutes; } export namespace TopicRoutes { export type AsObject = { rulesList: Array<TopicRule.AsObject>, pb_default: string, } } export class TopicRule extends jspb.Message { getMatch(): string; setMatch(value: string): TopicRule; getPath(): string; setPath(value: string): TopicRule; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): TopicRule.AsObject; static toObject(includeInstance: boolean, msg: TopicRule): TopicRule.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: TopicRule, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): TopicRule; static deserializeBinaryFromReader(message: TopicRule, reader: jspb.BinaryReader): TopicRule; } export namespace TopicRule { export type AsObject = { match: string, path: string, } } export class ListInputBindingsResponse extends jspb.Message { clearBindingsList(): void; getBindingsList(): Array<string>; setBindingsList(value: Array<string>): ListInputBindingsResponse; addBindings(value: string, index?: number): string; serializeBinary(): Uint8Array; toObject(includeInstance?: boolean): ListInputBindingsResponse.AsObject; static toObject(includeInstance: boolean, msg: ListInputBindingsResponse): ListInputBindingsResponse.AsObject; static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>}; static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>}; static serializeBinaryToWriter(message: ListInputBindingsResponse, writer: jspb.BinaryWriter): void; static deserializeBinary(bytes: Uint8Array): ListInputBindingsResponse; static deserializeBinaryFromReader(message: ListInputBindingsResponse, reader: jspb.BinaryReader): ListInputBindingsResponse; } export namespace ListInputBindingsResponse { export type AsObject = { bindingsList: Array<string>, } }
the_stack
import type {Options} from "../src/Options"; import { CREATE_STAR_EXPORT_PREFIX, ESMODULE_PREFIX, IMPORT_DEFAULT_PREFIX, IMPORT_WILDCARD_PREFIX, JSX_PREFIX, OPTIONAL_CHAIN_PREFIX, } from "./prefixes"; import {assertResult, devProps} from "./util"; function assertTypeScriptResult( code: string, expectedResult: string, options: Partial<Options> = {}, ): void { assertResult(code, expectedResult, {transforms: ["jsx", "imports", "typescript"], ...options}); } function assertTypeScriptESMResult( code: string, expectedResult: string, options: Partial<Options> = {}, ): void { assertResult(code, expectedResult, {transforms: ["jsx", "typescript"], ...options}); } function assertTypeScriptImportResult( code: string, {expectedCJSResult, expectedESMResult}: {expectedCJSResult: string; expectedESMResult: string}, ): void { assertTypeScriptResult(code, expectedCJSResult); assertTypeScriptESMResult(code, expectedESMResult); } describe("typescript transform", () => { it("removes type assertions using `as`", () => { assertTypeScriptResult( ` const x = 0; console.log(x as string); `, `"use strict"; const x = 0; console.log(x ); `, ); }); it("properly handles variables named 'as'", () => { assertTypeScriptResult( ` const as = "Hello"; console.log(as); `, `"use strict"; const as = "Hello"; console.log(as); `, ); }); it("removes access modifiers from class methods and fields", () => { assertTypeScriptResult( ` class A { private b: number; public c(): string { return "hi"; } } `, `"use strict"; class A { c() { return "hi"; } } `, ); }); it("handles class field assignment with an existing constructor", () => { assertTypeScriptResult( ` class A { x = 1; constructor() { this.y = 2; } } `, `"use strict"; class A { __init() {this.x = 1} constructor() {;A.prototype.__init.call(this); this.y = 2; } } `, ); }); it("handles class field assignment after a constructor with super", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super(a); } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super(a);A.prototype.__init.call(this);; } } `, ); }); it("handles class field assignment after a constructor with multiple super calls", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super(a); super(b); } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super(a);A.prototype.__init.call(this);; super(b); } } `, ); }); it("handles class field assignment after a constructor with super and super method call", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super(a); super.b(); } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super(a);A.prototype.__init.call(this);; super.b(); } } `, ); }); it("handles class field assignment after a constructor with invalid super method before super call", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super.b(); super(a); } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super.b(); super(a);A.prototype.__init.call(this);; } } `, ); }); it("handles class field assignment after a constructor with super prop", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super(); super.a; super.b = 1; } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super();A.prototype.__init.call(this);; super.a; super.b = 1; } } `, ); }); it("handles class field assignment after a constructor with invalid super prop before super call", () => { assertTypeScriptResult( ` class A extends B { x = 1; constructor(a) { super.a; super.b = 1; super(); } } `, `"use strict"; class A extends B { __init() {this.x = 1} constructor(a) { super.a; super.b = 1; super();A.prototype.__init.call(this);; } } `, ); }); it("handles class field assignment with no constructor", () => { assertTypeScriptResult( ` class A { x = 1; } `, `"use strict"; class A {constructor() { A.prototype.__init.call(this); } __init() {this.x = 1} } `, ); }); it("handles class field assignment with no constructor in a subclass", () => { assertTypeScriptResult( ` class A extends B { x = 1; } `, `"use strict"; class A extends B {constructor(...args) { super(...args); A.prototype.__init.call(this); } __init() {this.x = 1} } `, ); }); it("does not generate a conflicting name in a generated constructor", () => { assertTypeScriptResult( ` class A extends B { args = 1; } `, `"use strict"; class A extends B {constructor(...args2) { super(...args2); A.prototype.__init.call(this); } __init() {this.args = 1} } `, ); }); it("handles readonly constructor initializers", () => { assertTypeScriptResult( ` class A { constructor(readonly x: number) { } } `, `"use strict"; class A { constructor( x) {;this.x = x; } } `, ); }); it("removes non-null assertion operator but not negation operator", () => { assertTypeScriptResult( ` const x = 1!; const y = x!; const z = !x; const a = (x)!(y); const b = x + !y; `, `"use strict"; const x = 1; const y = x; const z = !x; const a = (x)(y); const b = x + !y; `, ); }); it("handles static class methods", () => { assertTypeScriptResult( ` export default class Foo { static run(): Result { } } `, `"use strict";${ESMODULE_PREFIX} class Foo { static run() { } } exports.default = Foo; `, ); }); it("handles async class methods", () => { assertTypeScriptResult( ` export default class Foo { async run(): Promise<Result> { } } `, `"use strict";${ESMODULE_PREFIX} class Foo { async run() { } } exports.default = Foo; `, ); }); it("handles type predicates", () => { assertTypeScriptResult( ` function foo(x: any): x is number { return x === 0; } `, `"use strict"; function foo(x) { return x === 0; } `, ); }); it("handles type predicates involving this", () => { assertTypeScriptResult( ` class A { foo(): this is B { return false; } } `, `"use strict"; class A { foo() { return false; } } `, ); }); it("export default functions with type parameters", () => { assertTypeScriptResult( ` export default function flatMap<T, U>(list: Array<T>, map: (element: T) => Array<U>): Array<U> { return list.reduce((memo, item) => memo.concat(map(item)), [] as Array<U>); } `, `"use strict";${ESMODULE_PREFIX} function flatMap(list, map) { return list.reduce((memo, item) => memo.concat(map(item)), [] ); } exports.default = flatMap; `, ); }); it("handles interfaces using `extends`", () => { assertTypeScriptResult( ` export interface A extends B { } `, `"use strict"; `, ); }); it("removes non-bare import statements consisting of only types", () => { assertTypeScriptResult( ` import A from 'a'; import {default as B} from 'b'; import 'c'; import D from 'd'; import 'd'; import E from 'e'; function f(a: A): boolean { return a instanceof A; } function g(b: B): boolean { return true; } `, `"use strict";${IMPORT_DEFAULT_PREFIX} var _a = require('a'); var _a2 = _interopRequireDefault(_a); require('c'); var _d = require('d'); var _d2 = _interopRequireDefault(_d); function f(a) { return a instanceof _a2.default; } function g(b) { return true; } `, ); }); it("allows class fields with keyword names", () => { assertTypeScriptResult( ` class A { readonly function: number; f: any = function() {}; } `, `"use strict"; class A {constructor() { A.prototype.__init.call(this); } __init() {this.f = function() {}} } `, ); }); it("allows `export abstract class` syntax", () => { assertTypeScriptResult( ` export abstract class A {} `, `"use strict";${ESMODULE_PREFIX} class A {} exports.A = A; `, ); }); it("handles type predicates when processing arrow functions", () => { assertTypeScriptResult( ` values.filter((node): node is Node => node !== null); `, `"use strict"; values.filter((node) => node !== null); `, ); }); it("allows an explicit type parameter at function invocation time", () => { assertTypeScriptResult( ` const f = f<number>(y); values.filter<Node>((node): node is Node => node !== null); const c = new Cache<number>(); `, `"use strict"; const f = f(y); values.filter((node) => node !== null); const c = new Cache(); `, ); }); it("allows computed field names", () => { assertTypeScriptResult( ` class A { [a + b] = 3; 0 = 1; "Hello, world" = 2; } `, `"use strict"; class A {constructor() { A.prototype.__init.call(this);A.prototype.__init2.call(this);A.prototype.__init3.call(this); } __init() {this[a + b] = 3} __init2() {this[0] = 1} __init3() {this["Hello, world"] = 2} } `, ); }); it("allows simple enums", () => { assertTypeScriptResult( ` enum Foo { A, B, C } `, `"use strict"; var Foo; (function (Foo) { const A = 0; Foo[Foo["A"] = A] = "A"; const B = A + 1; Foo[Foo["B"] = B] = "B"; const C = B + 1; Foo[Foo["C"] = C] = "C"; })(Foo || (Foo = {})); `, ); }); it("allows simple string enums", () => { assertTypeScriptResult( ` enum Foo { A = "eh", B = "bee", C = "sea", } `, `"use strict"; var Foo; (function (Foo) { const A = "eh"; Foo["A"] = A; const B = "bee"; Foo["B"] = B; const C = "sea"; Foo["C"] = C; })(Foo || (Foo = {})); `, ); }); it("handles complex enum cases", () => { assertTypeScriptResult( ` enum Foo { A = 15.5, "Hello world" = A / 2, "", "D" = "foo".length, E = D / D, "debugger" = 4, default = 7, "!" = E << E, "\\n", ",", "'", "f f" = "g g" } `, `"use strict"; var Foo; (function (Foo) { const A = 15.5; Foo[Foo["A"] = A] = "A"; Foo[Foo["Hello world"] = A / 2] = "Hello world"; Foo[Foo[""] = Foo["Hello world"] + 1] = ""; const D = "foo".length; Foo[Foo["D"] = D] = "D"; const E = D / D; Foo[Foo["E"] = E] = "E"; Foo[Foo["debugger"] = 4] = "debugger"; Foo[Foo["default"] = 7] = "default"; Foo[Foo["!"] = E << E] = "!"; Foo[Foo["\\n"] = Foo["!"] + 1] = "\\n"; Foo[Foo[","] = Foo["\\n"] + 1] = ","; Foo[Foo["'"] = Foo[","] + 1] = "'"; Foo["f f"] = "g g"; })(Foo || (Foo = {})); `, ); }); it("handles reserved literals when transforming enums", () => { assertTypeScriptESMResult( ` enum Foo { true, false, null, undefined } `, ` var Foo; (function (Foo) { Foo[Foo["true"] = 0] = "true"; Foo[Foo["false"] = Foo["true"] + 1] = "false"; Foo[Foo["null"] = Foo["false"] + 1] = "null"; const undefined = Foo["null"] + 1; Foo[Foo["undefined"] = undefined] = "undefined"; })(Foo || (Foo = {})); `, ); }); it("removes functions without bodies", () => { assertTypeScriptResult( ` function foo(x: number); export function bar(s: string); function foo(x: any) { console.log(x); } `, `"use strict"; function foo(x) { console.log(x); } `, ); }); it("handles and removes `declare module` syntax", () => { assertTypeScriptResult( ` declare module "builtin-modules" { let result: string[]; export = result; } `, `"use strict"; `, ); }); it("handles and removes `declare module` syntax with an identifier", () => { assertTypeScriptResult( ` declare module Builtins { let result: string[]; export = result; } `, `"use strict"; `, ); }); it("handles and removes `declare global` syntax", () => { assertTypeScriptResult( ` declare global { } `, `"use strict"; `, ); }); it("handles and removes `export declare class` syntax", () => { assertTypeScriptResult( ` export declare class Foo { } `, `"use strict"; `, ); }); it("allows a parameter named declare", () => { assertTypeScriptResult( ` function foo(declare: boolean): string { return "Hello!"; } `, `"use strict"; function foo(declare) { return "Hello!"; } `, ); }); it("properly allows modifier names as params", () => { assertTypeScriptResult( ` class Foo { constructor(set, readonly) {} constructor(set: any, readonly: boolean) {} } `, `"use strict"; class Foo { constructor(set, readonly) {} constructor(set, readonly) {} } `, ); }); it("properly handles method parameters named readonly", () => { assertTypeScriptResult( ` class Foo { bar(readonly: number) { console.log(readonly); } } `, `"use strict"; class Foo { bar(readonly) { console.log(readonly); } } `, ); }); it("handles export default abstract class", () => { assertTypeScriptResult( ` export default abstract class Foo { } `, `"use strict";${ESMODULE_PREFIX} class Foo { } exports.default = Foo; `, ); }); it("allows calling a function imported via `import *` with TypeScript enabled", () => { assertTypeScriptResult( ` import * as f from './myFunc'; console.log(f()); `, `"use strict";${IMPORT_WILDCARD_PREFIX} var _myFunc = require('./myFunc'); var f = _interopRequireWildcard(_myFunc); console.log(f()); `, ); }); it("treats const enums as regular enums", () => { assertTypeScriptResult( ` const enum A { Foo, Bar, } `, `"use strict"; var A; (function (A) { const Foo = 0; A[A["Foo"] = Foo] = "Foo"; const Bar = Foo + 1; A[A["Bar"] = Bar] = "Bar"; })(A || (A = {})); `, ); }); it("allows `export enum`", () => { assertTypeScriptResult( ` export enum A { Foo, Bar, } `, `"use strict";${ESMODULE_PREFIX} var A; (function (A) { const Foo = 0; A[A["Foo"] = Foo] = "Foo"; const Bar = Foo + 1; A[A["Bar"] = Bar] = "Bar"; })(A || (exports.A = A = {})); `, ); }); it("allows exported const enums", () => { assertTypeScriptResult( ` export const enum A { Foo, Bar, } `, `"use strict";${ESMODULE_PREFIX} var A; (function (A) { const Foo = 0; A[A["Foo"] = Foo] = "Foo"; const Bar = Foo + 1; A[A["Bar"] = Bar] = "Bar"; })(A || (exports.A = A = {})); `, ); }); it("properly handles simple abstract classes", () => { assertTypeScriptResult( ` abstract class A { } `, `"use strict"; class A { } `, ); }); it("properly handles exported abstract classes with abstract methods", () => { assertTypeScriptResult( ` export abstract class A { abstract a(); b(): void { console.log("hello"); } } `, `"use strict";${ESMODULE_PREFIX} class A { b() { console.log("hello"); } } exports.A = A; `, ); }); it("does not prune imports that are then exported", () => { assertTypeScriptResult( ` import A from 'a'; export {A}; `, `"use strict";${ESMODULE_PREFIX}${IMPORT_DEFAULT_PREFIX} var _a = require('a'); var _a2 = _interopRequireDefault(_a); exports.A = _a2.default; `, ); }); it("allows TypeScript CJS-style imports and exports", () => { assertTypeScriptResult( ` import a = require('a'); console.log(a); export = 3; `, `"use strict"; const a = require('a'); console.log(a); module.exports = 3; `, ); }); it("allows this types in functions", () => { assertTypeScriptResult( ` function foo(this: number, x: number): number { return this + x; } `, `"use strict"; function foo( x) { return this + x; } `, ); }); it("supports export * in TypeScript", () => { assertTypeScriptResult( ` export * from './MyVars'; `, `"use strict";${ESMODULE_PREFIX}${CREATE_STAR_EXPORT_PREFIX} var _MyVars = require('./MyVars'); _createStarExport(_MyVars); `, ); }); it("properly handles access modifiers on constructors", () => { assertTypeScriptResult( ` class A { x = 1; public constructor() { } } `, `"use strict"; class A { __init() {this.x = 1} constructor() {;A.prototype.__init.call(this); } } `, ); }); it("allows old-style type assertions in non-JSX TypeScript", () => { assertResult( ` const x = <number>3; `, `"use strict"; const x = 3; `, {transforms: ["typescript", "imports"]}, ); }); it("properly handles new declarations within interfaces", () => { assertTypeScriptResult( ` interface Foo { new(): Foo; } `, `"use strict"; `, ); }); it("handles code with an index signature", () => { assertTypeScriptResult( ` const o: {[k: string]: number} = { a: 1, b: 2, } `, `"use strict"; const o = { a: 1, b: 2, } `, ); }); it("handles assert and assign syntax", () => { assertTypeScriptResult( ` (a as b) = c; `, `"use strict"; (a ) = c; `, ); }); it("handles possible JSX ambiguities", () => { assertTypeScriptResult( ` f<T>(); new C<T>(); type A = T<T>; `, `"use strict"; f(); new C(); `, ); }); it("handles the 'unique' contextual keyword", () => { assertTypeScriptResult( ` let y: unique symbol; `, `"use strict"; let y; `, ); }); it("handles async arrow functions with rest params", () => { assertTypeScriptResult( ` const foo = async (...args: any[]) => {} const bar = async (...args?: any[]) => {} `, `"use strict"; const foo = async (...args) => {} const bar = async (...args) => {} `, ); }); it("handles conditional types", () => { assertTypeScriptResult( ` type A = B extends C ? D : E; `, `"use strict"; `, ); }); it("handles the 'infer' contextual keyword in types", () => { assertTypeScriptResult( ` type Element<T> = T extends (infer U)[] ? U : T; `, `"use strict"; `, ); }); it("handles definite assignment assertions in classes", () => { assertTypeScriptResult( ` class A { foo!: number; getFoo(): number { return foo; } } `, `"use strict"; class A { getFoo() { return foo; } } `, ); }); it("handles definite assignment assertions in classes with disableESTransforms", () => { assertTypeScriptResult( ` class A { foo!: number; } `, `"use strict"; class A { foo; } `, {disableESTransforms: true}, ); }); it("handles definite assignment assertions on variables", () => { assertTypeScriptResult( ` let x!: number; initX(); console.log(x + 1); `, `"use strict"; let x; initX(); console.log(x + 1); `, ); }); it("handles definite assignment assertions on private fields in classes", () => { assertTypeScriptResult( ` class A { #a!: number; } `, `"use strict"; class A { #a; } `, ); }); it("handles definite assignment assertions on private fields in classes with disableESTransforms", () => { assertTypeScriptResult( ` class A { #a!: number; } `, `"use strict"; class A { #a; } `, {disableESTransforms: true}, ); }); it("handles mapped type modifiers", () => { assertTypeScriptResult( ` let map: { +readonly [P in string]+?: number; }; let map2: { -readonly [P in string]-?: number }; `, `"use strict"; let map; let map2; `, ); }); it("does not prune imported identifiers referenced by JSX", () => { assertTypeScriptResult( ` import React from 'react'; import Foo from './Foo'; import Bar from './Bar'; import someProp from './someProp'; import lowercaseComponent from './lowercaseComponent'; import div from './div'; const x: Bar = 3; function render(): JSX.Element { return ( <div> <Foo.Bar someProp="a" /> <lowercaseComponent.Thing /> </div> ); } `, `"use strict";${JSX_PREFIX}${IMPORT_DEFAULT_PREFIX} var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _Foo = require('./Foo'); var _Foo2 = _interopRequireDefault(_Foo); var _lowercaseComponent = require('./lowercaseComponent'); var _lowercaseComponent2 = _interopRequireDefault(_lowercaseComponent); const x = 3; function render() { return ( _react2.default.createElement('div', {__self: this, __source: {fileName: _jsxFileName, lineNumber: 13}} , _react2.default.createElement(_Foo2.default.Bar, { someProp: "a", __self: this, __source: {fileName: _jsxFileName, lineNumber: 14}} ) , _react2.default.createElement(_lowercaseComponent2.default.Thing, {__self: this, __source: {fileName: _jsxFileName, lineNumber: 15}} ) ) ); } `, ); }); it("does not elide a React import when the file contains a JSX fragment", () => { assertTypeScriptResult( ` import React from 'react'; function render(): JSX.Element { return <>Hello</>; } `, `"use strict";${IMPORT_DEFAULT_PREFIX} var _react = require('react'); var _react2 = _interopRequireDefault(_react); function render() { return _react2.default.createElement(_react2.default.Fragment, null, "Hello"); } `, ); }); it("correctly takes JSX pragmas into account avoiding JSX import elision", () => { assertResult( ` import {A, B, C, D} from 'foo'; function render(): JSX.Element { return <>Hello</>; } `, ` import {A, C,} from 'foo'; function render() { return A.B(C.D, null, "Hello"); } `, {transforms: ["typescript", "jsx"], jsxPragma: "A.B", jsxFragmentPragma: "C.D"}, ); }); it("correctly takes JSX pragmas into account avoiding JSX import elision with fragments unused", () => { assertResult( ` import {A, B, C, D} from 'foo'; function render(): JSX.Element { return <span />; } `, `const _jsxFileName = ""; import {A,} from 'foo'; function render() { return A.B('span', {${devProps(4)}} ); } `, {transforms: ["typescript", "jsx"], jsxPragma: "A.B", jsxFragmentPragma: "C.D"}, ); }); it("handles TypeScript exported enums in ESM mode", () => { assertTypeScriptESMResult( ` export enum Foo { X = "Hello", } `, ` export var Foo; (function (Foo) { const X = "Hello"; Foo["X"] = X; })(Foo || (Foo = {})); `, ); }); it("changes import = require to plain require in ESM mode", () => { assertTypeScriptESMResult( ` import a = require('a'); a(); `, ` const a = require('a'); a(); `, ); }); it("properly transforms JSX in ESM mode", () => { assertTypeScriptESMResult( ` import React from 'react'; const x = <Foo />; `, `${JSX_PREFIX} import React from 'react'; const x = React.createElement(Foo, {__self: this, __source: {fileName: _jsxFileName, lineNumber: 3}} ); `, ); }); it("properly prunes TypeScript imported names", () => { assertTypeScriptESMResult( ` import a, {n as b, m as c, d} from './e'; import f, * as g from './h'; a(); const x: b = 3; const y = c + 1; `, ` import a, { m as c,} from './e'; a(); const x = 3; const y = c + 1; `, ); }); it("properly handles optional class fields with default values", () => { assertTypeScriptResult( ` class A { n?: number = 3; } `, `"use strict"; class A {constructor() { A.prototype.__init.call(this); } __init() {this.n = 3} } `, ); }); // TODO: TypeScript 2.9 makes this required, so we can drop support for this syntax when we don't // need to support older versions of TypeScript. it("allows trailing commas after rest elements", () => { assertTypeScriptResult( ` function foo(a, ...b,) {} const {a, ...b,} = c; const [a, ...b,] = c; `, `"use strict"; function foo(a, ...b,) {} const {a, ...b,} = c; const [a, ...b,] = c; `, ); }); it("allows index signatures in classes", () => { assertTypeScriptResult( ` export class Foo { f() { } [name: string]: any; x = 1; } `, `"use strict";${ESMODULE_PREFIX} class Foo {constructor() { Foo.prototype.__init.call(this); } f() { } __init() {this.x = 1} } exports.Foo = Foo; `, ); }); it("allows destructured params in function types", () => { assertTypeScriptResult( ` const f: ({a}: {a: number}) => void = () => {}; const g: ([a]: Array<number>) => void = () => {}; const h: ({a: {b: [c]}}: any) => void = () => {}; const o: ({a: {b: c}}) = {}; `, `"use strict"; const f = () => {}; const g = () => {}; const h = () => {}; const o = {}; `, ); }); it("allows type arguments in JSX elements", () => { assertTypeScriptResult( ` const e1 = <Foo<number> x="1" /> const e2 = <Foo<string>><span>Hello</span></Foo> `, `"use strict";const _jsxFileName = ""; const e1 = React.createElement(Foo, { x: "1", __self: this, __source: {fileName: _jsxFileName, lineNumber: 2}} ) const e2 = React.createElement(Foo, {__self: this, __source: {fileName: _jsxFileName, lineNumber: 3}}, React.createElement('span', {__self: this, __source: {fileName: _jsxFileName, lineNumber: 3}}, "Hello")) `, ); }); it("allows type arguments tagged templates", () => { assertTypeScriptResult( ` f<T>\`\`; new C<T> \`\`; `, `"use strict"; f\`\`; new C \`\`; `, ); }); it("allows export default interface", () => { assertTypeScriptResult( ` export default interface A {} `, `"use strict"; `, ); }); it("parses type arguments on decorators", () => { assertTypeScriptResult( ` @decorator<string>() class Test {} `, `"use strict"; @decorator() class Test {} `, ); }); it("properly parses tuple types with optional values", () => { assertTypeScriptResult( ` let x: [string, number?, (string | number)?]; `, `"use strict"; let x; `, ); }); it("allows a rest element on a tuple type", () => { assertTypeScriptResult( ` let x: [string, ...number[]]; `, `"use strict"; let x; `, ); }); it("allows rest elements in the middle of tuple types", () => { assertTypeScriptResult( ` let x: [...number[], string]; let y: [...[number, string], string]; `, `"use strict"; let x; let y; `, ); }); it("allows overloads for constructors", () => { assertTypeScriptResult( ` class A { constructor(s: string) constructor(n: number) constructor(sn: string | number) {} } `, `"use strict"; class A { constructor(sn) {} } `, ); }); it("properly elides CJS imports that only have value references in shadowed names", () => { assertTypeScriptResult( ` import T from './T'; const x: T = 3; function foo() { let T = 3; console.log(T); } `, `"use strict";${IMPORT_DEFAULT_PREFIX} const x = 3; function foo() { let T = 3; console.log(T); } `, ); }); it("properly elides ESM imports that only have value references in shadowed names", () => { assertTypeScriptESMResult( ` import T, {a as b, c} from './T'; import {d, e} from './foo'; const x: T = 3; console.log(e); function foo() { let T = 3, b = 4, c = 5, d = 6; console.log(T, b, c, d); } `, ` import { e} from './foo'; const x = 3; console.log(e); function foo() { let T = 3, b = 4, c = 5, d = 6; console.log(T, b, c, d); } `, ); }); it("handles import() types", () => { assertTypeScriptESMResult( ` type T1 = import("./foo"); type T2 = typeof import("./bar"); type T3 = import("./bar").Point; type T4 = import("./utils").HashTable<number>; `, ` `, ); }); it("properly compiles class fields with extends in a type parameter", () => { assertTypeScriptESMResult( ` class A<B extends C> { x = 1; } `, ` class A {constructor() { A.prototype.__init.call(this); } __init() {this.x = 1} } `, ); }); it("properly handles a declaration that looks like an assignment to an export (#401)", () => { assertTypeScriptResult( ` export class Foo {} let foo: Foo = new Foo(); `, `"use strict";${ESMODULE_PREFIX} class Foo {} exports.Foo = Foo; let foo = new Foo(); `, ); }); it("properly handles comparison operators that look like JSX or generics (#408)", () => { assertTypeScriptResult( ` a < b > c `, `"use strict"; a < b > c `, ); }); it("elides type-only exports", () => { assertTypeScriptImportResult( ` type T = number; type U = number; export {T, U as w}; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} `, expectedESMResult: ` export {}; `, }, ); }); it("preserves non-type exports in ESM mode", () => { assertTypeScriptImportResult( ` const T = 3; export {T as u}; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} const T = 3; exports.u = T; `, expectedESMResult: ` const T = 3; export {T as u}; `, }, ); }); it("preserves type-and-non-type exports in ESM mode", () => { assertTypeScriptImportResult( ` type T = number; const T = 3; export {T}; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} const T = 3; exports.T = T; `, expectedESMResult: ` const T = 3; export {T}; `, }, ); }); it("elides unknown and type-only exports in CJS, and only elides type-only exports in ESM", () => { assertTypeScriptImportResult( ` import A, {b, c as d} from './foo'; enum E { X = 1 } class F {} interface G {} function h() {} import I = require('./i'); type J = number; export {A, b, c, d, E, F, G, h, I, J}; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX}${IMPORT_DEFAULT_PREFIX} var _foo = require('./foo'); var _foo2 = _interopRequireDefault(_foo); var E; (function (E) { const X = 1; E[E["X"] = X] = "X"; })(E || (E = {})); class F {} function h() {} const I = exports.I = require('./i'); exports.A = _foo2.default; exports.b = _foo.b; exports.d = _foo.c; exports.E = E; exports.F = F; exports.h = h; exports.I = I; `, expectedESMResult: ` import A, {b, c as d} from './foo'; var E; (function (E) { const X = 1; E[E["X"] = X] = "X"; })(E || (E = {})); class F {} function h() {} const I = require('./i'); export {A, b, c, d, E, F, h, I,}; `, }, ); }); it("preserves exported variables assigned with a destructure", () => { assertTypeScriptImportResult( ` const o = {x: 1}; const {x} = o; const {x: y} = o; type z = number; export {x, y, z}; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} const o = {x: 1}; const {x} = o; const {x: y} = o; exports.x = x; exports.y = y; `, expectedESMResult: ` const o = {x: 1}; const {x} = o; const {x: y} = o; export {x, y,}; `, }, ); }); it("elides export default when the value is an identifier declared as a type", () => { assertTypeScriptImportResult( ` type T = number; export default T; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} ; `, expectedESMResult: ` ; `, }, ); }); it("does not elide export default when the value is a complex expression", () => { assertTypeScriptImportResult( ` type T = number; export default T | U; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} exports. default = T | U; `, expectedESMResult: ` export default T | U; `, }, ); }); it("does not elide export default when the value is used as a binding within a type", () => { assertTypeScriptImportResult( ` type f = (x: number) => void; export default x; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} exports. default = x; `, expectedESMResult: ` export default x; `, }, ); }); it("preserves export default when the value is an unknown identifier", () => { assertTypeScriptImportResult( ` export default window; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} exports. default = window; `, expectedESMResult: ` export default window; `, }, ); }); it("preserves export default when the value is a plain variable", () => { assertTypeScriptImportResult( ` const x = 1; export default x; `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} const x = 1; exports. default = x; `, expectedESMResult: ` const x = 1; export default x; `, }, ); }); it("elides unused import = statements", () => { assertTypeScriptImportResult( ` import A = require('A'); import B = require('B'); import C = A.C; B(); const c: C = 2; `, { expectedCJSResult: `"use strict"; ; const B = require('B'); ; B(); const c = 2; `, expectedESMResult: ` ; const B = require('B'); ; B(); const c = 2; `, }, ); }); // We don't support this for now since it needs a more complex implementation than we have // anywhere else, and ideally you would just write `const B = A.B;`, which works. it.skip("handles transitive references when eliding import = statements", () => { assertTypeScriptImportResult( ` import A from 'A'; import B = A.B; B(); `, { expectedCJSResult: `"use strict";${ESMODULE_PREFIX} const A_1 = require("A"); const B = A_1.default.B; B(); `, expectedESMResult: ` import A from 'A'; const B = A.B; B(); `, }, ); }); it("handles newlines before class declarations", () => { assertTypeScriptResult( ` abstract class A {} declare class B {} declare const x: number, y: string; declare const { x, y }: { x: number, y: number }; declare interface I {} declare let x; declare var x; declare var x: any; module Foo {} namespace Foo {} type Foo = string; `, `"use strict"; abstract class A {} declare class B {} declare const x, y; declare const { x, y }; declare declare let x; declare var x; declare var x; module Foo {} namespace Foo {} type Foo = string; `, ); }); it("handles const contexts", () => { assertTypeScriptResult( ` let x = 5 as const; `, `"use strict"; let x = 5 ; `, ); }); it("handles the readonly type modifier", () => { assertTypeScriptResult( ` let z: readonly number[]; let z1: readonly [number, number]; `, `"use strict"; let z; let z1; `, ); }); it("allows template literal syntax for type literals", () => { assertTypeScriptResult( ` let x: \`foo\`; `, `"use strict"; let x; `, ); }); it("allows template literal substitutions in literal string types", () => { assertTypeScriptResult( ` type Color = "red" | "blue"; type Quantity = "one" | "two"; type SeussFish = \`\${Quantity | Color} fish\`; const fish: SeussFish = "blue fish"; `, `"use strict"; const fish = "blue fish"; `, ); }); it("allows complex template literal substitutions in literal string types", () => { // Uppercase<T> is an example of a type expression that isn't a valid value // expression, ensuring that we're using a type parser for the substitution. assertTypeScriptResult( ` type EnthusiasticGreeting<T extends string> = \`\${Uppercase<T>}\`; `, `"use strict"; `, ); }); it("allows bigint literal syntax for type literals", () => { assertTypeScriptResult( ` let x: 10n; type T = { n: 20n, m: -30n }; function f(arg: [40n]): 50n[] {}; `, `"use strict"; let x; function f(arg) {}; `, ); }); it("allows decimal literal syntax for type literals", () => { assertTypeScriptResult( ` let x: 10m; type T = { n: 20m, m: -30m }; function f(arg: [40m]): 50m[] {}; `, `"use strict"; let x; function f(arg) {}; `, ); }); it("allows private field syntax", () => { assertTypeScriptResult( ` class Foo { readonly #x: number; readonly #y: number; } `, `"use strict"; class Foo { #x; #y; } `, ); }); it("allows assertion signature syntax", () => { assertTypeScriptResult( ` function assert(condition: any, msg?: string): asserts condition { if (!condition) { throw new AssertionError(msg) } } `, `"use strict"; function assert(condition, msg) { if (!condition) { throw new AssertionError(msg) } } `, ); }); it("allows assertion signature syntax with is", () => { assertTypeScriptResult( ` function assertIsDefined<T>(x: T): asserts x is NonNullable<T> { if (x == null) throw "oh no"; } `, `"use strict"; function assertIsDefined(x) { if (x == null) throw "oh no"; } `, ); }); it("allows assertion signature syntax using this", () => { assertTypeScriptResult( ` class Foo { isBar(): asserts this is Foo {} isBaz = (): asserts this is Foo => {} } `, `"use strict"; class Foo {constructor() { Foo.prototype.__init.call(this); } isBar() {} __init() {this.isBaz = () => {}} } `, ); }); it("does not get confused by a user-defined type guard on a variable called asserts", () => { assertTypeScriptResult( ` function checkIsDefined(asserts: any): asserts is NonNullable<T> { return false; } `, `"use strict"; function checkIsDefined(asserts) { return false; } `, ); }); it("does not get confused by a return type called asserts", () => { assertTypeScriptResult( ` function checkIsDefined(x: any): asserts { return false; } `, `"use strict"; function checkIsDefined(x) { return false; } `, ); }); it("correctly parses optional chain calls with type arguments", () => { assertTypeScriptResult( ` example.inner?.greet<string>() `, `"use strict";${OPTIONAL_CHAIN_PREFIX} _optionalChain([example, 'access', _ => _.inner, 'optionalAccess', _2 => _2.greet, 'call', _3 => _3()]) `, ); }); it("allows optional async methods", () => { assertTypeScriptResult( ` class A extends B { async method?(val: string): Promise<void>; } `, `"use strict"; class A extends B { } `, ); }); it("handles trailing commas at the end of tuple type with rest", () => { assertTypeScriptResult( ` let x: [string, ...string[],] `, `"use strict"; let x `, ); }); it("supports type arguments with optional chaining", () => { assertTypeScriptResult( ` const x = a.b?.<number>(); `, `"use strict";${OPTIONAL_CHAIN_PREFIX} const x = _optionalChain([a, 'access', _ => _.b, 'optionalCall', _2 => _2()]); `, ); }); it("parses and removes import type statements in CJS mode", () => { assertTypeScriptResult( ` import type foo from 'foo'; import bar from 'bar'; console.log(foo, bar); `, `"use strict";${IMPORT_DEFAULT_PREFIX} var _bar = require('bar'); var _bar2 = _interopRequireDefault(_bar); console.log(foo, _bar2.default); `, ); }); it("parses and removes named import type statements in CJS mode", () => { assertTypeScriptResult( ` import type {foo} from 'foo'; import {bar} from 'bar'; console.log(foo, bar); `, `"use strict"; var _bar = require('bar'); console.log(foo, _bar.bar); `, ); }); it("parses and removes import type statements in ESM mode", () => { assertTypeScriptESMResult( ` import type foo from 'foo'; import bar from 'bar'; console.log(foo, bar); `, ` import bar from 'bar'; console.log(foo, bar); `, ); }); it("parses and removes named import type statements in ESM mode", () => { assertTypeScriptESMResult( ` import type {foo} from 'foo'; import {bar} from 'bar'; console.log(foo, bar); `, ` import {bar} from 'bar'; console.log(foo, bar); `, ); }); it("parses and removes export type statements in CJS mode", () => { assertTypeScriptResult( ` import T from './T'; let x: T; export type {T}; `, `"use strict";${ESMODULE_PREFIX}${IMPORT_DEFAULT_PREFIX} var _T = require('./T'); var _T2 = _interopRequireDefault(_T); let x; ; `, ); }); it("parses and removes export type statements in ESM mode", () => { assertTypeScriptESMResult( ` import T from './T'; let x: T; export type {T}; `, ` import T from './T'; let x; ; `, ); }); it("parses and removes export type re-export statements in CJS mode", () => { assertTypeScriptResult( ` export type {T} from './T'; export type {T1 as TX, T2 as TY} from './OtherTs'; `, `"use strict";${ESMODULE_PREFIX} ; ; `, ); }); it("parses and removes export type re-export statements in ESM mode", () => { assertTypeScriptESMResult( ` export type {T} from './T'; export type {T1 as TX, T2 as TY} from './OtherTs'; `, ` ; ; `, ); }); it("properly handles default args in constructors", () => { assertTypeScriptResult( ` class Foo { constructor(p = -1) {} } `, `"use strict"; class Foo { constructor(p = -1) {} } `, ); }); it("properly emits assignments with multiple constructor initializers", () => { assertTypeScriptResult( ` class Foo { constructor(a: number, readonly b: number, private c: number) {} } `, `"use strict"; class Foo { constructor(a, b, c) {;this.b = b;this.c = c;} } `, ); }); it("properly removes class fields with declare", () => { assertTypeScriptResult( ` class Foo { declare a: number; public declare b: number; declare public c: number; static declare d: number; declare static e: number; declare public static f: number; public declare static g: number; public static declare h: number; constructor() { console.log('Hi'); } } `, `"use strict"; class Foo { constructor() { console.log('Hi'); } } `, ); }); it("properly removes types from catch clauses", () => { assertTypeScriptResult( ` try {} catch (e: unknown) {} try {} catch (e: string | [...number, string]) {} `, `"use strict"; try {} catch (e) {} try {} catch (e) {} `, ); }); it("properly removes labeled tuple types", () => { assertTypeScriptResult( ` type T1 = [x: number, y?: number, ...rest: number[]]; function f(args: [s?: string, ...ns: number[]]) {} `, `"use strict"; function f(args) {} `, ); }); it("properly handles a >= symbol after an `as` cast", () => { assertTypeScriptResult( ` const x: string | number = 1; if (x as number >= 5) {} `, `"use strict"; const x = 1; if (x >= 5) {} `, ); }); it("handles simple template literal interpolations in types", () => { assertTypeScriptResult( ` type A = \`make\${A | B}\`; `, `"use strict"; `, ); }); it("handles complex template literal interpolations in types", () => { assertTypeScriptResult( ` type A = \`foo\${{ [k: string]: number}}\`; `, `"use strict"; `, ); }); it("handles mapped type `as` clauses", () => { assertTypeScriptResult( ` type MappedTypeWithNewKeys<T> = { [K in keyof T as NewKeyType]: T[K] }; type RemoveKindField<T> = { [K in keyof T as Exclude<K, "kind">]: T[K] }; type PickByValueType<T, U> = { [K in keyof T as T[K] extends U ? K : never]: T[K] }; `, `"use strict"; `, ); }); it("handles an arrow function with typed destructured params", () => { assertTypeScriptResult( ` ( { a, b }: T, ): T => {}; `, `"use strict"; ( { a, b }, ) => {}; `, ); }); it("handles various forms of optional parameters in an interface", () => { assertTypeScriptResult( ` interface B { foo([]?): void; bar({}, []?): any; baz(a: string, b: number, []?): void; } `, `"use strict"; `, ); }); it("correctly handles methods and fields named declare", () => { assertTypeScriptResult( ` class A { declare() { } } class B { static declare() { } } class C { declare = 2; } `, `"use strict"; class A { declare() { } } class B { static declare() { } } class C {constructor() { C.prototype.__init.call(this); } __init() {this.declare = 2} } `, ); }); it("correctly handles field declarations after function overloads", () => { assertTypeScriptResult( ` class Class { method(a: number); method(a: unknown) {} declare field: number; } `, `"use strict"; class Class { method(a) {} } `, ); }); it("correctly transforms enum expressions", () => { assertTypeScriptResult( ` import A from './A'; enum E { Foo = A.Foo, Bar = A.Bar, } `, `"use strict";${IMPORT_DEFAULT_PREFIX} var _A = require('./A'); var _A2 = _interopRequireDefault(_A); var E; (function (E) { const Foo = _A2.default.Foo; E[E["Foo"] = Foo] = "Foo"; const Bar = _A2.default.Bar; E[E["Bar"] = Bar] = "Bar"; })(E || (E = {})); `, ); }); it("does not handle a module declaration split by newlines", () => { // See https://github.com/babel/babel/issues/12773 , the proper parsing of // this code is to treat each line as separate valid JS. assertTypeScriptESMResult( ` declare module "A" {} `, ` declare module "A" {} `, ); }); it("allows and removes namespace statements", () => { assertTypeScriptESMResult( ` namespace foo {} `, ` `, ); }); it("allows and removes export namespace statements", () => { assertTypeScriptESMResult( ` export namespace foo {} `, ` `, ); }); it("allows and removes module statements", () => { assertTypeScriptESMResult( ` module foo {} `, ` `, ); }); it("allows and removes export module statements", () => { assertTypeScriptESMResult( ` export module foo {} `, ` `, ); }); it("handles abstract constructor signatures", () => { assertTypeScriptESMResult( ` let x: abstract new () => void = X; `, ` let x = X; `, ); }); it("handles import type =", () => { assertTypeScriptESMResult( ` import type A = require("A"); `, ` ; `, ); }); it("handles importing an identifier named type", () => { assertTypeScriptESMResult( ` import type = require("A"); `, ` ; `, ); }); it("handles export import type =", () => { assertTypeScriptESMResult( ` export import type B = require("B"); `, ` ; `, ); }); it("allows static index signatures", () => { assertTypeScriptESMResult( ` class C { static [x: string]: any; } `, ` class C { } `, ); }); it("allows static index signatures with other modifiers", () => { assertTypeScriptESMResult( ` class C { static readonly [x: string]: any; } `, ` class C { } `, ); }); it("allows static index signatures not starting with static", () => { assertTypeScriptESMResult( ` class C { readonly static [x: string]: any; } `, ` class C { } `, ); }); it("allows and removes the override keyword on class methods", () => { assertTypeScriptESMResult( ` class A extends B { override method1(): void {} public override method2(): void {} override public method3(): void {} override field1 = 1; static override field2 = 2; } `, ` class A extends B {constructor(...args) { super(...args); A.prototype.__init.call(this); } method1() {} method2() {} method3() {} __init() {this.field1 = 1} static __initStatic() {this.field2 = 2} } A.__initStatic(); `, ); }); it("allows override on constructor params", () => { assertTypeScriptESMResult( ` class A extends B { constructor(override foo: string) { } } `, ` class A extends B { constructor( foo) {;this.foo = foo; } } `, ); }); it("allows getters and setters on interfaces and object types", () => { assertTypeScriptESMResult( ` interface A { get foo(): string; set foo(s: string); } type T = { get bar(): number; set bar(n: number); } `, ` `, ); }); it("allows keys named get and set", () => { assertTypeScriptESMResult( ` type T = { get: 3, set: 4, } `, ` `, ); }); it("transforms constructor initializers even with disableESTransforms", () => { assertTypeScriptESMResult( ` class A extends B { constructor(readonly x, private y = 2, z: number = 3) { console.log("Hello"); super(); console.log("World"); } } `, ` class A extends B { constructor( x, y = 2, z = 3) { console.log("Hello"); super();this.x = x;this.y = y;; console.log("World"); } } `, {disableESTransforms: true}, ); }); it("removes types from class fields with disableESTransforms", () => { assertTypeScriptESMResult( ` class A { x: number = 3; static y: string = "Hello"; z: boolean; static s: unknown; } `, ` class A { x = 3; static y = "Hello"; z; static s; } `, {disableESTransforms: true}, ); }); it("removes declare fields with disableESTransforms", () => { assertTypeScriptESMResult( ` class A { abstract readonly a: number = 3; declare b: string; declare static c: string; static declare d: string; } `, ` class A { a = 3; ; ; ; } `, {disableESTransforms: true}, ); }); });
the_stack
* A third-party license is embeded for some of the code in this file: * The tree layoutHelper implementation was originally copied from * "d3.js"(https://github.com/d3/d3-hierarchy) with * some modifications made for this project. * (see more details in the comment of the specific method below.) * The use of the source code of this file is also subject to the terms * and consitions of the licence of "d3.js" (BSD-3Clause, see * </licenses/LICENSE-d3>). */ /** * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing * the tree. */ import * as layout from '../../util/layout'; import { TreeNode } from '../../data/Tree'; import TreeSeriesModel from './TreeSeries'; import ExtensionAPI from '../../core/ExtensionAPI'; interface HierNode { defaultAncestor: TreeLayoutNode, ancestor: TreeLayoutNode, prelim: number, modifier: number, change: number, shift: number, i: number, thread: TreeLayoutNode } export interface TreeLayoutNode extends TreeNode { parentNode: TreeLayoutNode hierNode: HierNode children: TreeLayoutNode[] } /** * Initialize all computational message for following algorithm. */ export function init(inRoot: TreeNode) { const root = inRoot as TreeLayoutNode; root.hierNode = { defaultAncestor: null, ancestor: root, prelim: 0, modifier: 0, change: 0, shift: 0, i: 0, thread: null }; const nodes = [root]; let node; let children; while (node = nodes.pop()) { // jshint ignore:line children = node.children; if (node.isExpand && children.length) { const n = children.length; for (let i = n - 1; i >= 0; i--) { const child = children[i]; child.hierNode = { defaultAncestor: null, ancestor: child, prelim: 0, modifier: 0, change: 0, shift: 0, i: i, thread: null }; nodes.push(child); } } } } /** * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. * * Computes a preliminary x coordinate for node. Before that, this function is * applied recursively to the children of node, as well as the function * apportion(). After spacing out the children by calling executeShifts(), the * node is placed to the midpoint of its outermost children. */ export function firstWalk(node: TreeLayoutNode, separation: SeparationFunc) { const children = node.isExpand ? node.children : []; const siblings = node.parentNode.children; const subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null; if (children.length) { executeShifts(node); const midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2; if (subtreeW) { node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW); node.hierNode.modifier = node.hierNode.prelim - midPoint; } else { node.hierNode.prelim = midPoint; } } else if (subtreeW) { node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW); } node.parentNode.hierNode.defaultAncestor = apportion( node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation ); } /** * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. * * Computes all real x-coordinates by summing up the modifiers recursively. */ export function secondWalk(node: TreeLayoutNode) { const nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier; node.setLayout({x: nodeX}, true); node.hierNode.modifier += node.parentNode.hierNode.modifier; } export function separation(cb?: SeparationFunc) { return arguments.length ? cb : defaultSeparation; } /** * Transform the common coordinate to radial coordinate. */ export function radialCoordinate(rad: number, r: number) { rad -= Math.PI / 2; return { x: r * Math.cos(rad), y: r * Math.sin(rad) }; } /** * Get the layout position of the whole view. */ export function getViewRect(seriesModel: TreeSeriesModel, api: ExtensionAPI) { return layout.getLayoutRect( seriesModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() } ); } /** * All other shifts, applied to the smaller subtrees between w- and w+, are * performed by this function. * * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. */ function executeShifts(node: TreeLayoutNode) { const children = node.children; let n = children.length; let shift = 0; let change = 0; while (--n >= 0) { const child = children[n]; child.hierNode.prelim += shift; child.hierNode.modifier += shift; change += child.hierNode.change; shift += child.hierNode.shift + change; } } /** * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. * * The core of the algorithm. Here, a new subtree is combined with the * previous subtrees. Threads are used to traverse the inside and outside * contours of the left and right subtree up to the highest common level. * Whenever two nodes of the inside contours conflict, we compute the left * one of the greatest uncommon ancestors using the function nextAncestor() * and call moveSubtree() to shift the subtree and prepare the shifts of * smaller subtrees. Finally, we add a new thread (if necessary). */ function apportion( subtreeV: TreeLayoutNode, subtreeW: TreeLayoutNode, ancestor: TreeLayoutNode, separation: SeparationFunc ): TreeLayoutNode { if (subtreeW) { let nodeOutRight = subtreeV; let nodeInRight = subtreeV; let nodeOutLeft = nodeInRight.parentNode.children[0]; let nodeInLeft = subtreeW; let sumOutRight = nodeOutRight.hierNode.modifier; let sumInRight = nodeInRight.hierNode.modifier; let sumOutLeft = nodeOutLeft.hierNode.modifier; let sumInLeft = nodeInLeft.hierNode.modifier; while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) { nodeOutRight = nextRight(nodeOutRight); nodeOutLeft = nextLeft(nodeOutLeft); nodeOutRight.hierNode.ancestor = subtreeV; const shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight); if (shift > 0) { moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift); sumInRight += shift; sumOutRight += shift; } sumInLeft += nodeInLeft.hierNode.modifier; sumInRight += nodeInRight.hierNode.modifier; sumOutRight += nodeOutRight.hierNode.modifier; sumOutLeft += nodeOutLeft.hierNode.modifier; } if (nodeInLeft && !nextRight(nodeOutRight)) { nodeOutRight.hierNode.thread = nodeInLeft; nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight; } if (nodeInRight && !nextLeft(nodeOutLeft)) { nodeOutLeft.hierNode.thread = nodeInRight; nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft; ancestor = subtreeV; } } return ancestor; } /** * This function is used to traverse the right contour of a subtree. * It returns the rightmost child of node or the thread of node. The function * returns null if and only if node is on the highest depth of its subtree. */ function nextRight(node: TreeLayoutNode): TreeLayoutNode { const children = node.children; return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread; } /** * This function is used to traverse the left contour of a subtree (or a subforest). * It returns the leftmost child of node or the thread of node. The function * returns null if and only if node is on the highest depth of its subtree. */ function nextLeft(node: TreeLayoutNode) { const children = node.children; return children.length && node.isExpand ? children[0] : node.hierNode.thread; } /** * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor. * Otherwise, returns the specified ancestor. */ function nextAncestor( nodeInLeft: TreeLayoutNode, node: TreeLayoutNode, ancestor: TreeLayoutNode ): TreeLayoutNode { return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor; } /** * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. * * Shifts the current subtree rooted at wr. * This is done by increasing prelim(w+) and modifier(w+) by shift. */ function moveSubtree( wl: TreeLayoutNode, wr: TreeLayoutNode, shift: number ) { const change = shift / (wr.hierNode.i - wl.hierNode.i); wr.hierNode.change -= change; wr.hierNode.shift += shift; wr.hierNode.modifier += shift; wr.hierNode.prelim += shift; wl.hierNode.change += change; } /** * The implementation of this function was originally copied from "d3.js" * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js> * with some modifications made for this program. * See the license statement at the head of this file. */ function defaultSeparation(node1: TreeLayoutNode, node2: TreeLayoutNode): number { return node1.parentNode === node2.parentNode ? 1 : 2; } interface SeparationFunc { (node1: TreeLayoutNode, node2: TreeLayoutNode): number }
the_stack
import * as nodePath from 'path'; import { v4 as uuid } from 'uuid'; import * as vscode from 'vscode'; import { Repository } from '../api/api'; import { CommentHandler, registerCommentHandler, unregisterCommentHandler } from '../commentHandlerResolver'; import { DiffSide, IComment, IReviewThread } from '../common/comment'; import { getCommentingRanges } from '../common/commentingRanges'; import { mapNewPositionToOld, mapOldPositionToNew } from '../common/diffPositionMapping'; import { GitChangeType } from '../common/file'; import { ISessionState } from '../common/sessionState'; import { fromReviewUri, ReviewUriParams, toReviewUri } from '../common/uri'; import { formatError, groupBy, uniqBy } from '../common/utils'; import { FolderRepositoryManager } from '../github/folderRepositoryManager'; import { GHPRComment, GHPRCommentThread, TemporaryComment } from '../github/prComment'; import { PullRequestOverviewPanel } from '../github/pullRequestOverview'; import { CommentReactionHandler, createVSCodeCommentThreadForReviewThread, updateCommentReviewState, updateCommentThreadLabel, updateThread, } from '../github/utils'; import { ReviewManager } from './reviewManager'; import { ReviewModel } from './reviewModel'; import { GitFileChangeNode, gitFileChangeNodeFilter, RemoteFileChangeNode } from './treeNodes/fileChangeNode'; export class ReviewCommentController implements vscode.Disposable, CommentHandler, vscode.CommentingRangeProvider, CommentReactionHandler { private _localToDispose: vscode.Disposable[] = []; private _onDidChangeComments = new vscode.EventEmitter<IComment[]>(); public onDidChangeComments = this._onDidChangeComments.event; private _commentHandlerId: string; private _commentController: vscode.CommentController; public get commentController(): vscode.CommentController | undefined { return this._commentController; } // Note: marked as protected so that tests can verify caches have been updated correctly without breaking type safety protected _workspaceFileChangeCommentThreads: { [key: string]: GHPRCommentThread[] } = {}; protected _reviewSchemeFileChangeCommentThreads: { [key: string]: GHPRCommentThread[] } = {}; protected _obsoleteFileChangeCommentThreads: { [key: string]: GHPRCommentThread[] } = {}; protected _visibleNormalTextEditors: vscode.TextEditor[] = []; private _pendingCommentThreadAdds: GHPRCommentThread[] = []; constructor( private _reviewManager: ReviewManager, private _reposManager: FolderRepositoryManager, private _repository: Repository, private _reviewModel: ReviewModel, private readonly _sessionState: ISessionState ) { this._commentController = vscode.comments.createCommentController( `github-review-${_reposManager.activePullRequest!.number}`, _reposManager.activePullRequest!.title, ); this._commentController.commentingRangeProvider = this; this._commentController.reactionHandler = this.toggleReaction.bind(this); this._localToDispose.push(this._commentController); this._commentHandlerId = uuid(); registerCommentHandler(this._commentHandlerId, this); } // #region initialize async initialize(): Promise<void> { this._visibleNormalTextEditors = vscode.window.visibleTextEditors.filter( ed => ed.document.uri.scheme !== 'comment', ); await this._reposManager.activePullRequest!.validateDraftMode(); await this.initializeCommentThreads(); await this.registerListeners(); } /** * Creates a comment thread for a thread that is not on the latest changes. * @param path The path to the file the comment thread is on. * @param thread The comment thread information from GitHub. * @returns A GHPRCommentThread that has been created on an editor. */ private createOutdatedCommentThread(path: string, thread: IReviewThread): GHPRCommentThread { const commit = thread.comments[0].originalCommitId!; const uri = vscode.Uri.file(nodePath.join(`commit~${commit.substr(0, 8)}`, path)); const reviewUri = toReviewUri( uri, path, undefined, commit, true, { base: thread.diffSide === DiffSide.LEFT }, this._repository.rootUri, ); const range = new vscode.Range( new vscode.Position(thread.originalLine - 1, 0), new vscode.Position(thread.originalLine - 1, 0), ); return createVSCodeCommentThreadForReviewThread(reviewUri, range, thread, this._commentController); } /** * Creates a comment thread for a thread that appears on the right-hand side, which is a * document that has a scheme matching the workspace uri scheme, typically 'file'. * @param uri The uri to the file the comment thread is on. * @param path The path to the file the comment thread is on. * @param thread The comment thread information from GitHub. * @returns A GHPRCommentThread that has been created on an editor. */ private async createWorkspaceCommentThread( uri: vscode.Uri, path: string, thread: IReviewThread, ): Promise<GHPRCommentThread> { let line = thread.line; const localDiff = await this._repository.diffWithHEAD(path); if (localDiff) { line = mapOldPositionToNew(localDiff, thread.line); } const range = new vscode.Range(new vscode.Position(line - 1, 0), new vscode.Position(line - 1, 0)); return createVSCodeCommentThreadForReviewThread(uri, range, thread, this._commentController); } /** * Creates a comment thread for a thread that appears on the left-hand side, which is a * document that has a 'review' scheme whose content is created by the extension. * @param uri The uri to the file the comment thread is on. * @param path The path to the file the comment thread is on. * @param thread The comment thread information from GitHub. * @returns A GHPRCommentThread that has been created on an editor. */ private createReviewCommentThread(uri: vscode.Uri, path: string, thread: IReviewThread): GHPRCommentThread { if (!this._reposManager.activePullRequest?.mergeBase) { throw new Error('Cannot create review comment thread without an active pull request base.'); } const reviewUri = toReviewUri( uri, path, undefined, this._reposManager.activePullRequest.mergeBase, false, { base: true }, this._repository.rootUri, ); const range = new vscode.Range( new vscode.Position(thread.line - 1, 0), new vscode.Position(thread.line - 1, 0), ); return createVSCodeCommentThreadForReviewThread(reviewUri, range, thread, this._commentController); } private async doInitializeCommentThreads(reviewThreads: IReviewThread[]): Promise<void> { const threadsByPath = groupBy(reviewThreads, thread => thread.path); Object.keys(threadsByPath).forEach(path => { const threads = threadsByPath[path]; const firstThread = threads[0]; if (firstThread) { const fullPath = nodePath.join(this._repository.rootUri.path, firstThread.path).replace(/\\/g, '/'); const uri = this._repository.rootUri.with({ path: fullPath }); let rightSideCommentThreads: GHPRCommentThread[] = []; let leftSideThreads: GHPRCommentThread[] = []; let outdatedCommentThreads: GHPRCommentThread[] = []; const threadPromises = threads.map(async thread => { if (thread.isOutdated) { outdatedCommentThreads.push(this.createOutdatedCommentThread(path, thread)); } else { if (thread.diffSide === DiffSide.RIGHT) { rightSideCommentThreads.push(await this.createWorkspaceCommentThread(uri, path, thread)); } else { leftSideThreads.push(this.createReviewCommentThread(uri, path, thread)); } } }); Promise.all(threadPromises); this._workspaceFileChangeCommentThreads[path] = rightSideCommentThreads; this._reviewSchemeFileChangeCommentThreads[path] = leftSideThreads; this._obsoleteFileChangeCommentThreads[path] = outdatedCommentThreads; } }); } private async initializeCommentThreads(): Promise<void> { const activePullRequest = this._reposManager.activePullRequest; if (!activePullRequest || !activePullRequest.isResolved()) { return; } return this.doInitializeCommentThreads(activePullRequest.reviewThreadsCache); } private async registerListeners(): Promise<void> { this._localToDispose.push( this._reposManager.activePullRequest!.onDidChangePendingReviewState(newDraftMode => { [ this._workspaceFileChangeCommentThreads, this._obsoleteFileChangeCommentThreads, this._reviewSchemeFileChangeCommentThreads, ].forEach(commentThreadMap => { for (const fileName in commentThreadMap) { commentThreadMap[fileName].forEach(thread => { updateCommentReviewState(thread, newDraftMode); updateCommentThreadLabel(thread); }); } }); }), ); this._localToDispose.push( this._reposManager.activePullRequest!.onDidChangeReviewThreads(e => { e.added.forEach(async thread => { const { path } = thread; const index = this._pendingCommentThreadAdds.findIndex(async t => { const fileName = this.gitRelativeRootPath(t.uri.path); if (fileName !== thread.path) { return false; } const diff = await this.getContentDiff(t.uri, fileName); const line = mapNewPositionToOld(diff, t.range.start.line); const sameLine = line + 1 === thread.line; return sameLine; }); let newThread: GHPRCommentThread; if (index > -1) { newThread = this._pendingCommentThreadAdds[index]; newThread.gitHubThreadId = thread.id; newThread.comments = thread.comments.map(c => new GHPRComment(c, newThread)); this._pendingCommentThreadAdds.splice(index, 1); } else { const fullPath = nodePath.join(this._repository.rootUri.path, path).replace(/\\/g, '/'); const uri = this._repository.rootUri.with({ path: fullPath }); if (thread.isOutdated) { newThread = this.createOutdatedCommentThread(path, thread); } else { if (thread.diffSide === DiffSide.RIGHT) { newThread = await this.createWorkspaceCommentThread(uri, path, thread); } else { newThread = this.createReviewCommentThread(uri, path, thread); } } } const threadMap = thread.isOutdated ? this._obsoleteFileChangeCommentThreads : thread.diffSide === DiffSide.RIGHT ? this._workspaceFileChangeCommentThreads : this._reviewSchemeFileChangeCommentThreads; if (threadMap[path]) { threadMap[path].push(newThread); } else { threadMap[path] = [newThread]; } }); e.changed.forEach(thread => { const threadMap = thread.isOutdated ? this._obsoleteFileChangeCommentThreads : thread.diffSide === DiffSide.RIGHT ? this._workspaceFileChangeCommentThreads : this._reviewSchemeFileChangeCommentThreads; const index = threadMap[thread.path].findIndex(t => t.gitHubThreadId === thread.id); if (index > -1) { const matchingThread = threadMap[thread.path][index]; updateThread(matchingThread, thread); } }); e.removed.forEach(thread => { const threadMap = thread.isOutdated ? this._obsoleteFileChangeCommentThreads : thread.diffSide === DiffSide.RIGHT ? this._workspaceFileChangeCommentThreads : this._reviewSchemeFileChangeCommentThreads; const index = threadMap[thread.path].findIndex(t => t.gitHubThreadId === thread.id); if (index > -1) { const matchingThread = threadMap[thread.path][index]; threadMap[thread.path].splice(index, 1); matchingThread.dispose(); } }); }), ); this._localToDispose.push( this._sessionState.onDidChangeCommentsExpandState(expand => { this.updateCommentExpandState(expand); })); } public updateCommentExpandState(expand: boolean) { if (!this._reposManager.activePullRequest) { return undefined; } function updateThreads(threads: { [key: string]: GHPRCommentThread[] }, reviewThreads: Map<string, Map<string, IReviewThread>>) { if (reviewThreads.size === 0) { return; } for (const path of reviewThreads.keys()) { const reviewThreadsForPath = reviewThreads.get(path)!; const commentThreads = threads[path]; for (const commentThread of commentThreads) { const reviewThread = reviewThreadsForPath.get(commentThread.gitHubThreadId)!; updateThread(commentThread, reviewThread, expand); } } } const obsoleteReviewThreads: Map<string, Map<string, IReviewThread>> = new Map(); const reviewSchemeReviewThreads: Map<string, Map<string, IReviewThread>> = new Map(); const workspaceFileReviewThreads: Map<string, Map<string, IReviewThread>> = new Map(); for (const reviewThread of this._reposManager.activePullRequest.reviewThreadsCache) { let mapToUse: Map<string, Map<string, IReviewThread>>; if (reviewThread.isOutdated) { mapToUse = obsoleteReviewThreads; } else { if (reviewThread.diffSide === DiffSide.RIGHT) { mapToUse = workspaceFileReviewThreads; } else { mapToUse = reviewSchemeReviewThreads; } } if (!mapToUse.has(reviewThread.path)) { mapToUse.set(reviewThread.path, new Map()); } mapToUse.get(reviewThread.path)!.set(reviewThread.id, reviewThread); } updateThreads(this._obsoleteFileChangeCommentThreads, obsoleteReviewThreads); updateThreads(this._reviewSchemeFileChangeCommentThreads, reviewSchemeReviewThreads); updateThreads(this._workspaceFileChangeCommentThreads, workspaceFileReviewThreads); } private visibleEditorsEqual(a: vscode.TextEditor[], b: vscode.TextEditor[]): boolean { a = a.filter(ed => ed.document.uri.scheme !== 'comment'); b = b.filter(ed => ed.document.uri.scheme !== 'comment'); a = uniqBy(a, editor => editor.document.uri.toString()); b = uniqBy(b, editor => editor.document.uri.toString()); if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { const findRet = b.find(editor => editor.document.uri.toString() === a[i].document.uri.toString()); if (!findRet) { return false; } } return true; } // #endregion hasCommentThread(thread: vscode.CommentThread): boolean { if (thread.uri.scheme === 'review') { return true; } const currentWorkspace = vscode.workspace.getWorkspaceFolder(thread.uri); if (!currentWorkspace) { return false; } if ( thread.uri.scheme === currentWorkspace.uri.scheme && thread.uri.fsPath.startsWith(this._repository.rootUri.fsPath) ) { return true; } return false; } async provideCommentingRanges( document: vscode.TextDocument, _token: vscode.CancellationToken, ): Promise<vscode.Range[] | undefined> { let query: ReviewUriParams | undefined = (document.uri.query && document.uri.query !== '') ? fromReviewUri(document.uri.query) : undefined; if (query) { const matchedFile = this.findMatchedFileChangeForReviewDiffView(this._reviewModel.localFileChanges, document.uri); if (matchedFile) { return getCommentingRanges(await matchedFile.diffHunks(), query.base); } } const currentWorkspace = vscode.workspace.getWorkspaceFolder(document.uri); if (!currentWorkspace) { return; } if (document.uri.scheme === currentWorkspace.uri.scheme) { if (!this._reposManager.activePullRequest!.isResolved()) { return; } const fileName = this.gitRelativeRootPath(document.uri.path); const matchedFile = gitFileChangeNodeFilter(this._reviewModel.localFileChanges).find( fileChange => fileChange.fileName === fileName, ); const ranges: vscode.Range[] = []; if (matchedFile) { const diffHunks = await matchedFile.diffHunks(); if ((matchedFile.status === GitChangeType.RENAME) && (diffHunks.length === 0)) { return []; } const contentDiff = await this.getContentDiff(document.uri, matchedFile.fileName); for (let i = 0; i < diffHunks.length; i++) { const diffHunk = diffHunks[i]; const start = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber); const end = mapOldPositionToNew(contentDiff, diffHunk.newLineNumber + diffHunk.newLength - 1); if (start > 0 && end > 0) { ranges.push(new vscode.Range(start - 1, 0, end - 1, 0)); } } } return ranges; } return; } // #endregion private async getContentDiff(uri: vscode.Uri, fileName: string): Promise<string> { const matchedEditor = vscode.window.visibleTextEditors.find( editor => editor.document.uri.toString() === uri.toString(), ); if (!this._reposManager.activePullRequest?.head) { throw new Error('Cannot get content diff without an active pull request head.'); } if (matchedEditor && matchedEditor.document.isDirty) { const documentText = matchedEditor.document.getText(); const details = await this._repository.getObjectDetails( this._reposManager.activePullRequest.head.sha, fileName, ); const idAtLastCommit = details.object; const idOfCurrentText = await this._repository.hashObject(documentText); // git diff <blobid> <blobid> return await this._repository.diffBlobs(idAtLastCommit, idOfCurrentText); } else { return await this._repository.diffWith(this._reposManager.activePullRequest.head.sha, fileName); } } private findMatchedFileChangeForReviewDiffView( fileChanges: (GitFileChangeNode | RemoteFileChangeNode)[], uri: vscode.Uri, ): GitFileChangeNode | undefined { const query = fromReviewUri(uri.query); const matchedFiles = fileChanges.filter(fileChange => { if (fileChange instanceof RemoteFileChangeNode) { return false; } if (fileChange.fileName !== query.path) { return false; } if (fileChange.filePath.scheme !== 'review') { // local file if (fileChange.sha === query.commit) { return true; } } const q = fileChange.filePath.query ? JSON.parse(fileChange.filePath.query) : undefined; if (q && (q.commit === query.commit)) { return true; } const parentQ = fileChange.parentFilePath.query ? JSON.parse(fileChange.parentFilePath.query) : undefined; if (parentQ && (parentQ.commit === query.commit)) { return true; } return false; }); if (matchedFiles && matchedFiles.length) { return matchedFiles[0] as GitFileChangeNode; } return undefined; } private gitRelativeRootPath(path: string) { // get path relative to git root directory. Handles windows path by converting it to unix path. return nodePath.relative(this._repository.rootUri.path, path).replace(/\\/g, '/'); } // #endregion // #region Review private getCommentSide(thread: GHPRCommentThread): DiffSide { if (thread.uri.scheme === 'review') { const query = fromReviewUri(thread.uri.query); return query.base ? DiffSide.LEFT : DiffSide.RIGHT; } return DiffSide.RIGHT; } public async startReview(thread: GHPRCommentThread, input: string): Promise<void> { const hasExistingComments = thread.comments.length; const temporaryCommentId = this.optimisticallyAddComment(thread, input, true); try { if (!hasExistingComments) { const fileName = this.gitRelativeRootPath(thread.uri.path); const side = this.getCommentSide(thread); this._pendingCommentThreadAdds.push(thread); // If the thread is on the workspace file, make sure the position // is properly adjusted to account for any local changes. let line: number; if (side === DiffSide.RIGHT) { const diff = await this.getContentDiff(thread.uri, fileName); line = mapNewPositionToOld(diff, thread.range.start.line); } else { line = thread.range.start.line; } await this._reposManager.activePullRequest!.createReviewThread(input, fileName, line + 1, side); } else { const comment = thread.comments[0]; if (comment instanceof GHPRComment) { await this._reposManager.activePullRequest!.createCommentReply( input, comment._rawComment.graphNodeId, false, ); } else { throw new Error('Cannot reply to temporary comment'); } } } catch (e) { vscode.window.showErrorMessage(`Starting review failed: ${e}`); thread.comments = thread.comments.map(c => { if (c instanceof TemporaryComment && c.id === temporaryCommentId) { c.mode = vscode.CommentMode.Editing; } return c; }); } } public async openReview(): Promise<void> { await this._reviewManager.openDescription(); PullRequestOverviewPanel.scrollToReview(); } // #endregion private optimisticallyAddComment(thread: GHPRCommentThread, input: string, inDraft: boolean): number { const currentUser = this._reposManager.getCurrentUser(this._reposManager.activePullRequest!); const comment = new TemporaryComment(thread, input, inDraft, currentUser); this.updateCommentThreadComments(thread, [...thread.comments, comment]); return comment.id; } private updateCommentThreadComments(thread: GHPRCommentThread, newComments: (GHPRComment | TemporaryComment)[]) { thread.comments = newComments; updateCommentThreadLabel(thread); } private optimisticallyEditComment(thread: GHPRCommentThread, comment: GHPRComment): number { const currentUser = this._reposManager.getCurrentUser(this._reposManager.activePullRequest!); const temporaryComment = new TemporaryComment( thread, comment.body instanceof vscode.MarkdownString ? comment.body.value : comment.body, !!comment.label, currentUser, comment, ); thread.comments = thread.comments.map(c => { if (c instanceof GHPRComment && c.commentId === comment.commentId) { return temporaryComment; } return c; }); return temporaryComment.id; } // #region Comment async createOrReplyComment( thread: GHPRCommentThread, input: string, isSingleComment: boolean, inDraft?: boolean, ): Promise<void> { if (!this._reposManager.activePullRequest) { throw new Error('Cannot create comment without an active pull request.'); } const hasExistingComments = thread.comments.length; const isDraft = isSingleComment ? false : inDraft !== undefined ? inDraft : this._reposManager.activePullRequest.hasPendingReview; const temporaryCommentId = this.optimisticallyAddComment(thread, input, isDraft); try { if (!hasExistingComments) { const fileName = this.gitRelativeRootPath(thread.uri.path); this._pendingCommentThreadAdds.push(thread); const side = this.getCommentSide(thread); // If the thread is on the workspace file, make sure the position // is properly adjusted to account for any local changes. let line: number; if (side === DiffSide.RIGHT) { const diff = await this.getContentDiff(thread.uri, fileName); line = mapNewPositionToOld(diff, thread.range.start.line); } else { line = thread.range.start.line; } await this._reposManager.activePullRequest.createReviewThread( input, fileName, line + 1, side, isSingleComment, ); } else { const comment = thread.comments[0]; if (comment instanceof GHPRComment) { await this._reposManager.activePullRequest.createCommentReply( input, comment._rawComment.graphNodeId, isSingleComment, ); } else { throw new Error('Cannot reply to temporary comment'); } } if (isSingleComment) { await this._reposManager.activePullRequest.submitReview(); } } catch (e) { if (e.graphQLErrors?.length && e.graphQLErrors[0].type === 'NOT_FOUND') { vscode.window.showWarningMessage('The comment that you\'re replying to was deleted. Refresh to update.', 'Refresh').then(result => { if (result === 'Refresh') { this._reviewManager.updateComments(); } }); } else { vscode.window.showErrorMessage(`Creating comment failed: ${e}`); } thread.comments = thread.comments.map(c => { if (c instanceof TemporaryComment && c.id === temporaryCommentId) { c.mode = vscode.CommentMode.Editing; } return c; }); } } private async createCommentOnResolve(thread: GHPRCommentThread, input: string): Promise<void> { if (!this._reposManager.activePullRequest) { throw new Error('Cannot create comment on resolve without an active pull request.'); } const pendingReviewId = await this._reposManager.activePullRequest.getPendingReviewId(); await this.createOrReplyComment(thread, input, !pendingReviewId); } async resolveReviewThread(thread: GHPRCommentThread, input?: string): Promise<void> { try { if (input) { await this.createCommentOnResolve(thread, input); } await this._reposManager.activePullRequest!.resolveReviewThread(thread.gitHubThreadId); } catch (e) { vscode.window.showErrorMessage(`Resolving conversation failed: ${e}`); } } async unresolveReviewThread(thread: GHPRCommentThread, input?: string): Promise<void> { try { if (input) { await this.createCommentOnResolve(thread, input); } await this._reposManager.activePullRequest!.unresolveReviewThread(thread.gitHubThreadId); } catch (e) { vscode.window.showErrorMessage(`Unresolving conversation failed: ${e}`); } } async editComment(thread: GHPRCommentThread, comment: GHPRComment | TemporaryComment): Promise<void> { if (comment instanceof GHPRComment) { const temporaryCommentId = this.optimisticallyEditComment(thread, comment); try { if (!this._reposManager.activePullRequest) { throw new Error('Unable to find active pull request'); } await this._reposManager.activePullRequest.editReviewComment( comment._rawComment, comment.body instanceof vscode.MarkdownString ? comment.body.value : comment.body, ); } catch (e) { vscode.window.showErrorMessage(formatError(e)); thread.comments = thread.comments.map(c => { if (c instanceof TemporaryComment && c.id === temporaryCommentId) { return new GHPRComment(comment._rawComment, thread); } return c; }); } } else { this.createOrReplyComment( thread, comment.body instanceof vscode.MarkdownString ? comment.body.value : comment.body, false, ); } } async deleteComment(thread: GHPRCommentThread, comment: GHPRComment | TemporaryComment): Promise<void> { try { if (!this._reposManager.activePullRequest) { throw new Error('Unable to find active pull request'); } if (comment instanceof GHPRComment) { await this._reposManager.activePullRequest.deleteReviewComment(comment.commentId); } else { thread.comments = thread.comments.filter(c => !(c instanceof TemporaryComment && c.id === comment.id)); } if (thread.comments.length === 0) { thread.dispose(); } else { updateCommentThreadLabel(thread); } const inDraftMode = await this._reposManager.activePullRequest.validateDraftMode(); if (inDraftMode !== this._reposManager.activePullRequest.hasPendingReview) { this._reposManager.activePullRequest.hasPendingReview = inDraftMode; } this.update(); } catch (e) { throw new Error(formatError(e)); } } // #endregion // #region Incremental update comments public async update(): Promise<void> { await this._reposManager.activePullRequest!.validateDraftMode(); } // #endregion // #region Reactions async toggleReaction(comment: GHPRComment, reaction: vscode.CommentReaction): Promise<void> { try { if (!this._reposManager.activePullRequest) { throw new Error('Unable to find active pull request'); } if ( comment.reactions && !comment.reactions.find(ret => ret.label === reaction.label && !!ret.authorHasReacted) ) { await this._reposManager.activePullRequest.addCommentReaction( comment._rawComment.graphNodeId, reaction, ); } else { await this._reposManager.activePullRequest.deleteCommentReaction( comment._rawComment.graphNodeId, reaction, ); } } catch (e) { throw new Error(formatError(e)); } } // #endregion public dispose() { if (this._commentController) { this._commentController.dispose(); } unregisterCommentHandler(this._commentHandlerId); this._localToDispose.forEach(d => d.dispose()); } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { TextElement } from '../../../src/diagram/core/elements/text-element'; import { DiagramModel, DiagramElement, NodeModel } from '../../../src/diagram/index'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; /** * Text Element  */ describe('Diagram Control', () => { let width: string = 'width'; let height: string = 'height'; let firstOutput: object[] = [{ width: 100, height: 100 }, { width: 204, height: 15 }, { width: 100, height: 100 }, { width: 100, height: 100 }, { width: 100, height: 100 }, { width: 4, height: 15 }]; let secondOutput: object[] = [{ width: 100, height: 100 }, { width: 318, height: 15 }, { width: 219, height: 44 }, { width: 150, height: 100 }, { width: 150, height: 100 }, { width: 100, height: 100 }, { width: 287, height: 44 }, { width: 166, height: 29 }]; let thirdOutput: object[] = [ { width: 100, height: 60 }, { width: 100, height: 60 }, { width: 100, height: 60 }, { width: 100, height: 60 } ]; describe('Text element style with width', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagram46' }); document.body.appendChild(ele); let element1: TextElement = new TextElement(); element1.content = 'Text element with width/100 height/100'; element1.style.color = 'red'; element1.style.italic = true; element1.style.fontSize = 12; element1.offsetX = 400; element1.offsetY = 100; element1.style.fill = 'transparent'; element1.width = 100; element1.height = 100; element1.style.bold = true; element1.style.fontFamily = 'Arial'; element1.style.textAlign = 'Center'; let element2: TextElement = new TextElement(); element2.content = 'Text element without width and height'; element2.style.fontSize = 12; element2.style.fill = 'transparent'; element2.offsetX = 350; element2.offsetY = 250; element2.style.textAlign = 'Center'; let element3: TextElement = new TextElement(); element3.content = 'Text element align with left side'; element3.style.fill = 'transparent'; element3.style.fontSize = 12; element3.offsetX = 350; element3.offsetY = 400; element3.width = 100; element3.height = 100; element3.style.textAlign = 'Left'; let element4: TextElement = new TextElement(); element4.content = 'Text element align with center'; element4.style.fontSize = 12; element4.style.fill = 'transparent'; element4.offsetX = 400; element4.offsetY = 550; element4.width = 100; element4.height = 100; element4.style.textAlign = 'Center'; let element5: TextElement = new TextElement(); element5.content = 'Text element align with right side'; element5.style.fontSize = 12; element5.style.fill = 'transparent'; element5.offsetX = 400; element5.offsetY = 700; element5.width = 100; element5.height = 100; element5.style.textAlign = 'Right'; let element6: TextElement = new TextElement(); element6.offsetX = 400; element6.offsetY = 700; element6.style.bold = true; element6.style.italic = true; let element7: TextElement = new TextElement(); element7.content = 'Text element align with height'; element7.style.fontSize = 12; element7.style.fill = 'transparent'; element7.offsetX = 600; element7.offsetY = 700; element7.height = 100; element7.style.textAlign = 'Right'; diagram = new Diagram({ width: '1000px', height: '1000px', basicElements: [element1, element2, element3, element4, element5, element6, element7] } as DiagramModel); diagram.appendTo('#diagram46'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking text wrapping', (done: Function) => { let i: number = 0; for (let element of diagram.basicElements) { expect(!firstOutput[i] || (Math.ceil(element.actualSize.width) == firstOutput[i][width] && Math.ceil(element.actualSize.height) == firstOutput[i][height])).toBe(true); i++; } done(); }); }); describe('Text element white space and break word property', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagram47' }); document.body.appendChild(ele); let element7: TextElement = new TextElement(); element7.content = 'Text element will not be wrapped - width/100'; element7.offsetX = 400; element7.offsetY = 250; element7.style.fill = 'transparent'; element7.width = 100; element7.height = 100; element7.style.fontSize = 12; element7.style.whiteSpace = 'CollapseAll'; element7.style.textAlign = 'Center'; let element8: TextElement = new TextElement(); element8.content = 'Text element will not be wrapped - with out width and height'; element8.offsetX = 250; element8.offsetY = 400; element8.style.fontSize = 12; element8.style.fill = 'transparent'; element8.style.whiteSpace = 'CollapseAll'; element8.style.textAlign = 'Center'; let element9: TextElement = new TextElement(); element9.content = 'Text element will be wrapped \n on line breaks \n width and when necessary - without size'; element9.offsetX = 250; element9.offsetY = 550; element9.style.fill = 'transparent'; element9.style.fontSize = 12; element9.style.whiteSpace = 'CollapseSpace'; element9.style.textAlign = 'Center'; let element10: TextElement = new TextElement(); element10.content = 'It will not collapse the white space and \n will not wrap the text - with width and height'; element10.offsetX = 450; element10.offsetY = 700; element10.style.fill = 'transparent'; element10.style.fontSize = 12; element10.style.whiteSpace = 'PreserveAll'; element10.width = 150; element10.height = 100; element10.style.textAlign = 'Center'; let element11: TextElement = new TextElement(); element11.content = 'It will not collapse the white space and \n will wrap the text on breaks and when necessary - with width and height'; element11.offsetX = 600; element11.offsetY = 100; element11.width = 150; element11.height = 100; element11.style.fill = 'transparent'; element11.style.fontSize = 12; element11.style.whiteSpace = 'PreserveAll'; element11.style.textAlign = 'Center'; let element12: TextElement = new TextElement(); element12.content = 'Text element will be wrapped based on characters with size(100)'; element12.offsetX = 650; element12.offsetY = 250; element12.width = 100; element12.height = 100; element12.style.fill = 'transparent'; element12.style.fontSize = 12; element12.style.whiteSpace = 'PreserveAll'; element12.style.textWrapping = 'Wrap'; element12.style.textAlign = 'Center'; let element13: TextElement = new TextElement(); element13.content = 'Text element(nl) \n style(nl) \ as keep-all(nl) \n and pre-line so text will be wrapped based on words '; element13.offsetX = 650; element13.offsetY = 400; element12.width = 100; element12.height = 100; element13.style.fontSize = 12; element13.style.fill = 'transparent'; element13.style.whiteSpace = 'CollapseSpace'; element13.style.textWrapping = 'NoWrap'; element13.style.textAlign = 'Center'; let element14: TextElement = new TextElement(); element14.content = 'Text element\n style \ as wrap and preserve all'; element14.offsetX = 600; element14.offsetY = 550; element14.style.fontSize = 12; element14.style.fill = 'transparent'; element14.style.whiteSpace = 'PreserveAll'; element14.style.textWrapping = 'WrapWithOverflow'; element14.style.textAlign = 'Center'; diagram = new Diagram({ width: '1000px', height: '1000px', basicElements: [element7, element8, element9, element10, element11, element12, element13, element14] } as DiagramModel); diagram.appendTo('#diagram47'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking text wrapping', (done: Function) => { let i: number = 0; for (let element of diagram.basicElements) { expect((Math.ceil(element.actualSize.width) == secondOutput[i][width] || Math.ceil(element.actualSize.width) == 216 || Math.ceil(element.actualSize.width) == 220) && Math.ceil(element.actualSize.height) == secondOutput[i][height]).toBe(true); i++; } done(); }); }); describe('Text element With text overflow', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagramoverflow' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 75, height: 75, offsetX: 300, offsetY: 200, annotations: [{ content: 'The text element given with property of overflow as clip and wrapping as wrap so that element to be clipped', style: { textWrapping: 'Wrap', textOverflow: 'Clip' } }] }; let node2: NodeModel = { id: 'node2', width: 75, height: 75, offsetX: 400, offsetY: 200, annotations: [{ content: 'The text element given with property of overflow as clip and wrapping as wrap so that element to be clipped', style: { textOverflow: 'Ellipsis', textWrapping: 'Wrap' } }] }; let node3: NodeModel = { id: 'node3', width: 75, height: 75, offsetX: 500, offsetY: 200, annotations: [{ content: 'Node3', style: { textOverflow: 'Clip', textWrapping: 'WrapWithOverflow' } }] }; diagram = new Diagram({ width: '1000px', height: '500px', nodes: [node, node2, node3] }); diagram.appendTo('#diagramoverflow'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking Text overflow - Clip', (done: Function) => { let node: DiagramElement = diagram.nodes[0].wrapper.children[1]; expect((node as TextElement).wrapBounds.x === -37.34375||(node as TextElement).wrapBounds.x === -37.3515625).toBe(true); expect(Math.ceil((node as TextElement).wrapBounds.width) === 77 || Math.floor((node as TextElement).wrapBounds.width) === 76).toBe(true); done(); }); it('Checking Text overflow - Ellipsis', (done: Function) => { let node: DiagramElement = diagram.nodes[1].wrapper.children[1]; expect((node as TextElement).wrapBounds.x === -37.34375||(node as TextElement).wrapBounds.x === -37.3515625).toBe(true); expect(Math.ceil((node as TextElement).wrapBounds.width) === 77 || Math.floor((node as TextElement).wrapBounds.width) === 76).toBe(true); done(); }); it('Checking Text Wrapping - Wrap with overflow', (done: Function) => { let node: DiagramElement = diagram.nodes[2].wrapper.children[1]; console.log((node as TextElement).wrapBounds.x); console.log((node as TextElement).wrapBounds.width); expect((node as TextElement).wrapBounds.x === -17.6796875 || (node as TextElement).wrapBounds.x === -17.84375 || (node as TextElement).wrapBounds.x === -19.3515625).toBe(true); expect((node as TextElement).wrapBounds.width === 35.359375 || (node as TextElement).wrapBounds.width === 35.6875 || (node as TextElement).wrapBounds.width === 38.703125).toBe(true); done(); }); }); describe('Text element style with Text Align', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let element1: TextElement = new TextElement(); element1.content = 'Text element with Wrapping and align - center'; element1.style.color = 'red'; element1.style.italic = true; element1.style.fontSize = 12; element1.offsetX = 400; element1.offsetY = 100; element1.style.fill = 'transparent'; element1.width = 100; element1.height = 60; element1.style.bold = true; element1.style.fontFamily = 'Arial'; element1.style.textAlign = 'Center'; let element2: TextElement = new TextElement(); element2.content = 'Text element with Wrapping and without align'; element2.style.color = 'red'; element2.style.italic = true; element2.style.fontSize = 12; element2.offsetX = 400; element2.offsetY = 300; element2.style.fill = 'transparent'; element2.width = 100; element2.height = 60; element2.style.bold = true; element2.style.fontFamily = 'Arial'; let element3: TextElement = new TextElement(); element3.content = 'Text element with Wrapping and align - right'; element3.style.color = 'blue'; element3.style.italic = false; element3.style.bold = true; element3.style.fontSize = 12; element3.offsetX = 600; element3.offsetY = 100; element3.style.fill = 'transparent'; element3.width = 100; element3.height = 60; element3.style.bold = true; element3.style.fontFamily = 'Arial'; element3.style.textAlign = 'Right'; let element4: TextElement = new TextElement(); element4.content = 'Text element with Wrapping and align - left'; element4.style.color = 'green'; element4.style.italic = false; element4.style.bold = true; element4.style.fontSize = 12; element4.offsetX = 600; element4.offsetY = 300; element4.style.fill = 'transparent'; element4.width = 100; element4.height = 60; element4.style.bold = true; element4.style.fontFamily = 'Arial'; element4.style.textAlign = 'Left'; diagram = new Diagram({ width: '1000px', height: '1000px', basicElements: [element1, element2, element3, element4] } as DiagramModel); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking text wrapping', (done: Function) => { let i: number = 0; for (let element of diagram.basicElements) { expect(element.actualSize.width == thirdOutput[i][width] && element.actualSize.height == thirdOutput[i][height]).toBe(true); i++; } done(); }); 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); }) }); });
the_stack
import { CancellationToken, Hover, MarkupKind } from 'vscode-languageserver'; import { Declaration, DeclarationType } from '../analyzer/declaration'; import { convertDocStringToMarkdown, convertDocStringToPlainText } from '../analyzer/docStringConversion'; import * as ParseTreeUtils from '../analyzer/parseTreeUtils'; import { SourceMapper } from '../analyzer/sourceMapper'; import { TypeEvaluator } from '../analyzer/typeEvaluatorTypes'; import { getTypeAliasInfo, isClassInstance, isFunction, isInstantiableClass, isModule, isOverloadedFunction, isTypeVar, Type, UnknownType, } from '../analyzer/types'; import { ClassMemberLookupFlags, isProperty, lookUpClassMember } from '../analyzer/typeUtils'; import { throwIfCancellationRequested } from '../common/cancellationUtils'; import { fail } from '../common/debug'; import { convertOffsetToPosition, convertPositionToOffset } from '../common/positionUtils'; import { Position, Range } from '../common/textRange'; import { TextRange } from '../common/textRange'; import { NameNode, ParseNode, ParseNodeType } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; import { getDocumentationPartsForTypeAndDecl, getOverloadedFunctionTooltip } from './tooltipUtils'; export interface HoverTextPart { python?: boolean; text: string; } export interface HoverResults { parts: HoverTextPart[]; range: Range; } export class HoverProvider { static getHoverForPosition( sourceMapper: SourceMapper, parseResults: ParseResults, position: Position, format: MarkupKind, evaluator: TypeEvaluator, token: CancellationToken ): HoverResults | undefined { throwIfCancellationRequested(token); const offset = convertPositionToOffset(position, parseResults.tokenizerOutput.lines); if (offset === undefined) { return undefined; } const node = ParseTreeUtils.findNodeByOffset(parseResults.parseTree, offset); if (node === undefined) { return undefined; } const results: HoverResults = { parts: [], range: { start: convertOffsetToPosition(node.start, parseResults.tokenizerOutput.lines), end: convertOffsetToPosition(TextRange.getEnd(node), parseResults.tokenizerOutput.lines), }, }; if (node.nodeType === ParseNodeType.Name) { const declarations = evaluator.getDeclarationsForNameNode(node); if (declarations && declarations.length > 0) { // In most cases, it's best to treat the first declaration as the // "primary". This works well for properties that have setters // which often have doc strings on the getter but not the setter. // The one case where using the first declaration doesn't work as // well is the case where an import statement within an __init__.py // file uses the form "from .A import A". In this case, if we use // the first declaration, it will show up as a module rather than // the imported symbol type. let primaryDeclaration = declarations[0]; if (primaryDeclaration.type === DeclarationType.Alias && declarations.length > 1) { primaryDeclaration = declarations[1]; } this._addResultsForDeclaration( format, sourceMapper, results.parts, primaryDeclaration, node, evaluator ); } else if (!node.parent || node.parent.nodeType !== ParseNodeType.ModuleName) { // If we had no declaration, see if we can provide a minimal tooltip. We'll skip // this if it's part of a module name, since a module name part with no declaration // is a directory (a namespace package), and we don't want to provide any hover // information in that case. if (results.parts.length === 0) { const type = evaluator.getType(node) || UnknownType.create(); let typeText = ''; if (isModule(type)) { // Handle modules specially because submodules aren't associated with // declarations, but we want them to be presented in the same way as // the top-level module, which does have a declaration. typeText = '(module) ' + node.value; } else { typeText = node.value + ': ' + evaluator.printType(type, /* expandTypeAlias */ false); } this._addResultsPart(results.parts, typeText, true); this._addDocumentationPart(format, sourceMapper, results.parts, node, evaluator, undefined); } } } return results.parts.length > 0 ? results : undefined; } private static _addResultsForDeclaration( format: MarkupKind, sourceMapper: SourceMapper, parts: HoverTextPart[], declaration: Declaration, node: NameNode, evaluator: TypeEvaluator ): void { const resolvedDecl = evaluator.resolveAliasDeclaration(declaration, /* resolveLocalNames */ true); if (!resolvedDecl) { this._addResultsPart(parts, `(import) ` + node.value + this._getTypeText(node, evaluator), true); return; } switch (resolvedDecl.type) { case DeclarationType.Intrinsic: { this._addResultsPart(parts, node.value + this._getTypeText(node, evaluator), true); this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } case DeclarationType.Variable: { let label = resolvedDecl.isConstant || resolvedDecl.isFinal ? 'constant' : 'variable'; // If the named node is an aliased import symbol, we can't call // getType on the original name because it's not in the symbol // table. Instead, use the node from the resolved alias. let typeNode = node; if ( declaration.node.nodeType === ParseNodeType.ImportAs || declaration.node.nodeType === ParseNodeType.ImportFromAs ) { if (declaration.node.alias && node !== declaration.node.alias) { if (resolvedDecl.node.nodeType === ParseNodeType.Name) { typeNode = resolvedDecl.node; } } } else if (node.parent?.nodeType === ParseNodeType.Argument && node.parent.name === node) { // If this is a named argument, we would normally have received a Parameter declaration // rather than a variable declaration, but we can get here in the case of a dataclass. // Replace the typeNode with the node of the variable declaration. if (declaration.node.nodeType === ParseNodeType.Name) { typeNode = declaration.node; } } // Determine if this identifier is a type alias. If so, expand // the type alias when printing the type information. const type = evaluator.getType(typeNode); let expandTypeAlias = false; let typeVarName: string | undefined; if (type?.typeAliasInfo) { const typeAliasInfo = getTypeAliasInfo(type); if (typeAliasInfo?.name === typeNode.value) { if (isTypeVar(type)) { label = type.details.isParamSpec ? 'param spec' : 'type variable'; typeVarName = type.details.name; } else { expandTypeAlias = true; label = 'type alias'; } } } const typeText = typeVarName || node.value + this._getTypeText(typeNode, evaluator, expandTypeAlias); this._addResultsPart(parts, `(${label}) ${typeText}`, true); this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } case DeclarationType.Parameter: { this._addResultsPart(parts, '(parameter) ' + node.value + this._getTypeText(node, evaluator), true); this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } case DeclarationType.Class: case DeclarationType.SpecialBuiltInClass: { if (this._addInitMethodInsteadIfCallNode(format, node, evaluator, parts, sourceMapper, resolvedDecl)) { return; } this._addResultsPart(parts, '(class) ' + node.value, true); this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } case DeclarationType.Function: { let label = 'function'; if (resolvedDecl.isMethod) { const declaredType = evaluator.getTypeForDeclaration(resolvedDecl); label = declaredType && isProperty(declaredType) ? 'property' : 'method'; } const type = evaluator.getType(node); if (type && isOverloadedFunction(type)) { this._addResultsPart(parts, `(${label})\n${getOverloadedFunctionTooltip(type, evaluator)}`, true); } else { this._addResultsPart(parts, `(${label}) ` + node.value + this._getTypeText(node, evaluator), true); } this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } case DeclarationType.Alias: { this._addResultsPart(parts, '(module) ' + node.value, true); this._addDocumentationPart(format, sourceMapper, parts, node, evaluator, resolvedDecl); break; } } } private static _addInitMethodInsteadIfCallNode( format: MarkupKind, node: NameNode, evaluator: TypeEvaluator, parts: HoverTextPart[], sourceMapper: SourceMapper, declaration: Declaration ) { // If the class is used as part of a call (i.e. it is being // instantiated), include the constructor arguments within the // hover text. let callLeftNode: ParseNode | undefined = node; // Allow the left to be a member access chain (e.g. a.b.c) if the // node in question is the last item in the chain. if ( callLeftNode.parent && callLeftNode.parent.nodeType === ParseNodeType.MemberAccess && node === callLeftNode.parent.memberName ) { callLeftNode = node.parent; } if ( !callLeftNode || !callLeftNode.parent || callLeftNode.parent.nodeType !== ParseNodeType.Call || callLeftNode.parent.leftExpression !== callLeftNode ) { return false; } // Get the init method for this class. const classType = evaluator.getType(node); if (!classType || !isInstantiableClass(classType)) { return false; } const initMethodMember = lookUpClassMember(classType, '__init__', ClassMemberLookupFlags.SkipInstanceVariables); if (!initMethodMember) { return false; } const instanceType = evaluator.getType(callLeftNode.parent); const functionType = evaluator.getTypeOfMember(initMethodMember); if (!instanceType || !functionType || !isClassInstance(instanceType) || !isFunction(functionType)) { return false; } const initMethodType = evaluator.bindFunctionToClassOrObject(instanceType, functionType); if (!initMethodType || !isFunction(initMethodType)) { return false; } const functionParts = evaluator.printFunctionParts(initMethodType); const classText = `${node.value}(${functionParts[0].join(', ')})`; this._addResultsPart(parts, '(class) ' + classText, true); const addedDoc = this._addDocumentationPartForType( format, sourceMapper, parts, initMethodType, declaration, evaluator ); if (!addedDoc) { this._addDocumentationPartForType(format, sourceMapper, parts, classType, declaration, evaluator); } return true; } private static _getTypeText(node: NameNode, evaluator: TypeEvaluator, expandTypeAlias = false): string { const type = evaluator.getType(node) || UnknownType.create(); return ': ' + evaluator.printType(type, expandTypeAlias); } private static _addDocumentationPart( format: MarkupKind, sourceMapper: SourceMapper, parts: HoverTextPart[], node: NameNode, evaluator: TypeEvaluator, resolvedDecl: Declaration | undefined ) { const type = evaluator.getType(node); if (type) { this._addDocumentationPartForType(format, sourceMapper, parts, type, resolvedDecl, evaluator); } } private static _addDocumentationPartForType( format: MarkupKind, sourceMapper: SourceMapper, parts: HoverTextPart[], type: Type, resolvedDecl: Declaration | undefined, evaluator: TypeEvaluator ): boolean { const docStrings = getDocumentationPartsForTypeAndDecl(sourceMapper, type, resolvedDecl, evaluator); let addedDoc = false; for (const docString of docStrings) { if (docString) { addedDoc = true; this._addDocumentationResultsPart(format, parts, docString); } } return addedDoc; } private static _addDocumentationResultsPart(format: MarkupKind, parts: HoverTextPart[], docString?: string) { if (docString) { if (format === MarkupKind.Markdown) { const markDown = convertDocStringToMarkdown(docString); if (parts.length > 0 && markDown.length > 0) { parts.push({ text: '---\n' }); } this._addResultsPart(parts, markDown); } else if (format === MarkupKind.PlainText) { this._addResultsPart(parts, convertDocStringToPlainText(docString)); } else { fail(`Unsupported markup type: ${format}`); } } } private static _addResultsPart(parts: HoverTextPart[], text: string, python = false) { parts.push({ python, text, }); } } export function convertHoverResults(format: MarkupKind, hoverResults: HoverResults | undefined): Hover | undefined { if (!hoverResults) { return undefined; } const markupString = hoverResults.parts .map((part) => { if (part.python) { if (format === MarkupKind.Markdown) { return '```python\n' + part.text + '\n```\n'; } else if (format === MarkupKind.PlainText) { return part.text + '\n\n'; } else { fail(`Unsupported markup type: ${format}`); } } return part.text; }) .join('') .trimEnd(); return { contents: { kind: format, value: markupString, }, range: hoverResults.range, }; }
the_stack
export function Model(arg?: { hooks?: {}, remotes?: {} }): any; export interface ModelLoopback { modelName?: string; dataSource?: { name: string; config: any; }; sharedMethod?: any; settings: any; } export interface ModelConstructor { //Event stuff// /** * @see https://docs.strongloop.com/display/public/APIC/Basic+model+any#Basicmodelany-Events */ on(event: 'attached'|'dataSourceAttached'|'set'|'changed'|'deleted'|'deletedAll', listener: () => void): void; // Persistedmodel /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-bulkupdate */ bulkUpdate(updates: any[], options: any, callback: findCallback): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-bulkupdate */ changes(since: number, filter: Filter, callback: findCallback): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-checkpoint */ checkpoint(callback: findCallback): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-checkpoint */ count(where: any, callback: countCallback): PromiseLike<number>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-create */ create(data: any | any[], callback: findCallbackById): PromiseLike<any>; /** * Check Fireloop () => voidality for this method in RealTime * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-create */ // createChangeStream(data: any | any[], callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-createupdates */ createUpdates(deltas: any[], callback: () => void): PromiseLike<any[]>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-currentcheckpoint */ currentCheckpoint(callback: () => void): PromiseLike<number>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-destroyall */ destroyAll(where: any, callback: () => void): PromiseLike<number>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-destroybyid */ destroyById(id: string, callback: () => void): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-diff */ diff(since: number, remoteChanges: any[], callback: () => void): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-enablechangetracking */ enableChangeTracking(id: string, callback: () => void): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-exists */ exists(id: string, callback: () => void): PromiseLike<any>; //Find stuff// /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-find */ find(filter: Filter, callback: findCallback): PromiseLike<any[]>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-findbyid */ findById(id: string, filter: Filter, callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-findone */ findOne(filter: Filter, callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-findorcreate */ findOrCreate(filter: Filter, data: any, callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-getchangemodel */ getChangeModel(): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-getidname */ getIdName(): string; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-getsourceid */ getSourceId(callback: () => void): string; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-getsourceid */ handleChangeError(err: Error): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-rectifychange */ rectifyChange(id: string, callback: () => void): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-replacebyid */ replaceById(id: string, data: any, callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-replaceorcreate */ replaceOrCreate(data: any, options: any, callback: findCallbackById): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-replicate */ replicate(since: number, targetModel: ModelConstructor, options: any, filter: any, callback: () => void): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-updateall */ updateAll(where: any, data: any, callback: findCallback): void; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-upsert */ upsert(data: any, callback: findCallback): PromiseLike<any>; /** * Override this to customize core find behavior * * @see https://apidocs.strongloop.com/loopback/#persistedmodel-upsertwithwhere */ upsertWithWhere(where: any, data: any, callback: findCallback): PromiseLike<any>; //Remote method stuff// /** * The `loopback.Model.extend()` method calls this when you create a model that extends another model. * Add any setup or configuration code you want executed when the model is created. * See [Setting up a custom model](http://docs.strongloop.com/display/LB/Extending+built-in+models#Extendingbuilt-inmodels-Settingupacustommodel). */ setup(): void; /** * Check if the given access token can invoke the specified method. */ checkAccess(token: any, modelId: string, sharedMethod: any, ctx: any, callback: (err: string|Error, allowed: boolean) => void ): void; /** * Get the `Application` any to which the Model is attached. */ getApp(callback: findCallback): void; /** * Enable remote invocation for the specified method. * See [Remote methods](http://docs.strongloop.com/display/LB/Remote+methods) for more information. */ remoteMethod(name: string, options: RemoteMethodOptions): void; /** * Disable remote invocation for the method with the given name. */ disableRemoteMethod(name: string, isStatic: boolean): void; /** * Disable remote invocation for the method with the given name. */ disableRemoteMethodByName(name: string): void; /** * Enabled deeply-nested queries of related models via REST API. */ nestRemoting(relationName: string, options: any, filterCallback: findCallback): void; //Validatable stuff// /** * Validate presence of one or more specified properties. * Requires a model to include a property to be considered valid; fails when validated field is blank. */ validatesPresenceOf(propertyName: string): void; /** * Validate absence of one or more specified properties. * A model should not include a property to be considered valid; fails when validated field not blank. */ validatesAbsenceOf(propertyName: string): void; /** * Validate length. Require a property length to be within a specified range. * Three kinds of validations: min, max, is. */ validatesLengthOf(propertyName: string): void; /** * Validate numericality. Requires a value for property to be either an integer or number. */ validatesNumericalityOf(propertyName: string): void; /** * Validate inclusion in set. Require a value for property to be in the specified array. */ validatesInclusionOf(propertyName: string): void; /** * Validate exclusion. Require a property value not be in the specified array */ validatesExclusionOf(propertyName: string): void; /** * Validate format. Require a model to include a property that matches the given format. */ validatesFormatOf(propertyName: string): void; /** * Validate using custom validation () => void. */ validate(propertyName: string, validatorFn: () => void): void; /** * Validate using custom asynchronous validation () => void. */ validateAsync(propertyName: string, validatorFn: () => void): void; /** * Validate uniqueness. Ensure the value for property is unique in the collection of models. * Not available for all connectors. Currently supported with these connectors: * - In Memory * - Oracle * - MongoDB */ validatesUniquenessOf(propertyName: string): void; } export interface Filter { fields?: string|any|string[]; include?: string|any|any[]; limit?: number; order?: string; skip?: number; where?: any; } export type Next = (err?: Error, result?: any) => void; export type findCallbackById = (error?: Error, result?: any) => void; export type findCallback = (error?: Error, result?: any[]) => void; export type countCallback = (error?: Error, result?: number) => void; export interface RemoteMethodOptions { accepts: RemoteMethodArgument[]; description?: string|string[]; http: { path?: string; verb?: 'get' | 'post' | 'patch' | 'put' | 'del' | 'all'; status?: number; errorStatus?: number; }; isStatic?: boolean; notes?: string | string[]; returns: RemoteMethodArgument; } export interface RemoteMethodArgument { arg: string; description: string | string[]; http: any; required: boolean; root: boolean; type: 'any' | 'Array' | 'boolean' | 'Buffer' | 'Date' | 'GeoPoint' | 'null' | 'number' | 'any' | 'string'; default: string; }
the_stack
import has = Reflect.has; var universe = require("../parser/tools/universe"); import core = require("../parser/wrapped-ast/parserCore"); import proxy = require("../parser/ast.core/LowLevelASTProxy"); import yaml = require("yaml-ast-parser"); import def = require("raml-definition-system"); import tsInterfaces = def.tsInterfaces import hl = require("../parser/highLevelAST"); import ll = require("../parser/lowLevelAST"); import llImpl = require("../parser/jsyaml/jsyaml2lowLevel"); import hlImpl = require("../parser/highLevelImpl"); import linter = require("../parser/ast.core/linter"); import expander=require("../parser/ast.core/expanderLL"); import jsyaml = require("../parser/jsyaml/jsyaml2lowLevel"); import llJson = require("../parser/jsyaml/json2lowLevel"); import referencePatcher=require("../parser/ast.core/referencePatcher"); import referencePatcherLL=require("../parser/ast.core/referencePatcherLL"); import typeExpander = require("./typeExpander"); import jsonSerializerTL = require("./jsonSerializer"); import builder = require("../parser/ast.core/builder"); import typeSystem = def.rt; import nominals = typeSystem.nominalTypes; import typeExpressions = typeSystem.typeExpressions; import universeHelpers = require("../parser/tools/universeHelpers") import universes = require("../parser/tools/universe") import util = require("../util/index") import defaultCalculator = require("../parser/wrapped-ast/defaultCalculator"); import helpersLL = require("../parser/wrapped-ast/helpersLL"); import stubs = require('../parser/stubs'); import _ = require("underscore"); import path = require("path"); var pathUtils = require("path"); const RAML_MEDIATYPE = "application/raml+yaml"; export function dump(node: hl.IHighLevelNode|hl.IAttribute, options:SerializeOptions):any{ return new JsonSerializer(options).dump(node); } var getRootPath = function (node:hl.IParseResult) { var rootPath:string; var rootNode = node.root(); if (rootNode) { var llRoot = rootNode.lowLevel(); if (llRoot) { var rootUnit = llRoot.unit() if (rootUnit) { rootPath = rootUnit.absolutePath(); } } } return rootPath; }; export function appendSourcePath(eNode: hl.IParseResult, result: any) { let unitPath = hlImpl.actualPath(eNode); let sourceMap = result.sourceMap; if (!sourceMap) { sourceMap = {}; result.sourceMap = sourceMap; } if (!sourceMap.path) { sourceMap.path = unitPath; } }; export class JsonSerializer { constructor(private options?:SerializeOptions) { this.options = this.options || {}; if (this.options.allParameters == null) { this.options.allParameters = true; } if (this.options.expandSecurity == null) { this.options.expandSecurity = true; } if (this.options.serializeMetadata == null) { this.options.serializeMetadata = false; } if (this.options.attributeDefaults == null) { this.options.attributeDefaults = true; } if(this.options.expandExpressions == null){ this.options.expandExpressions = true; } if (this.options.expandTypes == null) { //this.options.expandTypes = true; } else if(this.options.expandTypes){ if(!this.options.typeExpansionRecursionDepth){ this.options.typeExpansionRecursionDepth = 0; } } this.defaultsCalculator = new defaultCalculator.AttributeDefaultsCalculator(true,true); this.nodeTransformers = [ new MethodsTransformer(), new ResourcesTransformer(this.options,this), new TypeTransformer(this.options,this), new UsesDeclarationTransformer(this), new SimpleNamesTransformer(), new TemplateParametrizedPropertiesTransformer(), new SchemasTransformer(), new ProtocolsToUpperCaseTransformer(), new ReferencesTransformer(), new Api10SchemasTransformer(), new SecurityExpandingTransformer(this.options.expandSecurity), new AllParametersTransformer(this.options.allParameters,this.options.serializeMetadata) ]; fillTransformersMap(this.nodeTransformers,this.nodeTransformersMap); fillTransformersMap(this.nodePropertyTransformers,this.nodePropertyTransformersMap); } nodeTransformers:Transformation[]; nodePropertyTransformers:Transformation[] = [ new ItemsTransformer() //new MethodsToMapTransformer(), //new TypesTransformer(), //new TraitsTransformer(), //new SecuritySchemesTransformer(), //new ResourceTypesTransformer(), //new ResourcesTransformer(), //new TypeExampleTransformer(), //new ParametersTransformer(), //new TypesTransformer(), //new UsesTransformer(), //new PropertiesTransformer(), //new TypeValueTransformer(), //new ExamplesTransformer(), //new ResponsesTransformer(), //new BodiesTransformer(), //new AnnotationsTransformer(), //new SecuritySchemesTransformer(), //new AnnotationTypesTransformer(), //new TemplateParametrizedPropertiesTransformer(), //new TraitsTransformer(), //new ResourceTypesTransformer(), //new FacetsTransformer(), //new SchemasTransformer(), //new ProtocolsToUpperCaseTransformer(), //new ResourceTypeMethodsToMapTransformer(), //new ReferencesTransformer(), //new OneElementArrayTransformer() ]; nodeTransformersMap:TransformersMap = {}; nodePropertyTransformersMap:TransformersMap = {}; private defaultsCalculator:defaultCalculator.AttributeDefaultsCalculator; private helpersMap:{[key:string]:HelperMethod}; private _astRoot:hl.IParseResult; private init(node:hl.IParseResult){ this._astRoot = node; this.helpersMap = { "baseUriParameters" : baseUriParametersHandler, "uriParameters" : uriParametersHandler }; var isElement = node.isElement(); if(isElement){ (<hlImpl.ASTNodeImpl>node).types(); var eNode = node.asElement(); var definition = eNode.definition(); if(definition.universe().version()=="RAML08"){ if(universeHelpers.isApiType(definition)){ var schemasCache08 = {}; eNode.elementsOfKind(universes.Universe08.Api.properties.schemas.name) .forEach(x=>schemasCache08[x.name()] = x); this.helpersMap["schemaContent"] = new SchemaContentHandler(schemasCache08); } } if(universeHelpers.isApiSibling(definition)) { this.helpersMap["traits"] = new TemplatesHandler(helpersLL.allTraits(eNode, false)); this.helpersMap["resourceTypes"] = new TemplatesHandler(helpersLL.allResourceTypes(eNode, false)); } else if(!universeHelpers.isLibraryType(definition)){ delete this.options.expandTypes; } } } astRoot():hl.IParseResult{ return this._astRoot; } private dispose(){ delete this.helpersMap; } dump(node:hl.IParseResult):any { this.init(node); var isElement = node.isElement(); var highLevelParent = node.parent(); var rootNodeDetails = !highLevelParent && this.options.rootNodeDetails; var rootPath = getRootPath(node); var result = this.dumpInternal(node, null, rootPath,null,true); if (rootNodeDetails) { var obj:any = result; result= {}; result.specification = obj; if(isElement) { var eNode = node.asElement(); var definition = eNode.definition(); if (definition) { let universe = definition.universe(); var ramlVersion = universe.version(); result.ramlVersion = ramlVersion; let typeName = definition.nameId(); if(!typeName){ if(definition.isAssignableFrom(def.universesInfo.Universe10.TypeDeclaration.name)){ let typeDecl = universe.type(def.universesInfo.Universe10.TypeDeclaration.name); let map:any = {}; typeDecl.allSubTypes().forEach(x=>map[x.nameId()]=true); for(let st of definition.allSuperTypes()){ if(map[st.nameId()]){ typeName = st.nameId(); break; } } } } result.type = typeName; } result.errors = this.dumpErrors(core.errors(eNode)); } } this.dispose(); return result; } dumpInternal(_node:hl.IParseResult, nodeProperty:hl.IProperty, rp:string,meta?:core.NodeMetadata,isRoot = false):any { if (_node == null) { return null; } if((<hlImpl.BasicASTNode>_node).isReused()) { let reusedJSON = (<hlImpl.BasicASTNode>_node).getJSON(); if(reusedJSON!=null){ //console.log(_node.id()); return reusedJSON; } } let result:any = {}; if (_node.isElement()) { let map:{[key:string]:PropertyValue} = {}; let eNode = _node.asElement(); let definition = eNode.definition(); let eNodeProperty = nodeProperty || eNode.property(); if(universeHelpers.isExampleSpecType(definition)){ if(eNode.parent()!=null){ result = "";//to be fulfilled by the transformer } else { let at = hlImpl.auxiliaryTypeForExample(eNode); let eObj:any = helpersLL.dumpExpandableExample( at.examples()[0], this.options.dumpXMLRepresentationOfExamples); let uses = eNode.elementsOfKind("uses").map(x=>this.dumpInternal(x, x.property(),rp)); if (uses.length > 0) { eObj["uses"] = uses; } result = eObj; } } else { let obj:any = {}; let children = (<hl.IParseResult[]>eNode.attrs()) .concat(eNode.children().filter(x=>!x.isAttr())); for (let ch of children) { let prop = ch.property(); if (prop != null) { let pName = prop.nameId(); let pVal = map[pName]; if (pVal == null) { pVal = new PropertyValue(prop); map[pName] = pVal; } pVal.registerValue(ch); } else { let llNode = ch.lowLevel(); let key = llNode.key(); if (key) { //obj[key] = llNode.dumpToObject(); } } } let scalarsAnnotations:any = {}; let scalarsSources:any = {}; for (let p of definition.allProperties() .concat((<def.NodeClass>definition).allCustomProperties())) { if (def.UserDefinedProp.isInstance(p)) { continue; } let pName = p.nameId(); //TODO implement as transformer or ignore case if (!isRoot && pName == "uses") { if (universeHelpers.isApiSibling(eNode.root().definition())) { continue; } } let pVal = map[pName]; if(universeHelpers.isTypeProperty(p)){ if(pVal && pVal.arr.length==1 && pVal.arr[0].isAttr()&&(pVal.arr[0].asAttr().value()==null)){ pVal = undefined; } } pVal = this.applyHelpers(pVal, eNode, p, this.options.serializeMetadata); let udVal = obj[pName]; let aVal:any; if (pVal !== undefined) { if (pVal.isMultiValue) { aVal = pVal.arr.map((x,i)=>{ let pMeta:core.NodeMetadata = pVal.hasMeta ? pVal.mArr[i] : null; return this.dumpInternal(x, pVal.prop,rp,pMeta); }); if (p.isValueProperty()) { let sAnnotations = []; let sPaths:string[] = []; let gotScalarAnnotations = false; pVal.arr.filter(x=>x.isAttr()).map(x=>x.asAttr()) .filter(x=>x.isAnnotatedScalar()).forEach(x=> { let sAnnotations1 = x.annotations().map(x=>this.dumpInternal(x, null,rp)); gotScalarAnnotations = gotScalarAnnotations || sAnnotations1.length > 0; sAnnotations.push(sAnnotations1); sPaths.push(hlImpl.actualPath(x,true)); }); if (gotScalarAnnotations) { scalarsAnnotations[pName] = sAnnotations; } if(sPaths.filter(x=>x!=null).length>0){ scalarsSources[pName] = sPaths.map(x=>{return {path:x}}); } } if (universeHelpers.isTypeDeclarationDescendant(definition) && universeHelpers.isTypeProperty(p)) { //TODO compatibility crutch if (pVal.arr.map(x=>(<hl.IAttribute>x).value()) .filter(x=>hlImpl.isStructuredValue(x)).length > 0) { aVal = aVal[0]; } } } else { aVal = this.dumpInternal(pVal.val, pVal.prop,rp); if (p.isValueProperty()) { let attr = pVal.val.asAttr(); if (attr.isAnnotatedScalar()) { let sAnnotations = attr.annotations().map(x=>this.dumpInternal(x, null,rp)); if (sAnnotations.length > 0) { scalarsAnnotations[pName] = [ sAnnotations ]; } } if(!(<hlImpl.ASTPropImpl>attr).isFromKey()) { let sPath = hlImpl.actualPath(attr, true); if (sPath) { scalarsSources[pName] = [ { path: sPath }]; } } } } } else if (udVal !== undefined) { aVal = udVal; } else if (this.options.attributeDefaults) { var defVal = this.defaultsCalculator.attributeDefaultIfEnabled(eNode, p); if(defVal != null) { meta = meta || new core.NodeMetadataImpl(); if (Array.isArray(defVal)) { defVal = defVal.map(x=> { if (hlImpl.isASTPropImpl(x)) { return this.dumpInternal(<hl.IParseResult>x, p, rp); } return x; }); } else if (hlImpl.BasicASTNode.isInstance(defVal)) { defVal = this.dumpInternal(<hl.IParseResult>defVal, p, rp); } aVal = defVal; if (aVal != null && p.isMultiValue() && !Array.isArray(aVal)) { aVal = [aVal]; } var insertionKind = this.defaultsCalculator.insertionKind(eNode,p); if(insertionKind == defaultCalculator.InsertionKind.CALCULATED) { (<core.NodeMetadataImpl>meta).registerCalculatedValue(pName); } else if(insertionKind == defaultCalculator.InsertionKind.BY_DEFAULT){ (<core.NodeMetadataImpl>meta).registerInsertedAsDefaultValue(pName); } } } aVal = applyTransformersMap(eNode, p, aVal, this.nodePropertyTransformersMap); if (aVal != null) { //TODO implement as transformer if ((pName === "type" || pName == "schema") && aVal && aVal.forEach && typeof aVal[0] === "string") { let schemaString = aVal[0].trim(); let canBeJson = (schemaString[0] === "{" && schemaString[schemaString.length - 1] === "}"); let canBeXml = (schemaString[0] === "<" && schemaString[schemaString.length - 1] === ">"); if (canBeJson || canBeXml) { let schemaPath = getSchemaPath(eNode); if(schemaPath){ result["schemaPath"] = schemaPath; let sourceMap = result.sourceMap; if(!sourceMap){ sourceMap = {}; result.sourceMap = sourceMap; } sourceMap.path = schemaPath; } } } result[pName] = aVal; } } if (this.options.dumpSchemaContents && map["schema"]) { if (map["schema"].prop.range().key() == universes.Universe08.SchemaString) { var schemas = eNode.root().elementsOfKind("schemas"); schemas.forEach(x=> { if (x.name() == result["schema"]) { var vl = x.attr("value"); if (vl) { result["schema"] = vl.value(); result["schemaContent"] = vl.value(); } } }) } } if (this.options.serializeMetadata) { this.serializeMeta(result, eNode, meta); } if (Object.keys(scalarsAnnotations).length > 0) { result["scalarsAnnotations"] = scalarsAnnotations; } if (this.options.sourceMap && Object.keys(scalarsSources).length > 0) { let sourceMap = result.sourceMap; if(!sourceMap){ sourceMap = {}; result.sourceMap = sourceMap; } sourceMap.scalarsSources = scalarsSources; } var pProps = helpersLL.getTemplateParametrizedProperties(eNode); if (pProps) { result["parametrizedProperties"] = pProps; } if (universeHelpers.isTypeDeclarationDescendant(definition)) { let fixedFacets = helpersLL.typeFixedFacets(eNode); if (fixedFacets) { result["fixedFacets"] = fixedFacets; } } result = applyTransformersMap(eNode, eNodeProperty, result, this.nodeTransformersMap); } if(this.options.sourceMap && typeof result == "object") { appendSourcePath(eNode, result); } } else if (_node.isAttr()) { let aNode = _node.asAttr(); let val = aNode.value(); let prop = aNode.property(); let rangeType = prop.range(); let isValueType = rangeType.isValueType(); if (isValueType && aNode['value']) { val = aNode['value'](); if(val==null && universeHelpers.isAnyTypeType(rangeType)){ let llAttrNode = aNode.lowLevel(); if(aNode.isAnnotatedScalar()){ llAttrNode = _.find(llAttrNode.children(),x=>x.key()=="value"); } if(llAttrNode&&llAttrNode.valueKind()!=yaml.Kind.SCALAR) { val = aNode.lowLevel().dumpToObject(); var pName = prop.nameId() if(aNode.lowLevel().key() == pName && typeof val == "object" && val.hasOwnProperty(pName)){ val = val[pName] } } } } if (val!=null&&(typeof val == 'number' || typeof val == 'string' || typeof val == 'boolean')) { if(universeHelpers.isStringTypeDescendant(prop.range())){ val = '' + val; } } else if (hlImpl.isStructuredValue(val)) { val = aNode.plainValue(); if (hlImpl.BasicASTNode.isInstance(val)) { val = this.dumpInternal(val, nodeProperty || aNode.property(), rp, null, true); } } else if(jsyaml.ASTNode.isInstance(val)||proxy.LowLevelProxyNode.isInstance(val)){ val = (<ll.ILowLevelASTNode>val).dumpToObject(); } val = applyTransformersMap(aNode, nodeProperty || aNode.property(), val, this.nodeTransformersMap); result = val; } else { let llNode = _node.lowLevel(); result = llNode ? llNode.dumpToObject() : null; } _node.setJSON(result); return result; } getDefaultsCalculator() : defaultCalculator.AttributeDefaultsCalculator { return this.defaultsCalculator; } private canBeFragment(node:core.BasicNodeImpl) { var definition = node.definition(); var arr = [definition].concat(definition.allSubTypes()); var arr1 = arr.filter(x=>x.getAdapter(def.RAMLService).possibleInterfaces() .filter(y=>y.nameId() == def.universesInfo.Universe10.FragmentDeclaration.name).length > 0); return arr1.length > 0; } private dumpErrors(errors:core.RamlParserError[]) { return errors.map(x=> { var eObj = this.dumpErrorBasic(x); if (x.trace && x.trace.length > 0) { eObj['trace'] = this.dumpErrors(x.trace); } return eObj; }).sort((x, y)=> { if (x.path != y.path) { return x.path.localeCompare(y.path); } if(y.range.start==null){ return 1; } else if(x.range.start==null){ return -1; } if(y.range.start==null){ return 1; } else if(x.range.start==null){ return -1; } if (x.range.start.position != y.range.start.position) { return x.range.start.position - y.range.start.position; } return x.code - y.code; }); } private dumpErrorBasic(x) { var eObj:any = { "code": x.code, //TCK error code "message": x.message, "path": x.path, "line": x.line, "column": x.column, "position": x.start, "range": x.range }; if (x.isWarning === true) { eObj.isWarning = true; } return eObj; } serializeMeta(obj:any, node:hl.IHighLevelNode,_meta:core.NodeMetadata) { if (!this.options.serializeMetadata) { return; } var definition = node.definition(); var isOptional = universeHelpers.isMethodType(definition)&&node.optional(); if(!_meta && !isOptional){ return; } var meta = <core.NodeMetadataImpl>_meta || new core.NodeMetadataImpl(false,false); if(isOptional){ meta.setOptional(); } //if (!meta.isDefault()) { obj["__METADATA__"] = meta.toJSON(); //} } private applyHelpers(pVal:PropertyValue, node:hl.IHighLevelNode, p:hl.IProperty, serializeMetadata:boolean) { var pName = p.nameId(); var hMethod = this.helpersMap[pName]; if (!hMethod) { return pVal; } var newVal = hMethod.apply(node, pVal, p, serializeMetadata); if (!newVal) { return pVal; } return newVal; } } export interface SerializeOptions{ /** * For root nodes additional details can be included into output. If the option is set to `true`, * node content is returned as value of the **specification** root property. Other root properties are: * * * **ramlVersion** version of RAML used by the specification represented by the node * * **type** type of the node: Api, Overlay, Extension, Library, or any other RAML type in fragments case * * **errors** errors of the specification represented by the node * @default false */ rootNodeDetails?:boolean /** * Whether to serialize metadata * @default false */ serializeMetadata?:boolean dumpXMLRepresentationOfExamples?:boolean dumpSchemaContents?:boolean attributeDefaults?:boolean allParameters?:boolean expandSecurity?:boolean expandExpressions?:boolean typeReferences?:boolean expandTypes?:boolean typeExpansionRecursionDepth?:number sourceMap?:boolean } class PropertyValue{ constructor(public prop:hl.IProperty){ this.isMultiValue = prop.isMultiValue(); } arr:hl.IParseResult[] = []; mArr:core.NodeMetadata[] = []; val:hl.IParseResult; isMultiValue:boolean; hasMeta:boolean; registerValue(val:hl.IParseResult){ if(this.isMultiValue){ this.arr.push(val); } else{ this.val = val; } } registerMeta(m:core.NodeMetadata){ if(this.isMultiValue){ this.mArr.push(m); } } } function applyHelpers( pVal:PropertyValue, node:hl.IHighLevelNode, p:hl.IProperty, serializeMetadata:boolean, schemasCache08:{[key:string]:hl.IHighLevelNode}){ var newVal:PropertyValue; if(universeHelpers.isBaseUriParametersProperty(p)){ newVal = baseUriParameters(node,pVal,p,serializeMetadata); } if(universeHelpers.isUriParametersProperty(p)){ newVal = uriParameters(node,pVal,p,serializeMetadata); } else if(universeHelpers.isTraitsProperty(p)){ var arr = helpersLL.allTraits(node,false); newVal = contributeExternalNodes(node,arr,p,serializeMetadata); } else if(universeHelpers.isResourceTypesProperty(p)){ var arr = helpersLL.allResourceTypes(node,false); newVal = contributeExternalNodes(node,arr,p,serializeMetadata); } else if(p.nameId()=="schemaContent"){ var attr = helpersLL.schemaContent08Internal(node,schemasCache08); if(attr){ newVal = new PropertyValue(p); newVal.registerValue(attr); } } if(newVal){ return newVal; } return pVal; } function uriParameters(resource:hl.IHighLevelNode,pVal:PropertyValue,p:hl.IProperty,serializeMetadata=false):PropertyValue{ var attr = resource.attr(universes.Universe10.Resource.properties.relativeUri.name); if(!attr){ return pVal; } var uri = attr.value(); return extractParams(pVal, uri, resource,p,serializeMetadata); } function baseUriParameters(api:hl.IHighLevelNode,pVal:PropertyValue,p:hl.IProperty,serializeMetadata=false):PropertyValue{ var buriAttr = api.attr(universes.Universe10.Api.properties.baseUri.name); var uri = buriAttr ? buriAttr.value() : ''; return extractParams(pVal, uri, api,p,serializeMetadata); } function extractParams( pVal:PropertyValue, uri:string, ownerHl:hl.IHighLevelNode, prop:hl.IProperty, serializeMetadata:boolean):PropertyValue { if(!uri){ return pVal; } var describedParams = {}; if(pVal) { pVal.arr.forEach(x=> { var arr = describedParams[x.name()]; if (!arr) { arr = []; describedParams[x.name()] = arr; } arr.push(x); }); } var newVal = new PropertyValue(prop); var prev = 0; var mentionedParams = {}; var gotUndescribedParam = false; for (var i = uri.indexOf('{'); i >= 0; i = uri.indexOf('{', prev)) { prev = uri.indexOf('}', ++i); if(prev<0){ break; } var paramName = uri.substring(i, prev); mentionedParams[paramName] = true; if (describedParams[paramName]) { describedParams[paramName].forEach(x=>{ newVal.registerValue(x); newVal.registerMeta(null); }); } else { gotUndescribedParam = true; var universe = ownerHl.definition().universe(); var nc=<def.NodeClass>universe.type(universes.Universe10.StringTypeDeclaration.name); var hlNode=stubs.createStubNode(nc,null,paramName,ownerHl.lowLevel().unit()); hlNode.setParent(ownerHl); hlNode.attrOrCreate("name").setValue(paramName); (<hlImpl.ASTNodeImpl>hlNode).patchProp(prop); newVal.registerValue(hlNode); if(serializeMetadata) { newVal.hasMeta = true; var meta = new core.NodeMetadataImpl(); meta.setCalculated(); newVal.registerMeta(meta); } } } if(!gotUndescribedParam){ return pVal; } Object.keys(describedParams).filter(x=>!mentionedParams[x]) .forEach(x=>describedParams[x].forEach(y=>{ newVal.registerValue(y); if(newVal.hasMeta){ newVal.registerMeta(null); } })); return newVal; }; function contributeExternalNodes( ownerNode:hl.IHighLevelNode, arr:hl.IHighLevelNode[], p:hl.IProperty, serializeMetadata:boolean):PropertyValue{ if(arr.length==0){ return null; } var rootPath = ownerNode.lowLevel().unit().absolutePath(); var newVal = new PropertyValue(p); arr.forEach(x=>{ newVal.registerValue(x); if(serializeMetadata){ if(x.lowLevel().unit().absolutePath()!=rootPath){ newVal.hasMeta = true; var meta = new core.NodeMetadataImpl(); meta.setCalculated(); newVal.mArr.push(meta); } else{ newVal.mArr.push(null); } } }); return newVal; } interface HelperMethod{ apply(node:hl.IHighLevelNode, pVal:PropertyValue, p:hl.IProperty, serializeMetadata:boolean):PropertyValue } var baseUriParametersHandler:HelperMethod = { apply: (node:hl.IHighLevelNode, pVal:PropertyValue, p:hl.IProperty, serializeMetadata:boolean) => { var buriAttr = node.attr(universes.Universe10.Api.properties.baseUri.name); var uri = buriAttr ? buriAttr.value() : ''; return extractParams(pVal, uri, node, p, serializeMetadata); } } var uriParametersHandler:HelperMethod = { apply: (node:hl.IHighLevelNode, pVal:PropertyValue, p:hl.IProperty, serializeMetadata:boolean) => { var attr = node.attr(universes.Universe10.Resource.properties.relativeUri.name); if (!attr) { return pVal; } var uri = attr.value(); return extractParams(pVal, uri, node, p, serializeMetadata); } } class TemplatesHandler implements HelperMethod { constructor(public arr:hl.IHighLevelNode[]){} apply(node:hl.IHighLevelNode, pVal:PropertyValue, p:hl.IProperty, serializeMetadata:boolean){ //var arr = helpersHL.allTraits(node,false); return contributeExternalNodes(node, this.arr, p, serializeMetadata); } } class SchemaContentHandler implements HelperMethod{ constructor(public schemasCache08:any){} apply(node:hl.IHighLevelNode, pVal:PropertyValue, p:hl.IProperty, serializeMetadata:boolean){ var newVal:PropertyValue = null; var attr = helpersLL.schemaContent08Internal(node, this.schemasCache08); if (attr) { newVal = new PropertyValue(p); newVal.registerValue(attr); } return newVal; } } export interface Transformation{ match(node:hl.IParseResult,prop:nominals.IProperty):boolean transform(value:any,node:hl.IParseResult,valueProp?:hl.IProperty); registrationInfo():Object; } export type TransformersMap = {[key:string]:{[key:string]:{[key:string]:Transformation[]}}}; export function applyTransformersMap(node:hl.IParseResult,prop:hl.IProperty,value:any,map:TransformersMap):any{ var definition:hl.ITypeDefinition; if(node.isElement()){ definition = node.asElement().definition(); } else if(node.isAttr()){ var p = node.asAttr().property(); if(p){ definition = p.range(); } } if(definition instanceof def.UserDefinedClass || definition.isUserDefined()){ definition = _.find(definition.allSuperTypes(),x=>!x.isUserDefined()); } if(definition==null){ return value; } var rv = definition.universe().version(); var uMap = map[rv]; if(!uMap){ return value; } var tMap = uMap[definition.nameId()]; if(!tMap){ return value; } var pName = prop ? prop.nameId() : "__$$anyprop__"; var arr = tMap[pName]; if(!arr){ arr = tMap["__$$anyprop__"]; } if(!arr){ return value; } for(var t of arr){ value = t.transform(value,node,prop); } return value; } function fillTransformersMap(tArr:Transformation[], map:TransformersMap){ for(var t of tArr){ var info = t.registrationInfo(); if(!info){ continue; } for(var uName of Object.keys(info)){ var uObject = info[uName]; var uMap = map[uName]; if(uMap==null){ uMap = {}; map[uName] = uMap; } for(var tName of Object.keys(uObject)){ var tObject = uObject[tName]; var tMap = uMap[tName]; if(tMap==null){ tMap = {}; uMap[tName] = tMap; } for(var pName of Object.keys(tObject)) { var arr:Transformation[] = tMap[pName]; if(arr==null){ arr = []; if(pName!="__$$anyprop__"){ var aArr = tMap["__$$anyprop__"]; if(aArr){ arr = arr.concat(aArr); } } tMap[pName] = arr; } if(pName=="__$$anyprop__"){ for(var pn of Object.keys(tMap)){ tMap[pn].push(t); } } else{ arr.push(t); } } } } } } interface ObjectPropertyMatcher{ match(td:nominals.ITypeDefinition,prop:nominals.IProperty):boolean registrationInfo():Object; } abstract class AbstractObjectPropertyMatcher implements ObjectPropertyMatcher{ match(td:nominals.ITypeDefinition,prop:nominals.IProperty):boolean{ if(td==null){ return false; } var info = this.registrationInfo(); var ver = td.universe().version(); if(td instanceof def.UserDefinedClass || td.isUserDefined()){ td = _.find(td.allSuperTypes(),x=>!x.isUserDefined()); if(td==null){ return prop==null; } } var uObject = info[ver]; if(!uObject){ return false; } var tObject = uObject[td.nameId()]; if(!tObject){ return false; } var p = (prop == null) || tObject[prop.nameId()]===true || tObject["__$$anyprop__"] === true; return p; } abstract registrationInfo():Object } class BasicObjectPropertyMatcher extends AbstractObjectPropertyMatcher{ constructor( protected typeName:string, protected propName:string, protected applyToDescendatns:boolean = false, protected restrictToUniverses: string[] = ["RAML10","RAML08"] ){ super(); } private regInfo:any; registrationInfo():Object{ if(this.regInfo){ return this.regInfo; } var result = {}; var uObjects:any[] = []; for(var uName of this.restrictToUniverses){ var uObj = {}; result[uName] = uObj; uObjects.push(uObj); } var tObjects:any[] = []; for(var uName of Object.keys(result)){ var t = def.getUniverse(uName).type(this.typeName); if(t) { var uObject = result[uName]; var typeNames = [this.typeName]; if (this.applyToDescendatns) { t.allSubTypes().forEach(x=>typeNames.push(x.nameId())); } for (var tName of typeNames) { var tObject = {}; if(this.propName!=null) { tObject[this.propName] = true; } else{ tObject["__$$anyprop__"] = true; } uObject[tName] = tObject; } } } this.regInfo = {}; Object.keys(result).forEach(x=>{ var uObject = result[x]; if(Object.keys(uObject).length>0){ this.regInfo[x] = uObject; } }); return this.regInfo; } } abstract class MatcherBasedTransformation implements Transformation{ constructor(protected matcher:ObjectPropertyMatcher){} match(node:hl.IParseResult,prop:nominals.IProperty):boolean{ var definition:hl.ITypeDefinition; if(node.isElement()) { definition = node.asElement().definition(); } else if(node.isAttr()){ var prop1 = node.asAttr().property(); if(prop1){ definition = prop1.range(); } } return definition ? this.matcher.match(definition,prop) : false; } abstract transform(_value:any,node:hl.IParseResult); registrationInfo():Object{ return this.matcher.registrationInfo(); } } abstract class BasicTransformation extends MatcherBasedTransformation{ constructor( protected typeName:string, protected propName:string, protected applyToDescendatns:boolean = false, protected restrictToUniverses: string[] = ["RAML10","RAML08"] ){ super(new BasicObjectPropertyMatcher(typeName,propName,applyToDescendatns,restrictToUniverses)); } } class CompositeObjectPropertyMatcher extends AbstractObjectPropertyMatcher{ constructor(protected matchers:ObjectPropertyMatcher[]){ super(); } private regInfo:any; registrationInfo():Object{ if(this.regInfo){ return this.regInfo; } this.regInfo = mergeRegInfos(this.matchers.map(x=>x.registrationInfo())); return this.regInfo; } } // class ArrayToMapTransformer implements Transformation{ // // constructor(protected matcher:ObjectPropertyMatcher, protected propName:string){} // // match(node:hl.IParseResult,prop:nominals.IProperty):boolean{ // return node.isElement()&&this.matcher.match(node.asElement().definition(),prop); // } // // transform(value:any,node:hl.IParseResult){ // if(Array.isArray(value)&&value.length>0 && value[0][this.propName]){ // var obj = {}; // value.forEach(x=>{ // var key = x["$$"+this.propName]; // if(key!=null){ // delete x["$$"+this.propName]; // } // else{ // key = x[this.propName]; // } // var previous = obj[key]; // if(previous){ // if(Array.isArray(previous)){ // previous.push(x); // } // else{ // obj[key] = [ previous, x ]; // } // } // else { // obj[key] = x; // } // }); // return obj; // } // return value; // } // // registrationInfo():Object{ // return this.matcher.registrationInfo(); // } // } class ResourcesTransformer extends BasicTransformation{ constructor(private options:SerializeOptions = {},private owner:JsonSerializer){ super(universes.Universe10.Resource.name,null,true); } transform(value:any,node:hl.IParseResult){ if(Array.isArray(value)){ return value; } var relUri = value[universes.Universe10.Resource.properties.relativeUri.name]; if(relUri){ var segments = relUri.trim().split("/"); while(segments.length > 0 && segments[0].length == 0){ segments.shift(); } value["relativeUriPathSegments"] = segments; value.absoluteUri = helpersLL.absoluteUri(node.asElement()); value.completeRelativeUri = helpersLL.completeRelativeUri(node.asElement()); if(universeHelpers.isResourceType(node.parent().definition())){ value.parentUri = helpersLL.completeRelativeUri(node.parent()); value.absoluteParentUri = helpersLL.absoluteUri(node.parent()); } else{ value.parentUri = ""; const parent = this.owner.astRoot().asElement() || node.parent(); let baseUriAttr = parent.attr(universes.Universe10.Api.properties.baseUri.name); let baseUri = (baseUriAttr && baseUriAttr.value())||""; value.absoluteParentUri = baseUri; } } return value; } } class ItemsTransformer extends BasicTransformation { constructor() { super(universes.Universe10.TypeDeclaration.name, universes.Universe10.ArrayTypeDeclaration.properties.items.name, true); } transform(value:any,node:hl.IParseResult){ if(!value || !Array.isArray(value) || value.length != 1 || (typeof value[0] !== "object") || !node.isElement()){ return value; } let highLevelNode = node.asElement(); let result = value[0]; let td = highLevelNode.definition().universe().type(universe.Universe10.TypeDeclaration.name); let hasType = highLevelNode.definition().universe().type(universe.Universe10.ArrayTypeDeclaration.name); let tNode:hlImpl.ASTNodeImpl; let llNode = highLevelNode.attr("items").lowLevel(); let itemsLocalType:nominals.ITypeDefinition; let stop:boolean; do { stop = true; tNode = new hlImpl.ASTNodeImpl(llNode, highLevelNode, td, hasType.property(universe.Universe10.ArrayTypeDeclaration.properties.items.name)); itemsLocalType = tNode.localType(); if(itemsLocalType && jsonSerializerTL.isEmpty(itemsLocalType)&& itemsLocalType.superTypes().length==1){ let tChildren = llNode.children().filter(y=>y.key()=="type"); if(tChildren.length==1){ if(tChildren[0].resolvedValueKind()==yaml.Kind.SCALAR){ result = tChildren[0].value(); break; } else{ llNode = tChildren[0]; stop = false; result = result.type[0]; } } } } while ( !stop ); if(itemsLocalType.getExtra(tsInterfaces.TOP_LEVEL_EXTRA) && typeof result == "object" && ! Array.isArray(result)){ result = result.type; } if(!Array.isArray(result)){ result = [ result ]; } return result; } } class MethodsTransformer extends BasicTransformation{ constructor(){ super(universes.Universe10.Method.name,null,true); } transform(value:any,node:hl.IParseResult){ if(Array.isArray(value)){ return value; } let parent = node.parent(); if(!universeHelpers.isResourceType(parent.definition())){ return value; } value.parentUri = helpersLL.completeRelativeUri(parent); value.absoluteParentUri = helpersLL.absoluteUri(parent); return value; } } class TypeTransformer extends BasicTransformation{ constructor(private options:SerializeOptions = {},private owner:JsonSerializer){ super(universes.Universe10.TypeDeclaration.name,null,true); } transform(_value:any,node:hl.IParseResult,valueProp?:hl.IProperty){ const nodeProperty = node.property(); if(this.options.expandTypes && node&&node.isElement()){ let parent = node.parent(); if(parent && universeHelpers.isTypeDeclarationDescendant(parent.definition())){ return {}; } let pt = node.asElement().parsedType(); let isInsideTemplate = linter.typeOfContainingTemplate(node)!=null; let isAnnotationType = nodeProperty && universeHelpers.isAnnotationTypesProperty(nodeProperty); let result = new typeExpander.TypeExpander({ node: node.asElement(), typeCollection: (<hlImpl.ASTNodeImpl>node).types(), typeExpansionRecursionDepth: this.options.typeExpansionRecursionDepth, serializeMetadata: this.options.serializeMetadata, sourceMap: this.options.sourceMap, isInsideTemplate: isInsideTemplate, isAnnotationType: isAnnotationType }).serializeType(pt); if(nodeProperty&&universeHelpers.isParametersProperty(nodeProperty)){ if(result.name && util.stringEndsWith(result.name,"?")){ result.name = result.name.substring(0,result.name.length-1); if(!result.hasOwnProperty("required")){ result.required = false; } } else if(!result.hasOwnProperty("required")){ result.required = true; this.appendMeta(result,"required","insertedAsDefault"); } if(result.displayName && util.stringEndsWith(result.displayName,"?")){ result.displayName = result.displayName.substring(0,result.displayName.length-1); } if(_value.hasOwnProperty("enum")&&!result.hasOwnProperty("enum")){ result.enum = _value.enum; this.appendMeta(result,"enum","calculated"); } if(_value.__METADATA__ && _value.__METADATA__.calculated===true){ this.appendMeta(result,null,"calculated"); } } if(nodeProperty&&universeHelpers.isBodyProperty(nodeProperty)){ if(result.name != _value.name){ result.name = _value.name; result.displayName = _value.displayName; } this.appendMeta(result,"name","calculated",_value.__METADATA__); this.appendMeta(result,"displayName","calculated",_value.__METADATA__); } if(_value && typeof _value === "object" && _value.hasOwnProperty("parametrizedProperties")){ result.parametrizedProperties = _value.parametrizedProperties; } return result; } var isArray = Array.isArray(_value); if(isArray && _value.length==0){ return _value; } var value = isArray ? _value[0] : _value; if(this.options.sourceMap) { appendSourcePath(node, value); } const aPropsVal = value[def.universesInfo.Universe10.ObjectTypeDeclaration.properties.additionalProperties.name]; if(typeof aPropsVal !== "boolean" && aPropsVal){ delete value[def.universesInfo.Universe10.ObjectTypeDeclaration.properties.additionalProperties.name]; } let prop = nodeProperty; // if(universeHelpers.isItemsProperty(prop)||universeHelpers.isTypeProperty(prop)){ // if(value.name == prop.nameId()){ // delete value.name; // } // } // else if(universeHelpers.isBodyProperty(prop)){ // if(node.lowLevel().key()==prop.nameId()){ // delete value.name; // } // } var isTopLevel = node.asElement().localType().getExtra(tsInterfaces.TOP_LEVEL_EXTRA) var isInTypes = nodeProperty && (universeHelpers.isTypesProperty(nodeProperty) ||universeHelpers.isSchemasProperty(nodeProperty)) if(isInTypes || !isTopLevel) { var exampleObj = helpersLL.typeExample( node.asElement(), this.options.dumpXMLRepresentationOfExamples); if (exampleObj) { value["examples"] = [exampleObj]; } else { var examples = helpersLL.typeExamples( node.asElement(), this.options.dumpXMLRepresentationOfExamples); if (examples.length > 0) { value["examples"] = examples; } } delete value["example"]; if (value["examples"] != null) { value["simplifiedExamples"] = value["examples"].map(x => { if (x == null) { return x; } let val = x["value"]; if (val == null) { return val; } else if (typeof val === "object") { return JSON.stringify(val); } return val; }); } } if(value.hasOwnProperty("schema")){ if(!value.hasOwnProperty("type")){ value["type"] = value["schema"]; } else{ var typeValue = value["type"]; if(!Array.isArray(typeValue)){ typeValue = [ typeValue ]; value["type"] = typeValue; } value["type"] = _.unique(typeValue); } delete value["schema"]; } if(valueProp && universeHelpers.isSchemaProperty(valueProp)&&value.name=="schema"){ value.name = "type"; if(value.displayName=="schema"){ value.displayName="type"; } } //this.refineTypeValue(value,node.asElement()); if(!Array.isArray(value.type)){ value.type = [value.type]; } let tp = node.isElement()&&node.asElement().parsedType(); if(tp&&tp.isUnion()){ const reg = node.root().types().getTypeRegistry(); tp.declaredFacets().filter(x=>{ if(value.hasOwnProperty(x.facetName())){ return false; } if(!x.validateSelf(reg).isOk()){ return false; } if(!this.facetsToExtract[x.facetName()]){ return false; } if(x.facetName()=="discriminatorValue"){ return (<any>x).isStrict(); } return true; }).forEach(x=>value[x.facetName()]=x.value()); } value.mediaType = RAML_MEDIATYPE; if(node && node.isElement()) { var e = node.asElement(); var externalType = e.localType().isExternal() ? e.localType(): null; if (!externalType) { for (var st of e.localType().allSuperTypes()) { if (st.isExternal()) { externalType = st; } } } if (externalType) { var sch = externalType.external().schema().trim(); if (util.stringStartsWith(sch, "<")) { value.mediaType = "application/xml"; } else { value.mediaType = "application/json"; } if(_value.type && _value.type.length){ let t = _value.type[0]; if(typeof t == "string"){ t = t.trim(); if(t == sch){ _value.type[0] = t; } } } } } if (!prop || !(universeHelpers.isHeadersProperty(prop) || universeHelpers.isQueryParametersProperty(prop) || universeHelpers.isUriParametersProperty(prop) || universeHelpers.isPropertiesProperty(prop) || universeHelpers.isBaseUriParametersProperty(prop))) { delete value["required"]; let metaObj = value["__METADATA__"] if (metaObj) { let pMetaObj = metaObj["primitiveValuesMeta"]; if (pMetaObj) { delete pMetaObj["required"]; if(!Object.keys(pMetaObj).length){ delete metaObj["primitiveValuesMeta"] } } if(!Object.keys(metaObj).length){ delete value["__METADATA__"] } } } var typeValue = value["type"]; if (typeValue.forEach && typeof typeValue[0] === "string") { var runtimeType = node.asElement().localType(); if (runtimeType && runtimeType.hasExternalInHierarchy()) { var schemaString = typeValue[0].trim(); var canBeJson = (schemaString[0] === "{" && schemaString[schemaString.length - 1] === "}"); var canBeXml= (schemaString[0] === "<" && schemaString[schemaString.length - 1] === ">"); if (canBeJson) { value["typePropertyKind"] = "JSON"; } else if (canBeXml) { value["typePropertyKind"] = "XML"; } else { value["typePropertyKind"] = "TYPE_EXPRESSION"; } } else { value["typePropertyKind"] = "TYPE_EXPRESSION"; } } else if (typeof typeValue === "object"){ value["typePropertyKind"] = "INPLACE"; } if(this.options.expandExpressions) { this.processExpressions(value,node); } return _value; } private facetsToExtract = { "maxItems" : true, "minItems" : true, "discriminatorValue" : true, "discriminator" : true, "pattern" : true, "minLength" : true, "maxLength" : true, "enum" : true, "minimum" : true, "maximum" : true, "format" : true, "fileTypes" : true } private processExpressions(value:any,node:hl.IParseResult):any{ this.parseExpressions(value,node); } private parseExpressions(obj,node:hl.IParseResult){ let typeValue = obj.type; let isSingleString = Array.isArray(typeValue) && typeValue.map(x=> typeof x === "string"); this.parseExpressionsForProperty(obj,"items", node); this.parseExpressionsForProperty(obj,"type", node); if(isSingleString){ let t = node.asElement().parsedType(); for(let i = 0 ; i < obj.type.length; i++) { if(!isSingleString[i]){ continue; } let newTypeValue = obj.type[i]; if (newTypeValue && typeof newTypeValue == "object") { let copy = false; if(!this.isEmptyUnion(t)&&obj.type.length==1){ copy = Object.keys(newTypeValue).filter(x=>{ if(x=="type"){ return false; } return !obj.hasOwnProperty(x); }).length>0; } if (copy) { Object.keys(newTypeValue).forEach(x => { obj[x] = newTypeValue[x]; }); } else if (!newTypeValue.name) { newTypeValue.name = "type" newTypeValue.displayName = "type" newTypeValue.typePropertyKind = "TYPE_EXPRESSION" this.appendMeta(newTypeValue, "displayName", "calculated"); } } } } } appendSource(obj:any,sourceMap:any){ if(!this.options.sourceMap||!sourceMap){ return; } obj.sourceMap = sourceMap; } appendMeta(obj:any,field:string,kind:string,maskObj?:any){ if(!this.options.serializeMetadata){ return; } let useMask = maskObj!=null; let maskScalarsObj = useMask && maskObj.primitiveValuesMeta; if(useMask && ! maskScalarsObj){ return; } let maskFObj = maskScalarsObj && maskScalarsObj[field]; if(useMask){ if(!maskFObj) { return; } else if(!maskFObj[kind]){ return; } } let metaObj = obj.__METADATA__; if(!metaObj){ metaObj = {}; obj.__METADATA__ = metaObj; } if(field==null){ metaObj[kind] = true; return; } let scalarsObj = metaObj.primitiveValuesMeta; if(!scalarsObj){ scalarsObj = {}; metaObj.primitiveValuesMeta = scalarsObj; } let fObj = scalarsObj[field]; if(!fObj){ fObj = {}; scalarsObj[field] = fObj; } fObj[kind] = true; } isEmptyUnion(t:typeSystem.IParsedType){ if(!t.isUnion()){ return false; } return !t.isEmpty(); } private parseExpressionsForProperty(obj:any, prop:string,node:hl.IParseResult){ let value = obj[prop]; if(!value){ return; } let isSingleString = false; if(!Array.isArray(value)){ if(value && typeof value == "object"){ if(value.unfolded){ obj.prop = value.unfolded; } else { this.parseExpressions(value,node); } return; } else if(typeof value == "string"){ isSingleString = true; value = [ value ]; } } let resultingArray:any[] = []; for(var i = 0 ; i < value.length ; i++) { let expr = value[i]; if(expr && typeof expr=="object"){ if(expr.unfolded){ expr = expr.unfolded; } else { this.parseExpressions(expr,node); } } if(typeof expr != "string"){ resultingArray.push(expr); continue; } let str = expr; var gotExpression = referencePatcher.checkExpression(str); if (!gotExpression) { let ref = this.options.typeReferences ? this.typeReference(node, expr) : expr; resultingArray.push(ref); continue; } let escapeData:referencePatcher.EscapeData = { status: referencePatcher.ParametersEscapingStatus.NOT_REQUIRED }; if(expr.indexOf("<<")>=0){ escapeData = referencePatcher.escapeTemplateParameters(expr); if (escapeData.status == referencePatcher.ParametersEscapingStatus.OK) { str = escapeData.resultingString; gotExpression = referencePatcher.checkExpression(str); if(!gotExpression){ resultingArray.push(expr); continue; } } else if (escapeData.status == referencePatcher.ParametersEscapingStatus.ERROR){ resultingArray.push(expr); continue; } } let parsedExpression: any; try { parsedExpression = typeExpressions.parse(str); } catch (exception) { resultingArray.push(expr); continue; } if (!parsedExpression) { resultingArray.push(expr); continue; } let exprObj = this.expressionToObject(parsedExpression,escapeData,node,obj.sourceMap); if(exprObj!=null){ resultingArray.push(exprObj); } } obj[prop] = isSingleString ? resultingArray[0] : resultingArray; } private expressionToObject( expr:typeExpressions.BaseNode, escapeData:referencePatcher.EscapeData, node:hl.IParseResult, sourceMap:any):any{ let result:any; let arr = 0; if(expr.type=="name"){ let literal = <typeExpressions.Literal>expr; arr = literal.arr; result = literal.value; if(escapeData.status==referencePatcher.ParametersEscapingStatus.OK){ let unescapeData = referencePatcher.unescapeTemplateParameters(result,escapeData.substitutions); if(unescapeData.status==referencePatcher.ParametersEscapingStatus.OK){ result = unescapeData.resultingString; } } if(this.options.typeReferences){ result = this.typeReference(node, result); } } else if(expr.type=="union"){ let union = <typeExpressions.Union>expr; result = { type: ["union"], anyOf: [] }; let components = toOptionsArray(union); for(var c of components){ if(c==null){ result = null; break; } let c1 = this.expressionToObject(c,escapeData,node,sourceMap); result.anyOf.push(c1); } result.anyOf = _.unique(result.anyOf); this.appendSource(result,sourceMap); } else if(expr.type=="parens"){ let parens = <typeExpressions.Parens>expr; arr = parens.arr; result = this.expressionToObject(parens.expr,escapeData,node,sourceMap); } if(result!=null && arr>0) { if (typeof result === "string"){ // result = { // type: [ result ], // name: "items", // displayName: "items", // typePropertyKind: "TYPE_EXPRESSION" // }; // this.appendMeta(result,"displayName","calculated"); // this.appendSource(result,sourceMap); } while (arr-- > 0) { result = { type: ["array"], items: [ result ] }; if(arr>0){ result.name = "items"; result.displayName = "items"; result.typePropertyKind = "TYPE_EXPRESSION"; this.appendMeta(result,"displayName","calculated"); this.appendSource(result,sourceMap); } } } if(typeof result === "object"){ result.typePropertyKind = "TYPE_EXPRESSION"; result.sourceMap = sourceMap; } return result; } private typeReference(node: hl.IParseResult, result: string) { if(!result){ return result; } let rootNode = this.owner.astRoot(); let types = rootNode.isElement() && rootNode.asElement().types(); let t = types && types.getTypeRegistry().getByChain(result); if (!t) { // let i0 = result.indexOf("<<"); // if(i0>=0 && result.indexOf(">>",i0)>=0 && linter.typeOfContainingTemplate(node)){ // // } // else { // // } } else if (t.isBuiltin()) { } else { let src = t.getExtra(typeSystem.SOURCE_EXTRA); let llNode: ll.ILowLevelASTNode; if (hlImpl.BasicASTNode.isInstance(src)) { llNode = src.lowLevel(); } else if (jsyaml.ASTNode.isInstance(src) || llJson.AstNode.isInstance(src) || proxy.LowLevelProxyNode.isInstance(src)) { llNode = src; } else if (hlImpl.LowLevelWrapperForTypeSystem.isInstance(src)) { llNode = src.node(); } let llRoot = rootNode.lowLevel(); if(llRoot.actual().libExpanded){ result = "#/specification/types/" + t.name(); } else { let location = ""; let rootUnit = llRoot.unit(); let unit = llNode.unit(); if (unit.absolutePath() != rootUnit.absolutePath()) { let resolver = (<jsyaml.Project>unit.project()).namespaceResolver(); let d = resolver.expandedPathMap(rootUnit)[unit.absolutePath()]; location = location + d.includePath; } result = location + "#/specification/types/" + t.name(); } } return result; } } class SimpleNamesTransformer extends MatcherBasedTransformation{ constructor(){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.TypeDeclaration.name,universes.Universe10.LibraryBase.properties.annotationTypes.name,true,["RAML10"]), new BasicObjectPropertyMatcher(universes.Universe10.TypeDeclaration.name,universes.Universe10.LibraryBase.properties.types.name,true,["RAML10"]), new BasicObjectPropertyMatcher(universes.Universe10.Trait.name,universes.Universe10.LibraryBase.properties.traits.name,true,["RAML10"]), new BasicObjectPropertyMatcher(universes.Universe10.AbstractSecurityScheme.name,universes.Universe10.LibraryBase.properties.securitySchemes.name,true,["RAML10"]), new BasicObjectPropertyMatcher(universes.Universe10.ResourceType.name,universes.Universe10.LibraryBase.properties.resourceTypes.name,true,["RAML10"]) ])); } transform(value:any,node:hl.IParseResult){ if (!node.parent() || !node.parent().lowLevel()["libProcessed"]) { return value; } patchDisplayName(value,node.lowLevel()); return value; } } class TemplateParametrizedPropertiesTransformer extends MatcherBasedTransformation{ constructor(){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.ResourceType.name,null,true), new BasicObjectPropertyMatcher(universes.Universe10.Trait.name,null,true), new BasicObjectPropertyMatcher(universes.Universe10.Method.name,null,true), new BasicObjectPropertyMatcher(universes.Universe10.Response.name,null,true), new BasicObjectPropertyMatcher(universes.Universe08.Parameter.name,null,true), new BasicObjectPropertyMatcher(universes.Universe08.BodyLike.name,null,true), new BasicObjectPropertyMatcher(universes.Universe10.TypeDeclaration.name,null,true) ])); } transform(value:any,node:hl.IParseResult){ if(Array.isArray(value)){ return value; } var propName = def.universesInfo.Universe10.Trait.properties.parametrizedProperties.name; var parametrizedProps = value[propName]; if(parametrizedProps){ Object.keys(parametrizedProps).forEach(y=>{ value[y] = parametrizedProps[y]; }); delete value[propName]; } return value; } } // // class PropertiesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.ObjectTypeDeclaration.name,universes.Universe10.ObjectTypeDeclaration.properties.properties.name,true) // ]),"name"); // } // // } class SchemasTransformer extends BasicTransformation{ constructor(){ super(universes.Universe08.GlobalSchema.name,universes.Universe08.Api.properties.schemas.name,true, ["RAML08"]); } transform(value:any,node:hl.IParseResult){ if(Array.isArray(value)){ return value; } else { if(value.sourceMap){ delete value.sourceMap["scalarsSources"]; if(Object.keys(value.sourceMap).length==0){ delete value["sourceMap"]; } } value.name = value.key; delete value.key; return value; } } } class ProtocolsToUpperCaseTransformer extends MatcherBasedTransformation{ constructor(){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.Api.name,universes.Universe10.Api.properties.protocols.name,true), new BasicObjectPropertyMatcher(universes.Universe10.MethodBase.name,universes.Universe10.MethodBase.properties.protocols.name,true), ])); } transform(value:any,node:hl.IParseResult){ if(typeof(value)=='string'){ return value.toUpperCase(); } else if(Array.isArray(value)){ return value.map(x=>x.toUpperCase()); } return value; } } class ReferencesTransformer extends MatcherBasedTransformation{ constructor(){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.SecuritySchemeRef.name,universes.Universe10.Api.properties.securedBy.name,true), new BasicObjectPropertyMatcher(universes.Universe10.TraitRef.name,universes.Universe10.MethodBase.properties.is.name,true), new BasicObjectPropertyMatcher(universes.Universe10.ResourceTypeRef.name,universes.Universe10.ResourceBase.properties.type.name,true) ])); } transform(value:any,node:hl.IParseResult){ if(value==null){ return null; } if(Array.isArray(value)){ return value; } return this.toSimpleValue(value); } private toSimpleValue(x):any { if(typeof(x) !== "object"){ return { name: x }; } let result:any = { name: x['name'] } var params = x['value']; if (params) { Object.keys(params).forEach(y=>{ result.parameters = result.parameters||[]; result.parameters.push({ name: y, value: params[y] }); }); } return result; } } class UsesDeclarationTransformer extends BasicTransformation { constructor(private dumper:JsonSerializer) { super(universes.Universe10.LibraryBase.name, null, true, ["RAML10"]); } private referencePatcher:referencePatcherLL.ReferencePatcher; private getReferencePatcher(){ this.referencePatcher = this.referencePatcher || new referencePatcherLL.ReferencePatcher(); return this.referencePatcher; } transform(_value:any,node?:hl.IParseResult){ let llNode = node.lowLevel(); let actual = llNode && llNode.actual(); let libExpanded = actual && actual.libExpanded; if(!libExpanded){ return _value; } let usesArray = _value[def.universesInfo.Universe10.FragmentDeclaration.properties.uses.name]; if(!usesArray||!Array.isArray(usesArray)||usesArray.length==0){ return _value; } let unit = llNode.unit(); let resolver = (<llImpl.Project>unit.project()).namespaceResolver(); if(!resolver){ return _value; } let nsMap = resolver.expandedNSMap(unit); if(!nsMap){ return _value; } let usagePropName = def.universesInfo.Universe10.Library.properties.usage.name; let annotationsPropName = def.universesInfo.Universe10.Annotable.properties.annotations.name; for(let u of usesArray){ let namespace = u.key; let usesEntry = nsMap[namespace]; if(!usesEntry){ continue; } let libUnit = usesEntry.unit; let libNode = libUnit.ast() let libAnnotations = libNode.children().filter(x=>{ var key = x.key() return util.stringStartsWith(key,"(") && util.stringEndsWith(key,")") }) let libUsage = libNode.children().find(x=>x.key()==usagePropName) if(libUsage){ u[usagePropName] = libUsage.value(); } if(libAnnotations.length>0){ var annotableType = node.root().definition().universe().type(universes.Universe10.Annotable.name) var annotationsProp = annotableType.property(universes.Universe10.Annotable.properties.annotations.name) let usesEntryAnnotations:any[] = []; for(let a of libAnnotations){ let dumped = a.dumpToObject(); let aObj = { name: a.key().substring(1,a.key().length-1), value: dumped[Object.keys(dumped)[0]] } if(!aObj || !aObj.name){ continue; } let aName = aObj.name; var hasRootMediaType = unit.ast().children().some(x=>x.key()==universes.Universe10.Api.properties.mediaType.name) var scope = new referencePatcherLL.Scope() scope.hasRootMediaType = hasRootMediaType var state = new referencePatcherLL.State(this.getReferencePatcher(),unit,scope,resolver) let patchedReference = this.getReferencePatcher().resolveReferenceValueBasic( aName, state, "annotationTypes",[unit, libUnit]); if(!patchedReference){ continue; } aObj.name = patchedReference.value(); usesEntryAnnotations.push(aObj); } if(usesEntryAnnotations.length>0){ u[annotationsPropName] = usesEntryAnnotations; } } } return _value; } } class SecurityExpandingTransformer extends MatcherBasedTransformation { constructor(private enabled: boolean = false) { super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.Api.name, null, true), new BasicObjectPropertyMatcher(universes.Universe10.Overlay.name, null, true), new BasicObjectPropertyMatcher(universes.Universe10.Extension.name, null, true), new BasicObjectPropertyMatcher(universes.Universe10.Library.name, null, true) ])); } match(node: hl.IParseResult, prop: nominals.IProperty): boolean { return this.enabled ? super.match(node, prop) : false; } registrationInfo(): Object { return this.enabled ? super.registrationInfo() : null; } transform(value:any,_node:hl.IParseResult){ this.processApi(value); return value; } private processApi(value:any){ let securitySchemesArr = value[def.universesInfo.Universe10.Api.properties.securitySchemes.name]; if(!securitySchemesArr || securitySchemesArr.length==0){ return; } let securitySchemes:any = {}; for(let ss of securitySchemesArr){ securitySchemes[ss.name] = ss; } this.expandSecuredBy(value, securitySchemes); let resources = value[def.universesInfo.Universe10.Api.properties.resources.name]; if(resources) { for (let r of resources) { this.processResource(r, securitySchemes); } } let resourceTypes = value[def.universesInfo.Universe10.LibraryBase.properties.resourceTypes.name]; if(resourceTypes) { for (let r of resourceTypes) { this.processResource(r, securitySchemes); } } let traits = value[def.universesInfo.Universe10.LibraryBase.properties.traits.name]; if(traits) { for (let t of traits) { this.expandSecuredBy(t, securitySchemes); } } return value; } private processResource(res:any,securitySchemes:any){ this.expandSecuredBy(res,securitySchemes); let methods = res[def.universesInfo.Universe10.Resource.properties.methods.name]; if(methods) { for (let m of methods) { this.expandSecuredBy(m, securitySchemes); } } let resources = res[def.universesInfo.Universe10.Resource.properties.resources.name]; if(resources) { for (let r of resources) { this.processResource(r, securitySchemes); } } } private expandSecuredBy(obj:any,securitySchemes:any){ let securedBy = obj[def.universesInfo.Universe10.ResourceBase.properties.securedBy.name]; if(!securedBy){ return; } for(let i = 0 ; i < securedBy.length ; i++){ let ref = securedBy[i]; if(ref==null){ continue; } let sch:any; if(typeof ref == "string"){ sch = securitySchemes[ref]; } else if (typeof ref == "object"){ let refObj = ref; ref = ref.name;//Object.keys(refObj)[0]; sch = JSON.parse(JSON.stringify(securitySchemes[ref])); let params = refObj.parameters; if(params && params.length>0) { // let paramNames = Object.keys(params); // if (paramNames.length > 0) { let settings: any = sch.settings; if (!settings) { settings = {}; sch.settings = settings; } for (let pn of params) { settings[pn.name] = pn.value; } //} } } if(!sch){ continue; } securedBy[i] = sch; } } } class AllParametersTransformer extends MatcherBasedTransformation{ constructor(private enabled:boolean=false,private serializeMetadata=false){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.Api.name,null,true) ])); } match(node:hl.IParseResult,prop:nominals.IProperty):boolean{ return this.enabled ? super.match(node,prop) : false; } registrationInfo():Object{ return this.enabled ? super.registrationInfo() : null; } private static uriParamsPropName = universes.Universe10.ResourceBase.properties.uriParameters.name; private static methodsPropName = universes.Universe10.ResourceBase.properties.methods.name; private static resourcesPropName = universes.Universe10.Api.properties.resources.name; private static queryParametersPropName = universes.Universe10.Method.properties.queryParameters.name; private static headersPropName = universes.Universe10.Method.properties.headers.name; private static securedByPropName = universes.Universe10.Method.properties.securedBy.name; private static responsesPropName = universes.Universe10.Method.properties.responses.name; transform(value:any,node:hl.IParseResult,uriParams?:any){ this.processApi(value); return value; } private processApi(api:any){ let params = this.extract(api,def.universesInfo.Universe10.Api.properties.baseUriParameters.name); let resources = api[def.universesInfo.Universe10.Resource.properties.resources.name]||[]; for(let r of resources){ this.processResource(r,params); } } private processResource(resource:any,uriParams:any[]){ let pName = def.universesInfo.Universe10.Resource.properties.uriParameters.name; let params1 = this.extract(resource,pName); let newParams = uriParams.concat(resource[pName]||[]); if(newParams.length>0) { resource[pName] = newParams; } let params2 = uriParams.concat(params1); let methods = resource[def.universesInfo.Universe10.ResourceBase.properties.methods.name]||[]; for(let m of methods){ this.processMethod(m,params2); } let resources = resource[def.universesInfo.Universe10.Resource.properties.resources.name]||[]; for(let r of resources){ this.processResource(r,params2); } } private processMethod(method:any,uriParams:any[]){ this.appendSecurityData(method); let pName = def.universesInfo.Universe10.Resource.properties.uriParameters.name; let newParams = uriParams.concat(method[pName]||[]); if(newParams.length>0) { method[pName] = newParams; } } private appendSecurityData(obj:any){ let headerPName = def.universesInfo.Universe10.Operation.properties.headers.name; let responsesPName = def.universesInfo.Universe10.Operation.properties.responses.name; let queryPName = def.universesInfo.Universe10.Operation.properties.queryParameters.name; let securedBy = obj[def.universesInfo.Universe10.Method.properties.securedBy.name]||[]; for(let sSch of securedBy){ if(!sSch){ continue; } let describedBy = sSch[def.universesInfo.Universe10.AbstractSecurityScheme.properties.describedBy.name]||{}; let sHeaders = this.extract(describedBy,headerPName); let sResponses = this.extract(describedBy,responsesPName); let sQParams = this.extract(describedBy,queryPName); if(sHeaders.length>0){ obj[headerPName] = (obj[headerPName]||[]).concat(sHeaders); } if(sResponses.length>0){ obj[responsesPName] = (obj[responsesPName]||[]).concat(sResponses); } if(sQParams.length>0){ obj[queryPName] = (obj[queryPName]||[]).concat(sQParams); } } } private extract(api: any,pName:string) { let arr = api[pName] || []; arr = JSON.parse(JSON.stringify(arr)); if(this.serializeMetadata) { for (let x of arr) { let mtd = x["__METADATA__"]; if (!mtd) { mtd = {}; x["__METADATA__"] = mtd; } mtd["calculated"] = true; } } return arr; } } // // class MethodsToMapTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.ResourceBase.name,universes.Universe10.ResourceBase.properties.methods.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.Resource.name,universes.Universe08.Resource.properties.methods.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.ResourceType.name,universes.Universe08.ResourceType.properties.methods.name,true) // ]),"method"); // } // } // // class TypesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,universes.Universe10.LibraryBase.properties.types.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,universes.Universe10.LibraryBase.properties.schemas.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,universes.Universe10.LibraryBase.properties.annotationTypes.name,true) // ]),"name"); // } // } // // class TraitsTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name, // universes.Universe10.LibraryBase.properties.traits.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.Api.name, // universes.Universe08.Api.properties.traits.name,true) // ]),"name"); // } // } // // class ResourceTypesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,universes.Universe10.LibraryBase.properties.resourceTypes.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.Api.name,universes.Universe10.Api.properties.resourceTypes.name,true,["RAML08"]) // ]),"name"); // } // } // // class SecuritySchemesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,universes.Universe10.LibraryBase.properties.securitySchemes.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.Api.name,universes.Universe08.Api.properties.securitySchemes.name,true,["RAML08"]) // ]),"name"); // } // } // // class ParametersTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.Api.name,universes.Universe10.Api.properties.baseUriParameters.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.ResourceBase.name,universes.Universe10.ResourceBase.properties.uriParameters.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.Resource.name,universes.Universe08.Resource.properties.uriParameters.name,true,["RAML08"]), // new BasicObjectPropertyMatcher(universes.Universe10.ResourceBase.name,universes.Universe10.MethodBase.properties.queryParameters.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.MethodBase.name,universes.Universe10.MethodBase.properties.queryParameters.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.Operation.name,universes.Universe10.MethodBase.properties.queryParameters.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.Operation.name,universes.Universe10.MethodBase.properties.headers.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.MethodBase.name,universes.Universe10.MethodBase.properties.headers.name,true), // new BasicObjectPropertyMatcher(universes.Universe08.BodyLike.name,universes.Universe08.BodyLike.properties.formParameters.name) // ]),"name"); // } // // } // // class ResponsesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // //new BasicObjectPropertyMatcher(universes.Universe10.Operation.name,universes.Universe10.Operation.properties.responses.name,true), // new BasicObjectPropertyMatcher(universes.Universe10.MethodBase.name,universes.Universe10.MethodBase.properties.responses.name,true) // ]),"code"); // } // } // // class AnnotationsTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.Annotable.name,universes.Universe10.Annotable.properties.annotations.name,true) // ]),"name"); // } // } // // class BodiesTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.Response.name,universes.Universe10.Response.properties.body.name), // new BasicObjectPropertyMatcher(universes.Universe10.MethodBase.name,universes.Universe10.MethodBase.properties.body.name,true) // ]),"name"); // } // // } // // class FacetsTransformer extends ArrayToMapTransformer{ // // constructor(){ // super(new CompositeObjectPropertyMatcher([ // new BasicObjectPropertyMatcher(universes.Universe10.TypeDeclaration.name,universes.Universe10.TypeDeclaration.properties.facets.name,true) // ]),"name"); // } // } class Api10SchemasTransformer extends MatcherBasedTransformation{ constructor(){ super(new CompositeObjectPropertyMatcher([ new BasicObjectPropertyMatcher(universes.Universe10.LibraryBase.name,null,true,["RAML10"]) ])); } transform(value:any,node:hl.IParseResult){ if(!value){ return value; } if(!value.hasOwnProperty("schemas")){ return value; } var schemasValue = value["schemas"]; if(!value.hasOwnProperty("types")){ value["types"] = schemasValue; } else{ var typesValue = value["types"]; value["types"] = typesValue.concat(schemasValue); } delete value["schemas"]; return value; } } export function mergeRegInfos(arr:Object[]):Object{ if(arr.length==0){ return {}; } var result = arr[0]; for(var i = 1; i < arr.length ; i++){ var obj = arr[i]; result = mergeObjects(result,obj); } return result; } function mergeObjects(o1:Object,o2:Object):Object{ for(var k of Object.keys(o2)){ var f1 = o1[k]; var f2 = o2[k]; if(f1==null){ o1[k] = f2; } else{ if(typeof(f1)=="object"&&typeof(f2)=="object"){ o1[k] = mergeObjects(f1,f2); } } } return o1; } export function toOptionsArray(union:typeExpressions.Union):typeExpressions.BaseNode[]{ let result:typeExpressions.BaseNode[]; let e1 = union.first; let e2 = union.rest; while(e1.type=="parens" && (<typeExpressions.Parens>e1).arr == 0){ e1 = (<typeExpressions.Parens>e1).expr; } while(e2.type=="parens" && (<typeExpressions.Parens>e2).arr == 0){ e2 = (<typeExpressions.Parens>e2).expr; } if(e1.type=="union"){ result = toOptionsArray(<typeExpressions.Union>e1); } else{ result = [ e1 ]; } if(e2.type=="union"){ result = result.concat(toOptionsArray(<typeExpressions.Union>e2)); } else{ result.push(e2); } return result; } export function getSchemaPath(eNode:hl.IHighLevelNode){ let include = eNode.lowLevel().includePath && eNode.lowLevel().includePath(); if(!include){ let typeAttr = eNode.attr("type"); if(!typeAttr){ typeAttr = eNode.attr("schema"); } if(typeAttr){ include = typeAttr.lowLevel().includePath && typeAttr.lowLevel().includePath(); } } let schemaPath:string; if(include) { let ind = include.indexOf("#"); let postfix = ""; if(ind>=0){ postfix = include.substring(ind); include = include.substring(0,ind); } let aPath = eNode.lowLevel().unit().resolve(include).absolutePath(); let relativePath; if (util.stringStartsWith(aPath,"http://") || util.stringStartsWith(aPath,"https://")) { relativePath = aPath; } else { relativePath = pathUtils.relative(eNode.lowLevel().unit().project().getRootPath(), aPath); } relativePath = relativePath.replace(/\\/g, '/'); schemaPath = relativePath + postfix; } return schemaPath; } export function patchDisplayName(value:any,llNode:ll.ILowLevelASTNode) { let key = llNode.key(); //value["$$name"] = key; let original: ll.ILowLevelASTNode = llNode; while (proxy.LowLevelProxyNode.isInstance(original)) { original = (<proxy.LowLevelProxyNode>original).originalNode(); } let oKey = original.key(); if(proxy.LowLevelProxyNode.isInstance(llNode)) { if (oKey && oKey.indexOf("<<") >= 0 && llNode.key().indexOf("<<") <= 0){ oKey = llNode.key(); } } if(oKey==null){ return; } let aVal = value; //aVal.name = oKey; if (aVal.displayName == key) { aVal.displayName = oKey; } }
the_stack
import React, { useCallback, useEffect, useState } from 'react' import styled from 'styled-components' import { AddRallyPointServerBody, AddRallyPointServerPayload, GetRallyPointServersPayload, RallyPointServer, UpdateRallyPointServerBody, UpdateRallyPointServerPayload, } from '../../common/rally-point' import { apiUrl } from '../../common/urls' import { useForm } from '../forms/form-hook' import SubmitOnEnter from '../forms/submit-on-enter' import CheckIcon from '../icons/material/check-24px.svg' import EditIcon from '../icons/material/edit-24px.svg' import CloseIcon from '../icons/material/ic_close_black_24px.svg' import { IconButton, RaisedButton, TextButton } from '../material/button' import CheckBox from '../material/check-box' import NumberTextField from '../material/number-text-field' import TextField from '../material/text-field' import fetchJson from '../network/fetch' import { useRefreshToken } from '../network/refresh-token' import { useAppDispatch } from '../redux-hooks' import { openSnackbar } from '../snackbars/action-creators' import { CenteredContentContainer } from '../styles/centered-container' import { headline5, subtitle1 } from '../styles/typography' const Content = styled.div` max-width: 960px; margin: 0 auto; ` const PageHeadline = styled.div` ${headline5}; margin-top: 16px; margin-bottom: 8px; ` const HeadlineAndButton = styled.div` display: flex; align-items: center; justify-content: space-between; margin-top: 8px; margin-bottom: 8px; padding-left: 12px; ` const Row = styled.div<{ $editable?: boolean }>` ${subtitle1}; min-height: 48px; display: flex; align-items: center; padding-left: ${props => (props.$editable ? '0' : '12px')}; padding-right: ${props => (props.$editable ? '0' : '172px')}; ` const EnabledContent = styled.div<{ $editable?: boolean }>` width: 24px; height: 24px; margin-right: 16px; flex-grow: 0; margin-bottom: ${props => (props.$editable ? '20px' : '0')}; ` const DescriptionContent = styled.div` flex-basis: 128px; flex-grow: 1; ` const HostnameContent = styled.div` margin: 0 8px; flex-basis: 128px; flex-grow: 1; ` const PortContent = styled.div` width: 104px; flex-grow: 0; ` const ButtonWithIcon = styled(TextButton)` padding-left: 12px; svg { margin-right: 8px; } ` const ButtonRow = styled.div` display: flex; margin-bottom: 20px; ` interface AddServerModel { description?: string hostname?: string port: number } export function AddServerRow(props: { onSubmit: (model: AddServerModel) => void onCancel: () => void }) { const { onSubmit, bindInput, bindCustom } = useForm<AddServerModel>( { port: 14098 }, { description: value => (value && value.length ? undefined : 'Description must be provided'), hostname: value => (value && value.length ? undefined : 'Hostname must be provided'), port: value => value <= 0 || value >= 65536 ? 'Enter a value between 1 and 65535' : undefined, }, { onSubmit: props.onSubmit }, ) return ( <form noValidate={true} onSubmit={onSubmit}> <SubmitOnEnter /> <Row $editable={true}> <EnabledContent $editable={true} /> <DescriptionContent> <TextField {...bindInput('description')} label='Description' floatingLabel={true} dense={true} inputProps={{ tabIndex: 0, }} /> </DescriptionContent> <HostnameContent> <TextField {...bindInput('hostname')} label='Hostname' floatingLabel={true} dense={true} inputProps={{ tabIndex: 0, }} /> </HostnameContent> <PortContent> <NumberTextField {...bindCustom('port')} floatingLabel={false} dense={true} label='Port' inputProps={{ min: 1, max: 65536 }} /> </PortContent> <ButtonRow> <ButtonWithIcon color='accent' label={ <> <CloseIcon /> <span>Cancel</span> </> } onClick={props.onCancel} /> <ButtonWithIcon color='accent' label={ <> <CheckIcon /> <span>Save</span> </> } onClick={onSubmit} /> </ButtonRow> </Row> </form> ) } export function ServerRow({ server, onEdit, }: { server: RallyPointServer onEdit: (server: RallyPointServer) => void }) { const onClick = useCallback(() => { onEdit(server) }, [onEdit, server]) return ( <Row> <EnabledContent>{server.enabled ? <CheckIcon /> : <CloseIcon />}</EnabledContent> <DescriptionContent>{server.description}</DescriptionContent> <HostnameContent>{server.hostname}</HostnameContent> <PortContent>{server.port}</PortContent> <IconButton icon={<EditIcon />} title='Edit' onClick={onClick} /> </Row> ) } type EditServerModel = Omit<RallyPointServer, 'id'> export function EditServerRow({ server, onSubmit: onFormSubmit, onCancel, }: { server: RallyPointServer onSubmit: (server: RallyPointServer) => void onCancel: () => void }) { // Keep a reference to the first server passed in just to ensure we know its ID even if the prop // changes? const [serverState] = useState(server) if (serverState.id !== server.id) { // TODO(tec27): It'd be better to be able to reset the form when this happens, need to // impelment that though. In any case I don't think that can happen with this form because of // keys in its parent throw new Error('server prop changed :(') } const onSubmitCallback = useCallback( (model: EditServerModel) => { onFormSubmit({ ...model, id: serverState.id, }) }, [onFormSubmit, serverState.id], ) const { onSubmit, bindCheckable, bindInput, bindCustom } = useForm<EditServerModel>( { enabled: server.enabled, description: server.description, hostname: server.hostname, port: server.port, }, { description: value => (value && value.length ? undefined : 'Description must be provided'), hostname: value => (value && value.length ? undefined : 'Hostname must be provided'), port: value => value <= 0 || value >= 65536 ? 'Enter a value between 1 and 65535' : undefined, }, { onSubmit: onSubmitCallback }, ) return ( <form noValidate={true} onSubmit={onSubmit}> <SubmitOnEnter /> <Row $editable={true}> <EnabledContent $editable={true}> <CheckBox {...bindCheckable('enabled')} inputProps={{ tabIndex: 0, title: 'Enabled' }} /> </EnabledContent> <DescriptionContent> <TextField {...bindInput('description')} label='Description' floatingLabel={true} dense={true} inputProps={{ tabIndex: 0, }} /> </DescriptionContent> <HostnameContent> <TextField {...bindInput('hostname')} label='Hostname' floatingLabel={true} dense={true} inputProps={{ tabIndex: 0, }} /> </HostnameContent> <PortContent> <NumberTextField {...bindCustom('port')} floatingLabel={true} dense={true} label='Port' inputProps={{ min: 1, max: 65536 }} /> </PortContent> <ButtonRow> <ButtonWithIcon color='accent' label={ <> <CloseIcon /> <span>Cancel</span> </> } onClick={onCancel} /> <ButtonWithIcon color='accent' label={ <> <CheckIcon /> <span>Save</span> </> } onClick={onSubmit} /> </ButtonRow> </Row> </form> ) } export function AdminRallyPoint() { const dispatch = useAppDispatch() const [refreshToken, triggerRefresh] = useRefreshToken() const [servers, setServers] = useState<RallyPointServer[]>([]) const [isAdding, setIsAdding] = useState(false) const [editing, setEditing] = useState<number>() const onAddClick = useCallback(() => { setIsAdding(true) }, []) const onAddSubmit = useCallback( (model: AddServerModel) => { const requestBody: AddRallyPointServerBody = { description: model.description!, hostname: model.hostname!, port: model.port, } fetchJson<AddRallyPointServerPayload>(apiUrl`admin/rally-point/`, { method: 'post', body: JSON.stringify(requestBody), }) .then(() => { setIsAdding(false) triggerRefresh() }) .catch(err => { dispatch(openSnackbar({ message: 'Error adding server' })) console.error(err) }) }, [dispatch, triggerRefresh], ) const onAddCancel = useCallback(() => { setIsAdding(false) }, []) const onEdit = useCallback((server: RallyPointServer) => { setEditing(server.id) }, []) const onEditSubmit = useCallback( (server: RallyPointServer) => { const requestBody: UpdateRallyPointServerBody = { id: server.id, enabled: server.enabled, description: server.description, hostname: server.hostname, port: server.port, } fetchJson<UpdateRallyPointServerPayload>(apiUrl`admin/rally-point/${server.id}`, { method: 'put', body: JSON.stringify(requestBody), }) .then(() => { setEditing(undefined) triggerRefresh() }) .catch(err => { dispatch(openSnackbar({ message: 'Error editing server' })) console.error(err) }) }, [dispatch, triggerRefresh], ) const onEditCancel = useCallback(() => { setEditing(undefined) }, []) useEffect(() => { fetchJson<GetRallyPointServersPayload>(apiUrl`admin/rally-point/`) .then(data => setServers(data.servers)) .catch(err => { dispatch(openSnackbar({ message: 'Error retrieving servers' })) console.error(err) }) }, [dispatch, refreshToken]) return ( <CenteredContentContainer> <Content> <HeadlineAndButton> <PageHeadline>Rally-point servers</PageHeadline> <RaisedButton color='primary' label='Refresh' onClick={triggerRefresh} /> </HeadlineAndButton> {servers.map(s => editing === s.id ? ( <EditServerRow key={s.id} server={s} onSubmit={onEditSubmit} onCancel={onEditCancel} /> ) : ( <ServerRow key={s.id} server={s} onEdit={onEdit} /> ), )} {isAdding ? ( <AddServerRow onSubmit={onAddSubmit} onCancel={onAddCancel} /> ) : ( <RaisedButton color='primary' label={'Add'} onClick={onAddClick} /> )} </Content> </CenteredContentContainer> ) }
the_stack
import { promises as fs } from 'fs'; import * as path from 'path'; import * as io from '@actions/io'; import * as core from '@actions/core'; import * as github from '@actions/github'; import * as git from './git'; import { Benchmark, BenchmarkResult } from './extract'; import { Config, ToolType } from './config'; import { DEFAULT_INDEX_HTML } from './default_index_html'; export type BenchmarkSuites = { [name: string]: Benchmark[] }; export interface DataJson { lastUpdate: number; repoUrl: string; entries: BenchmarkSuites; } export const SCRIPT_PREFIX = 'window.BENCHMARK_DATA = '; const DEFAULT_DATA_JSON = { lastUpdate: 0, repoUrl: '', entries: {}, }; async function loadDataJs(dataPath: string): Promise<DataJson> { try { const script = await fs.readFile(dataPath, 'utf8'); const json = script.slice(SCRIPT_PREFIX.length); const parsed = JSON.parse(json); core.debug(`Loaded data.js at ${dataPath}`); return parsed; } catch (err) { console.log(`Could not find data.js at ${dataPath}. Using empty default: ${err}`); return { ...DEFAULT_DATA_JSON }; } } async function storeDataJs(dataPath: string, data: DataJson) { const script = SCRIPT_PREFIX + JSON.stringify(data, null, 2); await fs.writeFile(dataPath, script, 'utf8'); core.debug(`Overwrote ${dataPath} for adding new data`); } async function addIndexHtmlIfNeeded(dir: string) { const indexHtml = path.join(dir, 'index.html'); try { await fs.stat(indexHtml); core.debug(`Skipped to create default index.html since it is already existing: ${indexHtml}`); return; } catch (_) { // Continue } await fs.writeFile(indexHtml, DEFAULT_INDEX_HTML, 'utf8'); await git.cmd('add', indexHtml); console.log('Created default index.html at', indexHtml); } function biggerIsBetter(tool: ToolType): boolean { switch (tool) { case 'cargo': return false; case 'go': return false; case 'benchmarkjs': return true; case 'pytest': return true; case 'googlecpp': return false; case 'catch2': return false; } } interface Alert { current: BenchmarkResult; prev: BenchmarkResult; ratio: number; } function findAlerts(curSuite: Benchmark, prevSuite: Benchmark, threshold: number): Alert[] { core.debug(`Comparing current:${curSuite.commit.id} and prev:${prevSuite.commit.id} for alert`); const alerts = []; for (const current of curSuite.benches) { const prev = prevSuite.benches.find(b => b.name === current.name); if (prev === undefined) { core.debug(`Skipped because benchmark '${current.name}' is not found in previous benchmarks`); continue; } const ratio = biggerIsBetter(curSuite.tool) ? prev.value / current.value // e.g. current=100, prev=200 : current.value / prev.value; // e.g. current=200, prev=100 if (ratio > threshold) { core.warning( `Performance alert! Previous value was ${prev.value} and current value is ${current.value}.` + ` It is ${ratio}x worse than previous exceeding a ratio threshold ${threshold}`, ); alerts.push({ current, prev, ratio }); } } return alerts; } function getCurrentRepoMetadata() { const { repo, owner } = github.context.repo; return { name: repo, owner: { login: owner, }, // eslint-disable-next-line @typescript-eslint/camelcase html_url: `https://github.com/${owner}/${repo}`, }; } function floatStr(n: number) { if (Number.isInteger(n)) { return n.toFixed(0); } if (n > 0.1) { return n.toFixed(2); } return n.toString(); } function strVal(b: BenchmarkResult): string { let s = `\`${b.value}\` ${b.unit}`; if (b.range) { s += ` (\`${b.range}\`)`; } return s; } function commentFooter(): string { const repoMetadata = getCurrentRepoMetadata(); // eslint-disable-next-line @typescript-eslint/camelcase const repoUrl = repoMetadata.html_url ?? ''; const actionUrl = repoUrl + '/actions?query=workflow%3A' + encodeURIComponent(github.context.workflow); return `This comment was automatically generated by [workflow](${actionUrl}) using [github-action-benchmark](https://github.com/marketplace/actions/continuous-benchmark).`; } function buildComment(benchName: string, curSuite: Benchmark, prevSuite: Benchmark): string { const lines = [ `# ${benchName}`, '', '<details>', '', `| Benchmark suite | Current: ${curSuite.commit.id} | Previous: ${prevSuite.commit.id} | Ratio |`, '|-|-|-|-|', ]; for (const current of curSuite.benches) { let line; const prev = prevSuite.benches.find(i => i.name === current.name); if (prev) { const ratio = biggerIsBetter(curSuite.tool) ? prev.value / current.value // e.g. current=100, prev=200 : current.value / prev.value; line = `| \`${current.name}\` | ${strVal(current)} | ${strVal(prev)} | \`${floatStr(ratio)}\` |`; } else { line = `| \`${current.name}\` | ${strVal(current)} | | |`; } lines.push(line); } // Footer lines.push('', '</details>', '', commentFooter()); return lines.join('\n'); } function buildAlertComment( alerts: Alert[], benchName: string, curSuite: Benchmark, prevSuite: Benchmark, threshold: number, cc: string[], ): string { // Do not show benchmark name if it is the default value 'Benchmark'. const benchmarkText = benchName === 'Benchmark' ? '' : ` **'${benchName}'**`; const title = threshold === 0 ? '# Performance Report' : '# :warning: **Performance Alert** :warning:'; const thresholdString = floatStr(threshold); const lines = [ title, '', `Possible performance regression was detected for benchmark${benchmarkText}.`, `Benchmark result of this commit is worse than the previous benchmark result exceeding threshold \`${thresholdString}\`.`, '', `| Benchmark suite | Current: ${curSuite.commit.id} | Previous: ${prevSuite.commit.id} | Ratio |`, '|-|-|-|-|', ]; for (const alert of alerts) { const { current, prev, ratio } = alert; const line = `| \`${current.name}\` | ${strVal(current)} | ${strVal(prev)} | \`${floatStr(ratio)}\` |`; lines.push(line); } // Footer lines.push('', commentFooter()); if (cc.length > 0) { lines.push('', `CC: ${cc.join(' ')}`); } return lines.join('\n'); } async function leaveComment(commitId: string, body: string, token: string) { core.debug('Sending comment:\n' + body); const repoMetadata = getCurrentRepoMetadata(); // eslint-disable-next-line @typescript-eslint/camelcase const repoUrl = repoMetadata.html_url ?? ''; const client = new github.GitHub(token); const res = await client.repos.createCommitComment({ owner: repoMetadata.owner.login, repo: repoMetadata.name, // eslint-disable-next-line @typescript-eslint/camelcase commit_sha: commitId, body, }); const commitUrl = `${repoUrl}/commit/${commitId}`; console.log(`Comment was sent to ${commitUrl}. Response:`, res.status, res.data); return res; } async function handleComment(benchName: string, curSuite: Benchmark, prevSuite: Benchmark, config: Config) { const { commentAlways, githubToken } = config; if (!commentAlways) { core.debug('Comment check was skipped because comment-always is disabled'); return; } if (!githubToken) { throw new Error("'comment-always' input is set but 'github-token' input is not set"); } core.debug('Commenting about benchmark comparison'); const body = buildComment(benchName, curSuite, prevSuite); await leaveComment(curSuite.commit.id, body, githubToken); } async function handleAlert(benchName: string, curSuite: Benchmark, prevSuite: Benchmark, config: Config) { const { alertThreshold, githubToken, commentOnAlert, failOnAlert, alertCommentCcUsers, failThreshold } = config; if (!commentOnAlert && !failOnAlert) { core.debug('Alert check was skipped because both comment-on-alert and fail-on-alert were disabled'); return; } const alerts = findAlerts(curSuite, prevSuite, alertThreshold); if (alerts.length === 0) { core.debug('No performance alert found happily'); return; } core.debug(`Found ${alerts.length} alerts`); const body = buildAlertComment(alerts, benchName, curSuite, prevSuite, alertThreshold, alertCommentCcUsers); let message = body; let url = null; if (commentOnAlert) { if (!githubToken) { throw new Error("'comment-on-alert' input is set but 'github-token' input is not set"); } const res = await leaveComment(curSuite.commit.id, body, githubToken); // eslint-disable-next-line @typescript-eslint/camelcase url = res.data.html_url; message = body + `\nComment was generated at ${url}`; } if (failOnAlert) { // Note: alertThreshold is smaller than failThreshold. It was checked in config.ts const len = alerts.length; const threshold = floatStr(failThreshold); const failures = alerts.filter(a => a.ratio > failThreshold); if (failures.length > 0) { core.debug('Mark this workflow as fail since one or more fatal alerts found'); if (failThreshold !== alertThreshold) { // Prepend message that explains how these alerts were detected with different thresholds message = `${failures.length} of ${len} alerts exceeded the failure threshold \`${threshold}\` specified by fail-threshold input:\n\n${message}`; } throw new Error(message); } else { core.debug( `${len} alerts exceeding the alert threshold ${alertThreshold} were found but` + ` all of them did not exceed the failure threshold ${threshold}`, ); } } } function addBenchmarkToDataJson( benchName: string, bench: Benchmark, data: DataJson, maxItems: number | null, ): Benchmark | null { // eslint-disable-next-line @typescript-eslint/camelcase const repoMetadata = getCurrentRepoMetadata(); const htmlUrl = repoMetadata.html_url ?? ''; let prevBench: Benchmark | null = null; data.lastUpdate = Date.now(); data.repoUrl = htmlUrl; // Add benchmark result if (data.entries[benchName] === undefined) { data.entries[benchName] = [bench]; core.debug(`No suite was found for benchmark '${benchName}' in existing data. Created`); } else { const suites = data.entries[benchName]; // Get last suite which has different commit ID for alert comment for (const e of suites.slice().reverse()) { if (e.commit.id !== bench.commit.id) { prevBench = e; break; } } suites.push(bench); if (maxItems !== null && suites.length > maxItems) { suites.splice(0, suites.length - maxItems); core.debug( `Number of data items for '${benchName}' was truncated to ${maxItems} due to max-items-in-charts`, ); } } return prevBench; } function isRemoteRejectedError(err: unknown) { if (err instanceof Error) { return ['[remote rejected]', '[rejected]'].some(l => err.message.includes(l)); } return false; } async function writeBenchmarkToGitHubPagesWithRetry( bench: Benchmark, config: Config, retry: number, ): Promise<Benchmark | null> { const { name, tool, ghPagesBranch, benchmarkDataDirPath, githubToken, autoPush, skipFetchGhPages, maxItemsInChart, } = config; const dataPath = path.join(benchmarkDataDirPath, 'data.js'); // FIXME: This payload is not available on `schedule:` or `workflow_dispatch:` events. const isPrivateRepo = github.context.payload.repository?.private ?? false; if (!skipFetchGhPages && (!isPrivateRepo || githubToken)) { await git.pull(githubToken, ghPagesBranch); } else if (isPrivateRepo && !skipFetchGhPages) { core.warning( "'git pull' was skipped. If you want to ensure GitHub Pages branch is up-to-date " + "before generating a commit, please set 'github-token' input to pull GitHub pages branch", ); } await io.mkdirP(benchmarkDataDirPath); const data = await loadDataJs(dataPath); const prevBench = addBenchmarkToDataJson(name, bench, data, maxItemsInChart); await storeDataJs(dataPath, data); await git.cmd('add', dataPath); await addIndexHtmlIfNeeded(benchmarkDataDirPath); await git.cmd('commit', '-m', `add ${name} (${tool}) benchmark result for ${bench.commit.id}`); if (githubToken && autoPush) { try { await git.push(githubToken, ghPagesBranch); console.log( `Automatically pushed the generated commit to ${ghPagesBranch} branch since 'auto-push' is set to true`, ); } catch (err) { if (!isRemoteRejectedError(err)) { throw err; } // Fall through core.warning(`Auto-push failed because the remote ${ghPagesBranch} was updated after git pull`); if (retry > 0) { core.debug('Rollback the auto-generated commit before retry'); await git.cmd('reset', '--hard', 'HEAD~1'); core.warning( `Retrying to generate a commit and push to remote ${ghPagesBranch} with retry count ${retry}...`, ); return await writeBenchmarkToGitHubPagesWithRetry(bench, config, retry - 1); // Recursively retry } else { core.warning(`Failed to add benchmark data to '${name}' data: ${JSON.stringify(bench)}`); throw new Error( `Auto-push failed 3 times since the remote branch ${ghPagesBranch} rejected pushing all the time. Last exception was: ${err.message}`, ); } } } else { core.debug( `Auto-push to ${ghPagesBranch} is skipped because it requires both 'github-token' and 'auto-push' inputs`, ); } return prevBench; } async function writeBenchmarkToGitHubPages(bench: Benchmark, config: Config): Promise<Benchmark | null> { const { ghPagesBranch, skipFetchGhPages } = config; if (!skipFetchGhPages) { await git.cmd('fetch', 'origin', `${ghPagesBranch}:${ghPagesBranch}`); } await git.cmd('switch', ghPagesBranch); try { return await writeBenchmarkToGitHubPagesWithRetry(bench, config, 10); } finally { // `git switch` does not work for backing to detached head await git.cmd('checkout', '-'); } } async function loadDataJson(jsonPath: string): Promise<DataJson> { try { const content = await fs.readFile(jsonPath, 'utf8'); const json: DataJson = JSON.parse(content); core.debug(`Loaded external JSON file at ${jsonPath}`); return json; } catch (err) { core.warning( `Could not find external JSON file for benchmark data at ${jsonPath}. Using empty default: ${err}`, ); return { ...DEFAULT_DATA_JSON }; } } async function writeBenchmarkToExternalJson( bench: Benchmark, jsonFilePath: string, config: Config, ): Promise<Benchmark | null> { const { name, maxItemsInChart, saveDataFile } = config; const data = await loadDataJson(jsonFilePath); const prevBench = addBenchmarkToDataJson(name, bench, data, maxItemsInChart); if (!saveDataFile) { core.debug('Skipping storing benchmarks in external data file'); return prevBench; } try { const jsonDirPath = path.dirname(jsonFilePath); await io.mkdirP(jsonDirPath); await fs.writeFile(jsonFilePath, JSON.stringify(data, null, 2), 'utf8'); } catch (err) { throw new Error(`Could not store benchmark data as JSON at ${jsonFilePath}: ${err}`); } return prevBench; } export async function writeBenchmark(bench: Benchmark, config: Config) { const { name, externalDataJsonPath } = config; const prevBench = externalDataJsonPath ? await writeBenchmarkToExternalJson(bench, externalDataJsonPath, config) : await writeBenchmarkToGitHubPages(bench, config); // Put this after `git push` for reducing possibility to get conflict on push. Since sending // comment take time due to API call, do it after updating remote branch. if (prevBench === null) { core.debug('Alert check was skipped because previous benchmark result was not found'); } else { await handleComment(name, bench, prevBench, config); await handleAlert(name, bench, prevBench, config); } }
the_stack
import Bowser from 'bowser'; import { Logger } from './Logger'; import { EnhancedEventEmitter } from './EnhancedEventEmitter'; import { UnsupportedError, InvalidStateError } from './errors'; import * as utils from './utils'; import * as ortc from './ortc'; import { Transport, TransportOptions, CanProduceByKind } from './Transport'; import { HandlerFactory, HandlerInterface } from './handlers/HandlerInterface'; import { Chrome74 } from './handlers/Chrome74'; import { Chrome70 } from './handlers/Chrome70'; import { Chrome67 } from './handlers/Chrome67'; import { Chrome55 } from './handlers/Chrome55'; import { Firefox60 } from './handlers/Firefox60'; import { Safari12 } from './handlers/Safari12'; import { Safari11 } from './handlers/Safari11'; import { Edge11 } from './handlers/Edge11'; import { ReactNative } from './handlers/ReactNative'; import { RtpCapabilities, MediaKind } from './RtpParameters'; import { SctpCapabilities } from './SctpParameters'; const logger = new Logger('Device'); export type BuiltinHandlerName = | 'Chrome74' | 'Chrome70' | 'Chrome67' | 'Chrome55' | 'Firefox60' | 'Safari12' | 'Safari11' | 'Edge11' | 'ReactNative'; export type DeviceOptions = { /** * The name of one of the builtin handlers. */ handlerName?: BuiltinHandlerName; /** * Custom handler factory. */ handlerFactory?: HandlerFactory; /** * DEPRECATED! * The name of one of the builtin handlers. */ Handler?: string; }; interface InternalTransportOptions extends TransportOptions { direction: 'send' | 'recv'; } export function detectDevice(): BuiltinHandlerName | undefined { // React-Native. // NOTE: react-native-webrtc >= 1.75.0 is required. if (typeof navigator === 'object' && navigator.product === 'ReactNative') { if (typeof RTCPeerConnection === 'undefined') { logger.warn( 'this._detectDevice() | unsupported ReactNative without RTCPeerConnection'); return undefined; } logger.debug('this._detectDevice() | ReactNative handler chosen'); return 'ReactNative'; } // Browser. else if (typeof navigator === 'object' && typeof navigator.userAgent === 'string') { const ua = navigator.userAgent; const browser = Bowser.getParser(ua); const engine = browser.getEngine(); // Chrome, Chromium, and Edge. if (browser.satisfies({ chrome: '>=74', chromium: '>=74', 'microsoft edge': '>=88' })) { return 'Chrome74'; } else if (browser.satisfies({ chrome: '>=70', chromium: '>=70' })) { return 'Chrome70'; } else if (browser.satisfies({ chrome: '>=67', chromium: '>=67' })) { return 'Chrome67'; } else if (browser.satisfies({ chrome: '>=55', chromium: '>=55' })) { return 'Chrome55'; } // Firefox. else if (browser.satisfies({ firefox: '>=60' })) { return 'Firefox60'; } // Firefox on iOS. else if (browser.satisfies({ ios: { OS: '>=14.3', firefox: '>=30.0' } })) { return 'Safari12'; } // Safari with Unified-Plan support enabled. else if ( browser.satisfies({ safari: '>=12.0' }) && typeof RTCRtpTransceiver !== 'undefined' && RTCRtpTransceiver.prototype.hasOwnProperty('currentDirection') ) { return 'Safari12'; } // Safari with Plab-B support. else if (browser.satisfies({ safari: '>=11' })) { return 'Safari11'; } // Old Edge with ORTC support. else if ( browser.satisfies({ 'microsoft edge': '>=11' }) && browser.satisfies({ 'microsoft edge': '<=18' }) ) { return 'Edge11'; } // Best effort for Chromium based browsers. else if (engine.name && engine.name.toLowerCase() === 'blink') { const match = ua.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i); if (match) { const version = Number(match[1]); if (version >= 74) { return 'Chrome74'; } else if (version >= 70) { return 'Chrome70'; } else if (version >= 67) { return 'Chrome67'; } else { return 'Chrome55'; } } else { return 'Chrome74'; } } // Unsupported browser. else { logger.warn( 'this._detectDevice() | browser not supported [name:%s, version:%s]', browser.getBrowserName(), browser.getBrowserVersion()); return undefined; } } // Unknown device. else { logger.warn('this._detectDevice() | unknown device'); return undefined; } } export class Device { // RTC handler factory. private readonly _handlerFactory: HandlerFactory; // Handler name. private readonly _handlerName: string; // Loaded flag. private _loaded = false; // Extended RTP capabilities. private _extendedRtpCapabilities?: any; // Local RTP capabilities for receiving media. private _recvRtpCapabilities?: RtpCapabilities; // Whether we can produce audio/video based on computed extended RTP // capabilities. private readonly _canProduceByKind: CanProduceByKind; // Local SCTP capabilities. private _sctpCapabilities?: SctpCapabilities; // Observer instance. protected readonly _observer = new EnhancedEventEmitter(); /** * Create a new Device to connect to mediasoup server. * * @throws {UnsupportedError} if device is not supported. */ constructor({ handlerName, handlerFactory, Handler }: DeviceOptions = {}) { logger.debug('constructor()'); // Handle deprecated option. if (Handler) { logger.warn( 'constructor() | Handler option is DEPRECATED, use handlerName or handlerFactory instead'); if (typeof Handler === 'string') handlerName = Handler as BuiltinHandlerName; else throw new TypeError( 'non string Handler option no longer supported, use handlerFactory instead'); } if (handlerName && handlerFactory) { throw new TypeError( 'just one of handlerName or handlerInterface can be given'); } if (handlerFactory) { this._handlerFactory = handlerFactory; } else { if (handlerName) { logger.debug('constructor() | handler given: %s', handlerName); } else { handlerName = detectDevice(); if (handlerName) logger.debug('constructor() | detected handler: %s', handlerName); else throw new UnsupportedError('device not supported'); } switch (handlerName) { case 'Chrome74': this._handlerFactory = Chrome74.createFactory(); break; case 'Chrome70': this._handlerFactory = Chrome70.createFactory(); break; case 'Chrome67': this._handlerFactory = Chrome67.createFactory(); break; case 'Chrome55': this._handlerFactory = Chrome55.createFactory(); break; case 'Firefox60': this._handlerFactory = Firefox60.createFactory(); break; case 'Safari12': this._handlerFactory = Safari12.createFactory(); break; case 'Safari11': this._handlerFactory = Safari11.createFactory(); break; case 'Edge11': this._handlerFactory = Edge11.createFactory(); break; case 'ReactNative': this._handlerFactory = ReactNative.createFactory(); break; default: throw new TypeError(`unknown handlerName "${handlerName}"`); } } // Create a temporal handler to get its name. const handler = this._handlerFactory(); this._handlerName = handler.name; handler.close(); this._extendedRtpCapabilities = undefined; this._recvRtpCapabilities = undefined; this._canProduceByKind = { audio : false, video : false }; this._sctpCapabilities = undefined; } /** * The RTC handler name. */ get handlerName(): string { return this._handlerName; } /** * Whether the Device is loaded. */ get loaded(): boolean { return this._loaded; } /** * RTP capabilities of the Device for receiving media. * * @throws {InvalidStateError} if not loaded. */ get rtpCapabilities(): RtpCapabilities { if (!this._loaded) throw new InvalidStateError('not loaded'); return this._recvRtpCapabilities!; } /** * SCTP capabilities of the Device. * * @throws {InvalidStateError} if not loaded. */ get sctpCapabilities(): SctpCapabilities { if (!this._loaded) throw new InvalidStateError('not loaded'); return this._sctpCapabilities!; } /** * Observer. * * @emits newtransport - (transport: Transport) */ get observer(): EnhancedEventEmitter { return this._observer; } /** * Initialize the Device. */ async load( { routerRtpCapabilities }: { routerRtpCapabilities: RtpCapabilities } ): Promise<void> { logger.debug('load() [routerRtpCapabilities:%o]', routerRtpCapabilities); routerRtpCapabilities = utils.clone(routerRtpCapabilities, undefined); // Temporal handler to get its capabilities. let handler: HandlerInterface | undefined; try { if (this._loaded) throw new InvalidStateError('already loaded'); // This may throw. ortc.validateRtpCapabilities(routerRtpCapabilities); handler = this._handlerFactory(); const nativeRtpCapabilities = await handler.getNativeRtpCapabilities(); logger.debug( 'load() | got native RTP capabilities:%o', nativeRtpCapabilities); // This may throw. ortc.validateRtpCapabilities(nativeRtpCapabilities); // Get extended RTP capabilities. this._extendedRtpCapabilities = ortc.getExtendedRtpCapabilities( nativeRtpCapabilities, routerRtpCapabilities); logger.debug( 'load() | got extended RTP capabilities:%o', this._extendedRtpCapabilities); // Check whether we can produce audio/video. this._canProduceByKind.audio = ortc.canSend('audio', this._extendedRtpCapabilities); this._canProduceByKind.video = ortc.canSend('video', this._extendedRtpCapabilities); // Generate our receiving RTP capabilities for receiving media. this._recvRtpCapabilities = ortc.getRecvRtpCapabilities(this._extendedRtpCapabilities); // This may throw. ortc.validateRtpCapabilities(this._recvRtpCapabilities); logger.debug( 'load() | got receiving RTP capabilities:%o', this._recvRtpCapabilities); // Generate our SCTP capabilities. this._sctpCapabilities = await handler.getNativeSctpCapabilities(); logger.debug( 'load() | got native SCTP capabilities:%o', this._sctpCapabilities); // This may throw. ortc.validateSctpCapabilities(this._sctpCapabilities); logger.debug('load() succeeded'); this._loaded = true; handler.close(); } catch (error) { if (handler) handler.close(); throw error; } } /** * Whether we can produce audio/video. * * @throws {InvalidStateError} if not loaded. * @throws {TypeError} if wrong arguments. */ canProduce(kind: MediaKind): boolean { if (!this._loaded) throw new InvalidStateError('not loaded'); else if (kind !== 'audio' && kind !== 'video') throw new TypeError(`invalid kind "${kind}"`); return this._canProduceByKind[kind]; } /** * Creates a Transport for sending media. * * @throws {InvalidStateError} if not loaded. * @throws {TypeError} if wrong arguments. */ createSendTransport( { id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData = {} }: TransportOptions ): Transport { logger.debug('createSendTransport()'); return this._createTransport( { direction : 'send', id : id, iceParameters : iceParameters, iceCandidates : iceCandidates, dtlsParameters : dtlsParameters, sctpParameters : sctpParameters, iceServers : iceServers, iceTransportPolicy : iceTransportPolicy, additionalSettings : additionalSettings, proprietaryConstraints : proprietaryConstraints, appData : appData }); } /** * Creates a Transport for receiving media. * * @throws {InvalidStateError} if not loaded. * @throws {TypeError} if wrong arguments. */ createRecvTransport( { id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData = {} }: TransportOptions ): Transport { logger.debug('createRecvTransport()'); return this._createTransport( { direction : 'recv', id : id, iceParameters : iceParameters, iceCandidates : iceCandidates, dtlsParameters : dtlsParameters, sctpParameters : sctpParameters, iceServers : iceServers, iceTransportPolicy : iceTransportPolicy, additionalSettings : additionalSettings, proprietaryConstraints : proprietaryConstraints, appData : appData }); } private _createTransport( { direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData = {} }: InternalTransportOptions ): Transport { if (!this._loaded) throw new InvalidStateError('not loaded'); else if (typeof id !== 'string') throw new TypeError('missing id'); else if (typeof iceParameters !== 'object') throw new TypeError('missing iceParameters'); else if (!Array.isArray(iceCandidates)) throw new TypeError('missing iceCandidates'); else if (typeof dtlsParameters !== 'object') throw new TypeError('missing dtlsParameters'); else if (sctpParameters && typeof sctpParameters !== 'object') throw new TypeError('wrong sctpParameters'); else if (appData && typeof appData !== 'object') throw new TypeError('if given, appData must be an object'); // Create a new Transport. const transport = new Transport( { direction, id, iceParameters, iceCandidates, dtlsParameters, sctpParameters, iceServers, iceTransportPolicy, additionalSettings, proprietaryConstraints, appData, handlerFactory : this._handlerFactory, extendedRtpCapabilities : this._extendedRtpCapabilities, canProduceByKind : this._canProduceByKind }); // Emit observer event. this._observer.safeEmit('newtransport', transport); return transport; } }
the_stack
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { assert } from '@ember/debug'; import { action } from '@ember/object'; import { next } from '@ember/runloop'; import * as Classes from '../../_private/common/classes'; import * as Keys from '../../_private/common/keys'; import type { IProps } from '../../_private/common'; export interface IOverlayableProps { /** * Whether the overlay should acquire application focus when it first opens. * @default true */ autoFocus?: boolean; /** * Whether pressing the `esc` key should invoke `onClose`. * @default true */ canEscapeKeyClose?: boolean; /** * Whether the overlay should prevent focus from leaving itself. That is, if the user attempts * to focus an element outside the overlay and this prop is enabled, then the overlay will * immediately bring focus back to itself. If you are nesting overlay components, either disable * this prop on the "outermost" overlays or mark the nested ones `usePortal={false}`. * @default true */ enforceFocus?: boolean; /** * If `true` and `usePortal={true}`, the `Portal` containing the children is created and attached * to the DOM when the overlay is opened for the first time; otherwise this happens when the * component mounts. Lazy mounting provides noticeable performance improvements if you have lots * of overlays at once, such as on each row of a table. * @default true */ lazy?: boolean; /** * Indicates how long (in milliseconds) the overlay's enter/leave transition takes. * This is used by React `CSSTransition` to know when a transition completes and must match * the duration of the animation in CSS. Only set this prop if you override Blueprint's default * transitions with new transitions of a different length. * @default 300 */ transitionDuration?: number; /** * Whether the overlay should be wrapped in a `Portal`, which renders its contents in a new * element attached to `portalContainer` prop. * * This prop essentially determines which element is covered by the backdrop: if `false`, * then only its parent is covered; otherwise, the entire page is covered (because the parent * of the `Portal` is the `<body>` itself). * * Set this prop to `false` on nested overlays (such as `Dialog` or `Popover`) to ensure that they * are rendered above their parents. * @default true */ usePortal?: boolean; /** * Space-delimited string of class names applied to the `Portal` element if * `usePortal={true}`. */ portalClassName?: string; /** * The container element into which the overlay renders its contents, when `usePortal` is `true`. * This prop is ignored if `usePortal` is `false`. * @default document.body */ portalContainer?: HTMLElement; /** * A callback that is invoked when user interaction causes the overlay to close, such as * clicking on the overlay or pressing the `esc` key (if enabled). * * Receives the event from the user's interaction, if there was an event (generally either a * mouse or key event). Note that, since this component is controlled by the `isOpen` prop, it * will not actually close itself until that prop becomes `false`. */ onClose?: (event?: HTMLElement | KeyboardEvent | MouseEvent) => void; onBackDropMouseDown?: (event?: MouseEvent) => void; } export interface IBackdropProps { /** CSS class names to apply to backdrop element. */ backdropClassName?: string; /** HTML props for the backdrop element. */ backdropProps?: HTMLDivElement; /** * Whether clicking outside the overlay element (either on backdrop when present or on document) * should invoke `onClose`. * @default true */ canOutsideClickClose?: boolean; /** * Whether a container-spanning backdrop element should be rendered behind the contents. * @default true */ hasBackdrop?: boolean; } export interface IOverlayProps extends IBackdropProps, IOverlayableProps { /** * Toggles the visibility of the overlay and its children. * This prop is required because the component is controlled. */ isOpen: boolean; /** * Name of the transition for internal `CSSTransition`. * Providing your own name here will require defining new CSS transition properties. * @default Classes.OVERLAY */ transitionName?: string; } interface OverlayArgs extends IOverlayProps, IProps { props: OverlayArgs; } export default class Overlay extends Component<OverlayArgs> { containerElement!: HTMLElement; OVERLAY = Classes.OVERLAY; OVERLAY_OPEN = Classes.OVERLAY_OPEN; OVERLAY_INLINE = Classes.OVERLAY_INLINE; OVERLAY_BACKDROP = Classes.OVERLAY_BACKDROP; OVERLAY_CONTENT = Classes.OVERLAY_CONTENT; PORTAL = Classes.PORTAL; popperContainer = '.ember-application'; @tracked prevPropsIsOpen = false; @tracked hasEverOpened = false; //ember css transition state handling @tracked isShowContentAnimation = true; hasBackdropState = true; get props() { return this.args.props || {}; } get getClassName() { let className; if (this.args.className != undefined) { className = this.args.className; } else if (this.props.className != undefined) { className = this.props.className; } return className; } get getPortalClassName() { let portalClassName; if (this.args.portalClassName != undefined) { portalClassName = this.args.portalClassName; } else if (this.props.portalClassName != undefined) { portalClassName = this.props.portalClassName; } return portalClassName; } get getBackdropClassName() { let backdropClassName; if (this.args.backdropClassName != undefined) { backdropClassName = this.args.backdropClassName; } else if (this.props.backdropClassName != undefined) { backdropClassName = this.props.backdropClassName; } return backdropClassName; } get getTransitionName() { let transitionName = this.OVERLAY; if (this.args.transitionName != undefined) { transitionName = this.args.transitionName; } else if (this.props.transitionName != undefined) { transitionName = this.props.transitionName; } return transitionName; } get getLazyProp() { return this.getLazy(); } get renderInPlace() { return !this.getUsePortal(); } get getUserPortalPro() { return this.getUsePortal(); } get getHasBackdropProp() { const hasBackDrop = this.getHasBackdrop(); this.hasBackdropState = hasBackDrop; // eslint-disable-line return hasBackDrop; } get getCanOutsideClickCloseProp() { return this.getCanOutsideClickClose(); } get getIsOpenProp() { this.didReceiveAttributes(); return this.getIsOpen; } get _overlayContainer() { const renderInPlace = !this.getUsePortal(); const maybeContainer = this.popperContainer; let popperContainer; if (renderInPlace) { popperContainer = null; } else if (typeof maybeContainer === 'string') { const selector = maybeContainer; const possibleContainers = self.document.querySelectorAll(selector); assert( `ember-popper with popperContainer selector "${selector}" found ` + `${possibleContainers.length} possible containers when there should be exactly 1`, possibleContainers.length === 1 ); popperContainer = possibleContainers[0]; } return popperContainer; } get hasEverOpenedProp() { return this.getHasEverOpened ? this.OVERLAY_OPEN : ''; } get getHasEverOpened() { return this.hasEverOpened ? true : false; } get getHasBackdropState() { return this.hasBackdropState ? true : false; } getautoFoucs() { let autoFocus = true; if (this.args.autoFocus != undefined) { autoFocus = this.args.autoFocus; } else if (this.props.autoFocus != undefined) { autoFocus = this.props.autoFocus; } return autoFocus; } getCanEscapeKeyClose() { let canEscapeKeyClose = true; if (this.args.canEscapeKeyClose != undefined) { canEscapeKeyClose = this.args.canEscapeKeyClose; } else if (this.props.canEscapeKeyClose != undefined) { canEscapeKeyClose = this.props.canEscapeKeyClose; } return canEscapeKeyClose; } getEnforceFocus() { let enforceFocus = true; if (this.args.enforceFocus != undefined) { enforceFocus = this.args.enforceFocus; } else if (this.props.enforceFocus != undefined) { enforceFocus = this.props.enforceFocus; } return enforceFocus; } getLazy() { let lazy = true; if (this.args.lazy != undefined) { lazy = this.args.lazy; } else if (this.props.lazy != undefined) { lazy = this.props.lazy; } return lazy; } getTransitionDuration() { let transitionDuration = 300; if (this.args.transitionDuration != undefined) { transitionDuration = this.args.transitionDuration; } else if (this.props.transitionDuration != undefined) { transitionDuration = this.props.transitionDuration; } return transitionDuration; } getUsePortal() { let usePortal = true; if (this.args.usePortal != undefined) { usePortal = this.args.usePortal; } else if (this.props.usePortal != undefined) { usePortal = this.props.usePortal; } return usePortal || false; } getCanOutsideClickClose() { let canOutsideClickClose = true; if (this.args.canOutsideClickClose != undefined) { canOutsideClickClose = this.args.canOutsideClickClose; } else if (this.props.canOutsideClickClose != undefined) { canOutsideClickClose = this.props.canOutsideClickClose; } return canOutsideClickClose; } getHasBackdrop() { let hasBackdrop = true; if (this.args.hasBackdrop != undefined) { hasBackdrop = this.args.hasBackdrop; } else if (this.props.hasBackdrop != undefined) { hasBackdrop = this.props.hasBackdrop; } return hasBackdrop; } get getIsOpen() { let isOpen = false; if (this.args.isOpen != undefined) { isOpen = this.args.isOpen; } else if (this.props.isOpen != undefined) { isOpen = this.props.isOpen; } return isOpen; } @action getRefElement(element: HTMLElement) { this.containerElement = element; element.tabIndex = 0; } @action didUpdateElement(_element: HTMLElement) { if (this.getIsOpen) { this.overlayWillOpen(); } } @action willDestroyElementComp() { this.overlayWillClose(); } private static openStack: Overlay[] = []; private static getLastOpened = () => Overlay.openStack[Overlay.openStack.length - 1]; didReceiveAttributes() { if (this.prevPropsIsOpen && !this.getIsOpen) { next(this, () => { this.hasBackdropState = false; this.isShowContentAnimation = false; }); setTimeout(() => { if (!this.isDestroyed) { next(this, () => { this.hasEverOpened = this.getIsOpen ? true : false; }); } if (!this.hasEverOpened) { this.overlayWillClose(); } }, this.getTransitionDuration()); } else { next(this, () => { this.isShowContentAnimation = true; this.hasEverOpened = this.getIsOpen ? true : false; }); } if (!this.prevPropsIsOpen && this.getIsOpen) { next(this, () => { this.hasBackdropState = this.getHasBackdrop(); this.prevPropsIsOpen = this.getIsOpen; }); this.overlayWillOpen(); } } get getIsShowContentAnimation() { return this.isShowContentAnimation ? true : false; } @action handleKeyDown(e: KeyboardEvent) { if (e.which === Keys.ESCAPE && this.getCanEscapeKeyClose()) { if (this.args.onClose) { this.args.onClose(e as KeyboardEvent); } e.preventDefault(); } } @action handleBackdropMouseDown(e: MouseEvent) { if (this.getCanOutsideClickClose()) { if (this.args.onClose) { this.args.onClose(e); } } if (this.getEnforceFocus()) { // make sure document.activeElement is updated before bringing the focus back this.bringFocusInsideOverlay(); } if (this.args.onBackDropMouseDown) { this.args.onBackDropMouseDown(e); } } public bringFocusInsideOverlay() { // always delay focus manipulation to just before repaint to prevent scroll jumping return requestAnimationFrame(() => { // container ref may be undefined between component mounting and Portal rendering // activeElement may be undefined in some rare cases in IE if (this.containerElement == null || document.activeElement == null || !this.getIsOpen) { return; } const isFocusOutsideModal = !this.containerElement.contains(document.activeElement); if (isFocusOutsideModal) { // element marked autofocus has higher priority than the other clowns const autofocusElement = this.containerElement.querySelector('[autofocus]') as HTMLElement; const wrapperElement = this.containerElement; if (autofocusElement != null) { autofocusElement.focus(); } else if (wrapperElement != null) { wrapperElement.focus(); } } }); } private overlayWillOpen() { const { openStack } = Overlay; if (openStack.length > 0) { document.removeEventListener( 'focus', Overlay.getLastOpened().handleDocumentFocus, /* useCapture */ true ); } openStack.push(this); if (this.getautoFoucs()) { this.bringFocusInsideOverlay(); } if (this.getEnforceFocus()) { document.addEventListener('focus', this.handleDocumentFocus, /* useCapture */ true); } if (this.getCanOutsideClickClose() && !this.getHasBackdrop()) { document.addEventListener('mousedown', this.handleDocumentClick); } if (this.getHasBackdrop() && this.getUsePortal()) { // add a class to the body to prevent scrolling of content below the overlay document.body.classList.add(Classes.OVERLAY_OPEN); } } private handleDocumentFocus = (e: FocusEvent) => { if ( this.getEnforceFocus() && this.containerElement != null && !this.containerElement.contains(e.target as HTMLElement) ) { // prevent default focus behavior (sometimes auto-scrolls the page) e.preventDefault(); e.stopImmediatePropagation(); this.bringFocusInsideOverlay(); } }; private handleDocumentClick = (e: MouseEvent) => { const eventTarget = e.target as HTMLElement; const stackIndex = Overlay.openStack.indexOf(this); const isClickInThisOverlayOrDescendant = Overlay.openStack .slice(stackIndex) .some(({ containerElement: elem }) => { // `elem` is the container of backdrop & content, so clicking on that container // should not count as being "inside" the overlay. return elem && elem.contains(eventTarget) && !elem.isSameNode(eventTarget); // eslint-disable-line }); if (this.getIsOpen && this.getCanOutsideClickClose() && !isClickInThisOverlayOrDescendant) { // casting to any because this is a native event if (this.args.onClose) { this.args.onClose(e); } } }; private overlayWillClose() { document.removeEventListener('focus', this.handleDocumentFocus, /* useCapture */ true); document.removeEventListener('mousedown', this.handleDocumentClick); const { openStack } = Overlay; const stackIndex = openStack.indexOf(this); if (stackIndex !== -1) { openStack.splice(stackIndex, 1); if (openStack.length > 0) { const lastOpenedOverlay = Overlay.getLastOpened(); if (lastOpenedOverlay.getEnforceFocus()) { document.addEventListener( 'focus', lastOpenedOverlay.handleDocumentFocus, /* useCapture */ true ); } } if (openStack.filter((o) => o.getUsePortal() && o.getHasBackdrop()).length === 0) { if (document.body.classList) document.body.classList.remove(Classes.OVERLAY_OPEN); } } } }
the_stack
import { Component, h, RenderableProps } from 'preact'; import { route } from 'preact-router'; import { AccountCode, IAccount } from '../../api/account'; import { TDevices } from '../../api/devices'; import Guide from './guide'; import A from '../../components/anchor/anchor'; import { Header } from '../../components/layout'; import { Spinner } from '../../components/spinner/Spinner'; import { load } from '../../decorators/load'; import { translate, TranslateProps } from '../../decorators/translate'; import { Button, Checkbox, Select } from '../../components/forms'; import { setConfig } from '../../utils/config'; import { apiGet } from '../../utils/request'; import { isBitcoinOnly } from '../account/utils'; import * as style from './info.css'; interface BuyInfoProps { accounts: IAccount[]; code?: string; devices: TDevices; } interface LoadedBuyInfoProps { config: any; } interface Option { text: string; value: AccountCode; } interface State { status: 'choose' | 'agree' selected?: string; options?: Option[] } type Props = BuyInfoProps & LoadedBuyInfoProps & TranslateProps; class BuyInfo extends Component<Props, State> { public readonly state: State = { status: this.props.config.frontend.skipBuyDisclaimer ? 'choose' : 'agree', selected: this.props.code, } componentDidMount = () => { this.checkSupportedCoins(); } private handleProceed = () => { const { status, selected } = this.state; if (selected && (status === 'choose' || this.props.config.frontend.skipBuyDisclaimer)) { route(`/buy/moonpay/${selected}`); } else { this.setState({ status: 'choose' }, this.maybeProceed); } } private maybeProceed = () => { if (this.state.status === 'choose' && this.state.options !== undefined && this.state.options.length === 1) { route(`/buy/moonpay/${this.state.options[0].value}`); } } private checkSupportedCoins = () => { Promise.all( this.props.accounts.map((account) => ( apiGet(`exchange/moonpay/buy-supported/${account.code}`) .then(isSupported => (isSupported ? account : false)) )) ) .then(results => results.filter(result => result)) // @ts-ignore .then(accounts => accounts.map(({ isToken, name, coinName, code }) => ({ text: isToken || name === coinName ? name : `${name} (${coinName})`, value: code }))) .then(options => { this.setState({ options }, this.maybeProceed); }) .catch(console.error); } private handleSkipDisclaimer = (e) => { setConfig({ frontend: { skipBuyDisclaimer: e.target.checked }}); } private getCryptoName = (): string => { const { accounts, code, t } = this.props; if (!code) { const onlyBitcoin = accounts.every(({ coinCode }) => isBitcoinOnly(coinCode)); return onlyBitcoin ? 'Bitcoin' : t('buy.info.crypto'); } const account = accounts.find(account => account.code === code); if (account) { return isBitcoinOnly(account.coinCode) ? 'Bitcoin' : t('buy.info.crypto'); } return t('buy.info.crypto'); } public render( { t }: RenderableProps<Props>, { status, selected, options, }: State ) { if (options === undefined) { return <Spinner text={t('loading')} />; } const name = this.getCryptoName(); return ( <div class="contentWithGuide"> <div class="container"> <Header title={<h2>{t('buy.info.title', { name })}</h2>} /> <div class="innerContainer"> { status === 'agree' ? ( <div class={style.disclaimerContainer}> <div class={style.disclaimer}> <h2 class={style.title}> {t('buy.info.disclaimer.title', { name })} </h2> <p>{t('buy.info.disclaimer.intro.0', { name })}</p> <p>{t('buy.info.disclaimer.intro.1', { name })}</p> <h2 class={style.title}> {t('buy.info.disclaimer.payment.title')} </h2> <p>{t('buy.info.disclaimer.payment.details', { name })}</p> <div class={style.table}> <table> <colgroup> <col width="*" /> <col width="50px" /> <col width="*" /> </colgroup> <thead> <tr> <th>{t('buy.info.disclaimer.payment.table.method')}</th> <th>{t('buy.info.disclaimer.payment.table.fee')}</th> <th>{t('buy.info.disclaimer.payment.table.description')}</th> </tr> </thead> <tbody> <tr> <td>{t('buy.info.disclaimer.payment.table.1_method')}</td> <td class={style.nowrap}>1.9 %</td> <td>{t('buy.info.disclaimer.payment.table.1_description')}</td> </tr> <tr> <td>{t('buy.info.disclaimer.payment.table.2_method')}</td> <td class={style.nowrap}>4.9 %</td> <td>{t('buy.info.disclaimer.payment.table.2_description')}</td> </tr> </tbody> </table> </div> <p>{t('buy.info.disclaimer.payment.footnote')}</p> <h2 class={style.title}> {t('buy.info.disclaimer.security.title')} </h2> <p>{t('buy.info.disclaimer.security.description', { name })}</p> <p> <A class={style.link} href="https://shiftcrypto.ch/bitbox02/threat-model/"> {t('buy.info.disclaimer.security.link')} </A> </p> <h2 class={style.title}> {t('buy.info.disclaimer.protection.title')} </h2> <p>{t('buy.info.disclaimer.protection.description', { name })}</p> <p> <A class={style.link} href="https://www.moonpay.com/privacy_policy"> {t('buy.info.disclaimer.privacyPolicy')} </A> </p> </div> <div class="text-center m-bottom-quarter"> <Checkbox id="skip_disclaimer" label={t('buy.info.skip')} onChange={this.handleSkipDisclaimer} /> </div> <div class="buttons text-center m-bottom-xlarge"> <Button primary onClick={this.handleProceed}> {t('buy.info.continue')} </Button> </div> </div> ) : ( options.length === 0 ? ( <div class="content narrow isVerticallyCentered">{t('accountSummary.noAccount')}</div> ) : ( <div class="content narrow isVerticallyCentered"> <h1 class={style.title}>{t('buy.title', { name })}</h1> <Select options={[{ text: t('buy.info.selectLabel'), disabled: true, value: 'choose', }, ...options] } onChange={(e: Event) => this.setState({ selected: (e.target as HTMLSelectElement).value})} value={selected} defaultValue={'choose'} id="coinAndAccountCode" /> <div class="buttons text-center m-bottom-xxlarge"> <Button primary onClick={this.handleProceed} disabled={!selected}> {t('buy.info.next')} </Button> </div> </div> ) )} </div> </div> <Guide t={t} name={name} /> </div> ); } } const loadHOC = load<LoadedBuyInfoProps, BuyInfoProps & TranslateProps>({ config: 'config' })(BuyInfo); const HOC = translate<BuyInfoProps>()(loadHOC); export { HOC as BuyInfo };
the_stack
import * as cdk from '@aws-cdk/core'; import * as cfn_parse from '@aws-cdk/core/lib/cfn-parse'; /** * Properties for defining a `AWS::Events::Archive`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html * @external */ export interface CfnArchiveProps { /** * `AWS::Events::Archive.SourceArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-sourcearn * @external */ readonly sourceArn: string; /** * `AWS::Events::Archive.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-description * @external */ readonly description?: string; /** * `AWS::Events::Archive.EventPattern`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-eventpattern * @external */ readonly eventPattern?: any | cdk.IResolvable; /** * `AWS::Events::Archive.RetentionDays`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-retentiondays * @external */ readonly retentionDays?: number; } /** * A CloudFormation `AWS::Events::Archive`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html * @external * @cloudformationResource AWS::Events::Archive */ export declare class CfnArchive extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::Events::Archive"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnArchive; /** * @external * @cloudformationAttribute ArchiveName */ readonly attrArchiveName: string; /** * @external * @cloudformationAttribute Arn */ readonly attrArn: string; /** * `AWS::Events::Archive.SourceArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-sourcearn * @external */ sourceArn: string; /** * `AWS::Events::Archive.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-description * @external */ description: string | undefined; /** * `AWS::Events::Archive.EventPattern`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-eventpattern * @external */ eventPattern: any | cdk.IResolvable | undefined; /** * `AWS::Events::Archive.RetentionDays`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-archive.html#cfn-events-archive-retentiondays * @external */ retentionDays: number | undefined; /** * Create a new `AWS::Events::Archive`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnArchiveProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::Events::EventBus`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html * @external */ export interface CfnEventBusProps { /** * `AWS::Events::EventBus.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html#cfn-events-eventbus-name * @external */ readonly name: string; /** * `AWS::Events::EventBus.EventSourceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html#cfn-events-eventbus-eventsourcename * @external */ readonly eventSourceName?: string; } /** * A CloudFormation `AWS::Events::EventBus`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html * @external * @cloudformationResource AWS::Events::EventBus */ export declare class CfnEventBus extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::Events::EventBus"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEventBus; /** * @external * @cloudformationAttribute Arn */ readonly attrArn: string; /** * @external * @cloudformationAttribute Name */ readonly attrName: string; /** * @external * @cloudformationAttribute Policy */ readonly attrPolicy: string; /** * `AWS::Events::EventBus.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html#cfn-events-eventbus-name * @external */ name: string; /** * `AWS::Events::EventBus.EventSourceName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbus.html#cfn-events-eventbus-eventsourcename * @external */ eventSourceName: string | undefined; /** * Create a new `AWS::Events::EventBus`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnEventBusProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * Properties for defining a `AWS::Events::EventBusPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html * @external */ export interface CfnEventBusPolicyProps { /** * `AWS::Events::EventBusPolicy.Action`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-action * @external */ readonly action: string; /** * `AWS::Events::EventBusPolicy.Principal`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-principal * @external */ readonly principal: string; /** * `AWS::Events::EventBusPolicy.StatementId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-statementid * @external */ readonly statementId: string; /** * `AWS::Events::EventBusPolicy.Condition`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-condition * @external */ readonly condition?: CfnEventBusPolicy.ConditionProperty | cdk.IResolvable; /** * `AWS::Events::EventBusPolicy.EventBusName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-eventbusname * @external */ readonly eventBusName?: string; } /** * A CloudFormation `AWS::Events::EventBusPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html * @external * @cloudformationResource AWS::Events::EventBusPolicy */ export declare class CfnEventBusPolicy extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::Events::EventBusPolicy"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnEventBusPolicy; /** * `AWS::Events::EventBusPolicy.Action`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-action * @external */ action: string; /** * `AWS::Events::EventBusPolicy.Principal`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-principal * @external */ principal: string; /** * `AWS::Events::EventBusPolicy.StatementId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-statementid * @external */ statementId: string; /** * `AWS::Events::EventBusPolicy.Condition`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-condition * @external */ condition: CfnEventBusPolicy.ConditionProperty | cdk.IResolvable | undefined; /** * `AWS::Events::EventBusPolicy.EventBusName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html#cfn-events-eventbuspolicy-eventbusname * @external */ eventBusName: string | undefined; /** * Create a new `AWS::Events::EventBusPolicy`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props: CfnEventBusPolicyProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::Events::EventBusPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-eventbuspolicy.html * @external * @cloudformationResource AWS::Events::EventBusPolicy */ export declare namespace CfnEventBusPolicy { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-eventbuspolicy-condition.html * @external */ interface ConditionProperty { /** * `CfnEventBusPolicy.ConditionProperty.Key`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-eventbuspolicy-condition.html#cfn-events-eventbuspolicy-condition-key * @external */ readonly key?: string; /** * `CfnEventBusPolicy.ConditionProperty.Type`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-eventbuspolicy-condition.html#cfn-events-eventbuspolicy-condition-type * @external */ readonly type?: string; /** * `CfnEventBusPolicy.ConditionProperty.Value`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-eventbuspolicy-condition.html#cfn-events-eventbuspolicy-condition-value * @external */ readonly value?: string; } } /** * Properties for defining a `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external */ export interface CfnRuleProps { /** * `AWS::Events::Rule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-description * @external */ readonly description?: string; /** * `AWS::Events::Rule.EventBusName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventbusname * @external */ readonly eventBusName?: string; /** * `AWS::Events::Rule.EventPattern`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventpattern * @external */ readonly eventPattern?: any | cdk.IResolvable; /** * `AWS::Events::Rule.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-name * @external */ readonly name?: string; /** * `AWS::Events::Rule.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-rolearn * @external */ readonly roleArn?: string; /** * `AWS::Events::Rule.ScheduleExpression`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-scheduleexpression * @external */ readonly scheduleExpression?: string; /** * `AWS::Events::Rule.State`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-state * @external */ readonly state?: string; /** * `AWS::Events::Rule.Targets`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-targets * @external */ readonly targets?: Array<CfnRule.TargetProperty | cdk.IResolvable> | cdk.IResolvable; } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare class CfnRule extends cdk.CfnResource implements cdk.IInspectable { /** * The CloudFormation resource type name for this resource class. * * @external */ static readonly CFN_RESOURCE_TYPE_NAME = "AWS::Events::Rule"; /** * A factory method that creates a new instance of this class from an object * containing the CloudFormation properties of this resource. * Used in the @aws-cdk/cloudformation-include module. * * @internal */ static _fromCloudFormation(scope: cdk.Construct, id: string, resourceAttributes: any, options: cfn_parse.FromCloudFormationOptions): CfnRule; /** * @external * @cloudformationAttribute Arn */ readonly attrArn: string; /** * `AWS::Events::Rule.Description`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-description * @external */ description: string | undefined; /** * `AWS::Events::Rule.EventBusName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventbusname * @external */ eventBusName: string | undefined; /** * `AWS::Events::Rule.EventPattern`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventpattern * @external */ eventPattern: any | cdk.IResolvable | undefined; /** * `AWS::Events::Rule.Name`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-name * @external */ name: string | undefined; /** * `AWS::Events::Rule.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-rolearn * @external */ roleArn: string | undefined; /** * `AWS::Events::Rule.ScheduleExpression`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-scheduleexpression * @external */ scheduleExpression: string | undefined; /** * `AWS::Events::Rule.State`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-state * @external */ state: string | undefined; /** * `AWS::Events::Rule.Targets`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-targets * @external */ targets: Array<CfnRule.TargetProperty | cdk.IResolvable> | cdk.IResolvable | undefined; /** * Create a new `AWS::Events::Rule`. * * @param scope - scope in which this resource is defined. * @param id - scoped id of the resource. * @param props - resource properties. * @external */ constructor(scope: cdk.Construct, id: string, props?: CfnRuleProps); /** * (experimental) Examines the CloudFormation resource and discloses attributes. * * @param inspector - tree inspector to collect and process attributes. * @experimental */ inspect(inspector: cdk.TreeInspector): void; /** * @external */ protected get cfnProperties(): { [key: string]: any; }; /** * @external */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-awsvpcconfiguration.html * @external */ interface AwsVpcConfigurationProperty { /** * `CfnRule.AwsVpcConfigurationProperty.AssignPublicIp`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-awsvpcconfiguration.html#cfn-events-rule-awsvpcconfiguration-assignpublicip * @external */ readonly assignPublicIp?: string; /** * `CfnRule.AwsVpcConfigurationProperty.SecurityGroups`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-awsvpcconfiguration.html#cfn-events-rule-awsvpcconfiguration-securitygroups * @external */ readonly securityGroups?: string[]; /** * `CfnRule.AwsVpcConfigurationProperty.Subnets`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-awsvpcconfiguration.html#cfn-events-rule-awsvpcconfiguration-subnets * @external */ readonly subnets: string[]; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batcharrayproperties.html * @external */ interface BatchArrayPropertiesProperty { /** * `CfnRule.BatchArrayPropertiesProperty.Size`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batcharrayproperties.html#cfn-events-rule-batcharrayproperties-size * @external */ readonly size?: number; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchparameters.html * @external */ interface BatchParametersProperty { /** * `CfnRule.BatchParametersProperty.ArrayProperties`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchparameters.html#cfn-events-rule-batchparameters-arrayproperties * @external */ readonly arrayProperties?: CfnRule.BatchArrayPropertiesProperty | cdk.IResolvable; /** * `CfnRule.BatchParametersProperty.JobDefinition`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchparameters.html#cfn-events-rule-batchparameters-jobdefinition * @external */ readonly jobDefinition: string; /** * `CfnRule.BatchParametersProperty.JobName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchparameters.html#cfn-events-rule-batchparameters-jobname * @external */ readonly jobName: string; /** * `CfnRule.BatchParametersProperty.RetryStrategy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchparameters.html#cfn-events-rule-batchparameters-retrystrategy * @external */ readonly retryStrategy?: CfnRule.BatchRetryStrategyProperty | cdk.IResolvable; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchretrystrategy.html * @external */ interface BatchRetryStrategyProperty { /** * `CfnRule.BatchRetryStrategyProperty.Attempts`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-batchretrystrategy.html#cfn-events-rule-batchretrystrategy-attempts * @external */ readonly attempts?: number; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-deadletterconfig.html * @external */ interface DeadLetterConfigProperty { /** * `CfnRule.DeadLetterConfigProperty.Arn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-deadletterconfig.html#cfn-events-rule-deadletterconfig-arn * @external */ readonly arn?: string; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html * @external */ interface EcsParametersProperty { /** * `CfnRule.EcsParametersProperty.Group`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-group * @external */ readonly group?: string; /** * `CfnRule.EcsParametersProperty.LaunchType`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-launchtype * @external */ readonly launchType?: string; /** * `CfnRule.EcsParametersProperty.NetworkConfiguration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-networkconfiguration * @external */ readonly networkConfiguration?: CfnRule.NetworkConfigurationProperty | cdk.IResolvable; /** * `CfnRule.EcsParametersProperty.PlatformVersion`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-platformversion * @external */ readonly platformVersion?: string; /** * `CfnRule.EcsParametersProperty.TaskCount`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-taskcount * @external */ readonly taskCount?: number; /** * `CfnRule.EcsParametersProperty.TaskDefinitionArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-taskdefinitionarn * @external */ readonly taskDefinitionArn: string; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-httpparameters.html * @external */ interface HttpParametersProperty { /** * `CfnRule.HttpParametersProperty.HeaderParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-httpparameters.html#cfn-events-rule-httpparameters-headerparameters * @external */ readonly headerParameters?: { [key: string]: (string); } | cdk.IResolvable; /** * `CfnRule.HttpParametersProperty.PathParameterValues`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-httpparameters.html#cfn-events-rule-httpparameters-pathparametervalues * @external */ readonly pathParameterValues?: string[]; /** * `CfnRule.HttpParametersProperty.QueryStringParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-httpparameters.html#cfn-events-rule-httpparameters-querystringparameters * @external */ readonly queryStringParameters?: { [key: string]: (string); } | cdk.IResolvable; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html * @external */ interface InputTransformerProperty { /** * `CfnRule.InputTransformerProperty.InputPathsMap`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputpathsmap * @external */ readonly inputPathsMap?: { [key: string]: (string); } | cdk.IResolvable; /** * `CfnRule.InputTransformerProperty.InputTemplate`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputtemplate * @external */ readonly inputTemplate: string; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-kinesisparameters.html * @external */ interface KinesisParametersProperty { /** * `CfnRule.KinesisParametersProperty.PartitionKeyPath`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-kinesisparameters.html#cfn-events-rule-kinesisparameters-partitionkeypath * @external */ readonly partitionKeyPath: string; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-networkconfiguration.html * @external */ interface NetworkConfigurationProperty { /** * `CfnRule.NetworkConfigurationProperty.AwsVpcConfiguration`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-networkconfiguration.html#cfn-events-rule-networkconfiguration-awsvpcconfiguration * @external */ readonly awsVpcConfiguration?: CfnRule.AwsVpcConfigurationProperty | cdk.IResolvable; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html * @external */ interface RedshiftDataParametersProperty { /** * `CfnRule.RedshiftDataParametersProperty.Database`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-database * @external */ readonly database: string; /** * `CfnRule.RedshiftDataParametersProperty.DbUser`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-dbuser * @external */ readonly dbUser?: string; /** * `CfnRule.RedshiftDataParametersProperty.SecretManagerArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-secretmanagerarn * @external */ readonly secretManagerArn?: string; /** * `CfnRule.RedshiftDataParametersProperty.Sql`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-sql * @external */ readonly sql: string; /** * `CfnRule.RedshiftDataParametersProperty.StatementName`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-statementname * @external */ readonly statementName?: string; /** * `CfnRule.RedshiftDataParametersProperty.WithEvent`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-redshiftdataparameters.html#cfn-events-rule-redshiftdataparameters-withevent * @external */ readonly withEvent?: boolean | cdk.IResolvable; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-retrypolicy.html * @external */ interface RetryPolicyProperty { /** * `CfnRule.RetryPolicyProperty.MaximumEventAgeInSeconds`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-retrypolicy.html#cfn-events-rule-retrypolicy-maximumeventageinseconds * @external */ readonly maximumEventAgeInSeconds?: number; /** * `CfnRule.RetryPolicyProperty.MaximumRetryAttempts`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-retrypolicy.html#cfn-events-rule-retrypolicy-maximumretryattempts * @external */ readonly maximumRetryAttempts?: number; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandparameters.html * @external */ interface RunCommandParametersProperty { /** * `CfnRule.RunCommandParametersProperty.RunCommandTargets`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandparameters.html#cfn-events-rule-runcommandparameters-runcommandtargets * @external */ readonly runCommandTargets: Array<CfnRule.RunCommandTargetProperty | cdk.IResolvable> | cdk.IResolvable; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html * @external */ interface RunCommandTargetProperty { /** * `CfnRule.RunCommandTargetProperty.Key`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html#cfn-events-rule-runcommandtarget-key * @external */ readonly key: string; /** * `CfnRule.RunCommandTargetProperty.Values`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html#cfn-events-rule-runcommandtarget-values * @external */ readonly values: string[]; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-sqsparameters.html * @external */ interface SqsParametersProperty { /** * `CfnRule.SqsParametersProperty.MessageGroupId`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-sqsparameters.html#cfn-events-rule-sqsparameters-messagegroupid * @external */ readonly messageGroupId: string; } } /** * A CloudFormation `AWS::Events::Rule`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html * @external * @cloudformationResource AWS::Events::Rule */ export declare namespace CfnRule { /** * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html * @external */ interface TargetProperty { /** * `CfnRule.TargetProperty.Arn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-arn * @external */ readonly arn: string; /** * `CfnRule.TargetProperty.BatchParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-batchparameters * @external */ readonly batchParameters?: CfnRule.BatchParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.DeadLetterConfig`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-deadletterconfig * @external */ readonly deadLetterConfig?: CfnRule.DeadLetterConfigProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.EcsParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-ecsparameters * @external */ readonly ecsParameters?: CfnRule.EcsParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.HttpParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-httpparameters * @external */ readonly httpParameters?: CfnRule.HttpParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.Id`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-id * @external */ readonly id: string; /** * `CfnRule.TargetProperty.Input`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-input * @external */ readonly input?: string; /** * `CfnRule.TargetProperty.InputPath`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-inputpath * @external */ readonly inputPath?: string; /** * `CfnRule.TargetProperty.InputTransformer`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-inputtransformer * @external */ readonly inputTransformer?: CfnRule.InputTransformerProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.KinesisParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-kinesisparameters * @external */ readonly kinesisParameters?: CfnRule.KinesisParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.RedshiftDataParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-redshiftdataparameters * @external */ readonly redshiftDataParameters?: CfnRule.RedshiftDataParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.RetryPolicy`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-retrypolicy * @external */ readonly retryPolicy?: CfnRule.RetryPolicyProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.RoleArn`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-rolearn * @external */ readonly roleArn?: string; /** * `CfnRule.TargetProperty.RunCommandParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-runcommandparameters * @external */ readonly runCommandParameters?: CfnRule.RunCommandParametersProperty | cdk.IResolvable; /** * `CfnRule.TargetProperty.SqsParameters`. * * @see http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-sqsparameters * @external */ readonly sqsParameters?: CfnRule.SqsParametersProperty | cdk.IResolvable; } }
the_stack
import { ContractTxFunctionObj } from '@0x/contract-wrappers'; import { blockchainTests, constants, expect, filterLogsToArguments, getRandomInteger, randomAddress, shortZip, } from '@0x/contracts-test-utils'; import { BigNumber, hexUtils, NULL_ADDRESS } from '@0x/utils'; import { DecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; import { DexForwarderBridgeCall, dexForwarderBridgeDataEncoder } from '../src/dex_forwarder_bridge'; import { artifacts } from './artifacts'; import { TestDexForwarderBridgeBridgeTransferFromCalledEventArgs as BtfCalledEventArgs, TestDexForwarderBridgeContract, TestDexForwarderBridgeEvents as TestEvents, } from './wrappers'; const { ZERO_AMOUNT } = constants; blockchainTests.resets('DexForwarderBridge unit tests', env => { let testContract: TestDexForwarderBridgeContract; let inputToken: string; let outputToken: string; const BRIDGE_SUCCESS = '0xdc1600f3'; const BRIDGE_FAILURE = '0xffffffff'; const BRIDGE_REVERT_ERROR = 'oopsie'; const NOT_AUTHORIZED_REVERT = 'DexForwarderBridge/SENDER_NOT_AUTHORIZED'; const DEFAULTS = { toAddress: randomAddress(), }; before(async () => { testContract = await TestDexForwarderBridgeContract.deployFrom0xArtifactAsync( artifacts.TestDexForwarderBridge, env.provider, env.txDefaults, artifacts, ); // Create test tokens. [inputToken, outputToken] = [ await callAndTransactAsync(testContract.createToken()), await callAndTransactAsync(testContract.createToken()), ]; await callAndTransactAsync(testContract.setAuthorized(env.txDefaults.from as string)); }); async function callAndTransactAsync<TResult>(fnCall: ContractTxFunctionObj<TResult>): Promise<TResult> { const result = await fnCall.callAsync(); await fnCall.awaitTransactionSuccessAsync({}, { shouldValidate: false }); return result; } function getRandomBridgeCall( bridgeAddress: string, fields: Partial<DexForwarderBridgeCall> = {}, ): DexForwarderBridgeCall { return { target: bridgeAddress, inputTokenAmount: getRandomInteger(1, '100e18'), outputTokenAmount: getRandomInteger(1, '100e18'), bridgeData: hexUtils.leftPad(inputToken), ...fields, }; } describe('bridgeTransferFrom()', () => { let goodBridgeCalls: DexForwarderBridgeCall[]; let revertingBridgeCall: DexForwarderBridgeCall; let failingBridgeCall: DexForwarderBridgeCall; let allBridgeCalls: DexForwarderBridgeCall[]; let totalFillableOutputAmount: BigNumber; let totalFillableInputAmount: BigNumber; let recipientOutputBalance: BigNumber; beforeEach(async () => { goodBridgeCalls = []; for (let i = 0; i < 4; ++i) { goodBridgeCalls.push(await createBridgeCallAsync({ returnCode: BRIDGE_SUCCESS })); } revertingBridgeCall = await createBridgeCallAsync({ revertError: BRIDGE_REVERT_ERROR }); failingBridgeCall = await createBridgeCallAsync({ returnCode: BRIDGE_FAILURE }); allBridgeCalls = _.shuffle([failingBridgeCall, revertingBridgeCall, ...goodBridgeCalls]); totalFillableInputAmount = BigNumber.sum(...goodBridgeCalls.map(c => c.inputTokenAmount)); totalFillableOutputAmount = BigNumber.sum(...goodBridgeCalls.map(c => c.outputTokenAmount)); // Grant the taker some output tokens. await testContract.setTokenBalance( outputToken, DEFAULTS.toAddress, (recipientOutputBalance = getRandomInteger(1, '100e18')), ); }); async function setForwarderInputBalanceAsync(amount: BigNumber): Promise<void> { await testContract .setTokenBalance(inputToken, testContract.address, amount) .awaitTransactionSuccessAsync({}, { shouldValidate: false }); } async function createBridgeCallAsync( opts: Partial<{ returnCode: string; revertError: string; callFields: Partial<DexForwarderBridgeCall>; outputFillAmount: BigNumber; }>, ): Promise<DexForwarderBridgeCall> { const { returnCode, revertError, callFields, outputFillAmount } = { returnCode: BRIDGE_SUCCESS, revertError: '', ...opts, }; const bridge = await callAndTransactAsync(testContract.createBridge(returnCode, revertError)); const call = getRandomBridgeCall(bridge, callFields); await testContract .setBridgeTransferAmount(call.target, outputFillAmount || call.outputTokenAmount) .awaitTransactionSuccessAsync({}, { shouldValidate: false }); return call; } async function callBridgeTransferFromAsync(opts: { bridgeData: string; sellAmount?: BigNumber; buyAmount?: BigNumber; }): Promise<DecodedLogs> { // Fund the forwarder with input tokens to sell. await setForwarderInputBalanceAsync(opts.sellAmount || totalFillableInputAmount); const call = testContract.bridgeTransferFrom( outputToken, testContract.address, DEFAULTS.toAddress, opts.buyAmount || totalFillableOutputAmount, opts.bridgeData, ); const returnCode = await call.callAsync(); if (returnCode !== BRIDGE_SUCCESS) { throw new Error('Expected BRIDGE_SUCCESS'); } const receipt = await call.awaitTransactionSuccessAsync({}, { shouldValidate: false }); // tslint:disable-next-line: no-unnecessary-type-assertion return receipt.logs as DecodedLogs; } it('succeeds with no bridge calls and no input balance', async () => { const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls: [], }); await callBridgeTransferFromAsync({ bridgeData, sellAmount: ZERO_AMOUNT }); }); it('succeeds with bridge calls and no input balance', async () => { const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls: allBridgeCalls, }); await callBridgeTransferFromAsync({ bridgeData, sellAmount: ZERO_AMOUNT }); }); it('succeeds with no bridge calls and an input balance', async () => { const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls: [], }); await callBridgeTransferFromAsync({ bridgeData, sellAmount: new BigNumber(1), }); }); it('succeeds if entire input token balance is not consumed', async () => { const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls: allBridgeCalls, }); await callBridgeTransferFromAsync({ bridgeData, sellAmount: totalFillableInputAmount.plus(1), }); }); it('fails if not authorized', async () => { const calls = goodBridgeCalls.slice(0, 1); const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); await callAndTransactAsync(testContract.setAuthorized(NULL_ADDRESS)); return expect(callBridgeTransferFromAsync({ bridgeData, sellAmount: new BigNumber(1) })).to.revertWith( NOT_AUTHORIZED_REVERT, ); }); it('succeeds with one bridge call', async () => { const calls = goodBridgeCalls.slice(0, 1); const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); await callBridgeTransferFromAsync({ bridgeData, sellAmount: calls[0].inputTokenAmount }); }); it('succeeds with many bridge calls', async () => { const calls = goodBridgeCalls; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); await callBridgeTransferFromAsync({ bridgeData }); }); it('swallows a failing bridge call', async () => { const calls = _.shuffle([...goodBridgeCalls, failingBridgeCall]); const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); await callBridgeTransferFromAsync({ bridgeData }); }); it('consumes input tokens for output tokens', async () => { const calls = allBridgeCalls; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); await callBridgeTransferFromAsync({ bridgeData }); const currentBridgeInputBalance = await testContract .balanceOf(inputToken, testContract.address) .callAsync(); expect(currentBridgeInputBalance).to.bignumber.eq(0); const currentRecipientOutputBalance = await testContract .balanceOf(outputToken, DEFAULTS.toAddress) .callAsync(); expect(currentRecipientOutputBalance).to.bignumber.eq(totalFillableOutputAmount); }); it("transfers only up to each call's input amount to each bridge", async () => { const calls = goodBridgeCalls; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); const logs = await callBridgeTransferFromAsync({ bridgeData }); const btfs = filterLogsToArguments<BtfCalledEventArgs>(logs, TestEvents.BridgeTransferFromCalled); for (const [call, btf] of shortZip(goodBridgeCalls, btfs)) { expect(btf.inputTokenBalance).to.bignumber.eq(call.inputTokenAmount); } }); it('transfers only up to outstanding sell amount to each bridge', async () => { // Prepend an extra bridge call. const calls = [ await createBridgeCallAsync({ callFields: { inputTokenAmount: new BigNumber(1), outputTokenAmount: new BigNumber(1), }, }), ...goodBridgeCalls, ]; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); const logs = await callBridgeTransferFromAsync({ bridgeData }); const btfs = filterLogsToArguments<BtfCalledEventArgs>(logs, TestEvents.BridgeTransferFromCalled); expect(btfs).to.be.length(goodBridgeCalls.length + 1); // The last call will receive 1 less token. const lastCall = calls.slice(-1)[0]; const lastBtf = btfs.slice(-1)[0]; expect(lastBtf.inputTokenBalance).to.bignumber.eq(lastCall.inputTokenAmount.minus(1)); }); it('recoups funds from a bridge that fails', async () => { // Prepend a call that will take the whole input amount but will // fail. const badCall = await createBridgeCallAsync({ callFields: { inputTokenAmount: totalFillableInputAmount }, returnCode: BRIDGE_FAILURE, }); const calls = [badCall, ...goodBridgeCalls]; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); const logs = await callBridgeTransferFromAsync({ bridgeData }); const btfs = filterLogsToArguments<BtfCalledEventArgs>(logs, TestEvents.BridgeTransferFromCalled); expect(btfs).to.be.length(goodBridgeCalls.length); }); it('recoups funds from a bridge that reverts', async () => { // Prepend a call that will take the whole input amount but will // revert. const badCall = await createBridgeCallAsync({ callFields: { inputTokenAmount: totalFillableInputAmount }, revertError: BRIDGE_REVERT_ERROR, }); const calls = [badCall, ...goodBridgeCalls]; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); const logs = await callBridgeTransferFromAsync({ bridgeData }); const btfs = filterLogsToArguments<BtfCalledEventArgs>(logs, TestEvents.BridgeTransferFromCalled); expect(btfs).to.be.length(goodBridgeCalls.length); }); it('recoups funds from a bridge that under-pays', async () => { // Prepend a call that will take the whole input amount but will // underpay the output amount.. const badCall = await createBridgeCallAsync({ callFields: { inputTokenAmount: totalFillableInputAmount, outputTokenAmount: new BigNumber(2), }, outputFillAmount: new BigNumber(1), }); const calls = [badCall, ...goodBridgeCalls]; const bridgeData = dexForwarderBridgeDataEncoder.encode({ inputToken, calls, }); const logs = await callBridgeTransferFromAsync({ bridgeData }); const btfs = filterLogsToArguments<BtfCalledEventArgs>(logs, TestEvents.BridgeTransferFromCalled); expect(btfs).to.be.length(goodBridgeCalls.length); }); }); describe('executeBridgeCall()', () => { it('cannot be called externally', async () => { return expect( testContract .executeBridgeCall( randomAddress(), randomAddress(), randomAddress(), randomAddress(), new BigNumber(1), new BigNumber(1), constants.NULL_BYTES, ) .callAsync(), ).to.revertWith('DexForwarderBridge/ONLY_SELF'); }); }); });
the_stack
import * as OPI from 'object-path-immutable' import { FlexLength, LayoutSystem, Sides } from 'utopia-api' import { getReorderDirection } from '../../components/canvas/controls/select-mode/yoga-utils' import { getImageSize, scaleImageDimensions } from '../../components/images' import { foldThese, makeThat, makeThis, makeThisAndThat, mergeThese, setThat, These, } from '../../utils/these' import Utils, { IndexPosition } from '../../utils/utils' import { getLayoutProperty } from '../layout/getLayoutProperty' import { FlexLayoutHelpers, LayoutHelpers } from '../layout/layout-helpers' import { LayoutProp } from '../layout/layout-helpers-new' import { flattenArray, mapDropNulls, pluck, stripNulls, flatMapArray, uniqBy, reverse, } from '../shared/array-utils' import { intrinsicHTMLElementNamesThatSupportChildren } from '../shared/dom-utils' import { alternativeEither, Either, eitherToMaybe, flatMapEither, foldEither, forEachRight, isLeft, isRight, left, mapEither, right, traverseEither, Left, Right, maybeEitherToMaybe, } from '../shared/either' import { ElementInstanceMetadata, ElementsByUID, getJSXElementNameLastPart, getJSXElementNameNoPathName, isJSXArbitraryBlock, isJSXElement, isJSXTextBlock, JSXAttributes, JSXElement, JSXElementChild, UtopiaJSXComponent, JSXElementName, getJSXElementNameAsString, isIntrinsicElement, jsxElementName, ElementInstanceMetadataMap, isIntrinsicHTMLElement, getJSXAttribute, } from '../shared/element-template' import { getModifiableJSXAttributeAtPath, jsxSimpleAttributeToValue, } from '../shared/jsx-attributes' import { CanvasPoint, CanvasRectangle, canvasRectangle, LocalRectangle, localRectangle, SimpleRectangle, Size, } from '../shared/math-utils' import { optionalMap } from '../shared/optional-utils' import { ElementOriginType, Imports, isUnknownOrGeneratedElement, NodeModules, PropertyPath, ElementPath, } from '../shared/project-file-types' import * as PP from '../shared/property-path' import * as EP from '../shared/element-path' import { findJSXElementChildAtPath, getUtopiaID, isSceneElement } from './element-template-utils' import { isImportedComponent, isAnimatedElement, isGivenUtopiaAPIElement, isUtopiaAPIComponent, getUtopiaJSXComponentsFromSuccess, isViewLikeFromMetadata, isSceneFromMetadata, isUtopiaAPIComponentFromMetadata, isGivenUtopiaElementFromMetadata, isImportedComponentNPM, } from './project-file-utils' import { ResizesContentProp } from './scene-utils' import { fastForEach } from '../shared/utils' import { omit } from '../shared/object-utils' import { UTOPIA_LABEL_KEY } from './utopia-constants' import { withUnderlyingTarget } from '../../components/editor/store/editor-state' import { ProjectContentTreeRoot } from '../../components/assets' const ObjectPathImmutable: any = OPI export const getChildrenOfCollapsedViews = ( elementPaths: ElementPath[], collapsedViews: Array<ElementPath>, ): Array<ElementPath> => { return Utils.flatMapArray((view) => { return Utils.stripNulls( elementPaths.map((childPath) => { return EP.isDescendantOf(childPath, view) ? childPath : null }), ) }, collapsedViews) } const ElementsToDrillIntoForTextContent = ['div', 'span'] export const MetadataUtils = { getElementOriginType( elements: Array<UtopiaJSXComponent>, target: ElementPath, ): ElementOriginType { const staticTarget = EP.dynamicPathToStaticPath(target) if (staticTarget == null) { return 'unknown-element' } else { if (EP.pathsEqual(target, staticTarget)) { return 'statically-defined' } else { const element = findJSXElementChildAtPath(elements, staticTarget) if (element != null && isJSXElement(element)) { return 'generated-static-definition-present' } else { return 'unknown-element' } } } }, anyUnknownOrGeneratedElements( projectContents: ProjectContentTreeRoot, nodeModules: NodeModules, openFile: string | null, targets: Array<ElementPath>, ): boolean { return targets.some((target) => { const elementOriginType = withUnderlyingTarget<ElementOriginType>( target, projectContents, nodeModules, openFile, 'unknown-element', (success, element, underlyingTarget, underlyingFilePath) => { return MetadataUtils.getElementOriginType( getUtopiaJSXComponentsFromSuccess(success), underlyingTarget, ) }, ) return isUnknownOrGeneratedElement(elementOriginType) }) }, findElementByElementPath( elementMap: ElementInstanceMetadataMap, path: ElementPath | null, ): ElementInstanceMetadata | null { if (path == null) { return null } else { return elementMap[EP.toString(path)] ?? null } }, findElementsByElementPath( elementMap: ElementInstanceMetadataMap, paths: Array<ElementPath>, ): Array<ElementInstanceMetadata> { return stripNulls(paths.map((path) => MetadataUtils.findElementByElementPath(elementMap, path))) }, isSceneTreatedAsGroup(scene: ElementInstanceMetadata | null): boolean { if (scene == null) { return false } else { return scene.props[ResizesContentProp] ?? false } }, isProbablySceneFromMetadata(jsxMetadata: ElementInstanceMetadataMap, path: ElementPath): boolean { const elementMetadata = MetadataUtils.findElementByElementPath(jsxMetadata, path) return ( elementMetadata != null && elementMetadata.importInfo != null && foldEither( (_) => false, (info) => info.path === 'utopia-api' && info.originalName === 'Scene', elementMetadata.importInfo, ) ) }, findElements( elementMap: ElementInstanceMetadataMap, predicate: (element: ElementInstanceMetadata) => boolean, ): Array<ElementInstanceMetadata> { return Object.values(elementMap).filter(predicate) }, getViewZIndexFromMetadata(metadata: ElementInstanceMetadataMap, target: ElementPath): number { const siblings = MetadataUtils.getSiblings(metadata, target) return siblings.findIndex((child) => { return getUtopiaID(child) === EP.toUid(target) }) }, getParent( metadata: ElementInstanceMetadataMap, target: ElementPath | null, ): ElementInstanceMetadata | null { if (target == null) { return null } const parentPath = EP.parentPath(target) return MetadataUtils.findElementByElementPath(metadata, parentPath) }, getSiblings( metadata: ElementInstanceMetadataMap, target: ElementPath | null, ): ElementInstanceMetadata[] { if (target == null) { return [] } const parentPath = EP.parentPath(target) const parentMetadata = MetadataUtils.findElementByElementPath(metadata, parentPath) const siblingPathsOrNull = EP.isRootElementOfInstance(target) ? MetadataUtils.getRootViewPaths(metadata, parentPath) : MetadataUtils.getChildrenPaths(metadata, parentPath) const siblingPaths = siblingPathsOrNull ?? [] return MetadataUtils.findElementsByElementPath(metadata, siblingPaths) }, isParentYogaLayoutedContainerAndElementParticipatesInLayout( path: ElementPath, metadata: ElementInstanceMetadataMap, ): boolean { const instance = MetadataUtils.findElementByElementPath(metadata, path) return ( optionalMap( MetadataUtils.isParentYogaLayoutedContainerForElementAndElementParticipatesInLayout, instance, ) ?? false ) }, isParentYogaLayoutedContainerForElementAndElementParticipatesInLayout( element: ElementInstanceMetadata, ): boolean { return ( MetadataUtils.isParentYogaLayoutedContainerForElement(element) && !MetadataUtils.isPositionAbsolute(element) ) }, isParentYogaLayoutedContainerForElement(element: ElementInstanceMetadata): boolean { return element.specialSizeMeasurements.parentLayoutSystem === 'flex' }, isGroup(path: ElementPath | null, metadata: ElementInstanceMetadataMap): boolean { if (path == null) { return false } else { const instance = MetadataUtils.findElementByElementPath(metadata, path) if (instance != null && isRight(instance.element) && isJSXElement(instance.element.value)) { return ( LayoutHelpers.getLayoutSystemFromProps(right(instance.element.value.props)) === LayoutSystem.Group ) } else { return false } } }, isFlexLayoutedContainer(instance: ElementInstanceMetadata | null): boolean { return instance?.specialSizeMeasurements.layoutSystemForChildren === 'flex' }, isGridLayoutedContainer(instance: ElementInstanceMetadata | null): boolean { return instance?.specialSizeMeasurements.layoutSystemForChildren === 'grid' }, isPositionAbsolute(instance: ElementInstanceMetadata | null): boolean { return instance?.specialSizeMeasurements.position === 'absolute' }, isButton(target: ElementPath, metadata: ElementInstanceMetadataMap): boolean { const instance = MetadataUtils.findElementByElementPath(metadata, target) const elementName = MetadataUtils.getJSXElementName(maybeEitherToMaybe(instance?.element)) if ( elementName != null && PP.depth(elementName.propertyPath) === 0 && elementName.baseVariable === 'button' ) { return true } let buttonRoleFound: boolean = false if (instance != null) { forEachRight(instance.element, (elem) => { if (isJSXElement(elem)) { const attrResult = getSimpleAttributeAtPath(right(elem.props), PP.create(['role'])) forEachRight(attrResult, (value) => { if (value === 'button') { buttonRoleFound = true } }) } }) } if (buttonRoleFound) { return true } else { return instance?.specialSizeMeasurements.htmlElementName.toLowerCase() === 'button' } }, getYogaSizeProps(target: ElementPath, metadata: ElementInstanceMetadataMap): Partial<Size> { const parentInstance = this.getParent(metadata, target) if (parentInstance == null) { return {} } else { const flexDirection = getReorderDirection(this.getFlexDirection(parentInstance)) const staticTarget = EP.dynamicPathToStaticPath(target) if (staticTarget == null) { return {} } else { const element = maybeEitherToMaybe( MetadataUtils.findElementByElementPath(metadata, target)?.element, ) if (element != null && isJSXElement(element)) { const widthLookupAxis: LayoutProp = flexDirection === 'horizontal' ? 'flexBasis' : 'Width' const heightLookupAxis: LayoutProp = flexDirection === 'vertical' ? 'flexBasis' : 'Height' let result: Partial<Size> = {} const width: Either<string, FlexLength> = alternativeEither( getLayoutProperty(widthLookupAxis, right(element.props)), getLayoutProperty('Width', right(element.props)), ) const height: Either<string, FlexLength> = alternativeEither( getLayoutProperty(heightLookupAxis, right(element.props)), getLayoutProperty('Height', right(element.props)), ) // FIXME We should really be supporting string values here forEachRight(width, (w) => { if (w != null && typeof w === 'number') { result.width = w } }) forEachRight(height, (h) => { if (h != null && typeof h === 'number') { result.height = h } }) return result } else { return {} } } } }, getElementMargin(path: ElementPath, metadata: ElementInstanceMetadataMap): Partial<Sides> | null { const instance = MetadataUtils.findElementByElementPath(metadata, path) if (instance != null && isRight(instance.element) && isJSXElement(instance.element.value)) { return instance.specialSizeMeasurements.margin } else { return null } }, getElementPadding( path: ElementPath, metadata: ElementInstanceMetadataMap, ): Partial<Sides> | null { const instance = MetadataUtils.findElementByElementPath(metadata, path) if (instance != null && isRight(instance.element) && isJSXElement(instance.element.value)) { return instance.specialSizeMeasurements.padding } else { return null } }, getFlexDirection: function (instance: ElementInstanceMetadata | null): string { return instance?.specialSizeMeasurements?.flexDirection ?? 'row' }, getFlexWrap: function ( instance: ElementInstanceMetadata | null, ): 'wrap' | 'wrap-reverse' | 'nowrap' { if (instance != null && isRight(instance.element) && isJSXElement(instance.element.value)) { return FlexLayoutHelpers.getFlexWrap(instance.element.value.props) } else { return 'nowrap' // TODO read this value from spy } }, isAutoSizingView( metadata: ElementInstanceMetadataMap, element: ElementInstanceMetadata | null, ): boolean { if (element != null && isRight(element.element) && isJSXElement(element.element.value)) { // TODO NEW Property Path const isAutoSizing = LayoutHelpers.getLayoutSystemFromProps(right(element.element.value.props)) === 'group' const isYogaLayoutedContainer = MetadataUtils.isFlexLayoutedContainer(element) const childrenPaths = MetadataUtils.getChildrenPaths(metadata, element.elementPath) const hasChildren = childrenPaths.length > 0 const parentIsYoga = MetadataUtils.isParentYogaLayoutedContainerForElementAndElementParticipatesInLayout( element, ) return isAutoSizing && !isYogaLayoutedContainer && hasChildren && !parentIsYoga } else { return false } }, isAutoSizingViewFromComponents( metadata: ElementInstanceMetadataMap, target: ElementPath | null, ): boolean { if (target == null) { return false } const instance = MetadataUtils.findElementByElementPath(metadata, target) return MetadataUtils.isAutoSizingView(metadata, instance) }, isAutoSizingText(instance: ElementInstanceMetadata): boolean { return MetadataUtils.isTextAgainstImports(instance) && instance.props.textSizing === 'auto' }, findNonGroupParent( metadata: ElementInstanceMetadataMap, target: ElementPath, ): ElementPath | null { const parentPath = EP.parentPath(target) if (parentPath == null) { return null } else if (EP.isStoryboardChild(parentPath)) { // we've reached the top return parentPath } else { const parent = MetadataUtils.findElementByElementPath(metadata, parentPath) if (MetadataUtils.isAutoSizingView(metadata, parent)) { return MetadataUtils.findNonGroupParent(metadata, parentPath) } else { return parentPath } } }, shiftGroupFrame( metadata: ElementInstanceMetadataMap, target: ElementPath, originalFrame: CanvasRectangle | null, addOn: boolean, ): CanvasRectangle | null { if (originalFrame == null) { // if the originalFrame is null, we have nothing to shift return null } if (EP.isStoryboardChild(target)) { // If it's a scene we don't need to shift return originalFrame } const shiftMultiplier = addOn ? 1 : -1 let workingFrame: CanvasRectangle = originalFrame // If this is held within a group, then we need to add on the frames of the parent groups. let ancestorPath = EP.parentPath(target) while (!EP.isStoryboardChild(ancestorPath) && !EP.isEmptyPath(ancestorPath)) { const ancestorElement = MetadataUtils.findElementByElementPath(metadata, ancestorPath) const ancestorParentPath = EP.parentPath(ancestorPath) if (ancestorElement == null) { break } else { if ( MetadataUtils.isAutoSizingView(metadata, ancestorElement) && ancestorElement.localFrame != null ) { // if the ancestorElement is a group, it better have a measurable frame, too, // TODO check with Sean if there are implications of this nullcheck workingFrame = Utils.offsetRect(workingFrame, { x: shiftMultiplier * ancestorElement.localFrame.x, y: shiftMultiplier * ancestorElement.localFrame.y, } as CanvasPoint) } } ancestorPath = ancestorParentPath } return workingFrame }, setPropertyDirectlyIntoMetadata( metadata: ElementInstanceMetadataMap, target: ElementPath, property: PropertyPath, value: any, ): ElementInstanceMetadataMap { return this.transformAtPathOptionally(metadata, target, (element) => { return { ...element, props: ObjectPathImmutable.set(element.props, PP.getElements(property), value), } }) }, unsetPropertyDirectlyIntoMetadata( metadata: ElementInstanceMetadataMap, target: ElementPath, property: PropertyPath, ): ElementInstanceMetadataMap { return this.transformAtPathOptionally(metadata, target, (element) => { return { ...element, props: ObjectPathImmutable.del(element.props, PP.getElements(property)), } }) }, getRootViewPaths(elements: ElementInstanceMetadataMap, target: ElementPath): Array<ElementPath> { const possibleRootElementsOfTarget = mapDropNulls((elementPathString) => { const elementPath = EP.fromString(elementPathString) if (EP.isRootElementOf(elementPath, target)) { return elementPath } else { return null } }, Object.keys(elements)) return possibleRootElementsOfTarget }, getRootViews( elements: ElementInstanceMetadataMap, target: ElementPath, ): Array<ElementInstanceMetadata> { const rootPaths = MetadataUtils.getRootViewPaths(elements, target) return MetadataUtils.findElementsByElementPath(elements, rootPaths ?? []) }, getChildrenPaths(elements: ElementInstanceMetadataMap, target: ElementPath): Array<ElementPath> { const possibleChildren = mapDropNulls((elementPathString) => { const elementPath = EP.fromString(elementPathString) if (EP.isChildOf(elementPath, target) && !EP.isRootElementOfInstance(elementPath)) { return elementPath } else { return null } }, Object.keys(elements)) return possibleChildren }, getChildren( elements: ElementInstanceMetadataMap, target: ElementPath, ): Array<ElementInstanceMetadata> { const childrenPaths = MetadataUtils.getChildrenPaths(elements, target) return MetadataUtils.findElementsByElementPath(elements, childrenPaths ?? []) }, getImmediateChildrenPaths( elements: ElementInstanceMetadataMap, target: ElementPath, ): Array<ElementPath> { const element = MetadataUtils.findElementByElementPath(elements, target) const rootPaths = MetadataUtils.getRootViewPaths(elements, target) const childrenPaths = MetadataUtils.getChildrenPaths(elements, target) return element == null ? [] : [...rootPaths, ...childrenPaths] }, getImmediateChildren( metadata: ElementInstanceMetadataMap, target: ElementPath, ): Array<ElementInstanceMetadata> { const childrenPaths = MetadataUtils.getImmediateChildrenPaths(metadata, target) return MetadataUtils.findElementsByElementPath(metadata, childrenPaths ?? []) }, getChildrenHandlingGroups( metadata: ElementInstanceMetadataMap, target: ElementPath, includeGroups: boolean, ): Array<ElementInstanceMetadata> { const immediateChildren = MetadataUtils.getImmediateChildren(metadata, target) const getChildrenInner = ( childInstance: ElementInstanceMetadata, ): Array<ElementInstanceMetadata> => { // autoSizing views are the new groups if (this.isAutoSizingViewFromComponents(metadata, childInstance.elementPath)) { const rawChildren = MetadataUtils.getChildren(metadata, childInstance.elementPath) const children = Utils.flatMapArray(getChildrenInner, rawChildren) if (includeGroups) { return [childInstance, ...children] } else { return children } } else { return [childInstance] } } return Utils.flatMapArray(getChildrenInner, immediateChildren) }, getStoryboardMetadata(metadata: ElementInstanceMetadataMap): ElementInstanceMetadata | null { return Object.values(metadata).find((e) => EP.isStoryboardPath(e.elementPath)) ?? null }, getAllStoryboardChildren(metadata: ElementInstanceMetadataMap): ElementInstanceMetadata[] { const storyboardMetadata = MetadataUtils.getStoryboardMetadata(metadata) return storyboardMetadata == null ? [] : MetadataUtils.getImmediateChildren(metadata, storyboardMetadata.elementPath) }, getAllStoryboardChildrenPaths(metadata: ElementInstanceMetadataMap): ElementPath[] { const storyboardMetadata = MetadataUtils.getStoryboardMetadata(metadata) return storyboardMetadata == null ? [] : MetadataUtils.getImmediateChildrenPaths(metadata, storyboardMetadata.elementPath) }, getAllCanvasRootPaths(metadata: ElementInstanceMetadataMap): ElementPath[] { const rootScenesAndElements = MetadataUtils.getAllStoryboardChildren(metadata) return flatMapArray<ElementInstanceMetadata, ElementPath>((root) => { const rootElements = MetadataUtils.getRootViewPaths(metadata, root.elementPath) if (rootElements.length > 0) { return rootElements } else { return [root.elementPath] } }, rootScenesAndElements) }, getAllPaths(metadata: ElementInstanceMetadataMap): ElementPath[] { // This function needs to explicitly return the paths in a depth first manner let result: Array<ElementPath> = [] function recurseElement(elementPath: ElementPath): void { result.push(elementPath) const descendants = MetadataUtils.getImmediateChildrenPaths(metadata, elementPath) fastForEach(descendants, recurseElement) } const storyboardChildren = this.getAllStoryboardChildrenPaths(metadata) fastForEach(storyboardChildren, recurseElement) return uniqBy<ElementPath>(result, EP.pathsEqual) }, getAllPathsIncludingUnfurledFocusedComponents( metadata: ElementInstanceMetadataMap, ): ElementPath[] { // This function needs to explicitly return the paths in a depth first manner let result: Array<ElementPath> = [] function recurseElement(elementPath: ElementPath): void { result.push(elementPath) const { children, unfurledComponents, } = MetadataUtils.getAllChildrenIncludingUnfurledFocusedComponents(elementPath, metadata) const childrenIncludingUnfurledComponents = [...children, ...unfurledComponents] fastForEach(childrenIncludingUnfurledComponents, recurseElement) } const rootInstances = this.getAllStoryboardChildrenPaths(metadata) fastForEach(rootInstances, (rootInstance) => { const element = MetadataUtils.findElementByElementPath(metadata, rootInstance) if (element != null) { result.push(rootInstance) const rootElements = MetadataUtils.getRootViewPaths(metadata, element.elementPath) rootElements.forEach(recurseElement) const children = MetadataUtils.getChildrenPaths(metadata, element.elementPath) children.forEach(recurseElement) } }) return uniqBy<ElementPath>(result, EP.pathsEqual) }, isElementOfType(instance: ElementInstanceMetadata, elementType: string): boolean { return foldEither( (name) => name === elementType, (element) => isJSXElement(element) && getJSXElementNameLastPart(element.name) === elementType, instance.element, ) }, isUtopiaAPIElementFromImports(imports: Imports, instance: ElementInstanceMetadata): boolean { return foldEither( (_) => false, (element) => isJSXElement(element) && isUtopiaAPIComponent(element.name, imports), instance.element, ) }, isGivenUtopiaAPIElementFromImports( instance: ElementInstanceMetadata, elementType: string, ): boolean { // KILLME Replace with isGivenUtopiaElementFromMetadata from project-file-utils.ts return isGivenUtopiaElementFromMetadata(instance, elementType) }, isViewAgainstImports(instance: ElementInstanceMetadata | null): boolean { return instance != null && MetadataUtils.isGivenUtopiaAPIElementFromImports(instance, 'View') }, isImg(instance: ElementInstanceMetadata): boolean { return this.isElementOfType(instance, 'img') }, isTextAgainstImports(instance: ElementInstanceMetadata | null): boolean { return instance != null && MetadataUtils.isGivenUtopiaAPIElementFromImports(instance, 'Text') }, isDiv(instance: ElementInstanceMetadata): boolean { return this.isElementOfType(instance, 'div') }, isSpan(instance: ElementInstanceMetadata): boolean { return this.isElementOfType(instance, 'span') }, overflows(instance: ElementInstanceMetadata | null): boolean { if (instance != null) { const overflow = Utils.propOr('visible', 'overflow', instance.props.style) return overflow !== 'hidden' && overflow !== 'clip' } else { return false } }, targetElementSupportsChildren(instance: ElementInstanceMetadata): boolean { // FIXME Replace with a property controls check const elementEither = instance.element if (isLeft(elementEither)) { return intrinsicHTMLElementNamesThatSupportChildren.includes(elementEither.value) } else { const element = elementEither.value if (isJSXElement(element) && isUtopiaAPIComponentFromMetadata(instance)) { // Explicitly prevent components / elements that we *know* don't support children return ( isViewLikeFromMetadata(instance) || isSceneFromMetadata(instance) || isGivenUtopiaElementFromMetadata(instance, 'Text') ) } else { // We don't know at this stage return true } } }, targetSupportsChildren(metadata: ElementInstanceMetadataMap, target: ElementPath): boolean { const instance = MetadataUtils.findElementByElementPath(metadata, target) return instance == null ? false : MetadataUtils.targetElementSupportsChildren(instance) }, getTextContentOfElement(element: ElementInstanceMetadata): string | null { if (isRight(element.element) && isJSXElement(element.element.value)) { if (element.element.value.children.length === 1) { const childElement = element.element.value.children[0] if (isJSXTextBlock(childElement)) { return childElement.text } else if (isJSXArbitraryBlock(childElement)) { return `{${childElement.originalJavascript}}` } } else if (element.element.value.children.length === 0) { return '' } } return null }, // TODO update this to work with the natural width / height getImageMultiplier( metadata: ElementInstanceMetadataMap, targets: Array<ElementPath>, ): number | null { const multipliers: Set<number> = Utils.emptySet() Utils.fastForEach(targets, (target) => { const instance = MetadataUtils.findElementByElementPath(metadata, target) if (instance != null && this.isImg(instance)) { const componentFrame = instance.localFrame if (componentFrame != null) { const imageSize = getImageSize(instance) const widthMultiplier = imageSize.width / componentFrame.width const roundedMultiplier = Utils.roundTo(widthMultiplier, 0) // Recalculate the scaled dimensions to see if they match. const scaledSize = scaleImageDimensions(imageSize, roundedMultiplier) const roundedSize = { width: Utils.roundTo(scaledSize.width, 0), height: Utils.roundTo(scaledSize.height, 0), } if ( roundedSize.width === componentFrame.width && roundedSize.height === componentFrame.height ) { multipliers.add(roundedMultiplier) } } } }) if (multipliers.size === 1) { return multipliers.values().next().value } else { return null } }, getAllChildrenIncludingUnfurledFocusedComponents( path: ElementPath, metadata: ElementInstanceMetadataMap, ): { children: Array<ElementPath>; unfurledComponents: Array<ElementPath> } { return { children: MetadataUtils.getChildrenPaths(metadata, path), unfurledComponents: MetadataUtils.getRootViewPaths(metadata, path), } }, getAllChildrenElementsIncludingUnfurledFocusedComponents( path: ElementPath, metadata: ElementInstanceMetadataMap, ): { children: Array<ElementInstanceMetadata> unfurledComponents: Array<ElementInstanceMetadata> } { return { children: MetadataUtils.getChildren(metadata, path), unfurledComponents: MetadataUtils.getRootViews(metadata, path), } }, createOrderedElementPathsFromElements( metadata: ElementInstanceMetadataMap, collapsedViews: Array<ElementPath>, ): { navigatorTargets: Array<ElementPath> visibleNavigatorTargets: Array<ElementPath> } { // This function exists separately from getAllPaths because the Navigator handles collapsed views let navigatorTargets: Array<ElementPath> = [] let visibleNavigatorTargets: Array<ElementPath> = [] function walkAndAddKeys(path: ElementPath, collapsedAncestor: boolean): void { navigatorTargets.push(path) if (!collapsedAncestor) { visibleNavigatorTargets.push(path) } const { children, unfurledComponents, } = MetadataUtils.getAllChildrenIncludingUnfurledFocusedComponents(path, metadata) const childrenIncludingFocusedElements = [...children, ...unfurledComponents] const isCollapsed = EP.containsPath(path, collapsedViews) fastForEach(childrenIncludingFocusedElements, (childElement) => { walkAndAddKeys(childElement, collapsedAncestor || isCollapsed) }) } const canvasRoots = MetadataUtils.getAllStoryboardChildrenPaths(metadata) fastForEach(canvasRoots, (childElement) => { walkAndAddKeys(childElement, false) }) return { navigatorTargets: navigatorTargets, visibleNavigatorTargets: visibleNavigatorTargets, } }, transformAtPathOptionally( elementMap: ElementInstanceMetadataMap, path: ElementPath, transform: (element: ElementInstanceMetadata) => ElementInstanceMetadata, ): ElementInstanceMetadataMap { const existing = MetadataUtils.findElementByElementPath(elementMap, path) if (existing == null) { return elementMap } else { const transformed = transform(existing) if (transformed === existing) { return elementMap } else { return { ...elementMap, [EP.toString(path)]: transformed, } } } }, getFrameInCanvasCoords( path: ElementPath, metadata: ElementInstanceMetadataMap, ): CanvasRectangle | null { const element = MetadataUtils.findElementByElementPath(metadata, path) return Utils.optionalMap((e) => e.globalFrame, element) }, getFrame(path: ElementPath, metadata: ElementInstanceMetadataMap): LocalRectangle | null { const element = MetadataUtils.findElementByElementPath(metadata, path) return Utils.optionalMap((e) => e.localFrame, element) }, getFrameRelativeTo: function ( parent: ElementPath | null, metadata: ElementInstanceMetadataMap, frame: CanvasRectangle, ): LocalRectangle { if (parent == null) { return Utils.asLocal(frame) } else { const paths = EP.allPathsForLastPart(parent) const parentFrames: Array<LocalRectangle> = Utils.stripNulls( paths.map((path) => this.getFrame(path, metadata)), ) return parentFrames.reduce((working, next) => { return Utils.offsetRect(working, { x: -next.x, y: -next.y, } as LocalRectangle) }, Utils.asLocal(frame)) } }, getElementLabelFromProps(element: ElementInstanceMetadata): string | null { const dataLabelProp = element.props[UTOPIA_LABEL_KEY] if (dataLabelProp != null && typeof dataLabelProp === 'string' && dataLabelProp.length > 0) { return dataLabelProp } else { return null } }, getElementLabel( path: ElementPath, metadata: ElementInstanceMetadataMap, staticName: JSXElementName | null = null, ): string { const element = this.findElementByElementPath(metadata, path) if (element != null) { const sceneLabel = element.label // KILLME? const dataLabelProp = MetadataUtils.getElementLabelFromProps(element) if (dataLabelProp != null) { return dataLabelProp } else if (sceneLabel != null) { return sceneLabel } else { const possibleName: string = foldEither( (tagName) => { const staticNameString = optionalMap(getJSXElementNameAsString, staticName) return staticNameString ?? tagName }, (jsxElement) => { switch (jsxElement.type) { case 'JSX_ELEMENT': const lastNamePart = getJSXElementNameLastPart(jsxElement.name) // Check for certain elements and check if they have text content within them. if (ElementsToDrillIntoForTextContent.includes(lastNamePart)) { const firstChild = jsxElement.children[0] if (firstChild != null) { if (isJSXTextBlock(firstChild)) { return firstChild.text } if (isJSXArbitraryBlock(firstChild)) { return `{${firstChild.originalJavascript}}` } } } // With images, take their alt and src properties as possible names first. if (lastNamePart === 'img') { const alt = element.props['alt'] if (alt != null && typeof alt === 'string' && alt.length > 0) { return alt } const src = element.props['src'] if (src != null && typeof src === 'string' && src.length > 0) { return src } } // For Text elements, use their text property if it exists. if (lastNamePart === 'Text') { const text = element.props['text'] if (text != null && typeof text === 'string' && text.length > 0) { return text } } return lastNamePart case 'JSX_TEXT_BLOCK': return '(text)' case 'JSX_ARBITRARY_BLOCK': return '(code)' case 'JSX_FRAGMENT': return '(fragment)' default: const _exhaustiveCheck: never = jsxElement throw new Error(`Unexpected element type ${jsxElement}`) } }, element.element, ) if (possibleName != null) { return possibleName } if (isRight(element.element)) { if (isJSXElement(element.element.value)) { return getJSXElementNameLastPart(element.element.value.name).toString() } } } } // Default catch all name, will probably avoid some odd cases in the future. return 'Element' }, getJSXElementFromMetadata( metadata: ElementInstanceMetadataMap, path: ElementPath, ): JSXElement | null { const element = MetadataUtils.findElementByElementPath(metadata, path) if (element == null) { return null } else { return foldEither( (_) => null, (e) => (isJSXElement(e) ? e : null), element.element, ) } }, getJSXElementName(jsxElement: JSXElementChild | null): JSXElementName | null { if (jsxElement != null) { if (isJSXElement(jsxElement)) { return jsxElement.name } else { return null } } else { return null } }, getJSXElementNameFromMetadata( metadata: ElementInstanceMetadataMap, path: ElementPath, ): JSXElementName | null { const element = MetadataUtils.findElementByElementPath(metadata, path) if (element != null) { return MetadataUtils.getJSXElementName(eitherToMaybe(element.element)) } else { return null } }, getJSXElementBaseName(path: ElementPath, components: Array<UtopiaJSXComponent>): string | null { const jsxElement = findElementAtPath(path, components) if (jsxElement != null) { if (isJSXElement(jsxElement)) { return jsxElement.name.baseVariable } else { return null } } else { return null } }, getJSXElementTagName(path: ElementPath, components: Array<UtopiaJSXComponent>): string | null { const jsxElement = findElementAtPath(path, components) if (jsxElement != null) { if (isJSXElement(jsxElement)) { return getJSXElementNameAsString(jsxElement.name) } else { return null } } else { return null } }, getDuplicationParentTargets(targets: ElementPath[]): ElementPath | null { return EP.getCommonParent(targets) }, mergeComponentMetadata( elementsByUID: ElementsByUID, fromSpy: ElementInstanceMetadataMap, fromDOM: Array<ElementInstanceMetadata>, ): ElementInstanceMetadataMap { // This logic effectively puts everything from the spy first, // then anything missed out from the DOM right after it. // Ideally this would function like a VCS diff inserting runs of new elements // inbetween matching metadata, so it may be necessary to implement something // like that in the future. But for now this is likely "good enough" that it // wont make any difference. let workingElements: ElementInstanceMetadataMap = { ...fromSpy } let newlyFoundElements: Array<ElementPath> = [] fastForEach(fromDOM, (domElem) => { const spyElem = MetadataUtils.findElementByElementPath(fromSpy, domElem.elementPath) if (spyElem == null) { workingElements[EP.toString(domElem.elementPath)] = domElem newlyFoundElements.push(domElem.elementPath) } else { let componentInstance = spyElem.componentInstance || domElem.componentInstance let jsxElement = alternativeEither(spyElem.element, domElem.element) const elemUID: string | null = EP.toStaticUid(domElem.elementPath) const possibleElement = elementsByUID[elemUID] if (possibleElement != null) { if (!isIntrinsicElement(possibleElement.name)) { componentInstance = true jsxElement = right(possibleElement) } } const elem: ElementInstanceMetadata = { ...domElem, props: spyElem.props, element: jsxElement, componentInstance: componentInstance, isEmotionOrStyledComponent: spyElem.isEmotionOrStyledComponent, label: spyElem.label, importInfo: spyElem.importInfo, } workingElements[EP.toString(domElem.elementPath)] = elem } }) return workingElements }, isStaticElement(elements: Array<UtopiaJSXComponent>, target: ElementPath): boolean { const originType = this.getElementOriginType(elements, target) return originType === 'statically-defined' }, removeElementMetadataChild( target: ElementPath, metadata: ElementInstanceMetadataMap, ): ElementInstanceMetadataMap { // Note this only removes the child element from the metadata, but keeps grandchildren in there (inaccessible). Is this a memory leak? let remainingElements: ElementInstanceMetadataMap = omit([EP.toString(target)], metadata) if (Object.keys(remainingElements).length === Object.keys(metadata).length) { // Nothing was removed return metadata } else { return remainingElements } }, insertElementMetadataChild( targetParent: ElementPath | null, elementToInsert: ElementInstanceMetadata, metadata: ElementInstanceMetadataMap, ): ElementInstanceMetadataMap { // Insert into the map if (!EP.pathsEqual(EP.parentPath(elementToInsert.elementPath), targetParent)) { throw new Error( `insertElementMetadataChild: trying to insert child metadata with incorrect parent path prefix. Target parent: ${EP.toString(targetParent!)}, child path: ${EP.toString(elementToInsert.elementPath)}`, ) } const withNewElement: ElementInstanceMetadataMap = { ...metadata, [EP.toString(elementToInsert.elementPath)]: elementToInsert, } return withNewElement }, duplicateElementMetadataAtPath( oldPath: ElementPath, newPath: ElementPath, newElement: Either<string, JSXElementChild>, metadata: ElementInstanceMetadataMap, ): ElementInstanceMetadataMap { let workingElements = { ...metadata } function duplicateElementMetadata( element: ElementInstanceMetadata, pathToReplace: ElementPath, pathToReplaceWith: ElementPath, newElementInner: Either<string, JSXElementChild>, ): ElementPath { const newElementPath = EP.replaceIfAncestor( element.elementPath, pathToReplace, pathToReplaceWith, )! const newElementMetadata: ElementInstanceMetadata = { ...element, elementPath: newElementPath, element: newElementInner, } workingElements[EP.toString(newElementPath)] = newElementMetadata return newElementPath } // Everything about this feels wrong const originalMetadata = MetadataUtils.findElementByElementPath(metadata, oldPath) if (originalMetadata == null) { return metadata } else { duplicateElementMetadata(originalMetadata, oldPath, newPath, newElement) return workingElements } }, transformAllPathsInMetadata( metadata: ElementInstanceMetadataMap, replaceSearch: ElementPath, replaceWith: ElementPath | null, ): ElementInstanceMetadataMap { let updatedElements: ElementInstanceMetadataMap = { ...metadata } const allPathsWithReplacements = Object.values(metadata) .map((e) => e.elementPath) .filter((path) => EP.isDescendantOfOrEqualTo(path, replaceSearch)) .map((path) => { const replacement = EP.replaceOrDefault(path, replaceSearch, replaceWith) return { path: path, replacement: replacement, pathString: EP.toString(path), replacementString: EP.toString(replacement), } }) // TODO updateChildren should actually change the keys of the children in the metadata... function updateChildren(children: ElementPath[]): ElementPath[] { let childWasUpdated = false const updatedChildren = children.map((child) => { const replacementChild = allPathsWithReplacements.find((pathWithReplacement) => EP.pathsEqual(pathWithReplacement.path, child), ) childWasUpdated = childWasUpdated && replacementChild != null return replacementChild == null ? child : replacementChild.replacement }) return childWasUpdated ? updatedChildren : children } fastForEach( allPathsWithReplacements, ({ path, replacement, pathString, replacementString }) => { const existing = MetadataUtils.findElementByElementPath(updatedElements, path) if (existing != null) { delete updatedElements[pathString] updatedElements[replacementString] = { ...existing, elementPath: replacement, } } }, ) return updatedElements }, findElementMetadata( target: ElementPath, elements: ReadonlyArray<ElementInstanceMetadata>, ): ElementInstanceMetadata | null { return elements.find((elem) => EP.pathsEqual(target, elem.elementPath)) ?? null }, getStaticElementName( path: ElementPath, rootElements: Array<UtopiaJSXComponent>, ): JSXElementName | null { const staticPath = EP.dynamicPathToStaticPath(path) const jsxElement = optionalMap((p) => findJSXElementChildAtPath(rootElements, p), staticPath) return optionalMap((element) => (isJSXElement(element) ? element.name : null), jsxElement) }, isComponentInstance(path: ElementPath, rootElements: Array<UtopiaJSXComponent>): boolean { const elementName = MetadataUtils.getStaticElementName(path, rootElements) return elementName != null && !isIntrinsicHTMLElement(elementName) }, isPinnedAndNotAbsolutePositioned( metadata: ElementInstanceMetadataMap, view: ElementPath, ): boolean { // Disable snapping and guidelines for pinned elements marked with relative positioning: const elementMetadata = MetadataUtils.findElementByElementPath(metadata, view) return ( elementMetadata != null && elementMetadata.specialSizeMeasurements.parentLayoutSystem === 'flow' && !MetadataUtils.isPositionAbsolute(elementMetadata) ) }, walkMetadata( metadata: ElementInstanceMetadataMap, withEachElement: ( element: ElementInstanceMetadata, parentMetadata: ElementInstanceMetadata | null, ) => void, ): void { fastForEach(Object.values(metadata), (elem) => { const parentPath = EP.parentPath(elem.elementPath) const parent = MetadataUtils.findElementByElementPath(metadata, parentPath) withEachElement(elem, parent) }) }, findContainingBlock( elementMap: ElementInstanceMetadataMap, path: ElementPath, ): ElementPath | null { const specialSizeMeasurements = MetadataUtils.findElementByElementPath(elementMap, path) ?.specialSizeMeasurements const parentPath = EP.parentPath(path) if (parentPath == null || specialSizeMeasurements == null) { return null } if (specialSizeMeasurements.immediateParentProvidesLayout) { return parentPath } else { return this.findContainingBlock(elementMap, parentPath) } }, findNearestAncestorFlexDirectionChange( elementMap: ElementInstanceMetadataMap, path: ElementPath, ): ElementPath | null { const parentPath = EP.parentPath(path) const specialSizeMeasurements = MetadataUtils.findElementByElementPath(elementMap, path) ?.specialSizeMeasurements const parentSizeMeasurements = MetadataUtils.findElementByElementPath(elementMap, parentPath) ?.specialSizeMeasurements if (parentPath == null || specialSizeMeasurements == null || parentSizeMeasurements == null) { return null } if (specialSizeMeasurements.flexDirection !== parentSizeMeasurements.flexDirection) { return parentPath } else { return this.findNearestAncestorFlexDirectionChange(elementMap, parentPath) } }, isFocusableComponent(path: ElementPath, metadata: ElementInstanceMetadataMap): boolean { const element = MetadataUtils.findElementByElementPath(metadata, path) const elementName = MetadataUtils.getJSXElementName(maybeEitherToMaybe(element?.element)) if (element?.isEmotionOrStyledComponent) { return false } const isAnimatedComponent = isAnimatedElement(element) if (isAnimatedComponent) { return false } const isImported = isImportedComponentNPM(element) if (isImported) { return false } const isComponent = elementName != null && !isIntrinsicElement(elementName) if (isComponent) { return true } else { return false } }, isFocusableLeafComponent(path: ElementPath, metadata: ElementInstanceMetadataMap): boolean { return ( MetadataUtils.getChildrenPaths(metadata, path).length === 0 && MetadataUtils.isFocusableComponent(path, metadata) ) }, isEmotionOrStyledComponent(path: ElementPath, metadata: ElementInstanceMetadataMap): boolean { const element = MetadataUtils.findElementByElementPath(metadata, path) return element?.isEmotionOrStyledComponent ?? false }, } export function findElementAtPath( target: ElementPath | null, components: Array<UtopiaJSXComponent>, ): JSXElementChild | null { if (target == null) { return null } else { const staticTarget = EP.dynamicPathToStaticPath(target) return findJSXElementChildAtPath(components, staticTarget) } } export function findJSXElementAtPath( target: ElementPath | null, components: Array<UtopiaJSXComponent>, ): JSXElement | null { const elem = findElementAtPath(target, components) return Utils.optionalMap((e) => { if (isJSXElement(e)) { return e } else { return null } }, elem) } export function getScenePropsOrElementAttributes( target: ElementPath, metadata: ElementInstanceMetadataMap, ): PropsOrJSXAttributes | null { const targetMetadata = MetadataUtils.findElementByElementPath(metadata, target) if (targetMetadata == null) { return null } else { return foldEither( () => null, (element) => { if (isJSXElement(element)) { return right(element.props) } else { return null } }, targetMetadata.element, ) } } export type PropsOrJSXAttributes = Either<any, JSXAttributes> export function getSimpleAttributeAtPath( propsOrAttributes: PropsOrJSXAttributes, path: PropertyPath, ): Either<string, any> { return foldEither( (props) => { const possibleValue = Utils.path(PP.getElements(path), props) if (possibleValue == null) { return right(undefined) } else { return right(possibleValue) } }, (attributes) => { const getAttrResult = getModifiableJSXAttributeAtPath(attributes, path) return flatMapEither((attr) => jsxSimpleAttributeToValue(attr), getAttrResult) }, propsOrAttributes, ) }
the_stack
import Conditions from '../../../../../resources/conditions'; import NetRegexes from '../../../../../resources/netregexes'; import { UnreachableCode } from '../../../../../resources/not_reached'; import Outputs from '../../../../../resources/outputs'; import { Responses } from '../../../../../resources/responses'; import ZoneId from '../../../../../resources/zone_id'; import { RaidbossData } from '../../../../../types/data'; import { NetMatches } from '../../../../../types/net_matches'; import { TriggerSet } from '../../../../../types/trigger'; // TODO: is there a way to know if a Tertius Terminus Est sword is X or +? // 55CD has no heading. // 55CE has a heading of 45 degrees, but that's too late to know. // https://jp.finalfantasyxiv.com/lodestone/character/28705669/blog/4618012/ // TODO: handle mechanized maneuver with GetCombatnats? // TODO: handle divebombs during mechanized maneuver with GetCombatants? export interface Data extends RaidbossData { seenMines?: boolean; orbs?: NetMatches['AddedCombatant'][]; primusPlayers?: string[]; tertius?: NetMatches['Ability'][]; } const centerX = 100; const centerY = 100; const sharedOutputStrings = { sharedTankStack: { en: 'Tank stack', de: 'Tanks sammeln', fr: 'Package Tanks', ja: 'タンク頭割り', cn: '坦克分摊', ko: '탱끼리 모이기', }, }; const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.CastrumMarinumExtreme, timelineFile: 'emerald_weapon-ex.txt', timelineTriggers: [ { id: 'EmeraldEx Bit Storm', regex: /Bit Storm/, beforeSeconds: 4, response: Responses.getUnder(), }, { id: 'EmeraldEx Photon Ring', regex: /Photon Ring/, beforeSeconds: 4, response: Responses.getOut(), }, ], triggers: [ { id: 'EmeraldEx Emerald Shot', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55B0' }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55B0' }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55B0' }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55B0' }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55B0' }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55B0' }), response: Responses.tankBuster(), }, { id: 'EmeraldEx Optimized Ultima', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: ['55B1', '5B10'], capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: ['55B1', '5B10'], capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: ['55B1', '5B10'], capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: ['55B1', '5B10'], capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: ['55B1', '5B10'], capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: ['55B1', '5B10'], capture: false }), response: Responses.aoe(), }, { id: 'EmeraldEx Aetheroplasm Production', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55AA', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55AA', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55AA', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55AA', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55AA', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55AA', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Get orbs', de: 'Orbs nehmen', fr: 'Prenez les orbes', ja: '玉を処理', cn: '撞球', ko: '구슬 부딪히기', }, }, }, { id: 'EmeraldEx Aetheroplasm Rotate', type: 'AddedCombatant', // 9705 = Ceruleum Sphere, 9706 = Nitrosphere netRegex: NetRegexes.addedCombatantFull({ npcNameId: '9706' }), condition: (data, matches) => { (data.orbs ??= []).push(matches); return data.orbs.length === 4; }, alertText: (data, _matches, output) => { if (!data.orbs) return; const isNitro = [false, false, false, false, false, false, false, false]; for (const orb of data.orbs) { const x = parseFloat(orb.x) - centerX; const y = parseFloat(orb.y) - centerY; // Positions: N = (100, 78), E = (122, 100), S = (100, 122), W = (78, 100) // Dirs: N = 0, NE = 1, ..., NW = 7 const dir = Math.round(4 - 4 * Math.atan2(x, y) / Math.PI) % 8; if (isNitro[dir]) { console.error('Aetheroplasm collision'); return; } isNitro[dir] = true; } // Check if west must rotate clockwise to avoid taking two in a row. // There are only two patterns here, so it's sufficient to check west. if (isNitro[6] === isNitro[7]) return output.counterclock!(); return output.clockwise!(); }, outputStrings: { clockwise: { en: 'Rotate Clockwise', de: 'Im Uhrzeigersinn rotieren', fr: 'Tournez dans le sens horaire', cn: '顺时针转', ko: '시계방향', }, counterclock: { en: 'Rotate Counterclockwise', de: 'Gegen den Uhrzeigersinn rotieren', fr: 'Tournez dans le sens anti-horaire', cn: '逆时针转', ko: '반시계방향', }, }, }, { id: 'EmeraldEx Aire Tam Storm', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: ['558F', '55D0'], capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: ['558F', '55D0'], capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: ['558F', '55D0'], capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: ['558F', '55D0'], capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: ['558F', '55D0'], capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: ['558F', '55D0'], capture: false }), infoText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Away From Red Circle', de: 'Weg vom roten Kreis', fr: 'Éloignez vous du cercle rouge', cn: '远离红圈', ko: '빨간 장판에서 멀리 떨어지기', }, }, }, { id: 'EmeraldEx Magitek Magnetism', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '5594', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '5594', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '5594', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '5594', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '5594', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '5594', capture: false }), delaySeconds: 9, durationSeconds: 6, alertText: (data, _matches, output) => { // Suppress first magnetism call for tanks, who are handling flares. if (!data.seenMines && data.role === 'tank') return; return output.text!(); }, run: (data) => data.seenMines = true, outputStrings: { text: { en: 'Get Near Same Polarity Mines', de: 'Nahe den Bomben mit gleicher Polarisierung', fr: 'Allez vers les mines de même polarité', ja: '同じ極性の爆雷に近づく', cn: '靠近同级地雷', ko: '같은 극성 폭탄쪽으로', }, }, }, { id: 'EmeraldEx Divide Et Impera P1', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '5537', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '5537', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '5537', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '5537', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '5537', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '5537', capture: false }), alertText: (data, _matches, output) => { if (data.role === 'tank') return output.sharedTankStack!(); return output.spread!(); }, outputStrings: { spread: Outputs.spread, ...sharedOutputStrings, }, }, { id: 'EmeraldEx Magitek Magnetism Flare', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0057' }), condition: Conditions.targetIsYou(), alertText: (data, matches, output) => output.text!(), outputStrings: { text: { en: 'Flare on YOU', de: 'Flare auf DIR', fr: 'Brasier sur VOUS', ja: '自分にフレア', cn: '核爆点名', ko: '플레어 대상자', }, }, }, { id: 'EmeraldEx Magitek Magnetism Bait', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '0017' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Bait Lines Away From Safe Spot', de: 'Linien weg vom Safespot ködern', fr: 'Orientez les lignes hors de la zone sûre', ja: '線を安置に被らないように捨てる', cn: '诱导直线,不要覆盖安全点', ko: '안전지대 밖으로 장판 유도', }, }, }, { id: 'EmeraldEx Expire', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55[D9]1', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55[D9]1', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55[D9]1', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55[D9]1', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55[D9]1', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55[D9]1', capture: false }), response: Responses.getOut(), }, { id: 'EmeraldEx Divide Et Impera P2', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '555B', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '555B', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '555B', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '555B', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '555B', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '555B', capture: false }), alertText: (data, _matches, output) => { if (data.role === 'tank') return output.sharedTankStack!(); return output.protean!(); }, outputStrings: { protean: { en: 'Protean', de: 'Himmelsrichtungen', fr: 'Position', ja: '8方向散開', cn: '分散站位', ko: '정해진 위치로 산개', }, ...sharedOutputStrings, }, }, { id: 'EmeraldEx Primus Terminus Est', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00F[9ABC]' }), condition: (data, matches) => { (data.primusPlayers ??= []).push(matches.target); return data.me === matches.target; }, alertText: (_data, matches, output) => { const id = matches.id.toUpperCase(); if (id === '00F9') return output.text!({ dir: output.south!() }); if (id === '00FA') return output.text!({ dir: output.west!() }); if (id === '00FB') return output.text!({ dir: output.north!() }); if (id === '00FC') return output.text!({ dir: output.east!() }); }, outputStrings: { text: { en: 'Go ${dir}, Aim Across', de: 'Geh nach ${dir}, schau Gegenüber', fr: 'Allez direction ${dir}, visez en face', cn: '去${dir}, 看好对面', ko: '${dir}으로 이동, 반대쪽 확인', }, north: Outputs.north, east: Outputs.east, south: Outputs.south, west: Outputs.west, }, }, { id: 'EmeraldEx Primus Terminus Est Dodge', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00F[9ABC]', capture: false }), delaySeconds: 0.5, suppressSeconds: 1, alertText: (data, _matches, output) => { if (!data.primusPlayers?.includes(data.me)) return output.text!(); }, run: (data) => delete data.primusPlayers, outputStrings: { text: { en: 'Dodge Arrow Lines', de: 'Weiche den Pfeillinien aus', fr: 'Évitez les flèches (lignes)', cn: '避开箭头路径', ko: '화살표 방향 피하기', }, }, }, { id: 'EmeraldEx Tertius Terminus Cleanup', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55CC', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55CC', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55CC', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55CC', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55CC', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55CC', capture: false }), run: (data) => delete data.tertius, }, { id: 'EmeraldEx Tertius Terminus Est', // StartsUsing has positions but is inconsistent when entities are newly moved. // This is still ~7s of warning, and if we wanted to be fancier, knowing 4 would be enough. type: 'Ability', netRegex: NetRegexes.abilityFull({ source: 'BitBlade', id: '55CD' }), netRegexDe: NetRegexes.abilityFull({ source: 'Revolverklingen-Arm', id: '55CD' }), netRegexFr: NetRegexes.abilityFull({ source: 'Pistolame Volante', id: '55CD' }), netRegexJa: NetRegexes.abilityFull({ source: 'ガンブレードビット', id: '55CD' }), netRegexCn: NetRegexes.abilityFull({ source: '枪刃浮游炮', id: '55CD' }), netRegexKo: NetRegexes.abilityFull({ source: '건블레이드 비트', id: '55CD' }), durationSeconds: 7, alertText: (data, matches, output) => { (data.tertius ??= []).push(matches); if (data.tertius.length !== 6) return; const [s0, s1, s2, s3, s4, s5] = data.tertius.map((sword) => { const x = parseFloat(sword.x) - centerX; const y = parseFloat(sword.y) - centerY; if (Math.abs(x) < 10 && Math.abs(y) < 10) return output.middle!(); if (x < 0) return y < 0 ? output.dirNW!() : output.dirSW!(); return y < 0 ? output.dirNE!() : output.dirSE!(); }); if (!s0 || !s1 || !s2 || !s3 || !s4 || !s5) throw new UnreachableCode(); // A pair of swords s0/s1, s2/s3, s4/s5 is either two intercard corners or two middle. // The second pair (s2/s3) is never the middle pair of swords. // Therefore, if the first two are not the same, they are not the middle // and so the first safe is the middle set of swords (s4, s5). const firstSafeIsMiddle = s0 !== s1; if (firstSafeIsMiddle) return output.middleFirst!({ middle: s4, dir1: s0, dir2: s1 }); return output.middleLast!({ middle: s0, dir1: s4, dir2: s5 }); }, outputStrings: { dirNE: Outputs.dirNE, dirSE: Outputs.dirSE, dirSW: Outputs.dirSW, dirNW: Outputs.dirNW, middle: Outputs.middle, middleFirst: { en: '${middle} -> ${dir1} / ${dir2}', de: '${middle} -> ${dir1} / ${dir2}', fr: '${middle} -> ${dir1} / ${dir2}', cn: '${middle} -> ${dir1} / ${dir2}', ko: '${middle} -> ${dir1} / ${dir2}', }, middleLast: { en: '${dir1} / ${dir2} -> ${middle}', de: '${dir1} / ${dir2} -> ${middle}', fr: '${dir1} / ${dir2} -> ${middle}', cn: '${dir1} / ${dir2} -> ${middle}', ko: '${dir1} / ${dir2} -> ${middle}', }, }, }, { id: 'EmeraldEx Sidescathe Left', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55D5', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55D5', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55D5', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55D5', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55D5', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55D5', capture: false }), response: Responses.goLeft(), }, { id: 'EmeraldEx Sidescathe Right', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55D4', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55D4', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55D4', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55D4', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55D4', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55D4', capture: false }), response: Responses.goRight(), }, { id: 'EmeraldEx Emerald Crusher', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'The Emerald Weapon', id: '55D6', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Smaragd-Waffe', id: '55D6', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Arme Émeraude', id: '55D6', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'エメラルドウェポン', id: '55D6', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '绿宝石神兵', id: '55D6', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '에메랄드 웨폰', id: '55D6', capture: false }), // Don't collide with Tertius Terminus Est alert, and this is important. response: Responses.knockback('alarm'), }, { id: 'EmeraldEx Secundus Terminus Est Plus', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00FD' }), condition: Conditions.targetIsYou(), alarmText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Intercard + Out (Plus)', de: 'Interkardinal + Raus (Plus)', fr: 'Intercardinal + Extérieur (Plus)', cn: '去场边角落 (十字)', ko: '대각선 밖으로 (십자)', }, }, }, { id: 'EmeraldEx Secundus Terminus Est Cross', type: 'HeadMarker', netRegex: NetRegexes.headMarker({ id: '00FE' }), condition: Conditions.targetIsYou(), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Cardinal + Out (Cross)', de: 'Kardinal + Raus (Kreuz)', fr: 'Cardinal + Extérieur (Croix)', cn: '去场边中点 (X字)', ko: '동서남북 밖으로 (X자)', }, }, }, { id: 'EmeraldEx Magitek Cannon', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Reaper Image', id: '55BE', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Schnitter-Projektion', id: '55BE', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Spectre De Faucheuse', id: '55BE', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'リーパーの幻影', id: '55BE', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '魔导死神的幻影', id: '55BE', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '리퍼의 환영', id: '55BE', capture: false }), response: Responses.goMiddle(), }, { id: 'EmeraldEx Full Rank', type: 'StartsUsing', netRegex: NetRegexes.startsUsing({ source: 'Black Wolf\'s Image', id: '55C0', capture: false }), netRegexDe: NetRegexes.startsUsing({ source: 'Gaius-Projektion', id: '55C0', capture: false }), netRegexFr: NetRegexes.startsUsing({ source: 'Spectre De Gaius', id: '55C0', capture: false }), netRegexJa: NetRegexes.startsUsing({ source: 'ガイウスの幻影', id: '55C0', capture: false }), netRegexCn: NetRegexes.startsUsing({ source: '盖乌斯的幻影', id: '55C0', capture: false }), netRegexKo: NetRegexes.startsUsing({ source: '가이우스의 환영', id: '55C0', capture: false }), alertText: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'Go North; Dodge Soldiers/Divebombs', de: 'Geh nach Norden; Achte auf die Lücken zwischen den Soldaten', fr: 'Allez au Nord, Évitez les soldats et les bombes', ja: '飛行部隊と射撃部隊を見覚える', // FIXME cn: '去北边;躲避士兵射击/飞机轰炸', ko: '북쪽으로 이동, 엑사플레어, 병사 사격 확인', }, }, }, ], timelineReplace: [ { 'locale': 'en', 'replaceText': { 'Emerald Crusher / Aire Tam Storm': 'Crusher / Aire Tam', 'Aire Tam Storm / Emerald Crusher': 'Aire Tam / Crusher', }, }, { 'locale': 'de', 'replaceSync': { 'bitblade': 'Revolverklingen-Arm', 'Black Wolf\'s Image': 'Gaius-Projektion', 'Imperial Image': 'garleisch(?:e|er|es|en) Soldat', 'Reaper Image': 'Schnitter-Projektion', 'The Emerald Weapon': 'Smaragd-Waffe', }, 'replaceText': { '--cutscene--': '--Zwischensequence--', 'Aetheroplasm Production': 'Blitzgenerator', 'Aire Tam Storm': 'Smaragdfeuersturm', 'Bit Storm': 'Satellitenarme: Zirkelangriff', 'Divide Et Impera': 'Divide et Impera', 'Emerald Beam': 'Smaragdstrahl', 'Emerald Shot': 'Smaragdschuss', 'Expire': 'Exspirieren', 'Heirsbane': 'Erbenbann', 'Legio Phantasmatis': 'Legio Phantasmatis', 'Magitek Cannon': 'Magitek-Kanone', 'Magitek Magnetism': 'Magimagnetismus', 'Optimized Ultima': 'Ultima-System', 'Photon Ring': 'Photonenkreis', 'Primus Terminus Est': 'Terminus Est: Unus', 'Secundus Terminus Est': 'Terminus Est: Duo', 'Shots Fired': 'Synchron-Salve', 'Sidescathe': 'Flankenbeschuss', 'Split': 'Segregation', 'Tertius Terminus Est': 'Terminus Est: Tres', 'Mechanized Maneuver': 'Bewegungsmanöver', 'Bombs Away': 'Bombardierungsbefehl', 'Emerald Crusher': 'Smaragdspalter', 'Full Rank': 'Truppenappell', 'Final Formation': 'Schlachtreihe', 'Fatal Fire': 'Feuergefecht', }, }, { 'locale': 'fr', 'missingTranslations': true, 'replaceSync': { 'bitblade': 'pistolame volante', 'Black Wolf\'s Image': 'spectre de Gaius', 'Imperial Image': 'spectre de soldat impérial', 'Reaper Image': 'spectre de faucheuse', 'The Emerald Weapon': 'Arme Émeraude', }, 'replaceText': { '--cutscene--': '--cinématique--', 'Aetheroplasm Production': 'Condensation d\'éthéroplasma', 'Aire Tam Storm': 'Aire Tam Storm', 'Bit Storm': 'Salve circulaire', 'Divide Et Impera': 'Divide Et Impera', 'Emerald Beam': 'Rayon émeraude', 'Emerald Shot': 'Tir émeraude', 'Expire': 'Jet de plasma', 'Heirsbane': 'Fléau de l\'héritier', 'Legio Phantasmatis': 'Legio Phantasmatis', 'Magitek Cannon': 'Canon magitek', 'Magitek Magnetism': 'Électroaimant magitek', 'Optimized Ultima': 'Ultima magitek', 'Photon Ring': 'Cercle photonique', 'Primus Terminus Est': 'Terminus Est : Unus', 'Secundus Terminus Est': 'Terminus Est : Duo', 'Shots Fired': 'Fusillade', 'Sidescathe': 'Salve latérale', 'Split': 'Séparation', 'Tertius Terminus Est': 'Terminus Est : Tres', 'Mechanized Maneuver': 'Murmuration stratégique', 'Bombs Away': 'Ordre de bombardement', 'Emerald Crusher': 'Écraseur émeraude', 'Full Rank': 'Regroupement de toutes les unités', 'Final Formation': 'Alignement de toutes les unités', 'Fatal Fire': 'Attaque groupée', }, }, { 'locale': 'ja', 'missingTranslations': true, 'replaceSync': { 'bitblade': 'ガンブレードビット', 'Black Wolf\'s Image': 'ガイウスの幻影', 'Imperial Image': '帝国兵の幻影', 'Reaper Image': 'リーパーの幻影', 'The Emerald Weapon': 'エメラルドウェポン', }, 'replaceText': { '--cutscene--': '--カットシーン--', 'Aetheroplasm Production': '爆雷生成', 'Aire Tam Storm': 'エメラルドビッグバン', 'Bit Storm': 'アームビット:円形射撃', 'Divide Et Impera': 'ディヴィデ・エト・インペラ', 'Emerald Beam': 'エメラルドビーム', 'Emerald Shot': 'エメラルドショット', 'Expire': '噴射', 'Heirsbane': 'No.IX', 'Legio Phantasmatis': 'レギオ・ファンタズマティス', 'Magitek Cannon': '魔導カノン', 'Magitek Magnetism': '魔導マグネット', 'Optimized Ultima': '魔導アルテマ', 'Photon Ring': 'フォトンサークル', 'Primus Terminus Est': 'ターミナス・エスト:ウーヌス', 'Secundus Terminus Est': 'ターミナス・エスト:ドゥオ', 'Shots Fired': '一斉掃射', 'Sidescathe': '側面掃射', 'Split': '分離', 'Tertius Terminus Est': 'ターミナス・エスト:トレース', 'Mechanized Maneuver': '機動戦術', 'Bombs Away': '空爆命令', 'Emerald Crusher': 'エメラルドクラッシャー', 'Full Rank': '全軍集結', 'Final Formation': '全軍整列', 'Fatal Fire': '全軍攻撃', }, }, { 'locale': 'cn', 'replaceSync': { 'bitblade': '枪刃浮游炮', 'Black Wolf\'s Image': '盖乌斯的幻影', 'Imperial Image': '帝国兵的幻影', 'Reaper Image': '魔导死神的幻影', 'The Emerald Weapon': '绿宝石神兵', }, 'replaceText': { '--cutscene--': '--过场动画--', 'Aetheroplasm Production': '生成炸弹', 'Aire Tam Storm': '绿宝石大爆炸', 'Bit Storm': '浮游炮:圆形射击', 'Divide Et Impera': '分而治之', 'Emerald Beam': '绿宝石光束', 'Emerald Shot': '绿宝石射击', 'Expire': '喷射', 'Heirsbane': '遗祸', 'Legio Phantasmatis': '幻影军团', 'Magitek Cannon': '魔导加农炮', 'Magitek Magnetism': '魔导磁石', 'Optimized Ultima': '魔导究极', 'Photon Ring': '光子环', 'Primus Terminus Est': '恩惠终结:壹', 'Secundus Terminus Est': '恩惠终结:贰', 'Shots Fired': '一齐扫射', 'Sidescathe': '侧面扫射', 'Split': '分离', 'Tertius Terminus Est': '恩惠终结:叁', 'Mechanized Maneuver': '机动战术', 'Bombs Away': '轰炸命令', 'Emerald Crusher': '绿宝石碎击', 'Full Rank': '全军集合', 'Final Formation': '全军列队', 'Fatal Fire': '全军攻击', }, }, { 'locale': 'ko', 'replaceSync': { 'bitblade': '건블레이드 비트', 'Black Wolf\'s Image': '가이우스의 환영', 'Imperial Image': '제국 병사의 환영', 'Reaper Image': '리퍼의 환영', 'The Emerald Weapon': '에메랄드 웨폰', }, 'replaceText': { '--cutscene--': '--컷신--', 'Aetheroplasm Production': '폭뢰 생성', 'Aire Tam Storm': '에메랄드 대폭발', 'Bit Storm': '암 비트: 원형 사격', 'Divide Et Impera': '분할 통치', 'Emerald Beam': '에메랄드 광선', 'Emerald Shot': '에메랄드 발사', 'Expire': '분사', 'Heirsbane': '제IX호', 'Legio Phantasmatis': '환영 군단', 'Magitek Cannon': '마도포', 'Magitek Magnetism': '마도 자석', 'Optimized Ultima': '마도 알테마', 'Photon Ring': '광자 고리', 'Primus Terminus Est': '파멸의 종착역 I', 'Secundus Terminus Est': '파멸의 종착역 II', 'Shots Fired': '일제 소사', 'Sidescathe': '측면 소사', 'Split': '분리', 'Tertius Terminus Est': '파멸의 종착역 III', 'Mechanized Maneuver': '기동 전술', 'Bombs Away': '공중 폭격 명령', 'Emerald Crusher': '에메랄드 분쇄', 'Full Rank': '전군 집결', 'Final Formation': '전군 정렬', 'Fatal Fire': '전군 공격', }, }, ], }; export default triggerSet;
the_stack
import '../support/polyfills'; import {DEFAULT_THEME} from '../../../src/defaults'; import {isFirefox} from '../../../src/utils/platform'; import {createOrUpdateDynamicTheme, removeDynamicTheme} from '../../../src/inject/dynamic-theme'; import {multiline, timeout, waitForEvent} from '../support/test-utils'; const theme = { ...DEFAULT_THEME, darkSchemeBackgroundColor: 'black', darkSchemeTextColor: 'white', }; let container: HTMLElement; beforeEach(() => { container = document.body; container.innerHTML = ''; }); afterEach(() => { removeDynamicTheme(); container.innerHTML = ''; document.documentElement.removeAttribute('style'); }); describe('CSS VARIABLES OVERRIDE', () => { it('should override style with variables', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: gray;', ' --text: red;', ' }', ' h1 { background: var(--bg); }', ' h1 strong { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(102, 102, 102)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1 strong')).color).toBe('rgb(255, 26, 26)'); }); it('should override style with variables(that contain spaces)', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: gray;', ' --text: red;', ' }', ' h1 { background: var( --bg ); }', ' h1 strong { color: var( --text ); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(102, 102, 102)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1 strong')).color).toBe('rgb(255, 26, 26)'); }); it('should override style with variables (reverse order)', () => { container.innerHTML = multiline( '<style>', ' h1 { background: var(--bg); }', ' h1 strong { color: var(--text); }', '</style>', '<style>', ' :root {', ' --bg: gray;', ' --text: green;', ' }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(102, 102, 102)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1 strong')).color).toBe('rgb(140, 255, 140)'); }); it('should skip undefined variables', () => { container.innerHTML = multiline( '<style>', ' h1 { background: var(--bg); }', ' h1 strong { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1 strong')).color).toBe('rgb(255, 255, 255)'); }); it('should use fallback variable value', () => { container.innerHTML = multiline( '<style>', ' h1 { color: var(--text, red); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should not use fallback variable value', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --text: green;', ' }', ' h1 { color: var(--text, red); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should handle variables referencing other variables', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --alert: red;', ' --text: var(--alert);', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should handle variables referencing other variables (reverse order)', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --text: var(--alert);', ' --alert: red;', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should handle shorthand background with deep color refs', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --red: red;', ' --bg: var(--red);', ' }', ' h1 {', ' background: var(--bg);', ' }', '</style>', '<h1>CSS <strong>variables</strong></h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should handle background with deep color refs (backwards)', () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background: var(--bg);', ' }', ' :root {', ' --red: red;', ' --bg: var(--red);', ' }', '</style>', '<h1>CSS <strong>variables</strong></h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should handle multi-type vars with deep color refs', () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background: var(--bg);', ' color: var(--red);', ' }', ' :root {', ' --red: red;', ' --bg: var(--red);', ' }', '</style>', '<h1>CSS <strong>variables</strong></h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should handle variables having multiple types', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --dark: red;', ' --light: green;', ' }', ' .dark {', ' background-color: var(--dark);', ' color: var(--light);', ' }', ' .light {', ' background: var(--light);', ' color: var(--dark);', ' }', '</style>', '<h1 class="dark">Dark background light text</h1>', '<h1 class="light">Light background dark text</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('.dark')).backgroundColor).toBe('rgb(204, 0, 0)'); expect(getComputedStyle(container.querySelector('.dark')).color).toBe('rgb(140, 255, 140)'); expect(getComputedStyle(container.querySelector('.light')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('.light')).color).toBe('rgb(255, 26, 26)'); }); /* it('should handle variables having multiple types in shorthand properties', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color: green;', ' }', ' h1 {', ' border: 1px solid var(--color);', ' }', ' h1 {', ' background: linear-gradient(var(--color), white);', ' }', '</style>', '<h1>Variables</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundImage).toBe('linear-gradient(rgb(0, 102, 0), rgb(0, 0, 0))'); expect(getComputedStyle(container.querySelector('h1')).borderColor).toBe('rgb(0, 217, 0)'); }); */ it('should use fallback when nested variables are missing', () => { container.innerHTML = multiline( '<style>', ' h1 { color: var(--text, var(--alert, green)); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should not freeze on cyclic references', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --text: var(--text);', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); }); it('should not freeze on nested cyclic references', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --alert: var(--text);', ' --text: var(--alert);', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); }); it('should react on variable change', async () => { container.innerHTML = multiline( '<style id="variables">', ' :root {', ' --text: red;', ' }', '</style>', '<style>', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); const styleElement = document.getElementById('variables') as HTMLStyleElement; styleElement.textContent = ':root { --text: green; }'; await timeout(0); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should use <html> element variables', async () => { document.documentElement.setAttribute('style', '--text: red;'); container.innerHTML = multiline( '<style>', ' h1 { color: var(--text); }', '</style>', '<h1>CSS <strong>variables</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); document.documentElement.setAttribute('style', '--text: green;'); await timeout(0); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should consider variable selector', () => { container.innerHTML = multiline( '<style>', ' .red {', ' --text: red;', ' }', ' .green {', ' --text: green;', ' }', ' h1 { color: var(--text); }', '</style>', '<h1 class="red">Red CSS variable</h1>', '<h1 class="green">Green CSS variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('.red')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('.green')).color).toBe('rgb(140, 255, 140)'); }); it('should handle internal conversion of hex to RGB', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: #fff;', ' --text: #000;', ' }', '</style>', '<style>', ' h1 {', ' background: var(--bg);', ' color: var(--text);', ' }', '</style>', '<h1>Dark <strong>Theme</strong>!</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 0, 0)'); }); it('should handle variables inside color values (constructed colors)', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: 255, 255, 255;', ' --text: 0, 0, 0;', ' }', '</style>', '<style>', ' h1 {', ' background: rgb(var(--bg));', ' color: rgb(var(--text));', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 0, 0)'); }); it('should use fallback when variable inside a color not found', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background: rgb(var(--bg, 255, 0, 0));', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should handle variables in constructed colors that refer to other vars', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --v255: 255;', ' --red: var(--v255), 0, 0;', ' --bg: var(--unknown, var(--red));', ' --text: var(--red);', ' }', '</style>', '<style>', ' h1 {', ' background: rgb(var(--bg));', ' color: rgb(var(--text));', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should handle variables that refer to constructed colors', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --red: 255, 0, 0;', ' --blue: 0, 0, 255;', ' --rgb-blue: rgb(var(--blue));', ' --bg: rgb(var(--red));', ' --text: var(--rgb-blue);', ' }', '</style>', '<style>', ' h1 {', ' background: var(--bg);', ' color: var(--text);', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(51, 125, 255)'); }); it('should handle variables that refer to constructed colors asynchronously', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --red: 255, 0, 0;', ' --bg: rgb(var(--red));', ' }', ' h1 {', ' color: var(--text);', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( ':root {', ' --blue: 0, 0, 255;', ' --rgb-blue: rgb(var(--blue));', ' --text: var(--rgb-blue);', '}', 'h1 {', ' background: var(--bg);', '}', ); container.append(anotherStyle); await timeout(0); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(51, 125, 255)'); }); it('should handle variables that are both contructed and usual colors', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --red: 255, 0, 0;', ' --bg: green;', ' }', ' h1 {', ' --bg: rgb(var(--red));', ' background: var(--bg)', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should handle cyclic references in constructed colors', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: var(--text);', ' --text: var(--bg);', ' }', '</style>', '<style>', ' h1 {', ' background: rgb(var(--bg));', ' color: rgb(var(--text));', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 0, 0)'); }); it('should handle variables inside border color values', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --red: 255, 0, 0;', ' }', '</style>', '<style>', ' h1 {', ' border: 1px solid rgb(var(--red));', ' }', '</style>', '<h1>Colors with variables inside</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const elementStyle = getComputedStyle(container.querySelector('h1')); if (isFirefox) { expect(elementStyle.borderTopColor).toBe('rgb(179, 0, 0)'); expect(elementStyle.borderRightColor).toBe('rgb(179, 0, 0)'); expect(elementStyle.borderBottomColor).toBe('rgb(179, 0, 0)'); expect(elementStyle.borderLeftColor).toBe('rgb(179, 0, 0)'); } else { expect(elementStyle.borderColor).toBe('rgb(179, 0, 0)'); } }); it('should handle media variables', () => { container.innerHTML = multiline( '<style>', ' @media screen and (min-width: 2px) {', ' .red {', ' --text: red;', ' }', ' .orange {', ' --text: orange', ' }', ' }', ' @media screen and (min-width: 2000000px) {', ' .green {', ' --text: green;', ' }', ' }', ' h1 { color: var(--text); }', '</style>', '<h1 class="red">Red CSS variable</h1>', '<h1 class="green">Green CSS variable</h1>', '<h1 class="orange">Orange CSS variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('.red')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('.green')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('.orange')).color).toBe('rgb(255, 174, 26)'); }); it('should handle nested variables', () => { container.innerHTML = multiline( '<style>', ' @media screen and (min-width: 2px) {', ' @media screen and (min-width: 3px) {', ' .red {', ' --text: red;', ' }', ' }', ' }', ' @media screen and (min-width: 2px) {', ' @media screen and (min-width: 2000000px) {', ' .green {', ' --text: green;', ' }', ' }', ' }', ' @media screen and (min-width: 2000000px) {', ' @media screen and (min-width: 2px) {', ' .orange {', ' --text: orange;', ' }', ' }', ' }', ' h1 {', ' color: var(--text);', ' }', '</style>', '<h1 class="red">Red CSS variable</h1>', '<h1 class="green">Green CSS variable</h1>', '<h1 class="orange">Orange CSS variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container).backgroundColor).toBe('rgb(0, 0, 0)'); expect(getComputedStyle(container.querySelector('.red')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('.green')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('.orange')).color).toBe('rgb(255, 255, 255)'); }); it('should handle media with the same selectors', () => { container.innerHTML = multiline( '<style>', ' @media screen and (min-width: 2px) {', ' h1 {', ' --text: green;', ' }', ' }', ' @media screen and (max-width: 2px) {', ' h1 {', ' --text: red;', ' }', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>Media with same selectors</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should preserve media after change', () => { container.innerHTML = multiline( '<style>', ' @media screen and (min-width: 2px) {', ' /* This media should be used */', ' h1 {', ' --text: green;', ' }', ' }', ' @media screen and (max-width: 2px) {', ' /* This media should not be used */', ' h1 {', ' --text: red;', ' }', ' }', ' h1 { color: var(--text); }', '</style>', '<h1>Media after change</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should handle same selector with different variables', () => { container.innerHTML = multiline( '<style>', ' @media screen and (min-width: 2px) {', ' h1 {', ' --text: green;', ' }', ' h1 {', ' --bg: red;', ' }', ' }', ' h1 { color: var(--text); background-color: var(--bg); }', '</style>', '<h1>Media with same selectors</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(204, 0, 0)'); }); it('should properly modify variables in light mode', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --bg: white;', ' --text: black;', ' }', ' h1 {', ' background: var(--bg);', ' color: var(--text);', ' }', '</style>', '<h1>Light scheme</h1>', ); const lightTheme = {...theme, mode: 0, lightSchemeBackgroundColor: '#dddddd', lightSchemeTextColor: '#222222'}; createOrUpdateDynamicTheme(lightTheme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(221, 221, 221)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(34, 34, 34)'); }); it('should handle variables inside values', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --border-color: #ff0000;', ' --text: green;', ' }', ' h1 {', ' border-bottom: 2px solid var(--border-color);', ' color: var(--text);', ' }', '</style>', '<h1>Border with variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).borderBottomColor).toBe('rgb(179, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should handle variables that have variables inside', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --dark-red: #ff0000;', ' --border: 2px solid var(--dark-red);', ' --text: green;', ' }', ' h1 {', ' border: var(--border);', ' color: var(--text);', ' }', '</style>', '<h1>Border with variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).borderTopColor).toBe('rgb(179, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).borderBottomColor).toBe('rgb(179, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).borderLeftColor).toBe('rgb(179, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).borderRightColor).toBe('rgb(179, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should handle border color variables', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --border-color: green;', ' }', ' h1 {', ' border: 1px solid;', ' border-color: var(--border-color);', ' }', '</style>', '<h1>Border color with variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const elementStyle = getComputedStyle(container.querySelector('h1')); if (isFirefox) { expect(elementStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(elementStyle.borderColor).toBe('rgb(0, 217, 0)'); } }); it('should handle variables with gradients', () => { container.innerHTML = multiline( '<style>', ' :root {', ' --text: red;', ' --gradient: linear-gradient(red, white);', ' --bg: green;', ' }', ' h1 {', ' color: var(--text);', ' background-color: var(--bg);', ' background-image: var(--gradient);', ' }', ' h2 {', ' background: var(--gradient);', ' }', '</style>', '<h1>Weow Gradients</h1>', '<h2>Gradient 2</h2>' ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('h1')).backgroundImage).toBe('linear-gradient(rgb(204, 0, 0), rgb(0, 0, 0))'); expect(getComputedStyle(container.querySelector('h2')).backgroundImage).toBe('linear-gradient(rgb(204, 0, 0), rgb(0, 0, 0))'); }); it('should handle variables with background images', async () => { const darkIcon = multiline( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8">', ' <circle fill="black" cx="4" cy="4" r="3" />', '</svg>', ); const redCross = multiline( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8">', ' <path fill="red" d="M3,1 h2 v2 h2 v2 h-2 v2 h-2 v-2 h-2 v-2 h2 z" />', '</svg>', ); container.innerHTML = multiline( '<style>', ' :root {', ` --icon: url("data:image/svg+xml;base64,${btoa(darkIcon)}");`, ` --red-cross: url("data:image/svg+xml;base64,${btoa(redCross)}");`, ' --bg: green;', ' }', ' .icon1 {', ' background-color: var(--bg);', ' background-image: var(--icon);', ' background-repeat: no-repeat;', ' background-size: 100%;', ' display: inline-block;', ' height: 1rem;', ' width: 1rem;', ' }', ' .icon2 {', ' background: no-repeat center/100% var(--icon);', ' display: inline-block;', ' height: 1rem;', ' width: 1rem;', ' }', ' .icon3 {', ' background: no-repeat center/100% var(--red-cross), no-repeat center/100% var(--icon);', ' display: inline-block;', ' height: 1rem;', ' width: 1rem;', ' }', '</style>', '<h1>', ' <i class="icon1"></i>', ' <i class="icon2"></i>', ' <i class="icon3"></i>', ' Icons', '</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await waitForEvent('__darkreader__test__asyncQueueComplete'); expect(getComputedStyle(container.querySelector('.icon1')).backgroundImage).toMatch(/^url\("data:image\/svg\+xml;base64,.*"\)$/); expect(getComputedStyle(container.querySelector('.icon2')).backgroundImage).toMatch(/^url\("data:image\/svg\+xml;base64,.*"\)$/); expect(getComputedStyle(container.querySelector('.icon3')).backgroundImage).toMatch(/^url\("data:image\/svg\+xml;base64,.*"\), url\("data:image\/svg\+xml;base64,.*"\)$/); }); it('should handle variables with gradients and images', async () => { const darkIcon = multiline( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 8" width="8" height="8">', ' <circle fill="black" cx="4" cy="4" r="3" />', '</svg>', ); container.innerHTML = multiline( '<style>', ' :root {', ` --icon: url("data:image/svg+xml;base64,${btoa(darkIcon)}");`, ' --gradient: linear-gradient(red, white);', ' }', ' .icon {', ' background: no-repeat center/100% var(--icon), var(--gradient);', ' display: inline-block;', ' height: 1rem;', ' width: 1rem;', ' }', '</style>', '<h1><i class="icon"></i>Mixed background</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await waitForEvent('__darkreader__test__asyncQueueComplete'); expect(getComputedStyle(container.querySelector('.icon')).backgroundImage).toMatch(/^url\("data:image\/svg\+xml;base64,.*"\), linear-gradient\(rgb\(204, 0, 0\), rgb\(0, 0, 0\)\)$/); }); it('should handle asynchronous variable type resolution', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color1: red;', ' --color2: green;', ' }', '</style>', '<h1>Asynchronous variables</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( 'h1 {', ' background: var(--color2);', ' color: var(--color1);', '}', ); container.append(anotherStyle); await timeout(0); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should handle async resolution of multiple variable types', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color: green;', ' }', '</style>', '<h1>Asynchronous variables with multiple types</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( 'h1 {', ' background: var(--color);', ' border: 1px solid var(--color);', ' color: var(--color);', '}', ); container.append(anotherStyle); await timeout(0); const updatedStyle = getComputedStyle(container.querySelector('h1')); expect(updatedStyle.backgroundColor).toBe('rgb(0, 102, 0)'); expect(updatedStyle.color).toBe('rgb(140, 255, 140)'); if (isFirefox) { expect(updatedStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(updatedStyle.borderColor).toBe('rgb(0, 217, 0)'); } }); it('should handle variable type resolution when style changed', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color1: yellow;', ' --color2: blue;', ' }', '</style>', '<h1>Asynchronous variables</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); const styleEl = container.querySelector('style'); styleEl.textContent = multiline( ':root {', ' --color1: red;', ' --color2: green;', ' --color3: blue;', '}', ); await timeout(0); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( 'h1 {', ' background: var(--color2);', ' color: var(--color1);', '}', ); container.append(anotherStyle); await timeout(0); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should handle variable type change', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color: green;', ' }', ' h1 {', ' background: var(--color);', ' }', '</style>', '<h1>Asynchronous variables</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(255, 255, 255)'); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( 'h1 {', ' color: var(--color);', '}', ); container.append(anotherStyle); await timeout(0); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('h1')).color).toBe('rgb(140, 255, 140)'); }); it('should rebuild dependant variable rule when type becomes known', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background: var(--color);', ' }', '</style>', '<h1>Asynchronous variables</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( ':root {', ' --color: green;', '}', ); container.append(anotherStyle); await timeout(50); expect(getComputedStyle(container.querySelector('h1')).backgroundColor).toBe('rgb(0, 102, 0)'); }); it('should not affect other declarations when variable type resolved', async () => { container.innerHTML = multiline( '<style>', ' :root {', ' --color1: red;', ' --color2: green;', ' }', '</style>', '<h1 class="color1">Variables with color 1</h1>', '<h1 class="color2">Variables with color 2</h1>', ); createOrUpdateDynamicTheme(theme, null, false); expect(getComputedStyle(container.querySelector('.color1')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('.color1')).color).toBe('rgb(255, 255, 255)'); expect(getComputedStyle(container.querySelector('.color2')).backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(getComputedStyle(container.querySelector('.color2')).color).toBe('rgb(255, 255, 255)'); const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( '.color1 {', ' background: var(--color1);', ' color: var(--color1);', '}', '.color2 {', ' background: var(--color2);', ' color: var(--color2);', '}', ); container.append(anotherStyle); await timeout(0); expect(getComputedStyle(container.querySelector('.color1')).backgroundColor).toBe('rgb(204, 0, 0)'); expect(getComputedStyle(container.querySelector('.color1')).color).toBe('rgb(255, 26, 26)'); expect(getComputedStyle(container.querySelector('.color2')).backgroundColor).toBe('rgb(0, 102, 0)'); expect(getComputedStyle(container.querySelector('.color2')).color).toBe('rgb(140, 255, 140)'); }); it('should not affect other declarations when variable type resolved', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' --color-bg: red;', ' border: green;', ' }', ' h1 {', ' --color-text: green;', ' }', '</style>', '<h1>Variables along with other declarations</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(elementStyle.color).toBe('rgb(255, 255, 255)'); if (isFirefox) { expect(elementStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(elementStyle.borderColor).toBe('rgb(0, 217, 0)'); } const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( 'h1 {', ' background-color: var(--color-bg);', ' color: var(--color-text);', '}', ); container.append(anotherStyle); await timeout(0); const updatedStyle = getComputedStyle(container.querySelector('h1')); expect(updatedStyle.backgroundColor).toBe('rgb(204, 0, 0)'); expect(updatedStyle.color).toBe('rgb(140, 255, 140)'); if (isFirefox) { expect(updatedStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(updatedStyle.borderColor).toBe('rgb(0, 217, 0)'); } }); it('should not affect other declarations when dependency variable type resolved', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background: var(--color);', ' border: green;', ' }', ' h1 {', ' color: red;', ' }', '</style>', '<h1>Dependency variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.backgroundColor).toBe('rgba(0, 0, 0, 0)'); expect(elementStyle.color).toBe('rgb(255, 26, 26)'); if (isFirefox) { expect(elementStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(elementStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(elementStyle.borderColor).toBe('rgb(0, 217, 0)'); } const anotherStyle = document.createElement('style'); anotherStyle.textContent = multiline( ':root {', ' --color: green;', '}', ); container.append(anotherStyle); await timeout(50); const updatedStyle = getComputedStyle(container.querySelector('h1')); expect(updatedStyle.backgroundColor).toBe('rgb(0, 102, 0)'); expect(updatedStyle.color).toBe('rgb(255, 26, 26)'); if (isFirefox) { expect(updatedStyle.borderTopColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderRightColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderBottomColor).toBe('rgb(0, 217, 0)'); expect(updatedStyle.borderLeftColor).toBe('rgb(0, 217, 0)'); } else { expect(updatedStyle.borderColor).toBe('rgb(0, 217, 0)'); } }); it('should add variables to root after the variable type is discovered', async () => { document.documentElement.setAttribute('style', '--text: red;'); container.innerHTML = multiline( '<style class="testcase-sheet">', '</style>', '<h1>Dependency variable</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const sheet = (document.querySelector('.testcase-sheet') as HTMLStyleElement).sheet; sheet.insertRule('h1 { color: var(--text);'); await timeout(0); expect(getComputedStyle(document.querySelector('h1')).color).toBe('rgb(255, 26, 26)'); }); it('should modify the caret-color property', async () => { container.innerHTML = multiline( '<style>', ' * {', ' --caret-color: green;', ' }', ' h1 {', ' caret-color: var(--caret-color);', ' }', '</style>', '<h1>Caret Color</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await timeout(0); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.caretColor).toBe('rgb(140, 255, 140)'); }); it('should modify the box-shadow actual color values in a variable', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' --offset: 8px;', ' }', ' h1 {', ' box-shadow: calc(var(--offset)*-1 - 1px) 0 0 0 #fff', ' }', '</style>', '<h1>COmplicated shit :(</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await timeout(0); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.boxShadow).toBe('rgb(0, 0, 0) -9px 0px 0px 0px'); }); it(`shouldn't modify the raw value of box-shadow when their is no color`, async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' --color-border-muted: green;', ' }', ' h1 {', ' box-shadow: inset 0 -1px 0 var(--color-border-muted)', ' }', '</style>', '<h1>COmplicated shit :(</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await timeout(0); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.boxShadow).toBe('rgb(0, 102, 0) 0px -1px 0px 0px inset'); }); it('should handle raw values within variable declarations and use proper replacement', async () => { container.innerHTML = multiline( '<style>', ' h1 {', ' border: 1px solid rgba(var(--color,240,240,240),1);', ' }', ' :root {', ' --color: 123,123,123 !important;', ' }', ' div {', ' --color: 0,0,0 !important;', ' }', '</style>', '<h1>Raw values are spooky</h1>', ); createOrUpdateDynamicTheme(theme, null, false); await timeout(0); const elementStyle = getComputedStyle(container.querySelector('h1')); if (isFirefox) { expect(elementStyle.borderTopColor).toBe('rgb(91, 91, 91)'); expect(elementStyle.borderRightColor).toBe('rgb(91, 91, 91)'); expect(elementStyle.borderBottomColor).toBe('rgb(91, 91, 91)'); expect(elementStyle.borderLeftColor).toBe('rgb(91, 91, 91)'); } else { expect(elementStyle.borderColor).toBe('rgb(91, 91, 91)'); } }); it('should modify inline variable', () => { container.innerHTML = multiline( '<style>', ' h1 {', ' background-color: var(--inline-var);', ' }', '</style>', '<h1 style="--inline-var: red">Raw values are spooky</h1>', ); createOrUpdateDynamicTheme(theme, null, false); const elementStyle = getComputedStyle(container.querySelector('h1')); expect(elementStyle.backgroundColor).toBe('rgb(204, 0, 0)'); }); });
the_stack
import type { BuildResult } from 'esbuild'; import type vite from '../vite'; import type { AstroConfig, ComponentInstance, GetStaticPathsResult, GetStaticPathsResultKeyed, Params, Props, Renderer, RouteCache, RouteData, RuntimeMode, SSRElement, SSRError, } from '../../@types/astro'; import type { LogOptions } from '../logger'; import eol from 'eol'; import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import { renderPage } from '../../runtime/server/index.js'; import { codeFrame, resolveDependency } from '../util.js'; import { getStylesForURL } from './css.js'; import { injectTags } from './html.js'; import { generatePaginateFunction } from './paginate.js'; import { getParams, validateGetStaticPathsModule, validateGetStaticPathsResult } from './routing.js'; import { createResult } from './result.js'; import { assignStaticPaths, ensureRouteCached, findPathItemByKey } from './route-cache.js'; const svelteStylesRE = /svelte\?svelte&type=style/; interface SSROptions { /** an instance of the AstroConfig */ astroConfig: AstroConfig; /** location of file on disk */ filePath: URL; /** logging options */ logging: LogOptions; /** "development" or "production" */ mode: RuntimeMode; /** production website, needed for some RSS & Sitemap functions */ origin: string; /** the web request (needed for dynamic routes) */ pathname: string; /** optional, in case we need to render something outside of a dev server */ route?: RouteData; /** pass in route cache because SSR can’t manage cache-busting */ routeCache: RouteCache; /** Vite instance */ viteServer: vite.ViteDevServer; } const cache = new Map<string, Promise<Renderer>>(); // TODO: improve validation and error handling here. async function resolveRenderer(viteServer: vite.ViteDevServer, renderer: string, astroConfig: AstroConfig) { const resolvedRenderer: any = {}; // We can dynamically import the renderer by itself because it shouldn't have // any non-standard imports, the index is just meta info. // The other entrypoints need to be loaded through Vite. const { default: { name, client, polyfills, hydrationPolyfills, server }, } = await import(resolveDependency(renderer, astroConfig)); resolvedRenderer.name = name; if (client) resolvedRenderer.source = path.posix.join(renderer, client); resolvedRenderer.serverEntry = path.posix.join(renderer, server); if (Array.isArray(hydrationPolyfills)) resolvedRenderer.hydrationPolyfills = hydrationPolyfills.map((src: string) => path.posix.join(renderer, src)); if (Array.isArray(polyfills)) resolvedRenderer.polyfills = polyfills.map((src: string) => path.posix.join(renderer, src)); const { url } = await viteServer.moduleGraph.ensureEntryFromUrl(resolvedRenderer.serverEntry); const { default: rendererSSR } = await viteServer.ssrLoadModule(url); resolvedRenderer.ssr = rendererSSR; const completedRenderer: Renderer = resolvedRenderer; return completedRenderer; } async function resolveRenderers(viteServer: vite.ViteDevServer, astroConfig: AstroConfig): Promise<Renderer[]> { const ids: string[] = astroConfig.renderers; const renderers = await Promise.all( ids.map((renderer) => { if (cache.has(renderer)) return cache.get(renderer)!; let promise = resolveRenderer(viteServer, renderer, astroConfig); cache.set(renderer, promise); return promise; }) ); return renderers; } interface ErrorHandlerOptions { filePath: URL; viteServer: vite.ViteDevServer; } async function errorHandler(e: unknown, { viteServer, filePath }: ErrorHandlerOptions) { // normalize error stack line-endings to \n if ((e as any).stack) { (e as any).stack = eol.lf((e as any).stack); } // fix stack trace with Vite (this searches its module graph for matches) if (e instanceof Error) { viteServer.ssrFixStacktrace(e); } // Astro error (thrown by esbuild so it needs to be formatted for Vite) if (Array.isArray((e as any).errors)) { const { location, pluginName, text } = (e as BuildResult).errors[0]; const err = e as SSRError; if (location) err.loc = { file: location.file, line: location.line, column: location.column }; let src = err.pluginCode; if (!src && err.id && fs.existsSync(err.id)) src = await fs.promises.readFile(err.id, 'utf8'); if (!src) src = await fs.promises.readFile(filePath, 'utf8'); err.frame = codeFrame(src, err.loc); err.id = location?.file; err.message = `${location?.file}: ${text} ${err.frame} `; if (pluginName) err.plugin = pluginName; throw err; } // Generic error (probably from Vite, and already formatted) throw e; } export type ComponentPreload = [Renderer[], ComponentInstance]; export async function preload({ astroConfig, filePath, viteServer }: SSROptions): Promise<ComponentPreload> { // Important: This needs to happen first, in case a renderer provides polyfills. const renderers = await resolveRenderers(viteServer, astroConfig); // Load the module from the Vite SSR Runtime. const mod = (await viteServer.ssrLoadModule(fileURLToPath(filePath))) as ComponentInstance; return [renderers, mod]; } export async function getParamsAndProps({ route, routeCache, logging, pathname, mod, validate = true, }: { route: RouteData | undefined; routeCache: RouteCache; pathname: string; mod: ComponentInstance; logging: LogOptions; validate?: boolean; }): Promise<[Params, Props]> { // Handle dynamic routes let params: Params = {}; let pageProps: Props; if (route && !route.pathname) { if (route.params.length) { const paramsMatch = route.pattern.exec(pathname); if (paramsMatch) { params = getParams(route.params)(paramsMatch); } } if (validate) { validateGetStaticPathsModule(mod); } if (!routeCache[route.component]) { await assignStaticPaths(routeCache, route, mod); } if (validate) { // This validation is expensive so we only want to do it in dev. validateGetStaticPathsResult(routeCache[route.component], logging); } const staticPaths: GetStaticPathsResultKeyed = routeCache[route.component]; const paramsKey = JSON.stringify(params); const matchedStaticPath = findPathItemByKey(staticPaths, paramsKey, logging); if (!matchedStaticPath) { throw new Error(`[getStaticPaths] route pattern matched, but no matching static path found. (${pathname})`); } // This is written this way for performance; instead of spreading the props // which is O(n), create a new object that extends props. pageProps = Object.create(matchedStaticPath.props || Object.prototype); } else { pageProps = {}; } return [params, pageProps]; } /** use Vite to SSR */ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrOpts: SSROptions): Promise<string> { const { astroConfig, filePath, logging, mode, origin, pathname, route, routeCache, viteServer } = ssrOpts; // Handle dynamic routes let params: Params = {}; let pageProps: Props = {}; if (route && !route.pathname) { if (route.params.length) { const paramsMatch = route.pattern.exec(pathname); if (paramsMatch) { params = getParams(route.params)(paramsMatch); } } validateGetStaticPathsModule(mod); await ensureRouteCached(routeCache, route, mod); validateGetStaticPathsResult(routeCache[route.component], logging); const routePathParams: GetStaticPathsResult = routeCache[route.component]; const matchedStaticPath = routePathParams.find(({ params: _params }) => JSON.stringify(_params) === JSON.stringify(params)); if (!matchedStaticPath) { throw new Error(`[getStaticPaths] route pattern matched, but no matching static path found. (${pathname})`); } pageProps = { ...matchedStaticPath.props } || {}; } // Validate the page component before rendering the page const Component = await mod.default; if (!Component) throw new Error(`Expected an exported Astro component but received typeof ${typeof Component}`); if (!Component.isAstroComponentFactory) throw new Error(`Unable to SSR non-Astro component (${route?.component})`); const result = createResult({ astroConfig, origin, params, pathname, renderers }); // Resolves specifiers in the inline hydrated scripts, such as "@astrojs/renderer-preact/client.js" result.resolve = async (s: string) => { // The legacy build needs these to remain unresolved so that vite HTML // Can do the resolution. Without this condition the build output will be // broken in the legacy build. This can be removed once the legacy build is removed. if (astroConfig.buildOptions.experimentalStaticBuild) { const [, resolvedPath] = await viteServer.moduleGraph.resolveUrl(s); return resolvedPath; } else { return s; } }; let html = await renderPage(result, Component, pageProps, null); // inject tags const tags: vite.HtmlTagDescriptor[] = []; // dev only: inject Astro HMR client if (mode === 'development') { tags.push({ tag: 'script', attrs: { type: 'module' }, // HACK: inject the direct contents of our `astro/runtime/client/hmr.js` to ensure // `import.meta.hot` is properly handled by Vite children: await getHmrScript(), injectTo: 'head', }); } // inject CSS [...getStylesForURL(filePath, viteServer)].forEach((href) => { if (mode === 'development' && svelteStylesRE.test(href)) { tags.push({ tag: 'script', attrs: { type: 'module', src: href }, injectTo: 'head', }); } else { tags.push({ tag: 'link', attrs: { rel: 'stylesheet', href, 'data-astro-injected': true, }, injectTo: 'head', }); } }); // add injected tags html = injectTags(html, tags); // run transformIndexHtml() in dev to run Vite dev transformations if (mode === 'development' && !astroConfig.buildOptions.experimentalStaticBuild) { const relativeURL = filePath.href.replace(astroConfig.projectRoot.href, '/'); html = await viteServer.transformIndexHtml(relativeURL, html, pathname); } // inject <!doctype html> if missing (TODO: is a more robust check needed for comments, etc.?) if (!/<!doctype html/i.test(html)) { html = '<!DOCTYPE html>\n' + html; } return html; } let hmrScript: string; async function getHmrScript() { if (hmrScript) return hmrScript; const filePath = fileURLToPath(new URL('../../runtime/client/hmr.js', import.meta.url)); const content = await fs.promises.readFile(filePath); hmrScript = content.toString(); return hmrScript; } export async function ssr(ssrOpts: SSROptions): Promise<string> { try { const [renderers, mod] = await preload(ssrOpts); return await render(renderers, mod, ssrOpts); // note(drew): without "await", errors won’t get caught by errorHandler() } catch (e: unknown) { await errorHandler(e, { viteServer: ssrOpts.viteServer, filePath: ssrOpts.filePath }); throw e; } }
the_stack
import { join, normalize, resolve } from '@angular-devkit/core'; import type { NgtscProgram, ParsedConfiguration } from '@angular/compiler-cli'; import type { NgCompiler } from '@angular/compiler-cli/src/ngtsc/core'; import { externalizePath } from '@ngtools/webpack/src/ivy/paths'; import { createHash } from 'crypto'; import * as path from 'path'; import { Inject, Injectable, Injector } from 'static-injector'; import ts from 'typescript'; import type { CompilerOptions } from 'typescript'; import { Compilation, Compiler } from 'webpack'; import { LIBRARY_OUTPUT_ROOTDIR } from '../library'; import { MiniProgramCompilerService } from '../mini-program-compiler'; import { BuildPlatform } from '../platform/platform'; import { angularCompilerCliPromise } from '../util/load_esm'; import { OLD_BUILDER, PAGE_PATTERN_TOKEN, TS_CONFIG_TOKEN, TS_SYSTEM, WEBPACK_COMPILATION, WEBPACK_COMPILER, } from './token'; import type { PagePattern } from './type'; @Injectable() export class MiniProgramApplicationAnalysisService { private dependencyUseModule = new Map<string, string[]>(); private cleanDependencyFileCacheSet = new Set<string>(); builder!: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram; private ngTscProgram!: NgtscProgram; private tsProgram!: ts.Program; private ngCompiler!: NgCompiler; constructor( private injector: Injector, @Inject(WEBPACK_COMPILATION) private compilation: Compilation, @Inject(TS_SYSTEM) private system: ts.System, @Inject(WEBPACK_COMPILER) private compiler: Compiler, @Inject(TS_CONFIG_TOKEN) private tsConfig: string, @Inject(OLD_BUILDER) private oldBuilder: ts.EmitAndSemanticDiagnosticsBuilderProgram | undefined, @Inject(PAGE_PATTERN_TOKEN) private pagePatternList: PagePattern[], private buildPlatform: BuildPlatform ) {} async exportComponentBuildMetaMap() { const injector = Injector.create({ providers: [ { provide: MiniProgramCompilerService, useFactory: (injector: Injector, buildPlatform: BuildPlatform) => { return new MiniProgramCompilerService( this.ngTscProgram, injector, buildPlatform ); }, deps: [Injector, BuildPlatform], }, ], parent: this.injector, }); const miniProgramCompilerService = injector.get(MiniProgramCompilerService); miniProgramCompilerService.init(); const metaMap = await miniProgramCompilerService.exportComponentBuildMetaMap(); const selfMetaCollection = metaMap.otherMetaCollectionGroup['$self']; const selfTemplate: Record<string, string> = {}; if (selfMetaCollection) { const importSelfTemplatePath = `/self-template/self${this.buildPlatform.fileExtname.contentTemplate}`; const importSelfTemplate = `<import src="${importSelfTemplatePath}"/>`; metaMap.outputContent.forEach((value, key) => { value = `${importSelfTemplate}${value}`; metaMap.outputContent.set(key, value); }); metaMap.useComponentPath.forEach((value, key) => { value.libraryPath.push(...selfMetaCollection.libraryPath); value.localPath.push(...selfMetaCollection.localPath); }); selfTemplate[importSelfTemplatePath] = selfMetaCollection.templateList .map((item) => item.content) .join(''); delete metaMap.otherMetaCollectionGroup['$self']; } metaMap.useComponentPath.forEach((value, key) => { value.libraryPath = Array.from(new Set(value.libraryPath)); value.localPath = Array.from(new Set(value.localPath)); }); const styleMap = new Map<string, string[]>(); metaMap.style.forEach((value, key) => { const entryPattern = this.getComponentPagePattern(key); styleMap.set(entryPattern.outputFiles.style, value); }); const contentMap = new Map<string, string>(); metaMap.outputContent.forEach((value, key) => { const entryPattern = this.getComponentPagePattern(key); contentMap.set(entryPattern.outputFiles.content, value); }); metaMap.style = styleMap; const config = new Map< string, { usingComponents: { selector: string; path: string }[]; existConfig: string; } >(); metaMap.useComponentPath.forEach((value, key) => { const entryPattern = this.getComponentPagePattern(key); const list = [ ...value.libraryPath.map((item) => { item.path = resolve( normalize('/'), join(normalize(LIBRARY_OUTPUT_ROOTDIR), item.path) ); return item; }), ]; list.push( ...value.localPath.map((item) => ({ selector: item.selector, path: resolve( normalize('/'), normalize(this.getComponentPagePattern(item.path).outputFiles.path) ), className: item.className, })) ); config.set(entryPattern.outputFiles.config, { usingComponents: list, existConfig: entryPattern.inputFiles.config, }); }); for (const key in metaMap.otherMetaCollectionGroup) { if ( Object.prototype.hasOwnProperty.call( metaMap.otherMetaCollectionGroup, key ) ) { const element = metaMap.otherMetaCollectionGroup[key]; element.libraryPath.forEach((item) => { item.path = resolve( normalize('/'), join(normalize(LIBRARY_OUTPUT_ROOTDIR), item.path) ); }); element.localPath.forEach((item) => { item.path = resolve( normalize('/'), normalize(this.getComponentPagePattern(item.path).outputFiles.path) ); }); } } return { style: styleMap, outputContent: contentMap, config: config, otherMetaCollectionGroup: metaMap.otherMetaCollectionGroup, selfTemplate, }; } private initHost(config: ParsedConfiguration) { const host = ts.createIncrementalCompilerHost(config.options, this.system); this.augmentResolveModuleNames(host, config.options); this.addCleanDependency(host); return host; } private async initTscProgram() { const { readConfiguration, NgtscProgram } = await angularCompilerCliPromise; const config = readConfiguration(this.tsConfig, undefined); const host = this.initHost(config); this.ngTscProgram = new NgtscProgram( config.rootNames, config.options, host ); this.tsProgram = this.ngTscProgram.getTsProgram(); this.augmentProgramWithVersioning(this.tsProgram); if (this.compiler.watchMode) { this.builder = this.oldBuilder = ts.createEmitAndSemanticDiagnosticsBuilderProgram( this.tsProgram, host, this.oldBuilder ); } else { this.builder = ts.createAbstractBuilder(this.tsProgram, host); } this.ngCompiler = this.ngTscProgram.compiler; } private getComponentPagePattern(fileName: string) { const findList = [fileName]; let maybeEntryPath: PagePattern | undefined; while (findList.length) { const module = findList.pop(); const moduleList = this.dependencyUseModule.get(path.normalize(module!)); if (moduleList && moduleList.length) { findList.push(...moduleList); } else { maybeEntryPath = this.pagePatternList.find( (item) => path.normalize(item.src) === path.normalize(module!) ); if (maybeEntryPath) { break; } } } if (!maybeEntryPath) { throw new Error(`没有找到组件[${fileName}]对应的入口点`); } return maybeEntryPath; } private addCleanDependency(host: ts.CompilerHost) { const oldReadFile = host.readFile; const _this = this; host.readFile = function (fileName) { if (fileName.includes('node_modules')) { _this.cleanDependencyFileCacheSet.add(externalizePath(fileName)); } return oldReadFile.call(this, fileName); }; } private saveModuleDependency( filePath: string, moduleName: string, module: ts.ResolvedModule ) { if (!module) { throw new Error(`模块未被解析,文件名${filePath},模块名${moduleName}`); } const useList = this.dependencyUseModule.get(path.normalize(module.resolvedFileName)) || []; useList.push(filePath); this.dependencyUseModule.set( path.normalize(module.resolvedFileName), useList ); } private augmentResolveModuleNames( host: ts.CompilerHost, compilerOptions: CompilerOptions ) { const moduleResolutionCache = ts.createModuleResolutionCache( host.getCurrentDirectory(), host.getCanonicalFileName.bind(host), compilerOptions ); const oldResolveModuleNames = host.resolveModuleNames; if (oldResolveModuleNames) { // eslint-disable-next-line @typescript-eslint/no-explicit-any host.resolveModuleNames = (moduleNames: string[], ...args: any[]) => { return moduleNames.map((name) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const result = (oldResolveModuleNames! as any).call( host, [name], ...args ); this.saveModuleDependency(args[0], name, result); return result; }); }; } else { host.resolveModuleNames = ( moduleNames: string[], containingFile: string, _reusedNames: string[] | undefined, redirectedReference: ts.ResolvedProjectReference | undefined, options: ts.CompilerOptions ) => { return moduleNames.map((name) => { const result = ts.resolveModuleName( name, containingFile, options, host, moduleResolutionCache, redirectedReference ).resolvedModule; if (!containingFile.includes('node_modules')) { this.saveModuleDependency(containingFile, name, result!); } return result; }); }; } } async analyzeAsync() { await this.initTscProgram(); await this.ngCompiler.analyzeAsync(); } getBuilder() { return this.builder; } cleanDependencyFileCache() { this.cleanDependencyFileCacheSet.forEach((filePath) => { try { this.compiler.inputFileSystem.purge!(filePath); } catch (error) {} }); } private augmentProgramWithVersioning(program: ts.Program): void { const baseGetSourceFiles = program.getSourceFiles; program.getSourceFiles = function (...parameters) { const files: readonly (ts.SourceFile & { version?: string })[] = baseGetSourceFiles(...parameters); for (const file of files) { if (file.version === undefined) { file.version = createHash('sha256').update(file.text).digest('hex'); } } return files; }; } }
the_stack
import { camelCase } from "lodash-es"; import { hAccSum } from "../util"; import { i18n } from "@/i18n"; /** 伤害类型 */ export enum DamageType { /** 冲击 */ Impact = "Impact", /** 穿刺 */ Puncture = "Puncture", /** 切割 */ Slash = "Slash", /** 冰冻 */ Cold = "Cold", /** 电击 */ Electricity = "Electricity", /** 火焰 */ Heat = "Heat", /** 毒素 */ Toxin = "Toxin", /** 爆炸 */ Blast = "Blast", /** 腐蚀 */ Corrosive = "Corrosive", /** 毒气 */ Gas = "Gas", /** 磁力 */ Magnetic = "Magnetic", /** 辐射 */ Radiation = "Radiation", /** 病毒 */ Viral = "Viral", /** 真实 */ True = "True", /** 虚空 */ Void = "Void", } export interface DamageTypeData { id: DamageType; name: string; type: "Physical" | "Elemental" | "Combined" | "Standalone"; desc: string; // ["肉体", "复制肉体", "化石", "感染", "感染肉体", "感染肌腱", "机械", "机器", "物件", "护盾", "原型护盾", "铁制装甲", "合金装甲"], dmgMul: number[]; combinedBy?: DamageType[]; } const _damageTypeDatabase = { Impact: ["Physical", null, [-0.25, -0.25, 0, 0, 0, 0, 0.25, 0, 0, 0.5, 0.25, 0, 0]], Puncture: ["Physical", null, [0, 0, 0, 0, 0, 0.25, 0, 0.25, 0, -0.2, -0.5, 0.5, 0.15]], Slash: ["Physical", null, [0.25, 0.25, 0.15, 0.25, 0.5, 0, 0, -0.25, 0, 0, 0, -0.15, -0.5]], Cold: ["Elemental", null, [0, 0, -0.25, 0, -0.5, 0.25, 0, 0, 0, 0.5, 0, 0, 0.25]], Electricity: ["Elemental", null, [0, 0, 0, 0, 0, 0, 0.5, 0.5, 0, 0, 0, 0, -0.5]], Heat: ["Elemental", null, [0, 0.25, 0, 0.25, 0.5, 0, 0, 0, 0, 0, -0.5, 0, 0]], Toxin: ["Elemental", null, [0.5, 0, -0.5, 0, 0, 0, -0.25, -0.25, 0, NaN, NaN, 0, 0]], Blast: ["Combined", "Cold+Heat", [0, 0, 0.5, 0, 0, -0.5, 0.75, 0, 0, 0, 0, -0.25, 0]], Corrosive: ["Combined", "Electricity+Toxin", [0, 0, 0.75, 0, 0, 0, 0, 0, 0, 0, -0.5, 0.75, 0]], Gas: ["Combined", "Heat+Toxin", [-0.25, -0.5, 0, 0.75, 0.5, 0, 0, 0, 0, 0, 0, 0, 0]], Magnetic: ["Combined", "Cold+Electricity", [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.75, 0.75, 0, -0.5]], Radiation: ["Combined", "Electricity+Heat", [0, 0, -0.75, -0.5, 0, 0.5, 0, 0.25, 0, -0.25, 0, 0, 0.75]], Viral: ["Combined", "Cold+Toxin", [0.5, 0.75, 0, -0.5, 0, 0, -0.25, 0, 0, 0, 0, 0, 0]], True: ["Standalone", null, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NaN, NaN]], Void: ["Standalone", null, [0, -0.5, -0.5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], } as { [key: string]: [string, string, number[]] }; /** * 伤害类型数据 */ export const DamageTypeDatabase: DamageTypeData[] = Object.keys(_damageTypeDatabase).map(k => { let v = _damageTypeDatabase[k]; let o = { id: k, type: v[0].trim(), dmgMul: v[2], } as DamageTypeData; if (v[1]) o.combinedBy = v[1].trim().split("+") as DamageType[]; return o; }, {}); /** 复合元素映射表 */ export const CombElementMap: { [key: string]: DamageType } = { "Cold+Heat": DamageType.Blast, "Electricity+Toxin": DamageType.Corrosive, "Heat+Toxin": DamageType.Gas, "Cold+Electricity": DamageType.Magnetic, "Electricity+Heat": DamageType.Radiation, "Cold+Toxin": DamageType.Viral, }; export enum FleshType { /** 肉体 */ Flesh, /** 复制肉体 */ ClonedFlesh, /** 化石 */ Fossilized, /** 感染 */ Infested, /** 感染肉体 */ InfestedFlesh, /** 感染肌腱 */ InfestedSinew, /** 机械 */ Machinery, /** 机器 */ Robotic, /** 物件 */ Object, /** 护盾 */ Shield, /** 原型护盾 */ ProtoShield, /** 铁制装甲 */ FerriteArmor, /** 合金装甲 */ AlloyArmor, } /** 敌人派系 */ export enum EnemyFaction { Tenno, Grineer, Corpus, Infested, Orokin, Sentient, Wild, } export interface IEnemyData { id: string; faction: EnemyFaction; baseLevel: number; baseHealth: number; baseShield: number; baseArmor: number; fleshType: FleshType; shieldType: FleshType; armorType: FleshType; resistence: number; ignoreProc: number; // 1免疫DoT 2免疫所有 3为夜灵 影响伤害算法 headMul: number; } export class EnemyData implements IEnemyData { id: string; get name() { const key = `enemy.names.${camelCase(this.id)}`; return i18n.te(key) ? i18n.t(key) : this.id; } faction: EnemyFaction; baseLevel: number; baseHealth: number; baseShield: number; baseArmor: number; fleshType: FleshType; shieldType: FleshType; armorType: FleshType; resistence: number; ignoreProc: number; // 1免疫DoT 2免疫所有 3为夜灵 影响伤害算法 headMul: number; // 头部倍率 constructor({ id, faction, baseLevel, baseHealth, baseShield, baseArmor, fleshType, shieldType, armorType, resistence, ignoreProc, headMul }: IEnemyData) { [this.id, this.faction] = [id, faction]; [this.baseLevel, this.baseHealth, this.baseShield, this.baseArmor] = [baseLevel, baseHealth, baseShield, baseArmor]; [this.fleshType, this.shieldType, this.armorType] = [fleshType, shieldType, armorType]; this.resistence = resistence; this.ignoreProc = ignoreProc; this.headMul = headMul; } } /** 敌人列表 [id, faction, baseLevel, baseHealth, baseShield, baseArmor, fleshType, shieldType, armorType, resistence, ignoreProc, headMul] */ const _enemyList = [ ["Wolf of Saturn Six", 5, , 20000, , 2500, 12, , 1, 0.6, 3], ["Eidolon Teralyst", 5, , 15000, , 200, 7, , 1, 0.6, 3, 1], ["Eidolon Gantulyst", 5, , 15000, , 200, 7, , 1, 0.6, 3, 1], ["Eidolon Hydrolyst", 5, , 15000, , 200, 7, , 1, 0.6, 3, 1], ["Teralyst Synovia", 5, , 2500, , 200, 7, , 1, 0.6, 3, 1], ["Profit-Taker Orb", 2, 50, 7000, 30000, 150, 7, , 1, , 2, 1], ["Condor Dropship", 2, , 1000, , 100, 7, , , , 1], ["Tusk Firbolg", 1, , 8000, , 600, 7, , 1, , 1], ["Tusk Bolkor", 1, , 10000, , 600, 7, , 1, , 1], ["Bailiff", 1, , 600, , 500, 1], ["Butcher", 1, , 50, , 5, 1], ["Flameblade", 1, , 50, , 5, 1], ["Fire Prosecutor", 1, , 1500, , 5, 1], ["Powerfist", 1, , 100, , 5, 1], ["Scorpion", 1, , 150, , 150, 1], ["Shield Lancer", 1, , 100, , 5, 1], ["Ballista", 1, , 100, , 100, 1], ["Eviscerator", 1, , 150, , 200, 1], ["Hellion", 1, , 100, , 100, 1], ["Lancer", 1, , 100, , 100, 1], ["Elite Lancer", 1, 15, 150, , 200, 1, , 1], ["Scorch", 1, 1, 120, , 100, 1], ["Seeker", 1, 1, 100, , 200, 1], ["Trooper", 1, 1, 120, , 150, 1], ["Bombard", 1, 1, 300, , 500, 1, , 1], ["Commander", 1, 3, 500, , 95, 1, , 1], ["Drahk Master", 1, 12, 500, , 200, 1], ["Heavy Gunner", 1, 8, 300, , 500, 1], ["Hyekka Master", 1, 12, 650, , 200, 1], ["Manic", 1, 1, 350, , 25, 1], ["Napalm", 1, 6, 600, , 500, 1, , 1], ["Nox", 1, 1, 250, , 350, 1, , 1, 0.9], ["Ghoul Auger", 1, 1, 400, , 200, 1], ["Ghoul Devourer", 1, 1, 600, , 250, 1], ["Ghoul Expired", 1, 1, 300, , 150, 1], ["Ghoul Rictus", 1, 1, 400, , 200, 1], ["Grineer Warden", 1, 1, 600, , 500, 1], ["Sensor Regulator", 1, 1, 100, , 300, 6], ["Human of Anyo Corp", 2, 1, 150, 100, 200, , , 1], ["Robotic of Anyo Corp", 2, 1, 150, 100, 200, 7, , 1], ["Crewman", 2, 1, 60, 150], ["Detron Crewman", 2, 1, 60, 150], ["Elite Crewman", 2, 15, 100, 200], ["Nullifier Crewman", 2, 1, 60, 150, , , 1], ["Prod Crewman", 2, 1, 100, 50], ["Sniper Crewman", 2, 15, 60, 150, , , 1], ["Corpus Tech", 2, 15, 700, 250, , , 1], ["Comba", 2, 15, 1100, 400], ["Scrambus", 2, 15, 1100, 400], ["Denial Bursa", 2, 1, 1200, 700, 200, 7, , 1], ["Drover Bursa", 2, 1, 1200, 700, 200, 7, , 1], ["Isolator Bursa", 2, 1, 1200, 700, 200, 7, , 1], ["MOA", 2, 1, 60, 150, , 7], ["Anti MOA", 2, 5, 50, 500, , 7], ["Fusion MOA", 2, 10, 250, 250, , 7], ["Railgun MOA", 2, 1, 60, 150, , 7], ["Shockwave MOA", 2, 15, 60, 150, , 7], ["Drone", 2, 1, 250, 75, , 7], ["Leech Osprey", 2, 1, 100, 50, , 7], ["Lynx Osprey", 2, 1, 35, 50, , 7], ["Mine Osprey", 2, 10, 100, 50, , 7], ["Oxium Osprey", 2, 1, 750, 150, 40, 7], ["Scavanger Osprey", 2, 1, 100, 50, , 7], ["Sapping Osprey", 2, 1, 200, 50, , 7], ["Shield Osprey", 2, 1, 35, 50, , 7], ["Charger", 3, 1, 80, , , 3], ["Leaper", 3, 1, 100, , , 3], ["Runner", 3, 1, 100, , , 3], ["Volatile Runner", 3, 1, 80, , , 3], ["Crawler", 3, 1, 50, , , 4], ["Electric Crawler", 3, 1, 50, , , 4], ["Lobber Crawler", 3, 1, 50, , , 4], ["Nauseous Crawler", 3, 1, 50, , , 4], ["Toxic Crawler", 3, 1, 50, , , 4], ["Mutalist Osprey", 3, 1, 200, , , 4], ["Swarm Mutalist MOA", 3, 12, 350, , , 2], ["Tar-Mutalist MOA", 3, 12, 350, , , 2], ["Ancient Disrupter", 3, 1, 400, , , 2], ["Ancient Healer", 3, 1, 400, , , 2], ["Boiler", 3, 12, 1200, , , 2], ["Brood Mother", 3, 12, 700, , , 2], ["Toxic Ancient", 3, 1, 400, , , 2], // ["Hemocyte", 3, 1, 2200, , 175, 2, , , , 3], ["Corrupted Ancient", 4, 1, 400, , , 2], ["Corrupted Butcher", 4, 1, 100, , 5, 1], ["Corrupted Bombard", 4, 4, 300, , 500, 1, , 1], ["Corrupted Heavy Gunner", 4, 8, 700, , 500, 1], ["Corrupted Lancer", 4, 1, 60, , 200, 1, , 1], ["Orokin Drone", 4, 1, 35, 50, , 7], ["Corrupted Crewman", 4, 1, 60, 150], ["Corrupted MOA", 4, 1, 250, 250, , 7], ["Corrupted Nullifier", 4, 15, 60, 150, , , 1], ] as [string, number, number, number, number, number, number, number, number, number, number, number][]; /** 敌人列表 */ export const EnemyList = _enemyList.map( v => new EnemyData({ id: v[0], faction: v[1], baseLevel: v[2] || 1, baseHealth: v[3] || 0, baseShield: v[4] || 0, baseArmor: v[5] || 0, fleshType: v[6] || 0, shieldType: (v[7] || 0) + 9, armorType: (v[8] || 0) + 11, resistence: v[9] || 0, ignoreProc: v[10] || 0, headMul: v[11] || 2, }) ); /** 伤害模型序列 [id, faction, flesh, shield, armor, resistence, ignoreProc] */ type DamageModelDataArray = [string, number, number, number, number, number, number]; const _damageModelList = [ // 伤害模型列表 ["Eidolon", 5, 6, , 1, 0.6, 3], ["Eidolon Unarmored", 5, 6, , , 0.6, 3], ["Eidolon Shield", 5, 10, , , 0.6, 4], ["Orb", 5, 6, , 1, 0, 2], ["Grineer", 1, 1, , 0, 0, 0], ["Grineer Unarmored", 1, 1, , , 0, 0], ["Grineer Elite", 1, 1, , 1, 0, 0], ["Corpus", 2, 0, , , 0, 0], ["Corpus Robotic", 2, 1, , , 0, 0], ["Corpus Shield", 2, , 0, , 0, 0], ["Corpus Elite", 2, 0, , 1, 0, 0], ["Corpus Elite Shield", 2, , 1, , 0, 0], ["Infested", 3, 3, , , 0, 0], ["Infested Flesh", 3, 4, , , 0, 0], ["Infested Elite", 3, 2, , , 0, 0], ["Infested Jordas Golem", 3, 5, , 0, 0, 0], ["Tenno", 0, 0, , 0, 0, 0], ] as DamageModelDataArray[]; export interface IDamageModelData { /** 模型ID */ id: string; /** 模型本地化名称 */ name: string; /** 派系 */ faction?: EnemyFaction; /** 血肉类型 */ fleshType?: FleshType; /** 护盾类型 */ shieldType?: FleshType; /** 护甲模型 */ armorType?: FleshType; /** 伤害抗性 */ resistence?: number; /** 计算模式 夜灵=3 */ ignoreProc?: number; } /** 伤害模型数据 */ export class DamageModelData implements IDamageModelData { id: string; get name() { const key = `enemy.models.${camelCase(this.id)}`; return i18n.te(key) ? i18n.t(key) : this.id; } faction?: EnemyFaction; fleshType?: FleshType; shieldType?: FleshType; armorType?: FleshType; resistence?: number; ignoreProc?: number; constructor(data: IDamageModelData | DamageModelDataArray) { if (Array.isArray(data)) { const [id, faction, fleshType, shieldType, armorType, resistence, ignoreProc] = data; this.id = id; this.faction = faction; this.fleshType = fleshType || 0; if (typeof shieldType === "number") this.shieldType = shieldType + 9; if (typeof armorType === "number") this.armorType = armorType + 11; this.resistence = resistence; this.ignoreProc = ignoreProc; } else { const { id, faction, fleshType, shieldType, armorType, resistence, ignoreProc } = data; this.id = id; this.faction = faction; this.fleshType = fleshType || 0; this.shieldType = shieldType; this.armorType = armorType; this.resistence = resistence; this.ignoreProc = ignoreProc; } } } export const DamageModelList = _damageModelList.map(v => new DamageModelData(v)); /** 简单伤害模型 */ export class SimpleDamageModel extends DamageModelData { currentArmor: number = 0; constructor(data: DamageModelData, currentArmor: number) { super(data); this.currentArmor = currentArmor; } /** * 根据克制修正系数计算伤害模型 * * @param {[string, number][]} dmgs * @param critChance 暴击几率 * @param threshold 阈值 * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamage(dmgs: [string, number][], critChance: number = 0, threshold = 300) { if (this.ignoreProc > 3) return this.mapEidolonDmg( dmgs.filter(v => v[0] === "Void"), critChance, threshold > 300 ? 300 : threshold ); if (this.ignoreProc > 2) return this.mapEidolonDmg(dmgs, critChance, threshold > 300 ? 300 : threshold); else return this.mapDamageNormal(dmgs); } /** * 根据克制修正系数计算触发伤害模型 * * @param {[string, number][]} dmgs * @param critChance 暴击几率 * @param threshold 阈值 * @returns 映射后的伤害数值 * @memberof Enemy */ mapProcDamage(dmgs: [string, number][]) { if (this.ignoreProc > 1) return dmgs.map(([vn, vv]) => [vn, 0] as [string, number]); else return this.mapDamageNormal(dmgs, true); } /** * 根据克制修正系数计算伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageNormal(dmgs: [string, number][], dot = false) { if (typeof this.shieldType === "number") return this.mapDamageShield(dmgs, dot); if (typeof this.armorType === "number") return this.mapDamageArmor(dmgs, dot); if (typeof this.fleshType === "number") return this.mapDamageHealth(dmgs, dot); return dmgs; } /** * 根据克制修正系数计算护盾伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageShield(dmgs: [string, number][], dot = false) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType((dot && id) as DamageType); if (!dtype) return [id, dmg]; let SM = dtype.dmgMul[this.shieldType]; // 毒素伤害直接穿透护盾对血量进行打击, 不计算对护盾的伤害 let DM = isNaN(SM) ? 0 : 1 + SM; return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 根据克制修正系数计算护甲伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageArmor(dmgs: [string, number][], dot = false) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType(id as DamageType); if (!dtype) return [id, dmg]; let HM = dtype.dmgMul[this.fleshType]; let AM = dtype.dmgMul[this.armorType]; let DM = ((1 + HM) * (1 + AM)) / (1 + (this.currentArmor * (1 - AM)) / 300); return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 根据克制修正系数计算血肉伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageHealth(dmgs: [string, number][], dot = false) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType(id as DamageType); if (!dtype) return [id, dmg]; let HM = dtype.dmgMul[this.fleshType]; let DM = 1 + HM; return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 应用伤害(夜灵) * * @param {[string, number][]} dmgs 伤害表 * @param critChance 暴击率 * @param threshold 阈值 * @returns 映射后的伤害数值 * @memberof Enemy */ mapEidolonDmg(dmgs: [string, number][], critChance: number, threshold = 300) { let mapped = this.mapDamageNormal(dmgs); let totalDmg = mapped.reduce((a, b) => a + b[1], 0); let eidolonCritDmg = totalDmg + totalDmg * (critChance > 1 ? 1 : critChance); // 目标夜灵 无视护盾 let eidolonDmg = eidolonCritDmg > threshold ? threshold + eidolonCritDmg / 10 : eidolonCritDmg; return mapped.map(([vn, vv]) => [vn, (vv / totalDmg) * eidolonDmg] as [string, number]); } } export class Procs { // [伤害, 剩余时间] Slash: [number, number][] = []; Heat: [number, number][] = []; Toxin: [number, number][] = []; Gas: [number, number][] = []; Electricity: [number, number][] = []; Viral: number = 0; HeatProc: number = 0; /** * 加入触发伤害 * * @param {DamageType} dtype 伤害类型 * @param {number} dmg 伤害值 * @param {number} durationMul 持续时间倍率 * @memberof Procs */ push(dtype: DamageType, dmg: number, durationMul: number) { switch (dtype) { // 切割伤害: https://warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0/%E5%88%87%E5%89%B2%E4%BC%A4%E5%AE%B3 case "Slash": this.Slash.push([dmg, ~~(6 * durationMul)]); break; // 毒素伤害: https://warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0/%E6%AF%92%E7%B4%A0%E4%BC%A4%E5%AE%B3 case "Toxin": this.Toxin.push([dmg, ~~(6 * durationMul)]); break; // 毒气伤害: https://warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0/%E6%AF%92%E6%B0%94%E4%BC%A4%E5%AE%B3 case "Gas": this.Gas.push([dmg, ~~(6 * durationMul)]); break; // 火焰伤害: https://warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0/%E7%81%AB%E7%84%B0%E4%BC%A4%E5%AE%B3 case "Heat": this.Heat.push([dmg, ~~(6 * durationMul)]); break; // 电击伤害: https://warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0/%E7%94%B5%E5%87%BB%E4%BC%A4%E5%AE%B3 case "Electricity": this.Electricity.push([dmg, ~~(6 * durationMul)]); break; } } /** * 结算触发伤害 * * @param {number} procDamageMul 触发伤害加成 * @returns {[DamageType, number][]} * @memberof Procs */ pop(procDamageMul: number): [DamageType, number][] { // 求和 然后去掉持续时间到0的 let totalSlash = this.Slash.reduce((a, b) => a + b[0], 0); this.Slash = this.Slash.filter(v => --v[1] > 0) as [number, number][]; let totalToxin = this.Toxin.reduce((a, b) => a + b[0], 0); this.Toxin = this.Toxin.filter(v => --v[1] > 0) as [number, number][]; let totalGas = this.Gas.reduce((a, b) => a + b[0], 0); this.Gas = this.Gas.filter(v => --v[1] > 0) as [number, number][]; let totalHeat = this.Heat.reduce((a, b) => a + b[0], 0); this.Heat = this.Heat.filter(v => --v[1] > 0) as [number, number][]; let totalElectricity = this.Electricity.reduce((a, b) => a + b[0], 0); this.Electricity = this.Electricity.filter(v => --v[1] > 0) as [number, number][]; let dmgs = []; if (totalSlash > 0) dmgs.push([DamageType.True, procDamageMul * totalSlash]); if (totalToxin > 0) dmgs.push([DamageType.Toxin, procDamageMul * totalToxin]); if (totalGas > 0) dmgs.push([DamageType.Gas, procDamageMul * totalGas]); if (totalHeat > 0) dmgs.push([DamageType.Heat, procDamageMul * totalHeat]); if (totalElectricity > 0) dmgs.push([DamageType.Electricity, procDamageMul * totalElectricity]); return dmgs; } } export interface EnemyTimelineState { ms: number; ammo: number; health: number; shield: number; armor: number; isDoT: boolean; } function trans(start: number, end: number, curr_lvl: number) { return Math.min(1, (Math.max(curr_lvl, start) - start) / (end - start)); } export class Enemy extends EnemyData { // === 静态属性 === get factionName() { return EnemyFaction[this.faction]; } get fleshTypeId() { return FleshType[this.fleshType]; } get shieldTypeId() { return FleshType[this.shieldType]; } get armorTypeId() { return FleshType[this.armorType]; } get fleshTypeName() { return i18n.t("enemy.fleshType")[this.fleshType]; } get shieldTypeName() { return i18n.t("enemy.shieldType")[this.shieldType]; } get armorTypeName() { return i18n.t("enemy.armorType")[this.armorType]; } get resistenceText() { return this.resistence && (this.resistence * 100).toFixed() + "%"; } // === 动态属性 === private _level: number; public get level(): number { return this._level; } public set level(value: number) { this._level = value; this.reset(); } currentHealth: number = 0; currentShield: number = 0; currentArmor: number = 0; currentProcs: Procs; amrorReduce: number = 0; // === 计算属性 === /** * 当前等级基础生命 * 资料: http: //warframe.huijiwiki.com/wiki/%E6%95%8C%E6%96%B9%E7%AD%89%E7%BA%A7%E5%8F%98%E5%8C%96%E8%A7%84%E5%BE%8B * = 基础生命 × ( 1 + ( 当前等级 − 基础等级 )^2 × 0.015 ) */ get health() { const high = 1 + (this.level - this.baseLevel) ** 0.5 * 10.75; const low = 1 + (this.level - this.baseLevel) ** 2 * 0.015; const ratio = trans(70 + this.baseLevel, 85, this.level); return this.baseHealth * ((1 - ratio) * low + ratio * high); } /** * 当前等级基础护盾 * = 基础护盾 × ( 1 + ( 当前等级 − 基础等级 )^2 × 0.0075 ) */ get shield() { const high = 1 + (this.level - this.baseLevel) ** 0.75 * 1.6; const low = 1 + (this.level - this.baseLevel) ** 2 * 0.0075; const ratio = trans(70 + this.baseLevel, 85, this.level); return this.baseShield * ((1 - ratio) * low + ratio * high); } /** * 当前等级基础护甲 * = 基础护甲 × ( 1 + ( 当前等级 − 基础等级 )^1.75 × 0.005 ) */ get armor() { const high = 1 + (this.level - this.baseLevel) ** 0.75 * 0.4; const low = 1 + (this.level - this.baseLevel) ** 1.75 * 0.005; const ratio = trans(70 + this.baseLevel, 85, this.level); return this.baseArmor * ((1 - ratio) * low + ratio * high); } /** * 重置当前血量护盾护甲 */ reset() { this.currentHealth = this.health; this.currentShield = this.shield; this.currentArmor = this.armor * (this.amrorReduce > 1 ? 0 : 1 - this.amrorReduce); this.currentProcs = new Procs(); this.stateHistory = []; this.tickCount = 0; this.pushState(false); } /** * 创建一个敌人对象 * @param {EnemyData} obj 参数对象 * @param level 等级 */ constructor(data: IEnemyData, level: number) { super(data); this.level = level; } get data() { return { id: this.id, name: this.name, faction: this.faction, baseLevel: this.baseLevel, baseHealth: this.baseHealth, baseShield: this.baseShield, baseArmor: this.baseArmor, fleshType: this.fleshType, shieldType: this.shieldType, armorType: this.armorType, resistence: this.resistence, ignoreProc: this.ignoreProc, headMul: this.headMul, }; } /** * 根据克制修正系数计算伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamage(dmgs: [string, number][]) { if (this.currentShield > 1) return this.mapDamageShield(dmgs); if (this.currentArmor > 1) return this.mapDamageArmor(dmgs); return this.mapDamageHealth(dmgs); } /** * 根据克制修正系数计算血肉伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageHealth(dmgs: [string, number][]) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType(id as DamageType); if (!dtype) return [id, dmg]; let HM = dtype.dmgMul[this.fleshType]; let DM = 1 + HM; return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 根据克制修正系数计算护甲伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageArmor(dmgs: [string, number][]) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType(id as DamageType); if (!dtype) return [id, dmg]; let HM = dtype.dmgMul[this.fleshType]; if (isNaN(HM)) return [id, 0]; let AM = dtype.dmgMul[this.armorType]; if (isNaN(AM)) AM = 0; let DM = ((1 + HM) * (1 + AM)) / (1 + (this.currentArmor * (1 - AM)) / 300); console.log(id, dmg * DM * (1 - this.resistence)) return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 根据克制修正系数计算护盾伤害模型 * * @param {[string, number][]} dmgs * @returns 映射后的伤害数值 * @memberof Enemy */ mapDamageShield(dmgs: [string, number][]) { return dmgs.map(([id, dmg]) => { let dtype = Damage2_0.getDamageType(id as DamageType); if (!dtype) return [id, dmg]; let SM = dtype.dmgMul[this.shieldType]; // 毒素伤害直接穿透护盾对血量进行打击, 不计算对护盾的伤害 let DM = isNaN(SM) ? 0 : 1 + SM; return [id, dmg * DM * (1 - this.resistence)]; }) as [string, number][]; } /** * 应用伤害 * * @param {[string, number][]} dmgs 伤害表 * @returns * @memberof Enemy */ applyDmg(dmgs: [string, number][]) { let mapped = this.mapDamage(dmgs); let totalDmg = mapped.reduce((a, b) => a + b[1], 0); for (let i = 0; i < mapped.length; i++) { let [id, dmg] = mapped[i]; // 真实伤害 if (id === DamageType.True) { this.currentHealth -= dmg; } else { // 毒素穿透护盾 if (this.currentShield > 0) { if (id === DamageType.Toxin) { let dtype = Damage2_0.getDamageType(id as DamageType); let HM = dtype.dmgMul[this.fleshType]; let AM = dtype.dmgMul[this.armorType]; let DM = ((1 + HM) * (1 + AM)) / (1 + (this.currentArmor * (1 - AM)) / 300); this.currentHealth -= dmgs[i][1] * DM; } else { this.currentShield -= dmg; } } else { this.currentHealth -= dmg; } } } // 如果伤害穿透护盾之后还有剩 按剩余比例再计算一次 if (this.currentShield < 0) { let remaingDmgRate = 1 - this.currentShield / totalDmg; this.currentShield = 0; this.applyDmg(dmgs.map(([id, dmg]) => [id, dmg * remaingDmgRate] as [string, number])); } return this; } /** * 应用伤害(夜灵) * * @param {[string, number][]} dmgs 伤害表 * @param {number} critChance 暴击率 * @param {number} [threshold=300] 阈值 * @memberof Enemy */ applyEidolonDmg(dmgs: [string, number][], critChance: number, threshold = 300) { let mapped = this.mapDamage(dmgs); let totalDmg = mapped.reduce((a, b) => a + b[1], 0); let eidolonCritDmg = totalDmg + totalDmg * (critChance > 1 ? 1 : critChance); // 目标夜灵 无视护盾 let eidolonDmg = eidolonCritDmg > threshold ? threshold + eidolonCritDmg / 10 : eidolonCritDmg; this.currentHealth -= eidolonDmg; return this; } /** * 应用DoT伤害 * * @param {[string, number][]} dmgs DoT单跳伤害列表 * @param {number} durationMul DoT伤害 * @memberof Enemy */ applyDoTDmg(dmgs: [string, number][], durationMul: number = 1, procDamageMul: number = 1) { let immediateDamages = dmgs.map(([vn, vv]) => { switch (vn) { // 切割伤害: https://warframe.huijiwiki.com/wiki/Damage_2.0/Slash_Damage // 无立即伤害 case "Slash": this.currentProcs.push(DamageType.Slash, vv * procDamageMul, durationMul); return [DamageType.True, vv]; // 毒素伤害: https://warframe.huijiwiki.com/wiki/Damage_2.0/Toxin_Damage // 无立即伤害 case "Toxin": this.currentProcs.push(DamageType.Toxin, vv * procDamageMul, durationMul); return [DamageType.Toxin, vv]; // 毒气伤害: https://warframe.huijiwiki.com/wiki/Damage_2.0/Gas_Damage // 无立即伤害 case "Gas": this.currentProcs.push(DamageType.Gas, vv * procDamageMul, durationMul); return [DamageType.Gas, vv]; // 火焰伤害: https://warframe.huijiwiki.com/wiki/Damage_2.0/Heat_Damage case "Heat": this.currentProcs.push(DamageType.Heat, vv * procDamageMul, durationMul); return [DamageType.Heat, vv]; // 电击伤害: https://warframe.huijiwiki.com/wiki/Damage_2.0/Electricity_Damage case "Electricity": this.currentProcs.push(DamageType.Electricity, vv * procDamageMul, durationMul); return [DamageType.Electricity, vv]; } }) as [DamageType, number][]; return this.applyDmg(immediateDamages); } /** * 计算单发射击后怪物血量剩余情况(连续) * * @param {[string, number][]} dmgs 伤害表 * @param {[string, number][]} procChanceMap 触发几率表(真实触发) * @param {[string, number][]} dotDamageMap 触发伤害表(DoT) * @param {number} [pellets=1] 弹片数 * @param {number} [durationMul=1] * @param {number} [durationMul=1] * @param {number} [critChance=0] * @param {number} [threshold=300] * @param {number} [procDamageMul=1] * @param {number} [ammo=1] * @memberof Enemy */ applyHit( dmgs: [string, number][], procChanceMap: [string, number][], dotDamageMap: [string, number][], pellets = 1, durationMul = 1, critChance = 0, threshold = 300, procDamageMul = 1, ammo = 1 ) { let procChance = procChanceMap.reduce((a, [id, val]) => ((a[id] = val), a), {}); // [0.每个弹片单独计算] let bls = pellets; while (bls > 0) { // [0.将伤害平分给每个弹片 不满整个的按比例计算] let bh = bls >= 1 ? 1 : bls; // 夜灵算法 https://warframe.huijiwiki.com/wiki/%E5%8D%9A%E5%AE%A2:%E5%A4%9C%E7%81%B5%E5%85%86%E5%8A%9B%E4%BD%BF%E4%BC%A4%E5%AE%B3%E6%9C%BA%E5%88%B6 if (this.ignoreProc > 2) { this.applyEidolonDmg( dmgs.map(([vn, vv]) => [vn, (vv * bh) / pellets] as [string, number]), critChance, threshold * this.resistence * bh ); // 不足一个的乘以阈值 } else if (this.ignoreProc === 2) { this.applyDmg(dmgs.map(([vn, vv]) => [vn, (vv * bh) / pellets] as [string, number])); } else { // [1.按当前病毒触发比例减少血上限 / 火减甲] let currentViral = this.currentProcs.Viral; let currentHeat = this.currentProcs.HeatProc; this.currentHealth *= 1 - 0.5 * currentViral; this.currentArmor *= 1 - 0.5 * currentHeat; // [2.直接伤害] this.applyDmg(dmgs.map(([vn, vv]) => [vn, (vv * bh) / pellets] as [string, number])); // [3.腐蚀扒皮] 计算腐蚀触发(连续) if (procChance[DamageType.Corrosive] > 0) { this.currentArmor *= 0.75 ** (procChance[DamageType.Corrosive] * bh); } // [4.1.磁力少盾] if (procChance[DamageType.Magnetic] > 0) { this.currentShield *= 0.25 ** (procChance[DamageType.Magnetic] * bh); } // [4.2.病毒少血] if (procChance[DamageType.Viral] > 0 && this.currentProcs.Viral < 1) { // 将病毒触发连续化计算增伤 let newViral = currentViral + procChance[DamageType.Viral] * bh; this.currentProcs.Viral = newViral > 1 ? 1 : newViral; } // [4.3.火减甲] if (procChance[DamageType.Heat] > 0 && this.currentProcs.HeatProc < 1) { // 将触发连续化计算增伤 let newHeat = currentHeat + procChance[DamageType.Heat] * bh; this.currentProcs.HeatProc = newHeat > 1 ? 1 : newHeat; } // [5.DoT伤害] if (this.ignoreProc === 0) this.applyDoTDmg( dotDamageMap.map(([vn, vv]) => [vn, (vv * bh) / pellets] as [string, number]), durationMul, procDamageMul ); // [6.将病毒下降的血量恢复 / 火减甲] this.currentHealth /= 1 - 0.5 * currentViral; this.currentArmor /= 1 - 0.5 * currentHeat; } bls = hAccSum(bls, -1); } this.pushState(false, ammo); } // === 时间线系统 === TICKCYCLE = 60; tickCount = 0; stateHistory: EnemyTimelineState[] = []; /** * 将DoT计时器进入下一秒 */ nextSecond(procDamageMul: number) { let dotDmgs = this.currentProcs.pop(procDamageMul); this.applyDmg(dotDmgs); this.pushState(true); } /** * 记录历史信息 * * @memberof Enemy */ pushState(isDoT = false, ammo = 0) { this.stateHistory.push({ ms: Math.ceil((this.tickCount * 1e3) / this.TICKCYCLE), ammo, health: this.currentHealth, shield: this.currentShield, armor: this.currentArmor, isDoT, }); } } /** * 伤害2.0计算 * http: //warframe.huijiwiki.com/wiki/%E4%BC%A4%E5%AE%B3_2.0 */ export class Damage2_0 { private dtypeDict: Map<DamageType, DamageTypeData>; protected static instance = new Damage2_0(); constructor() { this.dtypeDict = new Map(DamageTypeDatabase.map(v => [v.id, v] as [DamageType, DamageTypeData])); } static getDamageType(id: DamageType) { return this.instance.dtypeDict.get(id); } }
the_stack
import { IDataOptions, IDataSet } from '../../src/base/engine'; import { pivot_dataset } from '../base/datasource.spec'; import { PivotView } from '../../src/pivotview/base/pivotview'; import { createElement, remove, extend } from '@syncfusion/ej2-base'; import { GroupingBar } from '../../src/common/grouping-bar/grouping-bar'; import { PivotCellSelectedEventArgs } from '../../src/common/base/interface'; import { BeforeCopyEventArgs, RowSelectingEventArgs, RowSelectEventArgs, RowDeselectEventArgs, CellSelectingEventArgs, CellSelectEventArgs, CellDeselectEventArgs, QueryCellInfoEventArgs, HeaderCellInfoEventArgs, Grid, ColumnDragEventArgs, ResizeArgs } from '@syncfusion/ej2-grids'; import { ExcelExport, PDFExport } from '../../src/pivotview/actions'; import { profile, inMB, getMemoryProfile } from '../common.spec'; describe('Data Grid Features module - ', () => { beforeAll(() => { 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) return; } }); describe(' - dataSource ejGrid features combo - ', () => { let pivotGridObj: PivotView; let eventName: string; let args: any; let selectArgs: PivotCellSelectedEventArgs; let headers: any; let elem: HTMLElement = createElement('div', { id: 'PivotGrid', styles: 'height:200px;' }); document.body.appendChild(elem); afterAll(() => { if (pivotGridObj) { pivotGridObj.destroy(); } remove(elem); }); beforeAll(() => { if (document.getElementById(elem.id)) { remove(document.getElementById(elem.id)); } document.body.appendChild(elem); PivotView.Inject(GroupingBar, ExcelExport, PDFExport); pivotGridObj = new PivotView({ dataSourceSettings: { expandAll: true, dataSource: pivot_dataset as IDataSet[], rows: [{ name: 'eyeColor' }, { name: 'product' }], columns: [{ name: 'isActive' }, { name: 'gender' }], values: [{ name: 'balance' }, { name: 'quantity' }] }, width: 4000, showGroupingBar: true, gridSettings: { allowTextWrap: true, allowReordering: true, allowSelection: true, // contextMenuItems: [{ text: 'Copy with headers', target: '.e-content', id: 'copywithheader' }], selectionSettings: { cellSelectionMode: 'Box', mode: 'Cell', type: 'Single' }, rowHeight: 40, gridLines: 'None', // contextMenuClick: (args: MenuEventArgs): void => { // eventName = args.name; // args = args; // }, // contextMenuOpen: (args: ContextMenuOpenEventArgs): void => { // eventName = args.name; // args = args; // }, beforeCopy: (args: BeforeCopyEventArgs): void => { eventName = 'beforeCopy'; args = args; }, beforePrint: (args: any): void => { eventName = 'beforePrint'; args = args; }, printComplete: (args: any): void => { eventName = 'printComplete'; args = args; }, rowSelecting: (args: RowSelectingEventArgs): void => { eventName = 'rowSelecting'; args = args; }, rowSelected: (args: RowSelectEventArgs): void => { eventName = 'rowSelected'; args = args; }, rowDeselecting: (args: RowDeselectEventArgs): void => { eventName = 'rowDeselecting'; args = args; }, rowDeselected: (args: RowDeselectEventArgs): void => { eventName = 'rowDeselected'; args = args; }, cellSelecting: (args: CellSelectingEventArgs): void => { eventName = 'cellSelecting'; args = args; }, cellSelected: (args: CellSelectEventArgs): void => { eventName = 'cellSelected'; args = args; }, cellDeselecting: (args: CellDeselectEventArgs): void => { eventName = 'cellDeselecting'; args = args; }, cellDeselected: (args: CellDeselectEventArgs): void => { eventName = 'cellDeselected'; args = args; }, resizeStart: (args: ResizeArgs): void => { eventName = 'resizeStart'; args = args; }, resizing: (args: ResizeArgs): void => { eventName = 'resizing'; args = args; }, resizeStop: (args: ResizeArgs): void => { eventName = 'resizeStop'; args = args; }, queryCellInfo: (args: QueryCellInfoEventArgs): void => { eventName = 'queryCellInfo'; args = args; }, headerCellInfo: (args: HeaderCellInfoEventArgs): void => { eventName = 'headerCellInfo'; args = args; }, columnDragStart: (args: ColumnDragEventArgs): void => { eventName = 'resizeStop'; args = args; }, columnDrag: (args: ColumnDragEventArgs): void => { eventName = 'queryCellInfo'; args = args; }, columnDrop: (args: ColumnDragEventArgs): void => { eventName = 'headerCellInfo'; args = args; } }, cellSelected: (args: PivotCellSelectedEventArgs): void => { eventName = 'cellSelected'; selectArgs = args; } }); pivotGridObj.appendTo('#PivotGrid'); }); let click: MouseEvent = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': true }); let dataSourceSettings: IDataOptions let gridObj: Grid it('pivotgrid render testing', (done: Function) => { dataSourceSettings = extend({}, pivotGridObj.dataSourceSettings, null, true); gridObj = pivotGridObj.grid; jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect((document.querySelectorAll('td[aria-colindex="14"]')[0] as HTMLElement).innerText).toBe('1939'); done(); }, 1000); }); // it('context menu header', () => { // (gridObj.contextMenuModule as any).eventArgs = { target: gridObj.getHeaderTable().querySelector('th') }; // let e = { // event: (gridObj.contextMenuModule as any).eventArgs, // items: gridObj.contextMenuModule.contextMenu.items // }; // (gridObj.contextMenuModule as any).contextMenuBeforeOpen(e); // (gridObj.contextMenuModule as any).contextMenuOpen(); // (gridObj.contextMenuModule as any).contextMenuOnClose(e); // expect(gridObj.contextMenuModule.contextMenu.items.length).toBe(1); // }); // it('context menu content', () => { // (gridObj.contextMenuModule as any).eventArgs = { target: gridObj.getContent().querySelector('tr').querySelector('td') }; // let e = { // event: (gridObj.contextMenuModule as any).eventArgs, // items: gridObj.contextMenuModule.contextMenu.items // }; // (gridObj.contextMenuModule as any).contextMenuBeforeOpen(e); // expect(gridObj.contextMenuModule.isOpen).toBe(false); // expect((gridObj.contextMenuModule as any).disableItems.length).toBe(0); // expect((gridObj.contextMenuModule as any).hiddenItems.length).toBe(0); // }); it('Clipboard Check hidden clipboard textarea', () => { let clipArea: HTMLElement = (gridObj.element.querySelectorAll('.e-clipboard')[0] as HTMLElement); expect(gridObj.element.querySelectorAll('.e-clipboard').length > 0).toBeTruthy(); expect(clipArea.style.opacity === '0').toBeTruthy(); }); it('Clipboard Check with row type selection', (done: Function) => { gridObj.selectRows([0, 1]); gridObj.copy(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { // expect((document.querySelector('.e-clipboard') as HTMLInputElement).value.length).toBe(244); done(); }, 1000); }); it('Clipboard Check with row type selection - include header', (done: Function) => { gridObj.copy(true); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { //expect((document.querySelector('.e-clipboard') as HTMLInputElement).value.length).toBe(364); done(); }, 1000); }); // it('resize start', () => { // let handler: HTMLElement = gridObj.getHeaderTable().querySelectorAll('.' + resizeClassList.root)[0] as HTMLElement; // (gridObj.resizeModule as any).resizeStart({ target: handler }); // expect(handler.classList.contains(resizeClassList.icon)).toBeFalsy(); // }); // it('resize end', () => { // let handler: HTMLElement = gridObj.getHeaderTable().querySelectorAll('.' + resizeClassList.root)[0] as HTMLElement; // (gridObj.resizeModule as any).resizeEnd({ target: handler }); // expect(handler.classList.contains(resizeClassList.icon)).toBeFalsy(); // let head = gridObj.getHeaderTable(); // [].slice.call(head.querySelectorAll('th')).forEach((ele: HTMLElement) => { // expect(ele.classList.contains(resizeClassList.cursor)).toBeFalsy(); // }); // expect(gridObj.element.classList.contains(resizeClassList.cursor)).toBeFalsy(); // expect((gridObj.resizeModule as any).pageX).toBeNull(); // expect((gridObj.resizeModule as any).element).toBeNull(); // expect((gridObj.resizeModule as any).column).toBeNull(); // expect((gridObj.resizeModule as any).helper).toBeNull(); // expect(gridObj.element.querySelector('.' + resizeClassList.helper)).toBeFalsy(); // }); // it('resizing - mousemove', () => { // let handler: HTMLElement = gridObj.getHeaderTable().querySelectorAll('.' + resizeClassList.root)[0] as HTMLElement; // (gridObj.resizeModule as any).resizeStart({ target: handler, pageX: 0 }); // (gridObj.resizeModule as any).resizing({ target: handler, pageX: 200 }); // let width = (gridObj.getHeaderTable().querySelectorAll('th')[0]).offsetWidth; // (gridObj.resizeModule as any).resizing({ target: handler, pageX: 300 }); // width += 100; // expect(width).toEqual((gridObj.getHeaderTable().querySelectorAll('th')[0]).offsetWidth); // (gridObj.resizeModule as any).resizing({ target: handler, pageX: 100 }); // width -= 200; // expect(width).toEqual((gridObj.getHeaderTable().querySelectorAll('th')[0]).offsetWidth); // pivotGridObj.copy(); // }); it('select - col index 1', (done: Function) => { (document.querySelector('td[aria-colindex="1"]') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(selectArgs.selectedCellsInfo.length).toBe(1); expect(selectArgs.selectedCellsInfo[0].rowHeaders).toBe('blue'); expect(selectArgs.selectedCellsInfo[0].columnHeaders).toBe('false.female'); done(); }, 1000); }) it('select - col index 2', (done: Function) => { (document.querySelector('td[aria-colindex="2"]') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(selectArgs.selectedCellsInfo.length).toBe(1); expect(selectArgs.selectedCellsInfo[0].value).toBe(359); done(); }, 1000); }) it('switch row select', (done: Function) => { pivotGridObj.gridSettings.selectionSettings.mode = 'Row'; pivotGridObj.renderPivotGrid(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(selectArgs.selectedCellsInfo.length).toBe(0); done(); }, 1000); }) it('select - row index 5', (done: Function) => { (document.querySelector('td[index="5"]') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(selectArgs.selectedCellsInfo.length).toBe(15); expect(selectArgs.selectedCellsInfo[0].value).toBe('Car'); done(); }, 1000); }) it('select - row index 6', (done: Function) => { (document.querySelector('td[index="6"]') as HTMLElement).click(); jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; setTimeout(() => { expect(selectArgs.selectedCellsInfo.length).toBe(15); expect(selectArgs.selectedCellsInfo[0].value).toBe('Flight'); done(); }, 1000); }) }); 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); }); });
the_stack
import { DBusClient, DBusProxyConfig, DBusObject } from "./dbusClient"; import { ProxyObject, ClientInterface, Variant } from "dbus-next"; /** * Access to ratbagd. */ export class RatBagManager extends DBusObject { static readonly PROXY: DBusProxyConfig<RatBagManager> = { iface: "org.freedesktop.ratbag1", path: "/org/freedesktop/ratbag1", system: true, create(client: DBusClient, proxy: ProxyObject): RatBagManager { return new RatBagManager(client, proxy); }, }; constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); } /** * Gets the API version of ratbagd. This is built for API 1. Everything else might not work as intended. */ public async api(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Manager", "APIVersion")).value; } /** * Gets a list of all currently connected devices. */ public async devices(): Promise<RatBagDevice[]> { const variant = await this.getProperty("org.freedesktop.ratbag1.Manager", "Devices"); const paths: string[] = variant.value; const devices: RatBagDevice[] = []; for (const path of paths) { const proxy = await this.proxy.bus.getProxyObject("org.freedesktop.ratbag1", path); devices.push(new RatBagDevice(this.client, proxy)); } return devices; } } /** * A device, ratbagd can control. */ export class RatBagDevice extends DBusObject { private readonly device: RatBagDeviceInterface; constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); this.device = proxy.getInterface("org.freedesktop.ratbag1.Device") as RatBagDeviceInterface; } /** * Gets the device name. */ public async name(): Promise<string> { return (await this.getProperty("org.freedesktop.ratbag1.Device", "Name")).value; } /** * Gets the device model */ public async model(): Promise<RatBagModel> { let modelString: string = (await this.getProperty("org.freedesktop.ratbag1.Device", "Model")).value; try { const busType: string = modelString.substring(0, modelString.indexOf(":")); modelString = modelString.substring(modelString.indexOf(":") + 1); if (busType !== "usb" && busType !== "bluetooth") { // We don't know about that bus type. return { busType: "unknown" }; } const vendorHex = modelString.substring(0, modelString.indexOf(":")); modelString = modelString.substring(modelString.indexOf(":") + 1); const productHex = modelString.substring(0, modelString.indexOf(":")); modelString = modelString.substring(modelString.indexOf(":") + 1); const vendorId = parseInt(vendorHex, 16); const productId = parseInt(productHex, 16); const version = parseInt(modelString); if (isNaN(vendorId) || isNaN(productId) || isNaN(version)) { return { busType: "unknown" }; } return { busType: busType, vendorHex: vendorHex, vendorId: vendorId, productHex: productHex, productId: productId, version: version, }; } catch (err) { return { busType: "unknown" }; } } /** * Gets a list of profiles for that device. If a device does not support multiple profiles, * there'll be just one profile in the list that can be used. */ public async profiles(): Promise<RatBagProfile[]> { const variant = await this.getProperty("org.freedesktop.ratbag1.Device", "Profiles"); const paths: string[] = variant.value; const profiles: RatBagProfile[] = []; for (const path of paths) { const proxy = await this.proxy.bus.getProxyObject("org.freedesktop.ratbag1", path); profiles.push(new RatBagProfile(this.client, proxy)); } return profiles; } /** * Writes all changes that were made to the device. */ public async commit(): Promise<void> { await this.device.Commit(); } /** * Adds a listener for an event, when committing to the device fails. */ public on(event: "Resync", handler: () => void): void { this.device.on(event, handler); } public once(event: "Resync", handler: () => void): void { this.device.once(event, handler); } public off(event: "Resync", handler: () => void): void { this.device.off(event, handler); } } /** * A profile for a ratbagd device. */ export class RatBagProfile extends DBusObject { private readonly profile: RatBagProfileInterface; constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); this.profile = proxy.getInterface("org.freedesktop.ratbag1.Profile") as RatBagProfileInterface; } /** * Gets the index of the profile. */ public async index(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Profile", "Index")).value; } /** * Gets the name of the profile, if the device supports profile naming. */ public async name(): Promise<string | undefined> { const name = (await this.getProperty("org.freedesktop.ratbag1.Profile", "Name")).value; return name === "" ? undefined : name; } /** * Sets the name of a profile. This must not be called if the device does not support profile naming. * Use {@link name()} first, to find out whether you can use this. */ public async setName(name: string): Promise<void> { await this.setProperty("org.freedesktop.ratbag1.Profile", "Name", new Variant<string>("s", name)); } /** * Gets whether the profile is enabled. A disabled profile may have invalid values set, so you should * check these values before enabling a profile. */ public async enabled(): Promise<boolean> { return (await this.getProperty("org.freedesktop.ratbag1.Profile", "Enabled")).value; } /** * Enables this profile. */ public async enable(): Promise<void> { await this.setProperty("org.freedesktop.ratbag1.Profile", "Enabled", new Variant<boolean>("b", true)); } /** * Disables this profile. */ public async disable(): Promise<void> { await this.setProperty("org.freedesktop.ratbag1.Profile", "Enabled", new Variant<boolean>("b", false)); } /** * Gets whether this profile is currently active. There is always only one active profile. */ public async active(): Promise<boolean> { return (await this.getProperty("org.freedesktop.ratbag1.Profile", "IsActive")).value; } /** * Activates this profile. The currently active profile will be deactivated. */ public async activate(): Promise<void> { return await this.profile.SetActive(); } /** * Gets a list of display resolutions, that can be switched through. */ public async resolutions(): Promise<RatBagResolution[]> { const variant = await this.getProperty("org.freedesktop.ratbag1.Profile", "Resolutions"); const paths: string[] = variant.value; const resolutions: RatBagResolution[] = []; for (const path of paths) { const proxy = await this.proxy.bus.getProxyObject("org.freedesktop.ratbag1", path); resolutions.push(new RatBagResolution(this.client, proxy)); } return resolutions; } /** * Gets a list of buttons on the device for this profile. */ public async buttons(): Promise<RatBagButton[]> { const variant = await this.getProperty("org.freedesktop.ratbag1.Profile", "Buttons"); const paths: string[] = variant.value; const buttons: RatBagButton[] = []; for (const path of paths) { const proxy = await this.proxy.bus.getProxyObject("org.freedesktop.ratbag1", path); buttons.push(new RatBagButton(this.client, proxy)); } return buttons; } /** * Gets a list of leds on the device for this profile. */ public async leds(): Promise<RatBagLed[]> { const variant = await this.getProperty("org.freedesktop.ratbag1.Profile", "Leds"); const paths: string[] = variant.value; const leds: RatBagLed[] = []; for (const path of paths) { const proxy = await this.proxy.bus.getProxyObject("org.freedesktop.ratbag1", path); leds.push(new RatBagLed(this.client, proxy)); } return leds; } } /** * A resolution profile for a device profile. */ export class RatBagResolution extends DBusObject { private readonly resolution: RatBagResolutionInterface; constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); this.resolution = proxy.getInterface("org.freedesktop.ratbag1.Resolution") as RatBagResolutionInterface; } /** * Gets the index of this resolution profile. */ public async index(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Resolution", "Index")).value; } /** * Gets whether this resolution profile is the currently active resolution. */ public async active(): Promise<boolean> { return (await this.getProperty("org.freedesktop.ratbag1.Resolution", "IsActive")).value; } /** * Gets whether this resolution profile is the default. */ public async default(): Promise<boolean> { return (await this.getProperty("org.freedesktop.ratbag1.Resolution", "IsDefault")).value; } /** * Sets this resolution profile as the currently active resolution. */ public async activate(): Promise<void> { await this.resolution.SetActive(); } /** * Sets this resolution profile as default. */ public async setDefault(): Promise<void> { await this.resolution.SetDefault(); } /** * Gets the dpi values for this profile. */ public async dpi(): Promise<RatBagDpi> { const dpi: number | [number, number] = ( await this.getProperty("org.freedesktop.ratbag1.Resolution", "Resolution") ).value; if (typeof dpi === "number") { return dpi; } else { return { x: dpi[0], y: dpi[1], }; } } /** * Sets the dpi for this profile. If {@link dpi()} returns a single value, this must also be set to a single value. * If {@link dpi()} returns separate x and y values, this must be set to separate x and y values. */ public async setDpi(dpi: RatBagDpi): Promise<void> { const variant = typeof dpi === "number" ? new Variant<number>("u", dpi) : new Variant<[number, number]>("(uu)", [dpi.x, dpi.y]); await this.setProperty("org.freedesktop.ratbag1.Resolution", "Resolution", variant); } /** * Gets a list of numbers that can be used as dpi values. */ public async allowedDpiValues(): Promise<number[]> { return (await this.getProperty("org.freedesktop.ratbag1.Resolution", "Resolutions")).value; } } /** * A button on a device for a specific profile */ export class RatBagButton extends DBusObject { private static readonly SPECIAL_ACTION_MAP: Record<RatBagSpecialAction, number> = { unknown: 0x40000000, doubleclick: 0x40000001, "wheel left": 0x40000002, "wheel right": 0x40000003, "wheel up": 0x40000004, "wheel down": 0x40000005, "ratched mode switch": 0x40000006, "resolution cycle up": 0x40000007, "resolution cycle down": 0x40000008, "resolution up": 0x40000009, "resolution down": 0x4000000a, "resolution alternate": 0x4000000b, "resolution default": 0x4000000c, "profile cycle up": 0x4000000d, "profile cycle down": 0x4000000e, "profile up": 0x4000000f, "profile down": 0x40000010, "second mode": 0x40000011, "battery level": 0x40000012, }; constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); } /** * Gets the index of this button. */ public async index(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Button", "Index")).value; } /** * Gets the action currently bound to this button. */ public async mapping(): Promise<RatBagMapping> { // eslint-disable-next-line @typescript-eslint/no-explicit-any const raw: [number, Variant] = (await this.getProperty("org.freedesktop.ratbag1.Button", "Mapping")).value; if (raw[0] === 0) { return { type: "none", }; } else if (raw[0] === 1) { return { type: "button", button: raw[1].value, }; } else if (raw[0] === 2) { const id = Object.keys(RatBagButton.SPECIAL_ACTION_MAP).find( (key) => RatBagButton.SPECIAL_ACTION_MAP[key as RatBagSpecialAction] === raw[1].value, ) as RatBagSpecialAction | undefined; return { type: "special", action: id === undefined ? "unknown" : id, }; } else if (raw[0] === 3) { const macro: RatBagMacroAction[] = []; for (const entry of raw[1].value as [number, number][]) { macro.push({ type: entry[0] === 0 ? "release" : "press", keyCode: entry[1], }); } return { type: "macro", macro: macro, }; } else { return { type: "unknown", }; } } /** * Binds this button to the given action. */ public async setMapping(mapping: RatBagMapping): Promise<void> { let id = 1000; let variant: Variant = new Variant<number>("u", 0); if (mapping.type === "none") { id = 1000; variant = new Variant<number>("u", 0); } else if (mapping.type === "button") { id = 1; variant = new Variant<number>("u", mapping.button); } else if (mapping.type === "special") { id = 2; const func = RatBagButton.SPECIAL_ACTION_MAP[mapping.action]; variant = new Variant<number>("u", func === undefined ? 0x40000000 : func); } else if (mapping.type === "macro") { id = 3; const actions: [number, number][] = []; for (const action of mapping.macro) { actions.push([action.type === "press" ? 1 : 0, action.keyCode]); } variant = new Variant<[number, number][]>("a(uu)", actions); } await this.setProperty("org.freedesktop.ratbag1.Button", "Mapping", new Variant("(uv)", [id, variant])); } } /** * A led on a device for a specific profile */ export class RatBagLed extends DBusObject { constructor(client: DBusClient, proxy: ProxyObject) { super(client, proxy); } /** * Gets the index for this led. */ public async index(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Led", "Index")).value; } /** * Gets the current mode of the led. */ public async mode(): Promise<LedMode> { const modeId: number = (await this.getProperty("org.freedesktop.ratbag1.Led", "Mode")).value; switch (modeId) { case 1: return "on"; case 2: return "cycle"; case 3: return "breath"; default: return "off"; } } /** * Sets the mode of the led. */ public async setMode(mode: LedMode): Promise<void> { let modeId = 0; if (mode === "on") { modeId = 1; } else if (mode === "cycle") { modeId = 2; } else if (mode === "breath") { modeId = 3; } await this.setProperty("org.freedesktop.ratbag1.Led", "Mode", new Variant<number>("u", modeId)); } /** * Gets a list of supported led modes. */ public async supportedModes(): Promise<LedMode[]> { const modeIds: number[] = (await this.getProperty("org.freedesktop.ratbag1.Led", "Mode")).value; const modes: LedMode[] = []; for (const modeId of modeIds) { switch (modeId) { case 0: modes.push("off"); break; case 1: modes.push("on"); break; case 2: modes.push("cycle"); break; case 3: modes.push("breath"); break; } } return modes; } /** * Gets the color, the led is currently in. */ public async color(): Promise<RatBagColorObj & RatBagColorValue> { const color: [number, number, number] = (await this.getProperty("org.freedesktop.ratbag1.Led", "Color")).value; return { color: ((color[0] & 0xff) << 16) | ((color[1] & 0xff) << 8) | (color[2] & 0xff), red: color[0] & 0xff, green: color[1] & 0xff, blue: color[2] & 0xff, }; } /** * Sets the color for the led. */ public async setColor(color: RatBagColorObj | RatBagColorValue): Promise<void> { let value: [number, number, number]; if ("color" in color) { value = [(color.color >> 16) & 0xff, (color.color >> 8) & 0xff, color.color & 0xff]; } else { value = [color.red, color.green, color.blue]; } await this.setProperty( "org.freedesktop.ratbag1.Led", "Color", new Variant<[number, number, number]>("(uuu)", value), ); } /** * Gets the current effect duration in milliseconds. What exactly this means depends on the led mode. */ public async effectDuration(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Led", "EffectDuration")).value; } /** * Sets the current effect duration in milliseconds. */ public async setEffectDuration(millis: number): Promise<void> { await this.setProperty("org.freedesktop.ratbag1.Led", "EffectDuration", new Variant<number>("u", millis)); } /** * Gets the current led brightness [0;255] */ public async brightness(): Promise<number> { return (await this.getProperty("org.freedesktop.ratbag1.Led", "Brightness")).value & 0xff; } /** * Sets the current led brightness [0;255] */ public async setBrightness(brightness: number): Promise<void> { await this.setProperty( "org.freedesktop.ratbag1.Led", "Brightness", new Variant<number>("u", brightness & 0xff), ); } } /** * A model of a ratbagd device. */ export type RatBagModel = RatBagModelUnknown | RatBagModelCommon; /** * An unknown device model. */ export type RatBagModelUnknown = { busType: "unknown"; }; /** * A known device model. */ export type RatBagModelCommon = { /** * How the device id connected. */ busType: "usb" | "bluetooth"; /** * The vendor id of the device as a hex string. */ vendorHex: string; /** * The vendor id of the device as a number. */ vendorId: number; /** * The product id of the device as a hex string. */ productHex: string; /** * The product id of the device as a number. */ productId: number; /** * The version of the device. This number is only used internally to distinguish multiple * devices of the same type. */ version: number; }; /** * A resolution in DPI. This can either be a single value or separate values for x and y depending on the device. * When setting a DPI value, it must be exactly the kind of value, the device supports. */ export type RatBagDpi = number | { x: number; y: number }; /** * A mapping for a button. */ export type RatBagMapping = | RatBagMappingNone | RatBagMappingUnknown | RatBagMappingButton | RatBagMappingSpecial | RatBagMappingMacro; /** * A button mapping that does nothing. */ export type RatBagMappingNone = { type: "none"; }; /** * An unknown button mapping. */ export type RatBagMappingUnknown = { type: "unknown"; }; /** * A button mapping that maps a physical button to a logical button. */ export type RatBagMappingButton = { type: "button"; /** * The logical mouse button to map to. */ button: number; }; /** * A mapping that triggers a special action. */ export type RatBagMappingSpecial = { type: "special"; /** * The action to trigger. */ action: RatBagSpecialAction; }; /** * A mapping that triggers a macro. */ export type RatBagMappingMacro = { type: "macro"; macro: RatBagMacroAction[]; }; /** * An action in a macro. */ export type RatBagMacroAction = { type: "press" | "release"; keyCode: number; }; /** * A color represented by red, green and blue values in range [0;255] */ export type RatBagColorObj = { red: number; green: number; blue: number; }; /** * A color represented as 0xRRGGBB */ export type RatBagColorValue = { color: number; }; /** * A special button action. */ export type RatBagSpecialAction = | "unknown" | "doubleclick" | "wheel left" | "wheel right" | "wheel up" | "wheel down" | "ratched mode switch" | "resolution cycle up" | "resolution cycle down" | "resolution up" | "resolution down" | "resolution alternate" | "resolution default" | "profile cycle up" | "profile cycle down" | "profile up" | "profile down" | "second mode" | "battery level"; /** * A mode for a led. */ export type LedMode = "off" | "on" | "cycle" | "breath"; type RatBagDeviceInterface = ClientInterface & { Commit(): Promise<void>; }; type RatBagProfileInterface = ClientInterface & { SetActive(): Promise<void>; }; type RatBagResolutionInterface = ClientInterface & { SetDefault(): Promise<void>; SetActive(): Promise<void>; };
the_stack
import "jest-extended"; import { ForgeNewBlockAction, IsForgingAllowedAction } from "@packages/core-forger/src/actions"; import { Contracts } from "@packages/core-kernel"; import { Sandbox } from "@packages/core-test-framework"; import { Interfaces } from "@packages/crypto"; import { Slots } from "@packages/crypto/dist/crypto"; import { HostNoResponseError, RelayCommunicationError } from "@packages/core-forger/src/errors"; import { ForgerService } from "@packages/core-forger/src/forger-service"; import { Container, Enums, Services, Utils } from "@packages/core-kernel"; import { NetworkStateStatus } from "@packages/core-p2p"; import { GetActiveDelegatesAction } from "@packages/core-state/src/actions"; import { Crypto, Managers } from "@packages/crypto"; import { Address } from "@packages/crypto/src/identities"; import { BuilderFactory } from "@packages/crypto/src/transactions"; import { calculateActiveDelegates } from "./__utils__/calculate-active-delegates"; let sandbox: Sandbox; const logger = { error: jest.fn(), debug: jest.fn(), info: jest.fn(), warning: jest.fn(), }; const client = { register: jest.fn(), dispose: jest.fn(), broadcastBlock: jest.fn(), syncWithNetwork: jest.fn(), getRound: jest.fn(), getNetworkState: jest.fn(), getTransactions: jest.fn(), emitEvent: jest.fn(), selectHost: jest.fn(), }; const handlerProvider = { isRegistrationRequired: jest.fn(), registerHandlers: jest.fn(), }; beforeEach(() => { sandbox = new Sandbox(); sandbox.app.bind(Container.Identifiers.LogService).toConstantValue(logger); sandbox.app.bind(Container.Identifiers.TransactionHandlerProvider).toConstantValue(handlerProvider); sandbox.app.bind(Container.Identifiers.TriggerService).to(Services.Triggers.Triggers).inSingletonScope(); sandbox.app .get<Services.Triggers.Triggers>(Container.Identifiers.TriggerService) .bind("getActiveDelegates", new GetActiveDelegatesAction(sandbox.app)); sandbox.app .get<Services.Triggers.Triggers>(Container.Identifiers.TriggerService) .bind("forgeNewBlock", new ForgeNewBlockAction()); sandbox.app .get<Services.Triggers.Triggers>(Container.Identifiers.TriggerService) .bind("isForgingAllowed", new IsForgingAllowedAction()); const getTimeStampForBlock = (height: number) => { switch (height) { case 1: return 0; default: throw new Error(`Test scenarios should not hit this line`); } }; jest.spyOn(Utils.forgingInfoCalculator, "getBlockTimeLookup").mockResolvedValue(getTimeStampForBlock); }); afterEach(() => { jest.resetAllMocks(); }); describe("ForgerService", () => { let forgerService: ForgerService; const mockHost = { hostname: "127.0.0.1", port: 4000 }; let delegates; let mockNetworkState; let mockTransaction; let transaction; let mockRound; let round; beforeEach(() => { forgerService = sandbox.app.resolve<ForgerService>(ForgerService); jest.spyOn(sandbox.app, "resolve").mockReturnValueOnce(client); // forger-service only resolves Client const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); delegates = calculateActiveDelegates(); round = { data: { delegates, timestamp: Slots.getTime() - 3, reward: 0, lastBlock: { height: 100 }, }, canForge: false, }; mockNetworkState = { status: NetworkStateStatus.Default, getNodeHeight: () => 10, getLastBlockId: () => "11111111", getOverHeightBlockHeaders: () => [], getQuorum: () => 0.7, toJson: () => "test json", }; const recipientAddress = Address.fromPassphrase("recipient's secret"); transaction = BuilderFactory.transfer() .version(1) .amount("100") .recipientId(recipientAddress) .sign("sender's secret") .build(); mockTransaction = { transactions: [transaction.serialized.toString("hex")], poolSize: 10, count: 10, }; mockRound = { timestamp: Slots.getTime() - 5, reward: 0, lastBlock: { height: 100 }, }; }); describe("GetRound", () => { it("should return undefined", () => { forgerService.register({ hosts: [mockHost] }); expect(forgerService.getRound()).toBeUndefined(); }); }); describe("GetRemainingSlotTime", () => { it("should return undefined", () => { forgerService.register({ hosts: [mockHost] }); expect(forgerService.getRemainingSlotTime()).toBeUndefined(); }); }); describe("GetLastForgedBlock", () => { it("should return undefined", () => { forgerService.register({ hosts: [mockHost] }); expect(forgerService.getLastForgedBlock()).toBeUndefined(); }); }); describe("Register", () => { it("should register an associated client", async () => { forgerService.register({ hosts: [mockHost] }); expect(client.register).toBeCalledTimes(1); expect(client.register).toBeCalledWith([mockHost]); }); }); describe("Dispose", () => { it("should dispose of an associated client", async () => { forgerService.register({ hosts: [mockHost] }); const spyDisposeClient = jest.spyOn((forgerService as any).client, "dispose"); // @ts-ignore expect(forgerService.isStopped).toEqual(false); forgerService.dispose(); expect(spyDisposeClient).toHaveBeenCalled(); // @ts-ignore expect(forgerService.isStopped).toEqual(true); }); }); describe("Boot", () => { it("should register handlers, set delegates, and log active delegates info message", async () => { handlerProvider.isRegistrationRequired.mockReturnValue(true); forgerService.register({ hosts: [mockHost] }); client.getRound.mockReturnValueOnce({ delegates }); await expect(forgerService.boot(delegates)).toResolve(); expect((forgerService as any).delegates).toEqual(delegates); const expectedInfoMessage = `Loaded ${Utils.pluralize( "active delegate", delegates.length, true, )}: ${delegates.map((wallet) => `${wallet.delegate.username} (${wallet.publicKey})`).join(", ")}`; expect(handlerProvider.registerHandlers).toBeCalled(); expect(logger.info).toHaveBeenCalledWith(expectedInfoMessage); }); it("should skip logging when the service is already initialised", async () => { forgerService.register({ hosts: [mockHost] }); client.getRound.mockReturnValueOnce({ delegates }); (forgerService as any).initialized = true; await expect(forgerService.boot(delegates)).toResolve(); expect(logger.info).not.toHaveBeenCalledWith(`Forger Manager started.`); }); it("should not log when there are no active delegates", async () => { forgerService.register({ hosts: [mockHost] }); client.getRound.mockReturnValueOnce({ delegates }); await expect(forgerService.boot([])).toResolve(); expect(logger.info).toHaveBeenCalledTimes(1); expect(logger.info).toHaveBeenCalledWith(`Forger Manager started.`); }); it("should log inactive delegates correctly", async () => { const numberActive = 10; const round = { data: { delegates: delegates.slice(0, numberActive) } }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); const expectedInactiveDelegatesMessage = `Loaded ${Utils.pluralize( "inactive delegate", delegates.length - numberActive, true, )}: ${delegates .slice(numberActive) .map((delegate) => delegate.publicKey) .join(", ")}`; forgerService.register({ hosts: [mockHost] }); await expect(forgerService.boot(delegates)).toResolve(); expect(logger.info).toHaveBeenCalledWith(expectedInactiveDelegatesMessage); }); it("should catch and log errors", async () => { client.getRound.mockRejectedValueOnce(new Error("oops")); forgerService.register({ hosts: [mockHost] }); await expect(forgerService.boot(delegates)).toResolve(); expect(logger.warning).toHaveBeenCalledWith(`Waiting for a responsive host`); }); it("should set correct timeout to check slots", async () => { jest.useFakeTimers(); client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); await expect(forgerService.boot(delegates)).toResolve(); jest.runAllTimers(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), expect.toBeWithin(0, 2000)); }); }); describe("GetTransactionsForForging", () => { it("should log error when transactions are empty", async () => { forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); await expect(forgerService.getTransactionsForForging()).resolves.toEqual([]); expect(logger.error).toHaveBeenCalledWith(`Could not get unconfirmed transactions from transaction pool.`); }); it("should log and return valid transactions", async () => { forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); const recipientAddress = Address.fromPassphrase("recipient's secret"); const transaction = BuilderFactory.transfer() .version(1) .amount("100") .recipientId(recipientAddress) .sign("sender's secret") .build(); const mockTransaction = { transactions: [transaction.serialized.toString("hex")], poolSize: 10, count: 10, }; // @ts-ignore spyGetTransactions.mockResolvedValue(mockTransaction); await expect(forgerService.getTransactionsForForging()).resolves.toEqual([transaction.data]); expect(logger.error).not.toHaveBeenCalled(); const expectedLogInfo = `Received ${Utils.pluralize("transaction", 1, true)} ` + `from the pool containing ${Utils.pluralize("transaction", mockTransaction.poolSize, true)} total`; expect(logger.debug).toHaveBeenCalledWith(expectedLogInfo); }); }); describe("isForgingAllowed", () => { it("should not allow forging when network status is unknown", async () => { expect( // @ts-ignore forgerService.isForgingAllowed({ status: NetworkStateStatus.Unknown }, delegates[0]), ).toEqual(false); expect(logger.info).toHaveBeenCalledWith("Failed to get network state from client. Will not forge."); }); it("should not allow forging when network status is a cold start", async () => { expect( // @ts-ignore forgerService.isForgingAllowed({ status: NetworkStateStatus.ColdStart }, delegates[0]), ).toEqual(false); expect(logger.info).toHaveBeenCalledWith("Skipping slot because of cold start. Will not forge."); }); it("should not allow forging when network status is below minimum peers", async () => { expect( // @ts-ignore forgerService.isForgingAllowed({ status: NetworkStateStatus.BelowMinimumPeers }, delegates[0]), ).toEqual(false); expect(logger.info).toHaveBeenCalledWith("Network reach is not sufficient to get quorum. Will not forge."); }); it("should log double forge warning for any overheight block headers", async () => { client.getRound.mockReturnValueOnce({ delegates }); forgerService.register({ hosts: [mockHost] }); await forgerService.boot(delegates); const overHeightBlockHeaders: Array<{ [id: string]: any; }> = [ { generatorPublicKey: delegates[0].publicKey, id: 1, }, ]; mockNetworkState.getQuorum = () => 0.99; mockNetworkState.getOverHeightBlockHeaders = () => overHeightBlockHeaders; expect( // @ts-ignore forgerService.isForgingAllowed(mockNetworkState, delegates[0]), ).toEqual(true); const expectedOverHeightInfo = `Detected ${Utils.pluralize( "distinct overheight block header", overHeightBlockHeaders.length, true, )}.`; expect(logger.info).toHaveBeenCalledWith(expectedOverHeightInfo); const expectedDoubleForgeWarning = `Possible double forging delegate: ${delegates[0].delegate.username} (${delegates[0].publicKey}) - Block: ${overHeightBlockHeaders[0].id}.`; expect(logger.warning).toHaveBeenCalledWith(expectedDoubleForgeWarning); }); it("should not allow forging if quorum is not met", async () => { jest.useFakeTimers(); client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); await forgerService.boot(delegates); (mockNetworkState.getQuorum = () => 0.6), expect( // @ts-ignore forgerService.isForgingAllowed(mockNetworkState, delegates[0]), ).toEqual(false); expect(logger.info).toHaveBeenCalledWith("Not enough quorum to forge next block. Will not forge."); expect(logger.debug).toHaveBeenCalledWith(`Network State: ${mockNetworkState.toJson()}`); expect(logger.warning).not.toHaveBeenCalled(); }); it("should allow forging if quorum is met", async () => { client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); await forgerService.boot(delegates); expect( // @ts-ignore forgerService.isForgingAllowed(mockNetworkState, delegates[0]), ).toEqual(true); expect(logger.debug).not.toHaveBeenCalled(); expect(logger.warning).not.toHaveBeenCalled(); }); it("should allow forging if quorum is met, not log warning if overheight delegate is not the same", async () => { client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); await forgerService.boot(delegates); const overHeightBlockHeaders: Array<{ [id: string]: any; }> = [ { generatorPublicKey: delegates[0].publicKey, id: 1, }, ]; mockNetworkState.getOverHeightBlockHeaders = () => overHeightBlockHeaders; expect( // @ts-ignore forgerService.isForgingAllowed(mockNetworkState, delegates[1]), ).toEqual(true); expect(logger.debug).not.toHaveBeenCalled(); expect(logger.warning).not.toHaveBeenCalled(); }); }); describe("checkSlot", () => { it("should do nothing when the forging service is stopped", async () => { forgerService.register({ hosts: [mockHost] }); await forgerService.dispose(); await expect(forgerService.checkSlot()).toResolve(); expect(logger.info).not.toHaveBeenCalled(); expect(logger.warning).not.toHaveBeenCalled(); expect(logger.error).not.toHaveBeenCalled(); expect(logger.debug).not.toHaveBeenCalled(); }); it("should set timer if forging is not yet allowed", async () => { forgerService.register({ hosts: [mockHost] }); (forgerService as any).initialized = true; client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); await expect(forgerService.boot(delegates)).toResolve(); expect(logger.info).not.toHaveBeenCalledWith(`Forger Manager started.`); jest.useFakeTimers(); client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); await expect(forgerService.checkSlot()).toResolve(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 200); expect(logger.info).not.toHaveBeenCalled(); expect(logger.warning).not.toHaveBeenCalled(); expect(logger.error).not.toHaveBeenCalled(); expect(logger.debug).not.toHaveBeenCalled(); jest.useRealTimers(); }); it("should set timer and log nextForger which is active on node", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 1].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); (forgerService as any).initialized = true; await expect(forgerService.boot(delegates.slice(0, delegates.length - 2))).toResolve(); expect(logger.info).not.toHaveBeenCalledWith(`Forger Manager started.`); jest.useFakeTimers(); // @ts-ignore const spyClientSyncWithNetwork = jest.spyOn(forgerService.client, "syncWithNetwork"); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); await expect(forgerService.checkSlot()).toResolve(); expect(spyClientSyncWithNetwork).toHaveBeenCalled(); const expectedInfoMessage = `Next forging delegate ${delegates[delegates.length - 3].delegate.username} (${ delegates[delegates.length - 3].publicKey }) is active on this node.`; expect(logger.info).toHaveBeenCalledWith(expectedInfoMessage); expect(logger.warning).not.toHaveBeenCalled(); expect(logger.error).not.toHaveBeenCalled(); jest.useRealTimers(); }); it("should set timer and not log message if nextForger is not active", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 1].publicKey }, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); (forgerService as any).initialized = true; await expect(forgerService.boot(delegates.slice(0, delegates.length - 3))).toResolve(); expect(logger.info).not.toHaveBeenCalledWith(`Forger Manager started.`); jest.useFakeTimers(); // @ts-ignore const spyClientSyncWithNetwork = jest.spyOn(forgerService.client, "syncWithNetwork"); spyClientSyncWithNetwork.mockReset(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); await expect(forgerService.checkSlot()).toResolve(); expect(spyClientSyncWithNetwork).not.toHaveBeenCalled(); const expectedInfoMessage = `Next forging delegate ${delegates[delegates.length - 3].delegate.username} (${ delegates[delegates.length - 3].publicKey }) is active on this node.`; expect(logger.info).not.toHaveBeenCalledWith(expectedInfoMessage); expect(logger.warning).not.toHaveBeenCalled(); expect(logger.error).not.toHaveBeenCalled(); expect(logger.debug).not.toHaveBeenCalledWith(`Sending wake-up check to relay node ${mockHost.hostname}`); jest.useRealTimers(); }); it("should forge valid blocks when forging is allowed", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 3, }, timestamp: Crypto.Slots.getTime() - 7, reward: "0", current: 1, }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); // @ts-ignore spyGetNetworkState.mockResolvedValue(mockNetworkState); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(spyForgeNewBlock).toHaveBeenCalledWith( delegates[delegates.length - 2], round.data, mockNetworkState, ); const loggerWarningMessage = `The NetworkState height (${mockNetworkState.getNodeHeight()}) and round height (${ round.data.lastBlock.height }) are out of sync. This indicates delayed blocks on the network.`; expect(logger.warning).toHaveBeenCalledWith(loggerWarningMessage); jest.useRealTimers(); }); it("should not log warning message when nodeHeight does not equal last block height", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 10, }, timestamp: Crypto.Slots.getTime() - 7, reward: "0", }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); // @ts-ignore spyGetNetworkState.mockResolvedValue(mockNetworkState); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await forgerService.checkSlot(); expect(spyForgeNewBlock).toHaveBeenCalledWith( delegates[delegates.length - 2], round.data, mockNetworkState, ); const loggerWarningMessage = `The NetworkState height (${mockNetworkState.nodeHeight}) and round height (${round.data.lastBlock.height}) are out of sync. This indicates delayed blocks on the network.`; expect(logger.warning).not.toHaveBeenCalledWith(loggerWarningMessage); jest.useRealTimers(); }); it("should not allow forging when blocked by network status", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 10, }, timestamp: 0, reward: "0", }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); mockNetworkState.status = NetworkStateStatus.Unknown; // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); // @ts-ignore spyGetNetworkState.mockResolvedValue(mockNetworkState); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(spyForgeNewBlock).not.toHaveBeenCalled(); }); it("should catch network errors and set timeout to check slot later", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 10, }, timestamp: 0, reward: "0", }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); // @ts-ignore spyGetNetworkState.mockImplementation(() => { throw new HostNoResponseError(`blockchain isn't ready`); }); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 2000); expect(spyForgeNewBlock).not.toHaveBeenCalled(); expect(logger.info).toHaveBeenCalledWith(`Waiting for relay to become ready.`); jest.useRealTimers(); }); it("should log warning when error isn't a network error", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 10, }, timestamp: 0, reward: "0", }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); const mockEndpoint = `Test - Endpoint`; const mockError = `custom error`; // @ts-ignore spyGetNetworkState.mockImplementation(() => { throw new RelayCommunicationError(mockEndpoint, mockError); }); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 2000); expect(spyForgeNewBlock).not.toHaveBeenCalled(); expect(logger.warning).toHaveBeenCalledWith( `Request to ${mockEndpoint} failed, because of '${mockError}'.`, ); jest.useRealTimers(); }); it("should log error when error thrown during attempted forge isn't a network error", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = { data: { delegates, canForge: true, currentForger: { publicKey: delegates[delegates.length - 2].publicKey, }, nextForger: { publicKey: delegates[delegates.length - 3].publicKey }, lastBlock: { height: 10, }, timestamp: 0, reward: "0", current: 9, }, }; client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); // @ts-ignore const spyClientEmitEvent = jest.spyOn(forgerService.client, "emitEvent"); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); // @ts-ignore const spyGetNetworkState = jest.spyOn(forgerService.client, "getNetworkState"); const mockError = `custom error`; // @ts-ignore spyGetNetworkState.mockImplementation(() => { throw new Error(mockError); }); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round.data as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 2000); expect(spyForgeNewBlock).not.toHaveBeenCalled(); expect(logger.error).toHaveBeenCalled(); expect(spyClientEmitEvent).toHaveBeenCalledWith(Enums.ForgerEvent.Failed, { error: mockError }); const infoMessage = `Round: ${round.data.current.toLocaleString()}, height: ${round.data.lastBlock.height.toLocaleString()}`; expect(logger.info).toHaveBeenCalledWith(infoMessage); jest.useRealTimers(); }); it("should not error when there is no round info", async () => { const slotSpy = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); slotSpy.mockReturnValue(0); const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; delegates[delegates.length - 2] = Object.assign(nextDelegateToForge, delegates[delegates.length - 2]); const round = undefined; client.getRound.mockResolvedValueOnce(round as Contracts.P2P.CurrentRound); forgerService.register({ hosts: [mockHost] }); // @ts-ignore const spyGetTransactions = jest.spyOn(forgerService.client, "getTransactions"); // @ts-ignore spyGetTransactions.mockResolvedValue([]); // @ts-ignore const spyClientEmitEvent = jest.spyOn(forgerService.client, "emitEvent"); const spyForgeNewBlock = jest.spyOn(forgerService, "forgeNewBlock"); await expect(forgerService.boot(delegates)).toResolve(); client.getRound.mockResolvedValueOnce(round as Contracts.P2P.CurrentRound); jest.useFakeTimers(); // @ts-ignore await expect(forgerService.checkSlot()).toResolve(); expect(setTimeout).toHaveBeenCalledWith(expect.any(Function), 2000); expect(spyForgeNewBlock).not.toHaveBeenCalled(); expect(logger.error).toHaveBeenCalled(); expect(spyClientEmitEvent).toHaveBeenCalledWith(Enums.ForgerEvent.Failed, { error: expect.any(String) }); expect(logger.info).not.toHaveBeenCalled(); jest.useRealTimers(); }); }); describe("ForgeNewBlock", () => { it("should fail to forge when delegate is already in next slot", async () => { client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); client.getTransactions.mockResolvedValueOnce(mockTransaction); await forgerService.boot(delegates); const address = `Delegate-Wallet-${2}`; const mockBlock = { data: {} } as Interfaces.IBlock; const mockPrevRound = { ...mockRound, timestamp: Slots.getTime() - 9 }; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; // @ts-ignore await expect(forgerService.forgeNewBlock(nextDelegateToForge, mockPrevRound, mockNetworkState)).toResolve(); const prettyName = `Username: ${address} (${nextDelegateToForge.publicKey})`; const failedForgeMessage = `Failed to forge new block by delegate ${prettyName}, because already in next slot.`; expect(logger.warning).toHaveBeenCalledWith(failedForgeMessage); }); it("should fail to forge when there is not enough time left in slot", async () => { client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 7, lastBlock: { height: 100 }, }); forgerService.register({ hosts: [mockHost] }); client.getTransactions.mockResolvedValueOnce(mockTransaction); await forgerService.boot(delegates); const address = `Delegate-Wallet-${2}`; const mockBlock = { data: {} } as Interfaces.IBlock; const mockEndingRound = { ...mockRound, timestamp: Slots.getTime() - 7 }; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; const spyNextSlot = jest.spyOn(Crypto.Slots, "getSlotNumber"); spyNextSlot.mockReturnValue(0); // @ts-ignore await expect( forgerService.forgeNewBlock(nextDelegateToForge as any, mockEndingRound, mockNetworkState), ).toResolve(); const prettyName = `Username: ${address} (${nextDelegateToForge.publicKey})`; expect(logger.warning).toHaveBeenCalledWith( expect.stringContaining(`Failed to forge new block by delegate ${prettyName}, because there were`), ); }); it("should forge valid new blocks", async () => { client.getRound.mockReturnValueOnce({ delegates }); const timeLeftInMs = 3000; const spyTimeTillNextSlot = jest.spyOn(Crypto.Slots, "getTimeInMsUntilNextSlot"); spyTimeTillNextSlot.mockReturnValue(timeLeftInMs); forgerService.register({ hosts: [mockHost] }); client.getTransactions.mockResolvedValueOnce(mockTransaction); await forgerService.boot(delegates); const address = `Delegate-Wallet-${2}`; const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; const spyNextSlot = jest.spyOn(Crypto.Slots, "getSlotNumber"); spyNextSlot.mockReturnValue(0); client.emitEvent.mockReset(); // @ts-ignore await expect(forgerService.forgeNewBlock(nextDelegateToForge, mockRound, mockNetworkState)).toResolve(); const prettyName = `Username: ${address} (${nextDelegateToForge.publicKey})`; const infoForgeMessageOne = `Forged new block`; const infoForgeMessageTwo = ` by delegate ${prettyName}`; expect(logger.info).toHaveBeenCalledWith(expect.stringContaining(infoForgeMessageOne)); expect(logger.info).toHaveBeenCalledWith(expect.stringContaining(infoForgeMessageTwo)); expect(client.broadcastBlock).toHaveBeenCalledWith(mockBlock); expect(client.emitEvent).toHaveBeenNthCalledWith(1, Enums.BlockEvent.Forged, expect.anything()); expect(client.emitEvent).toHaveBeenNthCalledWith(2, Enums.TransactionEvent.Forged, transaction.data); }); it("should forge valid new blocks when passed specific milestones", async () => { client.getRound.mockReturnValueOnce({ delegates, timestamp: Crypto.Slots.getTime() - 3, lastBlock: { height: 100 }, }); const spyMilestone = jest.spyOn(Managers.configManager, "getMilestone"); spyMilestone.mockReturnValue({ ...Managers.configManager.getMilestone(1), block: { version: 0, idFullSha256: true }, }); forgerService.register({ hosts: [mockHost] }); client.getTransactions.mockResolvedValueOnce(mockTransaction); mockNetworkState.lastBlockId = "c2fa2d400b4c823873d476f6e0c9e423cf925e9b48f1b5706c7e2771d4095538"; jest.useFakeTimers(); await forgerService.boot(delegates); const address = `Delegate-Wallet-${2}`; const mockBlock = { data: {} } as Interfaces.IBlock; const nextDelegateToForge = { publicKey: delegates[2].publicKey, forge: jest.fn().mockReturnValue(mockBlock), }; const spyNextSlot = jest.spyOn(Crypto.Slots, "getSlotNumber"); spyNextSlot.mockReturnValueOnce(0).mockReturnValueOnce(0); client.emitEvent.mockReset(); // @ts-ignore await forgerService.forgeNewBlock(nextDelegateToForge, round.data, mockNetworkState); const prettyName = `Username: ${address} (${nextDelegateToForge.publicKey})`; const infoForgeMessageOne = `Forged new block`; const infoForgeMessageTwo = ` by delegate ${prettyName}`; expect(logger.info).toHaveBeenCalledWith(expect.stringContaining(infoForgeMessageOne)); expect(logger.info).toHaveBeenCalledWith(expect.stringContaining(infoForgeMessageTwo)); expect(client.broadcastBlock).toHaveBeenCalledWith(mockBlock); expect(client.emitEvent).toHaveBeenNthCalledWith(1, Enums.BlockEvent.Forged, expect.anything()); expect(client.emitEvent).toHaveBeenNthCalledWith(2, Enums.TransactionEvent.Forged, transaction.data); jest.useRealTimers(); }); }); });
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AddTagsCommand, AddTagsCommandInput, AddTagsCommandOutput } from "./commands/AddTagsCommand"; import { ApplySecurityGroupsToLoadBalancerCommand, ApplySecurityGroupsToLoadBalancerCommandInput, ApplySecurityGroupsToLoadBalancerCommandOutput, } from "./commands/ApplySecurityGroupsToLoadBalancerCommand"; import { AttachLoadBalancerToSubnetsCommand, AttachLoadBalancerToSubnetsCommandInput, AttachLoadBalancerToSubnetsCommandOutput, } from "./commands/AttachLoadBalancerToSubnetsCommand"; import { ConfigureHealthCheckCommand, ConfigureHealthCheckCommandInput, ConfigureHealthCheckCommandOutput, } from "./commands/ConfigureHealthCheckCommand"; import { CreateAppCookieStickinessPolicyCommand, CreateAppCookieStickinessPolicyCommandInput, CreateAppCookieStickinessPolicyCommandOutput, } from "./commands/CreateAppCookieStickinessPolicyCommand"; import { CreateLBCookieStickinessPolicyCommand, CreateLBCookieStickinessPolicyCommandInput, CreateLBCookieStickinessPolicyCommandOutput, } from "./commands/CreateLBCookieStickinessPolicyCommand"; import { CreateLoadBalancerCommand, CreateLoadBalancerCommandInput, CreateLoadBalancerCommandOutput, } from "./commands/CreateLoadBalancerCommand"; import { CreateLoadBalancerListenersCommand, CreateLoadBalancerListenersCommandInput, CreateLoadBalancerListenersCommandOutput, } from "./commands/CreateLoadBalancerListenersCommand"; import { CreateLoadBalancerPolicyCommand, CreateLoadBalancerPolicyCommandInput, CreateLoadBalancerPolicyCommandOutput, } from "./commands/CreateLoadBalancerPolicyCommand"; import { DeleteLoadBalancerCommand, DeleteLoadBalancerCommandInput, DeleteLoadBalancerCommandOutput, } from "./commands/DeleteLoadBalancerCommand"; import { DeleteLoadBalancerListenersCommand, DeleteLoadBalancerListenersCommandInput, DeleteLoadBalancerListenersCommandOutput, } from "./commands/DeleteLoadBalancerListenersCommand"; import { DeleteLoadBalancerPolicyCommand, DeleteLoadBalancerPolicyCommandInput, DeleteLoadBalancerPolicyCommandOutput, } from "./commands/DeleteLoadBalancerPolicyCommand"; import { DeregisterInstancesFromLoadBalancerCommand, DeregisterInstancesFromLoadBalancerCommandInput, DeregisterInstancesFromLoadBalancerCommandOutput, } from "./commands/DeregisterInstancesFromLoadBalancerCommand"; import { DescribeAccountLimitsCommand, DescribeAccountLimitsCommandInput, DescribeAccountLimitsCommandOutput, } from "./commands/DescribeAccountLimitsCommand"; import { DescribeInstanceHealthCommand, DescribeInstanceHealthCommandInput, DescribeInstanceHealthCommandOutput, } from "./commands/DescribeInstanceHealthCommand"; import { DescribeLoadBalancerAttributesCommand, DescribeLoadBalancerAttributesCommandInput, DescribeLoadBalancerAttributesCommandOutput, } from "./commands/DescribeLoadBalancerAttributesCommand"; import { DescribeLoadBalancerPoliciesCommand, DescribeLoadBalancerPoliciesCommandInput, DescribeLoadBalancerPoliciesCommandOutput, } from "./commands/DescribeLoadBalancerPoliciesCommand"; import { DescribeLoadBalancerPolicyTypesCommand, DescribeLoadBalancerPolicyTypesCommandInput, DescribeLoadBalancerPolicyTypesCommandOutput, } from "./commands/DescribeLoadBalancerPolicyTypesCommand"; import { DescribeLoadBalancersCommand, DescribeLoadBalancersCommandInput, DescribeLoadBalancersCommandOutput, } from "./commands/DescribeLoadBalancersCommand"; import { DescribeTagsCommand, DescribeTagsCommandInput, DescribeTagsCommandOutput, } from "./commands/DescribeTagsCommand"; import { DetachLoadBalancerFromSubnetsCommand, DetachLoadBalancerFromSubnetsCommandInput, DetachLoadBalancerFromSubnetsCommandOutput, } from "./commands/DetachLoadBalancerFromSubnetsCommand"; import { DisableAvailabilityZonesForLoadBalancerCommand, DisableAvailabilityZonesForLoadBalancerCommandInput, DisableAvailabilityZonesForLoadBalancerCommandOutput, } from "./commands/DisableAvailabilityZonesForLoadBalancerCommand"; import { EnableAvailabilityZonesForLoadBalancerCommand, EnableAvailabilityZonesForLoadBalancerCommandInput, EnableAvailabilityZonesForLoadBalancerCommandOutput, } from "./commands/EnableAvailabilityZonesForLoadBalancerCommand"; import { ModifyLoadBalancerAttributesCommand, ModifyLoadBalancerAttributesCommandInput, ModifyLoadBalancerAttributesCommandOutput, } from "./commands/ModifyLoadBalancerAttributesCommand"; import { RegisterInstancesWithLoadBalancerCommand, RegisterInstancesWithLoadBalancerCommandInput, RegisterInstancesWithLoadBalancerCommandOutput, } from "./commands/RegisterInstancesWithLoadBalancerCommand"; import { RemoveTagsCommand, RemoveTagsCommandInput, RemoveTagsCommandOutput } from "./commands/RemoveTagsCommand"; import { SetLoadBalancerListenerSSLCertificateCommand, SetLoadBalancerListenerSSLCertificateCommandInput, SetLoadBalancerListenerSSLCertificateCommandOutput, } from "./commands/SetLoadBalancerListenerSSLCertificateCommand"; import { SetLoadBalancerPoliciesForBackendServerCommand, SetLoadBalancerPoliciesForBackendServerCommandInput, SetLoadBalancerPoliciesForBackendServerCommandOutput, } from "./commands/SetLoadBalancerPoliciesForBackendServerCommand"; import { SetLoadBalancerPoliciesOfListenerCommand, SetLoadBalancerPoliciesOfListenerCommandInput, SetLoadBalancerPoliciesOfListenerCommandOutput, } from "./commands/SetLoadBalancerPoliciesOfListenerCommand"; import { ElasticLoadBalancingClient } from "./ElasticLoadBalancingClient"; /** * <fullname>Elastic Load Balancing</fullname> * * <p>A load balancer can distribute incoming traffic across your EC2 instances. * This enables you to increase the availability of your application. The load balancer * also monitors the health of its registered instances and ensures that it routes traffic * only to healthy instances. You configure your load balancer to accept incoming traffic * by specifying one or more listeners, which are configured with a protocol and port * number for connections from clients to the load balancer and a protocol and port number * for connections from the load balancer to the instances.</p> * <p>Elastic Load Balancing supports three types of load balancers: Application Load Balancers, Network Load Balancers, * and Classic Load Balancers. You can select a load balancer based on your application needs. For more * information, see the <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/">Elastic Load Balancing User Guide</a>.</p> * <p>This reference covers the 2012-06-01 API, which supports Classic Load Balancers. * The 2015-12-01 API supports Application Load Balancers and Network Load Balancers.</p> * * <p>To get started, create a load balancer with one or more listeners using <a>CreateLoadBalancer</a>. * Register your instances with the load balancer using <a>RegisterInstancesWithLoadBalancer</a>.</p> * * <p>All Elastic Load Balancing operations are <i>idempotent</i>, which means * that they complete at most one time. If you repeat an operation, it succeeds with a 200 OK * response code.</p> */ export class ElasticLoadBalancing extends ElasticLoadBalancingClient { /** * <p>Adds the specified tags to the specified load balancer. Each load balancer can have a maximum of 10 tags.</p> * * <p>Each tag consists of a key and an optional value. If a tag with the same key is already associated * with the load balancer, <code>AddTags</code> updates its value.</p> * * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/add-remove-tags.html">Tag Your Classic Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public addTags(args: AddTagsCommandInput, options?: __HttpHandlerOptions): Promise<AddTagsCommandOutput>; public addTags(args: AddTagsCommandInput, cb: (err: any, data?: AddTagsCommandOutput) => void): void; public addTags( args: AddTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddTagsCommandOutput) => void ): void; public addTags( args: AddTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddTagsCommandOutput) => void), cb?: (err: any, data?: AddTagsCommandOutput) => void ): Promise<AddTagsCommandOutput> | void { const command = new AddTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Associates one or more security groups with your load balancer in a virtual private cloud (VPC). The specified security groups override the previously associated security groups.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-security-groups.html#elb-vpc-security-groups">Security Groups for Load Balancers in a VPC</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public applySecurityGroupsToLoadBalancer( args: ApplySecurityGroupsToLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<ApplySecurityGroupsToLoadBalancerCommandOutput>; public applySecurityGroupsToLoadBalancer( args: ApplySecurityGroupsToLoadBalancerCommandInput, cb: (err: any, data?: ApplySecurityGroupsToLoadBalancerCommandOutput) => void ): void; public applySecurityGroupsToLoadBalancer( args: ApplySecurityGroupsToLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ApplySecurityGroupsToLoadBalancerCommandOutput) => void ): void; public applySecurityGroupsToLoadBalancer( args: ApplySecurityGroupsToLoadBalancerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ApplySecurityGroupsToLoadBalancerCommandOutput) => void), cb?: (err: any, data?: ApplySecurityGroupsToLoadBalancerCommandOutput) => void ): Promise<ApplySecurityGroupsToLoadBalancerCommandOutput> | void { const command = new ApplySecurityGroupsToLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds one or more subnets to the set of configured subnets for the specified load balancer.</p> * <p>The load balancer evenly distributes requests across all registered subnets. * For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-manage-subnets.html">Add or Remove Subnets for Your Load Balancer in a VPC</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public attachLoadBalancerToSubnets( args: AttachLoadBalancerToSubnetsCommandInput, options?: __HttpHandlerOptions ): Promise<AttachLoadBalancerToSubnetsCommandOutput>; public attachLoadBalancerToSubnets( args: AttachLoadBalancerToSubnetsCommandInput, cb: (err: any, data?: AttachLoadBalancerToSubnetsCommandOutput) => void ): void; public attachLoadBalancerToSubnets( args: AttachLoadBalancerToSubnetsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AttachLoadBalancerToSubnetsCommandOutput) => void ): void; public attachLoadBalancerToSubnets( args: AttachLoadBalancerToSubnetsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AttachLoadBalancerToSubnetsCommandOutput) => void), cb?: (err: any, data?: AttachLoadBalancerToSubnetsCommandOutput) => void ): Promise<AttachLoadBalancerToSubnetsCommandOutput> | void { const command = new AttachLoadBalancerToSubnetsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Specifies the health check settings to use when evaluating the health state of your EC2 instances.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-healthchecks.html">Configure Health Checks for Your Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public configureHealthCheck( args: ConfigureHealthCheckCommandInput, options?: __HttpHandlerOptions ): Promise<ConfigureHealthCheckCommandOutput>; public configureHealthCheck( args: ConfigureHealthCheckCommandInput, cb: (err: any, data?: ConfigureHealthCheckCommandOutput) => void ): void; public configureHealthCheck( args: ConfigureHealthCheckCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ConfigureHealthCheckCommandOutput) => void ): void; public configureHealthCheck( args: ConfigureHealthCheckCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ConfigureHealthCheckCommandOutput) => void), cb?: (err: any, data?: ConfigureHealthCheckCommandOutput) => void ): Promise<ConfigureHealthCheckCommandOutput> | void { const command = new ConfigureHealthCheckCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Generates a stickiness policy with sticky session lifetimes that follow that of an application-generated cookie. This policy can be associated only with HTTP/HTTPS listeners.</p> * <p>This policy is similar to the policy created by <a>CreateLBCookieStickinessPolicy</a>, * except that the lifetime of the special Elastic Load Balancing cookie, <code>AWSELB</code>, * follows the lifetime of the application-generated cookie specified in the policy configuration. * The load balancer only inserts a new stickiness cookie when the application response * includes a new application cookie.</p> * <p>If the application cookie is explicitly removed or expires, the session stops being sticky until a new application cookie is issued.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-sticky-sessions.html#enable-sticky-sessions-application">Application-Controlled Session Stickiness</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public createAppCookieStickinessPolicy( args: CreateAppCookieStickinessPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<CreateAppCookieStickinessPolicyCommandOutput>; public createAppCookieStickinessPolicy( args: CreateAppCookieStickinessPolicyCommandInput, cb: (err: any, data?: CreateAppCookieStickinessPolicyCommandOutput) => void ): void; public createAppCookieStickinessPolicy( args: CreateAppCookieStickinessPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAppCookieStickinessPolicyCommandOutput) => void ): void; public createAppCookieStickinessPolicy( args: CreateAppCookieStickinessPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAppCookieStickinessPolicyCommandOutput) => void), cb?: (err: any, data?: CreateAppCookieStickinessPolicyCommandOutput) => void ): Promise<CreateAppCookieStickinessPolicyCommandOutput> | void { const command = new CreateAppCookieStickinessPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Generates a stickiness policy with sticky session lifetimes controlled by the lifetime of the browser (user-agent) or a specified expiration period. This policy can be associated only with HTTP/HTTPS listeners.</p> * <p>When a load balancer implements this policy, the load balancer uses a special cookie to track the instance for each request. When the load balancer receives a request, it first checks to see if this cookie is present in the request. * If so, the load balancer sends the request to the application server specified in the cookie. If not, the load balancer sends the request to a server that is chosen based on the existing load-balancing algorithm.</p> * <p>A cookie is inserted into the response for binding subsequent requests from the same user to that server. The validity of the cookie is based on the cookie expiration time, which is specified in the policy configuration.</p> * * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-sticky-sessions.html#enable-sticky-sessions-duration">Duration-Based Session Stickiness</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public createLBCookieStickinessPolicy( args: CreateLBCookieStickinessPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLBCookieStickinessPolicyCommandOutput>; public createLBCookieStickinessPolicy( args: CreateLBCookieStickinessPolicyCommandInput, cb: (err: any, data?: CreateLBCookieStickinessPolicyCommandOutput) => void ): void; public createLBCookieStickinessPolicy( args: CreateLBCookieStickinessPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLBCookieStickinessPolicyCommandOutput) => void ): void; public createLBCookieStickinessPolicy( args: CreateLBCookieStickinessPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLBCookieStickinessPolicyCommandOutput) => void), cb?: (err: any, data?: CreateLBCookieStickinessPolicyCommandOutput) => void ): Promise<CreateLBCookieStickinessPolicyCommandOutput> | void { const command = new CreateLBCookieStickinessPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a Classic Load Balancer.</p> * * <p>You can add listeners, security groups, subnets, and tags when you create your load balancer, * or you can add them later using <a>CreateLoadBalancerListeners</a>, * <a>ApplySecurityGroupsToLoadBalancer</a>, <a>AttachLoadBalancerToSubnets</a>, * and <a>AddTags</a>.</p> * <p>To describe your current load balancers, see <a>DescribeLoadBalancers</a>. * When you are finished with a load balancer, you can delete it using * <a>DeleteLoadBalancer</a>.</p> * * <p>You can create up to 20 load balancers per region per account. * You can request an increase for the number of load balancers for your account. * For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-limits.html">Limits for Your Classic Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public createLoadBalancer( args: CreateLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLoadBalancerCommandOutput>; public createLoadBalancer( args: CreateLoadBalancerCommandInput, cb: (err: any, data?: CreateLoadBalancerCommandOutput) => void ): void; public createLoadBalancer( args: CreateLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLoadBalancerCommandOutput) => void ): void; public createLoadBalancer( args: CreateLoadBalancerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLoadBalancerCommandOutput) => void), cb?: (err: any, data?: CreateLoadBalancerCommandOutput) => void ): Promise<CreateLoadBalancerCommandOutput> | void { const command = new CreateLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates one or more listeners for the specified load balancer. If a listener with the specified port does not already exist, it is created; otherwise, the properties of the new listener must match the properties of the existing listener.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-listener-config.html">Listeners for Your Classic Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public createLoadBalancerListeners( args: CreateLoadBalancerListenersCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLoadBalancerListenersCommandOutput>; public createLoadBalancerListeners( args: CreateLoadBalancerListenersCommandInput, cb: (err: any, data?: CreateLoadBalancerListenersCommandOutput) => void ): void; public createLoadBalancerListeners( args: CreateLoadBalancerListenersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLoadBalancerListenersCommandOutput) => void ): void; public createLoadBalancerListeners( args: CreateLoadBalancerListenersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLoadBalancerListenersCommandOutput) => void), cb?: (err: any, data?: CreateLoadBalancerListenersCommandOutput) => void ): Promise<CreateLoadBalancerListenersCommandOutput> | void { const command = new CreateLoadBalancerListenersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a policy with the specified attributes for the specified load balancer.</p> * <p>Policies are settings that are saved for your load balancer and that can be applied to the listener or the application server, depending on the policy type.</p> */ public createLoadBalancerPolicy( args: CreateLoadBalancerPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLoadBalancerPolicyCommandOutput>; public createLoadBalancerPolicy( args: CreateLoadBalancerPolicyCommandInput, cb: (err: any, data?: CreateLoadBalancerPolicyCommandOutput) => void ): void; public createLoadBalancerPolicy( args: CreateLoadBalancerPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLoadBalancerPolicyCommandOutput) => void ): void; public createLoadBalancerPolicy( args: CreateLoadBalancerPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLoadBalancerPolicyCommandOutput) => void), cb?: (err: any, data?: CreateLoadBalancerPolicyCommandOutput) => void ): Promise<CreateLoadBalancerPolicyCommandOutput> | void { const command = new CreateLoadBalancerPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified load balancer.</p> * <p>If you are attempting to recreate a load balancer, you must reconfigure all settings. The DNS name associated with a deleted load balancer are no longer usable. The name and associated DNS record of the deleted load balancer no longer exist and traffic sent to any of its IP addresses is no longer delivered to your instances.</p> * <p>If the load balancer does not exist or has already been deleted, the call to * <code>DeleteLoadBalancer</code> still succeeds.</p> */ public deleteLoadBalancer( args: DeleteLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLoadBalancerCommandOutput>; public deleteLoadBalancer( args: DeleteLoadBalancerCommandInput, cb: (err: any, data?: DeleteLoadBalancerCommandOutput) => void ): void; public deleteLoadBalancer( args: DeleteLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLoadBalancerCommandOutput) => void ): void; public deleteLoadBalancer( args: DeleteLoadBalancerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLoadBalancerCommandOutput) => void), cb?: (err: any, data?: DeleteLoadBalancerCommandOutput) => void ): Promise<DeleteLoadBalancerCommandOutput> | void { const command = new DeleteLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified listeners from the specified load balancer.</p> */ public deleteLoadBalancerListeners( args: DeleteLoadBalancerListenersCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLoadBalancerListenersCommandOutput>; public deleteLoadBalancerListeners( args: DeleteLoadBalancerListenersCommandInput, cb: (err: any, data?: DeleteLoadBalancerListenersCommandOutput) => void ): void; public deleteLoadBalancerListeners( args: DeleteLoadBalancerListenersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLoadBalancerListenersCommandOutput) => void ): void; public deleteLoadBalancerListeners( args: DeleteLoadBalancerListenersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLoadBalancerListenersCommandOutput) => void), cb?: (err: any, data?: DeleteLoadBalancerListenersCommandOutput) => void ): Promise<DeleteLoadBalancerListenersCommandOutput> | void { const command = new DeleteLoadBalancerListenersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified policy from the specified load balancer. This policy must not be enabled for any listeners.</p> */ public deleteLoadBalancerPolicy( args: DeleteLoadBalancerPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLoadBalancerPolicyCommandOutput>; public deleteLoadBalancerPolicy( args: DeleteLoadBalancerPolicyCommandInput, cb: (err: any, data?: DeleteLoadBalancerPolicyCommandOutput) => void ): void; public deleteLoadBalancerPolicy( args: DeleteLoadBalancerPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLoadBalancerPolicyCommandOutput) => void ): void; public deleteLoadBalancerPolicy( args: DeleteLoadBalancerPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLoadBalancerPolicyCommandOutput) => void), cb?: (err: any, data?: DeleteLoadBalancerPolicyCommandOutput) => void ): Promise<DeleteLoadBalancerPolicyCommandOutput> | void { const command = new DeleteLoadBalancerPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deregisters the specified instances from the specified load balancer. After the instance is deregistered, it no longer receives traffic from the load balancer.</p> * * <p>You can use <a>DescribeLoadBalancers</a> to verify that the instance is deregistered from the load balancer.</p> * * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-deregister-register-instances.html">Register or De-Register EC2 Instances</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public deregisterInstancesFromLoadBalancer( args: DeregisterInstancesFromLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<DeregisterInstancesFromLoadBalancerCommandOutput>; public deregisterInstancesFromLoadBalancer( args: DeregisterInstancesFromLoadBalancerCommandInput, cb: (err: any, data?: DeregisterInstancesFromLoadBalancerCommandOutput) => void ): void; public deregisterInstancesFromLoadBalancer( args: DeregisterInstancesFromLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeregisterInstancesFromLoadBalancerCommandOutput) => void ): void; public deregisterInstancesFromLoadBalancer( args: DeregisterInstancesFromLoadBalancerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeregisterInstancesFromLoadBalancerCommandOutput) => void), cb?: (err: any, data?: DeregisterInstancesFromLoadBalancerCommandOutput) => void ): Promise<DeregisterInstancesFromLoadBalancerCommandOutput> | void { const command = new DeregisterInstancesFromLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the current Elastic Load Balancing resource limits for your AWS account.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-limits.html">Limits for Your Classic Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public describeAccountLimits( args: DescribeAccountLimitsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeAccountLimitsCommandOutput>; public describeAccountLimits( args: DescribeAccountLimitsCommandInput, cb: (err: any, data?: DescribeAccountLimitsCommandOutput) => void ): void; public describeAccountLimits( args: DescribeAccountLimitsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeAccountLimitsCommandOutput) => void ): void; public describeAccountLimits( args: DescribeAccountLimitsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAccountLimitsCommandOutput) => void), cb?: (err: any, data?: DescribeAccountLimitsCommandOutput) => void ): Promise<DescribeAccountLimitsCommandOutput> | void { const command = new DescribeAccountLimitsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the state of the specified instances with respect to the specified load balancer. If no instances are specified, the call describes the state of all instances that are currently registered with the load balancer. If instances are specified, their state is returned even if they are no longer registered with the load balancer. The state of terminated instances is not returned.</p> */ public describeInstanceHealth( args: DescribeInstanceHealthCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeInstanceHealthCommandOutput>; public describeInstanceHealth( args: DescribeInstanceHealthCommandInput, cb: (err: any, data?: DescribeInstanceHealthCommandOutput) => void ): void; public describeInstanceHealth( args: DescribeInstanceHealthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeInstanceHealthCommandOutput) => void ): void; public describeInstanceHealth( args: DescribeInstanceHealthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeInstanceHealthCommandOutput) => void), cb?: (err: any, data?: DescribeInstanceHealthCommandOutput) => void ): Promise<DescribeInstanceHealthCommandOutput> | void { const command = new DescribeInstanceHealthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the attributes for the specified load balancer.</p> */ public describeLoadBalancerAttributes( args: DescribeLoadBalancerAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeLoadBalancerAttributesCommandOutput>; public describeLoadBalancerAttributes( args: DescribeLoadBalancerAttributesCommandInput, cb: (err: any, data?: DescribeLoadBalancerAttributesCommandOutput) => void ): void; public describeLoadBalancerAttributes( args: DescribeLoadBalancerAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeLoadBalancerAttributesCommandOutput) => void ): void; public describeLoadBalancerAttributes( args: DescribeLoadBalancerAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeLoadBalancerAttributesCommandOutput) => void), cb?: (err: any, data?: DescribeLoadBalancerAttributesCommandOutput) => void ): Promise<DescribeLoadBalancerAttributesCommandOutput> | void { const command = new DescribeLoadBalancerAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the specified policies.</p> * <p>If you specify a load balancer name, the action returns the descriptions of all policies created for the load balancer. * If you specify a policy name associated with your load balancer, the action returns the description of that policy. * If you don't specify a load balancer name, the action returns descriptions of the specified sample policies, or descriptions of all sample policies. * The names of the sample policies have the <code>ELBSample-</code> prefix.</p> */ public describeLoadBalancerPolicies( args: DescribeLoadBalancerPoliciesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeLoadBalancerPoliciesCommandOutput>; public describeLoadBalancerPolicies( args: DescribeLoadBalancerPoliciesCommandInput, cb: (err: any, data?: DescribeLoadBalancerPoliciesCommandOutput) => void ): void; public describeLoadBalancerPolicies( args: DescribeLoadBalancerPoliciesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeLoadBalancerPoliciesCommandOutput) => void ): void; public describeLoadBalancerPolicies( args: DescribeLoadBalancerPoliciesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeLoadBalancerPoliciesCommandOutput) => void), cb?: (err: any, data?: DescribeLoadBalancerPoliciesCommandOutput) => void ): Promise<DescribeLoadBalancerPoliciesCommandOutput> | void { const command = new DescribeLoadBalancerPoliciesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the specified load balancer policy types or all load balancer policy types.</p> * <p>The description of each type indicates how it can be used. For example, * some policies can be used only with layer 7 listeners, * some policies can be used only with layer 4 listeners, * and some policies can be used only with your EC2 instances.</p> * <p>You can use <a>CreateLoadBalancerPolicy</a> to create a policy configuration for any of these policy types. * Then, depending on the policy type, use either <a>SetLoadBalancerPoliciesOfListener</a> or * <a>SetLoadBalancerPoliciesForBackendServer</a> to set the policy.</p> */ public describeLoadBalancerPolicyTypes( args: DescribeLoadBalancerPolicyTypesCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeLoadBalancerPolicyTypesCommandOutput>; public describeLoadBalancerPolicyTypes( args: DescribeLoadBalancerPolicyTypesCommandInput, cb: (err: any, data?: DescribeLoadBalancerPolicyTypesCommandOutput) => void ): void; public describeLoadBalancerPolicyTypes( args: DescribeLoadBalancerPolicyTypesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeLoadBalancerPolicyTypesCommandOutput) => void ): void; public describeLoadBalancerPolicyTypes( args: DescribeLoadBalancerPolicyTypesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeLoadBalancerPolicyTypesCommandOutput) => void), cb?: (err: any, data?: DescribeLoadBalancerPolicyTypesCommandOutput) => void ): Promise<DescribeLoadBalancerPolicyTypesCommandOutput> | void { const command = new DescribeLoadBalancerPolicyTypesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the specified the load balancers. If no load balancers are specified, the call describes all of your load balancers.</p> */ public describeLoadBalancers( args: DescribeLoadBalancersCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeLoadBalancersCommandOutput>; public describeLoadBalancers( args: DescribeLoadBalancersCommandInput, cb: (err: any, data?: DescribeLoadBalancersCommandOutput) => void ): void; public describeLoadBalancers( args: DescribeLoadBalancersCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeLoadBalancersCommandOutput) => void ): void; public describeLoadBalancers( args: DescribeLoadBalancersCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeLoadBalancersCommandOutput) => void), cb?: (err: any, data?: DescribeLoadBalancersCommandOutput) => void ): Promise<DescribeLoadBalancersCommandOutput> | void { const command = new DescribeLoadBalancersCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the tags associated with the specified load balancers.</p> */ public describeTags( args: DescribeTagsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeTagsCommandOutput>; public describeTags(args: DescribeTagsCommandInput, cb: (err: any, data?: DescribeTagsCommandOutput) => void): void; public describeTags( args: DescribeTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeTagsCommandOutput) => void ): void; public describeTags( args: DescribeTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeTagsCommandOutput) => void), cb?: (err: any, data?: DescribeTagsCommandOutput) => void ): Promise<DescribeTagsCommandOutput> | void { const command = new DescribeTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified subnets from the set of configured subnets for the load balancer.</p> * <p>After a subnet is removed, all EC2 instances registered with the load balancer * in the removed subnet go into the <code>OutOfService</code> state. Then, * the load balancer balances the traffic among the remaining routable subnets.</p> */ public detachLoadBalancerFromSubnets( args: DetachLoadBalancerFromSubnetsCommandInput, options?: __HttpHandlerOptions ): Promise<DetachLoadBalancerFromSubnetsCommandOutput>; public detachLoadBalancerFromSubnets( args: DetachLoadBalancerFromSubnetsCommandInput, cb: (err: any, data?: DetachLoadBalancerFromSubnetsCommandOutput) => void ): void; public detachLoadBalancerFromSubnets( args: DetachLoadBalancerFromSubnetsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DetachLoadBalancerFromSubnetsCommandOutput) => void ): void; public detachLoadBalancerFromSubnets( args: DetachLoadBalancerFromSubnetsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DetachLoadBalancerFromSubnetsCommandOutput) => void), cb?: (err: any, data?: DetachLoadBalancerFromSubnetsCommandOutput) => void ): Promise<DetachLoadBalancerFromSubnetsCommandOutput> | void { const command = new DetachLoadBalancerFromSubnetsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified Availability Zones from the set of Availability Zones for the specified load balancer * in EC2-Classic or a default VPC.</p> * <p>For load balancers in a non-default VPC, use <a>DetachLoadBalancerFromSubnets</a>.</p> * <p>There must be at least one Availability Zone registered with a load balancer at all times. * After an Availability Zone is removed, all instances registered with the load balancer that are in the removed * Availability Zone go into the <code>OutOfService</code> state. Then, the load balancer attempts to equally balance * the traffic among its remaining Availability Zones.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-az.html">Add or Remove Availability Zones</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public disableAvailabilityZonesForLoadBalancer( args: DisableAvailabilityZonesForLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<DisableAvailabilityZonesForLoadBalancerCommandOutput>; public disableAvailabilityZonesForLoadBalancer( args: DisableAvailabilityZonesForLoadBalancerCommandInput, cb: (err: any, data?: DisableAvailabilityZonesForLoadBalancerCommandOutput) => void ): void; public disableAvailabilityZonesForLoadBalancer( args: DisableAvailabilityZonesForLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisableAvailabilityZonesForLoadBalancerCommandOutput) => void ): void; public disableAvailabilityZonesForLoadBalancer( args: DisableAvailabilityZonesForLoadBalancerCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: DisableAvailabilityZonesForLoadBalancerCommandOutput) => void), cb?: (err: any, data?: DisableAvailabilityZonesForLoadBalancerCommandOutput) => void ): Promise<DisableAvailabilityZonesForLoadBalancerCommandOutput> | void { const command = new DisableAvailabilityZonesForLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds the specified Availability Zones to the set of Availability Zones for the specified load balancer * in EC2-Classic or a default VPC.</p> * <p>For load balancers in a non-default VPC, use <a>AttachLoadBalancerToSubnets</a>.</p> * <p>The load balancer evenly distributes requests across all its registered Availability Zones * that contain instances. For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-az.html">Add or Remove Availability Zones</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public enableAvailabilityZonesForLoadBalancer( args: EnableAvailabilityZonesForLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<EnableAvailabilityZonesForLoadBalancerCommandOutput>; public enableAvailabilityZonesForLoadBalancer( args: EnableAvailabilityZonesForLoadBalancerCommandInput, cb: (err: any, data?: EnableAvailabilityZonesForLoadBalancerCommandOutput) => void ): void; public enableAvailabilityZonesForLoadBalancer( args: EnableAvailabilityZonesForLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: EnableAvailabilityZonesForLoadBalancerCommandOutput) => void ): void; public enableAvailabilityZonesForLoadBalancer( args: EnableAvailabilityZonesForLoadBalancerCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: EnableAvailabilityZonesForLoadBalancerCommandOutput) => void), cb?: (err: any, data?: EnableAvailabilityZonesForLoadBalancerCommandOutput) => void ): Promise<EnableAvailabilityZonesForLoadBalancerCommandOutput> | void { const command = new EnableAvailabilityZonesForLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies the attributes of the specified load balancer.</p> * <p>You can modify the load balancer attributes, such as <code>AccessLogs</code>, <code>ConnectionDraining</code>, and * <code>CrossZoneLoadBalancing</code> by either enabling or disabling them. Or, you can modify the load balancer attribute * <code>ConnectionSettings</code> by specifying an idle connection timeout value for your load balancer.</p> * <p>For more information, see the following in the <i>Classic Load Balancers Guide</i>:</p> * <ul> * <li> * <p> * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-disable-crosszone-lb.html">Cross-Zone Load Balancing</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-conn-drain.html">Connection Draining</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/access-log-collection.html">Access Logs</a> * </p> * </li> * <li> * <p> * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/config-idle-timeout.html">Idle Connection Timeout</a> * </p> * </li> * </ul> */ public modifyLoadBalancerAttributes( args: ModifyLoadBalancerAttributesCommandInput, options?: __HttpHandlerOptions ): Promise<ModifyLoadBalancerAttributesCommandOutput>; public modifyLoadBalancerAttributes( args: ModifyLoadBalancerAttributesCommandInput, cb: (err: any, data?: ModifyLoadBalancerAttributesCommandOutput) => void ): void; public modifyLoadBalancerAttributes( args: ModifyLoadBalancerAttributesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ModifyLoadBalancerAttributesCommandOutput) => void ): void; public modifyLoadBalancerAttributes( args: ModifyLoadBalancerAttributesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ModifyLoadBalancerAttributesCommandOutput) => void), cb?: (err: any, data?: ModifyLoadBalancerAttributesCommandOutput) => void ): Promise<ModifyLoadBalancerAttributesCommandOutput> | void { const command = new ModifyLoadBalancerAttributesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds the specified instances to the specified load balancer.</p> * * <p>The instance must be a running instance in the same network as the load balancer (EC2-Classic or the same VPC). If you have EC2-Classic instances and a load balancer in a VPC with ClassicLink enabled, you can link the EC2-Classic instances to that VPC and then register the linked EC2-Classic instances with the load balancer in the VPC.</p> * * <p>Note that <code>RegisterInstanceWithLoadBalancer</code> completes when the request has been registered. * Instance registration takes a little time to complete. To check the state of the registered instances, use * <a>DescribeLoadBalancers</a> or <a>DescribeInstanceHealth</a>.</p> * * <p>After the instance is registered, it starts receiving traffic * and requests from the load balancer. Any instance that is not * in one of the Availability Zones registered for the load balancer * is moved to the <code>OutOfService</code> state. If an Availability Zone * is added to the load balancer later, any instances registered with the * load balancer move to the <code>InService</code> state.</p> * * <p>To deregister instances from a load balancer, use <a>DeregisterInstancesFromLoadBalancer</a>.</p> * * <p>For more information, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-deregister-register-instances.html">Register or De-Register EC2 Instances</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public registerInstancesWithLoadBalancer( args: RegisterInstancesWithLoadBalancerCommandInput, options?: __HttpHandlerOptions ): Promise<RegisterInstancesWithLoadBalancerCommandOutput>; public registerInstancesWithLoadBalancer( args: RegisterInstancesWithLoadBalancerCommandInput, cb: (err: any, data?: RegisterInstancesWithLoadBalancerCommandOutput) => void ): void; public registerInstancesWithLoadBalancer( args: RegisterInstancesWithLoadBalancerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RegisterInstancesWithLoadBalancerCommandOutput) => void ): void; public registerInstancesWithLoadBalancer( args: RegisterInstancesWithLoadBalancerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterInstancesWithLoadBalancerCommandOutput) => void), cb?: (err: any, data?: RegisterInstancesWithLoadBalancerCommandOutput) => void ): Promise<RegisterInstancesWithLoadBalancerCommandOutput> | void { const command = new RegisterInstancesWithLoadBalancerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes one or more tags from the specified load balancer.</p> */ public removeTags(args: RemoveTagsCommandInput, options?: __HttpHandlerOptions): Promise<RemoveTagsCommandOutput>; public removeTags(args: RemoveTagsCommandInput, cb: (err: any, data?: RemoveTagsCommandOutput) => void): void; public removeTags( args: RemoveTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveTagsCommandOutput) => void ): void; public removeTags( args: RemoveTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveTagsCommandOutput) => void), cb?: (err: any, data?: RemoveTagsCommandOutput) => void ): Promise<RemoveTagsCommandOutput> | void { const command = new RemoveTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Sets the certificate that terminates the specified listener's SSL connections. The specified certificate replaces any prior certificate that was used on the same load balancer and port.</p> * * <p>For more information about updating your SSL certificate, see * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-update-ssl-cert.html">Replace the SSL Certificate for Your Load Balancer</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public setLoadBalancerListenerSSLCertificate( args: SetLoadBalancerListenerSSLCertificateCommandInput, options?: __HttpHandlerOptions ): Promise<SetLoadBalancerListenerSSLCertificateCommandOutput>; public setLoadBalancerListenerSSLCertificate( args: SetLoadBalancerListenerSSLCertificateCommandInput, cb: (err: any, data?: SetLoadBalancerListenerSSLCertificateCommandOutput) => void ): void; public setLoadBalancerListenerSSLCertificate( args: SetLoadBalancerListenerSSLCertificateCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SetLoadBalancerListenerSSLCertificateCommandOutput) => void ): void; public setLoadBalancerListenerSSLCertificate( args: SetLoadBalancerListenerSSLCertificateCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: SetLoadBalancerListenerSSLCertificateCommandOutput) => void), cb?: (err: any, data?: SetLoadBalancerListenerSSLCertificateCommandOutput) => void ): Promise<SetLoadBalancerListenerSSLCertificateCommandOutput> | void { const command = new SetLoadBalancerListenerSSLCertificateCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Replaces the set of policies associated with the specified port on which the EC2 instance is listening with a new set of policies. * At this time, only the back-end server authentication policy type can be applied to the instance ports; this policy type is composed of multiple public key policies.</p> * <p>Each time you use <code>SetLoadBalancerPoliciesForBackendServer</code> to enable the policies, * use the <code>PolicyNames</code> parameter to list the policies that you want to enable.</p> * <p>You can use <a>DescribeLoadBalancers</a> or <a>DescribeLoadBalancerPolicies</a> to verify that the policy * is associated with the EC2 instance.</p> * * <p>For more information about enabling back-end instance authentication, see <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-create-https-ssl-load-balancer.html#configure_backendauth_clt">Configure Back-end Instance Authentication</a> * in the <i>Classic Load Balancers Guide</i>. For more information about Proxy Protocol, see * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/enable-proxy-protocol.html">Configure Proxy Protocol Support</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public setLoadBalancerPoliciesForBackendServer( args: SetLoadBalancerPoliciesForBackendServerCommandInput, options?: __HttpHandlerOptions ): Promise<SetLoadBalancerPoliciesForBackendServerCommandOutput>; public setLoadBalancerPoliciesForBackendServer( args: SetLoadBalancerPoliciesForBackendServerCommandInput, cb: (err: any, data?: SetLoadBalancerPoliciesForBackendServerCommandOutput) => void ): void; public setLoadBalancerPoliciesForBackendServer( args: SetLoadBalancerPoliciesForBackendServerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SetLoadBalancerPoliciesForBackendServerCommandOutput) => void ): void; public setLoadBalancerPoliciesForBackendServer( args: SetLoadBalancerPoliciesForBackendServerCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: SetLoadBalancerPoliciesForBackendServerCommandOutput) => void), cb?: (err: any, data?: SetLoadBalancerPoliciesForBackendServerCommandOutput) => void ): Promise<SetLoadBalancerPoliciesForBackendServerCommandOutput> | void { const command = new SetLoadBalancerPoliciesForBackendServerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Replaces the current set of policies for the specified load balancer port with the specified set of policies.</p> * <p>To enable back-end server authentication, use <a>SetLoadBalancerPoliciesForBackendServer</a>.</p> * <p>For more information about setting policies, see * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/ssl-config-update.html">Update the SSL Negotiation Configuration</a>, * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-sticky-sessions.html#enable-sticky-sessions-duration">Duration-Based Session Stickiness</a>, and * <a href="https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/elb-sticky-sessions.html#enable-sticky-sessions-application">Application-Controlled Session Stickiness</a> * in the <i>Classic Load Balancers Guide</i>.</p> */ public setLoadBalancerPoliciesOfListener( args: SetLoadBalancerPoliciesOfListenerCommandInput, options?: __HttpHandlerOptions ): Promise<SetLoadBalancerPoliciesOfListenerCommandOutput>; public setLoadBalancerPoliciesOfListener( args: SetLoadBalancerPoliciesOfListenerCommandInput, cb: (err: any, data?: SetLoadBalancerPoliciesOfListenerCommandOutput) => void ): void; public setLoadBalancerPoliciesOfListener( args: SetLoadBalancerPoliciesOfListenerCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: SetLoadBalancerPoliciesOfListenerCommandOutput) => void ): void; public setLoadBalancerPoliciesOfListener( args: SetLoadBalancerPoliciesOfListenerCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetLoadBalancerPoliciesOfListenerCommandOutput) => void), cb?: (err: any, data?: SetLoadBalancerPoliciesOfListenerCommandOutput) => void ): Promise<SetLoadBalancerPoliciesOfListenerCommandOutput> | void { const command = new SetLoadBalancerPoliciesOfListenerCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import * as should from "should"; import { redirectToFile } from "node-opcua-debug/nodeJS"; import { BaseUAObject, DataTypeFactory } from "node-opcua-factory"; import { makeExpandedNodeId } from "node-opcua-nodeid"; import { getObjectClassName } from "node-opcua-utils"; import { compare_obj_by_encoding, encode_decode_round_trip_test } from "node-opcua-packet-analyzer/dist/test_helpers"; import { BinaryStream } from "node-opcua-binary-stream"; import { analyze_object_binary_encoding } from "node-opcua-packet-analyzer"; import { AnyConstructorFunc, createDynamicObjectConstructor, getOrCreateStructuredTypeSchema, MapDataTypeAndEncodingIdProvider, StructureTypeRaw, TypeDictionary } from "../source"; import { MockProvider } from "./mock_id_provider"; const a = BaseUAObject; const typeDictionary = new TypeDictionary(); const Person_Schema: StructureTypeRaw = { baseType: "ExtensionObject", name: "Person", fields: [ { name: "lastName", fieldType: "opc:CharArray" }, { name: "address", fieldType: "opc:CharArray" }, { name: "age", fieldType: "opc:Int32", defaultValue: 25 } ] }; const Role_Schema = { baseType: "ExtensionObject", name: "Role", fields: [ { name: "title", fieldType: "opc:CharArray" }, { name: "description", fieldType: "opc:CharArray" } ] }; const Employee_Schema = { baseType: "Person", name: "Employee", fields: [ { name: "role", fieldType: "tns:Role" }, { name: "service", fieldType: "opc:CharArray" }, { name: "salary", fieldType: "opc:Double", defaultValue: 1000.0 } ] }; const Company_Schema = { baseType: "ExtensionObject", name: "Company", fields: [ { name: "name", fieldType: "opc:CharArray" }, { name: "employees", isArray: true, fieldType: "tns:Employee" }, { name: "companyValues", isArray: true, fieldType: "opc:CharArray" } ] }; const FakeBlob_Schema = { name: "FakeBlob", fields: [ { name: "name", fieldType: "String" }, { name: "buffer0", fieldType: "ByteString" }, { name: "buffer1", fieldType: "ByteString" } ] }; const dataTypeFactory = new DataTypeFactory([]); const idProvider = new MockProvider(); function p(structuredType: StructureTypeRaw, typeDictionary1: TypeDictionary): AnyConstructorFunc { typeDictionary1.addRaw(structuredType); const schema = getOrCreateStructuredTypeSchema(structuredType.name, typeDictionary1, dataTypeFactory, idProvider); return createDynamicObjectConstructor(schema, dataTypeFactory); } const Person = p(Person_Schema, typeDictionary); const Role = p(Role_Schema, typeDictionary); const Employee = p(Employee_Schema, typeDictionary); const Company = p(Company_Schema, typeDictionary); const FakeBlob = p(FakeBlob_Schema, typeDictionary); describe("Factories: construction", () => { it("a schema should provide a list of possible fields", () => { Person.possibleFields.should.eql(["lastName", "address", "age"]); Employee.possibleFields.should.eql(["lastName", "address", "age", "role", "service", "salary"]); }); }); describe("testing Factory", () => { it("FF1 - should construct a new object from a simple Class Description", () => { const person = new Person(); person.should.have.property("lastName"); person.should.have.property("address"); person.should.have.property("age"); person.lastName.should.equal(""); person.address.should.equal(""); person.age.should.equal(25); }); it("FF2 - should construct a new object with options from a simple Class Description", () => { const person = new Person({ lastName: "Joe" }); person.lastName.should.equal("Joe"); person.address.should.equal(""); person.age.should.equal(25); }); it("FF3 - should construct a new object from a complex Class Description", () => { const employee = new Employee({ lastName: "John", service: "R&D", role: { title: "developer", description: "create the awesome" } }); employee.should.be.instanceOf(Person); employee.should.be.instanceOf(Employee); employee.should.have.property("role"); employee.should.have.property("service"); employee.should.have.property("salary"); // due to inheritance, employee shall be a person employee.should.have.property("lastName"); employee.should.have.property("address"); employee.should.have.property("age"); employee.lastName.should.equal("John"); employee.address.should.equal(""); employee.age.should.equal(25); employee.service.should.equal("R&D"); employee.salary.should.equal(1000.0); employee.role.should.be.instanceOf(Role); employee.role.title.should.equal("developer"); employee.role.description.should.equal("create the awesome"); }); it("FF4 - should encode and decode a simple object created from the Factory", () => { const person = new Person({ lastName: "Joe" }); person.age = 50; person.address = "Paris"; const person_reloaded = encode_decode_round_trip_test(person); person.lastName.should.equal(person_reloaded.lastName); person.age.should.equal(person_reloaded.age); person.address.should.equal(person_reloaded.address); }); it("FF5 - should encode and decode a composite object created from the Factory", () => { const employee = new Employee({ lastName: "John", service: "R&D" }); encode_decode_round_trip_test(employee); console.log(employee.toJSON()); employee.toJSON().should.eql({ address: "", age: 25, lastName: "John", role: { description: "", title: "" }, salary: 1000, service: "R&D" }); }); it("FF6 - should encode and decode a composite object containing an array", () => { const company = new Company({ name: "ACME" }); company.employees.length.should.equal(0); const employee = new Employee({ lastName: "John", service: "R&D" }); company.employees.push(employee); company.employees.push(new Employee({ lastName: "Peter", service: "R&D" })); company.employees.length.should.equal(2); encode_decode_round_trip_test(company); }); it("FF7 - should create an Object with a containing an array of JSON object passed in the initializer", () => { const company = new Company({ name: "ACME", employees: [ { lastName: "John", age: 25, service: "R&D", role: { title: "manager", description: "" } }, { lastName: "Peter", age: 56, service: "R&D", role: { title: "engineer", description: "" } } ] }); company.employees.length.should.equal(2); company.employees[0].should.be.instanceOf(Employee); company.employees[1].should.be.instanceOf(Employee); encode_decode_round_trip_test(company); company.toJSON().should.eql({ companyValues: [], name: "ACME", employees: [ { address: "", age: 25, lastName: "John", role: { title: "manager", description: "" }, salary: 1000, service: "R&D" }, { address: "", age: 56, lastName: "Peter", role: { title: "engineer", description: "" }, salary: 1000, service: "R&D" } ] }); }); it("FF8 - should create an Object with a containing an array of string passed in the initializer", () => { const company = new Company({ name: "ACME", companyValues: [ "A commitment to sustainability and to acting in an environmentally friendly way", "A commitment to innovation and excellence.", "Encouraging employees to take initiative and give the best." ] }); company.companyValues.length.should.equal(3); company.companyValues[0].should.equal("A commitment to sustainability and to acting in an environmentally friendly way"); company.should.have.property("employees"); encode_decode_round_trip_test(company); }); }); describe("Factories: testing encodingDefaultBinary and constructObject", () => { it("XF1 a factory object should have a encodingDefaultBinary", () => { const company = new Company({ name: "ACME" }); company.constructor.schema.dataTypeNodeId .toString() .should.eql(makeExpandedNodeId(Company.schema.dataTypeNodeId).toString()); company.constructor.encodingDefaultBinary .toString() .should.eql(makeExpandedNodeId(Company.schema.encodingDefaultBinary).toString()); company.constructor.encodingDefaultXml .toString() .should.eql(makeExpandedNodeId(Company.schema.encodingDefaultXml!).toString()); // company.constructor.encodingDefaultJson.toString().should.eql(makeExpandedNodeId(Company.schema.encodingDefaultJson!).toString()); }); xit("XF2 should create a object from a encodingDefaultBinaryId", () => { should.exist(Company.schema.encodingDefaultBinary); const obj = dataTypeFactory.constructObject(Company.schema.encodingDefaultBinary!); console.log(obj); (obj.constructor as any).schema.name.should.equal("Company"); getObjectClassName(obj).should.equal("Object"); }); it("XF3 should pretty print an object ", (done) => { redirectToFile( "pretty_print.log", () => { const company = new Company({ name: "ACME" }); const employee = new Employee({ lastName: "John", service: "R&D" }); company.employees.push(employee); company.employees.push(new Employee({ lastName: "Peter", service: "R&D" })); const str = company.explore(); console.log(str); console.log(company.toString()); }, done ); }); it("XF4 - should encode and decode a Object containing ByteString", async () => { const blob = new FakeBlob({ buffer0: Buffer.alloc(0), buffer1: Buffer.alloc(1024) }); encode_decode_round_trip_test(blob); }); it("XF5 - should clone an object ", () => { const company = new Company({ name: "ACME" }); const employee = new Employee({ lastName: "John", service: "R&D" }); company.employees.push(employee); company.employees.push(new Employee({ lastName: "Peter", service: "R&D" })); const company_copy = company.clone(); company_copy.constructor.name.should.eql("Company"); company_copy.name.should.eql("ACME"); company_copy.employees.length.should.eql(2); company_copy.employees[0].lastName.should.eql("John"); company_copy.employees[0].service.should.eql("R&D"); company_copy.employees[1].lastName.should.eql("Peter"); company_copy.employees[1].service.should.eql("R&D"); compare_obj_by_encoding(company, company_copy); }); it("XF6 - should analyse a encoded object", (done) => { const company = new Company({ name: "ACME", employees: [ { lastName: "John", age: 25, service: "R&D" }, { lastName: "Peter", age: 56, service: "R&D" } ] }); const stream = new BinaryStream(company.binaryStoreSize()); company.encode(stream); redirectToFile( "analyze_object_binary_encoding", () => { analyze_object_binary_encoding(company); }, done ); }); });
the_stack
import { Logger, LogLevel } from "@pnp/logging"; import { IWeb } from "@pnp/sp/webs"; import "@pnp/sp/lists"; import "@pnp/sp/fields"; import "@pnp/sp/views"; import "@pnp/sp/site-groups"; import "@pnp/sp/security"; import { CustomListNames } from "../models/Enums"; import { params } from "./Parameters"; export interface IConfigService { validatePlaylists(owner: boolean): Promise<boolean>; validateAssets(owner: boolean): Promise<boolean>; validateConfig(owner: boolean): Promise<boolean>; } export class ConfigService implements IConfigService { private LOG_SOURCE: string = "ConfigService"; private _learningWeb: IWeb; constructor(learningWeb: IWeb) { this._learningWeb = learningWeb; } public async validatePlaylists(owner: boolean): Promise<boolean> { try { let playlistCheck = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.select("Title").filter("Title eq 'JSONData'").get<{ Title: string }[]>(); let playlistCheckCDN = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.select("Title").filter("Title eq 'CDN'").get<{ Title: string }[]>(); if (playlistCheck.length !== 1 || playlistCheckCDN.length !== 1) { if (owner) { try { //List exists, field doesn't if (playlistCheck.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).defaultView; await view.fields.add("JSONData"); Logger.write(`Adding JSONData field - ${this.LOG_SOURCE} (validatePlaylists)`, LogLevel.Warning); } if (playlistCheckCDN.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).defaultView; await view.fields.add("CDN"); Logger.write(`Adding CDN field - ${this.LOG_SOURCE} (validatePlaylists)`, LogLevel.Warning); //Set all existing entries to "Default" let playlists = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).items.top(5000).select("Id").get<{ Id: string }[]>(); for (let i = 0; i < playlists.length; i++) { await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).items.getById(+playlists[i].Id).update({ CDN: 'Default' }); } } } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validatePlaylists) - ${err}`, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validatePlaylists) -- User does not have appropriate rights to create field in custom playlists list.`, LogLevel.Error); return false; } } } catch (err) { //Assume list doesn't exist if (owner) { try { await this._learningWeb.lists.add(CustomListNames.customPlaylistsName, "Microsoft Custom Learning - Custom Playlists", 100, true); await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customPlaylistsName).defaultView; await view.fields.add("JSONData"); await view.fields.add("CDN"); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validatePlaylists) - ${err} - `, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validatePlaylists) -- User does not have appropriate rights to create custom playlists list.`, LogLevel.Error); return false; } } return true; } public async validateAssets(owner: boolean): Promise<boolean> { try { let assetsCheck = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.select("Title").filter("Title eq 'JSONData'").get<{ Title: string }[]>(); let assetsCheckCDN = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.select("Title").filter("Title eq 'CDN'").get<{ Title: string }[]>(); if (assetsCheck.length !== 1 || assetsCheckCDN.length !== 1) { if (owner) { try { //List exists, field doesn't if (assetsCheck.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).defaultView; await view.fields.add("JSONData"); Logger.write(`Adding JSONData field - ${this.LOG_SOURCE} (validateAssets)`, LogLevel.Warning); } if (assetsCheckCDN.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).defaultView; await view.fields.add("CDN"); Logger.write(`Adding CDN field - ${this.LOG_SOURCE} (validateAssets)`, LogLevel.Warning); //Set all existing entries to "Default" let assets = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).items.top(5000).select("Id").get<{ Id: string }[]>(); for (let i = 0; i < assets.length; i++) { await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).items.getById(+assets[i].Id).update({ CDN: 'Default' }); } } } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateAssets) - ${err} - `, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateAssets) -- User does not have appropriate rights to create field in custom assets list.`, LogLevel.Error); return false; } } } catch (err) { //Assume list doesn't exist if (owner) { try { await this._learningWeb.lists.add(CustomListNames.customAssetsName, "Microsoft Custom Learning - Custom Assets", 100, true); await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customAssetsName).defaultView; await view.fields.add("JSONData"); await view.fields.add("CDN"); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateAssets) - ${err} - `, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateAssets) -- User does not have appropriate rights to create custom assets list.`, LogLevel.Error); return false; } } return true; } private async getRoleInformation(): Promise<number[]> { let retVal: number[] = []; try { let targetGroup = await this._learningWeb.associatedVisitorGroup(); let targetGroupId = targetGroup.Id; let roleDefinition = await this._learningWeb.roleDefinitions.getByType(3).get(); let roleDefinitionId = roleDefinition.Id; retVal.push(targetGroupId); retVal.push(roleDefinitionId); } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (getRoleInformation) - ${err}`, LogLevel.Error); } return retVal; } public async validateConfig(owner: boolean): Promise<boolean> { try { let configCheck = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.select("Title").filter("Title eq 'JSONData'").get<{ Title: string }[]>(); let configCheckCDN = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.select("Title").filter("Title eq 'CDN'").get<{ Title: string }[]>(); let configCheckLanguage = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.select("Title").filter("Title eq 'Language'").get<{ Title: string }[]>(); if (configCheck.length !== 1 || configCheckCDN.length !== 1 || configCheckLanguage.length !== 1) { if (owner) { try { //List exists, field doesn't if (configCheck.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).defaultView; await view.fields.add("JSONData"); Logger.write(`Adding JSONData field - ${this.LOG_SOURCE} (validateConfig)`, LogLevel.Warning); } if (configCheckCDN.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).defaultView; await view.fields.add("CDN"); Logger.write(`Adding CDN field - ${this.LOG_SOURCE} (validateConfig)`, LogLevel.Warning); //Set all existing entries to "Default" let configs = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).items.top(5000).select("Id").get<{ Id: string }[]>(); for (let i = 0; i < configs.length; i++) { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).items.getById(+configs[i].Id).update({ CDN: 'Default' }); } } if (configCheckLanguage.length !== 1) { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("Language", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).defaultView; await view.fields.add("Language"); Logger.write(`Adding Language field - ${this.LOG_SOURCE} (validateConfig)`, LogLevel.Warning); //Set all existing entries to default language let configs = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).items.top(5000).select("Id", "Title").get<{ Id: string, Title: string }[]>(); for (let i = 0; i < configs.length; i++) { if (configs[i].Title === "CustomConfig") { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).items.getById(+configs[i].Id).update({ Language: params.defaultLanguage }); } } } } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateConfig) - ${err}`, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateConfig) -- User does not have appropriate rights to create field in custom config list.`, LogLevel.Error); return false; } } } catch (err) { //Assume list doesn't exist if (owner) { try { await this._learningWeb.lists.add(CustomListNames.customConfigName, "Microsoft Custom Learning - Custom Config", 100, true); await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("JSONData", "SP.Field", { "FieldTypeKind": 3 }); await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("CDN", "SP.Field", { "FieldTypeKind": 2 }); await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).fields.add("Language", "SP.Field", { "FieldTypeKind": 2 }); let view = await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).defaultView; await view.fields.add("JSONData"); await view.fields.add("CDN"); await view.fields.add("Language"); await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).breakRoleInheritance(true); let configPermissions = await this.getRoleInformation(); if (configPermissions.length > 0) { await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).roleAssignments.getById(configPermissions[0]).delete(); await this._learningWeb.lists.getByTitle(CustomListNames.customConfigName).roleAssignments.add(configPermissions[0], configPermissions[1]); } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateConfig) - ${CustomListNames.customConfigName} list created but permissions could not be set.`, LogLevel.Error); return false; } } catch (err) { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateConfig) - ${err}`, LogLevel.Error); return false; } } else { Logger.write(`🎓 M365LP:${this.LOG_SOURCE} (validateConfig) -- User does not have appropriate rights to create custom config list.`, LogLevel.Error); return false; } } return true; } }
the_stack
import { HalfEdge, HalfEdgeGraph, HalfEdgeMask } from "./Graph"; /** @packageDocumentation * @module Topology */ /** * A class to manage a set of edges as both (a) an array of possible members and (b) mask bits. * * A half edge is "in the MarkSet" if its mask is set. * * The MarkSet array is a superset of the half edges in the set. * * Entry of a HalfEdge into the set is indicated by both * * adding the HalfEdge to the array * * setting the mask on the half edge, edge, face, or vertex * * Half edges can "go out of the MarkSet" if the mask is cleared. * * This clearing can happen independently of the array management. * * Hence the array can contain half edges that are no longer in the MarkSet * * the "remove" methods monitor this. * * Derived classes expand this concept for edge, vertex, or face MarkSets. * * a single representative of an edge, vertex, or face is entered to the array * * all edges around the edge, vertex, or face are marked with the mask * * Hence the array contains one or more representatives of the edge, face, or vertex * * This allows quick query for both: * * Testing the mask gives constant time test of whether a HalfEdge is in the set * * access through the array gives direct access to the HalfEdge pointers * @internal */ export abstract class AbstractHalfEdgeGraphMarkSet { private _graph: HalfEdgeGraph; private _candidates: HalfEdge[]; protected _mask: HalfEdgeMask; protected constructor(graph: HalfEdgeGraph, mask: HalfEdgeMask) { this._graph = graph; this._candidates = []; this._mask = mask; this._graph.clearMask(mask); } /** remove all nodes from the set. * * This pops from the array, clearing masks as the pop. * * Note that it does NOT walk the entire graph to clear masks. */ public clear() { for (; undefined !== this.chooseAndRemoveAny();) { } } /** * count the number of active members. * * This is the number of HalfEdges which are (a) in the array and (b) masked. */ public getLength(): number { let n = 0; for (const candidate of this._candidates) { if (candidate.isMaskSet(this._mask)) n++; } return n; } /** * Return the number of candidates. * * This may be more than `getLength ()` * * This will typically only be called by the iterator. */ public getNumCandidates(): number { return this._candidates.length; } /** Read property accessor: return the graph */ public get graph(): HalfEdgeGraph { return this._graph; } /** return borrowed assets (the mask!) to the graph. */ public teardown() { this._graph.dropMask(this._mask); this._candidates.length = 0; // this._graph = undefined; } /** (Read property) return the mask used to mark members of the set. */ public get mask(): HalfEdgeMask { return this._mask; } /** pop and return the last node out of the array, without testing if it is still marked. */ protected popAndReturn(): HalfEdge | undefined { const n = this._candidates.length; if (n === 0) return undefined; const node = this._candidates[n - 1]; this._candidates.pop(); return node; } /** * * read at an index in the candidates array. * * if that candidate has the mask, return it. * * otherwise return undefined. * * REMARK: This is only to be called by the iterator. */ public getAtIndex(index: number): HalfEdge | undefined { if (index >= 0 && index < this._candidates.length) { const candidate = this._candidates[index]; if (candidate.isMaskSet(this._mask)) return candidate; } return undefined; } /** Add a node to the set. This means * * Set the mask * * push the node on the array * * (BUT!) If the node already has the mask, do nothing. * * This base class method affects only the single given HalfEdge. * * Derived classes for edge, face, and vertex will override this method and also set the mask around the larger structures. * @returns true if the HalfEdge is a new member of the set, false if it was already in the set. */ public addToSet(candidate: HalfEdge) { if (candidate.isMaskSet(this._mask)) return false; this._candidates.push(candidate); this.setMaskInScope(candidate); return true; } /** Test if `candidate` is already in the set. * * This examines only the mask. */ public isCandidateInSet(candidate: HalfEdge): boolean { return candidate.isMaskSet(this._mask); } /** * * If the candidate is not marked as a member of the MarkSet, do nothing. * * If the candidate is marked: * * clear the mask * * but do NOT search the array. * * As the array is searched, the candidate will appear and be ignored because the mask is not set. * @param candidate * @return true if the candidate was a member (an hence removed), false if the candidate was not masked. */ public removeFromSet(candidate: HalfEdge): boolean { if (!candidate.isMaskSet(this._mask)) return false; this.clearMaskInScope(candidate); return true; } /** * * Search the array to find any current set member * * If found, clear its mask and return it. * * If unmasked HalfEdges are found in the array, they are removed from the array. */ public chooseAndRemoveAny(): HalfEdge | undefined { for (; ;) { const candidate = this.popAndReturn(); if (!candidate) return undefined; if (this.removeFromSet(candidate)) return candidate; } } /** Set mask on candidate -- i.e. edge, face, vertex, or single half edge as required. * * Base class only changes the candidate mask. * * Derived classes change more masks around edge, face, or vertex. */ protected abstract setMaskInScope(candidate: HalfEdge | undefined): void; /** Clear mask on candidate -- i.e. edge, face, vertex, or single half edge as required. * * Base class only changes the candidate mask. * * Derived classes change more masks around edge, face, or vertex. */ protected abstract clearMaskInScope(candidate: HalfEdge | undefined): void; /** * Return the number of half edges that would be set/cleared when dealing with this candidate. * * This is always 1 for HalfEdgeMarkSet * @param candidate */ public abstract countHalfEdgesAroundCandidate(candidate: HalfEdge | undefined): number; /** Create an iterator over member HalfEdges */ public [Symbol.iterator](): IterableIterator<HalfEdge> { return new IterableHalfEdgeMarkSetIterator(this); } /** * * visit all half edges around face. * * Add each to mark set. */ public addAroundFace(seed: HalfEdge): void { let p = seed; do { this.addToSet(p); p = p.faceSuccessor; } while (p !== seed); } /** * * visit all half edges around vertex. * * Add each to mark set. */ public addAroundVertex(seed: HalfEdge): void { let p = seed; do { this.addToSet(p); p = p.vertexSuccessor; } while (p !== seed); } } /** * AbstractHalfEdgeGraphMarkSet specialized to manage the masks on individual half edges * @internal */ export class MarkedHalfEdgeSt extends AbstractHalfEdgeGraphMarkSet { constructor(graph: HalfEdgeGraph, mask: HalfEdgeMask) { super(graph, mask); } /** Create a new 'HalfEdgeMarkSet', operating on half edges with only themselves as scope. * * Returns undefined if unable to get a mask for the graph. * * Undefined return can only happen if the caller is failing to return grabbed masks. */ public static create(graph: HalfEdgeGraph): MarkedHalfEdgeSt | undefined { const mask = graph.grabMask(); if (mask === HalfEdgeMask.NULL_MASK) return undefined; return new MarkedHalfEdgeSt(graph, mask); } /** * * Set mask on candidate's edge. * * This overrides the base class implementation. */ protected setMaskInScope(candidate: HalfEdge) { candidate.setMask(this._mask); } /** * * Clear mask on candidate's edge. * * This overrides the base class implementation. */ protected clearMaskInScope(candidate: HalfEdge) { candidate.clearMask(this._mask); } /** * Return the number of half edges that would be set/cleared when dealing with this candidate. * * This is always 1 for EdgeMarkSet * * return 0 for undefined candidate * @param candidate */ public countHalfEdgesAroundCandidate(candidate: HalfEdge | undefined): number { if (!candidate) return 0; return 1; } } /** * AbstractHalfEdgeGraphMarkSet specialized to manage the mask on both sides of edges. * @internal */ export class MarkedEdgeSet extends AbstractHalfEdgeGraphMarkSet { constructor(graph: HalfEdgeGraph, mask: HalfEdgeMask) { super(graph, mask); } /** Create a new 'HalfEdgeMarkSet', operating on half edges with only themselves as scope. * * Returns undefined if unable to get a mask for the graph. * * Undefined return can only happen if the caller is failing to return grabbed masks. */ public static create(graph: HalfEdgeGraph): MarkedEdgeSet | undefined { const mask = graph.grabMask(); if (mask === HalfEdgeMask.NULL_MASK) return undefined; return new MarkedEdgeSet(graph, mask); } /** * * Set mask on candidate's edge. * * This overrides the base class implementation. */ protected setMaskInScope(candidate: HalfEdge) { candidate.setMaskAroundEdge(this._mask); } /** * * Clear mask on candidate's edge. * * This overrides the base class implementation. */ protected clearMaskInScope(candidate: HalfEdge) { candidate.clearMaskAroundEdge(this._mask); } /** * Return the number of half edges that would be set/cleared when dealing with this candidate. * * This is always 2 for EdgeMarkSet * @param candidate */ public countHalfEdgesAroundCandidate(candidate: HalfEdge | undefined): number { if (!candidate) return 0; return 2; } } /** * AbstractHalfEdgeGraphMarkSet specialized to manage the mask around faces * @internal */ export class MarkedFaceSet extends AbstractHalfEdgeGraphMarkSet { constructor(graph: HalfEdgeGraph, mask: HalfEdgeMask) { super(graph, mask); } /** Create a new 'HalfEdgeMarkSet', operating on half edges with only themselves as scope. * * Returns undefined if unable to get a mask for the graph. * * Undefined return can only happen if the caller is failing to return grabbed masks. */ public static create(graph: HalfEdgeGraph): MarkedFaceSet | undefined { const mask = graph.grabMask(); if (mask === HalfEdgeMask.NULL_MASK) return undefined; return new MarkedFaceSet(graph, mask); } /** * * Set mask on (all nodes around) candidate's face * * This overrides the base class implementation. */ protected setMaskInScope(candidate: HalfEdge) { candidate.setMaskAroundFace(this._mask); } /** * * Clear mask on (all nodes around) candidate's face. * * This overrides the base class implementation. */ protected clearMaskInScope(candidate: HalfEdge) { candidate.clearMaskAroundFace(this._mask); } /** * Return the number of half edges that would be set/cleared when dealing with this candidate. * * This is the "aroundFace" count. * @param candidate */ public countHalfEdgesAroundCandidate(candidate: HalfEdge | undefined): number { if (!candidate) return 0; return candidate.countEdgesAroundFace(); } } /** * AbstractHalfEdgeGraphMarkSet specialized to manage the mask around faces * @internal */ export class MarkedVertexSet extends AbstractHalfEdgeGraphMarkSet { constructor(graph: HalfEdgeGraph, mask: HalfEdgeMask) { super(graph, mask); } /** Create a new 'HalfEdgeMarkSet', operating on half edges with only themselves as scope. * * Returns undefined if unable to get a mask for the graph. * * Undefined return can only happen if the caller is failing to return grabbed masks. */ public static create(graph: HalfEdgeGraph): MarkedVertexSet | undefined { const mask = graph.grabMask(); if (mask === HalfEdgeMask.NULL_MASK) return undefined; return new MarkedVertexSet(graph, mask); } /** * * Set mask on (all nodes around) candidate's face * * This overrides the base class implementation. */ protected setMaskInScope(candidate: HalfEdge) { candidate.setMaskAroundVertex(this._mask); } /** * * Clear mask on (all nodes around) candidate's face. * * This overrides the base class implementation. */ protected clearMaskInScope(candidate: HalfEdge) { candidate.clearMaskAroundVertex(this._mask); } /** * Return the number of half edges that would be set/cleared when dealing with this candidate. * * This is the "aroundVertex" count. * @param candidate */ public countHalfEdgesAroundCandidate(candidate: HalfEdge | undefined): number { if (!candidate) return 0; return candidate.countEdgesAroundVertex(); } } /** * Class to act as an iterator over points in a markSet. * * Internal data is: * * pointer to the parent markSet * * index of index of the next point to read. * * the parent markSet class */ class IterableHalfEdgeMarkSetIterator implements Iterator<HalfEdge> { private _markSet: AbstractHalfEdgeGraphMarkSet; private _nextReadIndex: number; public constructor(markSet: AbstractHalfEdgeGraphMarkSet) { this._markSet = markSet; this._nextReadIndex = 0; } public next(): IteratorResult<HalfEdge> { const n = this._markSet.getNumCandidates(); // Walk over candidates that have been quietly de-masked while (this._nextReadIndex < n) { const p = this._markSet.getAtIndex(this._nextReadIndex++); if (p !== undefined) return { done: false, value: p }; } return { done: true, value: undefined } as any as IteratorResult<HalfEdge>; } public [Symbol.iterator](): IterableIterator<HalfEdge> { return this; } }
the_stack
import { malloc, free, realloc, listFreeBlocks, listAllocatedBlocks, stats, allocatorInit, } from "./functional"; import type { AllocatorState } from "./functionalInterfaces"; let allocatorState: AllocatorState; describe("next gen", () => { beforeEach(() => { allocatorState = allocatorInit({ size: 0x200, align: 8, start: 0, end: 0x200, compact: true, split: true, minSplit: 24, }); }); test("Before any allocation", () => { expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(`Array []`); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot( `Array []` ); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 480, "free": Object { "count": 0, "size": 0, }, "top": 32, "total": 512, "used": Object { "count": 0, "size": 0, }, } `); }); describe("Allocate", () => { test("Allocate single block", () => { const allocatedPointer = malloc(allocatorState, 8); expect(allocatedPointer).toMatchInlineSnapshot(`48`); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(`Array []`); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 456, "free": Object { "count": 0, "size": 0, }, "top": 56, "total": 512, "used": Object { "count": 1, "size": 24, }, } `); }); test("Allocate 2 blocks and free the first one", () => { const allocatedPointer1 = malloc(allocatorState, 8); const allocatedPointer2 = malloc(allocatorState, 16); expect(allocatedPointer1).toMatchInlineSnapshot(`48`); expect(allocatedPointer2).toMatchInlineSnapshot(`72`); expect(listFreeBlocks(allocatorState)).toHaveLength(0); expect(listAllocatedBlocks(allocatorState)).toHaveLength(2); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 16, "next": 32, "prev": 0, "size": 32, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 56, "size": 24, }, ] `); const statsBeforeFree = stats(allocatorState); expect(statsBeforeFree); free(allocatorState, allocatedPointer1); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listAllocatedBlocks(allocatorState)).toHaveLength(1); const statsAfterFree = stats(allocatorState); expect(statsAfterFree.top).toBe(statsBeforeFree.top); expect(statsAfterFree).toMatchInlineSnapshot(` Object { "available": 448, "free": Object { "count": 1, "size": 24, }, "top": 88, "total": 512, "used": Object { "count": 1, "size": 32, }, } `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 16, "next": 0, "prev": 0, "size": 32, }, ] `); }); test("Allocate 3 blocks, free the 2nd block", () => { const allocatedPointer1 = malloc(allocatorState, 8); const allocatedPointer2 = malloc(allocatorState, 8); const allocatedPointer3 = malloc(allocatorState, 8); expect(allocatedPointer1).toMatchInlineSnapshot(`48`); expect(allocatedPointer2).toMatchInlineSnapshot(`72`); expect(allocatedPointer3).toMatchInlineSnapshot(`96`); free(allocatorState, allocatedPointer2); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 432, "free": Object { "count": 1, "size": 24, }, "top": 104, "total": 512, "used": Object { "count": 2, "size": 48, }, } `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 80, "dataPointer": 96, "dataSize": 8, "next": 32, "prev": 0, "size": 24, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 80, "size": 24, }, ] `); }); test("Allocate 3 blocks, free the 1st block", () => { const allocatedPointer1 = malloc(allocatorState, 8); const allocatedPointer2 = malloc(allocatorState, 8); const allocatedPointer3 = malloc(allocatorState, 8); expect(allocatedPointer1).toMatchInlineSnapshot(`48`); expect(allocatedPointer2).toMatchInlineSnapshot(`72`); expect(allocatedPointer3).toMatchInlineSnapshot(`96`); free(allocatorState, allocatedPointer1); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 432, "free": Object { "count": 1, "size": 24, }, "top": 104, "total": 512, "used": Object { "count": 2, "size": 48, }, } `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 80, "dataPointer": 96, "dataSize": 8, "next": 56, "prev": 0, "size": 24, }, Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 0, "prev": 80, "size": 24, }, ] `); }); test("Allocate 3 blocks, free the 3rd block", () => { const allocatedPointer1 = malloc(allocatorState, 8); const allocatedPointer2 = malloc(allocatorState, 8); const allocatedPointer3 = malloc(allocatorState, 8); expect(allocatedPointer1).toMatchInlineSnapshot(`48`); expect(allocatedPointer2).toMatchInlineSnapshot(`72`); expect(allocatedPointer3).toMatchInlineSnapshot(`96`); expect(stats(allocatorState).top).toBe(104); free(allocatorState, allocatedPointer3); // The freed block is merged into top expect(stats(allocatorState).top).toBe(80); expect(listFreeBlocks(allocatorState)).toHaveLength(0); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 432, "free": Object { "count": 0, "size": 0, }, "top": 80, "total": 512, "used": Object { "count": 2, "size": 48, }, } `); expect(listFreeBlocks(allocatorState)).toHaveLength(0); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 32, "prev": 0, "size": 24, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 56, "size": 24, }, ] `); }); }); describe("Block reuse", () => { test("Simple block reuse", () => { const allocatedPointer1 = malloc(allocatorState, 8); const allocatedPointer2 = malloc(allocatorState, 8); const allocatedPointer3 = malloc(allocatorState, 8); expect(allocatedPointer1).toMatchInlineSnapshot(`48`); expect(allocatedPointer2).toMatchInlineSnapshot(`72`); expect(allocatedPointer3).toMatchInlineSnapshot(`96`); const statsBeforeFree = stats(allocatorState); free(allocatorState, allocatedPointer2); const statsAfterFree = stats(allocatorState); expect(statsAfterFree.top).toBe(statsBeforeFree.top); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 432, "free": Object { "count": 1, "size": 24, }, "top": 104, "total": 512, "used": Object { "count": 2, "size": 48, }, } `); const blockThatShouldComeFromReuse = malloc(allocatorState, 8); expect(blockThatShouldComeFromReuse).toBe(allocatedPointer2); expect(stats(allocatorState)).toMatchInlineSnapshot(` Object { "available": 408, "free": Object { "count": 0, "size": 0, }, "top": 104, "total": 512, "used": Object { "count": 3, "size": 72, }, } `); expect(listFreeBlocks(allocatorState)).toHaveLength(0); }); test("Block reuse / allocate 10, free 4, allocate 3", () => { const allocations = Array.from({ length: 10 }, () => { return malloc(allocatorState, 8); }); expect(listAllocatedBlocks(allocatorState)).toHaveLength(10); const freeFrom = 0; const howMuchToFree = 4; for (let i = 0; i < howMuchToFree * 2; i += 2) { free(allocatorState, allocations[freeFrom + i]); } expect(listFreeBlocks(allocatorState)).toHaveLength(4); malloc(allocatorState, 8); malloc(allocatorState, 8); malloc(allocatorState, 8); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listAllocatedBlocks(allocatorState)).toHaveLength(9); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 8, "next": 80, "prev": 0, "size": 24, }, Object { "blockPointer": 80, "dataPointer": 96, "dataSize": 8, "next": 32, "prev": 128, "size": 24, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 248, "prev": 80, "size": 24, }, Object { "blockPointer": 248, "dataPointer": 264, "dataSize": 8, "next": 224, "prev": 32, "size": 24, }, Object { "blockPointer": 224, "dataPointer": 240, "dataSize": 8, "next": 200, "prev": 248, "size": 24, }, Object { "blockPointer": 200, "dataPointer": 216, "dataSize": 8, "next": 152, "prev": 224, "size": 24, }, Object { "blockPointer": 152, "dataPointer": 168, "dataSize": 8, "next": 104, "prev": 200, "size": 24, }, Object { "blockPointer": 104, "dataPointer": 120, "dataSize": 8, "next": 56, "prev": 152, "size": 24, }, Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 0, "prev": 104, "size": 24, }, ] `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 176, "dataPointer": 192, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); }); test("Block reuse / enlarge into top", () => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const allocated1 = malloc(allocatorState, 8); const allocated2 = malloc(allocatorState, 8); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 32, "prev": 0, "size": 24, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 56, "size": 24, }, ] `); free(allocatorState, allocated2); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(`Array []`); const shouldBeReusedBlock = malloc(allocatorState, 16); expect(shouldBeReusedBlock).toBe(allocated2); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 16, "next": 32, "prev": 0, "size": 32, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 56, "size": 24, }, ] `); expect(listFreeBlocks(allocatorState)).toHaveLength(0); }); test("Block reuse / split block", () => { const allocated1 = malloc(allocatorState, 80); // eslint-disable-next-line @typescript-eslint/no-unused-vars const allocated2 = malloc(allocatorState, 80); free(allocatorState, allocated1); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 80, "next": 0, "prev": 0, "size": 96, }, ] `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 80, "next": 0, "prev": 0, "size": 96, }, ] `); const shouldBeReused = malloc(allocatorState, 8); expect(shouldBeReused).toBe(allocated1); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 128, "prev": 0, "size": 24, }, Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 80, "next": 0, "prev": 32, "size": 96, }, ] `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 56, "next": 0, "prev": 0, "size": 72, }, ] `); }); test("Block reuse / don't split when too small", () => { const allocated1 = malloc(allocatorState, 80); // eslint-disable-next-line @typescript-eslint/no-unused-vars const allocated2 = malloc(allocatorState, 80); free(allocatorState, allocated1); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 80, "next": 0, "prev": 0, "size": 96, }, ] `); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 80, "next": 0, "prev": 0, "size": 96, }, ] `); const shouldBeReused = malloc(allocatorState, 72); expect(shouldBeReused).toBe(allocated1); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 80, "next": 128, "prev": 0, "size": 96, }, Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 80, "next": 0, "prev": 32, "size": 96, }, ] `); expect(listFreeBlocks(allocatorState)).toHaveLength(0); }); }); describe("Merge adjacent", () => { test("Merge adjacent-before blocks after free", () => { const allocations = [ malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), ]; expect(listAllocatedBlocks(allocatorState)).toHaveLength(5); expect(listFreeBlocks(allocatorState)).toHaveLength(0); free(allocatorState, allocations[2]); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 80, "dataPointer": 96, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); free(allocatorState, allocations[1]); // merge expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 32, "next": 0, "prev": 0, "size": 48, }, ] `); }); test("Merge adjacent-next blocks after free", () => { const allocations = [ malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), ]; expect(listAllocatedBlocks(allocatorState)).toHaveLength(5); expect(listFreeBlocks(allocatorState)).toHaveLength(0); free(allocatorState, allocations[1]); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 0, "prev": 0, "size": 24, }, ] `); free(allocatorState, allocations[2]); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 32, "next": 0, "prev": 0, "size": 48, }, ] `); }); test("Merge adjacent blocks after free from both sides", () => { const allocations = [ malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), ]; expect(stats(allocatorState).top).toEqual(152); free(allocatorState, allocations[1]); free(allocatorState, allocations[3]); expect(stats(allocatorState).top).toEqual(152); expect(listFreeBlocks(allocatorState)).toHaveLength(2); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 8, "next": 104, "prev": 0, "size": 24, }, Object { "blockPointer": 104, "dataPointer": 120, "dataSize": 8, "next": 0, "prev": 56, "size": 24, }, ] `); free(allocatorState, allocations[2]); expect(stats(allocatorState).top).toEqual(152); expect(listFreeBlocks(allocatorState)).toHaveLength(1); expect(listFreeBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 56, "dataPointer": 72, "dataSize": 56, "next": 0, "prev": 0, "size": 72, }, ] `); expect(listAllocatedBlocks(allocatorState)).toMatchInlineSnapshot(` Array [ Object { "blockPointer": 128, "dataPointer": 144, "dataSize": 8, "next": 32, "prev": 0, "size": 24, }, Object { "blockPointer": 32, "dataPointer": 48, "dataSize": 8, "next": 0, "prev": 128, "size": 24, }, ] `); }); test("Merge adjacent blocks + meld with top", () => { const allocations = [ malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), malloc(allocatorState, 8), ]; expect(stats(allocatorState).top).toBe(176); expect(stats(allocatorState).used.count).toBe(6); expect(stats(allocatorState).free.count).toBe(0); free(allocatorState, allocations[4]); free(allocatorState, allocations[2]); expect(stats(allocatorState).top).toBe(176); expect(stats(allocatorState).used.count).toBe(4); expect(stats(allocatorState).free.count).toBe(2); free(allocatorState, allocations[3]); expect(stats(allocatorState).top).toBe(176); expect(stats(allocatorState).used.count).toBe(3); expect(stats(allocatorState).free.count).toBe(1); free(allocatorState, allocations[5]); expect(stats(allocatorState).top).toBe(80); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); }); }); describe("realloc", () => { test("block is already is in size, no change is needed", () => { const allocation = malloc(allocatorState, 8); // we make this allocation so the first allocation won't be adjacent to top const anotherAllocation = malloc(allocatorState, 8); expect(anotherAllocation).toMatchInlineSnapshot(`72`); expect(stats(allocatorState).used.count).toBe(2); const afterRealloc = realloc(allocatorState, allocation, 8); expect(stats(allocatorState).used.count).toBe(2); expect(allocation).toBe(afterRealloc); }); test("We are at top, oom when enlarge, fallback to malloc", () => { const allocations = [ malloc(allocatorState, 100), malloc(allocatorState, 200), malloc(allocatorState, 100), ]; expect(stats(allocatorState).used.count).toBe(3); free(allocatorState, allocations[1]); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(1); // fill all allocated space with 5's allocatorState.u32.fill(5, allocations[0] / 4, 100 / 4); const afterRealloc = realloc(allocatorState, allocations[0], 200); expect(afterRealloc).toBe(allocations[1]); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(1); // ensure the new area is all 5's expect( allocatorState.u32.slice(afterRealloc, 100).every((v) => v === 5) ).toBe(true); expect(afterRealloc).toBe(afterRealloc); }); test("enlarge into top", () => { const allocation = malloc(allocatorState, 8); expect(stats(allocatorState).used.count).toBe(1); const afterRealloc = realloc(allocatorState, allocation, 16); expect(stats(allocatorState).used.count).toBe(1); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(16); expect(allocation).toBe(afterRealloc); }); test("make smaller using top meld", () => { const allocation = malloc(allocatorState, 32); expect(stats(allocatorState).top).toBe(80); const afterRealloc = realloc(allocatorState, allocation, 8); expect(allocation).toBe(afterRealloc); expect(stats(allocatorState).top).toBe(56); expect(stats(allocatorState).used.count).toBe(1); }); test("make smaller by split block", () => { const allocation = malloc(allocatorState, 80); // allocation So Wont Be Adjacent To Top malloc(allocatorState, 80); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(224); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(80); const afterRealloc = realloc(allocatorState, allocation, 8); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(1); expect(allocation).toBe(afterRealloc); expect(stats(allocatorState).top).toBe(224); expect( listAllocatedBlocks(allocatorState).find( (b) => b.dataPointer === allocation )?.dataSize ).toBe(8); }); test("make smaller but can't split, dut to < monSplit so leave as is", () => { const allocation = malloc(allocatorState, 80); // allocation So Wont Be Adjacent To Top malloc(allocatorState, 80); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(224); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(80); const afterRealloc = realloc(allocatorState, allocation, 72); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(allocation).toBe(afterRealloc); expect(stats(allocatorState).top).toBe(224); expect( listAllocatedBlocks(allocatorState).find( (b) => b.dataPointer === allocation )?.dataSize ).toBe(80); }); test("allocate new bigger block, free old", () => { const allocation = malloc(allocatorState, 80); // allocation So Wont Be Adjacent To Top malloc(allocatorState, 8); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(152); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(8); const afterRealloc = realloc(allocatorState, allocation, 160); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(1); expect(afterRealloc).toBe( listAllocatedBlocks(allocatorState)[0].dataPointer ); expect(stats(allocatorState).top).toBe(328); }); test("oom when adjacent To Top", () => { malloc(allocatorState, 80); const allocation = malloc(allocatorState, 80); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(224); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(80); const statusBeforeOOM = stats(allocatorState); const afterRealloc = realloc(allocatorState, allocation, 400); // OOM expect(afterRealloc).toBe(0); // Make sure everything is the same - no state destruction due to oom expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(224); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(80); expect(stats(allocatorState)).toEqual(statusBeforeOOM); }); test("oom when not adjacent To Top", () => { const allocation = malloc(allocatorState, 80); // allocation So Wont Be Adjacent To Top malloc(allocatorState, 8); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(152); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(8); const statusBeforeOOM = stats(allocatorState); const afterRealloc = realloc(allocatorState, allocation, 400); // OOM expect(afterRealloc).toBe(0); // Make sure everything is the same - no state destruction due to oom expect(stats(allocatorState)).toEqual(statusBeforeOOM); expect(stats(allocatorState).used.count).toBe(2); expect(stats(allocatorState).free.count).toBe(0); expect(stats(allocatorState).top).toBe(152); expect(listAllocatedBlocks(allocatorState)[0].dataSize).toBe(8); }); }); });
the_stack
import { Text, TextPossibilities } from "./file-generator"; let indentation = " "; export const lineCommentPrefix = "//"; export const docCommentPrefix = "///"; export const EOL = "\n"; export const CommaChar = ", "; const acronyms = new Set([ "ip", "os", "ms", "vm", // 'ssl', 'https', 'http', '' ]); export function capitalize(str: string): string { if (acronyms.has(str)) { return str.toUpperCase(); } return str ? `${str.charAt(0).toUpperCase()}${str.substr(1)}` : str; } export function uncapitalize(str: string): string { return str ? `${str.charAt(0).toLowerCase()}${str.substr(1)}` : str; } export function join<T>(items: Array<T>, separator: string) { return items.filter((v) => (v ? true : false)).join(separator); } export function joinComma<T>(items: Array<T>, mapFn: (item: T) => string) { return join(items.map(mapFn), CommaChar); } export interface IHasName { name: string; } export function sortByName(a: IHasName, b: IHasName): number { return a.name < b.name ? -1 : a.name > b.name ? 1 : 0; } export function setIndentation(spaces: number) { indentation = " ".repeat(spaces); } export function trimDots(content: string) { return content.replace(/^[.\s]*(.*?)[.\s]*$/g, "$1"); } export function toMap<T>(source: Array<T>, eachFn: (item: T) => string): Map<string, Array<T>> { const result = new Map<string, Array<T>>(); for (const each of source) { const key = eachFn(each); let values = result.get(key); if (!values) { values = new Array<T>(); result.set(key, values); } values.push(each); } return result; } export function fixEOL(content: string) { return content.replace(/\r\n/g, EOL); } export function indent(content: string, factor = 1): string { const i = indentation.repeat(factor); content = i + fixEOL(content.trim()); return content.split(/\n/g).join(`${EOL}${i}`); } export function comment(content: string, prefix = lineCommentPrefix, factor = 0, maxLength = 120) { const result = new Array<string>(); let line = ""; prefix = indent(prefix, factor); content = content.trim(); if (content) { for (const word of content.replace(/\n+/g, " » ").split(/\s+/g)) { if (word === "»") { result.push(line); line = prefix; continue; } if (maxLength < line.length) { result.push(line); line = ""; } if (!line) { line = prefix; } line += ` ${word}`; } if (line) { result.push(line); } return result.join(EOL); } return ""; } export function docComment(content: string, prefix = docCommentPrefix, factor = 0, maxLength = 120) { return comment(content, prefix, factor, maxLength); } export function dotCombine(prefix: string, content: string) { return trimDots([trimDots(prefix), trimDots(content)].join(".")); } export function map<T, U>( dictionary: Record<string, T>, callbackfn: (key: string, value: T) => U, thisArg?: any, ): Array<U> { return Object.getOwnPropertyNames(dictionary).map((key) => callbackfn(key, dictionary[key])); } export function ToMap<T>(dictionary: Record<string, T>): Map<string, T> { const result = new Map<string, T>(); Object.getOwnPropertyNames(dictionary).map((key) => result.set(key, dictionary[key])); return result; } export function __selectMany<T>(multiArray: Array<Array<T>>): Array<T> { const result = new Array<T>(); multiArray.map((v) => result.push(...v)); return result; } export function pall<T, U>( array: Array<T>, callbackfn: (value: T, index: number, array: Array<T>) => Promise<U>, thisArg?: any, ): Promise<Array<U>> { return Promise.all(array.map(callbackfn)); } export function deconstruct(identifier: string | Array<string>): Array<string> { if (Array.isArray(identifier)) { return identifier.flatMap(deconstruct); } return `${identifier}` .replace(/([a-z]+)([A-Z])/g, "$1 $2") .replace(/(\d+)([a-z|A-Z]+)/g, "$1 $2") .replace(/\b([A-Z]+)([A-Z])([a-z])/, "$1 $2$3") .split(/[\W|_]+/) .map((each) => each.toLowerCase()); } export function isCapitalized(identifier: string): boolean { return /^[A-Z]/.test(identifier); } const ones = [ "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ]; const teens = [ "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", ]; const tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]; const magnitude = [ "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "septillion", "octillion", ]; const magvalues = [10 ** 3, 10 ** 6, 10 ** 9, 10 ** 12, 10 ** 15, 10 ** 18, 10 ** 21, 10 ** 24, 10 ** 27]; export function* convert(num: number): Iterable<string> { if (!num) { yield "zero"; return; } if (num > 1e30) { yield "lots"; return; } if (num > 999) { for (let i = magvalues.length; i > -1; i--) { const c = magvalues[i]; if (num > c) { yield* convert(Math.floor(num / c)); yield magnitude[i]; num = num % c; } } } if (num > 99) { yield ones[Math.floor(num / 100)]; yield "hundred"; num %= 100; } if (num > 19) { yield tens[Math.floor(num / 10)]; num %= 10; } if (num) { yield ones[num]; } } export function fixLeadingNumber(identifier: Array<string>): Array<string> { if (identifier.length > 0 && /^\d+/.exec(identifier[0])) { return [...convert(parseInt(identifier[0])), ...identifier.slice(1)]; } return identifier; } export function removeProhibitedPrefix( identifier: string, prohibitedPrefix: string, skipIdentifiers?: Array<string>, ): string { if (identifier.toLowerCase().startsWith(prohibitedPrefix.toLowerCase())) { const regex = new RegExp(`(^${prohibitedPrefix})(.*)`, "i"); let newIdentifier = identifier.replace(regex, "$2"); if (newIdentifier.length < 2) { // if it results in an empty string or a single letter string // then, it is not really a word. return identifier; } newIdentifier = isCapitalized(identifier) ? capitalize(newIdentifier) : uncapitalize(newIdentifier); return skipIdentifiers !== undefined ? skipIdentifiers.includes(newIdentifier) ? identifier : newIdentifier : newIdentifier; } return identifier; } export function isEqual(s1: string, s2: string): boolean { // when s2 is undefined and s1 is the string 'undefined', it returns 0, making this true. // To prevent that, first we need to check if s2 is undefined. return s2 !== undefined && !!s1 && !s1.localeCompare(s2, undefined, { sensitivity: "base" }); } export function removeSequentialDuplicates(identifier: Iterable<string>) { const ids = [...identifier].filter((each) => !!each); for (let i = 0; i < ids.length; i++) { while (isEqual(ids[i], ids[i - 1])) { ids.splice(i, 1); } while (isEqual(ids[i], ids[i - 2]) && isEqual(ids[i + 1], ids[i - 1])) { ids.splice(i, 2); } } return ids; } export function pascalCase(identifier: string | Array<string>, removeDuplicates = true): string { return identifier === undefined ? "" : typeof identifier === "string" ? pascalCase(fixLeadingNumber(deconstruct(identifier)), removeDuplicates) : (removeDuplicates ? [...removeSequentialDuplicates(identifier)] : identifier) .map((each) => capitalize(each)) .join(""); } export function camelCase(identifier: string | Array<string>): string { if (typeof identifier === "string") { return camelCase(fixLeadingNumber(deconstruct(identifier))); } switch (identifier.length) { case 0: return ""; case 1: return uncapitalize(identifier[0]); } return `${uncapitalize(identifier[0])}${pascalCase(identifier.slice(1))}`; } export function getPascalIdentifier(name: string): string { return pascalCase(fixLeadingNumber(deconstruct(name))); } export function escapeString(text: string | undefined): string { if (text) { const q = JSON.stringify(text); return q.substr(1, q.length - 2); } return ""; } /** emits c# to get the name of a property - uses nameof when it can, and uses a literal when it's an array value. */ export function nameof(text: string): string { if (text.indexOf("[") > -1) { return `$"${text.replace(/\[(.*)\]/, "[{$1}]")}"`; } return `nameof(${text})`; } export function* getRegions(source: string, prefix = "#", postfix = "") { source = source.replace(/\r?\n|\r/g, "«"); const rx = new RegExp( `(.*?)«?(\\s*${prefix}\\s*region\\s*(.*?)\\s*${postfix})\\s*«(.*?)«(\\s*${prefix}\\s*endregion\\s*${postfix})\\s*?«`, "g", ); let match; let finalPosition = 0; /* eslint-disable */ while ((match = rx.exec(source))) { if (match[1]) { // we have text before this region. yield { name: "", start: "", content: match[1].replace(/«/g, "\n"), end: "", }; } // this region yield { name: match[3], start: match[2], content: match[4].replace(/«/g, "\n"), end: match[5], }; finalPosition = rx.lastIndex; } if (finalPosition < source.length) { // we have text after the last region. yield { name: "", start: "", content: source.substring(finalPosition).replace(/«/g, "\n"), end: "", }; } } export function setRegion( source: string, region: string, content: TextPossibilities, prepend = true, prefix: string = "#", postfix: string = "", ) { const result = new Array<string>(); const ct = new Text(content).text .replace(/\r?\n|\r/g, "«") .replace(/^«*/, "") .replace(/«*$/, ""); let found = false; for (const each of getRegions(source, prefix, postfix)) { if (each.name === region) { // found the region, replace it. // (this also makes sure that we only have one region by that name when replacing/deleting) if (!found && ct) { // well, only if it has content, otherwise, we're deleting it. result.push(each.start, ct, each.end, "«"); found = true; } } else { result.push(each.start, each.content, each.end, "«"); } } if (!found) { if (prepend) { result.splice(0, 0, `${prefix} region ${region} ${postfix}`, ct, `${prefix} endregion ${postfix}«`); } else { result.push(`${prefix} region ${region} ${postfix}`, ct, `${prefix} endregion ${postfix}«`); } } return result .join("«") .replace(/\r?\n|\r/g, "«") .replace(/^«*/, "") .replace(/«*$/, "") .replace(/«««*/g, "««") .replace(/«/g, "\n"); } // Note: Where is this used? export function _setRegion( source: string, region: string, content: TextPossibilities, prepend = true, prefix: string = "#", postfix: string = "", ) { const ct = new Text(content).text .replace(/\r?\n|\r/g, "«") .replace(/^«*/, "") .replace(/«*$/, ""); source = source.replace(/\r?\n|\r/g, "«"); const rx = new RegExp( `«(\\s*${prefix}\\s*region\\s*${region}\\s*${postfix})\\s*«.*?(«\\s*${prefix}\\s*endregion\\s*${postfix}«?)`, "g", ); if (rx.test(source)) { if (ct.length > 0) { source = source.replace(rx, `«$1«${ct}$2`); } else { source = source.replace(rx, ""); } } else { if (ct.length > 0) { const text = `«${prefix} region ${region} ${postfix}«${ct}«${prefix} endregion ${postfix}«`; source = prepend ? text + source : source + text; } } source = source.replace(/«««*/g, "««").replace(/«/g, "\n"); return source; } export function selectName(nameOptions: Array<string>, reservedNames: Set<string>) { // we're here because the original name is in conflict. // so we start with the alternatives (skip the 0th!) NOT for (const each of nameOptions) { if (!reservedNames.has(each)) { reservedNames.add(each); return each; } } // hmm, none of the names were suitable. // use the first one, and tack on a number until we have a free value let i = 1; do { const name = `${nameOptions[0]}${i}`; if (!reservedNames.has(name)) { reservedNames.add(name); return name; } i++; } while (i < 100); // after an unreasonalbe search, return something invalid return `InvalidPropertyName${nameOptions[0]}`; }
the_stack
import { assert, expect } from "chai"; import * as os from "os"; import * as readline from "readline"; import { AccessToken, BriefcaseStatus, GuidString, StopWatch } from "@itwin/core-bentley"; import { BriefcaseIdValue, BriefcaseProps, IModelError, IModelVersion } from "@itwin/core-common"; import { UserCancelledError } from "@bentley/itwin-client"; import { BriefcaseDb, BriefcaseManager, IModelHost, IModelJsFs, RequestNewBriefcaseArg } from "@itwin/core-backend"; import { HubWrappers } from "@itwin/core-backend/lib/cjs/test/index"; import { HubUtility, TestUserType } from "../HubUtility"; // Configuration needed: // IMJS_TEST_REGULAR_USER_NAME // IMJS_TEST_REGULAR_USER_PASSWORD // IMJS_TEST_MANAGER_USER_NAME // IMJS_TEST_MANAGER_USER_PASSWORD // IMJS_TEST_SUPER_MANAGER_USER_NAME // imjs_test_super_manager_password // imjs_test_imodelhub_user_name // imjs_test_imodelhub_user_password // IMJS_OIDC_BROWSER_TEST_CLIENT_ID // - Required to be a SPA // IMJS_OIDC_BROWSER_TEST_REDIRECT_URI // IMJS_OIDC_BROWSER_TEST_SCOPES // - Required scopes: "openid imodelhub context-registry-service:read-only" describe("BriefcaseManager", () => { let testITwinId: string; let readOnlyTestIModelId: GuidString; const readOnlyTestVersions = ["FirstVersion", "SecondVersion", "ThirdVersion"]; const readOnlyTestElementCounts = [27, 28, 29]; let noVersionsTestIModelId: GuidString; let accessToken: AccessToken; before(async () => { accessToken = await HubUtility.getAccessToken(TestUserType.Regular); testITwinId = await HubUtility.getTestITwinId(accessToken); readOnlyTestIModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.readOnly); noVersionsTestIModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.readWrite); }); it("should open and close an iModel from the Hub", async () => { const iModel = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.first().toJSON(), deleteFirst: true }); assert.exists(iModel, "No iModel returned from call to BriefcaseManager.open"); // Validate that the IModelDb is readonly assert(iModel.isReadonly, "iModel not set to Readonly mode"); const expectedChangeSet = await IModelHost.hubAccess.getChangesetFromVersion({ version: IModelVersion.first(), accessToken, iModelId: readOnlyTestIModelId }); assert.strictEqual(iModel.changeset.id, expectedChangeSet.id); assert.strictEqual(iModel.changeset.id, expectedChangeSet.id); const pathname = iModel.pathName; assert.isTrue(IModelJsFs.existsSync(pathname)); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); assert.isFalse(IModelJsFs.existsSync(pathname), `Briefcase continues to exist at ${pathname}`); }); it("should reuse checkpoints", async () => { const iModel1 = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named("FirstVersion").toJSON() }); assert.exists(iModel1, "No iModel returned from call to BriefcaseManager.open"); const iModel2 = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named("FirstVersion").toJSON() }); assert.exists(iModel2, "No iModel returned from call to BriefcaseManager.open"); assert.equal(iModel1, iModel2, "previously open briefcase was expected to be shared"); const iModel3 = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named("SecondVersion").toJSON() }); assert.exists(iModel3, "No iModel returned from call to BriefcaseManager.open"); assert.notEqual(iModel3, iModel2, "opening two different versions should not cause briefcases to be shared when the older one is open"); const pathname2 = iModel2.pathName; iModel2.close(); assert.isTrue(IModelJsFs.existsSync(pathname2)); const pathname3 = iModel3.pathName; iModel3.close(); assert.isTrue(IModelJsFs.existsSync(pathname3)); const iModel4 = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named("FirstVersion").toJSON() }); assert.exists(iModel4, "No iModel returned from call to BriefcaseManager.open"); assert.equal(iModel4.pathName, pathname2, "previously closed briefcase was expected to be shared"); const iModel5 = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named("SecondVersion").toJSON() }); assert.exists(iModel5, "No iModel returned from call to BriefcaseManager.open"); assert.equal(iModel5.pathName, pathname3, "previously closed briefcase was expected to be shared"); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel4); assert.isFalse(IModelJsFs.existsSync(pathname2)); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel5); assert.isFalse(IModelJsFs.existsSync(pathname3)); }); it("should open iModels of specific versions from the Hub", async () => { const dirToPurge = BriefcaseManager.getIModelPath(readOnlyTestIModelId); IModelJsFs.purgeDirSync(dirToPurge); const iModelFirstVersion = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.first().toJSON(), deleteFirst: true }); assert.exists(iModelFirstVersion); assert.strictEqual(iModelFirstVersion.changeset.id, ""); const changesets = await IModelHost.hubAccess.queryChangesets({ accessToken, iModelId: readOnlyTestIModelId }); for (const [arrayIndex, versionName] of readOnlyTestVersions.entries()) { const iModelFromVersion = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.asOfChangeSet(changesets[arrayIndex + 1].id).toJSON() }); assert.exists(iModelFromVersion); assert.strictEqual(iModelFromVersion.changeset.id, changesets[arrayIndex + 1].id); const iModelFromChangeSet = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, asOf: IModelVersion.named(versionName).toJSON() }); assert.exists(iModelFromChangeSet); assert.strictEqual(iModelFromChangeSet, iModelFromVersion); assert.strictEqual(iModelFromChangeSet.changeset.id, changesets[arrayIndex + 1].id); const elementCount = iModelFromVersion.withStatement("SELECT COUNT(*) FROM bis.Element", (stmt) => { stmt.step(); return stmt.getValue(0).getInteger(); }); assert.equal(elementCount, readOnlyTestElementCounts[arrayIndex], `Count isn't what's expected for ${iModelFromVersion.pathName}, version ${versionName}`); iModelFromVersion.close(); iModelFromChangeSet.close(); } const iModelLatestVersion = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: readOnlyTestIModelId, deleteFirst: true }); assert.isDefined(iModelLatestVersion); assert.strictEqual(iModelLatestVersion.nativeDb.getCurrentChangeset().id, changesets[3].id); assert.equal(iModelLatestVersion.nativeDb.getCurrentChangeset().index, changesets[3].index); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModelFirstVersion); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModelLatestVersion); }); it("should open an iModel with no versions", async () => { const iModelNoVer = await HubWrappers.openCheckpointUsingRpc({ accessToken, iTwinId: testITwinId, iModelId: noVersionsTestIModelId }); assert.exists(iModelNoVer); assert(iModelNoVer.iModelId === noVersionsTestIModelId, "Correct iModel not found"); }); it("should be able to show progress when downloading a briefcase (#integration)", async () => { const testIModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.stadium); let numProgressCalls = 0; readline.clearLine(process.stdout, 0); readline.moveCursor(process.stdout, -20, 0); let done = 0; let complete = 0; const downloadProgress = (loaded: number, total: number) => { if (total > 0) { const message = `${HubUtility.testIModelNames.stadium} Download Progress ... ${(loaded * 100 / total).toFixed(2)}%`; process.stdout.write(message); readline.moveCursor(process.stdout, -1 * message.length, 0); if (loaded >= total) process.stdout.write(os.EOL); numProgressCalls++; done = loaded; complete = total; } return 0; }; const args: RequestNewBriefcaseArg & BriefcaseProps = { accessToken, iTwinId: testITwinId, iModelId: testIModelId, briefcaseId: BriefcaseIdValue.Unassigned, onProgress: downloadProgress, }; const fileName = BriefcaseManager.getFileName(args); await BriefcaseManager.deleteBriefcaseFiles(fileName); const watch = new StopWatch("download", true); const props = await BriefcaseManager.downloadBriefcase(args); // eslint-disable-next-line no-console console.log(`download took ${watch.elapsedSeconds} seconds`); const iModel = await BriefcaseDb.open({ fileName: props.fileName }); await expect(BriefcaseManager.downloadBriefcase(args)).to.be.rejectedWith(IModelError, "already exists", "should not be able to download a briefcase if a file with that name already exists"); await HubWrappers.closeAndDeleteBriefcaseDb(accessToken, iModel); assert.isAbove(numProgressCalls, 0, "download progress called"); assert.isAbove(done, 0, "done set"); assert.isAbove(complete, 0, "complete set"); }); it("Should be able to cancel an in progress download (#integration)", async () => { const testIModelId = await HubUtility.getTestIModelId(accessToken, HubUtility.testIModelNames.stadium); let aborted = 0; const args = { accessToken, iTwinId: testITwinId, iModelId: testIModelId, briefcaseId: BriefcaseIdValue.Unassigned, onProgress: () => aborted, }; await BriefcaseManager.deleteBriefcaseFiles(BriefcaseManager.getFileName(args), accessToken); const downloadPromise = BriefcaseManager.downloadBriefcase(args); setTimeout(async () => aborted = 1, 1000); await expect(downloadPromise).to.be.rejectedWith(UserCancelledError).to.eventually.have.property("errorNumber", BriefcaseStatus.DownloadCancelled); }); });
the_stack
import chai from 'chai'; import faker from 'faker'; import { readFileSync } from 'fs'; import path from 'path'; import { wrapSetToArrayField } from './utils'; const expect = chai.expect; const userFields = ` id username email status attributes location { lat lng } note { title text } `; const groupFields = ` id name `; const userWithGroupFields = ` id username email status attributes location { lat lng } note { title text } groups { ${groupFields} } `; const groupWithUserFields = ` id name members { ${userFields} } `; const fakeUserData = (data?: any) => { return { username: faker.internet.userName(), email: faker.internet.email(), status: 'OK', attributes: {x: 1}, location: { lat: faker.address.latitude(), lng: faker.address.longitude(), }, note: [{title: faker.lorem.slug(10), text: faker.lorem.sentence(100)}], ...data, }; }; export const sdl = readFileSync(path.resolve(__dirname, '../fixtures/manyToMany.graphql'), {encoding: 'utf8'}); export function testSuits() { it('should create unconnected item with bi-*-to-* from one side', async () => { const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); expect(createGroup).to.have.property('id'); expect(createGroup.name).to.be.eql(createGroupVariables.data.name); // tslint:disable-next-line:no-unused-expression expect(createGroup.members).to.be.an('array').that.is.empty; }); it('should create with create item with bi-*-to-* from one side', async () => { // create user const user = fakeUserData(); // create with to-one relation const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), members: { create: [wrapSetToArrayField(user)], }, }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); expect(createGroup).to.have.property('id'); expect(createGroup).to.deep.include({ name: createGroupVariables.data.name, }); expect(createGroup.members[0]).to.deep.include(user); }); it('should create connected item with bi-*-to-* from one side', async () => { // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // create with to-one relation const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), members: { connect: [ { id: createUser.id }, ], }, }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); expect(createGroup).to.have.property('id'); expect(createGroup).to.deep.include({ name: createGroupVariables.data.name, members: [createUser], }); }); it('should connect unconnected with bi-*-to-* from one side', async () => { // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // create new user const createNewUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const {createUser: newUser} = await (this as any).graphqlRequest(createUserQuery, createNewUserVariables); // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // tslint:disable-next-line:no-unused-expression expect(createGroup.members).to.be.an('array').that.is.empty; // update to-one relation const updateGroupQuery = ` mutation($where: GroupWhereUniqueInput!, $data: GroupUpdateInput!) { updateGroup (where: $where, data: $data) { id } } `; const updateGroupVariables = { where: { id: createGroup.id }, data: { members: { connect: [ { id: createUser.id }, { id: newUser.id }, ], }, }, }; const {updateGroup} = await (this as any).graphqlRequest(updateGroupQuery, updateGroupVariables); expect(updateGroup.id).to.be.eql(createGroup.id); // query const getGroupQuery = ` query ($where: GroupWhereUniqueInput!) { group (where: $where) { ${groupWithUserFields} } } `; const getGroupVariables = { where: { id: createGroup.id }, }; const {group} = await (this as any).graphqlRequest(getGroupQuery, getGroupVariables); expect(group).to.deep.include({ name: createGroupVariables.data.name, }); expect(group.members).to.have.deep.members([createUser, newUser]); }); it('should update with create with bi-*-to-* from one side', async () => { const user = fakeUserData(); // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // tslint:disable-next-line:no-unused-expression expect(createGroup.members).to.be.an('array').that.is.empty; // update relation const updateGroupQuery = ` mutation($where: GroupWhereUniqueInput!, $data: GroupUpdateInput!) { updateGroup (where: $where, data: $data) { id } } `; const updateGroupVariables = { where: { id: createGroup.id }, data: { members: { create: [wrapSetToArrayField(user)], }, }, }; const {updateGroup} = await (this as any).graphqlRequest(updateGroupQuery, updateGroupVariables); expect(updateGroup.id).to.be.eql(createGroup.id); // query const getGroupQuery = ` query ($where: GroupWhereUniqueInput!) { group (where: $where) { ${groupWithUserFields} } } `; const getGroupVariables = { where: { id: createGroup.id }, }; const {group} = await (this as any).graphqlRequest(getGroupQuery, getGroupVariables); expect(group).to.deep.include({ name: createGroupVariables.data.name, }); expect(group.members[0]).be.deep.include(user); }); it('should connect unconnected and disconnect connected with bi-*-to-* from one side', async () => { // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), members: { connect: [ { id: createUser.id }, ], }, }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); expect(createGroup.members).to.have.deep.members([createUser]); // create new user const createNewUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const {createUser: newUser} = await (this as any).graphqlRequest(createUserQuery, createNewUserVariables); // update to-one relation const updateGroupQuery = ` mutation($where: GroupWhereUniqueInput!, $data: GroupUpdateInput!) { updateGroup (where: $where, data: $data) { id } } `; const updateGroupVariables = { where: { id: createGroup.id }, data: { members: { connect: [ { id: newUser.id }, ], disconnect: [ { id: createUser.id }, ], }, }, }; const {updateGroup} = await (this as any).graphqlRequest(updateGroupQuery, updateGroupVariables); expect(updateGroup.id).to.be.eql(createGroup.id); // query const getGroupQuery = ` query ($where: GroupWhereUniqueInput!) { group (where: $where) { ${groupWithUserFields} } } `; const getGroupVariables = { where: { id: createGroup.id }, }; const {group} = await (this as any).graphqlRequest(getGroupQuery, getGroupVariables); expect(group).to.deep.include({ name: createGroupVariables.data.name, members: [newUser], }); }); it('should disconnect connected item with bi-*-to-* from one side', async () => { // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupWithUserFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), members: { connect: [ { id: createUser.id }, ], }, }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); expect(createGroup.members).to.have.deep.members([createUser]); // update to-one relation const updateGroupQuery = ` mutation($where: GroupWhereUniqueInput!, $data: GroupUpdateInput!) { updateGroup (where: $where, data: $data) { id } } `; const updateGroupVariables = { where: { id: createGroup.id }, data: { members: { disconnect: [ { id: createUser.id }, ], }, }, }; const {updateGroup} = await (this as any).graphqlRequest(updateGroupQuery, updateGroupVariables); expect(updateGroup.id).to.be.eql(createGroup.id); // query const getGroupQuery = ` query ($where: GroupWhereUniqueInput!) { group (where: $where) { ${groupWithUserFields} } } `; const getGroupVariables = { where: { id: createGroup.id }, }; const {group} = await (this as any).graphqlRequest(getGroupQuery, getGroupVariables); // tslint:disable-next-line:no-unused-expression expect(group.members).to.be.an('array').that.is.empty; }); it('should disconnect unconnected item with bi-*-to-* from one side'); it('should create unconnected item with bi-*-to-* from the other side', async () => { // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userWithGroupFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); expect(createUser).to.have.property('id'); // tslint:disable-next-line:no-unused-expression expect(createUser.groups).to.be.an('array').that.is.empty; }); it('should create connected item with bi-*-to-* from the other side', async () => { // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // create user const data = fakeUserData(); const createUserVariables = { data: { ...wrapSetToArrayField(data), groups: { connect: [ { id: createGroup.id }, ], }, }, }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userWithGroupFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); expect(createUser).to.have.property('id'); expect(createUser).to.deep.include({ ...data, groups: [createGroup], }); }); it('should create with create item with bi-*-to-* from the other side', async () => { const group = { name: faker.internet.userName(), }; const user = fakeUserData(); // create user const createUserVariables = { data: { ...wrapSetToArrayField(user), groups: { create: [group], }, }, }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userWithGroupFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); expect(createUser).to.have.property('id'); expect(createUser).to.deep.include(user); expect(createUser.groups[0]).to.deep.include(group); }); it('should connect unconnected item with bi-*-to-* from one side', async () => { // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // update user const updateUserQuery = ` mutation ($where: UserWhereUniqueInput!, $data: UserUpdateInput!) { updateUser (where: $where, data: $data) { id } } `; const updateUserVariables = { where: { id: createUser.id }, data: { groups: { connect: [ { id: createGroup.id }, ], }, }, }; const {updateUser} = await (this as any).graphqlRequest(updateUserQuery, updateUserVariables); expect(updateUser.id).to.be.eql(createUser.id); // get user const getUserQuery = ` query ($where: UserWhereUniqueInput!) { user (where: $where) { ${userWithGroupFields} } } `; const getUserVariable = { where: { id: createUser.id }, }; const {user} = await (this as any).graphqlRequest(getUserQuery, getUserVariable); expect(user.groups).to.have.deep.members([createGroup]); }); it('should update with create item with bi-*-to-* from one side', async () => { const group = { name: faker.internet.userName(), }; // create user const createUserVariables = { data: wrapSetToArrayField(fakeUserData()), }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // update user const updateUserQuery = ` mutation ($where: UserWhereUniqueInput!, $data: UserUpdateInput!) { updateUser (where: $where, data: $data) { id } } `; const updateUserVariables = { where: { id: createUser.id }, data: { groups: { create: [group], }, }, }; const {updateUser} = await (this as any).graphqlRequest(updateUserQuery, updateUserVariables); expect(updateUser.id).to.be.eql(createUser.id); // get user const getUserQuery = ` query ($where: UserWhereUniqueInput!) { user (where: $where) { ${userWithGroupFields} } } `; const getUserVariable = { where: { id: createUser.id }, }; const {user} = await (this as any).graphqlRequest(getUserQuery, getUserVariable); expect(user.groups[0]).to.deep.include(group); }); it('should update connect on connected item with bi-*-to-* from one side', async () => { // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // create user const createUserVariables = { data: { ...wrapSetToArrayField(fakeUserData()), groups: { connect: [ { id: createGroup.id }, ], }, }, }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userWithGroupFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // new Book const createNewBookVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup: newGroup} = await (this as any).graphqlRequest(createGroupQuery, createNewBookVariables); // update user const updateUserQuery = ` mutation ($where: UserWhereUniqueInput!, $data: UserUpdateInput!) { updateUser (where: $where, data: $data) { id } } `; const updateUserVariables = { where: { id: createUser.id }, data: { groups: { connect: [ { id: newGroup.id }, ], disconnect: [ { id: createGroup.id }, ], }, }, }; const {updateUser} = await (this as any).graphqlRequest(updateUserQuery, updateUserVariables); expect(updateUser.id).to.be.eql(createUser.id); // get user const getUserQuery = ` query ($where: UserWhereUniqueInput!) { user (where: $where) { ${userWithGroupFields} } } `; const getUserVariable = { where: { id: createUser.id }, }; const {user} = await (this as any).graphqlRequest(getUserQuery, getUserVariable); expect(user.groups).to.have.deep.members([newGroup]); }); it('should disconnect connected item with bi-*-to-* from one side', async () => { // create group const createGroupQuery = ` mutation ($data: GroupCreateInput!) { createGroup (data: $data) {${groupFields}} } `; const createGroupVariables = { data: { name: faker.internet.userName(), }, }; const {createGroup} = await (this as any).graphqlRequest(createGroupQuery, createGroupVariables); // create user const createUserVariables = { data: { ...wrapSetToArrayField(fakeUserData()), groups: { connect: [ { id: createGroup.id }, ], }, }, }; const createUserQuery = ` mutation ($data: UserCreateInput!) { createUser (data: $data) {${userWithGroupFields}} } `; const {createUser} = await (this as any).graphqlRequest(createUserQuery, createUserVariables); // tslint:disable-next-line:no-unused-expression expect(createUser.groups).to.not.be.empty; // update user const updateUserQuery = ` mutation ($where: UserWhereUniqueInput!, $data: UserUpdateInput!) { updateUser (where: $where, data: $data) { id } } `; const updateUserVariables = { where: { id: createUser.id }, data: { groups: { disconnect: [ { id: createGroup.id }, ], }, }, }; const {updateUser} = await (this as any).graphqlRequest(updateUserQuery, updateUserVariables); expect(updateUser.id).to.be.eql(createUser.id); // get user const getUserQuery = ` query ($where: UserWhereUniqueInput!) { user (where: $where) { ${userWithGroupFields} } } `; const getUserVariable = { where: { id: createUser.id }, }; const {user} = await (this as any).graphqlRequest(getUserQuery, getUserVariable); // tslint:disable-next-line:no-unused-expression expect(user.groups).to.be.an('array').that.is.empty; }); it('should disconnect unconnected item with bi-*-to-* from one side'); }
the_stack
import ActionType from '../public/ActionType' import ActionTagMap from './ActionTagMap' const { Attr, Behav, Event, Node, Style } = ActionType type ActionTagMap = { 'default': ActionType; [tag: string]: ActionType; } // @NOTE: those actions whose type determined by argument or property // (1) Element.attributes methods (e.g. setAttr, removeAttr) // (2) Attr value setter const AttrActionTagMap: ActionTagMap = { 'class': Style, 'style': Style, 'default': Attr } // @NOTE: those actions whose type determined by caller object // (1) classList -> Style // (2) others -> Attr const DOMTokenListActionTagMap: ActionTagMap = { 'classList': Style, 'default': Attr } const ActionMap: {[target in Target]: object} = { 'HTMLElement': { // https://developer.mozilla.org/zh-TW/docs/Web/API/HTMLElement /* properties */ // includes dataset, style 'accessKey': Attr, 'contentEditable': Attr, 'dir': Attr, 'draggable': Attr, 'hidden': Attr, // @NOTE: innerText on MDN is in Node.prototype, // but chrome put it in HTMLElement.prototype 'innerText': Attr | Node, 'lang': Attr, 'nonce': Attr, 'outerText': Attr | Node, 'spellcheck': Attr, // 'style': Style 'tabIndex': Attr, 'title': Attr, 'translate': Attr, 'onabort': Event, 'onanimationcancel': Event, 'onanimationend': Event, 'onanimationiteration': Event, 'onauxclick': Event, 'onblur': Event, 'oncancel': Event, 'oncanplay': Event, 'oncanplaythrough': Event, 'onchange': Event, 'onclick': Event, 'onclose': Event, 'oncontextmenu': Event, 'oncopy': Event, 'oncuechange': Event, 'oncut': Event, 'ondblclick': Event, 'ondrag': Event, 'ondragend': Event, 'ondragenter': Event, 'ondragleave': Event, 'ondragover': Event, 'ondragstart': Event, 'ondrop': Event, 'ondurationchange': Event, 'onemptied': Event, 'onended': Event, 'onerror': Event, 'onfocus': Event, 'ongotpointercapture': Event, 'oninput': Event, 'oninvalid': Event, 'onkeydown': Event, 'onkeypress': Event, 'onkeyup': Event, 'onload': Event, 'onloadeddata': Event, 'onloadedmetadata': Event, 'onloadend': Event, 'onloadstart': Event, 'onlostpointercapture': Event, 'onmousedown': Event, 'onmouseenter': Event, 'onmouseleave': Event, 'onmousemove': Event, 'onmouseout': Event, 'onmouseover': Event, 'onmouseup': Event, 'onmousewheel': Event, 'onpause': Event, 'onplay': Event, 'onplaying': Event, 'onprogress': Event, 'onpaste': Event, 'onpointercancel': Event, 'onpointerdown': Event, 'onpointerenter': Event, 'onpointerleave': Event, 'onpointermove': Event, 'onpointerout': Event, 'onpointerover': Event, 'onpointerup': Event, 'onratechange': Event, 'onreset': Event, 'onresize': Event, 'onscroll': Event, 'onseeked': Event, 'onseeking': Event, 'onselect': Event, 'onselectionchange': Event, 'onselectstart': Event, 'onshow': Event, 'onstalled': Event, 'onsubmit': Event, 'onsuspend': Event, 'ontimeupdate': Event, 'ontoggle': Event, 'ontouchcancel': Event, 'ontouchmove': Event, 'ontouchstart': Event, 'ontransitioncancel': Event, 'ontransitionend': Event, 'onvolumechange': Event, 'onwaiting': Event, 'onwheel': Event, /* methods */ 'blur': Behav | Event, 'click': Behav | Event, 'focus': Behav | Event, }, 'SVGElement': { // https://developer.mozilla.org/zh-TW/docs/Web/API/SVGElement /* properties */ // includes dataset, style 'nonce': Attr, 'tabIndex': Attr, 'onabort': Event, 'onanimationcancel': Event, 'onanimationend': Event, 'onanimationiteration': Event, 'onauxclick': Event, 'onblur': Event, 'oncancel': Event, 'oncanplay': Event, 'oncanplaythrough': Event, 'onchange': Event, 'onclick': Event, 'onclose': Event, 'oncontextmenu': Event, 'oncopy': Event, 'oncuechange': Event, 'oncut': Event, 'ondblclick': Event, 'ondrag': Event, 'ondragend': Event, 'ondragenter': Event, 'ondragleave': Event, 'ondragover': Event, 'ondragstart': Event, 'ondrop': Event, 'ondurationchange': Event, 'onemptied': Event, 'onended': Event, 'onerror': Event, 'onfocus': Event, 'ongotpointercapture': Event, 'oninput': Event, 'oninvalid': Event, 'onkeydown': Event, 'onkeypress': Event, 'onkeyup': Event, 'onload': Event, 'onloadeddata': Event, 'onloadedmetadata': Event, 'onloadend': Event, 'onloadstart': Event, 'onlostpointercapture': Event, 'onmousedown': Event, 'onmouseenter': Event, 'onmouseleave': Event, 'onmousemove': Event, 'onmouseout': Event, 'onmouseover': Event, 'onmouseup': Event, 'onmousewheel': Event, 'onpause': Event, 'onplay': Event, 'onplaying': Event, 'onprogress': Event, 'onpaste': Event, 'onpointercancel': Event, 'onpointerdown': Event, 'onpointerenter': Event, 'onpointerleave': Event, 'onpointermove': Event, 'onpointerout': Event, 'onpointerover': Event, 'onpointerup': Event, 'onratechange': Event, 'onreset': Event, 'onresize': Event, 'onscroll': Event, 'onseeked': Event, 'onseeking': Event, 'onselect': Event, 'onselectionchange': Event, 'onselectstart': Event, 'onshow': Event, 'onstalled': Event, 'onsubmit': Event, 'onsuspend': Event, 'ontimeupdate': Event, 'ontoggle': Event, 'ontouchcancel': Event, 'ontouchmove': Event, 'ontouchstart': Event, 'ontransitioncancel': Event, 'ontransitionend': Event, 'onvolumechange': Event, 'onwaiting': Event, 'onwheel': Event, /* methods */ 'blur': Behav | Event, 'focus': Behav | Event, }, 'Element': { // https://developer.mozilla.org/zh-TW/docs/Web/API/Element /* properties */ // includes attributes, classList 'id': Attr, 'name': Attr, 'slot': Attr, 'scrollTop': Attr, 'scrollLeft': Attr, 'onbeforecopy': Event, 'onbeforecut': Event, 'onbeforepaste': Event, 'oncopy': Event, 'oncut': Event, 'onpaste': Event, 'onsearch': Event, 'onselectstart': Event, 'onwebkitfullscreenchange': Event, 'onwebkitfullscreenerror': Event, 'innerHTML': Attr | Node, 'outerHTML': Attr | Node, 'className': Style, /* methods */ 'removeAttribute': AttrActionTagMap, 'removeAttributeNode': AttrActionTagMap, 'removeAttributeNS': AttrActionTagMap, 'setAttribute': AttrActionTagMap, 'setAttributeNode': AttrActionTagMap, // #anomaly 'setAttributeNodeNS': AttrActionTagMap, // #anomaly 'setAttributeNS': AttrActionTagMap, 'scrollIntoView': Behav, 'setPointerCapture': Behav | Event, 'append': Node, 'attachShadow': Node, 'insertAdjacentElement': Node, 'insertAdjacentHTML': Node, 'insertAdjacentText': Node, 'prepend': Node, // ChildNode https://developer.mozilla.org/zh-TW/docs/Web/API/ChildNode // Chrome keeps these methods in Element 'remove': Node, 'before': Node, 'after': Node, 'replaceWith': Node, // 'animate': Style, }, 'Node': { // https://developer.mozilla.org/zh-TW/docs/Web/API/Node /* properties */ 'nodeValue': Attr, 'textContent': Attr | Node, /* methods */ 'appendChild': Node, 'insertBefore': Node, 'normalize': Node, // [https://developer.mozilla.org/zh-TW/docs/Web/API/Node/normalize] The Node.normalize() method puts the specified node and all of its sub-tree into a 'normalized' form. In a normalized sub-tree, no text nodes in the sub-tree are empty and there are no adjacent text nodes. 'removeChild': Node, 'replaceChild': Node, }, 'EventTarget': { // https://developer.mozilla.org/zh-TW/docs/Web/API/EventTarget /* methods */ 'dispatchEvent': Behav | Event, 'addEventListener': Event, 'removeEventListener': Event, }, 'Attr': { // https://developer.mozilla.org/zh-TW/docs/Web/API/Attr /* properties */ 'value': AttrActionTagMap // #anomaly }, 'CSSStyleDeclaration': { // https://developer.mozilla.org/zh-TW/docs/Web/API/CSSStyleDeclaration // refer to HTMLElement.style /* methods */ 'removeProperty': Style, 'setProperty': Style }, 'DOMStringMap': { // https://developer.mozilla.org/zh-TW/docs/Web/API/DOMStringMap // refer to HTMLElement.dataset }, 'DOMTokenList': { // https://developer.mozilla.org/zh-TW/docs/Web/API/DOMTokenList // refer to Element.classList /* properties */ 'value': DOMTokenListActionTagMap, /* methods */ 'add': DOMTokenListActionTagMap, 'remove': DOMTokenListActionTagMap, 'replace': DOMTokenListActionTagMap, 'toggle': DOMTokenListActionTagMap }, 'NamedNodeMap': { // https://developer.mozilla.org/zh-TW/docs/Web/API/NamedNodeMap // refer to Element.attributes /* methods */ 'removeNamedItem': AttrActionTagMap, 'removeNamedItemNS': AttrActionTagMap, 'setNamedItem': AttrActionTagMap, // #anomaly 'setNamedItemNS': AttrActionTagMap, // #anomaly }, } const IActionMap = { getActionType({ caller, target, action, args = [] }: { caller: ActionTarget, target: Target, action: Action, args?: any[] }): ActionType { switch (target) { case 'CSSStyleDeclaration': return ActionType.Style case 'DOMStringMap': return ActionType.Attr default: if (this.has(target, action)) { const tag = ActionTagMap.fetchActionTag({ caller, target, action, args }) const type = ActionMap[target][action] return tag ? (type[tag] || type['default']) : type } return ActionType.None } }, has(target: Target, action: Action) { return !!(ActionMap[target] && ActionMap[target][action]) }, visit( callback: (target: Target, actionMap: object) => void ) { Object.keys(ActionMap).map( (target: Target) => { callback(target, ActionMap[target]) } ) } } export default IActionMap
the_stack
import { browser, protractor, $ } from 'protractor'; import { Menu } from '../page-objects/menu.po'; import { VulnerabilityReport } from '../page-objects/vulnerability-report.po'; import { AssetGroups } from '../page-objects/asset-groups.po'; import { CONFIGURATIONS } from './../../src/config/configurations'; const domain = CONFIGURATIONS.optional.general.e2e.DOMAIN; const timeOutHigh = 180000; describe('VulnerabilityReport', () => { let AssetGroups_po: AssetGroups; let menu_po: Menu; let VulnerabilityReport_po: VulnerabilityReport; const EC = protractor.ExpectedConditions; beforeAll(() => { AssetGroups_po = new AssetGroups(); menu_po = new Menu(); VulnerabilityReport_po = new VulnerabilityReport(); }); it('Verify title of vulnerability report', () => { browser.wait(EC.visibilityOf(menu_po.MenuClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(menu_po.MenuClick()), timeOutHigh); menu_po.MenuClick().click(); browser.wait(EC.visibilityOf(menu_po.VulnerabilityReportClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(menu_po.VulnerabilityReportClick()), timeOutHigh); menu_po.VulnerabilityReportClick().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getTitle()), timeOutHigh); expect(VulnerabilityReport_po.getTitle().getText()).toContain('Vulnerability Summary'); }); it('Check all the components are present', () => { browser.wait(EC.visibilityOf(VulnerabilityReport_po.getScanPercent()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getActionsToRemediate()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getPerformersTable()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkDistribution()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkTrend()), timeOutHigh); expect(VulnerabilityReport_po.getScanPercent().getText()).toContain('scan coverage'); }); it('Verify report calculation is opening', () => { browser.wait(EC.visibilityOf(VulnerabilityReport_po.getWorkflow()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getWorkflow()), timeOutHigh); VulnerabilityReport_po.getWorkflow().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getWorkflowHeading()), timeOutHigh); expect(VulnerabilityReport_po.getWorkflowHeading().getText()).toEqual('Vulnerability Report Calculation Workflow'); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getWorkflowClose()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getWorkflowClose()), timeOutHigh); VulnerabilityReport_po.getWorkflowClose().click(); }); it('Verify actions to remediate details', () => { browser.wait(EC.presenceOf(VulnerabilityReport_po.getActionsToRemediate()), timeOutHigh); browser.executeScript('arguments[0].scrollIntoView();', VulnerabilityReport_po.getActionsToRemediate().getWebElement()); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getActionsToRemediate()), timeOutHigh); VulnerabilityReport_po.getActionsToRemediate().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getPopHeading()), timeOutHigh); expect(VulnerabilityReport_po.getPopHeading().getText()).toEqual('Actions to Remediate'); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getClosePop()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getClosePop()), timeOutHigh); VulnerabilityReport_po.getClosePop().click(); }); it('Verify performers details', () => { browser.wait(EC.presenceOf(VulnerabilityReport_po.getPerformersTable()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getPerformers()), timeOutHigh); browser.executeScript('arguments[0].scrollIntoView();', VulnerabilityReport_po.getPerformers().getWebElement()); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getPerformers()), timeOutHigh); VulnerabilityReport_po.getPerformers().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getPopHeading()), timeOutHigh); expect(VulnerabilityReport_po.getPopHeading().getText()).toEqual('Highest & Lowest Performers'); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getClosePop()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.getClosePop()), timeOutHigh); VulnerabilityReport_po.getClosePop().click(); }); it('Verify scan percentage and lying between 0 and 100', () => { browser.wait(EC.visibilityOf(VulnerabilityReport_po.getScanPercent()), timeOutHigh); let scan_percent; VulnerabilityReport_po.getScanPercent().getText().then(function(text) { scan_percent = parseInt(text, 10); }); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getAssetsScanned()), timeOutHigh); let assets_scanned; VulnerabilityReport_po.getAssetsScanned().getText().then(function(text) { assets_scanned = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.visibilityOf(VulnerabilityReport_po.getAssetsNotScanned()), timeOutHigh); let assets_unscanned; VulnerabilityReport_po.getAssetsNotScanned().getText().then(function(text) { assets_unscanned = parseInt(text.replace(/,/g, ''), 10); expect(Math.floor((100 * assets_scanned) / (assets_scanned + assets_unscanned))).toEqual(scan_percent); let is_percent = false; if (scan_percent >= 0 && scan_percent <= 100) { is_percent = true; } expect(is_percent).toEqual(true); }); }); it('Check vulnerability summary validity', () => { let total_vulnerabilities; let total_assets; let total_occurrences; browser.wait(EC.presenceOf(VulnerabilityReport_po.getTotalVulnerabilities()), timeOutHigh); VulnerabilityReport_po.getTotalVulnerabilities().getText().then(function(text) { total_vulnerabilities = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.presenceOf(VulnerabilityReport_po.getTotalVulnerabilities()), timeOutHigh); VulnerabilityReport_po.getTotalAssets().getText().then(function(text) { total_assets = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.presenceOf(VulnerabilityReport_po.getTotalVulnerabilities()), timeOutHigh); VulnerabilityReport_po.getTotalOccurrences().getText().then(function(text) { total_occurrences = parseInt(text.replace(/,/g, ''), 10); }); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkDistribution()), timeOutHigh).then(function() { browser.sleep(4000); VulnerabilityReport_po.getDonuts().then(function(items) { for (let i = 1; i <= items.length; i++) { let vuln_lhs; let vuln_rhs; let assets_lhs; let assets_rhs; let occur_lhs; let occur_rhs; VulnerabilityReport_po.getDynamicElement(i, 2, 2).getText().then(function(eachText){ vuln_lhs = parseInt(eachText.replace(/,/g, ''), 10); }); VulnerabilityReport_po.getDynamicElement(i, 2, 3).getText().then(function(eachText){ vuln_rhs = parseInt(eachText.replace(/,/g, ''), 10); }); VulnerabilityReport_po.getDynamicElement(i, 3, 2).getText().then(function(eachText){ assets_lhs = parseInt(eachText.replace(/,/g, ''), 10); }); VulnerabilityReport_po.getDynamicElement(i, 3, 3).getText().then(function(eachText){ assets_rhs = parseInt(eachText.replace(/,/g, ''), 10); }); VulnerabilityReport_po.getDynamicElement(i, 4, 2).getText().then(function(eachText){ occur_lhs = parseInt(eachText.replace(/,/g, ''), 10); }); VulnerabilityReport_po.getDynamicElement(i, 4, 3).getText().then(function(eachText){ occur_rhs = parseInt(eachText.replace(/,/g, ''), 10); expect(vuln_lhs + vuln_rhs).toEqual(total_vulnerabilities); expect(assets_lhs + assets_rhs).toEqual(total_assets); expect(occur_lhs + occur_rhs).toEqual(total_occurrences); }); } }); }); }); it('Change filters and verify components refresh', () => { browser.wait(EC.visibilityOf(VulnerabilityReport_po.filterClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.filterClick()), timeOutHigh); VulnerabilityReport_po.filterClick().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.applyClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.applyClick()), timeOutHigh); VulnerabilityReport_po.applyClick().click(); browser.wait(EC.presenceOf(VulnerabilityReport_po.getScanPercent()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getActionsToRemediate()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getPerformersTable()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkDistribution()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkTrend()), timeOutHigh); expect(VulnerabilityReport_po.getScanPercent().getText()).toContain('scan coverage'); browser.wait(EC.visibilityOf(VulnerabilityReport_po.filterClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.filterClick()), timeOutHigh); VulnerabilityReport_po.filterClick().click(); browser.wait(EC.visibilityOf(VulnerabilityReport_po.applyClick()), timeOutHigh); browser.wait(EC.elementToBeClickable(VulnerabilityReport_po.applyClick()), timeOutHigh); VulnerabilityReport_po.applyClick().click(); }); it('Verify change of asset group', () => { browser.get(domain + '/pl/(compliance/compliance-dashboard//modal:change-default-asset-group//modalBGMenu:vulnerability-report)?ag=aws-all&domain=Infra%20%26%20Platforms#dtd-vulnerability'); browser.wait(EC.visibilityOf(AssetGroups_po.getAllPath()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetGroups_po.getAllPath()), timeOutHigh); AssetGroups_po.getAllPath().click(); browser.wait(EC.visibilityOf(AssetGroups_po.getAssetGroupSearch()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetGroups_po.getAssetGroupSearch()), timeOutHigh); AssetGroups_po.getAssetGroupSearch().click(); AssetGroups_po.getAssetGroupSearch().sendKeys('adapt'); browser.sleep(100); browser.wait(EC.visibilityOf(AssetGroups_po.getFirstAssetGroup()), timeOutHigh); browser.wait(EC.visibilityOf(AssetGroups_po.clickFirstAssetGroup()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetGroups_po.clickFirstAssetGroup()), timeOutHigh); AssetGroups_po.clickFirstAssetGroup().click(); browser.wait(EC.visibilityOf(AssetGroups_po.getSetDefault()), timeOutHigh); browser.wait(EC.elementToBeClickable(AssetGroups_po.getSetDefault()), timeOutHigh); AssetGroups_po.getSetDefault().click(); browser.wait(EC.presenceOf(VulnerabilityReport_po.getScanPercent()), timeOutHigh); expect(VulnerabilityReport_po.getScanPercent().getText()).toContain('scan coverage'); browser.wait(EC.presenceOf(VulnerabilityReport_po.getActionsToRemediate()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getPerformersTable()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkDistribution()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.checkTrend()), timeOutHigh); browser.wait(EC.presenceOf(VulnerabilityReport_po.getAgSelected()), timeOutHigh); VulnerabilityReport_po.getAgSelected().getText().then(function(text) { expect(text.toLowerCase()).toContain('adapt'); browser.get(domain + '/pl/(compliance/compliance-dashboard//modalBGMenu:vulnerability-report)?ag=aws-all&domain=Infra%20%26%20Platforms'); }); }); });
the_stack
import * as firebase from '@firebase/testing'; import * as fs from 'fs'; import { Offer, OfferFirestoreConverter, OfferStatus } from '../src/models/offers'; import { Questionnaire, QuestionnaireFirestoreConverter, QuestionnaireType } from '../src/models/questionnaires'; import { User, UserFirestoreConverter } from '../src/models/users'; import { Request, RequestFirestoreConverter } from '../src/models/requests'; import * as firebaseApp from 'firebase-admin'; import GeoPoint = firebaseApp.firestore.GeoPoint; const projectId = 'reach-4-help-test'; const rules = fs.readFileSync(`${__dirname}/../../firebase/firestore.rules`, 'utf8'); /** * Creates a new app with authentication data matching the input. * * @param {object} auth the object to use for authentication (typically {uid: some-uid}) * @return {object} the app. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any const authedApp = (auth?: object) => { return firebase.initializeTestApp({ projectId, auth }).firestore(); }; /** * Creates a new app with admin authentication. * * @return {object} the app. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any const adminApp = () => { return firebase.initializeAdminApp({ projectId }).firestore(); }; beforeAll(async () => { await firebase.loadFirestoreRules({ projectId, rules }); }); beforeEach(async () => { // Clear the database between tests await firebase.clearFirestoreData({ projectId }); }); afterAll(async () => { await Promise.all(firebase.apps().map(app => app.delete())); }); describe('users', () => { it('require users to log in before reading a profile', async () => { const db = authedApp(); const profile = db.collection('users').doc('1234'); await firebase.assertFails(profile.get()); }); it('require users to log in before listing profiles', async () => { const db = authedApp(); const profile = db.collection('users'); await firebase.assertFails(profile.get()); }); it('authenticated users can read other users profiles', async () => { const db = authedApp({ uid: '1234' }); const profile = db.collection('users').doc('5678'); await firebase.assertSucceeds(profile.get()); }); it('authenticated users can list users profiles', async () => { const db = authedApp({ uid: '1234' }); const profile = db.collection('users'); await firebase.assertSucceeds(profile.get()); }); it('require users to log in before creating a profile', async () => { const db = authedApp(); const profile = db.collection('users').doc('1234'); await firebase.assertFails( profile.withConverter(UserFirestoreConverter).set( User.factory({ username: 'test_user', }), ), ); }); it('users can only write to their own profile', async () => { const db = authedApp({ uid: '1234' }); const profile = db.collection('users').doc('5678'); await firebase.assertFails( profile.withConverter(UserFirestoreConverter).set( User.factory({ username: 'test_user', }), ), ); }); it('user id chain must be intact when writing to user.privilegedInformation', async () => { const db = authedApp({ uid: '1234' }); const data = db .collection('users') .doc('1234') .collection('privilegedInformation') .doc('5678'); await firebase.assertFails( data.set({ address: { a: 1 }, termsAccepted: firebase.firestore.FieldValue.serverTimestamp(), termsVersion: '1.0', }), ); }); it('should enforce the correct user data in users collection', async () => { const db = authedApp({ uid: '1234' }); const profile = db.collection('users').doc('1234'); await firebase.assertFails(profile.set({ username: 'test_user' })); await firebase.assertSucceeds( profile.withConverter(UserFirestoreConverter).set( User.factory({ username: 'test_user', }), ), ); }); it('should enforce the correct user data in user.privilegedInformation collection', async () => { const db = authedApp({ uid: '1234' }); const data = db .collection('users') .doc('1234') .collection('privilegedInformation') .doc('1234'); await firebase.assertFails(data.set({ fail: 'missing-keys' })); await firebase.assertSucceeds( data.set({ address: { a: 1 }, termsAccepted: firebase.firestore.FieldValue.serverTimestamp(), termsVersion: '1.0', }), ); }); }); describe('offers', () => { const createData = async () => { const db = adminApp(); await firebase.assertSucceeds( db .collection('users') .doc('pin-1') .withConverter(UserFirestoreConverter) .set( User.factory({ username: 'pin-1', }), ), ); await firebase.assertSucceeds( db .collection('users') .doc('cav-1') .withConverter(UserFirestoreConverter) .set( User.factory({ username: 'cav-1', }), ), ); await firebase.assertSucceeds( db .collection('users') .doc('cav-2') .withConverter(UserFirestoreConverter) .set( User.factory({ username: 'cav-2', }), ), ); const requestSnapshot = Request.factory({ pinUserRef: db.collection('users').doc('pin-1') as any, pinUserSnapshot: { username: 'pin-1' }, title: 'I need help!', description: 'Please help with groceries', latLng: new GeoPoint(10, -122), streetAddress: '123 Main St.', }); await firebase.assertSucceeds( db .collection('offers') .doc('offer-1') .withConverter(OfferFirestoreConverter) .set( Offer.factory({ cavUserRef: db.collection('users').doc('cav-1') as any, pinUserRef: db.collection('users').doc('pin-1') as any, requestRef: db.collection('requests').doc('request-1') as any, requestSnapshot, cavUserSnapshot: { averageRating: 1, casesCompleted: 0, requestsMade: 0, username: 'cav-1', }, message: 'I can help!', status: OfferStatus.pending, }), ), ); await firebase.assertSucceeds( db .collection('offers') .doc('offer-2') .withConverter(OfferFirestoreConverter) .set( Offer.factory({ cavUserRef: db.collection('users').doc('cav-2') as any, pinUserRef: db.collection('users').doc('pin-1') as any, requestRef: db.collection('requests').doc('request-1') as any, requestSnapshot, cavUserSnapshot: { averageRating: 1, casesCompleted: 0, requestsMade: 0, username: 'cav-2', }, message: 'I can help!!', status: OfferStatus.pending, }), ), ); }; it('require users to log in before listing offers', async () => { const db = authedApp(); const offers = db.collection('offers'); await firebase.assertFails(offers.get()); }); it('only pins can list offers that belong to them', async () => { await createData(); // Read from DB authed as PIN2, but filter by PIN1 - ERROR const dbPin2 = authedApp({ uid: 'pin-2', pin: true }); const pin1RefAsPin2 = dbPin2.collection('users').doc('pin-1'); const offer1RefAsPin2 = dbPin2.collection('offers').doc('offer-1'); await firebase.assertFails( dbPin2 .collection('offers') .where('pinUserRef', '==', pin1RefAsPin2) .get(), ); await firebase.assertFails(offer1RefAsPin2.get()); // Read from DB authed as PIN1, filter by PIN1 - SUCCESS const dbPin1 = authedApp({ uid: 'pin-1', pin: true }); const pin1Ref = dbPin1.collection('users').doc('pin-1'); const offer1RefAsPin1 = dbPin1.collection('offers').doc('offer-1'); await firebase.assertSucceeds( dbPin1 .collection('offers') .where('pinUserRef', '==', pin1Ref) .withConverter(OfferFirestoreConverter) .get() .then(querySnapshot => { querySnapshot.docs .map(value => value.data()) .forEach(offer => { expect(offer.pinUserRef.id).toBe('pin-1'); }); }), ); await firebase.assertSucceeds( offer1RefAsPin1 .withConverter(OfferFirestoreConverter) .get() .then(doc => { expect(doc.exists).toBeTruthy(); }), ); }); it('only cavs can list offers that belong to them', async () => { await createData(); // Read from DB authed as CAV3, but filter by CAV1 - ERROR const dbCav3 = authedApp({ uid: 'cav-3', cav: true }); const cav1RefAsCav3 = dbCav3.collection('users').doc('cav-1'); const offer1RefAsCav3 = dbCav3.collection('offers').doc('offer-1'); await firebase.assertFails( dbCav3 .collection('offers') .where('cavUserRef', '==', cav1RefAsCav3) .get(), ); await firebase.assertFails(offer1RefAsCav3.get()); // Read from DB authed as CAV1, filter by CAV1 - SUCCESS const dbCav1 = authedApp({ uid: 'cav-1', cav: true }); const cav1Ref = dbCav1.collection('users').doc('cav-1'); const offer1RefAsCav1 = dbCav1.collection('offers').doc('offer-1'); await firebase.assertSucceeds( dbCav1 .collection('offers') .where('cavUserRef', '==', cav1Ref) .withConverter(OfferFirestoreConverter) .get() .then(querySnapshot => { querySnapshot.docs .map(value => value.data()) .forEach(offer => { expect(offer.cavUserRef.id).toBe('cav-1'); }); }), ); await firebase.assertSucceeds( offer1RefAsCav1 .withConverter(OfferFirestoreConverter) .get() .then(doc => { expect(doc.exists).toBeTruthy(); }), ); }); // Check this for more info: https://firebase.google.com/docs/firestore/security/rules-conditions it('Users cannot list the entire offers collection without a query on PIN or CAV', async () => { // Even though there is only data with pin-1 as the ref... const dbPin1 = authedApp({ uid: 'pin-1', pin: true }); await firebase.assertFails(dbPin1.collection('offers').get()); // Would fail anyways as all the records mention pin-1 as the ref... const dbPin2 = authedApp({ uid: 'pin-2', pin: true }); await firebase.assertFails(dbPin2.collection('offers').get()); }); }); describe('requests', () => { const createData = async () => { const db = adminApp(); const user = User.factory({ username: 'pin-1' }); const userRef = db.collection('users').doc('pin-1'); await firebase.assertSucceeds(userRef.withConverter(UserFirestoreConverter).set(user)); await firebase.assertSucceeds( db .collection('questionnaires') .doc('questionnaire-1') .withConverter(RequestFirestoreConverter) .set( Request.factory({ pinUserRef: userRef as any, pinUserSnapshot: user, title: 'Sample Request', description: 'I Need Stuff', latLng: new GeoPoint(10, -122), streetAddress: '', }), ), ); }; it('require users to log in before listing requests', async () => { const db = authedApp(); const requests = db.collection('requests'); await firebase.assertFails(requests.get()); }); it('only pins and cavs can see requests', async () => { await createData(); const dbCav1 = authedApp({ uid: 'cav-1', cav: true }); const dbPin2 = authedApp({ uid: 'pin-2', pin: true }); // const dbUser = authedApp({ uid: 'user-1' }); await firebase.assertSucceeds( dbCav1 .collection('requests') .withConverter(RequestFirestoreConverter) .get(), ); await firebase.assertSucceeds( dbPin2 .collection('requests') .withConverter(RequestFirestoreConverter) .get(), ); // TODO: Re-enable once we finish the feature in the frontend for refreshing token // await firebase.assertFails( // dbUser // .collection('requests') // .withConverter(RequestFirestoreConverter) // .get(), // ); }); }); describe('questionnaires', () => { const createData = async () => { const db = adminApp(); await firebase.assertSucceeds( db .collection('questionnaires') .doc('questionnaire-1') .withConverter(QuestionnaireFirestoreConverter) .set( Questionnaire.factory({ parentRef: db.collection('users').doc('user-1'), data: { a: 1 }, type: QuestionnaireType.pin, version: '1.0', }), ), ); }; it('require users to log in before listing questionnaires', async () => { const db = authedApp(); const requests = db.collection('requests'); await firebase.assertFails(requests.get()); }); it('only the current user can access their questionnaires', async () => { await createData(); const userDb1 = authedApp({ uid: 'user-1' }); const user1Questionnaire = userDb1.collection('questionnaires').doc('questionnaire-1'); await firebase.assertSucceeds( user1Questionnaire .withConverter(QuestionnaireFirestoreConverter) .get() .then(doc => { expect(doc.exists).toBeTruthy(); }), ); const userDb2 = authedApp({ uid: 'user-2' }); const user1QuestionnaireAsUser2 = userDb2.collection('questionnaires').doc('questionnaire-1'); await firebase.assertFails(user1QuestionnaireAsUser2.get()); }); });
the_stack
declare namespace llvm { // bitcode/bitcodewriter import AttrKind = llvm.Attribute.AttrKind; function writeBitcodeToFile(module: Module, filename: string): void; // IR/verifier function verifyModule(mod: Module): void; function verifyFunction(fun: Function): void; // support function initializeAllTargetInfos(): void; function initializeAllTargets(): void; function initializeAllTargetMCs(): void; function initializeAllAsmParsers(): void; function initializeAllAsmPrinters(): void; namespace Attribute { enum AttrKind { Alignment, AllocSize, AlwaysInline, ArgMemOnly, Builtin, ByVal, Cold, Convergent, Dereferenceable, DereferenceableOrNull, InAlloca, InReg, InaccessibleMemOnly, InaccessibleMemOrArgMemOnly, InlineHint, JumpTable, MinSize, Naked, Nest, NoAlias, NoBuiltin, NoCapture, NoDuplicate, NoImplicitFloat, NoInline, NoRecurse, NoRedZone, NoReturn, NoUnwind, NonLazyBind, NonNull, OptimizeForSize, OptimizeNone, ReadNone, ReadOnly, Returned, ReturnsTwice, SExt, SafeStack, SanitizeAddress, SanitizeMemory, SanitizeThread, StackAlignment, StackProtect, StackProtectReq, StackProtectStrong, StructRet, SwiftError, SwiftSelf, UWTable, WriteOnly, ZExt, } } //ir enum LinkageTypes { ExternalLinkage, AvailableExternallyLinkage, LinkOnceAnyLinkage, LinkOnceODRLinkage, WeakAnyLinkage, WeakODRLinkage, AppendingLinkage, InternalLinkage, PrivateLinkage, ExternalWeakLinkage, CommonLinkage, } enum VisibilityTypes { Hidden, Default, Protected, } enum AtomicOrdering { NotAtomic, Unordered, Monotonic, Acquire, Release, AcquireRelease, SequentiallyConsistent, } class Value { static MaxAlignmentExponent: number; static MaximumAlignment: number; protected constructor(); readonly type: Type; name: string; dump?: () => void; hasName(): boolean; /** * Deletes the value. It is, therefore, forbidden to use the value any further */ release(): void; deleteValue(): void; replaceAllUsesWith(value: Value): void; useEmpty(): boolean; } class Argument extends Value { readonly argumentNumber: number; readonly parent?: Function; constructor(type: Type, name?: string, fn?: Function, argNo?: number); addAttr(kind: Attribute.AttrKind): void; hasAttribute(kind: Attribute.AttrKind): boolean; addDereferenceableAttr(bytes: number): void; } class AllocaInst extends Value { alignment: number; type: PointerType; allocatedType: Type; readonly arraySize: Value | null; private constructor(); } class BasicBlock extends Value { static create(context: LLVMContext, name?: string, parent?: Function, insertBefore?: BasicBlock): BasicBlock; private constructor(); readonly parent?: Function; readonly empty: boolean; readonly context: LLVMContext; eraseFromParent(): void; getTerminator(): Value | undefined; } class Constant extends Value { static getNullValue(type: Type): Constant; static getAllOnesValue(type: Type): Constant; protected constructor(); isNullValue(): boolean; isOneValue(): boolean; isAllOnesValue(): boolean; } class ConstantFP extends Constant { static get(context: LLVMContext, value: number): ConstantFP; static get(type: Type, value: string): Constant; static getZeroValueForNegation(type: Type): Constant; static getNegativeZero(type: Type): Constant; static getNaN(type: Type): Constant; static getInfinity(type: Type, negative?: boolean /* = false */): Constant; private constructor(); readonly value: number; } class ConstantInt extends Constant { static get(context: LLVMContext, value: number | string, numBits?: number, signed?: boolean): ConstantInt; static getFalse(context: LLVMContext): ConstantInt; static getTrue(context: LLVMContext): ConstantInt; private constructor(); readonly value: number; public toString(): string; } class ConstantPointerNull extends Constant { static get(pointerType: PointerType): ConstantPointerNull; private constructor(); } class ConstantArray extends Constant { static get(arrayType: ArrayType, elements: Constant[]): Constant; } class ConstantDataArray extends Constant { static get(llvmContext: LLVMContext, values: Uint32Array | Float32Array | Float64Array): Constant; static getString(llvmContext: LLVMContext, value: string): Constant; private constructor(); } class ConstantStruct extends Constant { static get(structType: StructType, values: Constant[]): Constant; private constructor(); } class Function extends Constant { static create(functionType: FunctionType, linkageTypes: LinkageTypes, name?: string, module?: Module): Function; callingConv: CallingConv; visibility: VisibilityTypes; type: PointerType & { elementType: FunctionType }; private constructor(); addAttribute(index: number, attribute: Attribute.AttrKind): void; addBasicBlock(basicBlock: BasicBlock): void; addDereferenceableAttr(attributeIndex: number, bytes: number): void; addDereferenceableOrNullAttr(attributeIndex: number, bytes: number): void; addFnAttr(attribute: Attribute.AttrKind): void; getArguments(): Argument[]; getEntryBlock(): BasicBlock | null; getBasicBlocks(): BasicBlock[]; viewCFG(): void; } class GlobalVariable extends Constant { constant: boolean; initializer: Constant | undefined; setUnnamedAddr(unnamedAddr: UnnamedAddr): void; hasGlobalUnnamedAddr(): boolean; constructor( module: Module, type: Type, constant: boolean, linkageType: LinkageTypes, initializer?: Constant, name?: string ); } enum UnnamedAddr { None, Local, Global, } class PhiNode extends Value { private constructor(); readonly elementType: Type; addIncoming(value: Value, basicBlock: BasicBlock): void; } class CallInst extends Value { callingConv: CallingConv; private constructor(); addDereferenceableAttr(index: number, size: number): void; hasRetAttr(kind: AttrKind): boolean; paramHasAttr(index: number, kind: AttrKind): boolean; getNumArgOperands(): number; } enum CallingConv { C, Fast, Cold, GHC, HiPE, WebKit_JS, AnyReg, PreserveMost, PreserveAll, CXX_FAST_TLS, FirstTargetCC, X86_StdCall, X86_FastCall, ARM_APCS, ARM_AAPCS, ARM_AAPCS_VFP, MSP430_INTR, X86_ThisCall, PTX_Kernel, PTX_Device, SPIR_FUNC, SPIR_KERNEL, Intel_OCL_BI, X86_64_SysV, Win64, X86_VectorCall, HHVM, HHVM_C, X86_INTR, AVR_INTR, AVR_SIGNAL, AVR_BUILTIN, AMDGPU_VS, AMDGPU_GS, AMDGPU_PS, AMDGPU_CS, AMDGPU_KERNEL, X86_RegCall, AMDGPU_HS, MSP430_BUILTIN, MaxID, } class UndefValue { private constructor(); static get(type: Type): UndefValue; } class DataLayout { constructor(layout: string); getStringRepresentation(): string; getPointerSize(as: number): number; getPrefTypeAlignment(type: Type): number; getTypeStoreSize(type: Type): number; getIntPtrType(context: LLVMContext, as: number): Type; } class Type { static TypeID: { VoidTyID: number; HalfTyID: number; FloatTyID: number; DoubleTyID: number; X86_FP80TyID: number; PPC_FP128TyID: number; LabelTyID: number; MetadataTyID: number; X86_MMXTyID: number; TokenTyID: number; IntegerTyID: number; FunctionTyID: number; StructTyID: number; ArrayTyID: number; PointerTyID: number; // LLVM 11+ FixedVectorTyID: number; ScalableVectorTyID: number; /** * @deprecated */ VectorTyID: number; }; static getFloatTy(context: LLVMContext): Type; static getDoubleTy(context: LLVMContext): Type; static getFP128Ty(context: LLVMContext): Type; static getVoidTy(context: LLVMContext): Type; static getLabelTy(context: LLVMContext): Type; static getInt1Ty(context: LLVMContext): IntegerType; static getInt8Ty(context: LLVMContext): IntegerType; static getInt16Ty(context: LLVMContext): IntegerType; static getInt32Ty(context: LLVMContext): IntegerType; static getInt64Ty(context: LLVMContext): IntegerType; static getInt128Ty(context: LLVMContext): IntegerType; static getIntNTy(context: LLVMContext, N: number): IntegerType; static getInt1PtrTy(context: LLVMContext, AS?: number): PointerType; static getInt8PtrTy(context: LLVMContext, AS?: number): PointerType; static getInt32PtrTy(context: LLVMContext, AS?: number): PointerType; static getDoublePtrTy(context: LLVMContext, AS?: number): PointerType; static getFloatPtrTy(context: LLVMContext, AS?: number): PointerType; static getHalfTy(context: LLVMContext): Type; protected constructor(); readonly typeID: number; equals(other: Type): boolean; isVoidTy(): boolean; isFloatTy(): boolean; isDoubleTy(): boolean; isFP128Ty(): boolean; isLabelTy(): boolean; isIntegerTy(bitWidth?: number): boolean; isFunctionTy(): this is FunctionType; isStructTy(): this is StructType; isArrayTy(): boolean; isHalfTy(): boolean; isPointerTy(): this is PointerType; getPointerTo(addressSpace?: number): PointerType; getPrimitiveSizeInBits(): number; toString(): string; } class IntegerType extends Type { private constructor(); getBitWidth(): number; } class FunctionType extends Type { static get(result: Type, isVarArg: boolean): FunctionType; static get(result: Type, params: Type[], isVarArg: boolean): FunctionType; static isValidReturnType(type: Type): boolean; static isValidArgumentType(type: Type): boolean; readonly returnType: Type; readonly isVarArg: boolean; readonly numParams: number; private constructor(); getParams(): Type[]; getParamType(index: number): Type; } class PointerType extends Type { static get(elementType: Type, AS: number): PointerType; elementType: Type; private constructor(); } class ArrayType extends Type { static get(elementType: Type, numElements: number): ArrayType; readonly elementType: Type; readonly numElements: number; private constructor(); } class StructType extends Type { static create(context: LLVMContext, name?: string): StructType; static get(context: LLVMContext, elements: Type[], isPacked?: boolean): StructType; name: string | undefined; readonly numElements: number; private constructor(); getElementType(index: number): Type; setBody(elements: Type[], packed?: boolean): void; } class IRBuilder { constructor(context: LLVMContext); constructor(basicBlock: BasicBlock, beforeInstruction?: Value); setInsertionPoint(basicBlock: BasicBlock): void; createAdd(lhs: Value, rhs: Value, name?: string): Value; createAlloca(type: Type, arraySize?: Value, name?: string): AllocaInst; createAlignedLoad(ptr: Value, align: number, name?: string): Value; createAlignedStore(value: Value, ptr: Value, align: number, isVolatile?: boolean): Value; createAnd(lhs: Value, rhs: Value, name?: string): Value; createAShr(lhs: Value, rhs: Value, name?: string): Value; createAtomicRMW(op: AtomicRMWInst.BinOp, ptr: Value, value: Value, ordering: AtomicOrdering): Value; createBitCast(value: Value, destType: Type, name?: string): Value; createBr(basicBlock: BasicBlock): Value; /** * @deprecated */ createCall(callee: Value, args: Value[], name?: string): CallInst; createCall(functionType: FunctionType, callee: Value, args: Value[], name?: string): CallInst; createCondBr(condition: Value, then: BasicBlock, elseBlock: BasicBlock): Value; createExtractValue(agg: Value, idxs: number[], name?: string): Value; createFAdd(lhs: Value, rhs: Value, name?: string): Value; createFCmpOGE(lhs: Value, rhs: Value, name?: string): Value; createFCmpOGT(lhs: Value, rhs: Value, name?: string): Value; createFCmpOLE(lhs: Value, rhs: Value, name?: string): Value; createFCmpOLT(lhs: Value, rhs: Value, name?: string): Value; createFCmpOEQ(lhs: Value, rhs: Value, name?: string): Value; createFCmpONE(lhs: Value, rhs: Value, name?: string): Value; createFCmpUGE(lhs: Value, rhs: Value, name?: string): Value; createFCmpUGT(lhs: Value, rhs: Value, name?: string): Value; createFCmpULE(lhs: Value, rhs: Value, name?: string): Value; createFCmpULT(lhs: Value, rhs: Value, name?: string): Value; createFCmpUEQ(lhs: Value, rhs: Value, name?: string): Value; createFCmpUNE(lhs: Value, rhs: Value, name?: string): Value; createFDiv(lhs: Value, rhs: Value, name?: string): Value; createFNeg(value: Value, name?: string): Value; createFMul(lhs: Value, rhs: Value, name?: string): Value; createFRem(lhs: Value, rhs: Value, name?: string): Value; createFSub(lhs: Value, rhs: Value, name?: string): Value; createFPToSI(value: Value, type: Type, name?: string): Value; createGlobalString(str: string, name?: string, addressSpace?: number): Value; createGlobalStringPtr(str: string, name?: string, addressSpace?: number): Value; createInBoundsGEP(ptr: Value, idxList: Value[], name?: string): Value; createInBoundsGEP(type: Type, ptr: Value, idxList: Value[], name?: string): Value; createInsertValue(agg: Value, val: Value, idxList: number[], name?: string): Value; createIntCast(vlaue: Value, type: Type, isSigned: boolean, name?: string): Value; createICmpEQ(lhs: Value, rhs: Value, name?: string): Value; createICmpNE(lhs: Value, rhs: Value, name?: string): Value; createICmpSGE(lhs: Value, rhs: Value, name?: string): Value; createICmpSGT(lhs: Value, rhs: Value, name?: string): Value; createICmpSLE(lhs: Value, rhs: Value, name?: string): Value; createICmpSLT(lhs: Value, rhs: Value, name?: string): Value; createICmpUGE(lhs: Value, rhs: Value, name?: string): Value; createICmpUGT(lhs: Value, rhs: Value, name?: string): Value; createICmpULE(lhs: Value, rhs: Value, name?: string): Value; createICmpULT(lhs: Value, rhs: Value, name?: string): Value; createLoad(ptr: Value, name?: string): Value; createLShr(lhs: Value, rhs: Value, name?: string): Value; createMul(lhs: Value, rhs: Value, name?: string): Value; createNeg(value: Value, name?: string, hasNUW?: boolean, hasNSW?: boolean): Value; createNot(value: Value, name?: string): Value; createOr(lhs: Value, rhs: Value, name?: string): Value; createXor(lhs: Value, rhs: Value, name?: string): Value; createPhi(type: Type, numReservedValues: number, name?: string): PhiNode; createPtrToInt(value: Value, destType: Type, name?: string): Value; createIntToPtr(value: Value, destType: Type, name?: string): Value; createRet(value: Value): Value; createRetVoid(): Value; createSelect(condition: Value, trueValue: Value, falseValue: Value, name?: string): Value; createSDiv(lhs: Value, rhs: Value, name?: string): Value; createShl(lhs: Value, rhs: Value, name?: string): Value; createSIToFP(value: Value, type: Type, name?: string): Value; createUIToFP(value: Value, type: Type, name?: string): Value; createSub(lhs: Value, rhs: Value, name?: string): Value; createStore(value: Value, ptr: Value, isVolatile?: boolean): Value; createSRem(lhs: Value, rhs: Value, name?: string): Value; CreateURem(lhs: Value, rhs: Value, name?: string): Value; createZExt(value: Value, destType: Type, name?: string): Value; getInsertBlock(): BasicBlock | undefined; } namespace AtomicRMWInst { enum BinOp { Add, Sub, And, Nand, Or, Xor, Max, Min, UMax, UMin, } } class LLVMContext { constructor(); // any property that makes ts emits an error if any other object is passed to a method that is not an llvm context private __marker: number; } interface FunctionCallee { callee: Value; functionType: FunctionType; } class Module { empty: boolean; readonly name: string; moduleIdentifier: string; sourceFileName: string; dataLayout: DataLayout; targetTriple: string; constructor(moduleId: string, context: LLVMContext); dump?: () => void; print(): string; getFunction(name: string): Function | undefined; getOrInsertFunction(name: string, functionType: FunctionType): FunctionCallee; getGlobalVariable(name: string, allowInternal?: boolean): GlobalVariable; getTypeByName(name: string): StructType | null; } // support class TargetRegistry { private constructor(); static lookupTarget(target: string): Target; } interface Target { readonly name: string; readonly shortDescription: string; createTargetMachine(triple: string, cpu: string): TargetMachine; } interface TargetMachine { createDataLayout(): DataLayout; } export const config: Readonly<{ LLVM_VERSION_MAJOR: number; LLVM_VERSION_MINOR: number; LLVM_VERSION_PATCH: number; LLVM_VERSION_STRING: string; LLVM_DEFAULT_TARGET_TRIPLE: string; }>; } export = llvm; export as namespace llvm;
the_stack
import * as React from "react"; import { Color, getColorConverter } from "../../core"; import { ColorPalette, addPowerBIThemeColors, predefinedPalettes, } from "../resources"; import { classNames } from "../utils"; import { Button } from "../views/panels/widgets/controls"; import { ColorSpaceDescription, ColorSpacePicker } from "./color_space_picker"; import { AppStore } from "../stores"; const sRGB_to_HCL = getColorConverter("sRGB", "hcl"); const HCL_to_sRGB = getColorConverter("hcl", "sRGB"); export function colorToCSS(color: Color) { return `rgb(${color.r.toFixed(0)},${color.g.toFixed(0)},${color.b.toFixed( 0 )})`; } function HSVtoRGB( h: number, s: number, v: number ): [number, number, number, boolean] { h /= 360; s /= 100; v /= 100; let r, g, b; const i = Math.floor(h * 6); const f = h * 6 - i; const p = v * (1 - s); const q = v * (1 - f * s); const t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: (r = v), (g = t), (b = p); break; case 1: (r = q), (g = v), (b = p); break; case 2: (r = p), (g = v), (b = t); break; case 3: (r = p), (g = q), (b = v); break; case 4: (r = t), (g = p), (b = v); break; case 5: (r = v), (g = p), (b = q); break; } return [ Math.max(0, Math.min(255, r * 255)), Math.max(0, Math.min(255, g * 255)), Math.max(0, Math.min(255, b * 255)), false, ]; } function RGBtoHSV(r: number, g: number, b: number): [number, number, number] { const max = Math.max(r, g, b), min = Math.min(r, g, b), d = max - min, s = max === 0 ? 0 : d / max, v = max / 255; let h; switch (max) { case min: h = 0; break; case r: h = g - b + d * (g < b ? 6 : 0); h /= 6 * d; break; case g: h = b - r + d * 2; h /= 6 * d; break; case b: h = r - g + d * 4; h /= 6 * d; break; } return [h * 360, s * 100, v * 100]; } export class HSVColorPicker extends React.Component< { defaultValue: Color; onChange?: (newValue: Color) => void; }, {} > { public static colorSpaces: ColorSpaceDescription[] = [ { name: "Hue", description: "Saturation, Value | Hue", dimension1: { name: "Hue", range: [360, 0] }, dimension2: { name: "Saturation", range: [0, 100] }, dimension3: { name: "Value", range: [100, 0] }, toRGB: HSVtoRGB, fromRGB: RGBtoHSV, }, { name: "Saturation", description: "Hue, Value | Saturation", dimension1: { name: "Saturation", range: [100, 0] }, dimension2: { name: "Hue", range: [360, 0] }, dimension3: { name: "Value", range: [100, 0] }, toRGB: (x1, x2, x3) => HSVtoRGB(x2, x1, x3), fromRGB: (r, g, b) => { const [h, s, v] = RGBtoHSV(r, g, b); return [s, h, v]; }, }, { name: "Value", description: "Hue, Saturation | Value", dimension1: { name: "Value", range: [100, 0] }, dimension2: { name: "Hue", range: [360, 0] }, dimension3: { name: "Saturation", range: [100, 0] }, toRGB: (x1, x2, x3) => HSVtoRGB(x2, x3, x1), fromRGB: (r, g, b) => { const [h, s, v] = RGBtoHSV(r, g, b); return [v, h, s]; }, }, ]; public render() { return ( <ColorSpacePicker {...this.props} colorSpaces={HSVColorPicker.colorSpaces} /> ); } } export class HCLColorPicker extends React.Component< { defaultValue: Color; onChange?: (newValue: Color) => void; }, {} > { public static colorSpaces: ColorSpaceDescription[] = [ { name: "Lightness", description: "Hue, Chroma | Lightness", dimension1: { name: "Lightness", range: [100, 0] }, dimension2: { name: "Hue", range: [0, 360] }, dimension3: { name: "Chroma", range: [100, 0] }, toRGB: (x1: number, x2: number, x3: number) => HCL_to_sRGB(x2, x3, x1) as [number, number, number, boolean], fromRGB: (r: number, g: number, b: number) => { const [h, c, l] = sRGB_to_HCL(r, g, b); return [l, h, c]; }, }, { name: "Hue", description: "Chroma, Lightness | Hue", dimension1: { name: "Hue", range: [0, 360] }, dimension2: { name: "Chroma", range: [0, 100] }, dimension3: { name: "Lightness", range: [100, 0] }, toRGB: (x1: number, x2: number, x3: number) => HCL_to_sRGB(x1, x2, x3) as [number, number, number, boolean], fromRGB: (r: number, g: number, b: number) => sRGB_to_HCL(r, g, b) as [number, number, number], }, { name: "Chroma", description: "Hue, Lightness | Chroma", dimension1: { name: "Chroma", range: [100, 0] }, dimension2: { name: "Hue", range: [0, 360] }, dimension3: { name: "Lightness", range: [100, 0] }, toRGB: (x1: number, x2: number, x3: number) => HCL_to_sRGB(x2, x1, x3) as [number, number, number, boolean], fromRGB: (r: number, g: number, b: number) => { const [h, c, l] = sRGB_to_HCL(r, g, b); return [c, h, l]; }, }, ]; public render() { return ( <ColorSpacePicker {...this.props} colorSpaces={HCLColorPicker.colorSpaces} /> ); } } export interface ColorPickerProps { defaultValue?: Color; allowNull?: boolean; onPick?: (color: Color) => void; store?: AppStore; } export interface ColorPickerState { currentPalette?: ColorPalette; currentPicker?: string; currentColor?: Color; } export interface ColorGridProps { defaultValue?: Color; colors: Color[][]; onClick?: (color: Color) => void; } export class ColorGrid extends React.PureComponent<ColorGridProps, {}> { public render() { return ( <div className="color-grid"> {this.props.colors.map((colors, index) => ( <div className="color-row" key={`m${index}`}> {colors.map((color, i) => ( <span key={`m${i}`} className={classNames("color-item", [ "active", this.props.defaultValue != null && colorToCSS(this.props.defaultValue) == colorToCSS(color), ])} onClick={() => { if (this.props.onClick) { this.props.onClick(color); } }} > <span style={{ backgroundColor: colorToCSS(color) }} /> </span> ))} </div> ))} </div> ); } } export interface PaletteListProps { selected: ColorPalette; palettes: ColorPalette[]; onClick?: (palette: ColorPalette) => void; } export class PaletteList extends React.PureComponent<PaletteListProps, {}> { public render() { const palettes = this.props.palettes; const groups: [string, ColorPalette[]][] = []; const group2Index = new Map<string, number>(); for (const p of palettes) { const groupName = p.name.split("/")[0]; let group: ColorPalette[]; if (group2Index.has(groupName)) { group = groups[group2Index.get(groupName)][1]; } else { group = []; group2Index.set(groupName, groups.length); groups.push([groupName, group]); } group.push(p); } return ( <ul> {groups.map((group, index) => { return ( <li key={`m${index}`}> <div className="label">{group[0]}</div> <ul> {group[1].map((x) => ( <li key={x.name} className={classNames("item", [ "active", this.props.selected == x, ])} onClick={() => this.props.onClick(x)} > {x.name.split("/")[1]} </li> ))} </ul> </li> ); })} </ul> ); } } export class ColorPicker extends React.Component< ColorPickerProps, ColorPickerState > { constructor(props: ColorPickerProps) { super(props); addPowerBIThemeColors(); if (this.props.defaultValue) { const colorCSS = colorToCSS(this.props.defaultValue); let matchedPalette: ColorPalette = null; for (const p of predefinedPalettes.filter((x) => x.type == "palette")) { for (const g of p.colors) { for (const c of g) { if (colorToCSS(c) == colorCSS) { matchedPalette = p; break; } } if (matchedPalette) { break; } } if (matchedPalette) { break; } } if (matchedPalette) { this.state = { currentPalette: matchedPalette, currentPicker: null, currentColor: this.props.defaultValue, }; } else { this.state = { currentPalette: null, currentPicker: "hcl", currentColor: this.props.defaultValue, }; } } else { this.state = { currentPalette: predefinedPalettes.filter( (x) => x.name == "Palette/ColorBrewer" )[0], currentPicker: null, }; } } public render() { return ( <div className="color-picker"> <section className="color-picker-left"> <div className="color-picker-palettes-list"> <ul> <li> <div className="label">ColorPicker</div> <ul> <li className={classNames("item", [ "active", this.state.currentPicker == "hcl", ])} onClick={() => { this.setState({ currentPalette: null, currentPicker: "hcl", }); }} > HCL Picker </li> <li className={classNames("item", [ "active", this.state.currentPicker == "hsv", ])} onClick={() => { this.setState({ currentPalette: null, currentPicker: "hsv", }); }} > HSV Picker </li> </ul> </li> </ul> <PaletteList palettes={predefinedPalettes.filter((x) => x.type == "palette")} selected={this.state.currentPalette} onClick={(p) => { this.setState({ currentPalette: p, currentPicker: null }); }} /> </div> {this.props.allowNull ? ( <div className="color-picker-null"> <Button text={"none"} icon="ChromeClose" onClick={() => { this.setState({ currentColor: null, }); this.props.onPick(null); }} /> </div> ) : null} </section> <section className="colors"> {this.state.currentPalette != null ? ( <ColorGrid colors={this.state.currentPalette.colors} defaultValue={this.state.currentColor} onClick={(c) => { this.props.onPick(c); this.setState({ currentColor: c }); }} /> ) : null} {this.state.currentPicker == "hcl" ? ( <HCLColorPicker defaultValue={this.state.currentColor || { r: 0, g: 0, b: 0 }} onChange={(c) => { this.props.onPick(c); this.setState({ currentColor: c }); }} /> ) : null} {this.state.currentPicker == "hsv" ? ( <HSVColorPicker defaultValue={this.state.currentColor || { r: 0, g: 0, b: 0 }} onChange={(c) => { this.props.onPick(c); this.setState({ currentColor: c }); }} /> ) : null} </section> </div> ); } }
the_stack
import { Trigger } from "@akashic/trigger"; import { AssetConfiguration, AssetManager, E, Scene, SceneStateString, StorageRegion } from ".."; import { customMatchers, Game, skeletonRuntime, ImageAsset, AudioAsset } from "./helpers"; expect.extend(customMatchers); describe("test Scene", () => { const assetsConfiguration: { [path: string]: AssetConfiguration } = { foo: { type: "image", path: "/path1.png", virtualPath: "path1.png", width: 1, height: 1 }, baa: { type: "image", path: "/path2.png", virtualPath: "path2.png", width: 1, height: 1 } }; const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); it("初期化 - SceneParameterObject", () => { const scene = new Scene({ game: game, assetIds: ["foo"], local: "interpolate-local", tickGenerationMode: "manual", name: "myScene" }); expect(scene.game).toBe(game); expect(scene.onAssetLoad.length).toEqual(0); expect(scene.onAssetLoadFailure.length).toEqual(0); expect(scene.onAssetLoadComplete.length).toEqual(0); expect(scene.onLoad.length).toEqual(0); expect(scene.children).not.toBeFalsy(); expect(scene.children.length).toBe(0); expect(scene._sceneAssetHolder._assetIds).toEqual(["foo"]); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(1); expect(scene.local).toBe("interpolate-local"); expect(scene.tickGenerationMode).toBe("manual"); expect(scene.name).toEqual("myScene"); expect(scene.onUpdate instanceof Trigger).toBe(true); expect(scene.onLoad instanceof Trigger).toBe(true); expect(scene.onAssetLoad instanceof Trigger).toBe(true); expect(scene.onAssetLoadFailure instanceof Trigger).toBe(true); expect(scene.onAssetLoadComplete instanceof Trigger).toBe(true); expect(scene.onStateChange instanceof Trigger).toBe(true); expect(scene.onMessage instanceof Trigger).toBe(true); expect(scene.onPointDownCapture instanceof Trigger).toBe(true); expect(scene.onPointMoveCapture instanceof Trigger).toBe(true); expect(scene.onPointUpCapture instanceof Trigger).toBe(true); expect(scene.onOperation instanceof Trigger).toBe(true); }); it("初期化 - Storage", () => { let scene = new Scene({ game: game }); expect(scene._storageLoader).toBeUndefined(); const key = { region: StorageRegion.Values, regionKey: "foo.bar", gameId: "123", userId: "456" }; scene = new Scene({ game: game, storageKeys: [key] }); expect(scene._storageLoader).toBeDefined(); expect(scene.storageValues).toBeDefined(); }); it("append", () => { const scene1 = new Scene({ game: game }); const scene2 = new Scene({ game: game }); const e = new E({ scene: scene1 }); scene1.append(e); expect(e.parent).toBe(scene1); scene2.append(e); expect(e.parent).toBe(scene2); }); it("remove", () => { const scene1 = new Scene({ game: game }); const scene2 = new Scene({ game: game }); const e1 = new E({ scene: scene1 }); const e2 = new E({ scene: scene2 }); scene1.append(e1); scene2.append(e2); expect(e1.parent).toBe(scene1); scene1.remove(e1); expect(e1.parent).toBeUndefined(); expect(scene1.remove(e2)).toBeUndefined(); // e2 is not child of scene1 expect(e2.parent).toBe(scene2); scene2.remove(e2); expect(e2.parent).toBeUndefined(); }); it("insertBefore", () => { const scene1 = new Scene({ game: game }); const scene2 = new Scene({ game: game }); const e = new E({ scene: scene1 }); scene1.insertBefore(e, undefined); expect(e.parent).toBe(scene1); scene2.insertBefore(e, undefined); expect(e.parent).toBe(scene2); const e2 = new E({ scene: scene2 }); scene2.insertBefore(e2, e); expect(scene2.children[0]).toBe(e2); expect(scene2.children[1]).toBe(e); }); it("loads assets", done => { const scene = new Scene({ game: game, assetIds: ["foo", "baa"], name: "SceneToLoadAsset" }); scene._onReady.add(() => { expect(scene.assets.foo).not.toBeUndefined(); expect(scene.assets.bar).toBeUndefined(); expect(scene.assets.baa).not.toBeUndefined(); expect(scene.asset.getImageById("foo").path).toBe("/path1.png"); expect(() => scene.asset.getImage("/unexistent.png")).toThrowError("AssertionError"); done(); }); scene._load(); }); it("loads storage", done => { const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const values = [[{ data: "apple" }]]; const scene = new Scene({ game: game, storageKeys: keys, name: "SceneLoadsStorage" }); game.storage._registerLoad((_keys, loader) => { loader._onLoaded(values); }); scene._onReady.add(() => { expect(scene._storageLoader!._loaded).toBe(true); expect(scene.storageValues!.get(0)).toBe(values[0]); done(); }); scene._load(); }); it("serializedValues", done => { const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const values = [[{ data: "apple" }]]; const scene = new Scene({ game: game, storageKeys: keys }); game.storage._registerLoad((_keys, loader) => { loader._onLoaded(values); }); scene._onReady.add(() => { expect(scene._storageLoader!._loaded).toBe(true); expect(scene.serializeStorageValues()).toBeUndefined(); done(); }); scene._load(); }); it("loads storage - with serialization", done => { const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const values = [[{ data: "apple" }]]; const serializedValues = [[{ data: "orange" }]]; const scene = new Scene({ game: game, storageKeys: keys, storageValuesSerialization: "myserialization1" }); game.storage._registerLoad((_keys, loader) => { if (!loader._valueStoreSerialization) { loader._onLoaded(values); } else { expect(loader._valueStoreSerialization).toBe("myserialization1"); loader._onLoaded(serializedValues); } }); scene._onReady.add(() => { expect(scene._storageLoader!._loaded).toBe(true); expect(scene.serializeStorageValues()).toBe("myserialization1"); expect(scene.storageValues!.get(0)).toBe(serializedValues[0]); done(); }); scene._load(); }); it("loads assets and storage", done => { const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const values = [[{ data: "apple" }]]; const scene = new Scene({ game: game, storageKeys: keys, assetIds: ["foo", "baa"] }); game.storage._registerLoad((_k, l) => { l._onLoaded(values); }); scene._onReady.add(() => { expect(scene._storageLoader).toBeDefined(); expect(scene.storageValues!.get(0)).toBe(values[0]); expect(scene.assets.foo).toBeDefined(); expect(scene.assets.baa).toBeDefined(); done(); }); scene._load(); }); it("prefetch - called after _load()", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; scene._onReady.add(() => { expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(false); done(); }); scene._load(); expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(false); setTimeout(() => { scene.prefetch(); // _load() 後の呼び出しでは prefetch() の呼び出しを無視する expect(scene._prefetchRequested).toBe(false); // _load() / prefetch() されていても flushDelayedAssets() してないので読み込みが終わっていない expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); game.resourceFactory.flushDelayedAssets(); }, 0); }); it("prefetch - called twice", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; scene._onReady.add(() => { done(); }); scene.prefetch(); scene.prefetch(); game.resourceFactory.flushDelayedAssets(); setTimeout(() => { scene._load(); }, 0); }); it("prefetch - with no assets", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game }); game.resourceFactory.createsDelayedAsset = true; scene._onReady.add(() => { done(); }); scene.prefetch(); game.resourceFactory.flushDelayedAssets(); setTimeout(() => { scene._load(); }, 0); }); // prefetch()テストメモ // // prefetch()が絡んでも、loadedのfireタイミングがおかしくならないことを確認したい。 // loadedのタイミングに関係するのは、アセット読み込み(prefetch(), _load()が引き起こす)と // ストレージ読み込み(_load()が引き起こす)である。関連する事象を以下のように置く: // a) prefetch() 呼び出し // b) _load() 呼び出し // c) アセット読み込み完了 // d) ストレージ読み込み完了 // e) loaded 発火 // d は存在しない場合がある。実装から、明らかに次のことが言える。 // b -> d -- (1) // ただしここで X -> Y は「YはXの後に生じる」ことを表す。同じく実装から、明らかに_load()後のprefetch()は // 単に無視される。したがって (b -> a) のパスを改めて確認する必要はない。テストすべきケースは常に // a -> b -- (2) // (1), (2) から // a -> b -> d -- (3) // また Assetmanager#requestAssets() の呼び出し箇所から、c は a または b の後にのみ生じる。よって (2) から // a -> c -- (4) // さてここで我々が確認すべきことは「e は常に b, c, d すべての後に生じる」である。 // d が存在しないケースを踏まえると、(3), (4) から、確認すべきケースは次の五つである: // a -> c -> b -- (5a) // a -> b -> c -- (5b) // a -> c -> b -> d -- (5c) // a -> b -> c -> d -- (5d) // a -> b -> d -> c -- (5e) // このいずれのケースでも、すべての後に e が生じることをテストすればよい。 // 上記コメント (5a) のケース it("prefetch - prefetch-(asset loaded)-_load-loaded", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; let ready = false; scene._onReady.add(() => { expect(ready).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); done(); }); scene.prefetch(); // (a) expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); game.resourceFactory.flushDelayedAssets(); // (c) setTimeout(() => { ready = true; scene._load(); // (b) expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(true); }, 0); }); // 上記コメント (5b) のケース it("prefetch - prefetch-_loaded-(asset loaded)-loaded", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; let ready = false; scene._onReady.add(() => { expect(ready).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); done(); }); expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(false); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); scene.prefetch(); // (a) expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(true); scene._load(); // (b) expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); // _load() / prefetch() されていても flushDelayedAssets() してないので読み込みが終わっていない ready = true; game.resourceFactory.flushDelayedAssets(); // (c) }); // 上記コメント (5c) のケース it("prefetch - prefetch-(asset loaded)-_load-(storage loaded)-loaded", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const scene = new Scene({ game: game, storageKeys: keys, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; let notifyStorageLoaded = (_value: any): void => { fail("storage load not started"); }; game.storage._registerLoad((_k, l) => { notifyStorageLoaded = l._onLoaded.bind(l); }); let ready = false; scene._onReady.add(() => { expect(ready).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); done(); }); scene.prefetch(); // (a) expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); game.resourceFactory.flushDelayedAssets(); // (c) setTimeout(() => { scene._load(); // (b) expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); ready = true; notifyStorageLoaded(["dummy"]); // (d) }, 0); }); // 上記コメント (5d) のケース it("prefetch - prefetch-_load-(asset loaded)-(storage loaded)-loaded", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const scene = new Scene({ game: game, storageKeys: keys, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; let notifyStorageLoaded = (_values: any[]): void => { fail("storage load not started"); }; game.storage._registerLoad((_k, l) => { notifyStorageLoaded = l._onLoaded.bind(l); }); let ready = false; scene._onReady.add(() => { expect(ready).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); done(); }); scene.prefetch(); // (a) expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); scene._load(); // (b) expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); game.resourceFactory.flushDelayedAssets(); // (c) setTimeout(() => { expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); ready = true; notifyStorageLoaded(["dummy"]); // (d) }, 0); }); // 上記コメント (5e) のケース it("prefetch - prefetch-_load-(storage loaded)-(asset loaded)-loaded", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const keys = [ { region: StorageRegion.Values, regionKey: "a001.b001", gameId: "123", userId: "456" } ]; const scene = new Scene({ game: game, storageKeys: keys, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; let notifyStorageLoaded = (_values: any): void => { fail("storage load not started"); }; game.storage._registerLoad((_k, l) => { notifyStorageLoaded = l._onLoaded.bind(l); }); let ready = false; scene._onReady.add(() => { expect(ready).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(0); done(); }); scene.prefetch(); // (a) expect(scene._loaded).toBe(false); expect(scene._prefetchRequested).toBe(true); expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); scene._load(); // (b) expect(scene._loaded).toBe(true); expect(scene._prefetchRequested).toBe(true); notifyStorageLoaded(["dummy"]); // (d) expect(scene._sceneAssetHolder.waitingAssetsCount).toBe(2); ready = true; game.resourceFactory.flushDelayedAssets(); // (c) }); it("loads assets dynamically", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); game._onLoad.add(() => { const scene = new Scene({ game: game, assetIds: [ "foo", { id: "dynamicImage", type: "image", width: 10, height: 10, uri: "http://dummy.unused.example/someImage.png" } ] }); scene.onLoad.add(() => { const foo = scene.assets.foo; const dynamicImage = scene.assets.dynamicImage as ImageAsset; expect(foo instanceof ImageAsset).toBe(true); expect(foo.id).toBe("foo"); expect(dynamicImage instanceof ImageAsset).toBe(true); expect(dynamicImage.width).toBe(10); let loaded = false; scene.requestAssets( [ "baa", { id: "zooAudio", type: "audio", duration: 450, systemId: "sound", uri: "http://dummy.unused.example/zoo" } ], () => { loaded = true; const baa = scene.assets.baa as ImageAsset; const zoo = scene.assets.zooAudio as AudioAsset; expect(baa instanceof ImageAsset).toBe(true); expect(baa.id).toBe("baa"); expect(baa.width).toBe(1); expect(zoo instanceof AudioAsset).toBe(true); expect(zoo.duration).toBe(450); expect(foo.destroyed()).toBe(false); expect(dynamicImage.destroyed()).toBe(false); expect(baa.destroyed()).toBe(false); expect(zoo.destroyed()).toBe(false); game.popScene(); game._flushPostTickTasks(); expect(foo.destroyed()).toBe(true); expect(dynamicImage.destroyed()).toBe(true); expect(baa.destroyed()).toBe(true); expect(zoo.destroyed()).toBe(true); done(); } ); // Scene#requestAssets() のハンドラ呼び出しは Game#tick() に同期しており、実ロードの完了後に tick() が来るまで遅延される。 // テスト上は tick() を呼び出さないので、 _flushPostTickTasks() を呼び続けることで模擬する。 function flushUntilLoaded(): void { if (loaded) return; game._flushPostTickTasks(); setTimeout(flushUntilLoaded, 10); } flushUntilLoaded(); }); game.pushScene(scene); game._flushPostTickTasks(); }); game._startLoadingGlobalAssets(); }); it("does not crash even if destroyed while loading assets", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo", "baa"] }); game.resourceFactory.createsDelayedAsset = true; scene._load(); scene.destroy(); game.resourceFactory.flushDelayedAssets(); setTimeout(() => { done(); }, 0); }); it("handles asset loading failure", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo"] }); let failureCount = 0; let loadedCount = 0; scene.onAssetLoad.add(asset => { expect(asset instanceof ImageAsset).toBe(true); expect(asset.id).toBe("foo"); expect(failureCount).toBe(2); ++loadedCount; }); scene.onAssetLoadFailure.add(failureInfo => { expect(failureInfo.asset instanceof ImageAsset).toBe(true); expect(failureInfo.asset.id).toBe("foo"); expect(failureInfo.error instanceof Error).toBe(true); expect(failureInfo.error.name).toBe("AssetLoadError"); expect(failureInfo.error.retriable).toBe(true); expect(failureInfo.cancelRetry).toBe(false); ++failureCount; }); scene._onReady.add(() => { expect(failureCount).toBe(2); expect(loadedCount).toBe(1); expect(scene.assets.foo).not.toBeUndefined(); done(); }); game.resourceFactory.withNecessaryRetryCount(2, () => { scene._load(); }); }); it("handles asset loading failure - unhandled", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo"] }); scene._onReady.add(() => { expect(scene.assets.foo).not.toBeUndefined(); done(); }); game.resourceFactory.withNecessaryRetryCount(2, () => { scene._load(); }); }); it("handles asset loading - retry limit exceed", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo"] }); let failureCount = 0; scene.onAssetLoad.add(() => { fail("should not be loaded"); }); scene.onAssetLoadFailure.add(failureInfo => { expect(failureInfo.asset instanceof ImageAsset).toBe(true); expect(failureInfo.asset.id).toBe("foo"); expect(failureInfo.error instanceof Error).toBe(true); expect(failureInfo.cancelRetry).toBe(false); ++failureCount; if (!failureInfo.error.retriable) { expect(failureInfo.error.name).toBe("AssetLoadError"); expect(failureCount).toBe(AssetManager.MAX_ERROR_COUNT + 1); done(); } }); scene._onReady.add(() => { fail("should not fire loaded"); }); game.resourceFactory.withNecessaryRetryCount(AssetManager.MAX_ERROR_COUNT + 1, () => { scene._load(); }); }); it("handles asset loading - giving up", done => { const game = new Game({ width: 320, height: 320, main: "", assets: assetsConfiguration }); const scene = new Scene({ game: game, assetIds: ["foo"] }); let failureCount = 0; scene.onAssetLoad.add(() => { fail("should not be loaded"); }); scene.onAssetLoadFailure.add(failureInfo => { expect(failureInfo.asset instanceof ImageAsset).toBe(true); expect(failureInfo.asset.id).toBe("foo"); expect(failureInfo.error instanceof Error).toBe(true); expect(failureInfo.error.retriable).toBe(true); expect(failureInfo.cancelRetry).toBe(false); expect(failureCount).toBe(0); ++failureCount; failureInfo.cancelRetry = true; setTimeout(() => { expect(game.terminatedGame).toBe(true); done(); }, 0); }); scene._onReady.add(() => { fail("should not fire loaded"); }); game.resourceFactory.withNecessaryRetryCount(AssetManager.MAX_ERROR_COUNT + 1, () => { scene._load(); }); }); it("cannot access undeclared assets", done => { const scene = new Scene({ game: game, assetIds: ["foo"] }); scene._onReady.add(() => { const child = new Scene({ game: game, assetIds: ["foo", "baa"] }); child._onReady.add(() => { expect(scene.assets.foo).not.toBeUndefined(); expect(scene.assets.baa).toBeUndefined(); expect(scene.assets.zoo).toBeUndefined(); expect(child.assets.foo).not.toBeUndefined(); expect(child.assets.baa).not.toBeUndefined(); expect(child.assets.zoo).toBeUndefined(); done(); }); child._load(); }); scene._load(); }); it("modified", () => { const scene = new Scene({ game: game }); scene.modified(); expect(scene.game._modified).toEqual(true); }); it("state", done => { const scene = new Scene({ game: game }); let raisedEvent = false; const stateChangeHandler = (): void => { raisedEvent = true; }; scene.onStateChange.add(stateChangeHandler); const sceneLoaded = (): void => { expect(scene.state).toBe("active"); expect(raisedEvent).toBe(true); raisedEvent = false; nextStep(); }; const scene2Loaded = (): void => { expect(scene.state).toBe("deactive"); expect(raisedEvent).toBe(true); raisedEvent = false; nextStep(); }; const steps = [ () => { scene.onLoad.add(sceneLoaded); game.pushScene(scene); }, () => { const scene2 = new Scene({ game: game }); scene2.onLoad.add(scene2Loaded); game.pushScene(scene2); }, () => { game.popScene(); nextStep(); }, () => { expect(scene.state).toBe("active"); expect(raisedEvent).toBe(true); raisedEvent = false; nextStep(); }, () => { game.popScene(); nextStep(); }, () => { expect(scene.state).toBe("destroyed"); expect(raisedEvent).toBe(true); done(); } ]; let stepIndex = -1; const nextStep = (): void => { setTimeout(() => { steps[++stepIndex](); game._flushPostTickTasks(); }, 0); }; expect(scene.state).toBe("standby"); nextStep(); }); it("state - change order and count", done => { const expected = [ ["S1", "active"], ["S1", "before-destroyed"], ["S1", "destroyed"], ["S2", "active"], ["S2", "deactive"], ["S3", "active"], ["S3", "before-destroyed"], ["S3", "destroyed"], ["S4", "active"], ["S4", "before-destroyed"], ["S4", "destroyed"], ["S2", "active"], ["S2", "before-destroyed"], ["S2", "destroyed"] ]; const actual: [string, string][] = []; function stateChangeHandler(this: Scene, state: SceneStateString): void { actual.push([this.name!, state]); } function makeScene(name: string): Scene { const scene = new Scene({ game: game, name }); scene.onStateChange.add(stateChangeHandler, scene); return scene; } const steps = [ () => { const scene1 = makeScene("S1"); scene1.onLoad.add(nextStep); game.pushScene(scene1); }, () => { const scene2 = makeScene("S2"); scene2.onLoad.add(nextStep); game.replaceScene(scene2); }, () => { const scene3 = makeScene("S3"); scene3.onLoad.add(nextStep); game.pushScene(scene3); }, () => { const scene4 = makeScene("S4"); scene4.onLoad.add(nextStep); game.replaceScene(scene4); }, () => { game.popScene(); nextStep(); }, () => { game.popScene(); nextStep(); }, () => { expect(actual).toEqual(expected); done(); } ]; let stepIndex = -1; const nextStep = (): void => { setTimeout(() => { steps[++stepIndex](); game._flushPostTickTasks(); }, 0); }; nextStep(); }); it("createTimer/deleteTimer", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene = runtime.scene; const timer = scene.createTimer(100); expect(scene._timer._timers.length).toBe(1); expect(scene._timer._timers[0]).toBe(timer); timer.onElapse.add(() => { fail("invalid call"); }, undefined); game.tick(true); game.tick(true); game.tick(true); timer.onElapse.removeAll({ owner: undefined }); expect(scene._timer._timers.length).toBe(1); let success = false; timer.onElapse.add(() => { success = true; }); game.tick(true); expect(success).toBe(true); expect(timer.canDelete()).toBe(false); timer.onElapse.removeAll(); expect(timer.canDelete()).toBe(true); scene.deleteTimer(timer); expect(scene._timer._timers.length).toBe(0); }); it("setInterval/clearInterval", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene1 = game.scene()!; let state1 = false; let success1 = false; expect(scene1._timer._timers.length).toBe(0); const holder1 = scene1.setInterval(() => { if (!state1) fail("fail1"); success1 = true; }, 100); expect(scene1._timer._timers.length).toBe(1); game.tick(true); game.tick(true); game.tick(true); state1 = true; game.tick(true); expect(success1).toBe(true); const scene2 = new Scene({ game: game }); let success2 = false; let state2 = false; game.pushScene(scene2); game._flushPostTickTasks(); state1 = false; const holder2 = scene2.setInterval(() => { if (!state2) fail("fail2"); success2 = true; }, 50); expect(scene1._timer._timers.length).toBe(1); expect(scene2._timer._timers.length).toBe(1); const holder3 = scene2.setInterval(() => { // do nothing }, 50); expect(scene2._timer._timers.length).toBe(1); game.tick(true); state2 = true; game.tick(true); expect(success2).toBe(true); game.tick(true, 10); // どれだけ時間経過してもscene1のtimerは呼ばれない scene2.clearInterval(holder3); expect(scene1._timer._timers.length).toBe(1); expect(scene2._timer._timers.length).toBe(1); scene1.clearInterval(holder1); expect(scene1._timer._timers.length).toBe(0); expect(scene2._timer._timers.length).toBe(1); scene2.clearInterval(holder2); expect(scene1._timer._timers.length).toBe(0); expect(scene2._timer._timers.length).toBe(0); }); it("setTimeout - deprecated", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene1 = game.scene()!; let state1 = false; let success1 = false; expect(scene1._timer._timers.length).toBe(0); scene1.setTimeout(() => { if (!state1) fail("fail1"); success1 = true; }, 100); expect(scene1._timer._timers.length).toBe(1); game.tick(true); game.tick(true); game.tick(true); state1 = true; game.tick(true); expect(success1).toBe(true); state1 = false; game.tick(true); game.tick(true); game.tick(true); game.tick(true); game.tick(true); expect(scene1._timer._timers.length).toBe(0); }); it("setTimeout", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene = game.scene()!; const owner = {}; let callCount = 0; scene.setTimeout( function (this: any): void { expect(this).toBe(owner); callCount++; }, 100, owner ); game.tick(true); game.tick(true); game.tick(true); expect(callCount).toBe(0); game.tick(true); expect(callCount).toBe(1); game.tick(true); game.tick(true); game.tick(true); game.tick(true); game.tick(true); game.tick(true); expect(callCount).toBe(1); }); it("clearTimeout", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene1 = game.scene()!; expect(scene1._timer._timers.length).toBe(0); const holder1 = scene1.setTimeout(() => { fail("fail1"); }, 100); expect(scene1._timer._timers.length).toBe(1); scene1.clearTimeout(holder1); expect(scene1._timer._timers.length).toBe(0); game.tick(true); game.tick(true); game.tick(true); game.tick(true); game.tick(true); }); it("setInterval - release scene", () => { const runtime = skeletonRuntime({ width: 320, height: 320, main: "", assets: {} }); const game = runtime.game; const scene1 = game.scene()!; const state2 = false; expect(scene1._timer._timers.length).toBe(0); scene1.setInterval(() => { // do nothing }, 100); expect(scene1._timer._timers.length).toBe(1); const scene2 = new Scene({ game: game }); game.pushScene(scene2); game._flushPostTickTasks(); scene2.setInterval(() => { if (!state2) fail("fail2"); }, 50); expect(scene1._timer._timers.length).toBe(1); expect(scene2._timer._timers.length).toBe(1); scene2.setInterval(() => { // do nothing }, 50); expect(scene1._timer._timers.length).toBe(1); expect(scene2._timer._timers.length).toBe(1); game.popScene(); game._flushPostTickTasks(); expect(scene1._timer._timers.length).toBe(1); expect(scene2._timer._timers).toBeUndefined(); const scene3 = new Scene({ game: game }); game.replaceScene(scene3); game._flushPostTickTasks(); expect(scene1._timer._timers).toBeUndefined(); }); it("setInterval", () => { const runtime = skeletonRuntime({ width: 320, height: 320, fps: 32, main: "", assets: {} }); const game = runtime.game; const scene = game.scene()!; const owner = {}; let callCount = 0; scene.setInterval( function (this: any): void { expect(this).toBe(owner); callCount++; }, 100, owner ); game.tick(true); game.tick(true); game.tick(true); // 3/32*1000 = 93.75ms expect(callCount).toBe(0); game.tick(true); // 4/32*1000 = 125ms expect(callCount).toBe(1); game.tick(true); game.tick(true); expect(callCount).toBe(1); game.tick(true); // 7/32*1000 = 218.75ms expect(callCount).toBe(2); game.tick(true); game.tick(true); expect(callCount).toBe(2); game.tick(true); // 10/32*1000 = 312.5ms expect(callCount).toBe(3); }); it("isCurrentScene/gotoScene/end", done => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); game._onLoad.add(() => { // game.scenes テストのため _loaded を待つ必要がある const scene1 = new Scene({ game: game }); const scene2 = new Scene({ game: game }); const scene3 = new Scene({ game: game }); game.pushScene(scene1); game._flushPostTickTasks(); expect(scene1.isCurrentScene()).toBe(true); expect(scene2.isCurrentScene()).toBe(false); expect(scene3.isCurrentScene()).toBe(false); scene1.gotoScene(scene2, true); // push scene2 game._flushPostTickTasks(); expect(scene1.isCurrentScene()).toBe(false); expect(scene2.isCurrentScene()).toBe(true); expect(scene3.isCurrentScene()).toBe(false); scene2.end(); game._flushPostTickTasks(); expect(scene1.isCurrentScene()).toBe(true); expect(scene3.isCurrentScene()).toBe(false); scene1.gotoScene(scene3, false); // replace scene1 to scene3 game._flushPostTickTasks(); expect(scene3.isCurrentScene()).toBe(true); done(); }); game._startLoadingGlobalAssets(); }); it("gotoScene - AssertionError", done => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); game._onLoad.add(() => { // game.scenes テストのため _loaded を待つ必要がある const scene1 = new Scene({ game: game }); const scene2 = new Scene({ game: game }); expect(() => { scene1.gotoScene(scene2); }).toThrowError("AssertionError"); done(); }); game._startLoadingGlobalAssets(); }); it("end - AssertionError", done => { const game = new Game({ width: 320, height: 320, main: "", assets: {} }); game._onLoad.add(() => { // game.scenes テストのため _loaded を待つ必要がある const scene1 = new Scene({ game: game }); expect(() => { scene1.end(); }).toThrowError("AssertionError"); done(); }); game._startLoadingGlobalAssets(); }); });
the_stack
import * as Globalize from "globalize"; import "jquery"; import { ColumnFilter, CoreTheme, EmptySorting, MatchType, PagerConfiguration, RelativeSorting, SortDefinitionOrder, SortOrder, StorageType, StringSorting, TablesorterConfiguration, WidgetOptions } from "tablesorter"; /** * Provides tests for the settings. */ export class TestSettings<T extends HTMLElement> { /** * Tests for the settings. */ Test() { let settings: TablesorterConfiguration<T>; let widgetOptions: WidgetOptions<T> = {}; /** * Settings * Legal settings */ settings = { cancelSelection: true, cssAsc: "asc", cssChildRow: "childRow", cssDesc: "desc", cssHeader: "header", cssHeaderRow: "headerRow", cssIcon: "icon", cssIconAsc: "icon-asc", cssIconDesc: "icon-desc", cssIconDisabled: "icon-disabled", cssIconNone: "icon-none", cssIgnoreRow: "ignored", cssInfoBlock: "row-info", cssNone: "no-sort", cssNoSort: "no-sort-control", cssProcessing: "loading-circle", dateFormat: "dd.mm.yyyy", debug: true, delayInit: true, duplicateSpan: true, emptyTo: "top", headers: { 0: { dateFormat: "yyyy-mm-dd", empty: "emptyMax", filter: "parsed", lockedOrder: "asc", parser: "date", resizable: true, sortInitialOrder: "asc", sorter: "date", string: "zero" }, 3: { parser: "ipAddress", sorter: "ipAddress" } }, headerTemplate: "{content} {icon}", ignoreCase: true, initialized(table) { // $ExpectType T table; }, initWidgets: true, namespace: "my-awesome-tablesorter-namespace", numberSorter(x, y, ascending, maxValue) { // $ExpectType number x; // $ExpectType number y; // $ExpectType boolean ascending; // $ExpectType number maxValue; if (x === y) { return 0; } else { return x < y ? -1 : 1; } }, onRenderHeader(index, config, table) { // $ExpectType number index; // $ExpectType TablesorterConfigurationStore<T> config; // $ExpectType JQuery<T> table; }, onRenderTemplate(index, text) { // $ExpectType number index; // $ExpectType string text; return `Column #${index}`; }, pointerClick: "click", pointerDown: "mousedown", pointerUp: "mouseup", resort: true, selectorHeaders: "> thead th", selectorRemove: ".remove-me", selectorSort: "th, td", serverSideSorting: true, showProcessing: true, sortAppend: [[1, 0], [2, 1]], sortForce: [[0, 1], [1, 1]], sortInitialOrder: "asc", sortList: [[0, 1], [1, 1]], sortLocaleCompare: true, sortMultiSortKey: "bubbles", sortReset: true, sortResetKey: "shiftKey", sortRestart: true, sortStable: true, stringTo: "top", tabIndex: true, tableClass: "tablesorter-table", textAttribute: "data-text", textExtraction: "basic", textSorter(x, y, direction, index, table) { // $ExpectType string x; // $ExpectType string y; // $ExpectType boolean direction; // $ExpectType number index; // $ExpectType T table; return x.localeCompare(y); }, theme: "bootstrap", usNumberFormat: true, widgetClass: "pleas-load-me-the-widget-named-{name}", widgetOptions, widgets: ["zebra"], widthFixed: true, checkboxClass: "checked", cehckboxVisible: true, data: {}, dateRange: 50, globalize: { lang: "de", Globalize: Globalize("de"), raw: "dd.mm.yyyy" }, ignoreChildRow: true, imgAttr: "alt" }; /** * Debugging components */ settings.debug = "filter columnSelector"; /** * Sorting relatively */ settings.sortAppend = { 0: [[1, "o"]], 1: [[2, "d"]] }; /** * Text-extraction * Root-level extraction * Basic extraction */ settings.textExtraction = "basic"; /** * Custom extraction */ settings.textExtraction = (node, table, index) => { // $ExpectType Element node; // $ExpectType T table; // $ExpectType number index; return $(node).text(); }; /** * Root-level extraction */ settings.textExtraction = { 0: "basic", ".test"(node, table, index) { // $ExpectType Element node; // $ExpectType T table; // $ExpectType number index; return $(node).text(); } }; /** * Globalization * Global settings */ settings.globalize = { lang: "de", Globalize: Globalize("de"), raw: "dd.mm.yyyy" }; /** * Per-row settings */ settings.globalize = { 0: { lang: "de", Globalize: Globalize("de"), raw: "dd.mm.yyyy" }, 1: { lang: "de", Globalize: Globalize("de"), raw: "dd.mm.yyyy" } }; /** * Widget settings * General settings */ widgetOptions = { columns: ["pri", "sec", "ter"], columns_tfoot: true, columns_thead: true, filter_cellFilter: "filter-control", filter_childByColumn: true, filter_childRows: false, filter_childWithSibs: false, filter_columnAnyMatch: true, filter_columnFilters: true, filter_cssFilter: "tablesorter-filter", filter_defaultAttrib: "data-filter", filter_defaultFilter: { 0: "{q}=", ".fuzzy": "~{q}" }, filter_excludeFilter: { ".text": "range", 2: "range, notMatch, exact" }, filter_external: ".external", filter_filteredRow: "filtered", filter_filterLabel: 'Filter "{{label}}" column by...', filter_formatter: {}, filter_functions: {}, filter_hideEmpty: true, filter_hideFilters: true, filter_ignoreCase: true, filter_liveSearch: true, filter_matchType: { input: "exact", select: "match" }, filter_onlyAvail: "filter-onlyAvail", filter_placeholder: { from: "From", to: "To", search: "Type a text...", select: "Select something" }, filter_reset: $("#reset"), filter_resetOnEsc: true, filter_saveFilters: true, filter_searchDelay: 300, filter_searchFiltered: true, filter_selectSource: { ".model-number": ["1|Awesome 1.x", "2|Awesome 2.x", "3|Awesome 3.x"] }, filter_selectSourceSeparator: "|", filter_serversideFiltering: true, filter_startsWith: true, filter_useParsedData: true, resizable: true, resizable_addLastColumn: true, resizable_includeFooter: true, resizable_targetLast: true, resizable_throttle: true, resizable_widths: ["10%", "100%", "50px"], saveSort: true, stickyHeaders: "tablesorter-sticky", stickyHeaders_addResizeEvent: true, stickyHeaders_appendTo: ".wrapper", stickyHeaders_attachTo: ".wrapper", stickyHeaders_cloneId: "-sticky", stickyHeaders_filteredToTop: true, stickyHeaders_includeCaption: true, stickyHeaders_offset: 10, stickyHeaders_xScroll: ".wrapper", stickyHeaders_yScroll: ".wrapper", stickyHeaders_zindex: 10, storage_fixedUrl: "/this/is/my/awesome/table/url", storage_group: "data-awesome-table-group", storage_page: "data-awesome-table-page", storage_storageType: "c", storage_tableId: "myAwesomeTable", zebra: ["even", "odd"] }; /** * Filter-settings * Filter-cell classes * Global filter-cell classes */ widgetOptions.filter_cellFilter = "filter-control"; /** * Per-row filter-cell classes */ widgetOptions.filter_cellFilter = ["hidden", "", "hidden", ""]; /** * Filter-classes * Global filter-classes */ widgetOptions.filter_cssFilter = "tablesorter-filter"; /** * Per-row filter-classes */ widgetOptions.filter_cssFilter = ["first-filter", "second-filter", "third-filter"]; /** * Filter-formaters * Creating filter-controls with all available options */ widgetOptions.filter_formatter = { "*": (cell, index) => { // $ExpectType JQuery<HTMLElement> cell; // $ExpectType number index; return $.tablesorter.filterFormatter.html5Number( cell, index, { addToggle: true, cellText: "Age", compare: ["<", ">", "="], delayed: true, disabled: true, exactMatch: true, min: 100, max: 1000, skipTest: true, step: 10, value: 110 }); }, 1: (cell, index) => { // $ExpectType JQuery<HTMLElement> cell; // $ExpectType number index; return $.tablesorter.filterFormatter.html5Range( cell, index, { allText: "all", cellText: "Medals", compare: "<", delayed: false, exactMatch: false, min: 1, max: 200, skipTest: true, step: 1, value: 1, valueToHeader: false }); }, 2: (cell, index) => $.tablesorter.filterFormatter.html5Color( cell, index, { addToggle: true, disabled: true, exactMatch: true, skipTest: true, value: "#999999", valueToHeader: true }), 3: (cell, index) => $.tablesorter.filterFormatter.uiSpinner( cell, index, { addToggle: true, cellText: "Level", compare: "=", delayed: true, disabled: true, exactMatch: true, min: 0, max: 100, step: 1, value: 1, culture: "de" }), 4: (cell, index) => $.tablesorter.filterFormatter.uiSlider( cell, index, { allText: "all", cellText: "Height", compare: ["<", ">"], delayed: true, exactMatch: true, min: 0, max: 3, step: 0.01, value: 1.60, valueToHeader: true }), 5: (cell, index) => $.tablesorter.filterFormatter.uiRange( cell, index, { delayed: true, min: 0, max: 1000000, valueToHeader: false }), 6: (cell, index) => $.tablesorter.filterFormatter.uiDateCompare( cell, index, { cellText: "Joindate", compare: ["<", ">"], endOfDay: true }), 7: (cell, index) => $.tablesorter.filterFormatter.uiDatepicker( cell, index, { endOfDay: true, from: new Date(), to: new Date(), textFrom: "From", textTo: "To", maxDate: new Date(1989, 1, 1) }), 8: (cell, index) => $.tablesorter.filterFormatter.select2( cell, index, { cellText: "Gender", exactMatch: true, value: "other", data: [ { id: "other", text: "Other" } ] }) }; /** * Creating filter-controls without options */ widgetOptions.filter_formatter = { "*": (cell, index) => $.tablesorter.filterFormatter.select2(cell, index) }; /** * Creating custom filter-controls */ widgetOptions.filter_formatter = { "*": () => $("input") }; /** * Filter-functions */ widgetOptions.filter_functions = { "*": (o, n, f, i, r, c, d) => { // $ExpectType string o; // $ExpectType string n; // $ExpectType string f; // $ExpectType number i; // $ExpectType JQuery<HTMLElement> r; // $ExpectType TablesorterConfigurationStore<T> c; // $ExpectType object d; return false; }, 1: { "A - D": (o, n, f, i, r, c, d) => { // $ExpectType string o; // $ExpectType string n; // $ExpectType string f; // $ExpectType number i; // $ExpectType JQuery<HTMLElement> r; // $ExpectType TablesorterConfigurationStore<T> c; // $ExpectType object d; return /^[A-D]/.test(o); }, "E - H": (e) => /^[E-H]/.test(e) } }; /** * Hide-filters * Hiding filters statically */ widgetOptions.filter_hideFilters = true; /** * Hiding filters dynamicaly */ widgetOptions.filter_hideFilters = (config) => { // $ExpectType TablesorterConfigurationStore<T> config; const filters = $.tablesorter.getFilters(config.table); return filters.join("") === ""; }; /** * Live-Search * Setting live-features statically */ widgetOptions.filter_liveSearch = true; /** * Setting live-features for a specific amount of characters */ widgetOptions.filter_liveSearch = 5; /** * Setting live-features per-column */ widgetOptions.filter_liveSearch = { 0: false, "*": true, ".fullname": 5 }; /** * Reset-button * Setting the reset-button using a jQuery-object */ widgetOptions.filter_reset = $("#reset"); /** * Setting the reset-button using a jQuery-selector */ widgetOptions.filter_reset = "#reset"; /** * Select-source * Setting a global select-source */ widgetOptions.filter_selectSource = (table, column, onlyAvail) => { // $ExpectType T table; // $ExpectType number column; // $ExpectType boolean onlyAvail; const values = $.tablesorter.filter.getOptions(table, column, onlyAvail); return values; }; /** * Setting per-column select-sources */ widgetOptions.filter_selectSource = { "*": ["1", "2", "3"], 0: [ { text: "JavaScript", value: "*.js", "data-class": "ui-icon-script" } ], 1: (table, column, onlyAvail) => { // $ExpectType T table; // $ExpectType number column; // $ExpectType boolean onlyAvail; return null; } }; /** * Sticky-Headers settings * Appending the sticky header * Using a jQuery-object */ widgetOptions.stickyHeaders_appendTo = $(".wrapper"); /** * Using a jQuery-selector */ widgetOptions.stickyHeaders_appendTo = ".wrapper"; /** * Appending the sticky header * Using a jQuery - object */ widgetOptions.stickyHeaders_appendTo = $(".wrapper"); /** * Using a jQuery-selector */ widgetOptions.stickyHeaders_appendTo = ".wrapper"; /** * Setting an offset * Using a static number */ widgetOptions.stickyHeaders_offset = 10; /** * Using a jQuery-selector */ widgetOptions.stickyHeaders_offset = ".navbar-fixed-top"; /** * Using a jQuery-object */ widgetOptions.stickyHeaders_offset = $(".navbar-fixed-top"); /** * Setting scroll-elements * Using a jQuery-selector */ widgetOptions.stickyHeaders_xScroll = ".wrapper"; widgetOptions.stickyHeaders_yScroll = ".wrapper"; /** * Using a jQuery-object */ widgetOptions.stickyHeaders_xScroll = $(".wrapper"); widgetOptions.stickyHeaders_yScroll = $(".wrapper"); /** * Pager-settings * Using widget-settings */ widgetOptions = { pager_ajaxError: (config, request, settings, error) => { // $ExpectType TablesorterConfigurationStore<T> config; // $ExpectType jqXHR<any> request; // $ExpectType AjaxSettings<any> settings; // $ExpectType string error; return "What do you think you're doing!?"; }, pager_ajaxObject: { dataType: "json" }, pager_ajaxProcessing: () => ({ total: 0 }), pager_ajaxUrl: "https://go.com/download/my/stuff/?p={page}", pager_selectors: { container: $(".container"), first: $(".first"), gotoPage: $(".goto"), last: $(".last"), next: $(".next"), pageDisplay: $(".display"), pageSize: $(".size"), prev: $(".prev") }, pager_countChildRows: true, pager_css: { disabled: "disabled", container: "container", errorRow: "error" }, pager_customAjaxUrl: (table, url) => { // $ExpectType T table; // $ExpectType string url; return url; }, pager_fixedHeight: true, pager_initialRows: { total: 100, filtered: 100 }, pager_output: "{startRow} to {endRow} of {totalRows} rows", pager_startPage: 2, pager_pageReset: true, pager_processAjaxOnInit: true, pager_removeRows: true, pager_savePages: true, pager_size: "all", pager_storageKey: "tablesorter-pager", pager_updateArrows: true }; /** * Using self-contained settings */ let pagerSettings: PagerConfiguration<T> = { ajaxError: () => { return "What are you even trying to do!?"; }, ajaxObject: { dataType: "csv" }, ajaxProcessing: () => ({ total: 1337 }), ajaxUrl: "https://go.com/download/my/stuff/?p={page}", container: $(".container"), countChildRows: true, cssDisabled: "disabled", cssErrorRow: "error", cssFirst: $(".first"), cssGoto: $(".goto"), cssLast: $(".last"), cssNext: $(".next"), cssPageDisplay: $(".display"), cssPageSize: $(".size"), cssPrev: $(".prev"), customAjaxUrl: (table, url) => { // $ExpectType T table; // $ExpectType string url; return url; }, fixedHeight: true, initialRows: { total: 100, filtered: 100 }, output: "{startRow} to {endRow} of {totalRows} rows", page: 2, pageReset: true, processAjaxOnInit: true, removeRows: true, savePages: true, size: "all", storageKey: "tablesorter-pager", updateArrows: true }; /** * Setting an ajax data-processor * Returning an object * With all available options */ pagerSettings.ajaxProcessing = widgetOptions.pager_ajaxProcessing = (data, table, request) => { // $ExpectType any data; // $ExpectType T table; // $ExpectType jqXHR<any> request; return ({ total: 1, filteredRows: 1, headers: ["ID"], output: "", rows: [["1"]] }); }; /** * With all required options */ pagerSettings.ajaxProcessing = widgetOptions.pager_ajaxProcessing = () => { return { total: 1 }; }; /** * Returning an array * With the total amount of rows only */ pagerSettings.ajaxProcessing = widgetOptions.pager_ajaxProcessing = () => [1]; /** * With the rows as a jQuery-object */ pagerSettings.ajaxProcessing = widgetOptions.pager_ajaxProcessing = (data) => [1, $(data.rows), ["ID", "Medals", "Exp"]]; /** * With the records in an array */ pagerSettings.ajaxProcessing = widgetOptions.pager_ajaxProcessing = () => [1, [[1, 1000, "John Doe"]], ["ID", "Medals", "Name"]]; /** * Setting elements for the pager * Using jQuery-selectors */ const selector = ".container"; pagerSettings = { container: selector, cssFirst: selector, cssGoto: selector, cssLast: selector, cssNext: selector, cssPageDisplay: selector, cssPageSize: selector, cssPrev: selector }; widgetOptions.pager_selectors = { container: selector, first: selector, gotoPage: selector, last: selector, next: selector, pageDisplay: selector, pageSize: selector, prev: selector }; /** * Using jQuery-objects */ const object = $(selector); pagerSettings = { container: object, cssFirst: object, cssGoto: object, cssLast: object, cssNext: object, cssPageDisplay: object, cssPageSize: object, cssPrev: object }; widgetOptions.pager_selectors = { container: object, first: object, gotoPage: object, last: object, next: object, pageDisplay: object, pageSize: object, prev: object }; /** * Setting a page-reset * Using an exact number */ pagerSettings.pageReset = widgetOptions.pager_pageReset = 3; /** * Enabling/disabling page-reset */ pagerSettings.pageReset = widgetOptions.pager_pageReset = true; pagerSettings.pageReset = widgetOptions.pager_pageReset = false; /** * Setting the initial page-size * Using an exact number */ pagerSettings.size = widgetOptions.pager_size = 20; /** * Using "all" */ pagerSettings.size = widgetOptions.pager_size = "all"; $<T>("#myTable").tablesorter(settings).tablesorterPager(pagerSettings); } }
the_stack
import { Inject, Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { PrismaService } from 'nestjs-prisma'; import { WINSTON_MODULE_PROVIDER } from 'nest-winston'; import { subSeconds, differenceInSeconds, subDays } from 'date-fns'; import { isEmpty } from 'lodash'; import * as winston from 'winston'; import { Prisma } from '@prisma/client'; import { DeployResult, EnumDeployStatus } from '@amplication/deployer'; import { DeployerService } from '@amplication/deployer/dist/nestjs'; import { EnvironmentService } from '../environment/environment.service'; import { EnumActionStepStatus } from '../action/dto/EnumActionStepStatus'; import { DeployerProvider } from '../deployer/deployerOptions.service'; import { EnumActionLogLevel } from '../action/dto/EnumActionLogLevel'; import { ActionService } from '../action/action.service'; import { ActionStep } from '../action/dto'; import * as domain from './domain.util'; import { Deployment } from './dto/Deployment'; import { CreateDeploymentArgs } from './dto/CreateDeploymentArgs'; import { EnumDeploymentStatus } from './dto/EnumDeploymentStatus'; import { FindOneDeploymentArgs } from './dto/FindOneDeploymentArgs'; import gcpDeployConfiguration from './gcp.deploy-configuration.json'; import { Build } from '../build/dto/Build'; import { Environment } from '../environment/dto'; export const PUBLISH_APPS_PATH = '/deployments/'; export const DEPLOY_STEP_NAME = 'DEPLOY_APP'; export const DEPLOY_STEP_MESSAGE = 'Deploy Application'; export const DESTROY_STEP_NAME = 'DESTROY_APP'; export const DESTROY_STEP_MESSAGE = 'Removing Deployment'; export const DESTROY_STEP_FINISH_LOG = 'The deployment removed successfully'; export const DEPLOYER_DEFAULT_VAR = 'DEPLOYER_DEFAULT'; export const GCP_APPS_PROJECT_ID_VAR = 'GCP_APPS_PROJECT_ID'; export const GCP_APPS_REGION_VAR = 'GCP_APPS_REGION'; export const GCP_APPS_TERRAFORM_STATE_BUCKET_VAR = 'GCP_APPS_TERRAFORM_STATE_BUCKET'; export const GCP_APPS_DATABASE_INSTANCE_VAR = 'GCP_APPS_DATABASE_INSTANCE'; export const GCP_APPS_DOMAIN_VAR = 'GCP_APPS_DOMAIN'; export const TERRAFORM_APP_ID_VARIABLE = 'app_id'; export const TERRAFORM_IMAGE_ID_VARIABLE = 'image_id'; export const GCP_TERRAFORM_PROJECT_VARIABLE = 'project'; export const GCP_TERRAFORM_REGION_VARIABLE = 'region'; export const GCP_TERRAFORM_DATABASE_INSTANCE_NAME_VARIABLE = 'database_instance'; export const GCP_TERRAFORM_DOMAIN_VARIABLE = 'domain'; export const DEPLOY_DEPLOYMENT_INCLUDE = { build: true, environment: true }; export const DEPLOY_STEP_FINISH_LOG = 'The deployment completed successfully'; export const DEPLOY_STEP_FAILED_LOG = 'The deployment failed'; export const DEPLOY_STEP_RUNNING_LOG = 'Waiting for deployment to complete...'; export const DEPLOY_STEP_START_LOG = 'Starting deployment. It may take a few minutes.'; export const AUTO_DEPLOY_MESSAGE = 'Auto deploy to sandbox environment'; export const ACTION_INCLUDE = { action: { include: { steps: true } } }; const MAX_DESTROY_PER_CYCLE = 2; const DESTROY_STALED_INTERVAL_DAYS = 30; const DEPLOY_STATUS_FETCH_INTERVAL_SEC = 10; const DEPLOY_STATUS_UPDATE_INTERVAL_SEC = 30; export function createInitialStepData( version: string, message: string, environment: string ) { return { message: 'Adding task to queue', status: EnumActionStepStatus.Success, completedAt: new Date(), logs: { create: [ { level: EnumActionLogLevel.Info, message: 'Create deployment task', meta: {} }, { level: EnumActionLogLevel.Info, message: `Deploy to environment: ${environment}`, meta: {} }, { level: EnumActionLogLevel.Info, message: `version: ${version}`, meta: {} }, { level: EnumActionLogLevel.Info, message: `message: ${message}`, meta: {} } ] } }; } @Injectable() export class DeploymentService { canDeploy: boolean; constructor( private readonly configService: ConfigService, private readonly prisma: PrismaService, private readonly deployerService: DeployerService, private readonly actionService: ActionService, private readonly environmentService: EnvironmentService, @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: winston.Logger ) { this.canDeploy = Boolean(this.deployerService.options.default); } async autoDeployToSandbox(build: Build): Promise<Deployment> { const sandboxEnvironment = await this.environmentService.getDefaultEnvironment( build.appId ); const deployment = (await this.prisma.deployment.create({ data: { build: { connect: { id: build.id } }, createdBy: { connect: { id: build.userId } }, environment: { connect: { id: sandboxEnvironment.id } }, message: AUTO_DEPLOY_MESSAGE, status: EnumDeploymentStatus.Waiting, createdAt: new Date(), action: { connect: { id: build.actionId } } } })) as Deployment; await this.deploy(deployment.id); return deployment; } async create(args: CreateDeploymentArgs): Promise<Deployment> { /**@todo: add validations */ const deployment = (await this.prisma.deployment.create({ data: { ...args.data, status: EnumDeploymentStatus.Waiting, createdAt: new Date(), // Create action record action: { create: { steps: { create: createInitialStepData( /** @todo replace with version number */ args.data.build.connect.id, args.data.message, /** @todo replace with environment name */ args.data.environment.connect.id ) } } } } })) as Deployment; await this.deploy(deployment.id); return deployment; } async findMany(args: Prisma.DeploymentFindManyArgs): Promise<Deployment[]> { return this.prisma.deployment.findMany(args) as Promise<Deployment[]>; } async findOne(args: FindOneDeploymentArgs): Promise<Deployment | null> { return this.prisma.deployment.findUnique(args) as Promise<Deployment>; } /** * Gets the updated status of running deployments from * DeployerService, and updates the step and deployment status. This function should * be called periodically from an external scheduler */ async updateRunningDeploymentsStatus(): Promise<void> { const lastUpdateThreshold = subSeconds( new Date(), DEPLOY_STATUS_FETCH_INTERVAL_SEC ); //find all deployments that are still running const deployments = await this.findMany({ where: { statusUpdatedAt: { lt: lastUpdateThreshold }, status: { equals: EnumDeploymentStatus.Waiting } }, include: ACTION_INCLUDE }); await Promise.all( deployments.map(async deployment => { const steps = await this.actionService.getSteps(deployment.actionId); const deployStep = steps.find(step => step.name === DEPLOY_STEP_NAME); const destroyStep = steps.find(step => step.name === DESTROY_STEP_NAME); const currentStep = destroyStep || deployStep; //when destroy step exist it is the current one try { const result = await this.deployerService.getStatus( deployment.statusQuery ); //To avoid too many messages in the log, if the status is still "running" handle the results only if the bigger interval passed if ( result.status !== EnumDeployStatus.Running || differenceInSeconds(new Date(), deployment.statusUpdatedAt) > DEPLOY_STATUS_UPDATE_INTERVAL_SEC ) { this.logger.info( `Deployment ${deployment.id}: current status ${result.status}` ); const updatedDeployment = await this.handleDeployResult( deployment, currentStep, result ); return updatedDeployment.status; } else { return deployment.status; } } catch (error) { await this.actionService.logInfo(currentStep, error); await this.actionService.complete( currentStep, EnumActionStepStatus.Failed ); const status = EnumDeploymentStatus.Failed; await this.updateStatus(deployment.id, status); } }) ); } async deploy(deploymentId: string): Promise<void> { const deployment = (await this.prisma.deployment.findUnique({ where: { id: deploymentId }, include: DEPLOY_DEPLOYMENT_INCLUDE })) as Deployment & { build: Build; environment: Environment }; await this.actionService.run( deployment.actionId, DEPLOY_STEP_NAME, DEPLOY_STEP_MESSAGE, async step => { const { build, environment } = deployment; const { appId } = build; const [imageId] = build.images; const deployerDefault = this.configService.get(DEPLOYER_DEFAULT_VAR); switch (deployerDefault) { case DeployerProvider.Docker: { throw new Error('Not implemented'); } case DeployerProvider.GCP: { const result = await this.deployToGCP( appId, imageId, environment.address ); await this.handleDeployResult(deployment, step, result); return; } default: { throw new Error(`Unknown deployment provider ${deployerDefault}`); } } }, true ); } private async handleDeployResult( deployment: Deployment, step: ActionStep, result: DeployResult ): Promise<Deployment> { switch (result.status) { case EnumDeployStatus.Completed: if (step.name === DESTROY_STEP_NAME) { await this.actionService.logInfo(step, DESTROY_STEP_FINISH_LOG); await this.actionService.complete(step, EnumActionStepStatus.Success); return this.updateStatus(deployment.id, EnumDeploymentStatus.Removed); } else { await this.actionService.logInfo(step, DEPLOY_STEP_FINISH_LOG); await this.actionService.complete(step, EnumActionStepStatus.Success); if (isEmpty(result.url)) { throw new Error( `Deployment ${deployment.id} completed without a deployment URL` ); } await this.prisma.environment.update({ where: { id: deployment.environmentId }, data: { address: result.url } }); //mark previous active deployments as removed await this.prisma.deployment.updateMany({ where: { environmentId: deployment.environmentId, status: EnumDeploymentStatus.Completed }, data: { status: EnumDeploymentStatus.Removed } }); return this.updateStatus( deployment.id, EnumDeploymentStatus.Completed ); } case EnumDeployStatus.Failed: await this.actionService.logInfo(step, DEPLOY_STEP_FAILED_LOG); await this.actionService.complete(step, EnumActionStepStatus.Failed); return this.updateStatus(deployment.id, EnumDeploymentStatus.Failed); default: await this.actionService.logInfo(step, DEPLOY_STEP_RUNNING_LOG); return this.update({ where: { id: deployment.id }, data: { statusQuery: result.statusQuery, statusUpdatedAt: new Date(), status: EnumDeploymentStatus.Waiting } }); } } private async update(args: Prisma.DeploymentUpdateArgs): Promise<Deployment> { return this.prisma.deployment.update(args) as Promise<Deployment>; } private async updateStatus( deploymentId: string, status: EnumDeploymentStatus ): Promise<Deployment> { return this.update({ where: { id: deploymentId }, data: { status } }); } async deployToGCP( appId: string, imageId: string, subdomain: string ): Promise<DeployResult> { const projectId = this.configService.get(GCP_APPS_PROJECT_ID_VAR); const terraformStateBucket = this.configService.get( GCP_APPS_TERRAFORM_STATE_BUCKET_VAR ); const region = this.configService.get(GCP_APPS_REGION_VAR); const databaseInstance = this.configService.get( GCP_APPS_DATABASE_INSTANCE_VAR ); const appsDomain = this.configService.get(GCP_APPS_DOMAIN_VAR); const deploymentDomain = domain.join([subdomain, appsDomain]); const backendConfiguration = { bucket: terraformStateBucket, prefix: appId }; const variables = { [TERRAFORM_APP_ID_VARIABLE]: appId, [TERRAFORM_IMAGE_ID_VARIABLE]: imageId, [GCP_TERRAFORM_PROJECT_VARIABLE]: projectId, [GCP_TERRAFORM_REGION_VARIABLE]: region, [GCP_TERRAFORM_DATABASE_INSTANCE_NAME_VARIABLE]: databaseInstance, [GCP_TERRAFORM_DOMAIN_VARIABLE]: deploymentDomain }; return this.deployerService.deploy( gcpDeployConfiguration, variables, backendConfiguration, DeployerProvider.GCP ); } /** * Destroy staled environments * This function should be called periodically from an external scheduler */ async destroyStaledDeployments(): Promise<void> { const lastDeployThreshold = subDays( new Date(), DESTROY_STALED_INTERVAL_DAYS ); const environments = await this.prisma.environment.findMany({ where: { deployments: { some: { createdAt: { lt: lastDeployThreshold }, status: { equals: EnumDeploymentStatus.Completed } } } }, take: MAX_DESTROY_PER_CYCLE }); await Promise.all( environments.map(async environment => { return this.destroy(environment.id); }) ); } async destroy(environmentId: string): Promise<void> { const deployment = (await this.prisma.deployment.findFirst({ where: { environmentId: environmentId, status: EnumDeploymentStatus.Completed }, orderBy: { createdAt: Prisma.SortOrder.desc }, include: DEPLOY_DEPLOYMENT_INCLUDE })) as Deployment & { build: Build; environment: Environment }; if (!deployment) return; await this.actionService.run( deployment.actionId, DESTROY_STEP_NAME, DESTROY_STEP_MESSAGE, async step => { const { build, environment } = deployment; const { appId } = build; const [imageId] = build.images; const deployerDefault = this.configService.get(DEPLOYER_DEFAULT_VAR); switch (deployerDefault) { case DeployerProvider.Docker: { throw new Error('Not implemented'); } case DeployerProvider.GCP: { await this.updateStatus( deployment.id, EnumDeploymentStatus.Waiting ); const result = await this.destroyOnGCP( appId, imageId, environment.address ); await this.handleDeployResult(deployment, step, result); return; } default: { throw new Error(`Unknown deployment provider ${deployerDefault}`); } } }, true ); } async destroyOnGCP( appId: string, imageId: string, subdomain: string ): Promise<DeployResult> { const projectId = this.configService.get(GCP_APPS_PROJECT_ID_VAR); const terraformStateBucket = this.configService.get( GCP_APPS_TERRAFORM_STATE_BUCKET_VAR ); const region = this.configService.get(GCP_APPS_REGION_VAR); const databaseInstance = this.configService.get( GCP_APPS_DATABASE_INSTANCE_VAR ); const appsDomain = this.configService.get(GCP_APPS_DOMAIN_VAR); const deploymentDomain = domain.join([subdomain, appsDomain]); const backendConfiguration = { bucket: terraformStateBucket, prefix: appId }; const variables = { [TERRAFORM_APP_ID_VARIABLE]: appId, [TERRAFORM_IMAGE_ID_VARIABLE]: imageId, [GCP_TERRAFORM_PROJECT_VARIABLE]: projectId, [GCP_TERRAFORM_REGION_VARIABLE]: region, [GCP_TERRAFORM_DATABASE_INSTANCE_NAME_VARIABLE]: databaseInstance, [GCP_TERRAFORM_DOMAIN_VARIABLE]: deploymentDomain }; return this.deployerService.destroy( gcpDeployConfiguration, variables, backendConfiguration, DeployerProvider.GCP ); } }
the_stack
import * as tape from 'tape'; import {formatDateTime} from "../../../../../../src/lib/helpers/format-date-time"; const {DateTime, Settings} = require('luxon'); Settings.defaultLocale = 'en'; // Thursday, January 1, 1970 4:12:29 PM let date = DateTime.fromMillis(58349457, {zone: 'UTC'}); // Tuesday, February 2, 1971 4:12:29 AM let date2 = DateTime.fromMillis(34315949457, {zone: 'UTC'}); // Friday, March 3, 1972 4:12:29 PM let date3 = DateTime.fromMillis(68487149457, {zone: 'UTC'}); // Wednesday, April 4, 1973 4:12:29 PM let date4 = DateTime.fromMillis(102744749457, {zone: 'UTC+1'}); // Wednesday, April 15, 1973 4:12:29 PM let date5 = DateTime.fromMillis(114235949457, {zone: 'UTC+1'}); // Wednesday, August 15, 1973 4:12:29 PM let dateInDst = DateTime.fromMillis(114235949457, {zone: 'America/New_York'}); tape('format-date-time', (test) => { test.same(formatDateTime(date, 'd'), '01', 'Day of the month, 2 digits with leading zeros'); test.same(formatDateTime(date2, 'd'), '02', 'Day of the month, 2 digits with leading zeros'); test.same(formatDateTime(date3, 'd'), '03', 'Day of the month, 2 digits with leading zeros'); test.same(formatDateTime(date4, 'd'), '04', 'Day of the month, 2 digits with leading zeros'); test.same(formatDateTime(date, 'D'), 'Thu', 'A textual representation of a day, three letters'); test.same(formatDateTime(date2, 'D'), 'Tue', 'A textual representation of a day, three letters'); test.same(formatDateTime(date3, 'D'), 'Fri', 'A textual representation of a day, three letters'); test.same(formatDateTime(date4, 'D'), 'Wed', 'A textual representation of a day, three letters'); test.same(formatDateTime(date, 'j'), '1', 'Day of the month without leading zeros'); test.same(formatDateTime(date2, 'j'), '2', 'Day of the month without leading zeros'); test.same(formatDateTime(date3, 'j'), '3', 'Day of the month without leading zeros'); test.same(formatDateTime(date4, 'j'), '4', 'Day of the month without leading zeros'); test.same(formatDateTime(date, 'l'), 'Thursday', 'A full textual representation of the day of the week'); test.same(formatDateTime(date2, 'l'), 'Tuesday', 'A full textual representation of the day of the week'); test.same(formatDateTime(date3, 'l'), 'Friday', 'A full textual representation of the day of the week'); test.same(formatDateTime(date4, 'l'), 'Wednesday', 'A full textual representation of the day of the week'); test.same(formatDateTime(date, 'N'), '4', 'ISO-8601 numeric representation of the day of the week (starting from 1)'); test.same(formatDateTime(date2, 'N'), '2', 'ISO-8601 numeric representation of the day of the week (starting from 1)'); test.same(formatDateTime(date3, 'N'), '5', 'ISO-8601 numeric representation of the day of the week (starting from 1)'); test.same(formatDateTime(date4, 'N'), '3', 'ISO-8601 numeric representation of the day of the week (starting from 1)'); test.same(formatDateTime(date, 'S'), 'st', 'English ordinal suffix for the day of the month, 2 characters'); test.same(formatDateTime(date2, 'S'), 'nd', 'English ordinal suffix for the day of the month, 2 characters'); test.same(formatDateTime(date3, 'S'), 'rd', 'English ordinal suffix for the day of the month, 2 characters'); test.same(formatDateTime(date4, 'S'), 'th', 'English ordinal suffix for the day of the month, 2 characters'); test.same(formatDateTime(date5, 'S'), 'th', 'English ordinal suffix for the day of the month, 2 characters'); test.same(formatDateTime(date, 'w'), '3', 'Numeric representation of the day of the week (starting from 0)'); test.same(formatDateTime(date2, 'w'), '1', 'Numeric representation of the day of the week (starting from 0)'); test.same(formatDateTime(date3, 'w'), '4', 'Numeric representation of the day of the week (starting from 0)'); test.same(formatDateTime(date4, 'w'), '2', 'Numeric representation of the day of the week (starting from 0)'); test.same(formatDateTime(date, 'z'), '0', 'The day of the year (starting from 0)'); test.same(formatDateTime(date2, 'z'), '32', 'The day of the year (starting from 0)'); test.same(formatDateTime(date3, 'z'), '62', 'The day of the year (starting from 0)'); test.same(formatDateTime(date4, 'z'), '93', 'The day of the year (starting from 0)'); test.same(formatDateTime(date, 'W'), '01', 'ISO-8601 week number of year, weeks starting on Monday'); test.same(formatDateTime(date2, 'W'), '05', 'ISO-8601 week number of year, weeks starting on Monday'); test.same(formatDateTime(date3, 'W'), '09', 'ISO-8601 week number of year, weeks starting on Monday'); test.same(formatDateTime(date4, 'W'), '14', 'ISO-8601 week number of year, weeks starting on Monday'); test.same(formatDateTime(date, 'F'), 'January', 'A full textual representation of a month, such as January or March'); test.same(formatDateTime(date2, 'F'), 'February', 'A full textual representation of a month, such as January or March'); test.same(formatDateTime(date3, 'F'), 'March', 'A full textual representation of a month, such as January or March'); test.same(formatDateTime(date4, 'F'), 'April', 'A full textual representation of a month, such as January or March'); test.same(formatDateTime(date, 'm'), '01', 'Numeric representation of a month, with leading zeros'); test.same(formatDateTime(date2, 'm'), '02', 'Numeric representation of a month, with leading zeros'); test.same(formatDateTime(date3, 'm'), '03', 'Numeric representation of a month, with leading zeros'); test.same(formatDateTime(date4, 'm'), '04', 'Numeric representation of a month, with leading zeros'); test.same(formatDateTime(date, 'M'), 'Jan', 'A short textual representation of a month, three letters'); test.same(formatDateTime(date2, 'M'), 'Feb', 'A short textual representation of a month, three letters'); test.same(formatDateTime(date3, 'M'), 'Mar', 'A short textual representation of a month, three letters'); test.same(formatDateTime(date4, 'M'), 'Apr', 'A short textual representation of a month, three letters'); test.same(formatDateTime(date, 'n'), '1', 'Numeric representation of a month, without leading zero'); test.same(formatDateTime(date2, 'n'), '2', 'Numeric representation of a month, without leading zero'); test.same(formatDateTime(date3, 'n'), '3', 'Numeric representation of a month, without leading zero'); test.same(formatDateTime(date4, 'n'), '4', 'Numeric representation of a month, without leading zero'); test.same(formatDateTime(date, 't'), '31', 'Number of days in the given month'); test.same(formatDateTime(date2, 't'), '28', 'Number of days in the given month'); test.same(formatDateTime(date3, 't'), '31', 'Number of days in the given month'); test.same(formatDateTime(date4, 't'), '30', 'Number of days in the given month'); test.same(formatDateTime(date, 'L'), '0', 'Whether it\'s a leap year'); test.same(formatDateTime(date2, 'L'), '0', 'Whether it\'s a leap year'); test.same(formatDateTime(date3, 'L'), '1', 'Whether it\'s a leap year'); test.same(formatDateTime(date4, 'L'), '0', 'Whether it\'s a leap year'); test.same(formatDateTime(date, 'o'), '1970', 'ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.'); test.same(formatDateTime(date2, 'o'), '1971', 'ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.'); test.same(formatDateTime(date3, 'o'), '1972', 'ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.'); test.same(formatDateTime(date4, 'o'), '1973', 'ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.'); test.same(formatDateTime(date, 'Y'), '1970', 'A full numeric representation of a year, 4 digits'); test.same(formatDateTime(date2, 'Y'), '1971', 'A full numeric representation of a year, 4 digits'); test.same(formatDateTime(date3, 'Y'), '1972', 'A full numeric representation of a year, 4 digits'); test.same(formatDateTime(date4, 'Y'), '1973', 'A full numeric representation of a year, 4 digits'); test.same(formatDateTime(date, 'y'), '70', 'A two digit representation of a year'); test.same(formatDateTime(date2, 'y'), '71', 'A two digit representation of a year'); test.same(formatDateTime(date3, 'y'), '72', 'A two digit representation of a year'); test.same(formatDateTime(date4, 'y'), '73', 'A two digit representation of a year'); test.same(formatDateTime(date, 'a'), 'pm', 'Lowercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date2, 'a'), 'am', 'Lowercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date3, 'a'), 'pm', 'Lowercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date4, 'a'), 'am', 'Lowercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date, 'A'), 'PM', 'Uppercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date2, 'A'), 'AM', 'Uppercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date3, 'A'), 'PM', 'Uppercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date4, 'A'), 'AM', 'Uppercase Ante meridiem and Post meridiem'); test.same(formatDateTime(date, 'B'), '675', 'Swatch Internet time'); test.same(formatDateTime(date2, 'B'), '175', 'Swatch Internet time'); test.same(formatDateTime(date3, 'B'), '675', 'Swatch Internet time'); test.same(formatDateTime(date4, 'B'), '217', 'Swatch Internet time'); test.same(formatDateTime(date, 'g'), '4', '12-hour format of an hour without leading zeros'); test.same(formatDateTime(date2, 'g'), '4', '12-hour format of an hour without leading zeros'); test.same(formatDateTime(date3, 'g'), '4', '12-hour format of an hour without leading zeros'); test.same(formatDateTime(date4, 'g'), '5', '12-hour format of an hour without leading zeros'); test.same(formatDateTime(date, 'G'), '16', '24-hour format of an hour without leading zeros'); test.same(formatDateTime(date2, 'G'), '4', '24-hour format of an hour without leading zeros'); test.same(formatDateTime(date3, 'G'), '16', '24-hour format of an hour without leading zeros'); test.same(formatDateTime(date4, 'G'), '5', '24-hour format of an hour without leading zeros'); test.same(formatDateTime(date, 'h'), '04', '12-hour format of an hour with leading zeros'); test.same(formatDateTime(date2, 'h'), '04', '12-hour format of an hour with leading zeros'); test.same(formatDateTime(date3, 'h'), '04', '12-hour format of an hour with leading zeros'); test.same(formatDateTime(date4, 'h'), '05', '12-hour format of an hour with leading zeros'); test.same(formatDateTime(date, 'H'), '16', '24-hour format of an hour with leading zeros'); test.same(formatDateTime(date2, 'H'), '04', '24-hour format of an hour with leading zeros'); test.same(formatDateTime(date3, 'H'), '16', '24-hour format of an hour with leading zeros'); test.same(formatDateTime(date4, 'H'), '05', '24-hour format of an hour with leading zeros'); test.same(formatDateTime(date, 'i'), '12', 'Minutes with leading zeros'); test.same(formatDateTime(date2, 'i'), '12', 'Minutes with leading zeros'); test.same(formatDateTime(date3, 'i'), '12', 'Minutes with leading zeros'); test.same(formatDateTime(date4, 'i'), '12', 'Minutes with leading zeros'); test.same(formatDateTime(date, 's'), '29', 'Seconds, with leading zeros'); test.same(formatDateTime(date2, 's'), '29', 'Seconds, with leading zeros'); test.same(formatDateTime(date3, 's'), '29', 'Seconds, with leading zeros'); test.same(formatDateTime(date4, 's'), '29', 'Seconds, with leading zeros'); test.same(formatDateTime(date, 'u'), '457000', 'Microseconds'); test.same(formatDateTime(date2, 'u'), '457000', 'Microseconds'); test.same(formatDateTime(date3, 'u'), '457000', 'Microseconds'); test.same(formatDateTime(date4, 'u'), '457000', 'Microseconds'); test.same(formatDateTime(date, 'v'), '457', 'Milliseconds'); test.same(formatDateTime(date2, 'v'), '457', 'Milliseconds'); test.same(formatDateTime(date3, 'v'), '457', 'Milliseconds'); test.same(formatDateTime(date4, 'v'), '457', 'Milliseconds'); test.same(formatDateTime(date, 'e'), 'UTC', 'Timezone identifier'); test.same(formatDateTime(date2, 'e'), 'UTC', 'Timezone identifier'); test.same(formatDateTime(date3, 'e'), 'UTC', 'Timezone identifier'); test.same(formatDateTime(date4, 'e'), 'UTC+1', 'Timezone identifier'); test.same(formatDateTime(date, 'I'), '0', 'Whether or not the date is in daylight saving time'); test.same(formatDateTime(date2, 'I'), '0', 'Whether or not the date is in daylight saving time'); test.same(formatDateTime(date3, 'I'), '0', 'Whether or not the date is in daylight saving time'); test.same(formatDateTime(date4, 'I'), '0', 'Whether or not the date is in daylight saving time'); test.same(formatDateTime(dateInDst, 'I'), '1', 'Whether or not the date is in daylight saving time'); test.same(formatDateTime(date, 'O'), '+0000', 'Difference to Greenwich time (GMT) in hours'); test.same(formatDateTime(date2, 'O'), '+0000', 'Difference to Greenwich time (GMT) in hours'); test.same(formatDateTime(date3, 'O'), '+0000', 'Difference to Greenwich time (GMT) in hours'); test.same(formatDateTime(date4, 'O'), '+0100', 'Difference to Greenwich time (GMT) in hours'); test.same(formatDateTime(date, 'P'), '+00:00', 'Difference to Greenwich time (GMT) with colon between hours and minutes'); test.same(formatDateTime(date2, 'P'), '+00:00', 'Difference to Greenwich time (GMT) with colon between hours and minutes'); test.same(formatDateTime(date3, 'P'), '+00:00', 'Difference to Greenwich time (GMT) with colon between hours and minutes'); test.same(formatDateTime(date4, 'P'), '+01:00', 'Difference to Greenwich time (GMT) with colon between hours and minutes'); test.same(formatDateTime(date, 'T'), 'UTC', 'Timezone abbreviation'); test.same(formatDateTime(date2, 'T'), 'UTC', 'Timezone abbreviation'); test.same(formatDateTime(date3, 'T'), 'UTC', 'Timezone abbreviation'); test.same(formatDateTime(date4, 'T'), 'UTC+1', 'Timezone abbreviation'); test.same(formatDateTime(date, 'Z'), '0', 'Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'); test.same(formatDateTime(date2, 'Z'), '0', 'Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'); test.same(formatDateTime(date3, 'Z'), '0', 'Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'); test.same(formatDateTime(date4, 'Z'), '3600', 'Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.'); test.same(formatDateTime(date, 'c'), '1970-01-01T16:12:29+00:00', 'ISO 8601 date'); test.same(formatDateTime(date2, 'c'), '1971-02-02T04:12:29+00:00', 'ISO 8601 date'); test.same(formatDateTime(date3, 'c'), '1972-03-03T16:12:29+00:00', 'ISO 8601 date'); test.same(formatDateTime(date4, 'c'), '1973-04-04T05:12:29+01:00', 'ISO 8601 date'); test.same(formatDateTime(date, 'r'), 'Thu, 01 Jan 1970 16:12:29 +0000', 'RFC 2822 formatted date'); test.same(formatDateTime(date2, 'r'), 'Tue, 02 Feb 1971 04:12:29 +0000', 'RFC 2822 formatted date'); test.same(formatDateTime(date3, 'r'), 'Fri, 03 Mar 1972 16:12:29 +0000', 'RFC 2822 formatted date'); test.same(formatDateTime(date4, 'r'), 'Wed, 04 Apr 1973 05:12:29 +0100', 'RFC 2822 formatted date'); test.same(formatDateTime(date, 'U'), '58349', 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'); test.same(formatDateTime(date2, 'U'), '34315949', 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'); test.same(formatDateTime(date3, 'U'), '68487149', 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'); test.same(formatDateTime(date4, 'U'), '102744749', 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)'); test.end(); });
the_stack
import type { ConnInfo, ServeInit } from "https://deno.land/std@0.144.0/http/server.ts"; import { serve as stdServe, serveTls } from "https://deno.land/std@0.144.0/http/server.ts"; import { readableStreamFromReader } from "https://deno.land/std@0.144.0/streams/conversion.ts"; import { generateErrorHtml, TransformError } from "../framework/core/error.ts"; import type { RouteConfig } from "../framework/core/route.ts"; import log, { LevelName } from "../lib/log.ts"; import { getContentType } from "../lib/mime.ts"; import util from "../lib/util.ts"; import { createContext } from "./context.ts"; import type { SessionOptions } from "./session.ts"; import { DependencyGraph } from "./graph.ts"; import { fixResponse, getAlephPkgUri, getDeploymentId, globalIt, initModuleLoaders, loadImportMap, loadJSXConfig, regFullVersion, setCookieHeader, toLocalPath, } from "./helpers.ts"; import { loadAndFixIndexHtml } from "./html.ts"; import renderer, { type SSR } from "./renderer.ts"; import { fetchRouteData, initRoutes, revive } from "./routing.ts"; import clientModuleTransformer from "./transformer.ts"; import type { AlephConfig, FetchHandler, Middleware } from "./types.ts"; export type ServerOptions = Omit<ServeInit, "onError"> & { certFile?: string; keyFile?: string; logLevel?: LevelName; session?: SessionOptions; middlewares?: Middleware[]; fetch?: FetchHandler; ssr?: SSR; onError?: ErrorCallback; } & AlephConfig; export type ErrorCallback = { ( error: unknown, cause: { by: "route-data-fetch" | "ssr" | "transplie" | "fs" | "middleware"; url: string; context?: Record<string, unknown>; }, ): Response | void; }; export const serve = (options: ServerOptions = {}) => { const { routes, unocss, build, devServer, middlewares, fetch, ssr, logLevel, onError } = options; const isDev = Deno.env.get("ALEPH_ENV") === "development"; // server handler const handler = async (req: Request, connInfo: ConnInfo): Promise<Response> => { const url = new URL(req.url); const { pathname, searchParams } = url; // close the hot-reloading websocket connection and tell the client to reload // this request occurs when the client try to connect to the hot-reloading websocket in production mode if (pathname === "/-/hmr") { const { socket, response } = Deno.upgradeWebSocket(req, {}); socket.addEventListener("open", () => { socket.send(JSON.stringify({ type: "reload" })); setTimeout(() => { socket.close(); }, 50); }); return response; } const postMiddlewares: Middleware[] = []; const customHTMLRewriter: [selector: string, handlers: HTMLRewriterHandlers][] = []; const ctx = createContext(req, { connInfo, customHTMLRewriter }); // use eager middlewares if (Array.isArray(middlewares)) { for (let i = 0, l = middlewares.length; i < l; i++) { const mw = middlewares[i]; const handler = mw.fetch; if (typeof handler === "function") { if (mw.eager) { try { let res = handler(req, ctx); if (res instanceof Promise) { res = await res; } if (res instanceof Response) { return res; } if (typeof res === "function") { setTimeout(res, 0); } } catch (err) { const res = onError?.(err, { by: "middleware", url: req.url, context: ctx }); if (res instanceof Response) { return res; } log.error(`[middleare${mw.name ? `(${mw.name})` : ""}]`, err); return new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } } else { postMiddlewares.push(mw); } } } } // transform client modules if (!searchParams.has("raw") && clientModuleTransformer.test(pathname)) { try { const importMap = await globalIt("__ALEPH_IMPORT_MAP", loadImportMap); const jsxConfig = await globalIt("__ALEPH_JSX_CONFIG", () => loadJSXConfig(importMap)); return await clientModuleTransformer.fetch(req, { importMap, jsxConfig, buildTarget: build?.target, isDev, }); } catch (err) { if (err instanceof TransformError) { log.error(err.message); const alephPkgUri = toLocalPath(getAlephPkgUri()); return new Response( `import { showTransformError } from "${alephPkgUri}/framework/core/error.ts";showTransformError(${ JSON.stringify(err) });`, { headers: [ ["Content-Type", "application/javascript"], ["X-Transform-Error", "true"], ], }, ); } if (!(err instanceof Deno.errors.NotFound)) { log.error(err); return onError?.(err, { by: "transplie", url: req.url }) ?? new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } } } // use loader to load modules const moduleLoaders = await globalIt("__ALEPH_MODULE_LOADERS", initModuleLoaders); const loader = searchParams.has("raw") ? null : moduleLoaders.find((loader) => loader.test(pathname)); if (loader) { try { const importMap = await globalIt("__ALEPH_IMPORT_MAP", loadImportMap); const jsxConfig = await globalIt("__ALEPH_JSX_CONFIG", () => loadJSXConfig(importMap)); return await clientModuleTransformer.fetch(req, { loader: loader, importMap, jsxConfig, buildTarget: build?.target, isDev, }); } catch (err) { if (err instanceof TransformError) { log.error(err.message); const alephPkgUri = toLocalPath(getAlephPkgUri()); return new Response( `import { showTransformError } from "${alephPkgUri}/framework/core/error.ts";showTransformError(${ JSON.stringify(err) });`, { headers: [ ["Content-Type", "application/javascript"], ["X-Transform-Error", "true"], ], }, ); } if (!(err instanceof Deno.errors.NotFound)) { log.error(err); return onError?.(err, { by: "transplie", url: req.url }) ?? new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } } } // serve static files const contentType = getContentType(pathname); if (!pathname.startsWith("/.") && contentType !== "application/octet-stream") { try { let filePath = `.${pathname}`; let stat = await Deno.lstat(filePath); if (stat.isDirectory && pathname !== "/") { filePath = `${util.trimSuffix(filePath, "/")}/index.html`; stat = await Deno.lstat(filePath); } if (stat.isFile) { const headers = new Headers({ "Content-Type": contentType }); const deployId = getDeploymentId(); let etag: string | null = null; if (deployId) { etag = `W/${btoa(pathname).replace(/[^a-z0-9]/g, "")}-${deployId}`; } else { const { mtime, size } = stat; if (mtime) { etag = `W/${mtime.getTime().toString(16)}-${size.toString(16)}`; headers.append("Last-Modified", new Date(mtime).toUTCString()); } } if (etag) { if (req.headers.get("If-None-Match") === etag) { return new Response(null, { status: 304 }); } headers.append("ETag", etag); } if (searchParams.get("v") || regFullVersion.test(pathname)) { headers.append("Cache-Control", "public, max-age=31536000, immutable"); } const file = await Deno.open(filePath, { read: true }); return new Response(readableStreamFromReader(file), { headers }); } } catch (err) { if (!(err instanceof Deno.errors.NotFound)) { log.error(err); return onError?.(err, { by: "fs", url: req.url }) ?? new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } } } // use post middlewares for (const mw of postMiddlewares) { try { let res = mw.fetch(req, ctx); if (res instanceof Promise) { res = await res; } if (res instanceof Response) { return res; } if (typeof res === "function") { setTimeout(res, 0); } } catch (err) { const res = onError?.(err, { by: "middleware", url: req.url, context: ctx }); if (res instanceof Response) { return res; } log.error(`[middleare${mw.name ? `(${mw.name})` : ""}]`, err); return new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } } // use the `fetch` handler if available if (typeof fetch === "function") { return fetch(req, ctx); } // request route api const routeConfig: RouteConfig | null = await globalIt( "__ALEPH_ROUTES", () => routes ? initRoutes(routes) : Promise.resolve(null), ); if (routeConfig && routeConfig.routes.length > 0) { const reqData = req.method === "GET" && (url.searchParams.has("_data_") || req.headers.get("Accept") === "application/json"); try { const resp = await fetchRouteData(routeConfig.routes, url, req, ctx, reqData); if (resp) { return resp; } } catch (err) { // javascript syntax error if (err instanceof TypeError && !reqData) { return new Response(generateErrorHtml(err.stack ?? err.message), { status: 500, headers: [["Content-Type", "text/html"]], }); } // use the `onError` if available const res = onError?.(err, { by: "route-data-fetch", url: req.url, context: ctx }); if (res instanceof Response) { return fixResponse(res, ctx.headers, reqData); } // user throw a response if (err instanceof Response) { return fixResponse(err, ctx.headers, reqData); } // prints the error stack if (err instanceof Error || typeof err === "string") { log.error(err); } // return the error as a json const status: number = util.isUint(err.status ?? err.code) ? err.status ?? err.code : 500; return Response.json({ ...err, status, message: err.message ?? String(err), stack: err.stack }, { status, headers: ctx.headers, }); } } // don't render those special asset files switch (pathname) { case "/favicon.ico": case "/robots.txt": return new Response("Not found", { status: 404 }); } try { const importMap = await globalIt("__ALEPH_IMPORT_MAP", loadImportMap); const indexHtml = await globalIt("__ALEPH_INDEX_HTML", () => loadAndFixIndexHtml({ isDev, importMap, ssr: typeof ssr === "function" ? {} : ssr, hmrWebSocketUrl: options.devServer?.hmrWebSocketUrl, })); return renderer.fetch(req, ctx, { indexHtml, routeConfig, customHTMLRewriter, isDev, ssr, }); } catch (err) { if (err instanceof Response) { return err; } let message: string; if (err instanceof Error) { message = err.stack as string; log.error("SSR", err); } else { message = err?.toString?.() || String(err); } const cc = ssr && typeof ssr !== "function" ? ssr.cacheControl : "public"; ctx.headers.append("Cache-Control", `${cc}, max-age=0, must-revalidate`); ctx.headers.append("Content-Type", "text/html; charset=utf-8"); return new Response(generateErrorHtml(message, "SSR"), { headers: ctx.headers }); } }; // set log level if specified if (logLevel) { log.setLevel(logLevel); } // inject global objects Reflect.set(globalThis, "__ALEPH_CONFIG", { routes, unocss, build, devServer }); Reflect.set(globalThis, "__ALEPH_CLIENT_DEP_GRAPH", new DependencyGraph()); const { hostname, port = 8080, certFile, keyFile, signal } = options; if (Deno.env.get("ALEPH_CLI")) { Reflect.set(globalThis, "__ALEPH_SERVER", { hostname, port, certFile, keyFile, handler, signal }); } else { if (certFile && keyFile) { serveTls(handler, { hostname, port, certFile, keyFile, signal }); } else { stdServe(handler, { hostname, port, signal }); } log.info(`Server ready on http://localhost:${port}`); } }; export { revive, setCookieHeader };
the_stack
import has = require('./has'); declare var process: any; declare var require: <ModuleType>(moduleId: string) => ModuleType; declare var module: { exports: any; }; export interface IConfig { baseUrl?: string; map?: IModuleMap; packages?: IPackage[]; paths?: { [path: string]: string; }; } export interface IDefine { (moduleId: string, dependencies: string[], factory: IFactory): void; (dependencies: string[], factory: IFactory): void; (factory: IFactory): void; (value: any): void; } export interface IFactory { (...modules: any[]): any; } export interface ILoaderPlugin { dynamic?: boolean; load?: (resourceId: string, require: IRequire, load: (value?: any) => void, config?: Object) => void; normalize?: (moduleId: string, normalize: (moduleId: string) => string) => string; } export interface IMapItem extends Array<any> { /* prefix */ 0: string; /* replacement */ 1: any; /* regExp */ 2: RegExp; /* length */ 3: number; } export interface IMapReplacement extends IMapItem { /* replacement */ 1: string; } export interface IMapRoot extends Array<IMapSource> { star?: IMapSource; } export interface IMapSource extends IMapItem { /* replacement */ 1: IMapReplacement[]; } export interface IModule extends ILoaderPlugin { cjs: { exports: any; id: string; setExports: (exports: any) => void; uri: string; }; def: IFactory; deps: IModule[]; executed: any; // TODO: enum injected: boolean; fix?: (module: IModule) => void; gc: boolean; mid: string; pack: IPackage; req: IRequire; require?: IRequire; // TODO: WTF? result: any; url: string; // plugin interface loadQ?: IModule[]; plugin?: IModule; prid: string; } export interface IModuleMap extends IModuleMapItem { [sourceMid: string]: IModuleMapReplacement; } export interface IModuleMapItem { [mid: string]: /*IModuleMapReplacement|IModuleMap*/any; } export interface IModuleMapReplacement extends IModuleMapItem { [findMid: string]: /* replaceMid */string; } export interface IPackage { location?: string; main?: string; name?: string; } export interface IPackageMap { [packageId: string]: IPackage; } export interface IPathMap extends IMapReplacement {} export interface IRequire { (config: IConfig, dependencies?: string[], callback?: IRequireCallback): void; (dependencies: string[], callback: IRequireCallback): void; <ModuleType>(moduleId: string): ModuleType; toAbsMid(moduleId: string): string; toUrl(path: string): string; } export interface IRequireCallback { (...modules: any[]): void; } export interface IRootRequire extends IRequire { config(config: IConfig): void; has: has; inspect?(name: string): any; nodeRequire?(id: string): any; signal(type: string, data: any[]): void; undef(moduleId: string): void; } (function (): void { var req: IRootRequire = <IRootRequire> function (config: any, dependencies?: any, callback?: IRequireCallback): void { if (/* require([], cb) */ Array.isArray(config) || /* require(mid) */ typeof config === 'string') { callback = <IRequireCallback> dependencies; dependencies = <string[]> config; config = {}; } if (has('loader-configurable')) { configure(config); } contextRequire(dependencies, callback); }; var has: has = req.has = (function (): has { var hasCache: { [name: string]: any; } = Object.create(null); var global: Window = this; var document: HTMLDocument = global.document; var element: HTMLDivElement = document && document.createElement('div'); var has: has = <has> function(name: string): any { return typeof hasCache[name] === 'function' ? (hasCache[name] = hasCache[name](global, document, element)) : hasCache[name]; }; has.add = function (name: string, test: any, now: boolean, force: boolean): void { (!(name in hasCache) || force) && (hasCache[name] = test); now && has(name); }; return has; })(); has.add('host-browser', typeof document !== 'undefined' && typeof location !== 'undefined'); has.add('host-node', typeof process === 'object' && process.versions && process.versions.node); has.add('debug', true); // IE9 will process multiple scripts at once before firing their respective onload events, so some extra work // needs to be done to associate the content of the define call with the correct node. This is known to be fixed // in IE10 and the bad behaviour cannot be inferred through feature detection, so simply target this one user-agent has.add('loader-ie9-compat', has('host-browser') && navigator.userAgent.indexOf('MSIE 9.0') > -1); has.add('loader-configurable', true); if (has('loader-configurable')) { /** * Configures the loader. * * @param {{ ?baseUrl: string, ?map: Object, ?packages: Array.<({ name, ?location, ?main }|string)> }} config * The configuration data. */ var configure: (config: IConfig) => void = req.config = function (config: IConfig): void { // TODO: Expose all properties on req as getter/setters? Plugin modules like dojo/node being able to // retrieve baseUrl is important. baseUrl is defined as a getter currently. baseUrl = (config.baseUrl || baseUrl).replace(/\/*$/, '/'); forEach(config.packages, function (p: IPackage): void { // Allow shorthand package definition, where name and location are the same if (typeof p === 'string') { p = { name: <string> p, location: <string> p }; } if (p.location != null) { p.location = p.location.replace(/\/*$/, '/'); } packs[p.name] = p; }); function computeMapProg(map: IModuleMapItem): IMapItem[] { // This method takes a map as represented by a JavaScript object and initializes an array of // arrays of (map-key, map-value, regex-for-map-key, length-of-map-key), sorted decreasing by length- // of-map-key. The regex looks for the map-key followed by either "/" or end-of-string at the beginning // of a the search source. // // Maps look like this: // // map: { C: { D: E } } // A B // // The computed mapping is a 4-array deep tree, where the outermost array corresponds to the source // mapping object A, the 2nd level arrays each correspond to one of the source mappings C -> B, the 3rd // level arrays correspond to each destination mapping object B, and the innermost arrays each // correspond to one of the destination mappings D -> E. // // So, the overall structure looks like this: // // mapProgs = [ source mapping array, source mapping array, ... ] // source mapping array = [ // source module id, // [ destination mapping array, destination mapping array, ... ], // RegExp that matches on source module id, // source module id length // ] // destination mapping array = [ // original module id, // destination module id, // RegExp that matches on original module id, // original module id length // ] var result: IMapItem[] = []; for (var moduleId in map) { var value: any = (<any> map)[moduleId]; var valueIsMapReplacement: boolean = typeof value === 'object'; var item = <IMapItem> { 0: moduleId, 1: valueIsMapReplacement ? computeMapProg(value) : value, 2: new RegExp('^' + moduleId.replace(/[-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') + '(?:\/|$)'), 3: moduleId.length }; result.push(item); if (valueIsMapReplacement && moduleId === '*') { (<IMapRoot> result).star = item[1]; } } result.sort(function (lhs: any, rhs: any): number { return rhs[3] - lhs[3]; }); return result; } mix(map, config.map); mapProgs = computeMapProg(map); // Note that old paths will get destroyed if reconfigured config.paths && (pathsMapProg = computeMapProg(config.paths)); }; } // // loader state data // // AMD baseUrl config var baseUrl: string = './'; // a map from pid to package configuration object var packs: IPackageMap = {}; // list of (from-path, to-path, regex, length) derived from paths; // a "program" to apply paths; see computeMapProg var pathsMapProg: IPathMap[] = []; // AMD map config variable var map: IModuleMap = {}; // array of quads as described by computeMapProg; map-key is AMD map key, map-value is AMD map value var mapProgs: IMapRoot = []; // A hash: (mid) --> (module-object) the module namespace // // pid: the package identifier to which the module belongs (e.g., "dojo"); "" indicates the system or default package // mid: the fully-resolved (i.e., mappings have been applied) module identifier without the package identifier (e.g., "dojo/io/script") // url: the URL from which the module was retrieved // pack: the package object of the package to which the module belongs // executed: false => not executed; EXECUTING => in the process of tranversing deps and running factory; true => factory has been executed // deps: the dependency array for this module (array of modules objects) // def: the factory for this module // result: the result of the running the factory for this module // injected: true => module has been injected // load, dynamic, normalize: plugin functions applicable only for plugins // // Modules go through several phases in creation: // // 1. Requested: some other module's definition or a require application contained the requested module in // its dependency array // // 2. Injected: a script element has been appended to the insert-point element demanding the resource implied by the URL // // 3. Loaded: the resource injected in [2] has been evaluated. // // 4. Defined: the resource contained a define statement that advised the loader about the module. // // 5. Evaluated: the module was defined via define and the loader has evaluated the factory and computed a result. var modules: { [moduleId: string]: IModule; } = {}; // hash: (mid | url)-->(function | string) // // A cache of resources. The resources arrive via a require.cache application, which takes a hash from either mid --> function or // url --> string. The function associated with mid keys causes the same code to execute as if the module was script injected. // // Both kinds of key-value pairs are entered into cache via the function consumePendingCache, which may relocate keys as given // by any mappings *iff* the cache was received as part of a module resource request. var cache: { [moduleId: string]: any; } = {}; // hash: (mid | url)-->(function | string) // // Gives a set of cache modules pending entry into cache. When cached modules are published to the loader, they are // entered into pendingCacheInsert; modules are then pressed into cache upon (1) AMD define or (2) upon receiving another // independent set of cached modules. (1) is the usual case, and this case allows normalizing mids given in the pending // cache for the local configuration, possibly relocating modules. var pendingCacheInsert: { [moduleId: string]: any; } = {}; function forEach<T>(array: T[], callback: (value: T, index: number, array: T[]) => void): void { array && array.forEach(callback); } function mix(target: {}, source: {}): {} { for (var key in source) { (<any> target)[key] = (<any> source)[key]; } return target; } function signal(type: string, event: any): void { req.signal.apply(req, arguments); } function consumePendingCacheInsert(referenceModule?: IModule): void { var item: any; for (var key in pendingCacheInsert) { item = pendingCacheInsert[key]; cache[typeof item === 'string' ? toUrl(key, referenceModule) : getModuleInfo(key, referenceModule).mid] = item; } pendingCacheInsert = {}; } var uidGenerator: number = 0; function contextRequire(moduleId: string, unused?: void, referenceModule?: IModule): IModule; function contextRequire(dependencies: string[], callback: IRequireCallback, referenceModule?: IModule): IModule; function contextRequire(a1: any, a2: any, referenceModule?: IModule): IModule { var module: IModule; if (typeof a1 === 'string') { module = getModule(a1, referenceModule); if (module.executed !== true && module.executed !== EXECUTING) { throw new Error('Attempt to require unloaded module ' + module.mid); } // Assign the result of the module to `module` // otherwise require('moduleId') returns the internal // module representation module = module.result; } else if (Array.isArray(a1)) { // signature is (requestList [,callback]) // construct a synthetic module to control execution of the requestList, and, optionally, callback module = getModuleInfo('*' + (++uidGenerator)); mix(module, { deps: resolveDeps(a1, module, referenceModule), def: a2 || {}, gc: true // garbage collect }); guardCheckComplete(function (): void { forEach(module.deps, injectModule.bind(null, module)); }); execQ.push(module); checkComplete(); } return module; } function createRequire(module: IModule): IRequire { var result: IRequire = (!module && req) || module.require; if (!result) { module.require = result = <IRequire> function (a1: any, a2: any): IModule { return contextRequire(a1, a2, module); }; mix(mix(result, req), { toUrl: function (name: string): string { return toUrl(name, module); }, toAbsMid: function (mid: string): string { return toAbsMid(mid, module); } }); } return result; } // The list of modules that need to be evaluated. var execQ: IModule[] = []; // The arguments sent to loader via AMD define(). var defArgs: any[] = null; // the number of modules the loader has injected but has not seen defined var waitingCount: number = 0; function runMapProg(targetMid: string, map: IMapItem[]): IMapSource { // search for targetMid in map; return the map item if found; falsy otherwise if (map) { for (var i = 0, j = map.length; i < j; ++i) { if (map[i][2].test(targetMid)) { return map[i]; } } } return null; } function compactPath(path: string): string { var result: string[] = []; var segment: string; var lastSegment: string; var splitPath: string[] = path.replace(/\\/g, '/').split('/'); while (splitPath.length) { segment = splitPath.shift(); if (segment === '..' && result.length && lastSegment !== '..') { result.pop(); lastSegment = result[result.length - 1]; } else if (segment !== '.') { result.push((lastSegment = segment)); } // else ignore "." } return result.join('/'); } function getModuleInfo(mid: string, referenceModule?: IModule): IModule { var match: string[]; var pid: string; var pack: IPackage; var midInPackage: string; var mapItem: IMapItem; var url: string; var result: IModule; // relative module ids are relative to the referenceModule; get rid of any dots mid = compactPath(/^\./.test(mid) && referenceModule ? (referenceModule.mid + '/../' + mid) : mid); // at this point, mid is an absolute mid // if there is a reference module, then use its module map, if one exists; otherwise, use the global map. // see computeMapProg for more information on the structure of the map arrays var moduleMap: IMapItem = referenceModule && runMapProg(referenceModule.mid, mapProgs); moduleMap = moduleMap ? moduleMap[1] : mapProgs.star; if ((mapItem = runMapProg(mid, moduleMap))) { mid = mapItem[1] + mid.slice(mapItem[3]); } match = mid.match(/^([^\/]+)(\/(.+))?$/); pid = match ? match[1] : ''; pack = packs[pid]; if (pack) { mid = pid + '/' + (midInPackage = (match[3] || pack.main || 'main')); } else { pid = ''; } if (!(result = modules[mid])) { mapItem = runMapProg(mid, pathsMapProg); url = mapItem ? mapItem[1] + mid.slice(mapItem[3]) : (pid ? pack.location + midInPackage : mid); result = <IModule> <any> { pid: pid, mid: mid, pack: pack, url: compactPath( // absolute urls should not be prefixed with baseUrl (/^(?:\/|\w+:)/.test(url) ? '' : baseUrl) + url + // urls with a javascript extension should not have another one added (/\.js(?:\?[^?]*)?$/.test(url) ? '' : '.js') ) }; } return result; } function resolvePluginResourceId(plugin: IModule, prid: string, contextRequire: IRequire): string { return plugin.normalize ? plugin.normalize(prid, contextRequire.toAbsMid) : contextRequire.toAbsMid(prid); } function getModule(mid: string, referenceModule?: IModule): IModule { // compute and construct (if necessary) the module implied by the mid with respect to referenceModule var match: string[]; var plugin: IModule; var prid: string; var result: IModule; var contextRequire: IRequire; var loaded: boolean; match = mid.match(/^(.+?)\!(.*)$/); if (match) { // name was <plugin-module>!<plugin-resource-id> plugin = getModule(match[1], referenceModule); loaded = Boolean(plugin.load); contextRequire = createRequire(referenceModule); if (loaded) { prid = resolvePluginResourceId(plugin, match[2], contextRequire); mid = (plugin.mid + '!' + (plugin.dynamic ? ++uidGenerator + '!' : '') + prid); } else { // if the plugin has not been loaded, then can't resolve the prid and must assume this plugin is dynamic until we find out otherwise prid = match[2]; mid = plugin.mid + '!' + (++uidGenerator) + '!*'; } result = <IModule> <any> { plugin: plugin, mid: mid, req: contextRequire, prid: prid, fix: !loaded }; } else { result = getModuleInfo(mid, referenceModule); } return modules[result.mid] || (modules[result.mid] = result); } function toAbsMid(mid: string, referenceModule: IModule): string { return getModuleInfo(mid, referenceModule).mid; } function toUrl(name: string, referenceModule: IModule): string { var moduleInfo: IModule = getModuleInfo(name + '/x', referenceModule); var url: string = moduleInfo.url; // "/x.js" since getModuleInfo automatically appends ".js" and we appended "/x" to make name look like a module id return url.slice(0, url.length - 5); } function makeCjs(mid: string): IModule { // TODO: Intentional incomplete coercion to IModule might be a bad idea var module: IModule = modules[mid] = <IModule> <any> { mid: mid, injected: true, executed: true }; return module; } var cjsRequireModule: IModule = makeCjs('require'); var cjsExportsModule: IModule = makeCjs('exports'); var cjsModuleModule: IModule = makeCjs('module'); var EXECUTING: string = 'executing'; var abortExec: Object = {}; var executedSomething: boolean = false; has.add('loader-debug-circular-dependencies', true); if (has('loader-debug-circular-dependencies')) { var circularTrace: string[] = []; } function execModule(module: IModule): any { // run the dependency array, then run the factory for module if (module.executed === EXECUTING) { // for circular dependencies, assume the first module encountered was executed OK // modules that circularly depend on a module that has not run its factory will get // the premade cjs.exports===module.result. They can take a reference to this object and/or // add properties to it. When the module finally runs its factory, the factory can // read/write/replace this object. Notice that so long as the object isn't replaced, any // reference taken earlier while walking the deps list is still valid. if ( has('loader-debug-circular-dependencies') && module.deps.indexOf(cjsExportsModule) === -1 && typeof console !== 'undefined' ) { console.warn('Circular dependency: ' + circularTrace.concat(module.mid).join(' -> ')); } return module.cjs.exports; } if (!module.executed) { // TODO: This seems like an incorrect condition inference. Originally it was simply !module.def // which caused modules with falsy defined values to never execute. if (!module.def && !module.deps) { return abortExec; } var deps: IModule[] = module.deps; var factory: IFactory = module.def; var result: any; var args: any[]; has('loader-debug-circular-dependencies') && circularTrace.push(module.mid); module.executed = EXECUTING; args = deps.map(function (dep: IModule): any { if (result !== abortExec) { result = ((dep === cjsRequireModule) ? createRequire(module) : ((dep === cjsExportsModule) ? module.cjs.exports : ((dep === cjsModuleModule) ? module.cjs : execModule(dep)))); } return result; }); if (result === abortExec) { module.executed = false; has('loader-debug-circular-dependencies') && circularTrace.pop(); return abortExec; } result = typeof factory === 'function' ? factory.apply(null, args) : factory; // TODO: But of course, module.cjs always exists. // Assign the new module.result to result so plugins can use exports // to define their interface; the plugin checks below use result result = module.result = result === undefined && module.cjs ? module.cjs.exports : result; module.executed = true; executedSomething = true; // delete references to synthetic modules if (module.gc) { modules[module.mid] = undefined; } // if result defines load, just assume it's a plugin; harmless if the assumption is wrong result && result.load && [ 'dynamic', 'normalize', 'load' ].forEach(function (key: string): void { (<any> module)[key] = (<any> result)[key]; }); // for plugins, resolve the loadQ forEach(module.loadQ, function (pseudoPluginResource: IModule): void { // manufacture and insert the real module in modules var prid: string = resolvePluginResourceId(module, pseudoPluginResource.prid, pseudoPluginResource.req); var mid: string = module.dynamic ? pseudoPluginResource.mid.replace(/\*$/, prid) : (module.mid + '!' + prid); var pluginResource: IModule = <IModule> mix(mix({}, pseudoPluginResource), { mid: mid, prid: prid }); if (!modules[mid]) { // create a new (the real) plugin resource and inject it normally now that the plugin is on board injectPlugin((modules[mid] = pluginResource)); } // else this was a duplicate request for the same (plugin, rid) for a nondynamic plugin // pluginResource is really just a placeholder with the wrong mid (because we couldn't calculate it until the plugin was on board) // fix() replaces the pseudo module in a resolved deps array with the real module // lastly, mark the pseudo module as arrived and delete it from modules pseudoPluginResource.fix(modules[mid]); --waitingCount; modules[pseudoPluginResource.mid] = undefined; }); module.loadQ = undefined; has('loader-debug-circular-dependencies') && circularTrace.pop(); } // at this point the module is guaranteed fully executed return module.result; } var checkCompleteGuard: number = 0; // TODO: Figure out what proc actually is function guardCheckComplete(proc: Function): void { ++checkCompleteGuard; proc(); --checkCompleteGuard; !defArgs && !waitingCount && !execQ.length && !checkCompleteGuard && signal('idle', []); } function checkComplete(): void { // keep going through the execQ as long as at least one factory is executed // plugins, recursion, cached modules all make for many execution path possibilities !checkCompleteGuard && guardCheckComplete(function (): void { for (var module: IModule, i = 0; i < execQ.length; ) { module = execQ[i]; if (module.executed === true) { execQ.splice(i, 1); } else { executedSomething = false; execModule(module); if (executedSomething) { // something was executed; this indicates the execQ was modified, maybe a // lot (for example a later module causes an earlier module to execute) i = 0; } else { // nothing happened; check the next module in the exec queue i++; } } } }); } function injectPlugin(module: IModule): void { // injects the plugin module given by module; may have to inject the plugin itself var plugin: IModule = module.plugin; var onLoad = function (def: any): void { module.result = def; --waitingCount; module.executed = true; checkComplete(); }; if (plugin.load) { plugin.load(module.prid, module.req, onLoad); } else if (plugin.loadQ) { plugin.loadQ.push(module); } else { // the unshift instead of push is important: we don't want plugins to execute as // dependencies of some other module because this may cause circles when the plugin // loadQ is run; also, generally, we want plugins to run early since they may load // several other modules and therefore can potentially unblock many modules plugin.loadQ = [module]; execQ.unshift(plugin); injectModule(module, plugin); } } function injectModule(parent: IModule, module: IModule): void { // TODO: This is for debugging, we should bracket it if (!module) { module = parent; parent = null; } if (module.plugin) { injectPlugin(module); } else if (!module.injected) { var cached: IFactory; var onLoadCallback = function (node?: HTMLScriptElement): void { // defArgs is an array of [dependencies, factory] consumePendingCacheInsert(module); if (has('loader-ie9-compat') && node) { defArgs = (<any> node).defArgs; } // non-amd module if (!defArgs) { defArgs = [ [], undefined ]; } defineModule(module, defArgs[0], defArgs[1]); defArgs = null; // checkComplete!==false holds the idle signal; we're not idle if we're injecting dependencies guardCheckComplete(function (): void { forEach(module.deps, injectModule.bind(null, module)); }); checkComplete(); }; ++waitingCount; module.injected = true; if ((cached = cache[module.mid])) { try { cached(); onLoadCallback(); return; } catch (error) { // If a cache load fails, notify and then retrieve using injectUrl signal('cachedThrew', [ error, module ]); } } injectUrl(module.url, onLoadCallback, module, parent); } } function resolveDeps(deps: string[], module: IModule, referenceModule: IModule): IModule[] { // resolve deps with respect to this module return deps.map(function (dep: string, i: number): IModule { var result: IModule = getModule(dep, referenceModule); if (result.fix) { result.fix = function (m: IModule): void { module.deps[i] = m; }; } return result; }); } function defineModule(module: IModule, deps: string[], def: IFactory): IModule { --waitingCount; return <IModule> mix(module, { def: def, deps: resolveDeps(deps, module, module), cjs: { id: module.mid, uri: module.url, exports: (module.result = {}), setExports: function (exports: any): void { module.cjs.exports = exports; } } }); } // PhantomJS has.add('function-bind', Boolean(Function.prototype.bind)); if (!has('function-bind')) { injectModule.bind = function (thisArg: any): typeof injectModule { var slice = Array.prototype.slice; var args: any[] = slice.call(arguments, 1); return function (): void { return injectModule.apply(thisArg, args.concat(slice.call(arguments, 0))); }; }; } var setGlobals: (require: IRequire, define: IDefine) => void; var injectUrl: (url: string, callback: (node?: HTMLScriptElement) => void, module: IModule, parent?: IModule) => void; if (has('host-node')) { var vm: any = require('vm'); var fs: any = require('fs'); // retain the ability to get node's require req.nodeRequire = require; injectUrl = function (url: string, callback: (node?: HTMLScriptElement) => void, module: IModule, parent?: IModule): void { fs.readFile(url, 'utf8', function (error: Error, data: string): void { if (error) { throw new Error('Failed to load module ' + module.mid + ' from ' + url + (parent ? ' (parent: ' + parent.mid + ')' : '')); } // global `module` variable needs to be shadowed for UMD modules that are loaded in an Electron webview; // in Node.js the `module` variable does not exist when using `vm.runInThisContext`, but in Electron it // exists in the webview when Node.js integration is enabled which causes loaded modules to register // with Node.js and break the loader var oldModule = this.module; this.module = undefined; try { vm.runInThisContext(data, url); } finally { this.module = oldModule; } callback(); }); }; setGlobals = function (require: IRequire, define: IDefine): void { module.exports = this.require = require; this.define = define; }; } else if (has('host-browser')) { injectUrl = function (url: string, callback: (node?: HTMLScriptElement) => void, module: IModule, parent?: IModule): void { // insert a script element to the insert-point element with src=url; // apply callback upon detecting the script has loaded. var node: HTMLScriptElement = document.createElement('script'); var handler: EventListener = function (event: Event): void { document.head.removeChild(node); if (event.type === 'load') { has('loader-ie9-compat') ? callback(node) : callback(); } else { throw new Error('Failed to load module ' + module.mid + ' from ' + url + (parent ? ' (parent: ' + parent.mid + ')' : '')); } }; node.addEventListener('load', handler, false); node.addEventListener('error', handler, false); (<any> node).crossOrigin = 'anonymous'; node.charset = 'utf-8'; node.src = url; document.head.appendChild(node); }; setGlobals = function (require: IRequire, define: IDefine): void { this.require = require; this.define = define; }; } else { throw new Error('Unsupported platform'); } has.add('loader-debug-internals', true); if (has('loader-debug-internals')) { req.inspect = function (name: string): any { /* tslint:disable:no-eval */ // TODO: Should this use console.log so people do not get any bright ideas about using this in apps? return eval(name); /* tslint:enable:no-eval */ }; } has.add('loader-undef', true); if (has('loader-undef')) { req.undef = function (id: string): void { if (modules[id]) { modules[id] = undefined; } }; } mix(req, { signal: function (): void {}, toAbsMid: toAbsMid, toUrl: toUrl, cache: function (cache: { [moduleId: string]: any; }): void { consumePendingCacheInsert(); pendingCacheInsert = cache; } }); Object.defineProperty(req, 'baseUrl', { get: function (): string { return baseUrl; }, enumerable: true }); has.add('loader-cjs-wrapping', true); if (has('loader-cjs-wrapping')) { var comments: RegExp = /\/\*[\s\S]*?\*\/|\/\/.*$/mg; var requireCall: RegExp = /require\s*\(\s*(["'])(.*?[^\\])\1\s*\)/g; } has.add('loader-explicit-mid', true); /** * @param deps //(array of commonjs.moduleId, optional) * @param factory //(any) */ var define: IDefine = <IDefine> mix(function (deps: string[], factory: IFactory): void { if (has('loader-explicit-mid') && arguments.length === 3) { var id: string = <any> deps; deps = <any> factory; factory = arguments[2]; // Some modules in the wild have an explicit module ID that is null; ignore the module ID in this case and // register normally using the request module ID if (id != null) { var module: IModule = getModule(id); module.injected = true; defineModule(module, deps, factory); } } if (arguments.length === 1) { if (has('loader-cjs-wrapping') && typeof deps === 'function') { factory = <any> deps; deps = [ 'require', 'exports', 'module' ]; // Scan factory for require() calls and add them to the // list of dependencies factory.toString() .replace(comments, '') .replace(requireCall, function (): string { deps.push(/* mid */ arguments[2]); return arguments[0]; }); } else if (/* define(value) */ !Array.isArray(deps)) { var value: any = deps; deps = []; factory = function (): any { return value; }; } } if (has('loader-ie9-compat')) { for (var i = document.scripts.length - 1, script: HTMLScriptElement; (script = <HTMLScriptElement> document.scripts[i]); --i) { if ((<any> script).readyState === 'interactive') { (<any> script).defArgs = [ deps, factory ]; break; } } } else { defArgs = [ deps, factory ]; } }, { amd: { vendor: 'dojotoolkit.org' } }); setGlobals(req, define); })();
the_stack
import type { ClientPagesLoaderOptions } from './webpack/loaders/next-client-pages-loader' import type { MiddlewareLoaderOptions } from './webpack/loaders/next-middleware-loader' import type { MiddlewareSSRLoaderQuery } from './webpack/loaders/next-middleware-ssr-loader' import type { NextConfigComplete } from '../server/config-shared' import type { PageRuntime } from '../server/config-shared' import type { ServerlessLoaderQuery } from './webpack/loaders/next-serverless-loader' import type { webpack5 } from 'next/dist/compiled/webpack/webpack' import type { LoadedEnvFiles } from '@next/env' import chalk from 'next/dist/compiled/chalk' import { posix, join } from 'path' import { stringify } from 'querystring' import { API_ROUTE, DOT_NEXT_ALIAS, MIDDLEWARE_FILE, MIDDLEWARE_FILENAME, PAGES_DIR_ALIAS, ROOT_DIR_ALIAS, APP_DIR_ALIAS, } from '../lib/constants' import { CLIENT_STATIC_FILES_RUNTIME_AMP, CLIENT_STATIC_FILES_RUNTIME_MAIN, CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT, CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH, EDGE_RUNTIME_WEBPACK, } from '../shared/lib/constants' import { __ApiPreviewProps } from '../server/api-utils' import { isTargetLikeServerless } from '../server/utils' import { warn } from './output/log' import { isServerComponentPage } from './utils' import { getPageStaticInfo } from './analysis/get-page-static-info' import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep' import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path' import { serverComponentRegex } from './webpack/loaders/utils' type ObjectValue<T> = T extends { [key: string]: infer V } ? V : never /** * For a given page path removes the provided extensions. */ export function getPageFromPath(pagePath: string, pageExtensions: string[]) { let page = normalizePathSep( pagePath.replace(new RegExp(`\\.+(${pageExtensions.join('|')})$`), '') ) page = page.replace(/\/index$/, '') return page === '' ? '/' : page } export function createPagesMapping({ hasServerComponents, isDev, pageExtensions, pagePaths, pagesType, }: { hasServerComponents: boolean isDev: boolean pageExtensions: string[] pagePaths: string[] pagesType: 'pages' | 'root' | 'app' }): { [page: string]: string } { const previousPages: { [key: string]: string } = {} const pages = pagePaths.reduce<{ [key: string]: string }>( (result, pagePath) => { // Do not process .d.ts files inside the `pages` folder if (pagePath.endsWith('.d.ts') && pageExtensions.includes('ts')) { return result } const pageKey = getPageFromPath(pagePath, pageExtensions) // Assume that if there's a Client Component, that there is // a matching Server Component that will map to the page. // so we will not process it if (hasServerComponents && /\.client$/.test(pageKey)) { return result } if (pageKey in result) { warn( `Duplicate page detected. ${chalk.cyan( join('pages', previousPages[pageKey]) )} and ${chalk.cyan( join('pages', pagePath) )} both resolve to ${chalk.cyan(pageKey)}.` ) } else { previousPages[pageKey] = pagePath } result[pageKey] = normalizePathSep( join( pagesType === 'pages' ? PAGES_DIR_ALIAS : pagesType === 'app' ? APP_DIR_ALIAS : ROOT_DIR_ALIAS, pagePath ) ) return result }, {} ) if (pagesType !== 'pages') { return pages } if (isDev) { delete pages['/_app'] delete pages['/_error'] delete pages['/_document'] } // In development we always alias these to allow Webpack to fallback to // the correct source file so that HMR can work properly when a file is // added or removed. const root = isDev ? PAGES_DIR_ALIAS : 'next/dist/pages' return { '/_app': `${root}/_app`, '/_error': `${root}/_error`, '/_document': `${root}/_document`, ...pages, } } interface CreateEntrypointsParams { buildId: string config: NextConfigComplete envFiles: LoadedEnvFiles isDev?: boolean pages: { [page: string]: string } pagesDir: string previewMode: __ApiPreviewProps rootDir: string rootPaths?: Record<string, string> target: 'server' | 'serverless' | 'experimental-serverless-trace' appDir?: string appPaths?: Record<string, string> pageExtensions: string[] } export function getEdgeServerEntry(opts: { absolutePagePath: string buildId: string bundlePath: string config: NextConfigComplete isDev: boolean isServerComponent: boolean page: string pages: { [page: string]: string } }) { if (opts.page === MIDDLEWARE_FILE) { const loaderParams: MiddlewareLoaderOptions = { absolutePagePath: opts.absolutePagePath, page: opts.page, } return `next-middleware-loader?${stringify(loaderParams)}!` } const loaderParams: MiddlewareSSRLoaderQuery = { absolute500Path: opts.pages['/500'] || '', absoluteAppPath: opts.pages['/_app'], absoluteDocumentPath: opts.pages['/_document'], absoluteErrorPath: opts.pages['/_error'], absolutePagePath: opts.absolutePagePath, buildId: opts.buildId, dev: opts.isDev, isServerComponent: isServerComponentPage( opts.config, opts.absolutePagePath ), page: opts.page, stringifiedConfig: JSON.stringify(opts.config), } return { import: `next-middleware-ssr-loader?${stringify(loaderParams)}!`, layer: opts.isServerComponent ? 'sc_server' : undefined, } } export function getAppEntry(opts: { name: string pagePath: string appDir: string pageExtensions: string[] }) { return { import: `next-app-loader?${stringify(opts)}!`, layer: 'sc_server', } } export function getServerlessEntry(opts: { absolutePagePath: string buildId: string config: NextConfigComplete envFiles: LoadedEnvFiles page: string previewMode: __ApiPreviewProps pages: { [page: string]: string } }): ObjectValue<webpack5.EntryObject> { const loaderParams: ServerlessLoaderQuery = { absolute404Path: opts.pages['/404'] || '', absoluteAppPath: opts.pages['/_app'], absoluteDocumentPath: opts.pages['/_document'], absoluteErrorPath: opts.pages['/_error'], absolutePagePath: opts.absolutePagePath, assetPrefix: opts.config.assetPrefix, basePath: opts.config.basePath, buildId: opts.buildId, canonicalBase: opts.config.amp.canonicalBase || '', distDir: DOT_NEXT_ALIAS, generateEtags: opts.config.generateEtags ? 'true' : '', i18n: opts.config.i18n ? JSON.stringify(opts.config.i18n) : '', // base64 encode to make sure contents don't break webpack URL loading loadedEnvFiles: Buffer.from(JSON.stringify(opts.envFiles)).toString( 'base64' ), page: opts.page, poweredByHeader: opts.config.poweredByHeader ? 'true' : '', previewProps: JSON.stringify(opts.previewMode), reactRoot: !!opts.config.experimental.reactRoot ? 'true' : '', runtimeConfig: Object.keys(opts.config.publicRuntimeConfig).length > 0 || Object.keys(opts.config.serverRuntimeConfig).length > 0 ? JSON.stringify({ publicRuntimeConfig: opts.config.publicRuntimeConfig, serverRuntimeConfig: opts.config.serverRuntimeConfig, }) : '', } return `next-serverless-loader?${stringify(loaderParams)}!` } export function getClientEntry(opts: { absolutePagePath: string page: string }) { const loaderOptions: ClientPagesLoaderOptions = { absolutePagePath: opts.absolutePagePath, page: opts.page, } const pageLoader = `next-client-pages-loader?${stringify(loaderOptions)}!` // Make sure next/router is a dependency of _app or else chunk splitting // might cause the router to not be able to load causing hydration // to fail return opts.page === '/_app' ? [pageLoader, require.resolve('../client/router')] : pageLoader } export async function createEntrypoints(params: CreateEntrypointsParams) { const { config, pages, pagesDir, isDev, rootDir, rootPaths, target, appDir, appPaths, pageExtensions, } = params const edgeServer: webpack5.EntryObject = {} const server: webpack5.EntryObject = {} const client: webpack5.EntryObject = {} const getEntryHandler = (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') => async (page: string) => { const bundleFile = normalizePagePath(page) const clientBundlePath = posix.join('pages', bundleFile) const serverBundlePath = pagesType === 'pages' ? posix.join('pages', bundleFile) : pagesType === 'app' ? posix.join('app', bundleFile) : bundleFile.slice(1) const absolutePagePath = mappings[page] // Handle paths that have aliases const pageFilePath = (() => { if (absolutePagePath.startsWith(PAGES_DIR_ALIAS)) { return absolutePagePath.replace(PAGES_DIR_ALIAS, pagesDir) } if (absolutePagePath.startsWith(APP_DIR_ALIAS) && appDir) { return absolutePagePath.replace(APP_DIR_ALIAS, appDir) } if (absolutePagePath.startsWith(ROOT_DIR_ALIAS)) { return absolutePagePath.replace(ROOT_DIR_ALIAS, rootDir) } return require.resolve(absolutePagePath) })() /** * When we find a middleware file that is not in the ROOT_DIR we fail. * There is no need to check on `dev` as this should only happen when * building for production. */ if ( !absolutePagePath.startsWith(ROOT_DIR_ALIAS) && /[\\\\/]_middleware$/.test(page) ) { throw new Error( `nested Middleware is not allowed (found pages${page}) - https://nextjs.org/docs/messages/nested-middleware` ) } const isServerComponent = serverComponentRegex.test(absolutePagePath) const staticInfo = await getPageStaticInfo({ nextConfig: config, pageFilePath, isDev, }) runDependingOnPageType({ page, pageRuntime: staticInfo.runtime, onClient: () => { if (isServerComponent) { // We skip the initial entries for server component pages and let the // server compiler inject them instead. } else { client[clientBundlePath] = getClientEntry({ absolutePagePath: mappings[page], page, }) } }, onServer: () => { if (pagesType === 'app' && appDir) { server[serverBundlePath] = getAppEntry({ name: serverBundlePath, pagePath: mappings[page], appDir, pageExtensions, }) } else if (isTargetLikeServerless(target)) { if (page !== '/_app' && page !== '/_document') { server[serverBundlePath] = getServerlessEntry({ ...params, absolutePagePath: mappings[page], page, }) } } else { server[serverBundlePath] = isServerComponent ? { import: mappings[page], layer: 'sc_server', } : [mappings[page]] } }, onEdgeServer: () => { edgeServer[serverBundlePath] = getEdgeServerEntry({ ...params, absolutePagePath: mappings[page], bundlePath: clientBundlePath, isDev: false, isServerComponent, page, }) }, }) } if (appDir && appPaths) { const entryHandler = getEntryHandler(appPaths, 'app') await Promise.all(Object.keys(appPaths).map(entryHandler)) } if (rootPaths) { await Promise.all( Object.keys(rootPaths).map(getEntryHandler(rootPaths, 'root')) ) } await Promise.all(Object.keys(pages).map(getEntryHandler(pages, 'pages'))) return { client, server, edgeServer, } } export function runDependingOnPageType<T>(params: { onClient: () => T onEdgeServer: () => T onServer: () => T page: string pageRuntime: PageRuntime }) { if (params.page === MIDDLEWARE_FILE) { return [params.onEdgeServer()] } else if (params.page.match(API_ROUTE)) { return [params.onServer()] } else if (params.page === '/_document') { return [params.onServer()] } else if ( params.page === '/_app' || params.page === '/_error' || params.page === '/404' || params.page === '/500' ) { return [params.onClient(), params.onServer()] } else { return [ params.onClient(), params.pageRuntime === 'edge' ? params.onEdgeServer() : params.onServer(), ] } } export function finalizeEntrypoint({ name, compilerType, value, isServerComponent, }: { compilerType?: 'client' | 'server' | 'edge-server' name: string value: ObjectValue<webpack5.EntryObject> isServerComponent?: boolean }): ObjectValue<webpack5.EntryObject> { const entry = typeof value !== 'object' || Array.isArray(value) ? { import: value } : value if (compilerType === 'server') { const isApi = name.startsWith('pages/api/') return { publicPath: isApi ? '' : undefined, runtime: isApi ? 'webpack-api-runtime' : 'webpack-runtime', layer: isApi ? 'api' : isServerComponent ? 'sc_server' : undefined, ...entry, } } if (compilerType === 'edge-server') { return { layer: name === MIDDLEWARE_FILENAME ? 'middleware' : undefined, library: { name: ['_ENTRIES', `middleware_[name]`], type: 'assign' }, runtime: EDGE_RUNTIME_WEBPACK, asyncChunks: false, ...entry, } } if ( // Client special cases name !== 'polyfills' && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN && name !== CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT && name !== CLIENT_STATIC_FILES_RUNTIME_AMP && name !== CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH ) { return { dependOn: name.startsWith('pages/') && name !== 'pages/_app' ? 'pages/_app' : 'main', ...entry, } } return entry }
the_stack
import { GeoPackage, GeoPackageAPI, FeatureColumn, GeometryColumns, GeoPackageDataType, BoundingBox, } from '@ngageoint/geopackage'; import fs from 'fs'; import path from 'path'; import stream from 'stream'; import shp from 'shp-stream'; import shpwrite from 'shp-write'; import proj4 from 'proj4'; import reproject from 'reproject'; import jszip from 'jszip'; /** * Add a Shapefile to the GeoPackage * | option | type | | * | ------------ | ------- | -------------- | * | `geopackage` | varies | This option can either be a string or a GeoPackage object. If the option is a string it is interpreted as a path to a GeoPackage file. If that file exists, it is opened. If it does not exist, a new file is created and opened. | * | `shapezipData` | Buffer | Buffer with the data for a zip file containing a shapefile and it's associated files | * | `shapeData` | Buffer | Buffer with the data for a shapefile (.shp) | * | `shapefile` | String | Interpreted as a path to a .shp or .zip file | * | `dbfData` | String | Only used if the 'shapeData' parameter was provided. Buffer with the data for a dbf file (.dbf) | * @param {object} options object describing the operation, see function description * @param {Function} progressCallback called with an object describing the progress and a done function to be called when the handling of progress is completed */ export interface ShapefileConverterOptions { append?: boolean; geoPackage?: GeoPackage; shapezipData?: Buffer; shapeData?: Buffer; shapefile?: string; dbfData?: string; } export class ShapefileToGeoPackage { constructor(private options?: ShapefileConverterOptions) {} async addLayer(options?: ShapefileConverterOptions, progressCallback?: Function): Promise<any> { const clonedOptions = { ...this.options, ...options }; clonedOptions.append = true; return this.setupConversion(clonedOptions, progressCallback); } async convert(options?: ShapefileConverterOptions, progressCallback?: Function): Promise<GeoPackage> { const clonedOptions = { ...this.options, ...options }; clonedOptions.append = false; return this.setupConversion(clonedOptions, progressCallback); } async extract(geopackage, tableName): Promise<any> { if (!tableName) { const tables = geopackage.getFeatureTables(); return this.createShapefile(geopackage, tables); } else { return this.createShapefile(geopackage, tableName); } } async createShapefile(geopackage: GeoPackage, tableName: string | Array<string>): Promise<any> { const geoJson = { type: 'FeatureCollection', features: [], }; if (!(tableName instanceof Array)) { tableName = [tableName]; } return tableName .reduce(function(sequence, name) { return sequence.then(function() { const iterator = geopackage.iterateGeoJSONFeatures(name); for (const feature of iterator) { geoJson.features.push(feature); } }); }, Promise.resolve()) .then(function() { return shpwrite.zip(geoJson); }); } determineTableName(preferredTableName: string, geopackage: GeoPackage): string { let name = preferredTableName; const tables = geopackage.getFeatureTables(); let count = 1; while (tables.indexOf(name) !== -1) { name = name + '_' + count; count++; } return name; } readRecord(builder) { return new Promise((resolve, reject) => { setTimeout(() => { builder.reader.readRecord((err, r) => { const feature = r; if (feature === shp.end) { return resolve(builder); } if (!feature) { return resolve(this.readRecord(builder)); } builder.features.push(feature); for (const key in feature.properties) { if (!builder.properties[key]) { builder.properties[key] = builder.properties[key] || { name: key, }; let type: string = typeof feature.properties[key]; if (feature.properties[key] !== undefined && feature.properties[key] !== null && type !== 'undefined') { if (type === 'object') { if (feature.properties[key] instanceof Date) { type = 'Date'; } else { continue; } } switch (type) { case 'Date': type = 'DATETIME'; break; case 'number': type = 'DOUBLE'; break; case 'string': type = 'TEXT'; break; case 'boolean': type = 'BOOLEAN'; break; } builder.properties[key] = { name: key, type: type, }; } } } return resolve(this.readRecord(builder)); }); }); }); } determineFeatureTableColumns(builder): any { const geometryColumns = new GeometryColumns(); geometryColumns.table_name = builder.tableName; geometryColumns.column_name = 'geometry'; geometryColumns.geometry_type_name = 'GEOMETRY'; geometryColumns.z = 0; geometryColumns.m = 0; const columns = []; columns.push(FeatureColumn.createPrimaryKeyColumnWithIndexAndName(0, 'id')); columns.push(FeatureColumn.createGeometryColumn(1, 'geometry', 'GEOMETRY', false, null)); let index = 2; for (const key in builder.properties) { const prop = builder.properties[key]; if (prop.name.toLowerCase() !== 'id') { columns.push(FeatureColumn.createColumn(index, prop.name, GeoPackageDataType.fromName(prop.type), false, null)); index++; } } builder.columns = columns; builder.geometryColumns = geometryColumns; return builder; } async createFeatureTable(geopackage: GeoPackage, builder: any): Promise<any> { let boundingBox = new BoundingBox(-180, 180, -90, 90); if (builder.projection && builder.bbox) { // bbox is xmin, ymin, xmax, ymax const ll = proj4(builder.projection).inverse([builder.bbox[0], builder.bbox[1]]); const ur = proj4(builder.projection).inverse([builder.bbox[2], builder.bbox[3]]); boundingBox = new BoundingBox(ll[0], ur[0], ll[1], ur[1]); } await geopackage.createFeatureTable(builder.tableName, builder.geometryColumns, builder.columns, boundingBox, 4326); builder.featureDao = geopackage.getFeatureDao(builder.tableName); return builder; } async addFeaturesToTable(geopackage: GeoPackage, builder: any, progressCallback: Function): Promise<void> { let count = 0; const featureCount = builder.features.length; const fivePercent = Math.floor(featureCount / 20); for (let i = 0; i < featureCount; i++) { let feature = builder.features[i]; if (builder.projection) { feature = reproject.reproject(feature, builder.projection, 'EPSG:4326'); } geopackage.addGeoJSONFeatureToGeoPackage(feature, builder.tableName); if (count++ % fivePercent === 0) { if (progressCallback) await progressCallback({ status: 'Inserting features into table "' + builder.tableName + '"', completed: count, total: featureCount, }); } } if (progressCallback) await progressCallback({ status: 'Done inserting features into table "' + builder.tableName + '"', }); } async convertShapefileReaders(readers: any, geopackage: GeoPackage, progressCallback: Function): Promise<GeoPackage> { for (let r = 0; r < readers.length; r++) { const shapefile = readers[r]; const builder = { tableName: shapefile.tableName, reader: shapefile.reader, projection: shapefile.projection, features: [], bbox: undefined, properties: {}, }; builder.tableName = this.determineTableName(builder.tableName, geopackage); await new Promise(function(resolve, reject) { shapefile.reader.readHeader(function(err, header) { builder.bbox = header ? header.bbox : undefined; resolve(builder); }); }); if (progressCallback) await progressCallback({ status: 'Reading Shapefile properties' }); builder.properties = {}; await this.readRecord(builder); this.determineFeatureTableColumns(builder); if (progressCallback) await progressCallback({ status: 'Creating table "' + builder.tableName + '"' }); await this.createFeatureTable(geopackage, builder); await this.addFeaturesToTable(geopackage, builder, progressCallback); await new Promise(function(resolve, reject) { if (shapefile.reader) { shapefile.reader.close(resolve); } else { resolve(); } }); } return geopackage; } async getReadersFromZip(zip: any): Promise<any[]> { const readers = []; const shpfileArray = zip.filter(function(relativePath, file) { return path.extname(relativePath) === '.shp' && relativePath.indexOf('__MACOSX') == -1; }); const dbffileArray = zip.filter(function(relativePath, file) { return path.extname(relativePath) === '.dbf' && relativePath.indexOf('__MACOSX') == -1; }); const prjfileArray = zip.filter(function(relativePath, file) { return path.extname(relativePath) === '.prj' && relativePath.indexOf('__MACOSX') == -1; }); for (let i = 0; i < shpfileArray.length; i++) { const shapeZipObject = shpfileArray[i]; const shpBuffer = await shapeZipObject.async('nodebuffer'); const shpStream = new stream.PassThrough(); shpStream.end(shpBuffer); const basename = path.basename(shapeZipObject.name, path.extname(shapeZipObject.name)); let dbfStream; for (let d = 0; d < dbffileArray.length; d++) { const dbfZipObject = dbffileArray[d]; if (dbfZipObject.name == basename + '.dbf') { const dbfBuffer = await dbfZipObject.async('nodebuffer'); dbfStream = new stream.PassThrough(); dbfStream.end(dbfBuffer); break; } } let projection; for (let p = 0; p < prjfileArray.length; p++) { const prjZipObject = prjfileArray[p]; if (prjZipObject.name == basename + '.prj') { const prjBuffer = await prjZipObject.async('nodebuffer'); projection = proj4.Proj(prjBuffer.toString()); break; } } readers.push({ tableName: basename, projection: projection, reader: shp.reader({ shp: shpStream, dbf: dbfStream, 'ignore-properties': !!dbfStream, }), }); } return readers; } async setupConversion(options: ShapefileConverterOptions, progressCallback: Function): Promise<any> { let geopackage = options.geoPackage; let readers; let dbf; if (options.shapezipData) { const zip = new jszip(); await zip.loadAsync(options.shapezipData); readers = await this.getReadersFromZip(zip); } else if (options.shapeData) { const shpStream = new stream.PassThrough(); const shpBuffer = new Buffer(options.shapeData); shpStream.end(shpBuffer); let dbfStream; if (options.dbfData) { dbfStream = new stream.PassThrough(); const dbfBuffer = new Buffer(options.dbfData); dbfStream.end(dbfBuffer); } readers = [ { tableName: 'features', reader: shp.reader({ dbf: dbfStream, 'ignore-properties': !!options.dbfData, shp: shpStream, }), }, ]; } else { const extension = path.extname(options.shapefile); if (extension.toLowerCase() === '.zip') { readers = await new Promise((resolve, reject) => { fs.readFile(options.shapefile, async (err, data) => { const zip = new jszip(); await zip.loadAsync(data); resolve(this.getReadersFromZip(zip)); }); }); } else { dbf = path.basename(options.shapefile, path.extname(options.shapefile)) + '.dbf'; try { const stats = fs.statSync(dbf); readers = [ { tableName: path.basename(options.shapefile, path.extname(options.shapefile)), reader: shp.reader(options.shapefile), }, ]; } catch (e) { readers = [ { tableName: path.basename(options.shapefile, path.extname(options.shapefile)), reader: shp.reader(options.shapefile, { 'ignore-properties': true, }), }, ]; } } } geopackage = await this.createOrOpenGeoPackage(geopackage, options, progressCallback); return this.convertShapefileReaders(readers, geopackage, progressCallback); } async createOrOpenGeoPackage( geopackage: GeoPackage, options: ShapefileConverterOptions, progressCallback?: Function, ): Promise<GeoPackage> { if (typeof geopackage === 'object') { if (progressCallback) await progressCallback({ status: 'Opening GeoPackage' }); return geopackage; } else { let stats; try { stats = fs.statSync(geopackage); } catch (e) {} if (stats && !options.append) { console.log('GeoPackage file already exists, refusing to overwrite ' + geopackage); throw new Error('GeoPackage file already exists, refusing to overwrite ' + geopackage); } else if (stats) { return GeoPackageAPI.open(geopackage); } if (progressCallback) await progressCallback({ status: 'Creating GeoPackage' }); console.log('Create new geopackage', geopackage); return GeoPackageAPI.create(geopackage); } } }
the_stack
import * as t from '@babel/types'; import traverse from '@babel/traverse'; import type { Metadata } from '../types'; import { babelEvaluateExpression, getMemberExpressionMeta, getPathOfNode, getValueFromObjectExpression, isCompiledKeyframesCallExpression, resolveBindingNode, wrapNodeInIIFE, } from './ast'; const createResultPair = (value: t.Expression, meta: Metadata) => ({ value, meta, }); /** * Will look in an expression and return the actual value along with updated metadata. * * E.g: If there is an identifier called `color` that is set somewhere as `const color = 'blue'`, * passing the `color` identifier to this function would return `'blue'`. * * @param expression Expression we want to interrogate. * @param meta {Metadata} Useful metadata that can be used during the transformation */ const traverseIdentifier = (expression: t.Identifier, meta: Metadata) => { let value: t.Node | undefined | null = undefined; let updatedMeta: Metadata = meta; const resolvedBinding = resolveBindingNode(expression.name, updatedMeta); if (resolvedBinding && resolvedBinding.constant && resolvedBinding.node) { // We recursively call get interpolation until it not longer returns an identifier or member expression ({ value, meta: updatedMeta } = evaluateExpression( resolvedBinding.node as t.Expression, resolvedBinding.meta )); } return createResultPair(value as t.Expression, updatedMeta); }; /** * Will evaluate object values recursively and return the actual value along with updated metadata. * * E.g: If there is an object expression `{ x: () => 10 }`, it will evaluate and * return `value` as `10`. * @param expression Expression we want to interrogate. * @param accessPath An array of nested object keys * @param meta {Metadata} Useful metadata that can be used during the transformation */ const evaluateObjectExpression = ( expression: t.Expression, accessPath: t.Identifier[], meta: Metadata ) => { let value: t.Node | undefined | null = expression; let updatedMeta: Metadata = meta; if (t.isObjectExpression(expression)) { const objectValue = getValueFromObjectExpression(expression, accessPath) as t.Expression; ({ value, meta: updatedMeta } = evaluateExpression(objectValue, updatedMeta)); } return createResultPair(value, updatedMeta); }; /** * Will look in an expression and return the actual value along with updated metadata. * * E.g: If there is a member expression called `colors().primary` that has identifier `colors` which * is set somewhere as `const colors = () => ({ primary: 'blue' })`, * passing the `colors` identifier to this function would return `'blue'`. * * @param expression Expression we want to interrogate. * @param accessPath An array of nested object keys * @param meta {Metadata} Useful metadata that can be used during the transformation */ const evaluateCallExpressionBindingMemberExpression = ( expression: t.Expression, accessPath: t.Identifier[], meta: Metadata ) => { let value: t.Node | undefined | null = expression; let updatedMeta: Metadata = meta; if (t.isFunction(expression)) { ({ value, meta: updatedMeta } = evaluateExpression(expression as t.Expression, meta)); ({ value, meta: updatedMeta } = evaluateObjectExpression(value, accessPath, updatedMeta)); } return createResultPair(value, updatedMeta); }; /** * Will look in an expression and return the actual value along with updated metadata. * * E.g: * 1. If there is a member expression called `colors.primary` that has identifier `colors` which * is set somewhere as `const colors = { primary: 'blue' }`, * passing the `colors` identifier to this function would return `'blue'`. * * 2. If there is a member expression called `colors.primary` that has identifier `colors` which * is set somewhere as `const colors = colorMixin();` calling another identifier * `const colorMixin = () => ({ primary: 'blue' })`, passing the `colors` identifier * to this function would return `'blue'`. * * @param expression Expression we want to interrogate. * @param accessPath An array of nested object keys * @param meta {Metadata} Useful metadata that can be used during the transformation */ const evaluateIdentifierBindingMemberExpression = ( expression: t.Expression, accessPath: t.Identifier[], meta: Metadata ) => { let value: t.Node | undefined | null = expression; let updatedMeta: Metadata = meta; if (t.isObjectExpression(expression)) { ({ value, meta: updatedMeta } = evaluateObjectExpression(expression, accessPath, meta)); } else if (t.isCallExpression(expression)) { ({ value, meta: updatedMeta } = evaluateExpression(expression, meta)); ({ value, meta: updatedMeta } = evaluateObjectExpression(value, accessPath, updatedMeta)); } return createResultPair(value, updatedMeta); }; /** * Will look in an expression and return the actual value along with updated metadata. * * E.g: If there is a member expression called `colors.primary` that has identifier `color` which * is set somewhere as `const colors = { primary: 'blue' }`, * passing the `colors` identifier to this function would return `'blue'`. * * @param expression Expression we want to interrogate. * @param meta {Metadata} Useful metadata that can be used during the transformation */ const traverseMemberExpression = (expression: t.MemberExpression, meta: Metadata) => { let value: t.Node | undefined | null = undefined; let updatedMeta: Metadata = meta; const { accessPath, bindingIdentifier, originalBindingType } = getMemberExpressionMeta( expression ); if (bindingIdentifier) { const resolvedBinding = resolveBindingNode(bindingIdentifier.name, updatedMeta); if (resolvedBinding && resolvedBinding.constant && t.isExpression(resolvedBinding.node)) { if (originalBindingType === 'Identifier') { ({ value, meta: updatedMeta } = evaluateIdentifierBindingMemberExpression( resolvedBinding.node, accessPath, resolvedBinding.meta )); } else if (originalBindingType === 'CallExpression') { ({ value, meta: updatedMeta } = evaluateCallExpressionBindingMemberExpression( resolvedBinding.node, accessPath, resolvedBinding.meta )); } } } return createResultPair(value as t.Expression, updatedMeta); }; /** * Will look in an expression and return the actual value along with updated metadata. * * E.g: If there was a function called `size` that is set somewhere as * `const size = () => 10` or `const size = function() { return 10; }` or `function size() { return 10; }`, * passing the `size` identifier to this function would return `10` (it will recursively evaluate). * * @param expression Expression we want to interrogate. * @param meta {Metadata} Useful metadata that can be used during the transformation */ const traverseFunction = (expression: t.Function, meta: Metadata) => { let value: t.Node | undefined | null = undefined; let updatedMeta: Metadata = meta; if (t.isBlockStatement(expression.body)) { traverse(expression.body, { noScope: true, ReturnStatement(path) { const { argument } = path.node; if (argument) { ({ value, meta: updatedMeta } = evaluateExpression(argument, meta)); } path.stop(); }, }); } else { ({ value, meta: updatedMeta } = evaluateExpression(expression.body, meta)); } return createResultPair(value as t.Expression, updatedMeta); }; /** * Will find the function node for the call expression and wrap an IIFE around it (to avoid name collision) * and move all the parameters mapped to passed arguments in the IIFE's scope (own scope in this case). * It will also set own scope path so that when we recursively evaluate any node, * we will look for its binding in own scope first, then parent scope. * * @param expression Expression we want to interrogate. * @param meta {Metadata} Useful metadata that can be used during the transformation */ const traverseCallExpression = (expression: t.CallExpression, meta: Metadata) => { const callee = expression.callee; let value: t.Node | undefined | null = undefined; // Make sure updatedMeta is a new object, so that when the ownPath is set, the meta does not get re-used incorrectly in // later parts of the AST let updatedMeta: Metadata = { ...meta }; /* Basically flow is as follows: 1. Get the calling function node. It can be either identifier `func('arg')` or a member expression `x.func('arg')`; 2. Save the reference of function node for example `func`. 3. Pull out its parameters. 4. Evaluate the args of calling function `func('arg')` by traversing recursively. 5. Loop through params, and map the args with params. 6. Pull the params and create an IIFE around the calling function `CallExpression` which creates a new scope around calling function and isolates everything (We add bindings at this step by pushing into its scope). 7. Add that IIFE node path to `ownPath`, and check only for own binding in `resolveBindingNode` function so that only isolated params are evaluated. 8. In `resolveBindingNode`, if `ownPath` is not set (module traversal case or any other case), it will pick things from `parentPath`. */ if (t.isExpression(callee)) { let functionNode = null; // Get func node either from `Identifier` i.e. `func('arg')` or `MemberExpression` i.e. `x.func('arg')`. // Right now we are only supported these 2 flavors. If we have complex case like `func('arg').fn().variable`, // it will not get evaluated. if (t.isIdentifier(callee)) { const resolvedBinding = resolveBindingNode(callee.name, updatedMeta); if (resolvedBinding && resolvedBinding.constant) { functionNode = resolvedBinding.node; } } else if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) { const { accessPath, bindingIdentifier } = getMemberExpressionMeta(callee); if (bindingIdentifier) { const resolvedBinding = resolveBindingNode(bindingIdentifier.name, updatedMeta); if (resolvedBinding && resolvedBinding.constant) { if (t.isObjectExpression(resolvedBinding.node)) { functionNode = getValueFromObjectExpression(resolvedBinding.node, accessPath); } } } } // Check if it is resolved if (functionNode && t.isFunction(functionNode)) { // Pull its parameters const { params } = functionNode; // Evaluate the passed args recursively const evaluatedArguments = expression.arguments.map( (argument) => evaluateExpression(argument as t.Expression, updatedMeta).value ); // Get path of the call expression `func('arg')` or `x.func('arg')` const expressionPath = getPathOfNode(expression, updatedMeta.parentPath); // Create an IIFE around it and replace its path. So `func('arg')` will become `(() => func('arg'))()` // and `x.func('arg')` will become `(() => x.func('arg'))()`. // `wrappingNodePath` is the path above. const [wrappingNodePath] = expressionPath.replaceWith(wrapNodeInIIFE(expression)); // Get arrowFunctionExpressionPath, which was created using the IIFE const arrowFunctionExpressionPath = getPathOfNode( wrappingNodePath.node.callee, wrappingNodePath as any ); // Loop through the parameters. Right now only identifier `param` and object pattern `{ param }` or `{ param: p }` // are supported. params .filter((param) => t.isIdentifier(param) || t.isObjectPattern(param)) .forEach((param, index) => { const evaluatedArgument = evaluatedArguments[index]; // Push evaluated args and params in the IIFE's scope by created a local variable // `const param = 'evaluated arg value'` arrowFunctionExpressionPath.scope.push({ id: param, init: evaluatedArgument, kind: 'const', }); }); // Set the `ownPath` which `resolveBindingNode` will use to check own binding for the // local variables we created above. updatedMeta.ownPath = arrowFunctionExpressionPath; } ({ value, meta: updatedMeta } = evaluateExpression(callee, updatedMeta)); } return createResultPair(value as t.Expression, updatedMeta); }; /** * Will look in an expression and return the actual value along with updated metadata. * If the expression is an identifier node (a variable) and a constant, * it will return the variable reference. * * E.g: If there was a identifier called `color` that is set somewhere as `const color = 'blue'`, * passing the `color` identifier to this function would return `'blue'`. * * This behaviour is the same for const string & numeric literals, * and object expressions. * * @param expression Expression we want to interrogate. * @param meta {Metadata} Useful metadata that can be used during the transformation */ export const evaluateExpression = ( expression: t.Expression, meta: Metadata ): { value: t.Expression; meta: Metadata } => { let value: t.Node | undefined | null = undefined; let updatedMeta: Metadata = meta; // -------------- // NOTE: We are recursively calling evaluateExpression() which is then going to try and evaluate it // multiple times. This may or may not be a performance problem - when looking for quick wins perhaps // there is something we could do better here. // -------------- if (t.isIdentifier(expression)) { ({ value, meta: updatedMeta } = traverseIdentifier(expression, updatedMeta)); } else if (t.isMemberExpression(expression)) { ({ value, meta: updatedMeta } = traverseMemberExpression(expression, updatedMeta)); } else if (t.isFunction(expression)) { ({ value, meta: updatedMeta } = traverseFunction(expression, updatedMeta)); } else if (t.isCallExpression(expression)) { ({ value, meta: updatedMeta } = traverseCallExpression(expression, updatedMeta)); } if ( t.isStringLiteral(value) || t.isNumericLiteral(value) || t.isObjectExpression(value) || t.isTaggedTemplateExpression(value) || // TODO this should be more generic (value && isCompiledKeyframesCallExpression(value, updatedMeta)) ) { return createResultPair(value, updatedMeta); } if (value) { // If we fail to statically evaluate `value` we will return `expression` instead. // It's preferable to use the identifier than its result if it can't be statically evaluated. // E.g. say we got the result of an identifier `foo` as `bar()` -- its more preferable to return // `foo` instead of `bar()` for a single source of truth. const babelEvaluatedNode = babelEvaluateExpression(value, updatedMeta, expression); return createResultPair(babelEvaluatedNode, updatedMeta); } const babelEvaluatedNode = babelEvaluateExpression(expression, updatedMeta); return createResultPair(babelEvaluatedNode, updatedMeta); };
the_stack
import { Code, Function as LambdaFunction, Runtime } from '@aws-cdk/aws-lambda'; import { Aws, CfnResource, Construct, Duration, RemovalPolicy, Stack, Tags } from '@aws-cdk/core'; import { IBucket } from '@aws-cdk/aws-s3'; import { LogGroup, RetentionDays } from '@aws-cdk/aws-logs'; import { Effect, Policy, PolicyDocument, PolicyStatement, Role, ServicePrincipal } from '@aws-cdk/aws-iam'; import { AccessLogFormat, AuthorizationType, CfnAccount, ContentHandling, Deployment, EndpointType, Integration, IntegrationType, LogGroupLogDestination, MethodLoggingLevel, MethodOptions, PassthroughBehavior, RequestValidator, RestApi, Stage } from '@aws-cdk/aws-apigateway'; /** * @interface DLTAPIProps * DLTAPI props */ export interface DLTAPIProps { // ECS CloudWatch Log Group readonly ecsCloudWatchLogGroup: LogGroup; // CloudWatch Logs Policy readonly cloudWatchLogsPolicy: Policy; // DynamoDB policy readonly dynamoDbPolicy: Policy, //Task Canceler Invoke Policy readonly taskCancelerInvokePolicy: Policy; // Test scenarios S3 bucket readonly scenariosBucketName: string; // Test scenarios S3 bucket policy readonly scenariosS3Policy: Policy; // Test scenarios DynamoDB table readonly scenariosTableName: string; // ECS cluster readonly ecsCuster: string; // ECS Task Execution Role ARN readonly ecsTaskExecutionRoleArn: string; // Task Runner state function readonly taskRunnerStepFunctionsArn: string; // Task canceler ARN readonly tastCancelerArn: string; /** * Solution config properties. * the metric URL endpoint, send anonymous usage, solution ID, version, source code bucket, and source code prefix */ readonly metricsUrl: string; readonly sendAnonymousUsage: string; readonly solutionId: string; readonly solutionVersion: string; readonly sourceCodeBucket: IBucket; readonly sourceCodePrefix: string; // UUID readonly uuid: string; } /** * @class * Distributed Load Testing on AWS API construct */ export class DLTAPI extends Construct { apiId: string; apiEndpointPath: string; constructor(scope: Construct, id: string, props: DLTAPIProps) { super(scope, id); const taskArn = Stack.of(this).formatArn({ service: 'ecs', resource: 'task', sep: '/', resourceName: '*' }); const taskDefArn = Stack.of(this).formatArn({ service: 'ecs', resource: 'task-definition/' }); const dltApiServicesLambdaRole = new Role(this, 'DLTAPIServicesLambdaRole', { assumedBy: new ServicePrincipal('lambda.amazonaws.com'), inlinePolicies: { 'DLTAPIServicesLambdaPolicy': new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: ['ecs:ListTasks'], resources: ['*'] }), new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'ecs:RunTask', 'ecs:DescribeTasks' ], resources: [ taskArn, taskDefArn ] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['iam:PassRole'], resources: [props.ecsTaskExecutionRoleArn] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['states:StartExecution'], resources: [props.taskRunnerStepFunctionsArn] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['logs:DeleteMetricFilter'], resources: [props.ecsCloudWatchLogGroup.logGroupArn] }), new PolicyStatement({ effect: Effect.ALLOW, actions: ['cloudwatch:DeleteDashboards'], resources: [`arn:${Aws.PARTITION}:cloudwatch::${Aws.ACCOUNT_ID}:dashboard/EcsLoadTesting*`] }) ] }) } }); dltApiServicesLambdaRole.attachInlinePolicy(props.cloudWatchLogsPolicy); dltApiServicesLambdaRole.attachInlinePolicy(props.dynamoDbPolicy); dltApiServicesLambdaRole.attachInlinePolicy(props.scenariosS3Policy); dltApiServicesLambdaRole.attachInlinePolicy(props.taskCancelerInvokePolicy); const ruleSchedArn = Stack.of(this).formatArn({ service: 'events', resource: 'rule', resourceName: '*Scheduled' }); const ruleCreateArn = Stack.of(this).formatArn({ service: 'events', resource: 'rule', resourceName: '*Create' }); const ruleListArn = Stack.of(this).formatArn({ service: 'events', resource: 'rule', resourceName: '*' }); const lambdaApiEventsPolicy = new Policy(this, 'LambdaApiEventsPolicy', { statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'events:PutTargets', 'events:PutRule', 'events:DeleteRule', 'events:RemoveTargets' ], resources: [ ruleSchedArn, ruleCreateArn ] }), new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'events:ListRules' ], resources: [ ruleListArn ] }) ] }); dltApiServicesLambdaRole.attachInlinePolicy(lambdaApiEventsPolicy); const apiLambdaRoleResource = dltApiServicesLambdaRole.node.defaultChild as CfnResource; apiLambdaRoleResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W11', reason: 'ecs:ListTasks does not support resource level permissions' }] }); const dltApiServicesLambda = new LambdaFunction(this, 'DLTAPIServicesLambda', { description: 'API microservices for creating, updating, listing and deleting test scenarios', code: Code.fromBucket(props.sourceCodeBucket, `${props.sourceCodePrefix}/api-services.zip`), runtime: Runtime.NODEJS_14_X, handler: 'index.handler', timeout: Duration.seconds(120), environment: { SCENARIOS_BUCKET: props.scenariosBucketName, SCENARIOS_TABLE: props.scenariosTableName, TASK_CLUSTER: props.ecsCuster, STATE_MACHINE_ARN: props.taskRunnerStepFunctionsArn, SOLUTION_ID: props.solutionId, UUID: props.uuid, VERSION: props.solutionVersion, SEND_METRIC: props.sendAnonymousUsage, METRIC_URL: props.metricsUrl, ECS_LOG_GROUP: props.ecsCloudWatchLogGroup.logGroupName, TASK_CANCELER_ARN: props.tastCancelerArn }, role: dltApiServicesLambdaRole }); Tags.of(dltApiServicesLambda).add('SolutionId', props.solutionId); const apiLambdaResource = dltApiServicesLambda.node.defaultChild as CfnResource; apiLambdaResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W58', reason: 'CloudWatchLogsPolicy covers a permission to write CloudWatch logs.' }, { id: 'W89', reason: 'VPC not needed for lambda' }, { id: 'W92', reason: 'Does not run concurrent executions' }] }); const lambdaApiPermissionPolicy = new Policy(this, 'LambdaApiPermissionPolicy', { statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'lambda:AddPermission', 'lambda:RemovePermission' ], resources: [dltApiServicesLambda.functionArn] }) ] }); dltApiServicesLambdaRole.attachInlinePolicy(lambdaApiPermissionPolicy); const apiLogs = new LogGroup(this, 'APILogs', { retention: RetentionDays.ONE_YEAR, removalPolicy: RemovalPolicy.RETAIN }); const apiLogsResource = apiLogs.node.defaultChild as CfnResource; apiLogsResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W84', reason: 'KMS encryption unnecessary for log group' }] }); const logsArn = Stack.of(this).formatArn({ service: 'logs', resource: '*' }) const apiLoggingRole = new Role(this, 'APILoggingRole', { assumedBy: new ServicePrincipal('apigateway.amazonaws.com'), inlinePolicies: { 'apiLoggingPolicy': new PolicyDocument({ statements: [ new PolicyStatement({ effect: Effect.ALLOW, actions: [ 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogGroups', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 'logs:FilterLogEvent', ], resources: [ logsArn ] }) ] }) } }); const api = new RestApi(this, 'DLTApi', { defaultCorsPreflightOptions: { allowOrigins: ['*'], allowHeaders: [ 'Authorization', 'Content-Type', 'X-Amz-Date', 'X-Amz-Security-Token', 'X-Api-Key' ], allowMethods: [ 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PATCH', 'POST', 'PUT' ], statusCode: 200 }, deploy: true, deployOptions: { accessLogDestination: new LogGroupLogDestination(apiLogs), accessLogFormat: AccessLogFormat.jsonWithStandardFields(), loggingLevel: MethodLoggingLevel.INFO, stageName: 'prod', tracingEnabled: true }, description: `Distributed Load Testing API - version ${props.solutionVersion}`, endpointTypes: [EndpointType.EDGE] }); this.apiId = api.restApiId; this.apiEndpointPath = api.url.slice(0, -1); const apiAccountConfig = new CfnAccount(this, 'ApiAccountConfig', { cloudWatchRoleArn: apiLoggingRole.roleArn }); apiAccountConfig.addDependsOn(api.node.defaultChild as CfnResource); const apiAllRequestValidator = new RequestValidator(this, 'APIAllRequestValidator', { restApi: api, validateRequestBody: true, validateRequestParameters: true }); const apiDeployment = api.node.findChild('Deployment') as Deployment; const apiDeploymentResource = apiDeployment.node.defaultChild as CfnResource; apiDeploymentResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W68', reason: 'The solution does not require the usage plan.' }] }); const apiFindProdResource = api.node.findChild('DeploymentStage.prod') as Stage; const apiProdResource = apiFindProdResource.node.defaultChild as CfnResource; apiProdResource.addMetadata('cfn_nag', { rules_to_suppress: [{ id: 'W64', reason: 'The solution does not require the usage plan.' }] }); const allIntegration = new Integration({ type: IntegrationType.AWS_PROXY, integrationHttpMethod: 'POST', options: { contentHandling: ContentHandling.CONVERT_TO_TEXT, integrationResponses: [{ statusCode: '200' }], passthroughBehavior: PassthroughBehavior.WHEN_NO_MATCH, }, uri: `arn:${Aws.PARTITION}:apigateway:${Aws.REGION}:lambda:path/2015-03-31/functions/${dltApiServicesLambda.functionArn}/invocations` }); const allMethodOptions: MethodOptions = { authorizationType: AuthorizationType.IAM, methodResponses: [{ statusCode: '200', responseModels: { 'application/json': { modelId: 'Empty' } } }], requestValidator: apiAllRequestValidator }; /** Test scenario API * /scenarios * /scenarios/{testId} * /tasks */ const scenariosResource = api.root.addResource('scenarios'); scenariosResource.addMethod('ANY', allIntegration, allMethodOptions); const testIds = scenariosResource.addResource('{testId}'); testIds.addMethod('ANY', allIntegration, allMethodOptions); const tasksResource = api.root.addResource('tasks'); tasksResource.addMethod('ANY', allIntegration, allMethodOptions); const invokeSourceArn = Stack.of(this).formatArn({ service: 'execute-api', resource: api.restApiId, resourceName: '*' }); dltApiServicesLambda.addPermission('DLTApiInvokePermission', { action: 'lambda:InvokeFunction', principal: new ServicePrincipal('apigateway.amazonaws.com'), sourceArn: invokeSourceArn }); } }
the_stack
import { ItemsList } from './items-list'; import { PickPaneComponent } from './pick-pane.component'; import { DefaultSelectionModel } from './selection-model'; import { PickPaneDragService } from './pick-pane-drag.service'; import { PicklistService } from '../picklist.service'; import { PickOption } from '../pick.types'; import { ChangeDetectorRef, ElementRef } from '@angular/core'; let list: ItemsList; let cmp: PickPaneComponent; describe('ItemsList', () => { describe('select', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('should add item to selected items', () => { list.select(new PickOption({ value: 'val' })); expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0].value).toBe('val'); list.select(new PickOption({ value: 'val2' })); expect(list.selectedItems.length).toBe(2); expect(list.selectedItems[1].value).toBe('val2'); }); it('should skip when item already selected', () => { list.select(new PickOption({ selected: true })); expect(list.selectedItems.length).toBe(0); }); it('should select all items in group when group is selected', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' } ]); list.select(list.items[0]); // G1 expect(list.selectedItems.length).toBe(2); expect(list.selectedItems[0]).toBe(list.items[1]); }); it('should be able to select items from different groups', () => { cmp.groupBy = 'groupKey'; list.setItems([ // G1 { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' }, // G2 { label: 'K3', val: 'V3', groupKey: 'G2' }, { label: 'K4', val: 'V4', groupKey: 'G2' } ]); list.select(list.items[1]); // K1 list.select(list.items[4]); // K3 expect(list.selectedItems.length).toBe(2); }); it('should not select disabled items when selecting group', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1', disabled: true } ]); list.select(list.items[0]); // G1 expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0].label).toBe('K1'); }); it('should mark group selected when all child items are selected', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' } ]); list.select(list.items[1]); // K1 list.select(list.items[2]); // K2 expect(list.selectedItems.length).toBe(2); // only children included in selectedItems array expect(list.items[0].label).toBe('G1'); expect(list.items[0].selected).toBeTruthy(); }); }); describe('unselect', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('should unselect selected items', () => { list.setItems([ { label: 'K1', val: 'V1' }, { label: 'K2', val: 'V2' }, ]); list.select(list.items[0]); list.select(list.items[1]); list.unselect(list.items[0]); list.unselect(list.items[1]); expect(list.selectedItems.length).toBe(0); }); it('should unselect grouped selected item', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' }, ]); list.select(list.items[1]); // K1 list.select(list.items[2]); // K2 list.unselect(list.items[1]); expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0]).toBe(list.items[2]); }); it('should unselect grouped selected item after group was selected', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' }, ]); list.select(list.items[0]); // G1 list.unselect(list.items[1]); // K1 expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0].label).toBe(list.items[2].label); // only K2 should be selected }); it('should not unselect disabled items within a group', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1', disabled: true }, { label: 'K3', val: 'V3', groupKey: 'G2' }, { label: 'K4', val: 'V4', groupKey: 'G2', disabled: true }, ]); const item = list.findByLabel('K2'); if (item) { list.selectedItems.push(item); } expect(list.selectedItems.length).toBe(1); const item2 = list.findByLabel('G1'); if (item2) { list.unselect(item2); } expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0].label).toBe('K2'); }); it('should not affect disabled items when unselecting a group', () => { cmp.groupBy = 'groupKey'; list.setItems([ { label: 'K1', val: 'V1', groupKey: 'G1' }, { label: 'K2', val: 'V2', groupKey: 'G1' }, { label: 'K3', val: 'V3', groupKey: 'G1', disabled: true }, ]); list.select(list.items[0]); // G1 list.unselect(list.items[1]); // K1 expect(list.selectedItems.length).toBe(1); expect(list.selectedItems[0].label).toBe('K2'); }); }); describe('filter', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('should find item from items list and update counts', () => { list.setItems([ { label: 'K1 part1 part2', val: 'V1' }, { label: 'K2 part1 part2', val: 'V2' }, { label: 'K3 part1 part2.2', val: 'V3' }, { label: 'K4 part1 part2.2', val: 'V4' }, { label: 'K5 part1 part2.2 part3', val: 'V5' }, ]); list.filter('part1'); expect(list.filteredItems.length).toBe(6); // +1 for default group expect(list.itemsShownCountStr).toBe('5'); // excludes groups expect(list.itemsTotalCountStr).toBe('5'); // excludes groups list.filter('part2.2'); expect(list.filteredItems.length).toBe(4); // +1 for default group expect(list.itemsShownCountStr).toBe('3'); expect(list.itemsTotalCountStr).toBe('5'); list.filter('part3'); expect(list.filteredItems.length).toBe(2); // +1 for default group expect(list.itemsShownCountStr).toBe('1'); expect(list.itemsTotalCountStr).toBe('5'); list.filter('nope'); expect(list.filteredItems.length).toBe(0); expect(list.itemsShownCountStr).toBe('0'); expect(list.itemsTotalCountStr).toBe('5'); }); it('should find item from grouped items list', () => { cmp.groupBy = 'groupKey'; list.setItems([ // G1 group { label: 'K1 part1 part2', val: 'V1', groupKey: 'G1' }, { label: 'K2 part1 part2', val: 'V2', groupKey: 'G1' }, // G2 group { label: 'K3 part1 part2.2', val: 'V3', groupKey: 'G2' }, { label: 'K4 part1 part2.2', val: 'V4', groupKey: 'G2' }, { label: 'K5 part1 part2.2 part3', val: 'V5', groupKey: 'G2' }, ]); list.filter('part1'); expect(list.filteredItems.length).toBe(7); // 5 items + 2 groups list.filter('part2.2'); expect(list.filteredItems.length).toBe(4); // 3 item + 1 group list.filter('part3'); expect(list.filteredItems.length).toBe(2); // 1 item + 1 group list.filter('nope'); expect(list.filteredItems.length).toBe(0); }); }); describe('markSelectedOrDefault', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(30)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('should mark first item', () => { list.markSelectedOrDefault(); expect(list.markedIndex).toBe(1); // index 0 is a group, so index 1 should be first selected }); it('should keep marked item if it is above last selected item', () => { list.select(list.items[10]); list.markSelectedOrDefault(); expect(list.markedIndex).toBe(10); list.markNextItem(true); list.markNextItem(true); list.markNextItem(true); list.markSelectedOrDefault(); expect(list.markedIndex).toBe(13); }); it('should mark first after previous marked item was filtered out', () => { list.markSelectedOrDefault(); list.markNextItem(true); list.filter('item-0'); list.markSelectedOrDefault(); expect(list.markedIndex).toBe(1); // index 0 is a group, so index 1 should be first selected list.markNextItem(true); expect(list.markedIndex).toBe(1); // index still 1, because there only 1 items available to be marked }); }); describe('unmark', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(30)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('should reset the markedIndex property', () => { list.markItem(list.items[5]); list.unmark(); expect(list.markedIndex).toBe(-1); }); }); describe('markItem', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(30)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('should set the markedIndex property according to the position of the item in the filtered list', () => { list.markItem(list.items[5]); expect(list.markedIndex).toBe(5); }); it('should set the markedIndex property to -1 if the given item is not in the list', () => { list.markItem(new PickOption({})); expect(list.markedIndex).toBe(-1); }); }); describe('markFirst', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(30)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('unmarks what ever is currently marked and then marks the first selectable item', () => { list.markItem(list.items[5]); list.markFirst(); expect(list.markedIndex).toBe(1); // groups are disabled by default, index 0 is a group }); }); describe('findOption', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(30)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('uses a given compareWith function to find a match', () => { cmp.compareWith = (a, b) => { return a === b.value; }; const result = list.findOption(list.items[3]); expect(result?.value).toBe(list.items[3].value); }); it('uses a given bindValue to find a match (if no compareWith func was given)', () => { cmp.bindValue = 'value'; const result = list.findOption(list.items[3].value); expect(result?.value).toBe(list.items[3].value); }); it('uses a given bindLabel to find a match (if no compareWith func or bindValue was given)', () => { cmp.bindValue = ""; cmp.bindLabel = 'label'; const result = list.findOption(list.items[3].value); expect(result?.value).toBe(list.items[3].value); }); }); describe('addOption', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(10)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('throws error if given an option without a parent', () => { const optionNoParent = new PickOption({ name: 'no parent', parent: undefined}); expect(() => { list.addOption(optionNoParent); }) .toThrow(new Error(`Trying to add an option that does not have a parent: ${optionNoParent}`)); }); it('adds option whose parent already exisits in the list', () => { const hasExistingParent = new PickOption({ name: 'default parent', parent: list.items[0]}); expect(list.items.length).toBe(11); list.addOption(hasExistingParent); expect(list.items.length).toBe(12); expect(list.items[0].children?.length).toBe(11); expect(list.items[0].children?.[10].name).toBe(hasExistingParent.name); }); it('adds option whose parent does not already exisits in the list', () => { const newParentOpt = new PickOption({name: 'new parent', children: []}); const optionWithNewParent = new PickOption({ name: 'has new parent', parent: newParentOpt}); newParentOpt.children?.push(optionWithNewParent); expect(list.items.length).toBe(11); list.addOption(optionWithNewParent); expect(list.items.length).toBe(13); expect(list.items[11].children?.length).toBe(1); expect(list.items[11].children?.[0].name).toBe(optionWithNewParent.name); }); }); describe('removeOption', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); const items = Array.from(Array(10)).map((_, index) => (`item-${index}`)); list.setItems(items); }); it('throws error if given an option without a parent', () => { const optionNoParent = new PickOption({ name: 'no parent', parent: undefined}); expect(() => { list.removeOption(optionNoParent); }) .toThrow(new Error(`Trying to remove an option that does not have a parent: ${optionNoParent}`)); }); it('removes a given option from items list', () => { const existingOption = list.items[1]; expect(list.items.length).toBe(11); list.removeOption(existingOption); expect(list.items.length).toBe(10); }); it('removes a given option and its parent group if it was the last option in that group', () => { list.clearList(); list.setItems([new PickOption({name: 'only option'})]); const onlyOption = list.items[1]; expect(list.items.length).toBe(2); // the only option and its parent list.removeOption(onlyOption); expect(list.items.length).toBe(0); }); }); describe('clearSelected', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('should empty selected items list', () => { list.setItems([new PickOption({name: 'only option'})]); const onlyOption = list.items[1]; list.select(onlyOption); expect(list.selectedItems.length).toBe(1); expect(onlyOption.selected).toBeTruthy(); list.clearSelected(); expect(list.selectedItems.length).toBe(0); expect(onlyOption.selected).toBeFalsy(); }); it('if nothing was selected when called, selectedItems property should still be empty', () => { list.setItems([45, 56, 67]); expect(list.selectedItems.length).toBe(0); list.clearSelected(); expect(list.selectedItems.length).toBe(0); }); }); describe('selectAll', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('selects all items in the list', () => { list.setItems(['one', 'two', 'three']); list.selectAll(); expect(list.selectedItems.length).toBe(3); list.selectedItems.forEach(i => { expect(i.selected).toBeTruthy(); }); }); it('marks all items as selected, including groups, if canSelectGroup is true', () => { cmp.canSelectGroup = true; list.setItems(['one', 'two', 'three']); list.selectAll(); expect(list.selectedItems.length).toBe(3); // only child items actually get placed in selectedItems array list.items.forEach(i => { expect(i.selected).toBeTruthy(); }); }); it('selects all items in the list except disabled items', () => { list.setItems(['one', 'two', 'three']); list.items[1].disabled = true; list.selectAll(); expect(list.selectedItems.length).toBe(2); expect(list.items[1].selected).toBeFalsy(); }); }); describe('resolveNested', () => { beforeEach(() => { cmp = ngSelectFactory(); list = itemsListFactory(cmp); }); it('can pluck given property value from an object', () => { const testObj = { test: 1 }; expect(list.resolveNested(testObj, 'test')).toBe(1); }); it('can pluck given nested property value from an object', () => { const testObj = { test: 1, nestTest: { test2: 2 }}; expect(list.resolveNested(testObj, 'nestTest.test2')).toBe(2); }); it('can pluck given deeply nested property value from an object', () => { const testObj = { test: 1, nestTest: { test2: 2, deepNest: { deeperNest: { deepestNest: 3 }}}}; expect(list.resolveNested(testObj, 'nestTest.deepNest.deeperNest.deepestNest')).toBe(3); }); }); describe('createHcOption', () => { beforeEach(() => { cmp = ngSelectFactory(); cmp.bindLabel = 'label'; list = itemsListFactory(cmp); }); it('converts raw primitive value into an option', () => { const result = list._createHcOption(3); expect(result.value).toBe(3); }); it('converts raw object value into an option', () => { const result = list._createHcOption({ countVal: 3 }); expect((result.value as Record<string, unknown>)['countVal']).toBe(3); }); it('use given index', () => { const result = list._createHcOption(3, 2); expect(result.index).toBe(2); }); it('use bindLabel from pane component to set label property', () => { cmp.bindLabel = 'myLabel'; const expectedLabelVal = 'i am the label'; const result = list._createHcOption({value: 4, myLabel: expectedLabelVal}); expect(result.label).toBe(expectedLabelVal); }); it('uses $hcOptionLabel and $hcOptionValue if they exist', () => { // for the <hc-pick-option> use case const expectedLabelVal = 'i am the label'; const result = list._createHcOption({ $hcOptionLabel: expectedLabelVal, $hcOptionValue: 7 }); expect(result.value).toBe(7); expect(result.label).toBe(expectedLabelVal); }); }); function itemsListFactory(pickCmp: PickPaneComponent): ItemsList { return new ItemsList(pickCmp, new DefaultSelectionModel()); } function ngSelectFactory(): PickPaneComponent { return new PickPaneComponent( () => new DefaultSelectionModel(), new ElementRef<HTMLElement>(document.createElement('div')), new PicklistService, (null as unknown) as ChangeDetectorRef, new PickPaneDragService()); } });
the_stack
import {t} from '@lingui/macro' import {Trans} from '@lingui/react' import {DataLink, ActionLink} from 'components/ui/DbLink' import NormalisedMessage from 'components/ui/NormalisedMessage' import styles from 'components/ui/Procs/ProcOverlay.module.css' import {Event, Events} from 'event' import {Analyser} from 'parser/core/Analyser' import {filter} from 'parser/core/filter' import {dependency} from 'parser/core/Injectable' import {Actors} from 'parser/core/modules/Actors' import Checklist, {Rule, Requirement} from 'parser/core/modules/Checklist' import {Data} from 'parser/core/modules/Data' import {Invulnerability} from 'parser/core/modules/Invulnerability' import {Statuses} from 'parser/core/modules/Statuses' import Suggestions, {Suggestion, SEVERITY} from 'parser/core/modules/Suggestions' import React, {ReactNode} from 'react' import {Accordion, Table, Message} from 'semantic-ui-react' import DISPLAY_ORDER from './DISPLAY_ORDER' import Procs from './Procs' const MAX_ALLOWED_BAD_GCD_THRESHOLD = 2000 const MAX_ALLOWED_T3_CLIPPING = 3000 interface ThunderApplicationData { event: Events['statusApply'], clip?: number, source: number, proc: boolean } interface ThunderStatusData { lastApplication: number, applications: ThunderApplicationData[] } interface ThunderTargetData { [key: number]: ThunderStatusData, } interface ThunderApplicationTracker { [key: string]: ThunderTargetData, } export class Thunder extends Analyser { static override handle = 'thunder' static override title = t('blm.thunder.title')`Thunder` static override displayOrder = DISPLAY_ORDER.THUNDER @dependency private actors!: Actors @dependency private checklist!: Checklist @dependency private data!: Data @dependency private invulnerability!: Invulnerability @dependency private procs!: Procs @dependency private statuses!: Statuses @dependency private suggestions!: Suggestions // Can never be too careful :blobsweat: private readonly STATUS_DURATION = { [this.data.statuses.THUNDER_III.id]: this.data.statuses.THUNDER_III.duration, [this.data.statuses.THUNDERCLOUD.id]: this.data.statuses.THUNDERCLOUD.duration, } private thunder3Casts = 0 private lastThunderProc: boolean = false private lastThunderCast: number = this.data.statuses.THUNDER_III.id private clip: {[key: number]: number} = { [this.data.statuses.THUNDER_III.id]: 0, } private tracker: ThunderApplicationTracker = {} override initialise() { const playerFilter = filter<Event>().source(this.parser.actor.id) this.addEventHook(playerFilter.type('action').action(this.data.actions.THUNDER_III.id), this.onDotCast) this.addEventHook(playerFilter.type('statusApply').status(this.data.statuses.THUNDER_III.id), this.onDotApply) this.addEventHook('complete', this.onComplete) } private createTargetApplicationList() { return { [this.data.statuses.THUNDER_III.id]: [], } } private pushApplication(targetKey: string, statusId: number, event: Events['statusApply'], clip?: number) { const target = this.tracker[targetKey] = this.tracker[targetKey] || this.createTargetApplicationList() const proc = this.lastThunderProc const source = this.lastThunderCast target[statusId].applications.push({event, clip, source, proc}) this.lastThunderProc = false } private onDotCast(event: Events['action']) { this.thunder3Casts++ if (this.procs.checkEventWasProc(event)) { this.lastThunderProc = true } this.lastThunderCast = event.action } private onDotApply(event: Events['statusApply']) { const statusId = event.status // Make sure we're tracking for this target const applicationKey = event.target const trackerInstance = this.tracker[applicationKey] = this.tracker[applicationKey] || {} // If it's not been applied yet, set it and skip out if (!trackerInstance[statusId]) { trackerInstance[statusId] = { lastApplication: event.timestamp, applications: [], } //save the application for later use in the output this.pushApplication(applicationKey, statusId, event) return } // Base clip calc let clip = this.STATUS_DURATION[statusId] - (event.timestamp - trackerInstance[statusId].lastApplication) clip = Math.max(0, clip) // Capping clip at 0 - less than that is downtime, which is handled by the checklist requirement this.clip[statusId] += clip //save the application for later use in the output this.pushApplication(applicationKey, statusId, event, clip) trackerInstance[statusId].lastApplication = event.timestamp } // Get the uptime percentage for the Thunder status debuff private getThunderUptime() { const statusTime = this.statuses.getUptime(this.data.statuses.THUNDER_III, this.actors.foes) const uptime = this.parser.currentDuration - this.invulnerability.getDuration({types: ['invulnerable']}) return (statusTime / uptime) * 100 } private onComplete() { // Checklist item for keeping Thunder 3 DoT rolling this.checklist.add(new Rule({ name: <Trans id="blm.thunder.checklist.dots.name">Keep your <DataLink status="THUNDER_III" /> DoT up</Trans>, description: <Trans id="blm.thunder.checklist.dots.description"> Your <DataLink status="THUNDER_III" /> DoT contributes significantly to your overall damage, both on its own, and from additional <DataLink status="THUNDERCLOUD" /> procs. Try to keep the DoT applied. </Trans>, target: 95, requirements: [ new Requirement({ name: <Trans id="blm.thunder.checklist.dots.requirement.name"><DataLink status="THUNDER_III" /> uptime</Trans>, percent: () => this.getThunderUptime(), }), ], })) // Suggestions to not spam T3 too much const sumClip = this.clip[this.data.statuses.THUNDER_III.id] const maxExpectedClip = (this.thunder3Casts - 1) * MAX_ALLOWED_T3_CLIPPING if (sumClip > maxExpectedClip) { this.suggestions.add(new Suggestion({ icon: this.data.actions.THUNDER_III.icon, content: <Trans id="blm.thunder.suggestions.excess-thunder.content"> Casting <DataLink action="THUNDER_III" /> too frequently can cause you to lose DPS by casting fewer <DataLink action="FIRE_IV" />. Try not to cast <DataLink showIcon={false} action="THUNDER_III" /> unless your <DataLink status="THUNDER_III" /> DoT or <DataLink status="THUNDERCLOUD" /> proc are about to wear off. Check the <a href="#" onClick={e => { e.preventDefault(); this.parser.scrollTo(Thunder.handle) }}><NormalisedMessage message={Thunder.title}/></a> module for more information. </Trans>, severity: sumClip > 2 * maxExpectedClip ? SEVERITY.MAJOR : SEVERITY.MEDIUM, why: <Trans id="blm.thunder.suggestions.excess-thunder.why"> Total DoT clipping exceeded the maximum clip time of {this.parser.formatDuration(maxExpectedClip)} by {this.parser.formatDuration(sumClip-maxExpectedClip)}. </Trans>, })) } } private createTargetStatusTable(target: ThunderTargetData) { let totalThunderClip = 0 return <Table collapsing unstackable> <Table.Header> <Table.Row> <Table.HeaderCell><DataLink action="THUNDER_III" /> <Trans id="blm.thunder.applied">Applied</Trans></Table.HeaderCell> <Table.HeaderCell><Trans id="blm.thunder.clip">Clip</Trans></Table.HeaderCell> <Table.HeaderCell><Trans id="blm.thunder.total-clip">Total Clip</Trans></Table.HeaderCell> <Table.HeaderCell><Trans id="blm.thunder.source">Source</Trans></Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {target[this.data.statuses.THUNDER_III.id].applications.map( (event) => { const thisClip = event.clip || 0 totalThunderClip += thisClip const action = this.data.getAction(event.source) let icon = <ActionLink showName={false} {...action} /> //if we have a clip, overlay the proc.png over the actionlink image if (event.proc) { icon = <div className={styles.procOverlay}><ActionLink showName={false} {...action} /></div> } const renderClipTime = event.clip != null ? this.parser.formatDuration(event.clip) : '-' let clipSeverity: ReactNode = renderClipTime // Make it white for expected clipping, yellow if the GCD aligned poorly, and red if it was definitely clipped too hard if (thisClip > MAX_ALLOWED_T3_CLIPPING && thisClip <= MAX_ALLOWED_T3_CLIPPING + MAX_ALLOWED_BAD_GCD_THRESHOLD) { clipSeverity = <span className="text-warning">{clipSeverity}</span> } if (thisClip > MAX_ALLOWED_T3_CLIPPING + MAX_ALLOWED_BAD_GCD_THRESHOLD) { clipSeverity = <span className="text-error">{clipSeverity}</span> } return <Table.Row key={event.event.timestamp}> <Table.Cell>{this.parser.formatEpochTimestamp(event.event.timestamp)}</Table.Cell> <Table.Cell>{clipSeverity}</Table.Cell> <Table.Cell>{totalThunderClip ? this.parser.formatDuration(totalThunderClip) : '-'}</Table.Cell> <Table.Cell style={{textAlign: 'center'}}>{icon}</Table.Cell> </Table.Row> })} </Table.Body> </Table> } override output() { const numTargets = Object.keys(this.tracker).length const disclaimer = <Message> <Trans id="blm.thunder.clip-disclaimer"> Due to the nature of <DataLink action="THUNDER_III" /> procs, you will run into situations where you will use your <DataLink status="THUNDERCLOUD" /> proc before it runs out, while your <DataLink status="THUNDER_III" /> is still running on your enemy. At most, this could theoretically lead to refreshing <DataLink showIcon={false} status="THUNDER_III" /> a maximum of ~3 seconds early every single refresh. Since this amount of clipping is still considered optimal, we quantify and call this the maximum clip time. </Trans> </Message> if (numTargets === 0) { return null } if (numTargets > 1) { const panels = Object.keys(this.tracker).map(applicationKey => { const target = this.actors.get(applicationKey) return { key: applicationKey, title: { content: <>{target.name}</>, }, content: { content: this.createTargetStatusTable(this.tracker[applicationKey]), }, } }) return <> {disclaimer} <Accordion exclusive={false} panels={panels} styled fluid /> </> } return <> {disclaimer} {this.createTargetStatusTable(Object.values(this.tracker)[0])} </> } }
the_stack
import { Visitor, NodePath } from '@babel/traverse'; import * as types from '@babel/types'; import { SFC_FUNC, SFC_COMPONENT, SFC_RENDER, getOptionsName, getSfcName, SFC_CREATE_OPTIONS, SFC_FORWARD_REF } from './utils'; import * as astUtils from './utils/ast'; import * as utils from './utils'; // import generate from '@babel/generator'; export interface State { opts?: { importedLib?: string[]; }; customImportName?: types.Identifier; } export default () => ({ name: 'babel-plugin-jsx-sfc', visitor: { Program(_path, state: State) { _path.traverse({ /* const App = sfc({ Component: (props) => { ... }, static: () => ({ utils: { ... } }), render({ data }) { ... }, styles: () => { ... } }); ↓ ↓ ↓ ↓ ↓ ↓ const $sfcOptions_lineNo = sfc.createOptions({ static: () => ({ utils: { ... } }), render({ data }) { ... }, styles: () => ({ ... }) }); const Sfc_lineNo = (props) => { ... return $sfcOptions_lineNo.render({ ... }); }; const App = sfc(Sfc_lineNo, $sfcOptions_lineNo); */ CallExpression: { enter(path) { const { callee } = path.node; const importedLib = state?.opts?.importedLib; /** * 0: nothing * 1: const App = sfc()({ ... }) * 2: const App = sfc({ ... }) * 3: const App = sfc.forwardRef()({ ... }) * 4: const App = sfc.forwardRef({ ... }) */ let sfcType: 0 | 1 | 2 | 3 | 4 = 0; if ( types.isCallExpression(callee) && astUtils.isCalleeImportedBySfc(callee.callee, path, importedLib, state?.customImportName) ) { if ( types.isMemberExpression(callee.callee) && types.isIdentifier(callee.callee.property) && callee.callee.property.name === SFC_FORWARD_REF ) { sfcType = 3; } else { sfcType = 1; } } else if (astUtils.isCalleeImportedBySfc(callee, path, importedLib, state?.customImportName)) { if ( types.isMemberExpression(callee) && types.isIdentifier(callee.property) && callee.property.name === SFC_FORWARD_REF ) { sfcType = 4; } else { sfcType = 2; } } if (sfcType) { const sfcArguments = path.node.arguments as types.ObjectExpression[]; if (types.isObjectExpression(sfcArguments?.[0])) { const componentProp = sfcArguments[0].properties.find( prop => types.isObjectProperty(prop) && types.isIdentifier(prop.key) && prop.key.name === SFC_COMPONENT ) as types.ObjectProperty; const componentMethod = sfcArguments[0].properties.find( prop => types.isObjectMethod(prop) && types.isIdentifier(prop.key) && prop.key.name === SFC_COMPONENT ) as types.ObjectMethod; if (!componentProp && !componentMethod) { return; } const indexInProps = sfcArguments[0].properties.indexOf( componentProp ? componentProp : componentMethod ); const lineNo = path?.node?.loc?.start.line; const sfcOptionsName = getOptionsName(lineNo); /* Component: props => { return { firstName: 'joe' }; } ↓ ↓ ↓ ↓ ↓ ↓ Component: props => { return $sfcOptions_lineNo.render({ firstName: 'joe' }); } */ let componentFuncPath: NodePath<types.ArrowFunctionExpression> | NodePath<types.ObjectMethod>; if (componentProp) { componentFuncPath = path.get(`arguments.0.properties.${indexInProps}.value`) as NodePath< types.ArrowFunctionExpression >; } else { componentFuncPath = path.get(`arguments.0.properties.${indexInProps}`) as NodePath< types.ObjectMethod >; } const funcBlockPath = componentFuncPath.get('body') as NodePath<types.BlockStatement>; const firstPropParamPath = componentFuncPath.get('params.0') as NodePath< types.Identifier | types.ObjectPattern >; let propsName = '__props'; if (firstPropParamPath) { if (types.isObjectPattern(firstPropParamPath.node)) { // const { styles, props } = { ...__props, ...$sfcOptions_lineNo, props: __props, originalProps(deprecated): __props }; funcBlockPath.unshiftContainer( 'body', types.variableDeclaration('const', [ types.variableDeclarator( firstPropParamPath.node, types.objectExpression([ types.spreadElement(types.identifier(propsName)), types.spreadElement(types.identifier(sfcOptionsName)), types.objectProperty(types.identifier('props'), types.identifier(propsName)), types.objectProperty(types.identifier('originalProps'), types.identifier(propsName)) ]) ) ]) ); firstPropParamPath.replaceWith(types.identifier(propsName)); } else { // props = { ...props, ...$sfcOptions_lineNo }; propsName = (firstPropParamPath.node as types.Identifier).name; funcBlockPath.unshiftContainer( 'body', types.expressionStatement( types.assignmentExpression( '=', types.identifier(propsName), types.objectExpression([ types.spreadElement(types.identifier(propsName)), types.spreadElement(types.identifier(sfcOptionsName)) ]) ) ) ); } } else { if (types.isObjectMethod(componentFuncPath.node)) { componentFuncPath.replaceWith( types.objectMethod( 'method', types.identifier(SFC_COMPONENT), [types.identifier(propsName)], funcBlockPath.node ) ); } else { componentFuncPath.replaceWith( types.arrowFunctionExpression([types.identifier(propsName)], funcBlockPath.node) ); } } const returnArgPath = componentFuncPath.get('body.body').find(p => p.isReturnStatement()) as NodePath< types.ReturnStatement >; // return $sfcOptions_lineNo.render({ ... }); let existProps: types.ObjectProperty | null = null; if (types.isObjectExpression(returnArgPath.node.argument)) { returnArgPath.replaceWith( types.returnStatement( types.callExpression( types.memberExpression(types.identifier(sfcOptionsName), types.identifier(SFC_RENDER)), [ types.objectExpression([ ...returnArgPath.node.argument.properties.filter(property => { if ( types.isObjectProperty(property) && types.isIdentifier(property.key) && property.key.name === 'props' ) { existProps = property; return false; } return true; }), existProps || types.objectProperty(types.identifier('props'), types.identifier(propsName)) ]) ] ) ) ); } sfcArguments[0].properties.splice(indexInProps, 1); // const $sfcOptions_lineNo = ... const componentVariable = path.findParent( path => path.isVariableDeclaration() || path.isExportDefaultDeclaration() ); const importName = state?.customImportName?.name || SFC_FUNC; const sfcOptionsPath = componentVariable?.insertBefore( types.variableDeclaration('const', [ types.variableDeclarator( types.identifier(sfcOptionsName), types.callExpression( types.memberExpression(types.identifier(importName), types.identifier(SFC_CREATE_OPTIONS)), sfcArguments ) ) ]) ); let actualComponentFunc: types.ArrowFunctionExpression; if (types.isArrowFunctionExpression(componentFuncPath.node)) { actualComponentFunc = componentFuncPath.node; } else { actualComponentFunc = types.arrowFunctionExpression( componentFuncPath.node.params, componentFuncPath.node.body ); } if (sfcType <= 2) { const sfcName = getSfcName(lineNo); componentVariable?.insertBefore( types.variableDeclaration('const', [ types.variableDeclarator(types.identifier(sfcName), actualComponentFunc) ]) ); if (types.isVariableDeclaration(componentVariable?.node)) { const declarationId = componentVariable?.node.declarations?.[0]?.id; if (types.isIdentifier(declarationId)) { const componentName = declarationId.name; componentVariable?.insertBefore( types.expressionStatement( types.assignmentExpression( '=', types.memberExpression(types.identifier(sfcName), types.identifier('displayName')), types.stringLiteral(componentName) ) ) ); } } path.replaceWith( types.callExpression(types.identifier(importName), [ types.identifier(sfcName), types.identifier(sfcOptionsName) ]) ); } else { path.replaceWith( types.callExpression( types.memberExpression(types.identifier(importName), types.identifier(SFC_FORWARD_REF)), [actualComponentFunc, types.identifier(sfcOptionsName)] ) ); } /* You can use @babel/generator here when debugging */ // console.log(generate(path.node).code); // console.log(generate(sfcOptionsPath[0].node).code); } } } } }); } } as Visitor }); export { astUtils, utils };
the_stack
import * as d3 from "d3"; import { AppState } from "../AppState"; import * as J from "../JavaIntf"; import { PubSub } from "../PubSub"; import { Singletons } from "../Singletons"; import { Div } from "./Div"; import { Main } from "./Main"; import { Constants as C } from "../Constants"; // https://observablehq.com/@d3/force-directed-tree // https://www.npmjs.com/package/d3 // https://d3js.org/ let S: Singletons; PubSub.sub(C.PUBSUB_SingletonsReady, (ctx: Singletons) => { S = ctx; }); export class FullScreenGraphViewer extends Main { nodeId: string; simulation: any; tooltip: any; isDragging: boolean; constructor(appState: AppState) { super(); this.domRemoveEvent = this.domRemoveEvent.bind(this); this.domUpdateEvent = this.domUpdateEvent.bind(this); this.domPreUpdateEvent = this.domPreUpdateEvent.bind(this); this.nodeId = appState.fullScreenGraphId; let node: J.NodeInfo = S.quanta.findNodeById(appState, this.nodeId); if (!node) { console.log("Can't find nodeId " + this.nodeId); } S.util.ajax<J.GraphRequest, J.GraphResponse>("graphNodes", { searchText: appState.graphSearchText, nodeId: this.nodeId }, (resp: J.GraphResponse) => { this.mergeState({ data: resp.rootNode }); }); } preRender(): void { this.setChildren([new Div(null, { className: "d3Graph" })]); } domPreUpdateEvent(): void { let elm = this.getRef(); let state = this.getState(); if (!state.data) return; let customForceDirectedTree = this.forceDirectedTree(); d3.select(".d3Graph") .datum(state.data) .call(customForceDirectedTree); super.domPreUpdateEvent(); } forceDirectedTree = () => { let _this = this; let margin = { top: 0, right: 0, bottom: 0, left: 0 }; let width = window.innerWidth; let height = window.innerHeight; function chart(selection) { let data = selection.datum(); let chartWidth = width - margin.left - margin.right; let chartHeight = height - margin.top - margin.bottom; let root = d3.hierarchy(data); let links = root.links(); let nodes = root.descendants(); let simulation = d3.forceSimulation(nodes) .force("link", d3.forceLink(links).id(d => d.id).distance(0).strength(1)) .force("charge", d3.forceManyBody().strength(-50)) .force("x", d3.forceX()) .force("y", d3.forceY()); _this.tooltip = selection .append("div") .attr("class", "tooltip alert alert-secondary") .style("font-size", "14px") .style("pointer-events", "none"); let mouseover = (event: any, d) => { if (d.data.id.startsWith("/")) { _this.updateTooltip(d, event.pageX, event.pageY); } else { _this.showTooltip(d, event.pageX, event.pageY); } }; let mouseout = () => { _this.tooltip.transition() .duration(300) .style("opacity", 0); }; let drag = function (simulation) { function dragstarted(event, d) { _this.isDragging = true; if (!event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; } function dragged(event, d) { d.fx = event.x; d.fy = event.y; } function dragended(event, d) { if (!event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; _this.isDragging = false; } return d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended); }; let svg = selection .selectAll("svg") .data([data]) .enter() .append("svg") .attr("width", chartWidth) .attr("height", chartHeight) .style("cursor", "move") .attr("viewBox", [-window.innerWidth / 2, -window.innerHeight / 2, window.innerWidth, window.innerHeight]); svg = svg.merge(svg); let g = svg.append("g"); let link = g.append("g") .attr("stroke", "#999") .attr("stroke-width", 1.5) .attr("stroke-opacity", 0.6) .selectAll("line") // PathShape (leave this comment, referenced below) .data(links) .join("line"); // PathShape (leave this comment, referenced below) let node = g.append("g") .attr("stroke-width", 1.5) .style("cursor", "pointer") .selectAll("circle") .data(nodes) .join("circle") .attr("fill", d => { let color = "black"; if (d.data.id === _this.nodeId) { color = "red"; } else if (d.data.highlight) { color = "green"; } // For some bizarre reason whenever we return "black" from here it renders as WHITE insead. Every other color // seems to work fine, but it just insists that black get rendered as white. // console.log("color[" + d.data.id + "]=" + color); return color; }) .attr("stroke", d => { return _this.getColorForLevel(d.data.level); }) .attr("r", d => { if (d.data.id === _this.nodeId) return 5; return 3.5; }) .on("mouseover", mouseover) .on("mouseout", mouseout) .on("click", function (event: any, d) { d3.select(this) .style("fill", "green"); // .style("stroke", "red"); _this.tooltip.text("Opening...") .style("left", (event.pageX + 15) + "px") .style("top", (event.pageY - 50) + "px"); // use timeout to give user time to notice the circle was colored white now setTimeout(() => { if (d.data.id) { window.open(S.util.getHostAndPort() + "/app?id=" + d.data.id, "_blank"); } }, 1000); }) .call(drag(simulation)); simulation.on("tick", () => { // ------------------- // DO NOT DELETE (if PathShape (above) is 'path' use this) // link.attr("d", function (d) { // let dx = d.target.x - d.source.x; // let dy = d.target.y - d.source.y; // let dr = Math.sqrt(dx * dx + dy * dy); // return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 1 0,1 " + d.target.x + "," + d.target.y; // }); // node // .attr("cx", d => d.x) // .attr("cy", d => d.y); // ------------------- // If PathShape (above) is 'line' do this link .attr("x1", d => d.source.x) .attr("y1", d => d.source.y) .attr("x2", d => d.target.x) .attr("y2", d => d.target.y); node .attr("cx", d => d.x) .attr("cy", d => d.y); }); let zoomHandler = d3.zoom() .on("zoom", zoomAction); function zoomAction(event) { const { transform } = event; g.attr("stroke-width", 1 / transform.k); g.attr("transform", transform); } zoomHandler(svg); } return chart; } getColorForLevel(level: number): string { switch (level) { case 1: return "red"; case 2: return "orange"; case 3: return "blueviolet"; case 4: return "brown"; case 5: return "blue"; case 6: return "deeppink"; case 7: return "darkcyan"; case 8: return "orange"; case 9: return "purple"; case 10: return "brown"; case 11: return "slateblue"; case 12: return "slategrey"; default: return "#fff"; } } updateTooltip = (d: any, x: number, y: number) => { const res = S.util.ajax<J.RenderNodeRequest, J.RenderNodeResponse>("renderNode", { nodeId: d.data.id, upLevel: false, siblingOffset: 0, renderParentIfLeaf: false, offset: 0, goToLastPage: false, forceIPFSRefresh: false, singleNode: true }, (res: J.RenderNodeResponse) => { if (res.node) { let content = res.node.content; if (content.length > 100) { content = content.substring(0, 100) + "..."; } d.data.name = content; this.showTooltip(d, x, y); } }); } showTooltip = (d: any, x: number, y: number) => { this.tooltip.transition() .duration(300) .style("opacity", (d) => !this.isDragging ? 0.97 : 0); // DO NOT DELETE (example for how to use HTML) // this.tooltip.html(() => { // return "<div class='alert alert-secondary'>" + d.data.name + "</div>"; // }) this.tooltip.text(d.data.name) .style("left", (x + 15) + "px") .style("top", (y - 50) + "px"); } domRemoveEvent(): void { this.stopSim(); } domUpdateEvent(): void { // #DEBUG-SCROLLING // console.log("scrollTop=0"); if (S.view.docElm) { S.view.docElm.scrollTop = 0; } super.domUpdateEvent(); } stopSim = () => { if (this.simulation) { this.simulation.stop(); this.simulation = null; } } }
the_stack
import * as React from "react"; import { ComponentClass, Component } from "react"; import { ReactComponent, ReactAnyComponent, ComponentEnhancer } from "./types"; import { createBlueprint, InstanceCallbackListTypesafe, StateUpdater, LifeCycleCallbackTypes, Blueprint, InstanceCallbackEntry, ComponentCallbacks, } from "./blueprint"; import getDisplayName from "./utils/getDisplayName"; import getUniqueKey from "./utils/getUniqueKey"; import isReferentiallyTransparentFunctionComponent from "./utils/isReferentiallyTransparentFunctionComponent"; type ComponentData = { props: any, context: any, component: ReactAnyComponent, childContext?: any, lifeCycleCallbacks?: {[P in keyof LifeCycleCallbackTypes]: Function[]} & { [name: string]: Function[] }, }; type StateCallbackEntry = InstanceCallbackEntry<"stateCallback"> & { init?: ComponentData, called?: boolean, startAt?: number, }; type ComponentWillReceivePropsCallbackkEntry = InstanceCallbackEntry<"componentWillReceivePropsCallback"> & { called?: boolean, }; type PendingDataUpdate = { dirty?: boolean, init?: ComponentData, startAt?: number, callbacks?: SetStateCallback[], }; type SetStateCallback = () => void; class AssemblyBase<T> extends Component<T, any> { private target: ReactComponent<any> | string; private isReferentiallyTransparent: boolean; private callbackList: InstanceCallbackListTypesafe; private computed: ComponentData; private pendingDataUpdate: PendingDataUpdate = false; private newestProps: any; private newestContext: any; private newestState: any = {}; private unmounted = false; constructor( blueprint: Blueprint, target: ReactComponent<any> | string, isReferentiallyTransparent: boolean, props: any, context: any, ) { super(props, context); this.newestProps = props; this.newestContext = context; this.isReferentiallyTransparent = isReferentiallyTransparent; this.target = target; this.callbackList = blueprint.instanceCallbacks(); this.computed = this.runInstanceCallbacks({ props, context, component: this.target }); this.state = this.newestState; } public getChildContext() { return this.computed.childContext; } public componentWillMount() { return this.runLifeCycleCallbacks("componentWillMountCallback"); } public componentDidMount() { return this.runLifeCycleCallbacks("componentDidMountCallback"); } public componentWillUnmount() { this.unmounted = true; return this.runLifeCycleCallbacks("componentWillUnmountCallback"); } public componentWillUpdate() { return this.runLifeCycleCallbacks("componentWillUpdateCallback"); } public componentDidUpdate() { return this.runLifeCycleCallbacks("componentDidUpdateCallback"); } public componentWillReceiveProps(nextProps: any, nextContext: any) { this.newestProps = nextProps; this.newestContext = nextContext; this.handleDataUpdate({ props: nextProps, context: nextContext, component: this.target, }); } public shouldComponentUpdate(nextProps: any, nextState: any, nextContext: any) { const callbacks = this.computed.lifeCycleCallbacks.shouldComponentUpdateCallback; if (callbacks) { for (let i = 0; i < callbacks.length; i++) { if (!callbacks[i]()) { return false; } } } return true; } public render() { const {component: Component, props} = this.computed; if (!Component) { return null; } if ( Component === this.target && this.isReferentiallyTransparent || isReferentiallyTransparentFunctionComponent(Component) ) { return (Component as any)(props); } return <Component {...props} />; } private runLifeCycleCallbacks(name: keyof LifeCycleCallbackTypes) { const callbacks = this.computed.lifeCycleCallbacks[name]; if (callbacks) { callbacks.forEach((cb) => cb()); } } private applyStateDiff(stateDiff: any) { this.newestState = { ...this.newestState, ...stateDiff }; } private setStateWithLifeCycle( stateDiff: any, callback: SetStateCallback, init: ComponentData = this.defaultInit, startAt: number = 0, ) { if (this.pendingDataUpdate) { // we are in the middle of a data update. if (!this.pendingDataUpdate.dirty || startAt < this.pendingDataUpdate.startAt) { this.pendingDataUpdate.dirty = true; this.pendingDataUpdate.init = init; this.pendingDataUpdate.startAt = startAt; } if (callback) { this.pendingDataUpdate.callbacks.push(callback); } this.applyStateDiff(stateDiff); } else { // runs callbacks with the new state which will run the `componentWillReceiveProps` lifecycle this.handleDataUpdate(init, startAt, stateDiff, callback); } } private get defaultInit(): ComponentData { return { props: this.newestProps, context: this.newestContext, component: this.target, }; } private handleDataUpdate( init: ComponentData = this.defaultInit, startAt: number = 0, stateDiff: any = {}, callback: SetStateCallback = null, ) { const oldState = this.newestState; if (stateDiff) { this.applyStateDiff(stateDiff); } this.pendingDataUpdate = { callbacks: callback ? [callback] : [] }; this.computed = this.runInstanceCallbacks(init, startAt); const callbacks = this.pendingDataUpdate.callbacks; this.pendingDataUpdate = null; if (this.newestState !== oldState) { // Component could be unmounted because something during the lifecycle call can // cause a parent component to unmount this before it completed its data update. if (!this.unmounted) { this.setState(this.newestState, () => callbacks.forEach((cb) => cb())); } } } private runInstanceCallbacks(init: ComponentData, startAt = 0): ComponentData { const interim = { ...init }; if (!interim.lifeCycleCallbacks) { interim.lifeCycleCallbacks = {}; } for (let idx = startAt; idx < this.callbackList.length; idx++) { const entry = this.callbackList[idx]; switch (entry.kind) { case "propsCallback": interim.props = entry.callback(interim.props, this.newestState, interim.context); break; case "stateCallback": { const sc = entry as StateCallbackEntry; sc.init = { ...interim, // Whenever state changes, the previous `shouldComponentUpdate` callbacks becomes irrelevant. lifeCycleCallbacks: { ...interim.lifeCycleCallbacks, shouldComponentUpdateCallback: [] }, }; sc.startAt = idx; if (!sc.called) { sc.called = true; const initState = (name: string, value: any) => { let unique = getUniqueKey(name, this.newestState); this.applyStateDiff({ [unique]: value }); const updater: StateUpdater<any> = (val, callback) => { this.setStateWithLifeCycle({ [unique]: val }, callback, sc.init, sc.startAt); }; return { name: unique, updater }; }; entry.callback(initState, interim.props, this.newestState, interim.context); } } break; case "childContextCallback": interim.childContext = entry.callback(interim.childContext, interim.props, this.newestState, interim.context); break; case "skipCallback": idx += entry.callback(interim.props, this.newestState, interim.context); break; case "renderCallback": interim.component = entry.callback(interim.component, interim.props, this.newestState, interim.context); break; case "lazyLoadCallback": const list = entry.callback(interim.props, this.newestState, interim.context); if (list && list.length > 0) { this.callbackList = [...this.callbackList.slice(0, idx + 1), ...list, ...this.callbackList.slice(idx + 1)]; } break; case "componentWillReceivePropsCallback": { const cc = entry as ComponentWillReceivePropsCallbackkEntry; const callback = entry.callback(interim.props, this.newestState, interim.context); if (cc.called && this.pendingDataUpdate) { // Props changed so we need to run this lifecycle. callback(); if (this.pendingDataUpdate.dirty) { // State changed during lifecycle, so we need to recalculated from an earlier position. this.pendingDataUpdate.dirty = false; return this.runInstanceCallbacks(this.pendingDataUpdate.init, this.pendingDataUpdate.startAt); } } else { cc.called = true; } } break; case "componentWillMountCallback": case "componentDidMountCallback": case "componentWillUnmountCallback": case "shouldComponentUpdateCallback": case "componentWillUpdateCallback": case "componentDidUpdateCallback": { const hasCallbacks = interim.lifeCycleCallbacks[entry.kind] !== undefined; const callback = entry.callback(interim.props, this.newestState, interim.context); interim.lifeCycleCallbacks = { ...interim.lifeCycleCallbacks, [entry.kind]: hasCallbacks ? [...interim.lifeCycleCallbacks[entry.kind], callback] : [callback], }; } break; default: throw new Error(`Unknown callback entry '${(entry as any).kind}'`); } } return interim; } } export function assemble(...callbacks: ComponentCallbacks[]): ComponentEnhancer<any, any>; export function assemble<TInner, TOuter>(...callbacks: ComponentCallbacks[]): ComponentEnhancer<TInner, TOuter>; export function assemble<TInner, TOuter>(...callbacks: ComponentCallbacks[]): ComponentEnhancer<TInner, TOuter> { const blueprint = createBlueprint(...callbacks); return (target: ReactComponent<TInner>) => { const isReferentiallyTransparent = isReferentiallyTransparentFunctionComponent(target); const targetName = getDisplayName(target); const assembled: ComponentClass<TOuter> = class extends AssemblyBase<TOuter> { public static displayName = isReferentiallyTransparent ? targetName : `Assembled(${targetName})`; constructor(props: any, context: any) { super(blueprint, target, isReferentiallyTransparent, props, context); } }; blueprint.staticCallbacks.forEach((cb) => cb(assembled, target)); return assembled; }; } export default assemble;
the_stack
import { html, property, CSSResultArray, TemplateResult, PropertyValues, ifDefined, } from '@spectrum-web-components/base'; import { Tab } from './Tab.js'; import { Focusable, getActiveElement } from '@spectrum-web-components/shared'; import tabStyles from './tabs.css.js'; import { TabPanel } from './TabPanel.js'; const availableArrowsByDirection = { vertical: ['ArrowUp', 'ArrowDown'], ['vertical-right']: ['ArrowUp', 'ArrowDown'], horizontal: ['ArrowLeft', 'ArrowRight'], }; declare global { interface Document { fonts?: { ready: Promise<void>; }; } } const noSelectionStyle = 'transform: translateX(0px) scaleX(0) scaleY(0)'; /** * @element sp-tabs * * @slot - Tab elements to manage as a group * @slot tab-panel - Tab Panel elements related to the listed Tab elements * @attr {Boolean} quiet - The tabs border is a lot smaller * @attr {Boolean} compact - The collection of tabs take up less space */ export class Tabs extends Focusable { public static get styles(): CSSResultArray { return [tabStyles]; } /** * Whether to activate a tab on keyboard focus or not. * * By default a tab is activated via a "click" interaction. This is specifically intended for when * tab content cannot be displayed instantly, e.g. not all of the DOM content is available, etc. * To learn more about "Deciding When to Make Selection Automatically Follow Focus", visit: * https://w3c.github.io/aria-practices/#kbd_selection_follows_focus */ @property({ type: Boolean }) public auto = false; @property({ reflect: true }) public direction: 'vertical' | 'vertical-right' | 'horizontal' = 'horizontal'; @property() public label = ''; @property({ attribute: false }) public selectionIndicatorStyle = noSelectionStyle; @property({ attribute: false }) public shouldAnimate = false; @property({ reflect: true }) public get selected(): string { return this._selected; } public set selected(value: string) { const oldValue = this.selected; if (value === oldValue) { return; } this._selected = value; this.shouldUpdateCheckedState(); this.requestUpdate('selected', oldValue); } private _selected = ''; private tabs: Tab[] = []; /** * @private */ public get focusElement(): Tab | this { const focusElement = this.tabs.find( (tab) => !tab.disabled && (tab.selected || tab.value === this.selected) ); if (focusElement) { return focusElement; } const fallback = this.tabs.find((tab) => !tab.disabled); return fallback || this; } protected manageAutoFocus(): void { const tabs = [...this.children] as Tab[]; const tabUpdateCompletes = tabs.map((tab) => { if (typeof tab.updateComplete !== 'undefined') { return tab.updateComplete; } return Promise.resolve(); }); Promise.all(tabUpdateCompletes).then(() => super.manageAutoFocus()); } protected managePanels({ target, }: Event & { target: HTMLSlotElement }): void { const panels = target.assignedElements() as TabPanel[]; panels.map((panel) => { const { value, id } = panel; const tab = this.querySelector(`[role="tab"][value="${value}"]`); if (tab) { tab.setAttribute('aria-controls', id); panel.setAttribute('aria-labelledby', tab.id); } panel.selected = value === this.selected; }); } protected render(): TemplateResult { return html` <div aria-label=${ifDefined(this.label ? this.label : undefined)} @click=${this.onClick} @keydown=${this.onKeyDown} @mousedown=${this.manageFocusinType} @focusin=${this.startListeningToKeyboard} id="list" role="tablist" > <slot @slotchange=${this.onSlotChange}></slot> <div id="selectionIndicator" class=${ifDefined( this.shouldAnimate ? undefined : 'first-position' )} style=${this.selectionIndicatorStyle} role="presentation" ></div> </div> <slot name="tab-panel" @slotchange=${this.managePanels}></slot> `; } protected firstUpdated(changes: PropertyValues): void { super.firstUpdated(changes); const selectedChild = this.querySelector('[selected]') as Tab; if (selectedChild) { this.selectTarget(selectedChild); } } protected updated(changes: PropertyValues<this>): void { super.updated(changes); if (changes.has('selected')) { if (changes.get('selected')) { const previous = this.querySelector( `[role="tabpanel"][value="${changes.get('selected')}"]` ) as TabPanel; if (previous) previous.selected = false; } const next = this.querySelector( `[role="tabpanel"][value="${this.selected}"]` ) as TabPanel; if (next) next.selected = true; } if (changes.has('direction')) { if (this.direction === 'horizontal') { this.removeAttribute('aria-orientation'); } else { this.setAttribute('aria-orientation', 'vertical'); } } if (changes.has('dir')) { this.updateSelectionIndicator(); } if (changes.has('disabled')) { if (this.disabled) { this.setAttribute('aria-disabled', 'true'); } else { this.removeAttribute('aria-disabled'); } } if ( !this.shouldAnimate && typeof changes.get('shouldAnimate') !== 'undefined' ) { this.shouldAnimate = true; } } /** * This will force apply the focus visible styling. * It should always do so when this styling is already applied. */ private shouldApplyFocusVisible = false; private manageFocusinType = (): void => { if (this.shouldApplyFocusVisible) { return; } const handleFocusin = (): void => { this.shouldApplyFocusVisible = false; this.removeEventListener('focusin', handleFocusin); }; this.addEventListener('focusin', handleFocusin); }; public startListeningToKeyboard(): void { this.addEventListener('keydown', this.handleKeydown); this.shouldApplyFocusVisible = true; const selected = this.querySelector('[selected]') as Tab; if (selected) { selected.tabIndex = -1; } const stopListeningToKeyboard = (): void => { this.removeEventListener('keydown', this.handleKeydown); this.shouldApplyFocusVisible = false; const selected = this.querySelector('[selected]') as Tab; if (selected) { selected.tabIndex = 0; } this.removeEventListener('focusout', stopListeningToKeyboard); }; this.addEventListener('focusout', stopListeningToKeyboard); } public handleKeydown(event: KeyboardEvent): void { const { code } = event; const availableArrows = [...availableArrowsByDirection[this.direction]]; if (!availableArrows.includes(code)) { return; } if (!this.isLTR && this.direction === 'horizontal') { availableArrows.reverse(); } event.preventDefault(); const currentFocusedTab = getActiveElement(this) as Tab; let currentFocusedTabIndex = this.tabs.indexOf(currentFocusedTab); currentFocusedTabIndex += code === availableArrows[0] ? -1 : 1; const nextTab = this.tabs[ (currentFocusedTabIndex + this.tabs.length) % this.tabs.length ]; nextTab.focus(); if (this.auto) { this.selected = nextTab.value; } } private onClick = (event: Event): void => { const target = event.target as Tab; if (this.disabled || target.disabled) { return; } this.shouldAnimate = true; this.selectTarget(target); if (this.shouldApplyFocusVisible && event.composedPath()[0] !== this) { /* Trick :focus-visible polyfill into thinking keyboard based focus */ this.dispatchEvent( new KeyboardEvent('keydown', { code: 'Tab', }) ); target.focus(); } }; private onKeyDown = (event: KeyboardEvent): void => { if (event.code === 'Enter' || event.code === 'Space') { event.preventDefault(); const target = event.target as HTMLElement; if (target) { this.selectTarget(target); } } }; private selectTarget(target: HTMLElement): void { const value = target.getAttribute('value'); if (value) { const selected = this.selected; this.selected = value; const applyDefault = this.dispatchEvent( new Event('change', { cancelable: true, }) ); if (!applyDefault) { this.selected = selected; } } } private onSlotChange(): void { this.tabs = [...this.querySelectorAll('[role="tab"]')] as Tab[]; this.shouldUpdateCheckedState(); } private shouldUpdateCheckedState(): void { this.tabChangeResolver(); this.tabChangePromise = new Promise( (res) => (this.tabChangeResolver = res) ); setTimeout(this.updateCheckedState); } private updateCheckedState = (): void => { if (!this.tabs.length) { this.tabs = [...this.querySelectorAll('[role="tab"]')] as Tab[]; } this.tabs.forEach((element) => { element.removeAttribute('selected'); }); if (this.selected) { const currentChecked = this.tabs.find( (el) => el.value === this.selected ); if (currentChecked) { currentChecked.selected = true; } else { this.selected = ''; } } else { const firstTab = this.tabs[0]; if (firstTab) { firstTab.setAttribute('tabindex', '0'); } } this.updateSelectionIndicator(); this.tabChangeResolver(); }; private updateSelectionIndicator = async (): Promise<void> => { const selectedElement = this.tabs.find((el) => el.selected); if (!selectedElement) { this.selectionIndicatorStyle = noSelectionStyle; return; } await Promise.all([ selectedElement.updateComplete, document.fonts ? document.fonts.ready : Promise.resolve(), ]); const tabBoundingClientRect = selectedElement.getBoundingClientRect(); const parentBoundingClientRect = this.getBoundingClientRect(); if (this.direction === 'horizontal') { const width = tabBoundingClientRect.width; const offset = this.dir === 'ltr' ? tabBoundingClientRect.left - parentBoundingClientRect.left : tabBoundingClientRect.right - parentBoundingClientRect.right; this.selectionIndicatorStyle = `transform: translateX(${offset}px) scaleX(${ this.dir === 'ltr' ? width : -1 * width });`; } else { const height = tabBoundingClientRect.height; const offset = tabBoundingClientRect.top - parentBoundingClientRect.top; this.selectionIndicatorStyle = `transform: translateY(${offset}px) scaleY(${height});`; } }; private tabChangePromise = Promise.resolve(); private tabChangeResolver: () => void = function () { return; }; protected async _getUpdateComplete(): Promise<boolean> { const complete = (await super._getUpdateComplete()) as boolean; await this.tabChangePromise; return complete; } public connectedCallback(): void { super.connectedCallback(); window.addEventListener('resize', this.updateSelectionIndicator); if ('fonts' in document) { ((document as unknown) as { fonts: { addEventListener: ( name: string, callback: () => void ) => void; }; }).fonts.addEventListener( 'loadingdone', this.updateSelectionIndicator ); } } public disconnectedCallback(): void { window.removeEventListener('resize', this.updateSelectionIndicator); if ('fonts' in document) { ((document as unknown) as { fonts: { removeEventListener: ( name: string, callback: () => void ) => void; }; }).fonts.removeEventListener( 'loadingdone', this.updateSelectionIndicator ); } super.disconnectedCallback(); } }
the_stack
import {Component, EventEmitter, Inject, OnInit, Output, QueryList, ViewChildren} from "@angular/core"; import {ResultConstant} from "../../enums/result-constant.enum"; import {TestCasePriority} from "../../models/test-case-priority.model"; import {TestCaseType} from "../../models/test-case-type.model"; import {Page} from "../../shared/models/page"; import {TranslateService} from '@ngx-translate/core'; import {ToastrService} from "ngx-toastr"; import {TestCaseTypesService} from "../../services/test-case-types.service"; import {TestCasePrioritiesService} from "../../services/test-case-priorities.service"; import {WorkspaceVersion} from "../../models/workspace-version.model"; import {MAT_DIALOG_DATA} from '@angular/material/dialog'; import {TestCaseFilter} from "../../models/test-case-filter.model"; import {TestCaseStatus} from "../../enums/test-case-status.enum"; import {AuthenticationGuard} from "../../shared/guards/authentication.guard"; import {TestCaseTag} from "../../models/test-case-tag.model"; import {TestCaseTagService} from "../../services/test-case-tag.service"; import {FilterQuery} from "../../models/filter-query"; import {FilterOperation} from "../../enums/filter.operation.enum"; import {FormControl, FormGroup} from "@angular/forms"; import * as moment from "moment"; @Component({ selector: 'app-filter', templateUrl: './test-cases-filter.component.html', styles: [] }) export class TestCasesFilterComponent implements OnInit { public showFilter: Boolean; public isStepGroup: boolean; public filterApplied: boolean; public filterTestCaseTypes: number[]; public filterTestCasePriorities: number[]; public filterStatuses: TestCaseStatus[]; public filterByResult: ResultConstant[]; public filterIsMappedToSuite: string; public filterStepGroup: boolean; public filterWorkspaceVersionId: number; public filterDeleted: boolean; public filterTagIds: number[]; public testCasePrioritiesList: Page<TestCasePriority>; public testCaseTypesList: Page<TestCaseType>; public tags: TestCaseTag[]; public customFieldsQueryHash: FilterQuery[] = []; public today: Date = new Date(); public suiteMappingStatus: string[] = ['Yes','No']; public createdDateRange = new FormGroup({ start: new FormControl(), end: new FormControl() }); public updatedDateRange = new FormGroup({ start: new FormControl(), end: new FormControl() }); maxDate = new Date(); @Output('filterAction') filterEvent = new EventEmitter<string>(); public disableStatus:boolean = false; public disableTestcaseType:boolean = false; public disablePriority:boolean = false; public disableRunResult:boolean = false; constructor( @Inject(MAT_DIALOG_DATA) public data: { version: WorkspaceVersion, filter: TestCaseFilter, query: string, isStepGroup:boolean }, public translate: TranslateService, private testCaseTypeService: TestCaseTypesService, private testCasePriorityService: TestCasePrioritiesService, private authGuard: AuthenticationGuard, private testCaseTagService: TestCaseTagService) { this.isStepGroup = data.isStepGroup; } get resultConstant() { return Object.values(ResultConstant); } get statuses() { return Object.keys(TestCaseStatus); } ngOnInit() { this.createdDateRange.valueChanges.subscribe(res => { if(this.createdDateRange.valid){ this.constructQueryString() } }) this.updatedDateRange.valueChanges.subscribe(res => { if(this.updatedDateRange.valid){ this.constructQueryString() } }) if (this.data.query) { this.filterApplied = true; this.data.filter.normalizeCustomQuery(this.data.query); } else { this.data.filter.normalizeQuery(this.data.version.id); } this.splitQueryHash(); this.fetchTestCaseTypes(); this.fetchTestCasePriorities(); this.fetchTags(); this.disableSingleSelectedFields(); } disableSingleSelectedFields(){ if (this.filterStatuses?.length > 0) this.disableStatus = true; if (this.filterTestCaseTypes?.length > 0) this.disableTestcaseType = true; if (this.filterTestCasePriorities?.length > 0) this.disablePriority = true; if (this.filterByResult?.length >0) this.disableRunResult = true; } constructQueryString() { let queryString = ""; if (this.filterTestCasePriorities?.length) queryString += ",priority@" + this.filterTestCasePriorities.join("#") if (this.filterStatuses?.length) queryString += ",status@" + this.filterStatuses.join("#") if (this.filterByResult?.length) queryString += ",result@" + this.filterByResult.join("#") if(this.filterIsMappedToSuite?.length) { if (this.filterIsMappedToSuite == 'Yes') queryString += ",suiteMapping:" + true; else if (this.filterIsMappedToSuite == 'No') queryString += ",suiteMapping:" + false; } if (this.createdDateRange?.valid) { queryString += ",createdDate>" + moment(this.createdDateRange.getRawValue().start).format("YYYY-MM-DD") queryString += ",createdDate<" + moment(this.createdDateRange.getRawValue().end).format("YYYY-MM-DD") } if (this.updatedDateRange?.valid) { queryString += ",updatedDate>" + moment(this.updatedDateRange.getRawValue().start).format("YYYY-MM-DD") queryString += ",updatedDate<" + moment(this.updatedDateRange.getRawValue().end).format("YYYY-MM-DD") } if (this.filterTestCaseTypes?.length) queryString += ",type@" + this.filterTestCaseTypes.join("#") if (this.filterTagIds?.length) queryString += ",tagId@" + this.filterTagIds.join("#") if(queryString) queryString += ",workspaceVersionId:" + this.filterWorkspaceVersionId + ",deleted:" + this.filterDeleted + ",isStepGroup:" + !!this.filterStepGroup; this.data.query = queryString; } filter() { this.filterApplied = !!this.data.query; this.filterEvent.emit(this.data.query); } reset() { this.filterApplied = false; this.filterTestCaseTypes = undefined; this.filterTestCasePriorities = undefined; this.filterStepGroup = undefined; this.filterDeleted = undefined; this.filterStatuses = undefined; this.filterByResult = undefined; this.updatedDateRange.controls['start'].setValue(undefined); this.updatedDateRange.controls['end'].setValue(undefined); this.createdDateRange.controls['start'].setValue(undefined); this.createdDateRange.controls['end'].setValue(undefined); this.data.filter.normalizeQuery(this.data.version.id); this.splitQueryHash(); this.customFieldsQueryHash = []; this.data.query = undefined; this.filterEvent.emit(this.data.query); this.filterIsMappedToSuite = undefined; } convertToResultTypeFormat(result):string { result = result.replaceAll('_',' ').toLowerCase(); return result.replace(result.charAt(0),result.charAt(0).toUpperCase()); } private splitQueryHash() { if (this.data.filter.normalizedQuery.find(query => query.key == "status")) this.filterStatuses = <TestCaseStatus[]>this.data.filter.normalizedQuery.find(query => query.key == "status").value; if (this.data.filter.normalizedQuery.find(query => query.key == "result")) this.filterByResult = <ResultConstant[]>this.data.filter.normalizedQuery.find(query => query.key == "result").value; if (this.data.filter.normalizedQuery.find(query => query.key == "isStepGroup")) this.filterStepGroup = <boolean>this.data.filter.normalizedQuery.find(query => query.key == "isStepGroup").value; if (this.data.filter.normalizedQuery.find(query => query.key == "deleted") || this.data.filter.isDeleted) this.filterDeleted = <boolean>this.data.filter.normalizedQuery.find(query => query.key == "deleted").value; if (this.data.filter.normalizedQuery.find(query => query.key == "suiteMapping")) this.filterIsMappedToSuite = <string>this.data.filter.normalizedQuery.find(query => query.key == "suiteMapping").value; if (this.data.filter.normalizedQuery.find(query => query.key == "workspaceVersionId")) this.filterWorkspaceVersionId = <number>this.data.filter.normalizedQuery.find(query => query.key == "workspaceVersionId").value; if (this.data.filter.normalizedQuery.find(query => query.key == "priority")) this.filterTestCasePriorities = <number[]>this.data.filter.normalizedQuery.find(query => query.key == "priority").value; if (this.data.filter.normalizedQuery.find(query => query.key == "type")) this.filterTestCaseTypes = <number[]>this.data.filter.normalizedQuery.find(query => query.key == "type").value; if (this.data.filter.normalizedQuery.find(query => query.key == "tagId")) this.filterTagIds = <number[]>this.data.filter.normalizedQuery.find(query => query.key == "tagId").value; if (this.data.filter.normalizedQuery.find(query => query.key == "createdDate" && query.operation == FilterOperation.LESS_THAN)) this.createdDateRange.controls['end'].setValue(moment(<number>this.data.filter.normalizedQuery.find(query => query.key == "createdDate" && query.operation == FilterOperation.LESS_THAN).value).format("YYYY-MM-DD")); if (this.data.filter.normalizedQuery.find(query => query.key == "createdDate" && query.operation == FilterOperation.GREATER_THAN)) this.createdDateRange.controls['start'].setValue(moment(<number>this.data.filter.normalizedQuery.find(query => query.key == "createdDate" && query.operation == FilterOperation.GREATER_THAN).value).format("YYYY-MM-DD")); if (this.data.filter.normalizedQuery.find(query => query.key == "updatedDate" && query.operation == FilterOperation.LESS_THAN)) this.updatedDateRange.controls['end'].setValue(moment(<number>this.data.filter.normalizedQuery.find(query => query.key == "updatedDate" && query.operation == FilterOperation.LESS_THAN).value).format("YYYY-MM-DD")); if (this.data.filter.normalizedQuery.find(query => query.key == "updatedDate" && query.operation == FilterOperation.GREATER_THAN)) this.updatedDateRange.controls['start'].setValue(moment(<number>this.data.filter.normalizedQuery.find(query => query.key == "updatedDate" && query.operation == FilterOperation.GREATER_THAN).value).format("YYYY-MM-DD")); } private fetchTestCasePriorities() { this.testCasePriorityService.findAll("workspaceId:" + this.data.version.workspaceId).subscribe(res => { this.testCasePrioritiesList = res; }); } private fetchTestCaseTypes(): void { this.testCaseTypeService.findAll("workspaceId:" + this.data.version.workspaceId).subscribe(res => { this.testCaseTypesList = res; }); } private fetchTags(): void { this.testCaseTagService.findAll(undefined).subscribe(res => { this.tags = res; }); } disableFilter() { return (!this.filterApplied && !this.data.query) || this.dateInvalid(this.updatedDateRange) || this.dateInvalid(this.createdDateRange); } dateInvalid(DateRange) { return ((DateRange.controls.start.value || DateRange.controls.start.errors?.matDatepickerParse?.text) || (DateRange.controls.end.value || DateRange.controls.end.errors?.matDatepickerParse?.text) ) && DateRange.invalid; } }
the_stack
import { get } from 'lodash'; import { ChartStatus, ChartStatusEnum } from 'model/Chart'; import { UnitEnum } from 'model/Metric'; import { DataFormatter } from 'utils/DataFormatter'; const ChartJS = require('chart.js') ChartJS.defaults.global.elements.line.borderWidth = 0; ChartJS.defaults.global.elements.line.cubicInterpolationMode = "monotone"; export const INTERVALS = [10000, 30000, 60 * 1000, 2 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000, 15 * 60 * 1000, 30 * 60 * 1000]; export const EXTRA_PLOTLINES = "extraPlotLines"; export function isNoData(chartStatus: ChartStatus) { if (!chartStatus || chartStatus.status) { return false; } const status:any = chartStatus.status return [ChartStatusEnum.Loaded, ChartStatusEnum.UnLimit, ChartStatusEnum.Loading].indexOf(status) < 0; } export function getVisibleInterval(times: any, interval: number, width: number) { const ticksCount = times.length; const perTickPX = width / (ticksCount - 1); let ticksPerVisibleTick = parseInt("" + 100 / perTickPX); const t = ticksPerVisibleTick * interval; let result = interval; if (t < 60 * 60 * 1000) { INTERVALS.forEach(item => { if (t / item < 0.6) { return; } else { result = item; } }); } else { result = t - t % (60 * 60 * 1000); } return result; } ChartJS.plugins.register({ afterUpdate: function (chart: any) { const xAxes = chart.scales["xAxes-bottom"]; const tickOffset = get(xAxes, "options.ticks.tickOffset", null); const display = get(xAxes, "options.display", false); if (display && tickOffset) { const width = get(chart, "scales.xAxes-bottom.width", 0); const interval = get(chart, "config.options.interval", 0); const times = get(chart, "config.options.times", []); const visibleInterval = getVisibleInterval(times, interval, width); xAxes.draw = function () { const xScale = chart.scales["xAxes-bottom"]; const helpers = ChartJS.helpers; const tickFontColor = helpers.getValueOrDefault(xScale.options.ticks.fontColor, ChartJS.defaults.global.defaultFontColor); const tickFontSize = helpers.getValueOrDefault(xScale.options.ticks.fontSize, ChartJS.defaults.global.defaultFontSize); const tickFontStyle = helpers.getValueOrDefault(xScale.options.ticks.fontStyle, ChartJS.defaults.global.defaultFontStyle); const tickFontFamily = helpers.getValueOrDefault(xScale.options.ticks.fontFamily, ChartJS.defaults.global.defaultFontFamily); const tickLabelFont = helpers.fontString(tickFontSize, tickFontStyle, tickFontFamily); const tl = xScale.options.gridLines.tickMarkLength; const isRotated = xScale.labelRotation !== 0; const yTickStart = xScale.top; const yTickEnd = xScale.top + tl; const chartArea = chart.chartArea; helpers.each( xScale.ticks, (label: any, index: any) => { if (times[index] % visibleInterval !== 0) { return; } // console.log("xxxxxx",index,times,visibleInterval) // copy of chart.js code let xLineValue = this.getPixelForTick(index); const xLabelValue = this.getPixelForTick(index, this.options.gridLines.offsetGridLines); if (this.options.gridLines.display) { this.ctx.lineWidth = this.options.gridLines.lineWidth; this.ctx.strokeStyle = this.options.gridLines.color; xLineValue += helpers.aliasPixel(this.ctx.lineWidth); // Draw the label area this.ctx.beginPath(); if (this.options.gridLines.drawTicks) { this.ctx.moveTo(xLineValue, yTickStart); this.ctx.lineTo(xLineValue, yTickEnd); } // Draw the chart area if (this.options.gridLines.drawOnChartArea) { this.ctx.moveTo(xLineValue, chartArea.top); this.ctx.lineTo(xLineValue, chartArea.bottom); } // Need to stroke in the loop because we are potentially changing line widths & colours this.ctx.stroke(); } if (this.options.ticks.display) { this.ctx.save(); this.ctx.translate(xLabelValue + this.options.ticks.labelOffset, (isRotated) ? this.top + 12 : this.options.position === "top" ? this.bottom - tl : this.top + tl); this.ctx.rotate(helpers.toRadians(this.labelRotation) * -1); this.ctx.font = tickLabelFont; this.ctx.textAlign = (isRotated) ? "right" : "center"; this.ctx.textBaseline = (isRotated) ? "middle" : this.options.position === "top" ? "bottom" : "top"; this.ctx.fillStyle = tickFontColor; this.ctx.fillText(label, 0, 0); this.ctx.restore(); } }, xScale); }; } }, afterDraw: function (chart: any) { const status = get(chart, "options.status", null); const ctx = chart.chart.ctx; if (isNoData(status)) { chart.clear(); const width = chart.chart.width; const height = chart.chart.height; let text = ""; let color = get(chart, "options.scales.yAxes[0].ticks.fontColor", null); ctx.textAlign = "center"; ctx.textBaseline = "middle"; switch (status.status) { case ChartStatusEnum.NoData: text = "No data to display"; break; case ChartStatusEnum.BadRequest: text = "Invalid Configuration"; color = "#D27613"; break; case ChartStatusEnum.LoadError: color = "#F56C6C"; ctx.fillStyle = color; ctx.fillText(status.msg, width / 2, (height / 2) + 20); text = "Internal Server Error"; break; default: break; } ctx.font = "13px Arial"; ctx.fillStyle = color; ctx.fillText(text, width / 2, height / 2); ctx.restore(); } else if (chart.options.isSeriesChart) { const chartArea = chart.chartArea; ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle = get(chart, "options.scales.yAxes[0].gridLines.color", null); ctx.moveTo(chartArea.left, chartArea.bottom); ctx.lineTo(chartArea.right, chartArea.bottom); ctx.stroke(); } } }); export const LEFT_Y_AXES = { id: "yAxes-left", position: "left", gridLines: { drawTicks: false, lineWidth: 0.3, autoSkip: true, tickMarkLength: 0, zeroLineWidth: 0, drawBorder: false, color: "#d2d2d2", // drawOnChartArea: false, // borderDash: [1, 1], }, ticks: { fontColor: "#d2d2d2", mirror: true, // draw tick in chart area padding: 2, display: true, min: 0, fontSize: 12, autoSkip: true, tickMarkLength: 0, maxTicksLimit: 6 }, }; export const RIGHT_Y_AXES = { id: "yAxes-right", position: "right", display: false, gridLines: { drawBorder: false, drawTicks: false, display: false, }, ticks: { fontColor: "#d2d2d2", mirror: true, // draw tick in chart area padding: 2, display: false, min: 0, fontSize: 12, autoSkip: true, maxTicksLimit: 6 } }; export const CANVAS_CHART_CONFIG = { data: {}, options: { responsive: true, maintainAspectRatio: false, responsiveAnimationDuration: 0, // animation duration after a resize legend: { display: false }, elements: { line: { tension: 0, // disables bezier curve borderWidth: 1 }, point: { radius: 0 }, arc: { borderWidth: 0 } }, tooltips: { enabled: false, mode: "dataset", }, hover: { animationDuration: 0, // duration of animations when hovering an item mode: "index", intersect: false, }, animation: { duration: 0, // general animation time }, zoom: { enabled: true, drag: true, mode: "x", limits: { max: 10, min: 0.5 } }, annotation: { events: ["click"], annotations: [] }, scales: { xAxes: [{ id: "xAxes-bottom", display: true, type: "category", gridLines: { drawTicks: false, lineWidth: 0.3, tickMarkLength: 2, color: "#d2d2d2", // drawOnChartArea: false, drawBorder: false, }, ticks: { fontSize: 12, fontColor: "#d2d2d2", maxRotation: 0, // angle in degrees tickOffset: 100 } }], yAxes: [LEFT_Y_AXES, RIGHT_Y_AXES] }, } }; /** * Build yAxes config * @param options yAxes options * @param yAxesType type */ export function getyAxesConfig(options: any, unit: UnitEnum) { if (unit) { options.ticks.callback = function (value: any, index: any, values: Array<number>) { if (index === 0) { return ""; } return DataFormatter.formatter(value, unit); }; } return options; }
the_stack
import BigNumber from 'bignumber.js'; import { bnToBytes32 } from '../src/lib/BytesHelper'; import { ADDRESSES } from '../src/lib/Constants'; import { createTypedSignature, getPrependedHash, SIGNATURE_TYPES, } from '../src/lib/SignatureHelper'; import { address, BaseValue, Balance, Price } from '../src/lib/types'; import { expectBN, expectAddressesEqual, expectThrow, expect } from './helpers/Expect'; import initializePerpetual from './helpers/initializePerpetual'; import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe'; let admin: address; async function init(ctx: ITestContext): Promise<void> { await initializePerpetual(ctx); admin = ctx.accounts[0]; } perpetualDescribe('Solidity libraries', init, (ctx: ITestContext) => { describe('Adminable', () => { it('getAdmin()', async () => { expectAddressesEqual(await ctx.perpetual.proxy.getAdmin(), admin); }); }); describe('BaseMath', () => { it('base()', async () => { expectBN(await ctx.perpetual.testing.lib.base()).to.equal(new BaseValue(1).toSolidity()); }); it('baseMul()', async () => { expectBN(await ctx.perpetual.testing.lib.baseMul( 23456, new BaseValue('123.456').toSolidity(), )).to.equal(2895783); }); it('baseDivMul()', async () => { expectBN(await ctx.perpetual.testing.lib.baseDivMul( new BaseValue(23456).toSolidity(), new BaseValue('123.456').toSolidity(), )).to.equal(new BaseValue('2895783.936').toSolidity()); }); it('baseMulRoundUp()', async () => { expectBN(await ctx.perpetual.testing.lib.baseMulRoundUp( 23456, new BaseValue('123.456').toSolidity(), )).to.equal(2895784); expectBN(await ctx.perpetual.testing.lib.baseMulRoundUp( 5, new BaseValue('5').toSolidity(), )).to.equal(25); // If value is zero. expectBN(await ctx.perpetual.testing.lib.baseMulRoundUp( 0, new BaseValue('5').toSolidity(), )).to.equal(0); // If baseValue is zero. expectBN(await ctx.perpetual.testing.lib.baseMulRoundUp( 5, new BaseValue('0').toSolidity(), )).to.equal(0); }); it('baseDiv()', async () => { expectBN(await ctx.perpetual.testing.lib.baseDiv( 2895783, new BaseValue('123.456').toSolidity(), )).to.equal(23455); }); it('baseDiv() reverts if denominator is zero', async () => { await expectThrow( ctx.perpetual.testing.lib.baseDiv(2895783, 0), 'SafeMath: division by zero', ); }); it('baseReciprocal()', async () => { expectBN(await ctx.perpetual.testing.lib.baseReciprocal( new BaseValue('123.456').toSolidity(), )).to.equal(new BaseValue('0.008100051840331778').toSolidity()); expectBN(await ctx.perpetual.testing.lib.baseReciprocal( new BaseValue('0.00810005184').toSolidity(), )).to.equal(new BaseValue('123.456000005056757760').toSolidity()); }); it('baseReciprocal() reverts if denominator is zero', async () => { await expectThrow( ctx.perpetual.testing.lib.baseReciprocal(0), 'SafeMath: division by zero', ); }); }); describe('Math', () => { it('getFraction()', async () => { expectBN(await ctx.perpetual.testing.lib.getFraction( 7000, 15000, 11, )).to.equal(9545454); }); it('getFractionRoundUp()', async () => { expectBN(await ctx.perpetual.testing.lib.getFractionRoundUp( 7000, 15000, 11, )).to.equal(9545455); // If target is zero. expectBN(await ctx.perpetual.testing.lib.getFractionRoundUp( 0, 15000, 11, )).to.equal(0); // If numerator is zero. expectBN(await ctx.perpetual.testing.lib.getFractionRoundUp( 7000, 0, 11, )).to.equal(0); }); it('getFractionRoundUp() reverts with message if denominator is zero', async () => { await expectThrow( ctx.perpetual.testing.lib.getFractionRoundUp( 7000, 15000, 0, ), 'SafeMath: division by zero', ); }); it('min()', async () => { expectBN(await ctx.perpetual.testing.lib.min(111, 111)).to.equal(111); expectBN(await ctx.perpetual.testing.lib.min(111, 112)).to.equal(111); expectBN(await ctx.perpetual.testing.lib.min(112, 111)).to.equal(111); }); it('max()', async () => { expectBN(await ctx.perpetual.testing.lib.max(111, 111)).to.equal(111); expectBN(await ctx.perpetual.testing.lib.max(111, 112)).to.equal(112); expectBN(await ctx.perpetual.testing.lib.max(112, 111)).to.equal(112); }); }); describe('Require', () => { it('that()', async () => { await ctx.perpetual.testing.lib.that(true, 'reason', ADDRESSES.TEST[0]); }); it('that() reverts', async () => { const address = ADDRESSES.TEST[0]; await expectThrow( ctx.perpetual.testing.lib.that(false, 'reason', address), `reason: ${address.slice(0, 10)}...${address.slice(-8)}`, ); }); }); describe('SafeCast', () => { it('toUint128()', async () => { const value = new BigNumber(2).pow(128).minus(1); expectBN(await ctx.perpetual.testing.lib.toUint128(value)).to.equal(value); }); it('toUint128() reverts', async () => { await expectThrow( ctx.perpetual.testing.lib.toUint128( new BigNumber(2).pow(128), ), 'SafeCast: value doesn\'t fit in 128 bits', ); }); it('toUint120()', async () => { const value = new BigNumber(2).pow(120).minus(1); expectBN(await ctx.perpetual.testing.lib.toUint120(value)).to.equal(value); }); it('toUint120() reverts', async () => { await expectThrow( ctx.perpetual.testing.lib.toUint120( new BigNumber(2).pow(120), ), 'SafeCast: value doesn\'t fit in 120 bits', ); }); it('toUint32()', async () => { const value = new BigNumber(2).pow(32).minus(1); expectBN(await ctx.perpetual.testing.lib.toUint32(value)).to.equal(value); }); it('toUint32() reverts', async () => { await expectThrow( ctx.perpetual.testing.lib.toUint32( new BigNumber(2).pow(32), ), 'SafeCast: value doesn\'t fit in 32 bits', ); }); }); describe('SignedMath', () => { it('add()', async () => { // First value may be positive or negative, second is always positive. expectBN(await ctx.perpetual.testing.lib.add(99, 100)).to.equal(199); expectBN(await ctx.perpetual.testing.lib.add(-99, 99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.add(-99, 100)).to.equal(1); expectBN(await ctx.perpetual.testing.lib.add(-100, 99)).to.equal(-1); }); it('sub()', async () => { // First value may be positive or negative, second is always positive. expectBN(await ctx.perpetual.testing.lib.sub(-99, 100)).to.equal(-199); expectBN(await ctx.perpetual.testing.lib.sub(99, 99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.sub(99, 100)).to.equal(-1); expectBN(await ctx.perpetual.testing.lib.sub(100, 99)).to.equal(1); }); it('signedAdd()', async () => { expectBN(await ctx.perpetual.testing.lib.signedAdd(99, 0)).to.equal(99); expectBN(await ctx.perpetual.testing.lib.signedAdd(99, -0)).to.equal(99); expectBN(await ctx.perpetual.testing.lib.signedAdd(99, 100)).to.equal(199); expectBN(await ctx.perpetual.testing.lib.signedAdd(-99, 99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.signedAdd(-99, 100)).to.equal(1); expectBN(await ctx.perpetual.testing.lib.signedAdd(-100, 99)).to.equal(-1); expectBN(await ctx.perpetual.testing.lib.signedAdd(-99, -100)).to.equal(-199); expectBN(await ctx.perpetual.testing.lib.signedAdd(99, -99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.signedAdd(99, -100)).to.equal(-1); expectBN(await ctx.perpetual.testing.lib.signedAdd(100, -99)).to.equal(1); }); it('signedSub()', async () => { expectBN(await ctx.perpetual.testing.lib.signedSub(99, 0)).to.equal(99); expectBN(await ctx.perpetual.testing.lib.signedSub(99, -0)).to.equal(99); expectBN(await ctx.perpetual.testing.lib.signedSub(-99, 100)).to.equal(-199); expectBN(await ctx.perpetual.testing.lib.signedSub(99, 99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.signedSub(99, 100)).to.equal(-1); expectBN(await ctx.perpetual.testing.lib.signedSub(100, 99)).to.equal(1); expectBN(await ctx.perpetual.testing.lib.signedSub(99, -100)).to.equal(199); expectBN(await ctx.perpetual.testing.lib.signedSub(-99, -99)).to.equal(0); expectBN(await ctx.perpetual.testing.lib.signedSub(-99, -100)).to.equal(1); expectBN(await ctx.perpetual.testing.lib.signedSub(-100, -99)).to.equal(-1); }); }); describe('Storage', () => { // keccak256('test') const testSlot = '0x9c22ff5f21f0b81b113e63f7db6da94fedef11b2119b4088b89664fb9a3cb658'; it('load()', async () => { expectBN(await ctx.perpetual.testing.lib.load(testSlot)).to.equal(0); }); it('store()', async () => { const value = bnToBytes32(9876543210987654321); await ctx.perpetual.testing.lib.store(testSlot, value); expectBN(await ctx.perpetual.testing.lib.load(testSlot)).to.equal(value); }); }); describe('TypedSignature', () => { const hash = '0x1234567812345678123456781234567812345678123456781234567812345678'; const r = '0x30755ed65396facf86c53e6217c52b4daebe72aa4941d89635409de4c9c7f946'; const s = '0x6d4e9aaec7977f05e923889b33c0d0dd27d7226b6e6f56ce737465c5cfd04be4'; const v = '0x1b'; const rawSignature = `${r}${s.substr(2)}${v.substr(2)}`; it('recover() no prepend', async () => { const signatureData = createTypedSignature(rawSignature, SIGNATURE_TYPES.NO_PREPEND) + '0'.repeat(60); const messageHash = getPrependedHash(hash, SIGNATURE_TYPES.NO_PREPEND); const signer = ctx.perpetual.web3.eth.accounts.recover({ r, s, v, messageHash }); expectAddressesEqual(signer, await ctx.perpetual.testing.lib.recover(hash, signatureData)); }); it('recover() decimal', async () => { const signatureData = createTypedSignature(rawSignature, SIGNATURE_TYPES.DECIMAL) + '0'.repeat(60); const messageHash = getPrependedHash(hash, SIGNATURE_TYPES.DECIMAL); const signer = ctx.perpetual.web3.eth.accounts.recover({ r, s, v, messageHash }); expectAddressesEqual(signer, await ctx.perpetual.testing.lib.recover(hash, signatureData)); }); it('recover() hexadecimal', async () => { const signatureData = createTypedSignature(rawSignature, SIGNATURE_TYPES.HEXADECIMAL) + '0'.repeat(60); const messageHash = getPrependedHash(hash, SIGNATURE_TYPES.HEXADECIMAL); const signer = ctx.perpetual.web3.eth.accounts.recover({ r, s, v, messageHash }); expectAddressesEqual(signer, await ctx.perpetual.testing.lib.recover(hash, signatureData)); }); }); describe('P1BalanceMath', async () => { const posPos = new Balance(200, 300); const posNeg = new Balance(200, -300); const negPos = new Balance(-200, 300); const negNeg = new Balance(-200, -300); it('copy()', async () => { expect(await ctx.perpetual.testing.lib.copy(posPos)).to.deep.equal(posPos); expect(await ctx.perpetual.testing.lib.copy(negNeg)).to.deep.equal(negNeg); }); it('addToMargin()', async () => { expect(await ctx.perpetual.testing.lib.addToMargin(negPos, 400)).to.deep.equal(posPos); expect(await ctx.perpetual.testing.lib.addToMargin(negNeg, 400)).to.deep.equal(posNeg); }); it('subFromMargin()', async () => { expect(await ctx.perpetual.testing.lib.subFromMargin(posPos, 400)).to.deep.equal(negPos); expect(await ctx.perpetual.testing.lib.subFromMargin(posNeg, 400)).to.deep.equal(negNeg); }); it('addToPosition()', async () => { expect(await ctx.perpetual.testing.lib.addToPosition(posNeg, 600)).to.deep.equal(posPos); expect(await ctx.perpetual.testing.lib.addToPosition(negNeg, 600)).to.deep.equal(negPos); }); it('subFromPosition()', async () => { expect(await ctx.perpetual.testing.lib.subFromPosition(posPos, 600)).to.deep.equal(posNeg); expect(await ctx.perpetual.testing.lib.subFromPosition(negPos, 600)).to.deep.equal(negNeg); }); it('getPositiveAndNegativeValue()', async () => { const price = new Price('.033'); let value = await ctx.perpetual.testing.lib.getPositiveAndNegativeValue(posPos, price); expectBN(value.positive.value).to.eq('209.9'); expectBN(value.negative.value).to.eq(0); value = await ctx.perpetual.testing.lib.getPositiveAndNegativeValue(posNeg, price); expectBN(value.positive.value).to.eq(200); expectBN(value.negative.value).to.eq('9.9'); value = await ctx.perpetual.testing.lib.getPositiveAndNegativeValue(negPos, price); expectBN(value.positive.value).to.eq('9.9'); expectBN(value.negative.value).to.eq(200); value = await ctx.perpetual.testing.lib.getPositiveAndNegativeValue(negNeg, price); expectBN(value.positive.value).to.eq(0); expectBN(value.negative.value).to.eq('209.9'); }); it('getMargin()', async () => { expectBN(await ctx.perpetual.testing.lib.getMargin(posPos)).to.equal(200); expectBN(await ctx.perpetual.testing.lib.getMargin(negNeg)).to.equal(-200); }); it('getPosition()', async () => { expectBN(await ctx.perpetual.testing.lib.getPosition(posNeg)).to.equal(-300); expectBN(await ctx.perpetual.testing.lib.getPosition(negPos)).to.equal(300); }); it('setMargin()', async () => { expect(await ctx.perpetual.testing.lib.setMargin(posPos, -200)).to.deep.equal(negPos); expect(await ctx.perpetual.testing.lib.setMargin(negNeg, 200)).to.deep.equal(posNeg); }); it('setPosition()', async () => { expect(await ctx.perpetual.testing.lib.setPosition(posNeg, 300)).to.deep.equal(posPos); expect(await ctx.perpetual.testing.lib.setPosition(negPos, -300)).to.deep.equal(negNeg); }); }); describe('ReentrancyGuard', () => { it('nonReentrant() blocks', async () => { await expectThrow( ctx.perpetual.testing.lib.nonReentrant1(), 'ReentrancyGuard: reentrant call', ); }); it('nonReentrant() success', async () => { const result = await ctx.perpetual.testing.lib.nonReentrant2(); expectBN(result).to.equal(0); }); }); });
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 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 ConfluentAgreementResource: msRest.CompositeMapper = { serializedName: "ConfluentAgreementResource", type: { name: "Composite", className: "ConfluentAgreementResource", 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" } }, systemData: { readOnly: true, serializedName: "systemData", type: { name: "Composite", className: "SystemData" } }, publisher: { serializedName: "properties.publisher", type: { name: "String" } }, product: { serializedName: "properties.product", type: { name: "String" } }, plan: { serializedName: "properties.plan", type: { name: "String" } }, licenseTextLink: { serializedName: "properties.licenseTextLink", type: { name: "String" } }, privacyPolicyLink: { serializedName: "properties.privacyPolicyLink", type: { name: "String" } }, retrieveDatetime: { serializedName: "properties.retrieveDatetime", type: { name: "DateTime" } }, signature: { serializedName: "properties.signature", type: { name: "String" } }, accepted: { serializedName: "properties.accepted", type: { name: "Boolean" } } } } }; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "OperationDisplay", 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 OperationResult: msRest.CompositeMapper = { serializedName: "OperationResult", type: { name: "Composite", className: "OperationResult", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } }, isDataAction: { serializedName: "isDataAction", type: { name: "Boolean" } } } } }; export const ErrorResponseBody: msRest.CompositeMapper = { serializedName: "ErrorResponseBody", type: { name: "Composite", className: "ErrorResponseBody", 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: "ErrorResponseBody" } } } } } } }; export const ResourceProviderDefaultErrorResponse: msRest.CompositeMapper = { serializedName: "ResourceProviderDefaultErrorResponse", type: { name: "Composite", className: "ResourceProviderDefaultErrorResponse", modelProperties: { error: { readOnly: true, serializedName: "error", type: { name: "Composite", className: "ErrorResponseBody" } } } } }; export const OfferDetail: msRest.CompositeMapper = { serializedName: "OfferDetail", type: { name: "Composite", className: "OfferDetail", modelProperties: { publisherId: { required: true, serializedName: "publisherId", constraints: { MaxLength: 50 }, type: { name: "String" } }, id: { required: true, serializedName: "id", constraints: { MaxLength: 50 }, type: { name: "String" } }, planId: { required: true, serializedName: "planId", constraints: { MaxLength: 50 }, type: { name: "String" } }, planName: { required: true, serializedName: "planName", constraints: { MaxLength: 50 }, type: { name: "String" } }, termUnit: { required: true, serializedName: "termUnit", constraints: { MaxLength: 25 }, type: { name: "String" } }, status: { serializedName: "status", type: { name: "String" } } } } }; export const UserDetail: msRest.CompositeMapper = { serializedName: "UserDetail", type: { name: "Composite", className: "UserDetail", modelProperties: { firstName: { serializedName: "firstName", constraints: { MaxLength: 50 }, type: { name: "String" } }, lastName: { serializedName: "lastName", constraints: { MaxLength: 50 }, type: { name: "String" } }, emailAddress: { required: true, serializedName: "emailAddress", constraints: { Pattern: /^\S+@\S+\.\S+$/ }, type: { name: "String" } } } } }; export const OrganizationResource: msRest.CompositeMapper = { serializedName: "OrganizationResource", type: { name: "Composite", className: "OrganizationResource", 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" } }, systemData: { readOnly: true, serializedName: "systemData", type: { name: "Composite", className: "SystemData" } }, createdTime: { readOnly: true, serializedName: "properties.createdTime", type: { name: "DateTime" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, organizationId: { readOnly: true, serializedName: "properties.organizationId", type: { name: "String" } }, ssoUrl: { readOnly: true, serializedName: "properties.ssoUrl", type: { name: "String" } }, offerDetail: { required: true, serializedName: "properties.offerDetail", type: { name: "Composite", className: "OfferDetail" } }, userDetail: { required: true, serializedName: "properties.userDetail", type: { name: "Composite", className: "UserDetail" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, location: { serializedName: "location", type: { name: "String" } } } } }; export const OrganizationResourceUpdate: msRest.CompositeMapper = { serializedName: "OrganizationResourceUpdate", type: { name: "Composite", className: "OrganizationResourceUpdate", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const ConfluentAgreementResourceListResponse: msRest.CompositeMapper = { serializedName: "ConfluentAgreementResourceListResponse", type: { name: "Composite", className: "ConfluentAgreementResourceListResponse", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "ConfluentAgreementResource" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const OperationListResult: msRest.CompositeMapper = { serializedName: "OperationListResult", type: { name: "Composite", className: "OperationListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "OperationResult" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const OrganizationResourceListResult: msRest.CompositeMapper = { serializedName: "OrganizationResourceListResult", type: { name: "Composite", className: "OrganizationResourceListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "OrganizationResource" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
'use strict'; export var FILE_NOT_FOUND = 'not found'; export class FileSystem { constructor(public root: Directory) { root.setParent(null); } private listeners: { [event: string]: {(...rest: any[]): any }[] } = {}; getFileForPath(path: string): File { var result = this.getEntryForFile(path, 'file'); if (!result) { result = new File({ name: path.substr(path.lastIndexOf('/') + 1), content : null }); result.fullPath = path; result.parentPath = path.substr(0, path.lastIndexOf('/')); result.id = path; } return result; } on(event: string, handler: (...rest: any[]) => any): void { var listeners = this.listeners[event]; if (listeners && listeners.indexOf(handler) !== -1) { return; } if (!listeners) { listeners = this.listeners[event] = []; } listeners.push(handler); } off(event: string, handler: (...rest: any[]) => any): void { var listeners = this.listeners[event], index = listeners && listeners.indexOf(handler); if (!listeners || index === -1) { return; } listeners.splice(index, 1); if (listeners.length = 0) { this.listeners[event] = null; } } dispatch(event: string, ...args: any[]) { var listeners = this.listeners[event]; if (!listeners) { return; } listeners.forEach(listerner => listerner.apply(null, [{}].concat(args))); } refresh(dir: Directory) { this.root = dir; this.root.setParent(null); this.dispatch('change', null); } updateFile(path: string, content: string) { var file = this.getFileForPath(path); file.content = content; this.dispatch('change', file); } renameFile(path: string, newPath: string) { var entry: FileSystemEntry = this.getEntryForFile(path, null), dir = this.getEntryForFile(entry.parentPath, 'directory'); if (!entry || !dir) { throw new Error('unknown dir : \'' + path + '\''); } var newEntry: FileSystemEntry; if (entry.isFile) { newEntry = new File({ name: newPath.substr(newPath.lastIndexOf('/') + 1), content: (<File>entry).content }); } else { newEntry = new Directory({ name: newPath.substr(newPath.lastIndexOf('/', newPath.length - 2) + 1), children: (<Directory>entry).children }); } dir.remove(entry); dir.add(newEntry); newEntry.setParent(dir); this.dispatch('rename', path, newPath); } deleteEntry(path: string) { var entry = this.getEntryForFile(path, null), dir = this.getEntryForFile(entry.parentPath, 'directory'); if (!dir) { throw new Error('unknown dir : \'' + path + '\''); } dir.remove(entry); this.dispatch('change', dir); } addEntry(entry: FileSystemEntry) { var dir = this.getEntryForFile(entry.parentPath, 'directory'); if (!dir) { throw new Error('unknown dir : \'' + entry.parentPath + '\''); } dir.add(entry); this.dispatch('change', dir); } getEntryForFile(path: string, type: 'directory'): Directory; getEntryForFile(path: string, type: 'file'): File; getEntryForFile(path: string, type: string): FileSystemEntry; getEntryForFile(path: string, type: string): FileSystemEntry { var result: FileSystemEntry; this.root.visit(entry => { if (entry.fullPath === path ) { if (type === 'file' && !entry.isFile) { return false; } else if (type === 'directory' && !entry.isDirectory) { return false; } result = <FileSystemEntry> entry; return false; } return true; }, null, () => 0); return result; } } export function d(options: DirectoryOptions) { return new Directory(options); } export function f(options: FileOptions, fullPath?: string, parentPath?: string) { var file = new File(options); if (typeof fullPath !== 'undefined') { file.id = file.fullPath = fullPath; } if (typeof parentPath !== 'undefined') { file.parentPath = parentPath; } return file; } export class FileSystemEntry implements brackets.FileSystemEntry { fullPath: string; name: string; parentPath: string; id: string; isFile: boolean; isDirectory: boolean; setParent(directory: Directory) { if (directory) { this.parentPath = directory.fullPath; this.fullPath = directory.fullPath + this.name; this.id = this.fullPath; } if (this.isDirectory) { var dir = <Directory> this; dir.children.forEach(entry => entry.setParent(dir)); } } exists(callback: (err: string, exist: boolean) => any): void { callback(null, true); } stat(callback: (err: string, stat: brackets.FileSystemStats) => any): void { callback(null, null); } rename(newFullPath: string, callback?: (err: string) => any): void { callback(null); } unlink(callback?: (err: string) => any): void { callback(null); } moveToTrash(callback?: (err: string) => any): void { callback(null); } visit(visitor: (entry: brackets.FileSystemEntry) => boolean, options: {failFast?: boolean; maxDepth?: number; maxEntries?: number}, callbak: (err: string) => any): void { this.internalVisit(visitor); callbak(null); } private internalVisit(visitor: (entry: brackets.FileSystemEntry) => boolean): boolean { if (!visitor(this)) { return false; } if (this.isDirectory) { var result: boolean; (<Directory>this).getContents((err: string, files: FileSystemEntry[]) => { result = files.every(file => file.internalVisit(visitor)); }); return result; } else { return true; } } } export interface FileOptions { name: string; content: string; } export class File extends FileSystemEntry implements brackets.File { public content: string; constructor(options: FileOptions) { super(); this.isDirectory = false; this.isFile = true; if (!options) { throw new Error('options manadatory'); } this.name = options.name; this.content = options.content; } /** * Read a file. * * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's contents and its stats. */ read(options: {}, callback: (err: string, data: string, stat: brackets.FileSystemStats) => any): void { setTimeout(() => { if (this.content) { callback(null, this.content, null); } else { callback(FILE_NOT_FOUND, null, null); } }, 0); } /** * Write a file. * * @param data Data to write. * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's new stats. */ write(data: string, options?: {}, callback?: (err: string, stat: brackets.FileSystemStats) => any ): void { } } export interface DirectoryOptions { name: string; children: FileSystemEntry[]; } export class Directory extends FileSystemEntry implements brackets.Directory { children: FileSystemEntry[]; constructor(options: DirectoryOptions) { super(); this.isDirectory = true; this.isFile = false; if (!options) { throw new Error('options manadatory'); } this.name = options.name; this.fullPath = this.name; this.id = this.fullPath; this.children = options.children || []; } create(callback: (err: string, stat: brackets.FileSystemStats) => any): void { callback(null, null); } getContents( callback: (err: string, files: FileSystemEntry[], stats: brackets.FileSystemStats, errors: { [path: string]: string; }) => any ) { callback(null, this.children , null, null); } remove(entry: FileSystemEntry) { var index = this.children.indexOf(entry); if (index !== -1) { this.children.splice(index, 1); } } add(entry: FileSystemEntry) { this.children.push(entry); } } export class ProjectManager { constructor( private fs: FileSystem ) {} async: boolean = false; getAllFiles(filter?: (file: brackets.File) => boolean, includeWorkingSet?: boolean) { var deferred = $.Deferred<brackets.File[]>(), files: brackets.File[] = []; var resolve = () => { this.fs.root.visit(entry => { if (entry.isFile) { files.push(<brackets.File> entry); } return true; }, null, () => { deferred.resolve(files); }); }; if (this.async) { setTimeout(resolve, 0); } else { resolve(); } return deferred.promise(); } }; export class Document { file: brackets.File; isDirty: boolean; lines: string[]; getText(useOriginalLineEndings?: boolean): string { return this.lines.join('/n'); } replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin?: string): void { } getLine(index: number): string { return this.lines[index]; } } export class Editor { _codeMirror: CodeMirror.Editor = null; document = new Document(); pos: CodeMirror.Position; getCursorPos(): CodeMirror.Position { return this.pos; } getModeForSelection(): string { return 'typescript'; } getSelection(boolean: boolean): { start: CodeMirror.Position; end: CodeMirror.Position } { return null; } setCursorPos(line: number, ch: number): void { this.pos = {line: line, ch: ch}; } setFile(file: String, content: String): void { this.document.file = <any>{ fullPath: file}; this.document.lines = content.split('\n'); } }
the_stack
module WinJSTests { "use strict"; function errorHandler(msg) { try { LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg); } catch (ex) { } } function post(v?) { return WinJS.Promise.timeout(). then(function () { return v; }); } // Posts using the same technique as "runNext" // function schedule(v) { return new WinJS.Promise(function (c) { WinJS.Utilities.Scheduler.schedule(function () { c(v); }, WinJS.Utilities.Scheduler.Priority.normal); }); } export class ParallelWorkQueueTests { testSimpleQueue() { var log = []; var q = new WinJS.UI._ParallelWorkQueue(1); function push(v) { return function () { return WinJS.Promise.wrap().then(function () { log.push(v); }) }; }; q.queue(push(1)); q.queue(push(2)); q.queue(push(3)); q.queue(push(4)); LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); } testSimpleAsyncQueueSort1(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(1); function push(v) { return function () { return post().then(function () { log.push(v); }) }; }; q.queue(push(1), 1); q.queue(push(2), 2); q.queue(push(3), 3); q.queue(push(4), 4); q.sort(function (a, b) { return b - a; }); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(1, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(4, log[1]); LiveUnit.Assert.areEqual(2, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(4, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(3, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(4, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(2, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testSimpleAsyncQueue1(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(1); function push(v) { return function () { return post().then(function () { log.push(v); }) }; }; q.queue(push(1)); q.queue(push(2)); q.queue(push(3)); q.queue(push(4)); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(1, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(2, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(3, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testSimpleAsyncQueue2(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(2); function push(v) { return function () { return post().then(function () { log.push(v); }) }; }; q.queue(push(1)); q.queue(push(2)); q.queue(push(3)); q.queue(push(4)); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(2, log.length); }). then(schedule). // double post is for the async "runNext" that happens when a then(post). // work item doesn't complete synchronously then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testSimpleAsyncQueue6(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v) { return function () { return post().then(function () { log.push(v); }) }; }; q.queue(push(1)); q.queue(push(2)); q.queue(push(3)); q.queue(push(4)); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testReturnValue(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v) { return function () { return post().then(function () { log.push(v); return v; }) }; }; q.queue(push(1)).then(function (v) { LiveUnit.Assert.areEqual(1, v); }); q.queue(push(2)).then(function (v) { LiveUnit.Assert.areEqual(2, v); }); q.queue(push(3)).then(function (v) { LiveUnit.Assert.areEqual(3, v); }); q.queue(push(4)).then(function (v) { LiveUnit.Assert.areEqual(4, v); }); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testErrorValue(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v) { return function () { return post().then(function () { log.push(v); return WinJS.Promise.wrapError(v); }) }; }; q.queue(push(1)).then(function () { LiveUnit.Assert.fail("should have returned an error"); }, function (v) { LiveUnit.Assert.areEqual(1, v); }); q.queue(push(2)).then(function () { LiveUnit.Assert.fail("should have returned an error"); }, function (v) { LiveUnit.Assert.areEqual(2, v); }); q.queue(push(3)).then(function () { LiveUnit.Assert.fail("should have returned an error"); }, function (v) { LiveUnit.Assert.areEqual(3, v); }); q.queue(push(4)).then(function () { LiveUnit.Assert.fail("should have returned an error"); }, function (v) { LiveUnit.Assert.areEqual(4, v); }); post(). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(3, log[2]); LiveUnit.Assert.areEqual(4, log[3]); LiveUnit.Assert.areEqual(4, log.length); }). then(null, errorHandler). then(complete); } testRecursiveChaining(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v) { return function () { return post(). then(function () { log.push(v); if (v > 1) { q.queue(push(v - 1)); } }); }; }; q.queue(push(3)); post(). then(function () { LiveUnit.Assert.areEqual(3, log[0]); LiveUnit.Assert.areEqual(1, log.length); }). then(post). then(function () { LiveUnit.Assert.areEqual(3, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(2, log.length); }). then(post). then(function () { LiveUnit.Assert.areEqual(3, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(1, log[2]); LiveUnit.Assert.areEqual(3, log.length); }). then(null, errorHandler). then(complete); } testReentrantChaining(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v, post) { return function () { return post(). then(function () { log.push(v); if (v > 1) { q.queue(push(v - 1, WinJS.Promise.wrap)); } }); }; }; q.queue(push(3, post)); post(). then(function () { LiveUnit.Assert.areEqual(3, log[0]); LiveUnit.Assert.areEqual(2, log[1]); LiveUnit.Assert.areEqual(1, log[2]); LiveUnit.Assert.areEqual(3, log.length); }). then(null, errorHandler). then(complete); } testQuickCancel6(complete) { var log = []; var q = new WinJS.UI._ParallelWorkQueue(6); function push(v) { return function () { return post(). then(post). then(function () { log.push(v); }) }; }; var a = q.queue(push(1)); var b = q.queue(push(2)); var c = q.queue(push(3)); var d = q.queue(push(4)); b.cancel(); d.cancel(); post(). then(post). then(function () { LiveUnit.Assert.areEqual(1, log[0]); LiveUnit.Assert.areEqual(3, log[1]); LiveUnit.Assert.areEqual(2, log.length); }). then(null, errorHandler). then(complete); } } } LiveUnit.registerTestClass('WinJSTests.ParallelWorkQueueTests');
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { ZoomOptions } from '../../../src/diagram/objects/interface/interfaces'; import { NodeModel } from '../../../src/diagram/objects/node-model'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; import { MouseEvents } from './mouseevents.spec'; /** * Selector spec */ describe('Diagram Control', () => { describe('Scroller', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagramik' }); ele.style.width = '100%'; document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 400, offsetY: 400 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 600, offsetY: 400 }; diagram = new Diagram({ width: '100%', height: '600px', nodes: [node, node2] }); diagram.appendTo('#diagramik'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Moving nodes out of view - negative', (done: Function) => { diagram.nodes[0].offsetX = -500; diagram.nodes[0].offsetY = -500; diagram.dataBind(); document.getElementById("diagramik").scrollLeft = 0; document.getElementById("diagramik").scrollTop = 0; diagram.updateScrollOffset(); done(); }); it('Moving nodes into view - negative', (done: Function) => { diagram.nodes[0].offsetX = 400; diagram.nodes[0].offsetY = 400; diagram.dataBind(); document.getElementById("diagramik").scrollLeft = 550; document.getElementById("diagramik").scrollTop = 550; diagram.updateScrollOffset(); done(); }); it('Moving nodes out of view - positive', (done: Function) => { diagram.nodes[1].offsetX = 1500; diagram.nodes[1].offsetY = 1000; diagram.dataBind(); document.getElementById("diagramik").scrollLeft = 874; document.getElementById("diagramik").scrollTop = 470; diagram.updateScrollOffset(); done(); }); it('Moving nodes into view - positive', (done: Function) => { diagram.nodes[1].offsetX = 600; diagram.nodes[1].offsetY = 400; diagram.dataBind(); document.getElementById("diagramik").scrollLeft = 0; document.getElementById("diagramik").scrollTop = 0; diagram.updateScrollOffset(); done(); }); it('Moving nodes out of view - invalid - negative', (done: Function) => { diagram.nodes[0].offsetX = 200; diagram.nodes[0].offsetY = 200; diagram.dataBind(); document.getElementById("diagramik").scrollLeft = 80; document.getElementById("diagramik").scrollTop = 80; diagram.updateScrollOffset(); done(); }); it('Moving nodes out of view - invalid', (done: Function) => { diagram.nodes[1].offsetX = 1400; diagram.nodes[1].offsetY = 800; document.getElementById("diagramik").scrollLeft = 1500; document.getElementById("diagramik").scrollTop = 800; diagram.updateScrollOffset(); done(); }); 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); }) }); describe('Diagram padding left and top', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagram_padding_tl' }); ele.style.width = '100%'; document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 50, offsetY: 50 }; diagram = new Diagram({ width: '400px', height: '400px', nodes: [node], scrollSettings: { padding: { left: 50, top: 50 } } }); diagram.appendTo('#diagram_padding_tl'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('checking Diagram padding left and top', (done: Function) => { let diagramContent: HTMLElement = document.getElementById(diagram.element.id + 'content'); expect(diagramContent.scrollLeft).toBe(50); expect(diagramContent.scrollTop).toBe(50); done(); }); 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); }); }); describe('Diagram padding Right and Bottom', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'diagram_padding_rb' }); ele.style.width = '100%'; document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 350, offsetY: 350 }; diagram = new Diagram({ width: '400px', height: '400px', nodes: [node], scrollSettings: { padding: { right: 50, bottom: 50 } } }); diagram.appendTo('#diagram_padding_rb'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('checking Diagram padding Right and Bottom', (done: Function) => { let diagramContent: HTMLElement = document.getElementById(diagram.element.id + 'content'); expect(diagramContent.scrollHeight).toBe(450); expect(diagramContent.scrollWidth).toBe(450); done(); }); }); describe('Fit to page is not working for zoom greater than 1', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'diagram_padding_rb' }); ele.style.width = '100%'; ele.style.width = '100%'; document.body.appendChild(ele); let nodes: NodeModel[] = [ { id: 'node1', width: 200, height: 200, offsetX: 100, offsetY: 100, shape: { type: "Basic", shape: "Ellipse", }, }, { id: 'node2', width: 200, height: 200, offsetX: 100, offsetY: 600, shape: { type: "Basic", shape: "Ellipse", }, }, { id: 'node3', width: 200, height: 200, offsetX: 600, offsetY: 100, shape: { type: "Basic", shape: "Ellipse", }, }, { id: 'node4', width: 200, height: 200, offsetX: 600, offsetY: 600, shape: { type: "Basic", shape: "Ellipse", }, }, ]; diagram = new Diagram({ width: '100%', height: '969px', nodes: nodes, }); diagram.appendTo('#diagram_padding_rb'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Fit to page is not working for zoom greater than 1', (done: Function) => { diagram.zoom(2, { x: 600, y: 600 }) diagram.fitToPage({ mode: "Page", region: "Content", }); expect(diagram.scroller.horizontalOffset == 25 && (diagram.scroller.verticalOffset == 132.5|| diagram.scroller.verticalOffset == 134.5)).toBe(true); diagram.fitToPage({ mode: "Page", region: "Content", }); expect(diagram.scroller.horizontalOffset == 25 && (diagram.scroller.verticalOffset == 132.5|| diagram.scroller.verticalOffset == 134.5)).toBe(true); done(); }); }); describe('Scroller issue', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagramVerticalScrollerIssue' }); ele.style.width = '500px'; document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 400, offsetY: 400 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 600, offsetY: 400 }; diagram = new Diagram({ width: '500px', height: '500px', connectors: [{ id: 'connector1', type: 'Straight', sourcePoint: { x: 100, y: 300 }, targetPoint: { x: 200, y: 400 }, }], nodes: [ { id: 'node1', width: 100, height: 100, offsetX: 100, offsetY: 100, annotations: [{ content: 'Default Shape' }] }, { id: 'node2', width: 100, height: 100, offsetX: 300, offsetY: 100, shape: { type: 'Path', data: 'M540.3643,137.9336L546.7973,159.7016L570.3633,159.7296L550.7723,171.9366L558.9053,194.9966L540.3643,' + '179.4996L521.8223,194.9966L529.9553,171.9366L510.3633,159.7296L533.9313,159.7016L540.3643,137.9336z' }, annotations: [{ content: 'Path Element' }] } ], pageSettings: { background: { color: 'transparent' } }, scrollSettings: { canAutoScroll: true, // enable auto scroll as element moves scrollLimit: 'Diagram', // Diagram scroll limit with in canvas autoScrollBorder: { left: 50, right: 50, bottom: 50, top: 50 } // specify the maximum distance between the object and diagram edge to trigger autoscroll } }); diagram.appendTo('#diagramVerticalScrollerIssue'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('CR issue(EJ2-42921) - Vertical Scroll bar appears while scroll the diagram', (done: Function) => { console.log('CR issue(EJ2-42921) - Vertical Scroll bar appears while scroll the diagram'); let mouseEvents: MouseEvents = new MouseEvents(); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); let diagramCanvas: HTMLElement = document.getElementById(diagram.element.id+'content'); var center = { x: 300, y: 300 }; mouseEvents.clickEvent(diagramCanvas, center.x, center.x); mouseEvents.mouseWheelEvent(diagramCanvas, 500, 850, false); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); expect(diagram.scrollSettings.verticalOffset == 0).toBe(true); done(); }); }); describe('Scroller issue after zooming the diagram', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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) return; } ele = createElement('div', { id: 'diagramVerticalScrollerIssue' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 100, height: 100, offsetX: 400, offsetY: 400 }; let node2: NodeModel = { id: 'node2', width: 100, height: 100, offsetX: 600, offsetY: 400 }; diagram = new Diagram({ width: '800px', height: '500px', pageSettings: { height: 500, width: 500, orientation: "Landscape", showPageBreaks: true }, rulerSettings: { showRulers: true }, }); diagram.appendTo('#diagramVerticalScrollerIssue'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('CR issue(EJ2-43276) - When zoom out the diagram ruler value not update properly', (done: Function) => { diagram.pageSettings.width = 1080; diagram.pageSettings.height = 1920; diagram.dataBind(); let zoomout: ZoomOptions = { type: "ZoomOut", zoomFactor: 0.2 }; diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); diagram.zoomTo(zoomout); console.log("Scroller issue after zooming the diagram"); let diagramCanvas = document.getElementById(diagram.element.id + 'content'); let mouseEvents = new MouseEvents(); mouseEvents.clickEvent(diagramCanvas, 300+diagram.element.offsetLeft, 300+diagram.element.offsetTop); // Scroll the diagram untill the top end console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); expect(diagram.scrollSettings.verticalOffset==191.86).toBe(true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); expect(diagram.scrollSettings.verticalOffset==221.86).toBe(true); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); expect(diagram.scrollSettings.verticalOffset==231.86).toBe(true); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); // Scroll the diagram untill the bottom end mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); expect(diagram.scrollSettings.verticalOffset==101.86).toBe(true); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, false); expect(diagram.scrollSettings.verticalOffset==91.86).toBe(true); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); // Try to scroll the diagram to top after the vertical offset is 0 mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, false, true); expect(diagram.scrollSettings.verticalOffset==131.86).toBe(true); console.log("diagram.scrollSettings.verticalOffset:"+diagram.scrollSettings.verticalOffset); expect(diagram.scrollSettings.horizontalOffset==306.97).toBe(true); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); // Scroll the diagram untill the left side end mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); expect(diagram.scrollSettings.horizontalOffset==336.97).toBe(true); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); expect(diagram.scrollSettings.horizontalOffset==346.97).toBe(true); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); // Scroll the diagram untill the right side end mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); expect(Math.abs(diagram.scrollSettings.horizontalOffset)==156.97).toBe(true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); expect(Math.abs(diagram.scrollSettings.horizontalOffset)==146.97).toBe(true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, false); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); expect(Math.abs(diagram.scrollSettings.horizontalOffset)==136.97).toBe(true); // Try to scroll the diagram to left after the horizontal offset is 0 mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); mouseEvents.mouseWheelEvent(diagramCanvas, 300, 300, false, true, true); console.log("diagram.scrollSettings.horizontalOffset:"+diagram.scrollSettings.horizontalOffset); expect(Math.abs(diagram.scrollSettings.horizontalOffset)==176.97).toBe(true); done(); }); }); });
the_stack
import * as keybase1 from '../keybase1' export type BundleRevision = number export type EncryptedBundle = { v: number e: Buffer n: keybase1.BoxNonce gen: keybase1.PerUserKeyGeneration } export enum BundleVersion { V1 = 'v1', V2 = 'v2', V3 = 'v3', V4 = 'v4', V5 = 'v5', V6 = 'v6', V7 = 'v7', V8 = 'v8', V9 = 'v9', V10 = 'v10', } export type BundleSecretUnsupported = {} export type EncryptedAccountBundle = { v: number e: Buffer n: keybase1.BoxNonce gen: keybase1.PerUserKeyGeneration } export enum AccountBundleVersion { V1 = 'v1', V2 = 'v2', V3 = 'v3', V4 = 'v4', V5 = 'v5', V6 = 'v6', V7 = 'v7', V8 = 'v8', V9 = 'v9', V10 = 'v10', } export type AccountBundleSecretUnsupported = {} export type AccountID = string export type SecretKey = string export type TransactionID = string export type PaymentID = string export type KeybaseTransactionID = string export type TimeMs = number export type Hash = Buffer export type KeybaseRequestID = string export type AssetCode = string export type Asset = { type: string code: string issuer: string verifiedDomain: string issuerName: string desc: string infoUrl: string infoUrlText: string showDepositButton: boolean depositButtonText: string showWithdrawButton: boolean withdrawButtonText: string withdrawType: string transferServer: string authEndpoint: string depositReqAuth: boolean withdrawReqAuth: boolean useSep24: boolean } export type AccountReserve = { amount: string description: string } export enum TransactionStatus { NONE = 'none', PENDING = 'pending', SUCCESS = 'success', ERROR_TRANSIENT = 'error_transient', ERROR_PERMANENT = 'error_permanent', } export enum RequestStatus { OK = 'ok', CANCELED = 'canceled', DONE = 'done', } export enum PaymentStrategy { NONE = 'none', DIRECT = 'direct', RELAY = 'relay', } export enum RelayDirection { CLAIM = 'claim', YANK = 'yank', } export type NoteRecipient = { user: keybase1.UserVersion pukGen: keybase1.PerUserKeyGeneration } export type EncryptedRelaySecret = { v: number e: Buffer n: keybase1.BoxNonce gen: keybase1.PerTeamKeyGeneration } export type OutsideCurrencyCode = string export type CurrencySymbol = { str: string ambigious: boolean postfix: boolean } export type PageCursor = { horizonCursor: string directCursor: string relayCursor: string } export enum AccountMode { NONE = 'none', USER = 'user', MOBILE = 'mobile', } export enum BalanceDelta { NONE = 'none', INCREASE = 'increase', DECREASE = 'decrease', } export enum PaymentStatus { NONE = 'none', PENDING = 'pending', CLAIMABLE = 'claimable', COMPLETED = 'completed', ERROR = 'error', UNKNOWN = 'unknown', CANCELED = 'canceled', } export enum ParticipantType { NONE = 'none', KEYBASE = 'keybase', STELLAR = 'stellar', SBS = 'sbs', OWNACCOUNT = 'ownaccount', } export type BuildPaymentID = string export enum AdvancedBanner { NO_BANNER = 'no_banner', SENDER_BANNER = 'sender_banner', RECEIVER_BANNER = 'receiver_banner', } export type InflationDestinationTag = string export type AirdropDetails = { isPromoted: boolean details: string disclaimer: string } export type AirdropState = string export type AirdropQualification = { title: string subtitle: string valid: boolean } export type AssetActionResultLocal = { externalUrl?: string messageFromAnchor?: string } export enum PublicNoteType { NONE = 'none', TEXT = 'text', ID = 'id', HASH = 'hash', RETURN = 'return', } export type BatchPaymentError = { message: string code: number } export type BatchPaymentArg = { recipient: string amount: string message: string } export type PartnerUrl = { url: string title: string description: string iconFilename: string adminOnly: boolean canPurchase: boolean extra: string } export type StaticConfig = { paymentNoteMaxLength: number requestNoteMaxLength: number publicMemoMaxLength: number } export type ChatConversationID = string export type DirectOp = { noteB64: string } export enum PaymentSummaryType { NONE = 'none', STELLAR = 'stellar', DIRECT = 'direct', RELAY = 'relay', } export type TimeboundsRecommendation = { timeNow: keybase1.UnixTime timeout: number } export type NetworkOptions = { baseFee: number } export type BundleVisibleEntryV2 = { accountId: AccountID mode: AccountMode isPrimary: boolean acctBundleRevision: BundleRevision encAcctBundleHash: Hash } export type BundleSecretEntryV2 = { accountId: AccountID name: string } export type AccountBundleSecretV1 = { accountId: AccountID signers: SecretKey[] | null } export type BundleEntry = { accountId: AccountID mode: AccountMode isPrimary: boolean name: string acctBundleRevision: BundleRevision encAcctBundleHash: Hash } export type AccountBundle = { prev: Hash ownHash: Hash accountId: AccountID signers: SecretKey[] | null } export type AssetListResult = { assets: Asset[] | null totalCount: number } export type Balance = { asset: Asset amount: string limit: string isAuthorized: boolean } export type PaymentResult = { senderAccountId: AccountID keybaseId: KeybaseTransactionID stellarId: TransactionID pending: boolean } export type RelayClaimResult = { claimStellarId: TransactionID } export type EncryptedNote = { v: number e: Buffer n: keybase1.BoxNonce sender: NoteRecipient recipient?: NoteRecipient } export type NoteContents = { note: string stellarId: TransactionID } export type RelayContents = { stellarId: TransactionID sk: SecretKey note: string } export type OutsideExchangeRate = { currency: OutsideCurrencyCode rate: string } export type OutsideCurrencyDefinition = { name: string symbol: CurrencySymbol } export type Trustline = { assetCode: AssetCode issuer: AccountID } export type PaymentPath = { sourceAmount: string sourceAmountMax: string sourceAsset: Asset path: Asset[] | null destinationAmount: string destinationAsset: Asset sourceInsufficientBalance: string } export type PaymentStatusMsg = { accountId: AccountID kbTxId: KeybaseTransactionID txId: TransactionID } export type RequestStatusMsg = { reqId: KeybaseRequestID } export type PaymentNotificationMsg = { accountId: AccountID paymentId: PaymentID } export type AccountAssetLocal = { name: string assetCode: string issuerName: string issuerAccountId: string issuerVerifiedDomain: string balanceTotal: string balanceAvailableToSend: string worthCurrency: string worth: string availableToSendWorth: string reserves: AccountReserve[] | null desc: string infoUrl: string infoUrlText: string showDepositButton: boolean depositButtonText: string showWithdrawButton: boolean withdrawButtonText: string } export type PaymentDetailsOnlyLocal = { publicNote: string publicNoteType: string externalTxUrl: string feeChargedDescription: string pathIntermediate: Asset[] | null } export type PaymentTrustlineLocal = { asset: Asset remove: boolean } export type CurrencyLocal = { description: string code: OutsideCurrencyCode symbol: string name: string } export type SendAssetChoiceLocal = { asset: Asset enabled: boolean left: string right: string subtext: string } export type SendBannerLocal = { level: string message: string proofsChanged: boolean offerAdvancedSendForm: AdvancedBanner } export type SendPaymentResLocal = { kbTxId: KeybaseTransactionID pending: boolean jumpToChat: string } export type RequestDetailsLocal = { id: KeybaseRequestID fromAssertion: string fromCurrentUser: boolean toUserType: ParticipantType toAssertion: string amount: string asset?: Asset currency?: OutsideCurrencyCode amountDescription: string worthAtRequestTime: string status: RequestStatus } export type PredefinedInflationDestination = { tag: InflationDestinationTag name: string recommended: boolean accountId: AccountID url: string } export type AirdropStatus = { state: AirdropState rows: AirdropQualification[] | null } export type SendResultCLILocal = { kbTxId: KeybaseTransactionID txId: TransactionID } export type PaymentCLILocal = { txId: TransactionID time: TimeMs status: string statusDetail: string amount: string asset: Asset displayAmount?: string displayCurrency?: string sourceAmountMax: string sourceAmountActual: string sourceAsset: Asset isAdvanced: boolean summaryAdvanced: string operations: string[] | null fromStellar: AccountID toStellar?: AccountID fromUsername?: string toUsername?: string toAssertion?: string note: string noteErr: string unread: boolean publicNote: string publicNoteType: string feeChargedDescription: string } export type LookupResultCLILocal = { accountId: AccountID username?: string } export type BatchPaymentResult = { username: string startTime: TimeMs submittedTime: TimeMs endTime: TimeMs txId: TransactionID status: PaymentStatus statusDescription: string error?: BatchPaymentError } export type TxDisplaySummary = { source: AccountID fee: number memo: string memoType: string operations: string[] | null } export type SignXdrResult = { singedTx: string accountId: AccountID submitErr?: string submitTxId?: TransactionID } export type PaymentDirectPost = { fromDeviceId: keybase1.DeviceID to?: keybase1.UserVersion displayAmount: string displayCurrency: string noteB64: string signedTransaction: string quickReturn: boolean chatConversationId?: ChatConversationID batchId: string } export type PaymentRelayPost = { fromDeviceId: keybase1.DeviceID to?: keybase1.UserVersion toAssertion: string relayAccount: AccountID teamId: keybase1.TeamID displayAmount: string displayCurrency: string boxB64: string signedTransaction: string quickReturn: boolean chatConversationId?: ChatConversationID batchId: string } export type RelayClaimPost = { keybaseId: KeybaseTransactionID dir: RelayDirection signedTransaction: string autoClaimToken?: string } export type PathPaymentPost = { fromDeviceId: keybase1.DeviceID to?: keybase1.UserVersion noteB64: string signedTransaction: string quickReturn: boolean chatConversationId?: ChatConversationID } export type RelayOp = { toAssertion: string relayAccount: AccountID teamId: keybase1.TeamID boxB64: string } export type PaymentSummaryDirect = { kbTxId: KeybaseTransactionID txId: TransactionID txStatus: TransactionStatus txErrMsg: string fromStellar: AccountID from: keybase1.UserVersion fromDeviceId: keybase1.DeviceID toStellar: AccountID to?: keybase1.UserVersion amount: string asset: Asset displayAmount?: string displayCurrency?: string noteB64: string fromDisplayAmount: string fromDisplayCurrency: string toDisplayAmount: string toDisplayCurrency: string ctime: TimeMs rtime: TimeMs cursorToken: string unread: boolean fromPrimary: boolean batchId: string fromAirdrop: boolean sourceAmountMax: string sourceAmountActual: string sourceAsset: Asset } export type ClaimSummary = { txId: TransactionID txStatus: TransactionStatus txErrMsg: string dir: RelayDirection toStellar: AccountID to: keybase1.UserVersion } export type SubmitMultiRes = { txId: TransactionID } export type AutoClaim = { kbTxId: KeybaseTransactionID } export type RequestPost = { toUser?: keybase1.UserVersion toAssertion: string amount: string asset?: Asset currency?: OutsideCurrencyCode } export type RequestDetails = { id: KeybaseRequestID fromUser: keybase1.UserVersion toUser?: keybase1.UserVersion toAssertion: string amount: string asset?: Asset currency?: OutsideCurrencyCode fromDisplayAmount: string fromDisplayCurrency: string toDisplayAmount: string toDisplayCurrency: string fundingKbTxId: KeybaseTransactionID status: RequestStatus } export type PaymentPathQuery = { source: AccountID destination: AccountID sourceAsset: Asset destinationAsset: Asset amount: string } export type BundleVisibleV2 = { revision: BundleRevision prev: Hash accounts: BundleVisibleEntryV2[] | null } export type BundleSecretV2 = { visibleHash: Hash accounts: BundleSecretEntryV2[] | null } export type AccountBundleSecretVersioned = | {version: AccountBundleVersion.V1; V1: AccountBundleSecretV1} | {version: AccountBundleVersion.V2; V2: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V3; V3: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V4; V4: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V5; V5: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V6; V6: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V7; V7: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V8; V8: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V9; V9: AccountBundleSecretUnsupported} | {version: AccountBundleVersion.V10; V10: AccountBundleSecretUnsupported} | { version: Exclude< AccountBundleVersion, | AccountBundleVersion.V1 | AccountBundleVersion.V2 | AccountBundleVersion.V3 | AccountBundleVersion.V4 | AccountBundleVersion.V5 | AccountBundleVersion.V6 | AccountBundleVersion.V7 | AccountBundleVersion.V8 | AccountBundleVersion.V9 | AccountBundleVersion.V10 > } export type Bundle = { revision: BundleRevision prev: Hash ownHash: Hash accounts: BundleEntry[] | null accountBundles: {[key: string]: AccountBundle} } export type StellarServerDefinitions = { revision: number currencies: {[key: string]: OutsideCurrencyDefinition} } export type WalletAccountLocal = { accountId: AccountID isDefault: boolean name: string balanceDescription: string seqno: string currencyLocal: CurrencyLocal accountMode: AccountMode accountModeEditable: boolean deviceReadOnly: boolean isFunded: boolean canSubmitTx: boolean canAddTrustline: boolean } export type PaymentLocal = { id: PaymentID txId: TransactionID time: TimeMs statusSimplified: PaymentStatus statusDescription: string statusDetail: string showCancel: boolean amountDescription: string delta: BalanceDelta worth: string worthAtSendTime: string issuerDescription: string issuerAccountId?: AccountID fromType: ParticipantType toType: ParticipantType assetCode: string fromAccountId: AccountID fromAccountName: string fromUsername: string toAccountId?: AccountID toAccountName: string toUsername: string toAssertion: string originalToAssertion: string note: string noteErr: string sourceAmountMax: string sourceAmountActual: string sourceAsset: Asset sourceConvRate: string isAdvanced: boolean summaryAdvanced: string operations: string[] | null unread: boolean batchId: string fromAirdrop: boolean isInflation: boolean inflationSource?: string trustline?: PaymentTrustlineLocal } export type BuildPaymentResLocal = { readyToReview: boolean from: AccountID toErrMsg: string amountErrMsg: string secretNoteErrMsg: string publicMemoErrMsg: string publicMemoOverride: string worthDescription: string worthInfo: string worthAmount: string worthCurrency: string displayAmountXlm: string displayAmountFiat: string sendingIntentionXlm: boolean amountAvailable: string banners: SendBannerLocal[] | null } export type BuildRequestResLocal = { readyToRequest: boolean toErrMsg: string amountErrMsg: string secretNoteErrMsg: string worthDescription: string worthInfo: string displayAmountXlm: string displayAmountFiat: string sendingIntentionXlm: boolean banners: SendBannerLocal[] | null } export type InflationDestinationResultLocal = { destination?: AccountID knownDestination?: PredefinedInflationDestination self: boolean } export type RecipientTrustlinesLocal = { trustlines: Balance[] | null recipientType: ParticipantType } export type PaymentPathLocal = { sourceDisplay: string sourceMaxDisplay: string destinationDisplay: string exchangeRate: string amountError: string destinationAccount: AccountID fullPath: PaymentPath } export type PaymentOrErrorCLILocal = { payment?: PaymentCLILocal err?: string } export type OwnAccountCLILocal = { accountId: AccountID isPrimary: boolean name: string balance: Balance[] | null exchangeRate?: OutsideExchangeRate accountMode: AccountMode } export type BatchResultLocal = { startTime: TimeMs preparedTime: TimeMs allSubmittedTime: TimeMs allCompleteTime: TimeMs endTime: TimeMs payments: BatchPaymentResult[] | null overallDurationMs: TimeMs prepareDurationMs: TimeMs submitDurationMs: TimeMs waitPaymentsDurationMs: TimeMs waitChatDurationMs: TimeMs countSuccess: number countDirect: number countRelay: number countError: number countPending: number avgDurationMs: TimeMs avgSuccessDurationMs: TimeMs avgDirectDurationMs: TimeMs avgRelayDurationMs: TimeMs avgErrorDurationMs: TimeMs } export type ValidateStellarURIResultLocal = { operation: string originDomain: string message: string callbackUrl: string xdr: string summary: TxDisplaySummary recipient: string amount: string assetCode: string assetIssuer: string memo: string memoType: string displayAmountFiat: string availableToSendNative: string availableToSendFiat: string signed: boolean } export type PaymentOp = { to?: keybase1.UserVersion direct?: DirectOp relay?: RelayOp } export type PaymentSummaryStellar = { txId: TransactionID from: AccountID to: AccountID amount: string asset: Asset ctime: TimeMs cursorToken: string unread: boolean isInflation: boolean inflationSource?: string sourceAmountMax: string sourceAmountActual: string sourceAsset: Asset isAdvanced: boolean summaryAdvanced: string operations: string[] | null trustline?: PaymentTrustlineLocal } export type PaymentSummaryRelay = { kbTxId: KeybaseTransactionID txId: TransactionID txStatus: TransactionStatus txErrMsg: string fromStellar: AccountID from: keybase1.UserVersion fromDeviceId: keybase1.DeviceID to?: keybase1.UserVersion toAssertion: string relayAccount: AccountID amount: string displayAmount?: string displayCurrency?: string ctime: TimeMs rtime: TimeMs boxB64: string teamId: keybase1.TeamID claim?: ClaimSummary cursorToken: string batchId: string fromAirdrop: boolean } export type AccountDetails = { accountId: AccountID seqno: string balances: Balance[] | null subentryCount: number available: string reserves: AccountReserve[] | null readTransactionId?: TransactionID unreadPayments: number displayCurrency: string inflationDestination?: AccountID } export type UIPaymentReviewed = { bid: BuildPaymentID reviewId: number seqno: number banners: SendBannerLocal[] | null nextButton: string } export type BundleSecretVersioned = | {version: BundleVersion.V1; V1: BundleSecretUnsupported} | {version: BundleVersion.V2; V2: BundleSecretV2} | {version: BundleVersion.V3; V3: BundleSecretUnsupported} | {version: BundleVersion.V4; V4: BundleSecretUnsupported} | {version: BundleVersion.V5; V5: BundleSecretUnsupported} | {version: BundleVersion.V6; V6: BundleSecretUnsupported} | {version: BundleVersion.V7; V7: BundleSecretUnsupported} | {version: BundleVersion.V8; V8: BundleSecretUnsupported} | {version: BundleVersion.V9; V9: BundleSecretUnsupported} | {version: BundleVersion.V10; V10: BundleSecretUnsupported} | { version: Exclude< BundleVersion, | BundleVersion.V1 | BundleVersion.V2 | BundleVersion.V3 | BundleVersion.V4 | BundleVersion.V5 | BundleVersion.V6 | BundleVersion.V7 | BundleVersion.V8 | BundleVersion.V9 | BundleVersion.V10 > } export type PaymentOrErrorLocal = { payment?: PaymentLocal err?: string } export type PaymentDetailsLocal = { summary: PaymentLocal details: PaymentDetailsOnlyLocal } export type PaymentMultiPost = { fromDeviceId: keybase1.DeviceID signedTransaction: string operations: PaymentOp[] | null batchId: string } export type PaymentSummary = | {typ: PaymentSummaryType.STELLAR; STELLAR: PaymentSummaryStellar} | {typ: PaymentSummaryType.DIRECT; DIRECT: PaymentSummaryDirect} | {typ: PaymentSummaryType.RELAY; RELAY: PaymentSummaryRelay} | {typ: Exclude<PaymentSummaryType, PaymentSummaryType.STELLAR | PaymentSummaryType.DIRECT | PaymentSummaryType.RELAY>} export type PaymentsPageLocal = { payments: PaymentOrErrorLocal[] | null cursor?: PageCursor oldestUnread?: PaymentID } export type PaymentDetails = { summary: PaymentSummary memo: string memoType: string externalTxUrl: string feeCharged: string pathIntermediate: Asset[] | null } export type PaymentsPage = { payments: PaymentSummary[] | null cursor?: PageCursor oldestUnread?: TransactionID } export type DetailsPlusPayments = { details: AccountDetails recentPayments: PaymentsPage pendingPayments: PaymentSummary[] | null }
the_stack
import fs = require("fs"); import util = require("util"); import SoapService = require('../lib/SoapService'); import { Utils } from '../lib/utils'; import url = require('url'); import { Server } from 'http'; import Camera = require('../lib/camera'); import { v4l2ctl } from '../lib/v4l2ctl'; import { exec } from 'child_process'; import PTZService = require('./ptz_service'); var utils = Utils.utils; class MediaService extends SoapService { media_service: any; camera: Camera; ptz_service: PTZService; ffmpeg_process: any = null; ffmpeg_responses: any[] = []; constructor(config: rposConfig, server: Server, camera: Camera, ptz_service: PTZService) { super(config, server); this.media_service = require('./stubs/media_service.js').MediaService; this.camera = camera; this.ptz_service = ptz_service; this.serviceOptions = { path: '/onvif/media_service', services: this.media_service, xml: fs.readFileSync('./wsdl/media_service.wsdl', 'utf8'), wsdlPath: 'wsdl/media_service.wsdl', onReady: function() { utils.log.info('media_service started'); } }; this.extendService(); } starting() { var listeners = this.webserver.listeners('request').slice(); this.webserver.removeAllListeners('request'); this.webserver.addListener('request', (request, response, next) => { utils.log.debug('web request received : %s', request.url); var uri = url.parse(request.url, true); var action = uri.pathname; if (action == '/web/snapshot.jpg') { try { if (this.ffmpeg_process != null) { utils.log.info("ffmpeg - already running"); this.ffmpeg_responses.push(response); } else { var cmd = `ffmpeg -fflags nobuffer -probesize 256 -rtsp_transport tcp -i rtsp://127.0.0.1:${this.config.RTSPPort}/${this.config.RTSPName} -vframes 1 -r 1 -s 640x360 -y /dev/shm/snapshot.jpg`; var options = { timeout: 15000 }; utils.log.info("ffmpeg - starting"); this.ffmpeg_responses.push(response); this.ffmpeg_process = exec(cmd, options, (error, stdout, stderr) => { // callback utils.log.info("ffmpeg - finished"); if (error) { utils.log.warn('ffmpeg exec error: %s', error); } // deliver the JPEG (or the logo jpeg file) for (let responseItem of this.ffmpeg_responses) { this.deliver_jpg(responseItem); // response.Write() and response.End() } // empty the list of responses this.ffmpeg_responses = []; this.ffmpeg_process = null; }); } } catch (err) { utils.log.warn('Error ' + err); } } else { for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].call(this, request, response, next); } } }); } deliver_jpg(response: any){ try { var img = fs.readFileSync('/dev/shm/snapshot.jpg'); response.writeHead(200, { 'Content-Type': 'image/jpg' }); response.end(img, 'binary'); return; } catch (err) { utils.log.debug("Error opening snapshot : %s", err); } try { var img = fs.readFileSync('./web/snapshot.jpg'); response.writeHead(200, { 'Content-Type': 'image/jpg' }); response.end(img, 'binary'); return; } catch (err) { utils.log.debug("Error opening snapshot : %s", err); } // Return 400 error response.writeHead(400, { 'Content-Type': 'text/plain' }); response.end('JPEG unavailable'); } started() { this.camera.startRtsp(); } extendService() { var port = this.media_service.MediaService.Media; var cameraOptions = this.camera.options; var cameraSettings = this.camera.settings; var camera = this.camera; var h264Profiles = v4l2ctl.Controls.CodecControls.h264_profile.getLookupSet().map(ls=>ls.desc); h264Profiles.splice(1, 1); var videoConfigurationOptions = { QualityRange: { Min: 1, Max: 1 }, H264: { ResolutionsAvailable: cameraOptions.resolutions, GovLengthRange: { Min: v4l2ctl.Controls.CodecControls.h264_i_frame_period.getRange().min, Max: v4l2ctl.Controls.CodecControls.h264_i_frame_period.getRange().max }, FrameRateRange: { Min: cameraOptions.framerates[0], Max: cameraOptions.framerates[cameraOptions.framerates.length - 1] }, EncodingIntervalRange: { Min: 1, Max: 1 }, H264ProfilesSupported: h264Profiles }, Extension: { H264: { ResolutionsAvailable: cameraOptions.resolutions, GovLengthRange: { Min: v4l2ctl.Controls.CodecControls.h264_i_frame_period.getRange().min, Max: v4l2ctl.Controls.CodecControls.h264_i_frame_period.getRange().max }, FrameRateRange: { Min: cameraOptions.framerates[0], Max: cameraOptions.framerates[cameraOptions.framerates.length - 1] }, EncodingIntervalRange: { Min: 1, Max: 1 }, H264ProfilesSupported: h264Profiles, BitrateRange: { Min: cameraOptions.bitrates[0], Max: cameraOptions.bitrates[cameraOptions.bitrates.length - 1] } } } }; var videoEncoderConfiguration = { attributes: { token: "encoder_config_token" }, Name: "PiCameraConfiguration", UseCount: 0, Encoding: "H264", Resolution: { Width: cameraSettings.resolution.Width, Height: cameraSettings.resolution.Height }, Quality: v4l2ctl.Controls.CodecControls.video_bitrate.value ? 1 : 1, RateControl: { FrameRateLimit: cameraSettings.framerate, EncodingInterval: 1, BitrateLimit: v4l2ctl.Controls.CodecControls.video_bitrate.value / 1000 }, H264: { GovLength: v4l2ctl.Controls.CodecControls.h264_i_frame_period.value, H264Profile: v4l2ctl.Controls.CodecControls.h264_profile.desc }, Multicast: { Address: { Type: "IPv4", IPv4Address: "0.0.0.0" }, Port: 0, TTL: 1, AutoStart: false }, SessionTimeout: "PT1000S" }; var videoSource = { attributes: { token: "video_src_token" }, Framerate: 25, Resolution: { Width: 1920, Height: 1280 } }; var videoSourceConfiguration = { Name: "Primary Source", UseCount: 0, attributes: { token: "video_src_config_token" }, SourceToken: "video_src_token", Bounds: { attributes: { x: 0, y: 0, width: 1920, height: 1080 } } }; var audioEncoderConfigurationOptions = { Options: [] }; var profile = { Name: "CurrentProfile", attributes: { token: "profile_token" }, VideoSourceConfiguration: videoSourceConfiguration, VideoEncoderConfiguration: videoEncoderConfiguration, PTZConfiguration: this.ptz_service.ptzConfiguration }; port.GetServiceCapabilities = (args /*, cb, headers*/) => { var GetServiceCapabilitiesResponse = { Capabilities: { attributes: { SnapshotUri: true, Rotation: false, VideoSourceMode: true, OSD: false }, ProfileCapabilities: { attributes: { MaximumNumberOfProfiles: 1 } }, StreamingCapabilities: { attributes: { RTPMulticast: this.config.MulticastEnabled, RTP_TCP: true, RTP_RTSP_TCP: true, NonAggregateControl: false, NoRTSPStreaming: false } } } }; return GetServiceCapabilitiesResponse; }; //var GetStreamUri = { //StreamSetup : { //Stream : { xs:string} //}, //ProfileToken : { xs:string} // //}; port.GetStreamUri = (args /*, cb, headers*/) => { // Usually RTSP server is on same IP Address as the ONVIF Service // Setting RTSPAddress in the config file lets you to use another IP Address let rtspAddress = utils.getIpAddress(); if (this.config.RTSPAddress.length > 0) rtspAddress = this.config.RTSPAddress; var GetStreamUriResponse = { MediaUri: { Uri: (args.StreamSetup.Stream == "RTP-Multicast" && this.config.MulticastEnabled ? `rtsp://${rtspAddress}:${this.config.RTSPPort}/${this.config.RTSPMulticastName}` : `rtsp://${rtspAddress}:${this.config.RTSPPort}/${this.config.RTSPName}`), InvalidAfterConnect: false, InvalidAfterReboot: false, Timeout: "PT30S" } }; return GetStreamUriResponse; }; port.GetProfile = (args) => { var GetProfileResponse = { Profile: profile }; return GetProfileResponse; }; port.GetProfiles = (args) => { var GetProfilesResponse = { Profiles: [profile] }; return GetProfilesResponse; }; port.CreateProfile = (args) => { var CreateProfileResponse = { Profile: profile }; return CreateProfileResponse; }; port.DeleteProfile = (args) => { var DeleteProfileResponse = {}; return DeleteProfileResponse; }; port.GetVideoSources = (args) => { var GetVideoSourcesResponse = { VideoSources: [videoSource] }; return GetVideoSourcesResponse; } port.GetVideoSourceConfigurations = (args) => { var GetVideoSourceConfigurationsResponse = { Configurations: [videoSourceConfiguration] }; return GetVideoSourceConfigurationsResponse; }; port.GetVideoSourceConfiguration = (args) => { var GetVideoSourceConfigurationResponse = { Configurations: videoSourceConfiguration }; return GetVideoSourceConfigurationResponse; }; port.GetVideoEncoderConfigurations = (args) => { var GetVideoEncoderConfigurationsResponse = { Configurations: [videoEncoderConfiguration] }; return GetVideoEncoderConfigurationsResponse; }; port.GetVideoEncoderConfiguration = (args) => { var GetVideoEncoderConfigurationResponse = { Configuration: videoEncoderConfiguration }; return GetVideoEncoderConfigurationResponse; }; port.SetVideoEncoderConfiguration = (args) => { var settings = { bitrate: args.Configuration.RateControl.BitrateLimit, framerate: args.Configuration.RateControl.FrameRateLimit, gop: args.Configuration.H264.GovLength, profile: args.Configuration.H264.H264Profile, quality: args.Configuration.Quality instanceof Object ? 1 : args.Configuration.Quality, resolution: args.Configuration.Resolution }; camera.setSettings(settings); var SetVideoEncoderConfigurationResponse = {}; return SetVideoEncoderConfigurationResponse; }; port.GetVideoEncoderConfigurationOptions = (args) => { var GetVideoEncoderConfigurationOptionsResponse = { Options: videoConfigurationOptions }; return GetVideoEncoderConfigurationOptionsResponse; }; port.GetGuaranteedNumberOfVideoEncoderInstances = (args) => { var GetGuaranteedNumberOfVideoEncoderInstancesResponse = { TotalNumber: 1, H264: 1 } return GetGuaranteedNumberOfVideoEncoderInstancesResponse; }; port.GetSnapshotUri = (args) => { var GetSnapshotUriResponse = { MediaUri : { Uri : "http://" + utils.getIpAddress() + ":" + this.config.ServicePort + "/web/snapshot.jpg", InvalidAfterConnect : false, InvalidAfterReboot : false, Timeout : "PT30S" } }; return GetSnapshotUriResponse; }; port.GetAudioEncoderConfigurationOptions = (args) => { var GetAudioEncoderConfigurationOptionsResponse = { Options: [{}] }; return GetAudioEncoderConfigurationOptionsResponse; }; } } export = MediaService;
the_stack
* @fileoverview Implements component Package object for handling * dynamic loading of components. * * @author dpvc@mathjax.org (Davide Cervone) */ import {CONFIG, Loader} from './loader.js'; /* * The browser document (for creating scripts to load components) */ declare var document: Document; /** * A map of package names to Package instances */ export type PackageMap = Map<string, Package>; /** * An error class that includes the package name */ export class PackageError extends Error { /* tslint:disable:jsdoc-require */ public package: string; constructor(message: string, name: string) { super(message); this.package = name; } /* tslint:enable */ } /** * Types for ready() and failed() functions and for promises */ export type PackageReady = (name: string) => string | void; export type PackageFailed = (message: PackageError) => void; export type PackagePromise = (resolve: PackageReady, reject: PackageFailed) => void; /** * The configuration data for a package */ export interface PackageConfig { ready?: PackageReady; // Function to call when package is loaded successfully failed?: PackageFailed; // Function to call when package fails to load checkReady?: () => Promise<void>; // Function called to see if package is fully loaded // (may cause additional packages to load, for example) } /** * The Package class for handling individual components */ export class Package { /** * The set of packages being used */ public static packages: PackageMap = new Map(); /** * The package name */ public name: string; /** * True when the package has been loaded successfully */ public isLoaded: boolean = false; /** * A promise that resolves when the package is loaded successfully and rejects when it fails to load */ public promise: Promise<string>; /** * True when the package is being loaded but hasn't yet finished loading */ protected isLoading: boolean = false; /** * True if the package has failed to load */ protected hasFailed: boolean = false; /** * True if this package should be loaded automatically (e.g., it was created in reference * to a MathJax.loader.ready() call when the package hasn't been requested to load) */ protected noLoad: boolean; /** * The function that resolves the package's promise */ protected resolve: PackageReady; /** * The function that rejects the package's promise */ protected reject: PackageFailed; /** * The packages that require this one */ protected dependents: Package[] = []; /** * The packages that this one depends on */ protected dependencies: Package[] = []; /** * The number of dependencies that haven't yet been loaded */ protected dependencyCount: number = 0; /** * The sub-packages that this one provides */ protected provided: Package[] = []; /** * @return {boolean} True when the package can be loaded (i.e., its dependencies are all loaded, * it is allowed to be loaded, isn't already loading, and hasn't failed to load * in the past) */ get canLoad(): boolean { return this.dependencyCount === 0 && !this.noLoad && !this.isLoading && !this.hasFailed; } /** * Compute the path for a package using the loader's path filters * * @param {string} name The name of the package to resolve * @param {boolean} addExtension True if .js should be added automatically * @return {string} The path (file or URL) for this package */ public static resolvePath(name: string, addExtension: boolean = true): string { const data = {name, original: name, addExtension}; Loader.pathFilters.execute(data); return data.name; } /** * Attempt to load all packages that are ready to be loaded * (i.e., that have no unloaded dependencies, and that haven't * already been loaded, and that aren't in process of being * loaded, and that aren't marked as noLoad). */ public static loadAll() { for (const extension of this.packages.values()) { if (extension.canLoad) { extension.load(); } } } /** * @param {string} name The name of the package * @param {boolean} noLoad True when the package is just for reference, not loading */ constructor(name: string, noLoad: boolean = false) { this.name = name; this.noLoad = noLoad; Package.packages.set(name, this); this.promise = this.makePromise(this.makeDependencies()); } /** * @return {Promise<string>[]} The array of promises that must be resolved before this package * can be loaded */ protected makeDependencies(): Promise<string>[] { const promises = [] as Promise<string>[]; const map = Package.packages; const noLoad = this.noLoad; const name = this.name; // // Get the dependencies for this package // const dependencies = [] as string[]; if (CONFIG.dependencies.hasOwnProperty(name)) { dependencies.push(...CONFIG.dependencies[name]); } else if (name !== 'core') { dependencies.push('core'); // Add 'core' dependency by default } // // Add all the dependencies (creating them, if needed) // and record the promises of unloaded ones // for (const dependent of dependencies) { const extension = map.get(dependent) || new Package(dependent, noLoad); if (this.dependencies.indexOf(extension) < 0) { extension.addDependent(this, noLoad); this.dependencies.push(extension); if (!extension.isLoaded) { this.dependencyCount++; promises.push(extension.promise); } } } // // Return the collected promises // return promises; } /** * @param {Promise<string>[]} promises The array or promises that must be resolved before * this package can load */ protected makePromise(promises: Promise<string>[]) { // // Make a promise and save its resolve/reject functions // let promise = new Promise<string>(((resolve, reject) => { this.resolve = resolve; this.reject = reject; }) as PackagePromise); // // If there is a ready() function in the configuration for this package, // Add running that to the promise // const config = (CONFIG[this.name] || {}) as PackageConfig; if (config.ready) { promise = promise.then((_name: string) => config.ready(this.name)) as Promise<string>; } // // If there are promises for dependencies, // Add the one for loading this package and create a promise for all of them // (That way, if any of them fail to load, our promise will reject automatically) // if (promises.length) { promises.push(promise); promise = Promise.all(promises).then((names: string[]) => names.join(', ')); } // // If there is a failed() function in the configuration for this package, // Add a catch to handle the error // if (config.failed) { promise.catch((message: string) => config.failed(new PackageError(message, this.name))); } // // Return the promise that represents when this file is loaded // return promise; } /** * Attempt to load this package */ public load() { if (!this.isLoaded && !this.isLoading && !this.noLoad) { this.isLoading = true; const url = Package.resolvePath(this.name); if (CONFIG.require) { this.loadCustom(url); } else { this.loadScript(url); } } } /** * Load using a custom require method (usually the one from node.js) */ protected loadCustom(url: string) { try { const result = CONFIG.require(url); if (result instanceof Promise) { result.then(() => this.checkLoad()) .catch((err) => this.failed('Can\'t load "' + url + '"\n' + err.message.trim())); } else { this.checkLoad(); } } catch (err) { this.failed(err.message); } } /** * Load in a browser by inserting a script to load the proper URL */ protected loadScript(url: string) { const script = document.createElement('script'); script.src = url; script.charset = 'UTF-8'; script.onload = (_event) => this.checkLoad(); script.onerror = (_event) => this.failed('Can\'t load "' + url + '"'); // FIXME: Should there be a timeout failure as well? document.head.appendChild(script); } /** * Called when the package is loaded. * * Mark it as loaded, and tell its dependents that this package * has been loaded (may cause dependents to load themselves). * Mark any provided packages as loaded. * Resolve the promise that says this package is loaded. */ public loaded() { this.isLoaded = true; this.isLoading = false; for (const dependent of this.dependents) { dependent.requirementSatisfied(); } for (const provided of this.provided) { provided.loaded(); } this.resolve(this.name); } /** * Called when the package fails to load for some reason * * Mark it as failed to load * Reject the promise for this package with an error * * @param {string} message The error message for a load failure */ protected failed(message: string) { this.hasFailed = true; this.isLoading = false; this.reject(new PackageError(message, this.name)); } /** * Check if a package is really ready to be marked as loaded * (When it is loaded, it may set its own checkReady() function * as a means of loading additional packages. E.g., an output * jax may load a font package, dependent on its configuration.) * * The configuration's checkReady() function returns a promise * that allows the loader to wait for addition actions to finish * before marking the file as loaded (or failing to load). */ protected checkLoad() { const config = (CONFIG[this.name] || {}) as PackageConfig; const checkReady = config.checkReady || (() => Promise.resolve()); checkReady().then(() => this.loaded()) .catch((message) => this.failed(message)); } /** * This is called when a dependency loads. * * Decrease the dependency count, and try to load this package * when the dependencies are all loaded. */ public requirementSatisfied() { if (this.dependencyCount) { this.dependencyCount--; if (this.canLoad) { this.load(); } } } /** * @param {string[]} names The names of the packages that this package provides */ public provides(names: string[] = []) { for (const name of names) { let provided = Package.packages.get(name); if (!provided) { if (!CONFIG.dependencies[name]) { CONFIG.dependencies[name] = []; } CONFIG.dependencies[name].push(name); provided = new Package(name, true); provided.isLoading = true; } this.provided.push(provided); } } /** * Add a package as a dependent, and if it is not just for reference, * check if we need to change our noLoad status. * * @param {Package} extension The package to add as a dependent * @param {boolean} noLoad The noLoad status of the dependent */ public addDependent(extension: Package, noLoad: boolean) { this.dependents.push(extension); if (!noLoad) { this.checkNoLoad(); } } /** * If this package is marked as noLoad, change that and check all * our dependencies to see if they need to change their noLoad * status as well. * * I.e., if there are dependencies that were set up for reference * and a leaf node needs to be loaded, make sure all parent nodes * are marked as needing to be loaded as well. */ public checkNoLoad() { if (this.noLoad) { this.noLoad = false; for (const dependency of this.dependencies) { dependency.checkNoLoad(); } } } }
the_stack
import { module, test } from 'qunit'; import { click, currentURL, visit, waitFor, waitUntil, fillIn, settled, } from '@ember/test-helpers'; import { setupApplicationTest } from 'ember-qunit'; import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2'; import { fromWei, toWei } from 'web3-utils'; import BN from 'bn.js'; import percySnapshot from '@percy/ember'; import { setupMirage } from 'ember-cli-mirage/test-support'; import prepaidCardColorSchemes from '../../mirage/fixture-data/prepaid-card-color-schemes'; import prepaidCardPatterns from '../../mirage/fixture-data/prepaid-card-patterns'; import { timeout } from 'ember-concurrency'; import { currentNetworkDisplayInfo as c } from '@cardstack/web-client/utils/web3-strategies/network-display-info'; import { faceValueOptions, WORKFLOW_VERSION, } from '@cardstack/web-client/components/card-pay/issue-prepaid-card-workflow/index'; import { MirageTestContext } from 'ember-cli-mirage/test-support'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import { setupHubAuthenticationToken } from '../helpers/setup'; import { deserializeState, WorkflowMeta, } from '@cardstack/web-client/models/workflow/workflow-session'; import { createDepotSafe, createMerchantSafe, createPrepaidCardSafe, createSafeToken, defaultCreatedPrepaidCardDID, getFilenameFromDid, } from '@cardstack/web-client/utils/test-factories'; import { convertAmountToNativeDisplay, spendToUsd, } from '@cardstack/cardpay-sdk'; interface Context extends MirageTestContext {} // Dai amounts based on available prepaid card options const MIN_SPEND_AMOUNT = Math.min(...faceValueOptions); const MIN_AMOUNT_TO_PASS = new BN( toWei(`${Math.ceil(MIN_SPEND_AMOUNT / 100)}`) ); const FAILING_AMOUNT_IN_ETHER = new BN( `${Math.floor(MIN_SPEND_AMOUNT / 100) - 1}` ); const FAILING_AMOUNT = new BN(toWei(`${FAILING_AMOUNT_IN_ETHER}`)); const SLIGHTLY_LESS_THAN_MAX_VALUE_IN_ETHER = Math.floor(Math.max(...faceValueOptions) / 100) - 1; const SLIGHTLY_LESS_THAN_MAX_VALUE = new BN( toWei(`${SLIGHTLY_LESS_THAN_MAX_VALUE_IN_ETHER}`) ); const MERCHANT_DID = 'did:cardstack:1moVYMRNGv6E5Ca3t7aXVD2Yb11e4e91103f084a'; const OTHER_MERCHANT_DID = 'did:cardstack:1mwMdyaSSE13eHk4Dtbk75GE58960e58910b5a66'; function postableSel(milestoneIndex: number, postableIndex: number): string { return `[data-test-milestone="${milestoneIndex}"][data-test-postable="${postableIndex}"]`; } function epiloguePostableSel(postableIndex: number): string { return `[data-test-epilogue][data-test-postable="${postableIndex}"]`; } function milestoneCompletedSel(milestoneIndex: number): string { return `[data-test-milestone-completed][data-test-milestone="${milestoneIndex}"]`; } function cancelationPostableSel(postableIndex: number) { return `[data-test-cancelation][data-test-postable="${postableIndex}"]`; } module('Acceptance | issue prepaid card', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; let depotAddress = '0xB236ca8DbAB0644ffCD32518eBF4924ba8666666'; hooks.beforeEach(function (this: Context) { this.server.db.loadData({ prepaidCardColorSchemes, prepaidCardPatterns, }); }); test('Initiating workflow without wallet connections', async function (this: Context, assert) { await visit('/card-pay'); assert.equal(currentURL(), '/card-pay/wallet'); await click('[data-test-workflow-button="issue-prepaid-card"]'); let post = postableSel(0, 0); assert.dom(`${postableSel(0, 0)} img`).exists(); assert.dom(postableSel(0, 0)).containsText('Hello, it’s nice to see you!'); assert.dom(postableSel(0, 1)).containsText('Let’s issue a prepaid card.'); assert .dom(postableSel(0, 2)) .containsText( `Before we get started, please connect your ${c.layer2.fullName} wallet via your Card Wallet mobile app.` ); assert .dom(postableSel(0, 3)) .containsText( 'Once you have installed the app, open the app and add an existing wallet/account' ); assert .dom(`${postableSel(0, 4)} [data-test-wallet-connect-loading-qr-code]`) .exists(); let layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateWalletConnectUri(); await waitFor('[data-test-wallet-connect-qr-code]'); assert.dom('[data-test-wallet-connect-qr-code]').exists(); // Simulate the user scanning the QR code and connecting their mobile wallet let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); let depotAddress = '0xB236ca8DbAB0644ffCD32518eBF4924ba8666666'; let merchantSafe = createMerchantSafe({ address: '0xE73604fC1724a50CEcBC1096d4229b81aF117c94', merchant: '0xprepaidDbAB0644ffCD32518eBF4924ba8666666', tokens: [ createSafeToken('DAI.CPXD', SLIGHTLY_LESS_THAN_MAX_VALUE.toString()), createSafeToken('CARD.CPXD', '450000000000000000000'), ], accumulatedSpendValue: 100, infoDID: MERCHANT_DID, }); let otherMerchantSafe = createMerchantSafe({ merchant: '0xprepaidDbAB0644ffCD32518eBF4924ba8666666', tokens: [ createSafeToken('DAI.CPXD', SLIGHTLY_LESS_THAN_MAX_VALUE.toString()), createSafeToken('CARD.CPXD', '450000000000000000000'), ], accumulatedSpendValue: 100, infoDID: OTHER_MERCHANT_DID, }); this.server.create('merchant-info', { id: await getFilenameFromDid(MERCHANT_DID), name: 'Mandello', slug: 'mandello1', did: MERCHANT_DID, 'owner-address': layer2AccountAddress, }); this.server.create('merchant-info', { id: await getFilenameFromDid(OTHER_MERCHANT_DID), name: 'Ollednam', slug: 'ollednam1', did: OTHER_MERCHANT_DID, 'owner-address': layer2AccountAddress, }); // Simulate the user scanning the QR code and connecting their mobile wallet layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ address: depotAddress, owners: [layer2AccountAddress], tokens: [ createSafeToken('DAI.CPXD', FAILING_AMOUNT.toString()), createSafeToken('CARD.CPXD', '250000000000000000000'), ], }), createPrepaidCardSafe({ address: '0x123400000000000000000000000000000000abcd', owners: [layer2AccountAddress], spendFaceValue: 2324, prepaidCardOwner: layer2AccountAddress, issuer: layer2AccountAddress, }), otherMerchantSafe, merchantSafe, ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); await waitUntil( () => !document.querySelector('[data-test-wallet-connect-qr-code]') ); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert.dom('[data-test-prepaid-cards-count]').containsText('1'); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); assert .dom(postableSel(1, 0)) .containsText( 'To store card customization data in the Cardstack Hub, you need to authenticate using your Card Wallet' ); post = postableSel(1, 1); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); layer2Service.test__simulateHubAuthentication('abc123--def456--ghi789'); await waitFor(postableSel(1, 2)); assert .dom(postableSel(1, 2)) .containsText('First, you can choose the look and feel of your card'); post = postableSel(1, 3); await waitFor('[data-test-layout-customization-form]'); assert.dom('[data-test-layout-customization-form]').isVisible(); assert .dom(`${post} [data-test-boxel-action-chin] [data-test-boxel-button]`) .isDisabled(); await fillIn('[data-test-layout-customization-name-input]', 'A'); assert .dom(`${post} [data-test-boxel-action-chin] [data-test-boxel-button]`) .isEnabled(); await fillIn('[data-test-layout-customization-name-input]', ''); assert .dom(`${post} [data-test-boxel-input-error-message]`) .containsText('required'); assert .dom(`${post} [data-test-boxel-action-chin] [data-test-boxel-button]`) .isDisabled(); await fillIn('[data-test-layout-customization-name-input]', 'JJ'); assert.dom(`${post} [data-test-boxel-input-error-message]`).doesNotExist(); assert .dom(`${post} [data-test-boxel-action-chin] [data-test-boxel-button]`) .isEnabled(); let backgroundChoice = prepaidCardColorSchemes[1].background; let patternChoice = prepaidCardPatterns[3].patternUrl; await waitUntil( () => document.querySelectorAll( '[data-test-customization-background-loading],[data-test-customization-theme-loading]' ).length === 0 ); assert .dom( `${post} [data-test-prepaid-card-background="${backgroundChoice}"][data-test-prepaid-card-pattern="${patternChoice}"]` ) .doesNotExist(); await click( `${post} [data-test-customization-background-selection-item="${backgroundChoice}"]` ); await click( `${post} [data-test-customization-pattern-selection-item="${patternChoice}"]` ); assert .dom( `${post} [data-test-prepaid-card-background="${backgroundChoice}"][data-test-prepaid-card-pattern="${patternChoice}"]` ) .exists(); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); assert.dom(`${post} [data-test-layout-customization-form]`).isNotVisible(); assert.dom(`${post} [data-test-layout-customization-display]`).isVisible(); assert .dom( `${post} [data-test-prepaid-card-background="${backgroundChoice}"][data-test-prepaid-card-pattern="${patternChoice}"]` ) .exists(); assert.dom(`${post} [data-test-prepaid-card-attributes]`).doesNotExist(); assert .dom(`${post} [data-test-boxel-action-chin] [data-test-boxel-button]`) .containsText('Edit') .isEnabled(); await settled(); assert.dom(milestoneCompletedSel(1)).containsText('Layout customized'); assert.dom(postableSel(2, 0)).containsText('Nice choice!'); assert .dom(postableSel(2, 1)) .containsText('How do you want to fund your prepaid card?'); post = postableSel(2, 2); // // funding-source card assert .dom(`${post} [data-test-funding-source-safe]`) .containsText(`Ollednam Business account ${otherMerchantSafe.address}`); assert .dom(`${post} [data-test-balance-chooser-dropdown="DAI.CPXD"]`) .containsText(`${SLIGHTLY_LESS_THAN_MAX_VALUE_IN_ETHER.toFixed(2)} DAI`); await click( '[data-test-safe-chooser-dropdown] .ember-power-select-trigger' ); assert .dom('[data-test-safe-chooser-dropdown] li:nth-child(1)') .containsText(otherMerchantSafe.address); assert .dom('[data-test-safe-chooser-dropdown] li:nth-child(2)') .containsText(merchantSafe.address); await click('[data-test-safe-chooser-dropdown] li:nth-child(2)'); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); assert .dom(`${post} [data-test-balance-chooser-dropdown="DAI.CPXD"]`) .doesNotExist(); assert .dom(`${post} [data-test-balance-display-amount]`) .containsText('499.00 DAI'); assert .dom(postableSel(2, 3)) .containsText('choose the face value of your prepaid card'); // // face-value card assert .dom('[data-test-balance-view-summary]') .containsText('499.00 DAI') .containsText('Merchant Mandello'); await click('[data-test-balance-view-summary]'); assert .dom('[data-test-balance-view-account-address]') .containsText(layer2AccountAddress); assert .dom('[data-test-balance-view-safe-address]') .containsText(merchantSafe.address); assert .dom('[data-test-balance-view-token-amount]') .containsText('499.00 DAI'); assert.dom('[data-test-face-value-display]').doesNotExist(); assert.dom('[data-test-face-value-option]').exists({ count: 6 }); assert .dom('[data-test-face-value-option][data-test-radio-option-checked]') .doesNotExist(); assert.dom('[data-test-face-value-option="10000"] input').isNotDisabled(); assert.dom('[data-test-face-value-option="50000"] input').isDisabled(); assert .dom('[data-test-face-value-option="50000"]') .containsText('50,000 SPEND'); assert .dom('[data-test-face-value-option="50000"]') .containsText('$500 USD'); assert .dom('[data-test-face-value-option="50000"]') .containsText('≈ 500 DAI.CPXD'); assert.dom('[data-test-face-value-option="10000"] input').isNotDisabled(); assert.dom('[data-test-face-value-option="5000"] input').isNotDisabled(); await click('[data-test-face-value-option="5000"]'); assert.dom('[data-test-face-value-option="5000"] input').isChecked(); assert .dom('[data-test-face-value-option][data-test-radio-option-checked]') .exists({ count: 1 }); await click( `${postableSel( 2, 4 )} [data-test-boxel-action-chin] [data-test-boxel-button]` ); assert.dom('[data-test-face-value-option]').doesNotExist(); assert.dom('[data-test-face-value-display]').containsText('5,000 SPEND'); await click( `${postableSel( 2, 4 )} [data-test-boxel-action-chin] [data-test-boxel-button]` ); await click('[data-test-face-value-option="10000"]'); assert.dom('[data-test-face-value-option="10000"] input').isChecked(); await click( `${postableSel( 2, 4 )} [data-test-boxel-action-chin] [data-test-boxel-button]` ); assert.dom('[data-test-face-value-display]').containsText('10,000 SPEND'); assert.dom('[data-test-face-value-display]').containsText('$100.00 USD'); assert.dom('[data-test-face-value-display]').containsText('≈ 100 DAI.CPXD'); await waitFor(milestoneCompletedSel(2)); assert.dom(milestoneCompletedSel(2)).containsText('Face value chosen'); assert .dom(postableSel(3, 0)) .containsText('This is what your prepaid card will look like.'); assert .dom(`${postableSel(3, 1)} [data-test-prepaid-card-issuer-name]`) .containsText('JJ'); assert .dom( `${postableSel( 3, 1 )} [data-test-prepaid-card-issuer-name-labeled-value]` ) .containsText('JJ'); assert .dom( `${postableSel(3, 1)} [data-test-prepaid-card-face-value-labeled-value]` ) .containsText('10,000 SPEND') .containsText('$100.00 USD'); assert .dom(`${postableSel(3, 1)} [data-test-prepaid-card-balance]`) .containsText('10,000'); assert .dom(`${postableSel(3, 1)} [data-test-prepaid-card-usd-balance]`) .containsText('100'); assert.dom(`${post} [data-test-prepaid-card-attributes]`).doesNotExist(); assert.dom( `${postableSel( 3, 1 )} [data-test-prepaid-card-background="${backgroundChoice}"][data-test-prepaid-card-pattern="${patternChoice}"]` ); layer2Service.balancesRefreshed = false; // preview card post = postableSel(3, 1); await click( `${post} [data-test-boxel-action-chin] [data-test-boxel-button]` ); assert .dom(`${post} [data-test-boxel-action-chin-action-status-area]`) .containsText('Preparing to create your custom prepaid card…'); await timeout(250); let prepaidCardAddress = '0xaeFbA62A2B3e90FD131209CC94480E722704E1F8'; layer2Service.test__simulateIssuePrepaidCardForAmountFromSource( 10000, merchantSafe.address, layer2AccountAddress, prepaidCardAddress, {} ); await waitFor(milestoneCompletedSel(3)); assert.dom(milestoneCompletedSel(3)).containsText('Transaction confirmed'); assert .dom(`${postableSel(3, 1)} [data-test-boxel-action-chin]`) .containsText('Confirmed'); await settled(); let customizationStorageRequest = ( this as any ).server.pretender.handledRequests.find((req: { url: string }) => req.url.includes('prepaid-card-customizations') ); assert.equal( customizationStorageRequest.requestHeaders['authorization'], 'Bearer abc123--def456--ghi789' ); let customizationRequestJson = JSON.parse( customizationStorageRequest.requestBody ); assert.equal(customizationRequestJson.data.attributes['issuer-name'], 'JJ'); assert.equal( customizationRequestJson.data.relationships.pattern.data.id, '80cb8f99-c5f7-419e-9c95-2e87a9d8db32' ); assert.equal( customizationRequestJson.data.relationships['color-scheme'].data.id, '4f219852-33ee-4e4c-81f7-76318630a423' ); assert .dom( `${postableSel(3, 1)} [data-test-prepaid-card-address-labeled-value]` ) .containsText(`0xaeFb...E1F8 on ${c.layer2.fullName}`); assert .dom(epiloguePostableSel(0)) .containsText('Congratulations, you have created a prepaid card!'); await waitFor(epiloguePostableSel(1)); assert.dom(epiloguePostableSel(1)).containsText('Prepaid card issued'); assert .dom(`${epiloguePostableSel(1)} [data-test-prepaid-card-issuer-name]`) .containsText('JJ'); assert .dom(`${epiloguePostableSel(1)} [data-test-prepaid-card-attributes]`) .containsText('Non-reloadable Transferrable'); assert.dom( `${epiloguePostableSel( 1 )} [data-test-prepaid-card-background="${backgroundChoice}"][data-test-prepaid-card-pattern="${patternChoice}"]` ); await waitFor(epiloguePostableSel(2)); assert .dom(epiloguePostableSel(2)) .containsText( `This is the remaining balance in your ${c.layer2.fullName} wallet` ); await waitFor(epiloguePostableSel(3)); assert .dom(`${epiloguePostableSel(3)} [data-test-balance-label]`) .containsText('Business balance'); assert .dom(`${epiloguePostableSel(3)} [data-test-balance="DAI.CPXD"]`) .containsText((SLIGHTLY_LESS_THAN_MAX_VALUE_IN_ETHER - 100).toString()); await waitFor(epiloguePostableSel(4)); let workflowPersistenceService = this.owner.lookup( 'service:workflow-persistence' ) as WorkflowPersistence; const workflowPersistenceId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id')!; assert .dom( `${epiloguePostableSel( 4 )} [data-test-issue-prepaid-card-next-step="dashboard"]` ) .exists(); await percySnapshot(assert); await click( `${epiloguePostableSel( 4 )} [data-test-issue-prepaid-card-next-step="dashboard"]` ); assert.dom('[data-test-workflow-thread]').doesNotExist(); assert.dom('[data-test-prepaid-cards-count]').containsText('2'); const persistedData = workflowPersistenceService.getPersistedData( workflowPersistenceId ); assert.equal(persistedData.name, 'PREPAID_CARD_ISSUANCE'); let persistedState = persistedData.state; let deserializedState = deserializeState({ ...persistedState, }); // We don't have a good way to control the date properties in an acceptance test yet // sinon.useFakeTimers will mess up a couple of browser apis + ember concurrency if (deserializedState.meta) { delete (deserializedState.meta as WorkflowMeta)?.createdAt; delete (deserializedState.meta as WorkflowMeta)?.updatedAt; } assert.propEqual(deserializedState, { colorScheme: { patternColor: 'white', textColor: 'black', background: '#37EB77', id: '4f219852-33ee-4e4c-81f7-76318630a423', }, daiMinValue: MIN_AMOUNT_TO_PASS.toString(), spendMinValue: MIN_SPEND_AMOUNT, did: defaultCreatedPrepaidCardDID, issuerName: 'JJ', layer2WalletAddress: layer2AccountAddress, pattern: { patternUrl: '/assets/images/prepaid-card-customizations/pattern-3-89f3b92e275536a92558d500a3dc9e4d.svg', id: '80cb8f99-c5f7-419e-9c95-2e87a9d8db32', }, prepaidCardAddress: '0xaeFbA62A2B3e90FD131209CC94480E722704E1F8', prepaidFundingSafeAddress: merchantSafe.address, prepaidFundingToken: 'DAI.CPXD', reloadable: false, spendFaceValue: 10000, transferrable: true, txnHash: 'exampleTxnHash', meta: { version: WORKFLOW_VERSION, completedCardNames: [ 'LAYER2_CONNECT', 'HUB_AUTH', 'LAYOUT_CUSTOMIZATION', 'FUNDING_SOURCE', 'FACE_VALUE', 'PREVIEW', 'CONFIRMATION', 'EPILOGUE_SAFE_BALANCE_CARD', ], completedMilestonesCount: 4, milestonesCount: 4, }, }); }); module('Tests with the layer 2 wallet already connected', function (hooks) { let layer2Service: Layer2TestWeb3Strategy; setupHubAuthenticationToken(hooks); hooks.beforeEach(async function () { layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; let testDepot = createDepotSafe({ address: depotAddress, owners: [layer2AccountAddress], tokens: [ createSafeToken('DAI.CPXD', MIN_AMOUNT_TO_PASS.toString()), createSafeToken('CARD.CPXD', '500000000000000000000'), ], }); layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ testDepot, ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); }); test('Disconnecting Layer 2 from within the workflow', async function (assert) { await visit('/card-pay'); assert.equal(currentURL(), '/card-pay/wallet'); await click('[data-test-workflow-button="issue-prepaid-card"]'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); await click( `[data-test-layer-2-wallet-card] [data-test-layer-2-wallet-disconnect-button]` ); // test that all cta buttons are disabled assert .dom( '[data-test-milestone] [data-test-boxel-action-chin] button[data-test-boxel-button]:not([disabled])' ) .doesNotExist(); assert .dom(cancelationPostableSel(0)) .containsText( `It looks like your ${c.layer2.fullName} wallet got disconnected. If you still want to create a prepaid card, please start again by connecting your wallet.` ); assert.dom(cancelationPostableSel(1)).containsText('Workflow canceled'); assert .dom( '[data-test-workflow-default-cancelation-restart="issue-prepaid-card"]' ) .exists(); }); test('Disconnecting Layer 2 from outside the current tab (mobile wallet / other tabs)', async function (assert) { await visit('/card-pay'); assert.equal(currentURL(), '/card-pay/wallet'); await click('[data-test-workflow-button="issue-prepaid-card"]'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); assert.dom('[data-test-layout-customization-form]').isVisible(); layer2Service.test__simulateDisconnectFromWallet(); await waitFor( '[data-test-workflow-default-cancelation-cta="issue-prepaid-card"]' ); // test that all cta buttons are disabled assert .dom( '[data-test-milestone] [data-test-boxel-action-chin] button[data-test-boxel-button]:not([disabled])' ) .doesNotExist(); assert .dom(cancelationPostableSel(0)) .containsText( `It looks like your ${c.layer2.fullName} wallet got disconnected. If you still want to create a prepaid card, please start again by connecting your wallet.` ); assert.dom(cancelationPostableSel(1)).containsText('Workflow canceled'); assert .dom( '[data-test-workflow-default-cancelation-restart="issue-prepaid-card"]' ) .exists(); }); test('Workflow is canceled after showing wallet connection card if balances insufficient to create prepaid card', async function (assert) { await visit('/card-pay'); assert.equal(currentURL(), '/card-pay/wallet'); layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ address: depotAddress, owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', FAILING_AMOUNT.toString())], }), createMerchantSafe({ merchant: '0xprepaidDbAB0644ffCD32518eBF4924ba8666666', tokens: [createSafeToken('DAI.CPXD', FAILING_AMOUNT.toString())], accumulatedSpendValue: 100, }), ]); await layer2Service.safes.fetch(); await click('[data-test-workflow-button="issue-prepaid-card"]'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom(cancelationPostableSel(0)) .containsText( `Looks like you don’t have a business account or depot with enough balance to fund a prepaid card. Before you can continue, you can add funds by bridging some tokens from your ${ c.layer2.fullName } wallet, or by claiming business revenue in Card Wallet. The minimum balance needed to issue a prepaid card is approximately ${Math.ceil( Number(fromWei(MIN_AMOUNT_TO_PASS.toString())) )} DAI.CPXD (${convertAmountToNativeDisplay( spendToUsd(MIN_SPEND_AMOUNT)!, 'USD' )}).` ); assert.dom(cancelationPostableSel(1)).containsText('Workflow canceled'); assert .dom( '[data-test-issue-prepaid-card-workflow-insufficient-funds-deposit]' ) .exists(); }); test('Changing Layer 2 account should cancel the workflow', async function (assert) { let secondLayer2AccountAddress = '0x5416C61193C3393B46C2774ac4717C252031c0bE'; await visit('/card-pay'); assert.equal(currentURL(), '/card-pay/wallet'); await click('[data-test-workflow-button="issue-prepaid-card"]'); assert .dom( '[data-test-postable] [data-test-layer-2-wallet-card] [data-test-address-field]' ) .containsText(layer2AccountAddress) .isVisible(); await settled(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); await layer2Service.test__simulateAccountsChanged([ secondLayer2AccountAddress, ]); await settled(); // test that all cta buttons are disabled assert .dom( '[data-test-milestone] [data-test-boxel-action-chin] button[data-test-boxel-button]:not([disabled])' ) .doesNotExist(); assert .dom(cancelationPostableSel(0)) .containsText( 'It looks like you changed accounts in the middle of this workflow. If you still want to create a prepaid card, please restart the workflow.' ); assert.dom(cancelationPostableSel(1)).containsText('Workflow canceled'); assert .dom( '[data-test-workflow-default-cancelation-restart="issue-prepaid-card"]' ) .exists(); }); }); });
the_stack
import { Nullable } from "../../../shared/types"; import * as React from "react"; import { Classes, Tabs, Tab, Tag, Divider, Intent } from "@blueprintjs/core"; import { Observer, Scene, EngineInstrumentation, SceneInstrumentation } from "babylonjs"; import { AbstractEditorPlugin, IEditorPluginProps } from "../../editor/tools/plugin"; export const title = "Stats"; export interface IStatsState { // Common averageFPS?: number; instantaneousFPS?: number; averageFrameTime?: number; instantaneousFrameTime?: number; // Count activeFaces?: number; activeIndices?: number; activeBones?: number; activeParticles?: number; activeMeshes?: number; drawCalls?: number; totalVertices?: number; totalMeshes?: number; totalMaterials?: number; totalTextures?: number; totalLights?: number; // Durations gpuFrameTime?: number; gpuFrameTimeAvarage?: number; absoluteFPS?: number; render?: number; frameTotal?: number; interFrame?: number; meshSelection?: number; renderTargets?: number; animations?: number; particles?: number; physics?: number; } export default class StatsPlugin extends AbstractEditorPlugin<IStatsState> { private _afterRenderObserver: Nullable<Observer<Scene>> = null; private _lastTime: number = 0; private _engineInstrumentation: Nullable<EngineInstrumentation> = null; private _sceneInstrumentation: Nullable<SceneInstrumentation> = null; /** * Constructor. * @param props the component's props. */ public constructor(props: IEditorPluginProps) { super(props); this.state = { }; } /** * Renders the component. */ public render(): React.ReactNode { const common = ( <div> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>FPS</Divider> <Tag key="averageFPS" fill={true} intent={(this.state.averageFPS ?? 60) < 30 ? Intent.WARNING : Intent.PRIMARY}>FPS: {this.state.averageFPS?.toFixed(2)}</Tag> <Tag intent={Intent.PRIMARY} key="instantaneousFPS" fill={true}>Instantaneous FPS: {this.state.instantaneousFPS?.toFixed(2)}</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Frame Time</Divider> <Tag intent={Intent.PRIMARY} key="averageFrameTime" fill={true}>Average Frame Time: {this.state.averageFrameTime?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="instantaneousFrameTime" fill={true}>Instantaneous Frame Time: {this.state.instantaneousFrameTime?.toFixed(2)} ms</Tag> </div> ); const count = ( <div> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Active Vertices</Divider> <Tag intent={Intent.PRIMARY} key="activeFaces" fill={true}>Active Faces: {this.state.activeFaces}</Tag> <Tag intent={Intent.PRIMARY} key="activeIndices" fill={true}>Active Indices: {this.state.activeIndices}</Tag> <Tag intent={Intent.PRIMARY} key="activeBones" fill={true}>Active Bones: {this.state.activeBones}</Tag> <Tag intent={Intent.PRIMARY} key="activeParticles" fill={true}>Active Particles: {this.state.activeParticles}</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Active</Divider> <Tag intent={Intent.PRIMARY} key="activeMeshes" fill={true}>Active Meshes: {this.state.activeMeshes}</Tag> <Tag intent={Intent.PRIMARY} key="drawCalls" fill={true}>Draw Calls: {this.state.drawCalls}</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Total Vertices</Divider> <Tag intent={Intent.PRIMARY} key="totalVertices" fill={true}>Total Vertices: {this.state.totalVertices}</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Total Others</Divider> <Tag intent={Intent.PRIMARY} key="totalMeshes" fill={true}>Total Meshes: {this.state.totalMeshes}</Tag> <Tag intent={Intent.PRIMARY} key="totalMaterials" fill={true}>Total Materials: {this.state.totalMaterials}</Tag> <Tag intent={Intent.PRIMARY} key="totalTextures" fill={true}>Total Textures: {this.state.totalTextures}</Tag> <Tag intent={Intent.PRIMARY} key="totalLights" fill={true}>Total Lights: {this.state.totalLights}</Tag> </div> ); const durations = ( <div> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>GPU</Divider> <Tag intent={Intent.PRIMARY} key="gpuFrameTime" fill={true}>GPU Frame Time: {this.state.gpuFrameTime?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="gpuFrameTimeAvarage" fill={true}>GPU Frame Time (Average): {this.state.gpuFrameTimeAvarage?.toFixed(2)} ms</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Scene</Divider> <Tag intent={Intent.PRIMARY} key="absoluteFPS" fill={true}>Absolute FPS: {this.state.absoluteFPS?.toFixed(0)}</Tag> <Tag intent={Intent.PRIMARY} key="render" fill={true}>Render: {this.state.render} ms</Tag> <Tag intent={Intent.PRIMARY} key="frameTotal" fill={true}>Frame Total: {this.state.frameTotal?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="interFrame" fill={true}>Inter-frame: {this.state.interFrame?.toFixed(2)} ms</Tag> <Divider style={{ backgroundColor: "#333333", borderRadius: "5px", paddingLeft: "3px" }}>Elements</Divider> <Tag intent={Intent.PRIMARY} key="meshSelection" fill={true}>Mesh Selection: {this.state.meshSelection?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="renderTargets" fill={true}>Render Targets: {this.state.renderTargets?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="animations" fill={true}>Animations: {this.state.animations?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="particles" fill={true}>Particles: {this.state.particles?.toFixed(2)} ms</Tag> <Tag intent={Intent.PRIMARY} key="physics" fill={true}>Physics: {this.state.physics?.toFixed(2)} ms</Tag> </div> ); return ( <div key="main-div" className={Classes.FILL} style={{ width: "100%", height: "100%", overflow: "auto" }}> <Tabs key="tabs" animate={true} renderActiveTabPanelOnly={true} vertical={false}> <Tab id="common" key="common-tab" title="Common" panel={common} /> <Tab id="count" key="count-tab" title="Count" panel={count} /> <Tab id="durations" key="durations-tab" title="Durations" panel={durations} /> </Tabs> </div> ); } /** * Called on the plugin is ready. */ public onReady(): void { if (this.editor.isInitialized) { return this._register(); } this.editor.editorInitializedObservable.addOnce(() => this._register()); } /** * Called on the panel has been resized. */ public resize(): void { } /** * Called on the plugin is closed. */ public onClose(): void { this.editor.scene!.onAfterRenderObservable.remove(this._afterRenderObserver); this._engineInstrumentation?.dispose(); this._sceneInstrumentation?.dispose(); } /** * Registers the on after render observable to update stats. */ private _register(): void { this._sceneInstrumentation = new SceneInstrumentation(this.editor.scene!); this._sceneInstrumentation.captureActiveMeshesEvaluationTime = true; this._sceneInstrumentation.captureRenderTargetsRenderTime = true; this._sceneInstrumentation.captureFrameTime = true; this._sceneInstrumentation.captureRenderTime = true; this._sceneInstrumentation.captureInterFrameTime = true; this._sceneInstrumentation.captureParticlesRenderTime = true; this._sceneInstrumentation.captureSpritesRenderTime = true; this._sceneInstrumentation.capturePhysicsTime = true; this._sceneInstrumentation.captureAnimationsTime = true; this._engineInstrumentation = new EngineInstrumentation(this.editor.engine!); this._engineInstrumentation.captureGPUFrameTime = true; this._afterRenderObserver = this.editor.scene!.onAfterRenderObservable.add(() => { this._lastTime += this.editor.engine!.getDeltaTime(); if (this._lastTime < 500) { return; } this._lastTime = 0; const p = this.editor.engine!.performanceMonitor; const s = this.editor.scene!; this.setState({ averageFPS: p.averageFPS, instantaneousFPS: p.instantaneousFPS, averageFrameTime: p.averageFrameTime, instantaneousFrameTime: p.instantaneousFrameTime, activeFaces: s.getActiveIndices() / 3, activeIndices: s.getActiveIndices(), activeBones: s.getActiveBones(), activeParticles: s.getActiveParticles(), activeMeshes: s.getActiveMeshes().length, drawCalls: this._sceneInstrumentation!.drawCallsCounter.current, totalVertices: s.getTotalVertices(), totalMeshes: s.meshes.length, totalMaterials: s.materials.length, totalTextures: s.textures.length, totalLights: s.lights.length, gpuFrameTime: this._engineInstrumentation!.gpuFrameTimeCounter.lastSecAverage * 0.000001, gpuFrameTimeAvarage: this._engineInstrumentation!.gpuFrameTimeCounter.average * 0.000001, absoluteFPS: 1000 / this._sceneInstrumentation!.frameTimeCounter.lastSecAverage, render: this._sceneInstrumentation?.renderTimeCounter.lastSecAverage, frameTotal: this._sceneInstrumentation?.frameTimeCounter.lastSecAverage, interFrame: this._sceneInstrumentation?.interFrameTimeCounter.lastSecAverage, meshSelection: this._sceneInstrumentation?.activeMeshesEvaluationTimeCounter.lastSecAverage, renderTargets: this._sceneInstrumentation?.renderTargetsRenderTimeCounter.lastSecAverage, animations: this._sceneInstrumentation?.animationsTimeCounter.lastSecAverage, particles: this._sceneInstrumentation?.physicsTimeCounter.lastSecAverage, physics: this._sceneInstrumentation?.physicsTimeCounter.lastSecAverage, }); }); } }
the_stack
import { Array } from "@siteimprove/alfa-array"; import { Token, Function, Nth } from "@siteimprove/alfa-css"; import { Element } from "@siteimprove/alfa-dom"; import { Equatable } from "@siteimprove/alfa-equatable"; import { Iterable } from "@siteimprove/alfa-iterable"; import { Serializable } from "@siteimprove/alfa-json"; import { Option, None } from "@siteimprove/alfa-option"; import { Parser } from "@siteimprove/alfa-parser"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Result, Err } from "@siteimprove/alfa-result"; import { Slice } from "@siteimprove/alfa-slice"; import * as dom from "@siteimprove/alfa-dom"; import * as json from "@siteimprove/alfa-json"; import { Context } from "./context"; const { delimited, either, end, flatMap, left, map, mapResult, oneOrMore, option, pair, peek, right, separatedList, take, takeBetween, zeroOrMore, } = Parser; const { and, not, property, equals } = Predicate; const { isElement, hasName } = Element; /** * {@link https://drafts.csswg.org/selectors/#selector} * * @public */ export type Selector = | Selector.Simple | Selector.Compound | Selector.Complex | Selector.Relative | Selector.List; /** * @public */ export namespace Selector { export interface JSON<T extends string = string> { [key: string]: json.JSON; type: T; } abstract class Selector<T extends string = string> implements Iterable<Simple | Compound | Complex | Relative>, Equatable, Serializable { public abstract get type(): T; /** * {@link https://drafts.csswg.org/selectors/#match} */ public abstract matches(element: Element, context?: Context): boolean; public abstract equals(value: Selector): boolean; public abstract equals(value: unknown): value is this; public abstract [Symbol.iterator](): Iterator< Simple | Compound | Complex | Relative >; public abstract toJSON(): JSON; } /** * @remarks * The selector parser is forward-declared as it is needed within its * subparsers. */ let parseSelector: Parser< Slice<Token>, Simple | Compound | Complex | List<Simple | Compound | Complex>, string >; /** * {@link https://drafts.csswg.org/selectors/#id-selector} */ export class Id extends Selector<"id"> { public static of(name: string): Id { return new Id(name); } private readonly _name: string; private constructor(name: string) { super(); this._name = name; } public get name(): string { return this._name; } public get type(): "id" { return "id"; } public matches(element: Element): boolean { return element.id.includes(this._name); } public equals(value: Id): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Id && value._name === this._name; } public *[Symbol.iterator](): Iterator<Id> { yield this; } public toJSON(): Id.JSON { return { type: "id", name: this._name, }; } public toString(): string { return `#${this._name}`; } } export namespace Id { export interface JSON extends Selector.JSON<"id"> { name: string; } } export function isId(value: unknown): value is Id { return value instanceof Id; } /** * {@link https://drafts.csswg.org/selectors/#typedef-id-selector} */ const parseId = map( Token.parseHash((hash) => hash.isIdentifier), (hash) => Id.of(hash.value) ); /** * {@link https://drafts.csswg.org/selectors/#class-selector} */ export class Class extends Selector<"class"> { public static of(name: string): Class { return new Class(name); } private readonly _name: string; private constructor(name: string) { super(); this._name = name; } public get name(): string { return this._name; } public get type(): "class" { return "class"; } public matches(element: Element): boolean { return Iterable.includes(element.classes, this._name); } public equals(value: Class): boolean; public equals(value: unknown): value is this; public equals(value: unknown): value is boolean { return value instanceof Class && value._name === this._name; } public *[Symbol.iterator](): Iterator<Class> { yield this; } public toJSON(): Class.JSON { return { type: "class", name: this._name, }; } public toString(): string { return `.${this._name}`; } } export namespace Class { export interface JSON extends Selector.JSON<"class"> { name: string; } } export function isClass(value: unknown): value is Class { return value instanceof Class; } const parseClass = map( right(Token.parseDelim("."), Token.parseIdent()), (ident) => Class.of(ident.value) ); /** * {@link https://drafts.csswg.org/selectors/#typedef-ns-prefix} */ const parseNamespace = map( left( option(either(Token.parseIdent(), Token.parseDelim("*"))), Token.parseDelim("|") ), (token) => token.map((token) => token.toString()).getOr("") ); /** * {@link https://drafts.csswg.org/selectors/#typedef-wq-name} */ const parseName = pair( option(parseNamespace), map(Token.parseIdent(), (ident) => ident.value) ); /** * {@link https://drafts.csswg.org/selectors/#attribute-selector} */ export class Attribute extends Selector<"attribute"> { public static of( namespace: Option<string>, name: string, value: Option<string> = None, matcher: Option<Attribute.Matcher> = None, modifier: Option<Attribute.Modifier> = None ): Attribute { return new Attribute(namespace, name, value, matcher, modifier); } private readonly _namespace: Option<string>; private readonly _name: string; private readonly _value: Option<string>; private readonly _matcher: Option<Attribute.Matcher>; private readonly _modifier: Option<Attribute.Modifier>; private constructor( namespace: Option<string>, name: string, value: Option<string>, matcher: Option<Attribute.Matcher>, modifier: Option<Attribute.Modifier> ) { super(); this._namespace = namespace; this._name = name; this._value = value; this._matcher = matcher; this._modifier = modifier; } public get namespace(): Option<string> { return this._namespace; } public get type(): "attribute" { return "attribute"; } public get name(): string { return this._name; } public get value(): Option<string> { return this._value; } public get matcher(): Option<Attribute.Matcher> { return this._matcher; } public get modifier(): Option<Attribute.Modifier> { return this._modifier; } public matches(element: Element): boolean { for (const namespace of this._namespace) { let predicate: Predicate<dom.Attribute>; switch (namespace) { case "*": predicate = property("name", equals(this._name)); break; case "": predicate = and( property("name", equals(this._name)), property("namespace", equals(None)) ); break; default: predicate = and( property("name", equals(this._name)), property("namespace", equals(namespace)) ); } return Iterable.some( element.attributes, and(predicate, (attribute) => this.matchesValue(attribute.value)) ); } return element .attribute(this._name) .some((attribute) => this.matchesValue(attribute.value)); } private matchesValue(value: string): boolean { for (const modifier of this._modifier) { switch (modifier) { case Attribute.Modifier.CaseInsensitive: value = value.toLowerCase(); } } for (const match of this._value) { switch (this._matcher.getOr(Attribute.Matcher.Equal)) { case Attribute.Matcher.Equal: return value === match; case Attribute.Matcher.Prefix: return value.startsWith(match); case Attribute.Matcher.Suffix: return value.endsWith(match); case Attribute.Matcher.Substring: return value.includes(match); case Attribute.Matcher.DashMatch: return value === match || value.startsWith(`${match}-`); case Attribute.Matcher.Includes: return value.split(/\s+/).some(equals(match)); } } return true; } public equals(value: Attribute): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Attribute && value._namespace.equals(this._namespace) && value._name === this._name && value._value.equals(this._value) && value._matcher.equals(this._matcher) && value._modifier.equals(this._modifier) ); } public *[Symbol.iterator](): Iterator<Attribute> { yield this; } public toJSON(): Attribute.JSON { return { type: "attribute", namespace: this._namespace.getOr(null), name: this._name, value: this._value.getOr(null), matcher: this._matcher.getOr(null), modifier: this._modifier.getOr(null), }; } public toString(): string { const namespace = this._namespace .map((namespace) => `${namespace}|`) .getOr(""); const value = this._value .map((value) => `"${JSON.stringify(value)}"`) .get(); const matcher = this._matcher.getOr(""); const modifier = this._modifier .map((modifier) => ` ${modifier}`) .getOr(""); return `[${namespace}${this._name}${matcher}${value}${modifier}]`; } } export namespace Attribute { export interface JSON extends Selector.JSON<"attribute"> { namespace: string | null; name: string; value: string | null; matcher: string | null; modifier: string | null; } export enum Matcher { /** * @example [foo=bar] */ Equal = "=", /** * @example [foo~=bar] */ Includes = "~=", /** * @example [foo|=bar] */ DashMatch = "|=", /** * @example [foo^=bar] */ Prefix = "^=", /** * @example [foo$=bar] */ Suffix = "$=", /** * @example [foo*=bar] */ Substring = "*=", } export enum Modifier { /** * @example [foo=bar i] */ CaseInsensitive = "i", /** * @example [foo=Bar s] */ CaseSensitive = "s", } } export function isAttribute(value: unknown): value is Attribute { return value instanceof Attribute; } /** * {@link https://drafts.csswg.org/selectors/#typedef-attr-matcher} */ const parseMatcher = map( left( option( either( Token.parseDelim("~"), either( Token.parseDelim("|"), either( Token.parseDelim("^"), either(Token.parseDelim("$"), Token.parseDelim("*")) ) ) ) ), Token.parseDelim("=") ), (delim) => delim.isNone() ? Attribute.Matcher.Equal : (`${delim.get()}=` as Attribute.Matcher) ); /** * {@link https://drafts.csswg.org/selectors/#typedef-attr-modifier} */ const parseModifier = either( map(Token.parseIdent("i"), () => Attribute.Modifier.CaseInsensitive), map(Token.parseIdent("s"), () => Attribute.Modifier.CaseSensitive) ); /** * {@link https://drafts.csswg.org/selectors/#typedef-attribute-selector} */ const parseAttribute = map( delimited( Token.parseOpenSquareBracket, pair( parseName, option( pair( pair(parseMatcher, either(Token.parseString(), Token.parseIdent())), delimited(option(Token.parseWhitespace), option(parseModifier)) ) ) ), Token.parseCloseSquareBracket ), (result) => { const [[namespace, name], rest] = result; if (rest.isNone()) { return Attribute.of(namespace, name); } const [[matcher, value], modifier] = rest.get(); return Attribute.of( namespace, name, Option.of(value.value), Option.of(matcher), modifier ); } ); /** * {@link https://drafts.csswg.org/selectors/#type-selector} */ export class Type extends Selector<"type"> { public static of(namespace: Option<string>, name: string): Type { return new Type(namespace, name); } private readonly _namespace: Option<string>; private readonly _name: string; private constructor(namespace: Option<string>, name: string) { super(); this._namespace = namespace; this._name = name; } public get namespace(): Option<string> { return this._namespace; } public get name(): string { return this._name; } public get type(): "type" { return "type"; } public matches(element: Element): boolean { if (this._name !== element.name) { return false; } if (this._namespace.isNone() || this._namespace.includes("*")) { return true; } return element.namespace.equals(this._namespace); } public equals(value: Type): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Type && value._namespace.equals(this._namespace) && value._name === this._name ); } public *[Symbol.iterator](): Iterator<Type> { yield this; } public toJSON(): Type.JSON { return { type: "type", namespace: this._namespace.getOr(null), name: this._name, }; } public toString(): string { const namespace = this._namespace .map((namespace) => `${namespace}|`) .getOr(""); return `${namespace}${this._name}`; } } export namespace Type { export interface JSON extends Selector.JSON<"type"> { namespace: string | null; name: string; } } export function isType(value: unknown): value is Type { return value instanceof Type; } /** * {@link https://drafts.csswg.org/selectors/#typedef-type-selector} */ const parseType = map(parseName, ([namespace, name]) => Type.of(namespace, name) ); /** * {@link https://drafts.csswg.org/selectors/#universal-selector} */ export class Universal extends Selector<"universal"> { public static of(namespace: Option<string>): Universal { return new Universal(namespace); } private static readonly _empty = new Universal(None); public static empty(): Universal { return this._empty; } private readonly _namespace: Option<string>; private constructor(namespace: Option<string>) { super(); this._namespace = namespace; } public get namespace(): Option<string> { return this._namespace; } public get type(): "universal" { return "universal"; } public matches(element: Element): boolean { if (this._namespace.isNone() || this._namespace.includes("*")) { return true; } return element.namespace.equals(this._namespace); } public equals(value: Universal): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Universal && value._namespace.equals(this._namespace) ); } public *[Symbol.iterator](): Iterator<Universal> { yield this; } public toJSON(): Universal.JSON { return { type: "universal", namespace: this._namespace.getOr(null), }; } public toString(): string { const namespace = this._namespace .map((namespace) => `${namespace}|`) .getOr(""); return `${namespace}*`; } } export namespace Universal { export interface JSON extends Selector.JSON<"universal"> { namespace: string | null; } } function isUniversal(value: unknown): value is Universal { return value instanceof Universal; } /** * {@link https://drafts.csswg.org/selectors/#typedef-type-selector} */ const parseUniversal = map( left(option(parseNamespace), Token.parseDelim("*")), (namespace) => Universal.of(namespace) ); export namespace Pseudo { export type JSON = Class.JSON | Element.JSON; export abstract class Class< N extends string = string > extends Selector<"pseudo-class"> { protected readonly _name: N; protected constructor(name: N) { super(); this._name = name; } public get name(): N { return this._name; } public get type(): "pseudo-class" { return "pseudo-class"; } public matches(element: dom.Element, context?: Context): boolean { return false; } public equals(value: Class): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Class && value._name === this._name; } public *[Symbol.iterator](): Iterator<Class> { yield this; } public toJSON(): Class.JSON<N> { return { type: "pseudo-class", name: this._name, }; } public toString(): string { return `:${this._name}`; } } export namespace Class { export interface JSON<N extends string = string> extends Selector.JSON<"pseudo-class"> { name: N; } } export function isClass(value: unknown): value is Class { return value instanceof Class; } export abstract class Element< N extends string = string > extends Selector<"pseudo-element"> { protected readonly _name: N; protected constructor(name: N) { super(); this._name = name; } public get name(): N { return this._name; } public get type(): "pseudo-element" { return "pseudo-element"; } public matches(element: dom.Element, context?: Context): boolean { return false; } public equals(value: Element): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Element && value._name === this._name; } public *[Symbol.iterator](): Iterator<Element> { yield this; } public toJSON(): Element.JSON<N> { return { type: "pseudo-element", name: this._name, }; } public toString(): string { return `::${this._name}`; } } export namespace Element { export interface JSON<N extends string = string> extends Selector.JSON<"pseudo-element"> { name: N; } } export function isElement(value: unknown): value is Element { return value instanceof Element; } } export type Pseudo = Pseudo.Class | Pseudo.Element; export const { isClass: isPseudoClass, isElement: isPseudoElement } = Pseudo; export function isPseudo(value: unknown): value is Pseudo { return isPseudoClass(value) || isPseudoElement(value); } const parseNth = left( Nth.parse, end((token) => `Unexpected token ${token}`) ); const parsePseudoClass = right( Token.parseColon, either( // Non-functional pseudo-classes mapResult(Token.parseIdent(), (ident) => { switch (ident.value) { case "hover": return Result.of(Hover.of() as Pseudo.Class); case "active": return Result.of(Active.of()); case "focus": return Result.of(Focus.of()); case "focus-within": return Result.of(FocusWithin.of()); case "focus-visible": return Result.of(FocusVisible.of()); case "link": return Result.of(Link.of()); case "visited": return Result.of(Visited.of()); case "root": return Result.of(Root.of()); case "empty": return Result.of(Empty.of()); case "first-child": return Result.of(FirstChild.of()); case "last-child": return Result.of(LastChild.of()); case "only-child": return Result.of(OnlyChild.of()); case "first-of-type": return Result.of(FirstOfType.of()); case "last-of-type": return Result.of(LastOfType.of()); case "only-of-type": return Result.of(OnlyOfType.of()); } return Err.of(`Unknown pseudo-class :${ident.value}`); }), // Funtional pseudo-classes mapResult(right(peek(Token.parseFunction()), Function.consume), (fn) => { const { name } = fn; const tokens = Slice.of(fn.value); switch (name) { // :<name>(<selector-list>) // :has() normally only accepts relative selectors, we currently // accept all. case "is": case "not": case "has": return parseSelector(tokens).map(([, selector]) => { switch (name) { case "is": return Is.of(selector) as Pseudo.Class; case "not": return Not.of(selector); case "has": return Has.of(selector); } }); // :<name>(<an+b>) case "nth-child": case "nth-last-child": case "nth-of-type": case "nth-last-of-type": return parseNth(tokens).map(([, nth]) => { switch (name) { case "nth-child": return NthChild.of(nth); case "nth-last-child": return NthLastChild.of(nth); case "nth-of-type": return NthOfType.of(nth); case "nth-last-of-type": return NthLastOfType.of(nth); } }); } return Err.of(`Unknown pseudo-class :${fn.name}()`); }) ) ); const parsePseudoElement = either( // Functional pseudo-elements need to be first because ::cue and // ::cue-region can be both functional and non-functional, so we want to // fail them as functional before testing them as non-functional. right( take(Token.parseColon, 2), mapResult(right(peek(Token.parseFunction()), Function.consume), (fn) => { const { name } = fn; const tokens = Slice.of(fn.value); switch (name) { case "cue": case "cue-region": return parseSelector(tokens).map(([, selector]) => name === "cue" ? (Cue.of(selector) as Pseudo.Element) : CueRegion.of(selector) ); case "part": return separatedList( Token.parseIdent(), Token.parseWhitespace )(tokens).map(([, idents]) => Part.of(idents)); case "slotted": return separatedList( parseCompound, Token.parseWhitespace )(tokens).map(([, selectors]) => Slotted.of(selectors)); } return Err.of(`Unknown pseudo-element ::${name}()`); }) ), // Non-functional pseudo-elements flatMap( map(takeBetween(Token.parseColon, 1, 2), (colons) => colons.length), (colons) => mapResult(Token.parseIdent(), (ident) => { if (colons === 1) { switch (ident.value) { // Legacy pseudo-elements must be accepted with both a single and // double colon. case "after": case "before": case "first-letter": case "first-line": break; default: return Err.of( `This pseudo-element is not allowed with single colon: ::${ident.value}` ); } } switch (ident.value) { case "after": return Result.of(After.of() as Pseudo.Element); case "backdrop": return Result.of(Backdrop.of()); case "before": return Result.of(Before.of()); case "cue": return Result.of(Cue.of()); case "cue-region": return Result.of(CueRegion.of()); case "file-selector-button": return Result.of(FileSelectorButton.of()); case "first-letter": return Result.of(FirstLetter.of()); case "first-line": return Result.of(FirstLine.of()); case "grammar-error": return Result.of(GrammarError.of()); case "marker": return Result.of(Marker.of()); case "placeholder": return Result.of(Placeholder.of()); case "selection": return Result.of(Selection.of()); case "spelling-error": return Result.of(SpellingError.of()); case "target-text": return Result.of(TargetText.of()); } return Err.of(`Unknown pseudo-element ::${ident.value}`); }) ) ); const parsePseudo = either(parsePseudoClass, parsePseudoElement); /** * {@link https://drafts.csswg.org/selectors/#matches-pseudo} */ export class Is extends Pseudo.Class<"is"> { public static of( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ): Is { return new Is(selector); } private readonly _selector: | Simple | Compound | Complex | List<Simple | Compound | Complex>; private constructor( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ) { super("is"); this._selector = selector; } public get selector(): | Simple | Compound | Complex | List<Simple | Compound | Complex> { return this._selector; } public matches(element: Element, context?: Context): boolean { return this._selector.matches(element, context); } public equals(value: Is): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Is && value._selector.equals(this._selector); } public toJSON(): Is.JSON { return { ...super.toJSON(), selector: this._selector.toJSON(), }; } public toString(): string { return `:${this.name}(${this._selector})`; } } export namespace Is { export interface JSON extends Pseudo.Class.JSON<"is"> { selector: Simple.JSON | Compound.JSON | Complex.JSON | List.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#negation-pseudo} */ export class Not extends Pseudo.Class<"not"> { public static of( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ): Not { return new Not(selector); } private readonly _selector: | Simple | Compound | Complex | List<Simple | Compound | Complex>; private constructor( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ) { super("not"); this._selector = selector; } public get selector(): | Simple | Compound | Complex | List<Simple | Compound | Complex> { return this._selector; } public matches(element: Element, context?: Context): boolean { return !this._selector.matches(element, context); } public equals(value: Not): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Not && value._selector.equals(this._selector); } public toJSON(): Not.JSON { return { ...super.toJSON(), selector: this._selector.toJSON(), }; } public toString(): string { return `:${this.name}(${this._selector})`; } } export namespace Not { export interface JSON extends Pseudo.Class.JSON<"not"> { selector: Simple.JSON | Compound.JSON | Complex.JSON | List.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#has-pseudo} */ export class Has extends Pseudo.Class<"has"> { public static of( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ): Has { return new Has(selector); } private readonly _selector: | Simple | Compound | Complex | List<Simple | Compound | Complex>; private constructor( selector: Simple | Compound | Complex | List<Simple | Compound | Complex> ) { super("has"); this._selector = selector; } public get selector(): | Simple | Compound | Complex | List<Simple | Compound | Complex> { return this._selector; } public equals(value: Has): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Has && value._selector.equals(this._selector); } public toJSON(): Has.JSON { return { ...super.toJSON(), selector: this._selector.toJSON(), }; } public toString(): string { return `:${this.name}(${this._selector})`; } } export namespace Has { export interface JSON extends Pseudo.Class.JSON<"has"> { selector: Simple.JSON | Compound.JSON | Complex.JSON | List.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#hover-pseudo} */ export class Hover extends Pseudo.Class<"hover"> { public static of(): Hover { return new Hover(); } private constructor() { super("hover"); } public matches( element: Element, context: Context = Context.empty() ): boolean { return context.isHovered(element); } } /** * {@link https://drafts.csswg.org/selectors/#active-pseudo} */ export class Active extends Pseudo.Class<"active"> { public static of(): Active { return new Active(); } private constructor() { super("active"); } public matches( element: Element, context: Context = Context.empty() ): boolean { return context.isActive(element); } } /** * {@link https://drafts.csswg.org/selectors/#focus-pseudo} */ export class Focus extends Pseudo.Class<"focus"> { public static of(): Focus { return new Focus(); } private constructor() { super("focus"); } public matches( element: Element, context: Context = Context.empty() ): boolean { return context.isFocused(element); } } /** * {@link https://drafts.csswg.org/selectors/#focus-within-pseudo} */ export class FocusWithin extends Pseudo.Class<"focus-within"> { public static of(): FocusWithin { return new FocusWithin(); } private constructor() { super("focus-within"); } public matches( element: Element, context: Context = Context.empty() ): boolean { return element .inclusiveDescendants({ flattened: true }) .filter(isElement) .some((element) => context.isFocused(element)); } } /** * {@link https://drafts.csswg.org/selectors/#focus-visible-pseudo} */ export class FocusVisible extends Pseudo.Class<"focus-visible"> { public static of(): FocusVisible { return new FocusVisible(); } private constructor() { super("focus-visible"); } public matches(): boolean { // For the purposes of accessibility testing, we currently assume that // focus related styling can safely be "hidden" behind the :focus-visible // pseudo-class and it will therefore always match. return true; } } /** * {@link https://drafts.csswg.org/selectors/#link-pseudo} */ export class Link extends Pseudo.Class<"link"> { public static of(): Link { return new Link(); } private constructor() { super("link"); } public matches( element: Element, context: Context = Context.empty() ): boolean { switch (element.name) { case "a": case "area": case "link": return element .attribute("href") .some(() => !context.hasState(element, Context.State.Visited)); } return false; } } /** * {@link https://drafts.csswg.org/selectors/#visited-pseudo} */ export class Visited extends Pseudo.Class<"visited"> { public static of(): Visited { return new Visited(); } private constructor() { super("visited"); } public matches( element: Element, context: Context = Context.empty() ): boolean { switch (element.name) { case "a": case "area": case "link": return element .attribute("href") .some(() => context.hasState(element, Context.State.Visited)); } return false; } } /** * {@link https://drafts.csswg.org/selectors/#root-pseudo} */ export class Root extends Pseudo.Class<"root"> { public static of(): Root { return new Root(); } private constructor() { super("root"); } public matches(element: Element): boolean { // The root element is the element whose parent is NOT itself an element. return element.parent().every(not(isElement)); } } /** * {@link https://drafts.csswg.org/selectors/#empty-pseudo} */ export class Empty extends Pseudo.Class<"empty"> { public static of(): Empty { return new Empty(); } private constructor() { super("empty"); } public matches(element: Element): boolean { return element.children().isEmpty(); } } /** * {@link https://drafts.csswg.org/selectors/#nth-child-pseudo} */ export class NthChild extends Pseudo.Class<"nth-child"> { public static of(index: Nth): NthChild { return new NthChild(index); } private static readonly _indices = new WeakMap<Element, number>(); private readonly _index: Nth; private constructor(index: Nth) { super("nth-child"); this._index = index; } public matches(element: Element): boolean { const indices = NthChild._indices; if (!indices.has(element)) { element .inclusiveSiblings() .filter(isElement) .forEach((element, i) => { indices.set(element, i + 1); }); } return this._index.matches(indices.get(element)!); } public equals(value: NthChild): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof NthChild && value._index.equals(this._index); } public toJSON(): NthChild.JSON { return { ...super.toJSON(), index: this._index.toJSON(), }; } public toString(): string { return `:${this.name}(${this._index})`; } } export namespace NthChild { export interface JSON extends Pseudo.Class.JSON<"nth-child"> { index: Nth.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#nth-last-child-pseudo} */ export class NthLastChild extends Pseudo.Class<"nth-last-child"> { public static of(index: Nth): NthLastChild { return new NthLastChild(index); } private static readonly _indices = new WeakMap<Element, number>(); private readonly _index: Nth; private constructor(nth: Nth) { super("nth-last-child"); this._index = nth; } public matches(element: Element): boolean { const indices = NthLastChild._indices; if (!indices.has(element)) { element .inclusiveSiblings() .filter(isElement) .reverse() .forEach((element, i) => { indices.set(element, i + 1); }); } return this._index.matches(indices.get(element)!); } public equals(value: NthLastChild): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof NthLastChild && value._index.equals(this._index); } public toJSON(): NthLastChild.JSON { return { ...super.toJSON(), index: this._index.toJSON(), }; } public toString(): string { return `:${this.name}(${this._index})`; } } export namespace NthLastChild { export interface JSON extends Pseudo.Class.JSON<"nth-last-child"> { index: Nth.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#first-child-pseudo} */ export class FirstChild extends Pseudo.Class<"first-child"> { public static of(): FirstChild { return new FirstChild(); } private constructor() { super("first-child"); } public matches(element: Element): boolean { return element .inclusiveSiblings() .filter(isElement) .first() .includes(element); } } /** * {@link https://drafts.csswg.org/selectors/#last-child-pseudo} */ export class LastChild extends Pseudo.Class<"last-child"> { public static of(): LastChild { return new LastChild(); } private constructor() { super("last-child"); } public matches(element: Element): boolean { return element .inclusiveSiblings() .filter(isElement) .last() .includes(element); } } /** * {@link https://drafts.csswg.org/selectors/#only-child-pseudo} */ export class OnlyChild extends Pseudo.Class<"only-child"> { public static of(): OnlyChild { return new OnlyChild(); } private constructor() { super("only-child"); } public matches(element: Element): boolean { return element.inclusiveSiblings().filter(isElement).size === 1; } } /** * {@link https://drafts.csswg.org/selectors/#nth-of-type-pseudo} */ export class NthOfType extends Pseudo.Class<"nth-of-type"> { public static of(index: Nth): NthOfType { return new NthOfType(index); } private static readonly _indices = new WeakMap<Element, number>(); private readonly _index: Nth; private constructor(index: Nth) { super("nth-of-type"); this._index = index; } public matches(element: Element): boolean { const indices = NthOfType._indices; if (!indices.has(element)) { element .inclusiveSiblings() .filter(isElement) .filter(hasName(element.name)) .forEach((element, i) => { indices.set(element, i + 1); }); } return this._index.matches(indices.get(element)!); } public equals(value: NthOfType): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof NthOfType && value._index.equals(this._index); } public toJSON(): NthOfType.JSON { return { ...super.toJSON(), index: this._index.toJSON(), }; } public toString(): string { return `:${this.name}(${this._index})`; } } export namespace NthOfType { export interface JSON extends Pseudo.Class.JSON<"nth-of-type"> { index: Nth.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#nth-last-of-type-pseudo} */ export class NthLastOfType extends Pseudo.Class<"nth-last-of-type"> { public static of(index: Nth): NthLastOfType { return new NthLastOfType(index); } private static readonly _indices = new WeakMap<Element, number>(); private readonly _index: Nth; private constructor(index: Nth) { super("nth-last-of-type"); this._index = index; } public matches(element: Element): boolean { const indices = NthLastOfType._indices; if (!indices.has(element)) { element .inclusiveSiblings() .filter(isElement) .filter(hasName(element.name)) .reverse() .forEach((element, i) => { indices.set(element, i + 1); }); } return this._index.matches(indices.get(element)!); } public equals(value: NthLastOfType): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof NthLastOfType && value._index.equals(this._index); } public toJSON(): NthLastOfType.JSON { return { ...super.toJSON(), index: this._index.toJSON(), }; } public toString(): string { return `:${this.name}(${this._index})`; } } export namespace NthLastOfType { export interface JSON extends Pseudo.Class.JSON<"nth-last-of-type"> { index: Nth.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#first-of-type-pseudo} */ export class FirstOfType extends Pseudo.Class<"first-of-type"> { public static of(): FirstOfType { return new FirstOfType(); } private constructor() { super("first-of-type"); } public matches(element: Element): boolean { return element .inclusiveSiblings() .filter(isElement) .filter(hasName(element.name)) .first() .includes(element); } } /** * {@link https://drafts.csswg.org/selectors/#last-of-type-pseudo} */ export class LastOfType extends Pseudo.Class<"last-of-type"> { public static of(): LastOfType { return new LastOfType(); } private constructor() { super("last-of-type"); } public matches(element: Element): boolean { return element .inclusiveSiblings() .filter(isElement) .filter(hasName(element.name)) .last() .includes(element); } } /** * {@link https://drafts.csswg.org/selectors/#only-of-type-pseudo} */ export class OnlyOfType extends Pseudo.Class<"only-of-type"> { public static of(): OnlyOfType { return new OnlyOfType(); } private constructor() { super("only-of-type"); } public matches(element: Element): boolean { return ( element .inclusiveSiblings() .filter(isElement) .filter(hasName(element.name)).size === 1 ); } } /** * {@link https://drafts.csswg.org/css-pseudo/#selectordef-after} */ export class After extends Pseudo.Element<"after"> { public static of(): After { return new After(); } private constructor() { super("after"); } } /** * {@link https://fullscreen.spec.whatwg.org/#::backdrop-pseudo-element} */ export class Backdrop extends Pseudo.Element<"backdrop"> { public static of(): Backdrop { return new Backdrop(); } private constructor() { super("backdrop"); } } /** * {@link https://drafts.csswg.org/css-pseudo/#selectordef-before} */ export class Before extends Pseudo.Element<"before"> { public static of(): Before { return new Before(); } private constructor() { super("before"); } } /** * {@link https://w3c.github.io/webvtt/#the-cue-pseudo-element} */ class Cue extends Pseudo.Element<"cue"> { public static of(selector?: Selector): Cue { return new Cue(Option.from(selector)); } private readonly _selector: Option<Selector>; private constructor(selector: Option<Selector>) { super("cue"); this._selector = selector; } public get selector(): Option<Selector> { return this._selector; } public equals(value: Cue): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Cue && value.selector.equals(this.selector); } public toJSON(): Cue.JSON { return { ...super.toJSON(), selector: this._selector.toJSON(), }; } public toString(): string { return `::${this.name}` + this._selector.isSome() ? `(${this._selector})` : ""; } } export namespace Cue { export interface JSON extends Pseudo.Element.JSON<"cue"> { selector: Option.JSON<Selector>; } } /** * {@link https://w3c.github.io/webvtt/#the-cue-region-pseudo-element} */ class CueRegion extends Pseudo.Element<"cue-region"> { public static of(selector?: Selector): CueRegion { return new CueRegion(Option.from(selector)); } private readonly _selector: Option<Selector>; private constructor(selector: Option<Selector>) { super("cue-region"); this._selector = selector; } public get selector(): Option<Selector> { return this._selector; } public equals(value: CueRegion): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof CueRegion && value.selector.equals(this.selector); } public toJSON(): CueRegion.JSON { return { ...super.toJSON(), selector: this._selector.toJSON(), }; } public toString(): string { return `::${this.name}` + this._selector.isSome() ? `(${this._selector})` : ""; } } export namespace CueRegion { export interface JSON extends Pseudo.Element.JSON<"cue-region"> { selector: Option.JSON<Selector>; } } /** *{@link https://drafts.csswg.org/css-pseudo-4/#file-selector-button-pseudo} */ export class FileSelectorButton extends Pseudo.Element<"file-selector-button"> { public static of(): FileSelectorButton { return new FileSelectorButton(); } private constructor() { super("file-selector-button"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#first-letter-pseudo} */ export class FirstLetter extends Pseudo.Element<"first-letter"> { public static of(): FirstLetter { return new FirstLetter(); } private constructor() { super("first-letter"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#first-line-pseudo} */ export class FirstLine extends Pseudo.Element<"first-line"> { public static of(): FirstLine { return new FirstLine(); } private constructor() { super("first-line"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#selectordef-grammar-error} */ export class GrammarError extends Pseudo.Element<"grammar-error"> { public static of(): GrammarError { return new GrammarError(); } private constructor() { super("grammar-error"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#marker-pseudo} */ export class Marker extends Pseudo.Element<"marker"> { public static of(): Marker { return new Marker(); } private constructor() { super("marker"); } } /** * {@link https://drafts.csswg.org/css-shadow-parts-1/#part} */ export class Part extends Pseudo.Element<"part"> { public static of(idents: Iterable<Token.Ident>): Part { return new Part(Array.from(idents)); } private readonly _idents: ReadonlyArray<Token.Ident>; private constructor(idents: Array<Token.Ident>) { super("part"); this._idents = idents; } public get idents(): Iterable<Token.Ident> { return this._idents; } public equals(value: Part): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return value instanceof Part && Array.equals(value._idents, this._idents); } public toJSON(): Part.JSON { return { ...super.toJSON(), idents: Array.toJSON(this._idents), }; } public toString(): string { return `::${this.name}(${this._idents})`; } } export namespace Part { export interface JSON extends Pseudo.Element.JSON<"part"> { idents: Array<Token.Ident.JSON>; } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#placeholder-pseudo} */ export class Placeholder extends Pseudo.Element<"placeholder"> { public static of(): Placeholder { return new Placeholder(); } private constructor() { super("placeholder"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#selectordef-selection} */ export class Selection extends Pseudo.Element<"selection"> { public static of(): Selection { return new Selection(); } private constructor() { super("selection"); } } /** * {@link https://drafts.csswg.org/css-scoping/#slotted-pseudo} */ export class Slotted extends Pseudo.Element<"slotted"> { public static of(selectors: Iterable<Simple | Compound>): Slotted { return new Slotted(Array.from(selectors)); } private readonly _selectors: ReadonlyArray<Simple | Compound>; private constructor(selectors: Array<Simple | Compound>) { super("slotted"); this._selectors = selectors; } public get selectors(): Iterable<Simple | Compound> { return this._selectors; } public equals(value: Slotted): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Slotted && Array.equals(value._selectors, this._selectors) ); } public toJSON(): Slotted.JSON { return { ...super.toJSON(), selectors: Array.toJSON(this._selectors), }; } public toString(): string { return `::${this.name}(${this._selectors})`; } } export namespace Slotted { export interface JSON extends Pseudo.Element.JSON<"slotted"> { selectors: Array<Simple.JSON | Compound.JSON>; } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#selectordef-spelling-error} */ export class SpellingError extends Pseudo.Element<"spelling-error"> { public static of(): SpellingError { return new SpellingError(); } private constructor() { super("spelling-error"); } } /** * {@link https://drafts.csswg.org/css-pseudo-4/#selectordef-target-text} */ export class TargetText extends Pseudo.Element<"target-text"> { public static of(): TargetText { return new TargetText(); } private constructor() { super("target-text"); } } /** * {@link https://drafts.csswg.org/selectors/#simple} */ export type Simple = Type | Universal | Attribute | Class | Id | Pseudo; export namespace Simple { export type JSON = | Type.JSON | Universal.JSON | Attribute.JSON | Class.JSON | Id.JSON | Pseudo.JSON; } export function isSimple(value: unknown): value is Simple { return ( isType(value) || isUniversal(value) || isAttribute(value) || isClass(value) || isId(value) || isPseudo(value) ); } /** * {@link https://drafts.csswg.org/selectors/#typedef-simple-selector} */ const parseSimple = either( parseClass, either( parseType, either( parseAttribute, either(parseId, either(parseUniversal, parsePseudo)) ) ) ); /** * {@link https://drafts.csswg.org/selectors/#compound} */ export class Compound extends Selector<"compound"> { public static of(left: Simple, right: Simple | Compound): Compound { return new Compound(left, right); } private readonly _left: Simple; private readonly _right: Simple | Compound; private constructor(left: Simple, right: Simple | Compound) { super(); this._left = left; this._right = right; } public get left(): Simple { return this._left; } public get right(): Simple | Compound { return this._right; } public get type(): "compound" { return "compound"; } public matches(element: Element, context?: Context): boolean { return ( this._left.matches(element, context) && this._right.matches(element, context) ); } public equals(value: Compound): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Compound && value._left.equals(this._left) && value._right.equals(this._right) ); } public *[Symbol.iterator](): Iterator<Compound> { yield this; } public toJSON(): Compound.JSON { return { type: "compound", left: this._left.toJSON(), right: this._right.toJSON(), }; } public toString(): string { return `${this._left}${this._right}`; } } export namespace Compound { export interface JSON extends Selector.JSON<"compound"> { left: Simple.JSON; right: Simple.JSON | JSON; } } export function isCompound(value: unknown): value is Compound { return value instanceof Compound; } /** * {@link https://drafts.csswg.org/selectors/#typedef-compound-selector} */ const parseCompound: Parser<Slice<Token>, Simple | Compound, string> = map( oneOrMore(parseSimple), (result) => { const [left, ...selectors] = Iterable.reverse(result); return Iterable.reduce( selectors, (right, left) => Compound.of(left, right), left as Simple | Compound ); } ); /** * {@link https://drafts.csswg.org/selectors/#selector-combinator} */ export enum Combinator { /** * @example div span */ Descendant = " ", /** * @example div \> span */ DirectDescendant = ">", /** * @example div ~ span */ Sibling = "~", /** * @example div + span */ DirectSibling = "+", } /** * {@link https://drafts.csswg.org/selectors/#typedef-combinator} */ const parseCombinator = either( delimited( option(Token.parseWhitespace), either( map(Token.parseDelim(">"), () => Combinator.DirectDescendant), either( map(Token.parseDelim("~"), () => Combinator.Sibling), map(Token.parseDelim("+"), () => Combinator.DirectSibling) ) ) ), map(Token.parseWhitespace, () => Combinator.Descendant) ); /** * {@link https://drafts.csswg.org/selectors/#complex} */ export class Complex extends Selector<"complex"> { public static of( combinator: Combinator, left: Simple | Compound | Complex, right: Simple | Compound ): Complex { return new Complex(combinator, left, right); } private readonly _combinator: Combinator; private readonly _left: Simple | Compound | Complex; private readonly _right: Simple | Compound; private constructor( combinator: Combinator, left: Simple | Compound | Complex, right: Simple | Compound ) { super(); this._combinator = combinator; this._left = left; this._right = right; } public get combinator(): Combinator { return this._combinator; } public get left(): Simple | Compound | Complex { return this._left; } public get right(): Simple | Compound { return this._right; } public get type(): "complex" { return "complex"; } public matches(element: Element, context?: Context): boolean { // First, make sure that the right side of the selector, i.e. the part // that relates to the current element, matches. if (this._right.matches(element, context)) { // If it does, move on to the heavy part of the work: Looking either up // the tree for a descendant match or looking to the side of the tree // for a sibling match. switch (this._combinator) { case Combinator.Descendant: return element .ancestors() .filter(isElement) .some((element) => this._left.matches(element, context)); case Combinator.DirectDescendant: return element .parent() .filter(isElement) .some((element) => this._left.matches(element, context)); case Combinator.Sibling: return element .preceding() .filter(isElement) .some((element) => this._left.matches(element, context)); case Combinator.DirectSibling: return element .preceding() .find(isElement) .some((element) => this._left.matches(element, context)); } } return false; } public equals(value: Complex): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Complex && value._combinator === this._combinator && value._left.equals(this._left) && value._right.equals(this._right) ); } public *[Symbol.iterator](): Iterator<Complex> { yield this; } public toJSON(): Complex.JSON { return { type: "complex", combinator: this._combinator, left: this._left.toJSON(), right: this._right.toJSON(), }; } public toString(): string { const combinator = this._combinator === Combinator.Descendant ? " " : ` ${this._combinator} `; return `${this._left}${combinator}${this._right}`; } } export namespace Complex { export interface JSON extends Selector.JSON<"complex"> { combinator: string; left: Simple.JSON | Compound.JSON | JSON; right: Simple.JSON | Compound.JSON; } } export function isComplex(value: unknown): value is Complex { return value instanceof Complex; } /** * {@link https://drafts.csswg.org/selectors/#typedef-complex-selector} */ const parseComplex = map( pair(parseCompound, zeroOrMore(pair(parseCombinator, parseCompound))), (result) => { const [left, selectors] = result; return Iterable.reduce( selectors, (left, [combinator, right]) => Complex.of(combinator, left, right), left as Simple | Compound | Complex ); } ); /** * {@link https://drafts.csswg.org/selectors/#relative-selector} */ export class Relative extends Selector<"relative"> { public static of( combinator: Combinator, selector: Simple | Compound | Complex ): Relative { return new Relative(combinator, selector); } private readonly _combinator: Combinator; private readonly _selector: Simple | Compound | Complex; private constructor( combinator: Combinator, selector: Simple | Compound | Complex ) { super(); this._combinator = combinator; this._selector = selector; } public get combinator(): Combinator { return this._combinator; } public get selector(): Simple | Compound | Complex { return this._selector; } public get type(): "relative" { return "relative"; } public matches(): boolean { return false; } public equals(value: Relative): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof Relative && value._combinator === this._combinator && value._selector.equals(this._selector) ); } public *[Symbol.iterator](): Iterator<Relative> { yield this; } public toJSON(): Relative.JSON { return { type: "relative", combinator: this._combinator, selector: this._selector.toJSON(), }; } public toString(): string { const combinator = this._combinator === Combinator.Descendant ? "" : `${this._combinator} `; return `${combinator}${this._selector}`; } } export namespace Relative { export interface JSON extends Selector.JSON<"relative"> { combinator: string; selector: Simple.JSON | Compound.JSON | Complex.JSON; } } /** * {@link https://drafts.csswg.org/selectors/#typedef-relative-selector} */ // const parseRelative = map(pair(parseCombinator, parseComplex), (result) => { // const [combinator, selector] = result; // return Relative.of(combinator, selector); // }); /** * {@link https://drafts.csswg.org/selectors/#selector-list} */ export class List< T extends Simple | Compound | Complex | Relative = | Simple | Compound | Complex | Relative > extends Selector<"list"> { public static of<T extends Simple | Compound | Complex | Relative>( left: T, right: T | List<T> ): List<T> { return new List(left, right); } private readonly _left: T; private readonly _right: T | List<T>; private constructor(left: T, right: T | List<T>) { super(); this._left = left; this._right = right; } public get left(): T { return this._left; } public get right(): T | List<T> { return this._right; } public get type(): "list" { return "list"; } public matches(element: Element, context?: Context): boolean { return ( this._left.matches(element, context) || this._right.matches(element, context) ); } public equals(value: List): boolean; public equals(value: unknown): value is this; public equals(value: unknown): boolean { return ( value instanceof List && value._left.equals(this._left) && value._right.equals(this._right) ); } public *[Symbol.iterator](): Iterator< Simple | Compound | Complex | Relative > { yield this._left; yield* this._right; } public toJSON(): List.JSON { return { type: "list", left: this._left.toJSON(), right: this._right.toJSON(), }; } public toString(): string { return `${this._left}, ${this._right}`; } } export namespace List { export interface JSON extends Selector.JSON<"list"> { left: Simple.JSON | Compound.JSON | Complex.JSON | Relative.JSON; right: Simple.JSON | Compound.JSON | Complex.JSON | Relative.JSON | JSON; } } /** * {@link https://drafts.csswg.org/selectors/#typedef-selector-list} */ const parseList = map( pair( parseComplex, zeroOrMore( right( delimited(option(Token.parseWhitespace), Token.parseComma), parseComplex ) ) ), (result) => { let [left, selectors] = result; [left, ...selectors] = [...Iterable.reverse(selectors), left]; return Iterable.reduce( selectors, (right, left) => List.of(left, right), left as Simple | Compound | Complex | List<Simple | Compound | Complex> ); } ); parseSelector = left( parseList, end((token) => `Unexpected token ${token}`) ); export const parse = parseSelector; }
the_stack
// NOTE: This file is only partially ported and is a work in progress /* eslint-disable */ import {Vector2, Vector3, Vector4, Color, CesiumMath} from '@math.gl/core'; // define([ // '../Core/Check', // '../Core/Color', // '../Core/defined', // '../Core/defineProperties', // '../Core/DeveloperError', // '../Core/isArray', // '../Core/Math', // '../Core/RuntimeError', // '../ThirdParty/jsep', // './ExpressionNodeType' // ], function( // Check, // Color, // defined, // defineProperties, // DeveloperError, // isArray, // CesiumMath, // RuntimeError, // jsep, // ExpressionNodeType) { // 'use strict'; // Scratch storage manager while evaluating deep expressions. // For example, an expression like dot(vec4(${red}), vec4(${green}) * vec4(${blue}) requires 3 scratch Cartesian4's var scratchStorage = { arrayIndex: 0, arrayArray: [[]], cartesian2Index: 0, cartesian3Index: 0, cartesian4Index: 0, cartesian2Array: [new Cartesian2()], cartesian3Array: [new Cartesian3()], cartesian4Array: [new Cartesian4()], reset: function() { this.arrayIndex = 0; this.cartesian2Index = 0; this.cartesian3Index = 0; this.cartesian4Index = 0; }, getArray: function() { if (this.arrayIndex >= this.arrayArray.length) { this.arrayArray.push([]); } var array = this.arrayArray[this.arrayIndex++]; array.length = 0; return array; }, getCartesian2: function() { if (this.cartesian2Index >= this.cartesian2Array.length) { this.cartesian2Array.push(new Cartesian2()); } return this.cartesian2Array[this.cartesian2Index++]; }, getCartesian3: function() { if (this.cartesian3Index >= this.cartesian3Array.length) { this.cartesian3Array.push(new Cartesian3()); } return this.cartesian3Array[this.cartesian3Index++]; }, getCartesian4: function() { if (this.cartesian4Index >= this.cartesian4Array.length) { this.cartesian4Array.push(new Cartesian4()); } return this.cartesian4Array[this.cartesian4Index++]; } }; /** * An expression for a style applied to a {@link Cesium3DTileset}. * <p> * Evaluates an expression defined using the * {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language}. * </p> * <p> * Implements the {@link StyleExpression} interface. * </p> */ class Expression { /* * @alias Expression * @constructor * * @param {String} [expression] The expression defined using the 3D Tiles Styling language. * @param {Object} [defines] Defines in the style. * * @example * var expression = new Cesium.Expression('(regExp("^Chest").test(${County})) && (${YearBuilt} >= 1970)'); * expression.evaluate(feature); // returns true or false depending on the feature's properties * * @example * var expression = new Cesium.Expression('(${Temperature} > 90) ? color("red") : color("white")'); * expression.evaluateColor(feature, result); // returns a Cesium.Color object */ constructor(expression, defines) { //>>includeStart('debug', pragmas.debug); Check.typeOf.string('expression', expression); //>>includeEnd('debug'); this._expression = expression; expression = replaceDefines(expression, defines); expression = replaceVariables(removeBackslashes(expression)); // customize jsep operators jsep.addBinaryOp('=~', 0); jsep.addBinaryOp('!~', 0); var ast; try { ast = jsep(expression); } catch (e) { throw new RuntimeError(e); } this._runtimeAst = createRuntimeAst(this, ast); } /** * Gets the expression defined in the 3D Tiles Styling language. * * @memberof Expression.prototype * * @type {String} * @readonly * * @default undefined */ get expression() { return this._expression; } /** * Evaluates the result of an expression, optionally using the provided feature's properties. If the result of * the expression in the * {@link https://github.com/AnalyticalGraphicsInc/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language} * is of type <code>Boolean</code>, <code>Number</code>, or <code>String</code>, the corresponding JavaScript * primitive type will be returned. If the result is a <code>RegExp</code>, a Javascript <code>RegExp</code> * object will be returned. If the result is a <code>Cartesian2</code>, <code>Cartesian3</code>, or <code>Cartesian4</code>, * a {@link Cartesian2}, {@link Cartesian3}, or {@link Cartesian4} object will be returned. If the <code>result</code> argument is * a {@link Color}, the {@link Cartesian4} value is converted to a {@link Color} and then returned. * * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression. * @param {Object} [result] The object onto which to store the result. * @returns {Boolean|Number|String|RegExp|Cartesian2|Cartesian3|Cartesian4|Color} The result of evaluating the expression. */ evaluate(feature, result) { scratchStorage.reset(); var value = this._runtimeAst.evaluate(feature); if (result instanceof Color && value instanceof Cartesian4) { return Color.fromCartesian4(value, result); } if (value instanceof Cartesian2 || value instanceof Cartesian3 || value instanceof Cartesian4) { return value.clone(result); } return value; } /** * Evaluates the result of a Color expression, optionally using the provided feature's properties. * <p> * This is equivalent to {@link Expression#evaluate} but always returns a {@link Color} object. * </p> * * @param {Cesium3DTileFeature} feature The feature whose properties may be used as variables in the expression. * @param {Color} [result] The object in which to store the result * @returns {Color} The modified result parameter or a new Color instance if one was not provided. */ evaluateColor(feature, result) { scratchStorage.reset(); var color = this._runtimeAst.evaluate(feature); return Color.fromCartesian4(color, result); } /** * Gets the shader function for this expression. * Returns undefined if the shader function can't be generated from this expression. * * @param {String} functionName Name to give to the generated function. * @param {String} attributePrefix Prefix that is added to any variable names to access vertex attributes. * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent. * @param {String} returnType The return type of the generated function. * * @returns {String} The shader function. * * @private */ getShaderFunction(functionName, attributePrefix, shaderState, returnType) { var shaderExpression = this.getShaderExpression(attributePrefix, shaderState); shaderExpression = returnType + ' ' + functionName + '() \n' + '{ \n' + ' return ' + shaderExpression + '; \n' + '} \n'; return shaderExpression; } /** * Gets the shader expression for this expression. * Returns undefined if the shader expression can't be generated from this expression. * * @param {String} attributePrefix Prefix that is added to any variable names to access vertex attributes. * @param {Object} shaderState Stores information about the generated shader function, including whether it is translucent. * * @returns {String} The shader expression. * * @private */ getShaderExpression(attributePrefix, shaderState) { return this._runtimeAst.getShaderExpression(attributePrefix, shaderState); } } var unaryOperators = ['!', '-', '+']; var binaryOperators = [ '+', '-', '*', '/', '%', '===', '!==', '>', '>=', '<', '<=', '&&', '||', '!~', '=~' ]; var variableRegex = /\${(.*?)}/g; // Matches ${variable_name} var backslashRegex = /\\/g; var backslashReplacement = '@#%'; var replacementRegex = /@#%/g; var scratchColor = new Color(); var unaryFunctions = { abs: getEvaluateUnaryComponentwise(Math.abs), sqrt: getEvaluateUnaryComponentwise(Math.sqrt), cos: getEvaluateUnaryComponentwise(Math.cos), sin: getEvaluateUnaryComponentwise(Math.sin), tan: getEvaluateUnaryComponentwise(Math.tan), acos: getEvaluateUnaryComponentwise(Math.acos), asin: getEvaluateUnaryComponentwise(Math.asin), atan: getEvaluateUnaryComponentwise(Math.atan), radians: getEvaluateUnaryComponentwise(CesiumMath.toRadians), degrees: getEvaluateUnaryComponentwise(CesiumMath.toDegrees), sign: getEvaluateUnaryComponentwise(CesiumMath.sign), floor: getEvaluateUnaryComponentwise(Math.floor), ceil: getEvaluateUnaryComponentwise(Math.ceil), round: getEvaluateUnaryComponentwise(Math.round), exp: getEvaluateUnaryComponentwise(Math.exp), exp2: getEvaluateUnaryComponentwise(exp2), log: getEvaluateUnaryComponentwise(Math.log), log2: getEvaluateUnaryComponentwise(log2), fract: getEvaluateUnaryComponentwise(fract), length: length, normalize: normalize }; var binaryFunctions = { atan2: getEvaluateBinaryComponentwise(Math.atan2, false), pow: getEvaluateBinaryComponentwise(Math.pow, false), min: getEvaluateBinaryComponentwise(Math.min, true), max: getEvaluateBinaryComponentwise(Math.max, true), distance: distance, dot: dot, cross: cross }; var ternaryFunctions = { clamp: getEvaluateTernaryComponentwise(CesiumMath.clamp, true), mix: getEvaluateTernaryComponentwise(CesiumMath.lerp, true) }; function fract(number) { return number - Math.floor(number); } function exp2(exponent) { return Math.pow(2.0, exponent); } function log2(number) { return CesiumMath.log2(number); } function getEvaluateUnaryComponentwise(operation) { return function(call, left) { if (typeof left === 'number') { return operation(left); } else if (left instanceof Cartesian2) { return Cartesian2.fromElements( operation(left.x), operation(left.y), scratchStorage.getCartesian2() ); } else if (left instanceof Cartesian3) { return Cartesian3.fromElements( operation(left.x), operation(left.y), operation(left.z), scratchStorage.getCartesian3() ); } else if (left instanceof Cartesian4) { return Cartesian4.fromElements( operation(left.x), operation(left.y), operation(left.z), operation(left.w), scratchStorage.getCartesian4() ); } throw new RuntimeError( 'Function "' + call + '" requires a vector or number argument. Argument is ' + left + '.' ); }; } function getEvaluateBinaryComponentwise(operation, allowScalar) { return function(call, left, right) { if (allowScalar && typeof right === 'number') { if (typeof left === 'number') { return operation(left, right); } else if (left instanceof Cartesian2) { return Cartesian2.fromElements( operation(left.x, right), operation(left.y, right), scratchStorage.getCartesian2() ); } else if (left instanceof Cartesian3) { return Cartesian3.fromElements( operation(left.x, right), operation(left.y, right), operation(left.z, right), scratchStorage.getCartesian3() ); } else if (left instanceof Cartesian4) { return Cartesian4.fromElements( operation(left.x, right), operation(left.y, right), operation(left.z, right), operation(left.w, right), scratchStorage.getCartesian4() ); } } if (typeof left === 'number' && typeof right === 'number') { return operation(left, right); } else if (left instanceof Cartesian2 && right instanceof Cartesian2) { return Cartesian2.fromElements( operation(left.x, right.x), operation(left.y, right.y), scratchStorage.getCartesian2() ); } else if (left instanceof Cartesian3 && right instanceof Cartesian3) { return Cartesian3.fromElements( operation(left.x, right.x), operation(left.y, right.y), operation(left.z, right.z), scratchStorage.getCartesian3() ); } else if (left instanceof Cartesian4 && right instanceof Cartesian4) { return Cartesian4.fromElements( operation(left.x, right.x), operation(left.y, right.y), operation(left.z, right.z), operation(left.w, right.w), scratchStorage.getCartesian4() ); } throw new RuntimeError( 'Function "' + call + '" requires vector or number arguments of matching types. Arguments are ' + left + ' and ' + right + '.' ); }; } function getEvaluateTernaryComponentwise(operation, allowScalar) { return function(call, left, right, test) { if (allowScalar && typeof test === 'number') { if (typeof left === 'number' && typeof right === 'number') { return operation(left, right, test); } else if (left instanceof Cartesian2 && right instanceof Cartesian2) { return Cartesian2.fromElements( operation(left.x, right.x, test), operation(left.y, right.y, test), scratchStorage.getCartesian2() ); } else if (left instanceof Cartesian3 && right instanceof Cartesian3) { return Cartesian3.fromElements( operation(left.x, right.x, test), operation(left.y, right.y, test), operation(left.z, right.z, test), scratchStorage.getCartesian3() ); } else if (left instanceof Cartesian4 && right instanceof Cartesian4) { return Cartesian4.fromElements( operation(left.x, right.x, test), operation(left.y, right.y, test), operation(left.z, right.z, test), operation(left.w, right.w, test), scratchStorage.getCartesian4() ); } } if (typeof left === 'number' && typeof right === 'number' && typeof test === 'number') { return operation(left, right, test); } else if ( left instanceof Cartesian2 && right instanceof Cartesian2 && test instanceof Cartesian2 ) { return Cartesian2.fromElements( operation(left.x, right.x, test.x), operation(left.y, right.y, test.y), scratchStorage.getCartesian2() ); } else if ( left instanceof Cartesian3 && right instanceof Cartesian3 && test instanceof Cartesian3 ) { return Cartesian3.fromElements( operation(left.x, right.x, test.x), operation(left.y, right.y, test.y), operation(left.z, right.z, test.z), scratchStorage.getCartesian3() ); } else if ( left instanceof Cartesian4 && right instanceof Cartesian4 && test instanceof Cartesian4 ) { return Cartesian4.fromElements( operation(left.x, right.x, test.x), operation(left.y, right.y, test.y), operation(left.z, right.z, test.z), operation(left.w, right.w, test.w), scratchStorage.getCartesian4() ); } throw new RuntimeError( 'Function "' + call + '" requires vector or number arguments of matching types. Arguments are ' + left + ', ' + right + ', and ' + test + '.' ); }; } function length(call, left) { if (typeof left === 'number') { return Math.abs(left); } else if (left instanceof Cartesian2) { return Cartesian2.magnitude(left); } else if (left instanceof Cartesian3) { return Cartesian3.magnitude(left); } else if (left instanceof Cartesian4) { return Cartesian4.magnitude(left); } throw new RuntimeError( 'Function "' + call + '" requires a vector or number argument. Argument is ' + left + '.' ); } function normalize(call, left) { if (typeof left === 'number') { return 1.0; } else if (left instanceof Cartesian2) { return Cartesian2.normalize(left, scratchStorage.getCartesian2()); } else if (left instanceof Cartesian3) { return Cartesian3.normalize(left, scratchStorage.getCartesian3()); } else if (left instanceof Cartesian4) { return Cartesian4.normalize(left, scratchStorage.getCartesian4()); } throw new RuntimeError( 'Function "' + call + '" requires a vector or number argument. Argument is ' + left + '.' ); } function distance(call, left, right) { if (typeof left === 'number' && typeof right === 'number') { return Math.abs(left - right); } else if (left instanceof Cartesian2 && right instanceof Cartesian2) { return Cartesian2.distance(left, right); } else if (left instanceof Cartesian3 && right instanceof Cartesian3) { return Cartesian3.distance(left, right); } else if (left instanceof Cartesian4 && right instanceof Cartesian4) { return Cartesian4.distance(left, right); } throw new RuntimeError( 'Function "' + call + '" requires vector or number arguments of matching types. Arguments are ' + left + ' and ' + right + '.' ); } function dot(call, left, right) { if (typeof left === 'number' && typeof right === 'number') { return left * right; } else if (left instanceof Cartesian2 && right instanceof Cartesian2) { return Cartesian2.dot(left, right); } else if (left instanceof Cartesian3 && right instanceof Cartesian3) { return Cartesian3.dot(left, right); } else if (left instanceof Cartesian4 && right instanceof Cartesian4) { return Cartesian4.dot(left, right); } throw new RuntimeError( 'Function "' + call + '" requires vector or number arguments of matching types. Arguments are ' + left + ' and ' + right + '.' ); } function cross(call, left, right) { if (left instanceof Cartesian3 && right instanceof Cartesian3) { return Cartesian3.cross(left, right, scratchStorage.getCartesian3()); } throw new RuntimeError( 'Function "' + call + '" requires vec3 arguments. Arguments are ' + left + ' and ' + right + '.' ); } class Node { constructor(type, value, left, right, test) { this._type = type; this._value = value; this._left = left; this._right = right; this._test = test; this.evaluate = undefined; setEvaluateFunction(this); } _evaluateLiteral() { return this._value; } _evaluateLiteralColor(feature) { var color = scratchColor; var args = this._left; if (this._value === 'color') { if (!defined(args)) { Color.fromBytes(255, 255, 255, 255, color); } else if (args.length > 1) { Color.fromCssColorString(args[0].evaluate(feature), color); color.alpha = args[1].evaluate(feature); } else { Color.fromCssColorString(args[0].evaluate(feature), color); } } else if (this._value === 'rgb') { Color.fromBytes( args[0].evaluate(feature), args[1].evaluate(feature), args[2].evaluate(feature), 255, color ); } else if (this._value === 'rgba') { // convert between css alpha (0 to 1) and cesium alpha (0 to 255) var a = args[3].evaluate(feature) * 255; Color.fromBytes( args[0].evaluate(feature), args[1].evaluate(feature), args[2].evaluate(feature), a, color ); } else if (this._value === 'hsl') { Color.fromHsl( args[0].evaluate(feature), args[1].evaluate(feature), args[2].evaluate(feature), 1.0, color ); } else if (this._value === 'hsla') { Color.fromHsl( args[0].evaluate(feature), args[1].evaluate(feature), args[2].evaluate(feature), args[3].evaluate(feature), color ); } return Cartesian4.fromColor(color, scratchStorage.getCartesian4()); } _evaluateLiteralVector(feature) { // Gather the components that make up the vector, which includes components from interior vectors. // For example vec3(1, 2, 3) or vec3(vec2(1, 2), 3) are both valid. // // If the number of components does not equal the vector's size, then a RuntimeError is thrown - with two exceptions: // 1. A vector may be constructed from a larger vector and drop the extra components. // 2. A vector may be constructed from a single component - vec3(1) will become vec3(1, 1, 1). // // Examples of invalid constructors include: // vec4(1, 2) // not enough components // vec3(vec2(1, 2)) // not enough components // vec3(1, 2, 3, 4) // too many components // vec2(vec4(1), 1) // too many components var components = scratchStorage.getArray(); var call = this._value; var args = this._left; var argsLength = args.length; for (var i = 0; i < argsLength; ++i) { var value = args[i].evaluate(feature); if (typeof value === 'number') { components.push(value); } else if (value instanceof Cartesian2) { components.push(value.x, value.y); } else if (value instanceof Cartesian3) { components.push(value.x, value.y, value.z); } else if (value instanceof Cartesian4) { components.push(value.x, value.y, value.z, value.w); } else { throw new RuntimeError( call + ' argument must be a vector or number. Argument is ' + value + '.' ); } } var componentsLength = components.length; var vectorLength = parseInt(call.charAt(3)); if (componentsLength === 0) { throw new RuntimeError('Invalid ' + call + ' constructor. No valid arguments.'); } else if (componentsLength < vectorLength && componentsLength > 1) { throw new RuntimeError('Invalid ' + call + ' constructor. Not enough arguments.'); } else if (componentsLength > vectorLength && argsLength > 1) { throw new RuntimeError('Invalid ' + call + ' constructor. Too many arguments.'); } if (componentsLength === 1) { // Add the same component 3 more times var component = components[0]; components.push(component, component, component); } if (call === 'vec2') { return Cartesian2.fromArray(components, 0, scratchStorage.getCartesian2()); } else if (call === 'vec3') { return Cartesian3.fromArray(components, 0, scratchStorage.getCartesian3()); } else if (call === 'vec4') { return Cartesian4.fromArray(components, 0, scratchStorage.getCartesian4()); } } _evaluateLiteralString() { return this._value; } _evaluateVariableString(feature) { var result = this._value; var match = variableRegex.exec(result); while (match !== null) { var placeholder = match[0]; var variableName = match[1]; var property = getFeatureProperty(feature, variableName); if (!defined(property)) { property = ''; } result = result.replace(placeholder, property); match = variableRegex.exec(result); } return result; } _evaluateVariable(feature) { // evaluates to undefined if the property name is not defined for that feature return getFeatureProperty(feature, this._value); } _checkFeature(ast) { return ast._value === 'feature'; } // PERFORMANCE_IDEA: Determine if parent property needs to be computed before runtime _evaluateMemberDot(feature) { if (this._checkFeature(this._left)) { return getFeatureProperty(feature, this._right.evaluate(feature)); } var property = this._left.evaluate(feature); if (!defined(property)) { return undefined; } var member = this._right.evaluate(feature); if ( property instanceof Cartesian2 || property instanceof Cartesian3 || property instanceof Cartesian4 ) { // Vector components may be accessed with .r, .g, .b, .a and implicitly with .x, .y, .z, .w if (member === 'r') { return property.x; } else if (member === 'g') { return property.y; } else if (member === 'b') { return property.z; } else if (member === 'a') { return property.w; } } return property[member]; } _evaluateMemberBrackets(feature) { if (this._checkFeature(this._left)) { return getFeatureProperty(feature, this._right.evaluate(feature)); } var property = this._left.evaluate(feature); if (!defined(property)) { return undefined; } var member = this._right.evaluate(feature); if ( property instanceof Cartesian2 || property instanceof Cartesian3 || property instanceof Cartesian4 ) { // Vector components may be accessed with [0][1][2][3], ['r']['g']['b']['a'] and implicitly with ['x']['y']['z']['w'] // For Cartesian2 and Cartesian3 out-of-range components will just return undefined if (member === 0 || member === 'r') { return property.x; } else if (member === 1 || member === 'g') { return property.y; } else if (member === 2 || member === 'b') { return property.z; } else if (member === 3 || member === 'a') { return property.w; } } return property[member]; } _evaluateArray(feature) { var array = []; for (var i = 0; i < this._value.length; i++) { array[i] = this._value[i].evaluate(feature); } return array; } // PERFORMANCE_IDEA: Have "fast path" functions that deal only with specific types // that we can assign if we know the types before runtime _evaluateNot(feature) { var left = this._left.evaluate(feature); if (typeof left !== 'boolean') { throw new RuntimeError('Operator "!" requires a boolean argument. Argument is ' + left + '.'); } return !left; } _evaluateNegative(feature) { var left = this._left.evaluate(feature); if (left instanceof Cartesian2) { return Cartesian2.negate(left, scratchStorage.getCartesian2()); } else if (left instanceof Cartesian3) { return Cartesian3.negate(left, scratchStorage.getCartesian3()); } else if (left instanceof Cartesian4) { return Cartesian4.negate(left, scratchStorage.getCartesian4()); } else if (typeof left === 'number') { return -left; } throw new RuntimeError( 'Operator "-" requires a vector or number argument. Argument is ' + left + '.' ); } _evaluatePositive(feature) { var left = this._left.evaluate(feature); if ( !( left instanceof Cartesian2 || left instanceof Cartesian3 || left instanceof Cartesian4 || typeof left === 'number' ) ) { throw new RuntimeError( 'Operator "+" requires a vector or number argument. Argument is ' + left + '.' ); } return left; } _evaluateLessThan(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (typeof left !== 'number' || typeof right !== 'number') { throw new RuntimeError( 'Operator "<" requires number arguments. Arguments are ' + left + ' and ' + right + '.' ); } return left < right; } _evaluateLessThanOrEquals(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (typeof left !== 'number' || typeof right !== 'number') { throw new RuntimeError( 'Operator "<=" requires number arguments. Arguments are ' + left + ' and ' + right + '.' ); } return left <= right; } _evaluateGreaterThan(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (typeof left !== 'number' || typeof right !== 'number') { throw new RuntimeError( 'Operator ">" requires number arguments. Arguments are ' + left + ' and ' + right + '.' ); } return left > right; } _evaluateGreaterThanOrEquals(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (typeof left !== 'number' || typeof right !== 'number') { throw new RuntimeError( 'Operator ">=" requires number arguments. Arguments are ' + left + ' and ' + right + '.' ); } return left >= right; } _evaluateOr(feature) { var left = this._left.evaluate(feature); if (typeof left !== 'boolean') { throw new RuntimeError( 'Operator "||" requires boolean arguments. First argument is ' + left + '.' ); } // short circuit the expression if (left) { return true; } var right = this._right.evaluate(feature); if (typeof right !== 'boolean') { throw new RuntimeError( 'Operator "||" requires boolean arguments. Second argument is ' + right + '.' ); } return left || right; } _evaluateAnd(feature) { var left = this._left.evaluate(feature); if (typeof left !== 'boolean') { throw new RuntimeError( 'Operator "&&" requires boolean arguments. First argument is ' + left + '.' ); } // short circuit the expression if (!left) { return false; } var right = this._right.evaluate(feature); if (typeof right !== 'boolean') { throw new RuntimeError( 'Operator "&&" requires boolean arguments. Second argument is ' + right + '.' ); } return left && right; } _evaluatePlus(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (right instanceof Cartesian2 && left instanceof Cartesian2) { return Cartesian2.add(left, right, scratchStorage.getCartesian2()); } else if (right instanceof Cartesian3 && left instanceof Cartesian3) { return Cartesian3.add(left, right, scratchStorage.getCartesian3()); } else if (right instanceof Cartesian4 && left instanceof Cartesian4) { return Cartesian4.add(left, right, scratchStorage.getCartesian4()); } else if (typeof left === 'string' || typeof right === 'string') { // If only one argument is a string the other argument calls its toString function. return left + right; } else if (typeof left === 'number' && typeof right === 'number') { return left + right; } throw new RuntimeError( 'Operator "+" requires vector or number arguments of matching types, or at least one string argument. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateMinus(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (right instanceof Cartesian2 && left instanceof Cartesian2) { return Cartesian2.subtract(left, right, scratchStorage.getCartesian2()); } else if (right instanceof Cartesian3 && left instanceof Cartesian3) { return Cartesian3.subtract(left, right, scratchStorage.getCartesian3()); } else if (right instanceof Cartesian4 && left instanceof Cartesian4) { return Cartesian4.subtract(left, right, scratchStorage.getCartesian4()); } else if (typeof left === 'number' && typeof right === 'number') { return left - right; } throw new RuntimeError( 'Operator "-" requires vector or number arguments of matching types. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateTimes(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (right instanceof Cartesian2 && left instanceof Cartesian2) { return Cartesian2.multiplyComponents(left, right, scratchStorage.getCartesian2()); } else if (right instanceof Cartesian2 && typeof left === 'number') { return Cartesian2.multiplyByScalar(right, left, scratchStorage.getCartesian2()); } else if (left instanceof Cartesian2 && typeof right === 'number') { return Cartesian2.multiplyByScalar(left, right, scratchStorage.getCartesian2()); } else if (right instanceof Cartesian3 && left instanceof Cartesian3) { return Cartesian3.multiplyComponents(left, right, scratchStorage.getCartesian3()); } else if (right instanceof Cartesian3 && typeof left === 'number') { return Cartesian3.multiplyByScalar(right, left, scratchStorage.getCartesian3()); } else if (left instanceof Cartesian3 && typeof right === 'number') { return Cartesian3.multiplyByScalar(left, right, scratchStorage.getCartesian3()); } else if (right instanceof Cartesian4 && left instanceof Cartesian4) { return Cartesian4.multiplyComponents(left, right, scratchStorage.getCartesian4()); } else if (right instanceof Cartesian4 && typeof left === 'number') { return Cartesian4.multiplyByScalar(right, left, scratchStorage.getCartesian4()); } else if (left instanceof Cartesian4 && typeof right === 'number') { return Cartesian4.multiplyByScalar(left, right, scratchStorage.getCartesian4()); } else if (typeof left === 'number' && typeof right === 'number') { return left * right; } throw new RuntimeError( 'Operator "*" requires vector or number arguments. If both arguments are vectors they must be matching types. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateDivide(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (right instanceof Cartesian2 && left instanceof Cartesian2) { return Cartesian2.divideComponents(left, right, scratchStorage.getCartesian2()); } else if (left instanceof Cartesian2 && typeof right === 'number') { return Cartesian2.divideByScalar(left, right, scratchStorage.getCartesian2()); } else if (right instanceof Cartesian3 && left instanceof Cartesian3) { return Cartesian3.divideComponents(left, right, scratchStorage.getCartesian3()); } else if (left instanceof Cartesian3 && typeof right === 'number') { return Cartesian3.divideByScalar(left, right, scratchStorage.getCartesian3()); } else if (right instanceof Cartesian4 && left instanceof Cartesian4) { return Cartesian4.divideComponents(left, right, scratchStorage.getCartesian4()); } else if (left instanceof Cartesian4 && typeof right === 'number') { return Cartesian4.divideByScalar(left, right, scratchStorage.getCartesian4()); } else if (typeof left === 'number' && typeof right === 'number') { return left / right; } throw new RuntimeError( 'Operator "/" requires vector or number arguments of matching types, or a number as the second argument. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateMod(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (right instanceof Cartesian2 && left instanceof Cartesian2) { return Cartesian2.fromElements( left.x % right.x, left.y % right.y, scratchStorage.getCartesian2() ); } else if (right instanceof Cartesian3 && left instanceof Cartesian3) { return Cartesian3.fromElements( left.x % right.x, left.y % right.y, left.z % right.z, scratchStorage.getCartesian3() ); } else if (right instanceof Cartesian4 && left instanceof Cartesian4) { return Cartesian4.fromElements( left.x % right.x, left.y % right.y, left.z % right.z, left.w % right.w, scratchStorage.getCartesian4() ); } else if (typeof left === 'number' && typeof right === 'number') { return left % right; } throw new RuntimeError( 'Operator "%" requires vector or number arguments of matching types. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateEqualsStrict(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if ( (right instanceof Cartesian2 && left instanceof Cartesian2) || (right instanceof Cartesian3 && left instanceof Cartesian3) || (right instanceof Cartesian4 && left instanceof Cartesian4) ) { return left.equals(right); } return left === right; } _evaluateNotEqualsStrict(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if ( (right instanceof Cartesian2 && left instanceof Cartesian2) || (right instanceof Cartesian3 && left instanceof Cartesian3) || (right instanceof Cartesian4 && left instanceof Cartesian4) ) { return !left.equals(right); } return left !== right; } _evaluateConditional(feature) { var test = this._test.evaluate(feature); if (typeof test !== 'boolean') { throw new RuntimeError( 'Conditional argument of conditional expression must be a boolean. Argument is ' + test + '.' ); } if (test) { return this._left.evaluate(feature); } return this._right.evaluate(feature); } _evaluateNaN(feature) { return isNaN(this._left.evaluate(feature)); } _evaluateIsFinite(feature) { return isFinite(this._left.evaluate(feature)); } _evaluateIsExactClass(feature) { if (defined(feature)) { return feature.isExactClass(this._left.evaluate(feature)); } return false; } _evaluateIsClass(feature) { if (defined(feature)) { return feature.isClass(this._left.evaluate(feature)); } return false; } _evaluateGetExactClassName(feature) { if (defined(feature)) { return feature.getExactClassName(); } } _evaluateBooleanConversion(feature) { return Boolean(this._left.evaluate(feature)); } _evaluateNumberConversion(feature) { return Number(this._left.evaluate(feature)); } _evaluateStringConversion(feature) { return String(this._left.evaluate(feature)); } _evaluateRegExp(feature) { var pattern = this._value.evaluate(feature); var flags = ''; if (defined(this._left)) { flags = this._left.evaluate(feature); } var exp; try { exp = new RegExp(pattern, flags); } catch (e) { throw new RuntimeError(e); } return exp; } _evaluateRegExpTest(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (!(left instanceof RegExp && typeof right === 'string')) { throw new RuntimeError( 'RegExp.test requires the first argument to be a RegExp and the second argument to be a string. Arguments are ' + left + ' and ' + right + '.' ); } return left.test(right); } _evaluateRegExpMatch(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (left instanceof RegExp && typeof right === 'string') { return left.test(right); } else if (right instanceof RegExp && typeof left === 'string') { return right.test(left); } throw new RuntimeError( 'Operator "=~" requires one RegExp argument and one string argument. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateRegExpNotMatch(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (left instanceof RegExp && typeof right === 'string') { return !left.test(right); } else if (right instanceof RegExp && typeof left === 'string') { return !right.test(left); } throw new RuntimeError( 'Operator "!~" requires one RegExp argument and one string argument. Arguments are ' + left + ' and ' + right + '.' ); } _evaluateRegExpExec(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); if (!(left instanceof RegExp && typeof right === 'string')) { throw new RuntimeError( 'RegExp.exec requires the first argument to be a RegExp and the second argument to be a string. Arguments are ' + left + ' and ' + right + '.' ); } var exec = left.exec(right); if (!defined(exec)) { return null; } return exec[1]; } _evaluateToString(feature) { var left = this._left.evaluate(feature); if ( left instanceof RegExp || left instanceof Cartesian2 || left instanceof Cartesian3 || left instanceof Cartesian4 ) { return String(left); } throw new RuntimeError('Unexpected function call "' + this._value + '".'); } getShaderExpression(attributePrefix, shaderState, parent) { var color; var left; var right; var test; var type = this._type; var value = this._value; if (defined(this._left)) { if (isArray(this._left)) { // Left can be an array if the type is LITERAL_COLOR or LITERAL_VECTOR left = getExpressionArray(this._left, attributePrefix, shaderState, this); } else { left = this._left.getShaderExpression(attributePrefix, shaderState, this); } } if (defined(this._right)) { right = this._right.getShaderExpression(attributePrefix, shaderState, this); } if (defined(this._test)) { test = this._test.getShaderExpression(attributePrefix, shaderState, this); } if (isArray(this._value)) { // For ARRAY type value = getExpressionArray(this._value, attributePrefix, shaderState, this); } switch (type) { case ExpressionNodeType.VARIABLE: return attributePrefix + value; case ExpressionNodeType.UNARY: // Supported types: +, -, !, Boolean, Number if (value === 'Boolean') { return 'bool(' + left + ')'; } else if (value === 'Number') { return 'float(' + left + ')'; } else if (value === 'round') { return 'floor(' + left + ' + 0.5)'; } else if (defined(unaryFunctions[value])) { return value + '(' + left + ')'; } else if ( value === 'isNaN' || value === 'isFinite' || value === 'String' || value === 'isExactClass' || value === 'isClass' || value === 'getExactClassName' ) { throw new RuntimeError( 'Error generating style shader: "' + value + '" is not supported.' ); } else if (defined(unaryFunctions[value])) { return value + '(' + left + ')'; } return value + left; case ExpressionNodeType.BINARY: // Supported types: ||, &&, ===, !==, <, >, <=, >=, +, -, *, /, % if (value === '%') { return 'mod(' + left + ', ' + right + ')'; } else if (value === '===') { return '(' + left + ' == ' + right + ')'; } else if (value === '!==') { return '(' + left + ' != ' + right + ')'; } else if (value === 'atan2') { return 'atan(' + left + ', ' + right + ')'; } else if (defined(binaryFunctions[value])) { return value + '(' + left + ', ' + right + ')'; } return '(' + left + ' ' + value + ' ' + right + ')'; case ExpressionNodeType.TERNARY: if (defined(ternaryFunctions[value])) { return value + '(' + left + ', ' + right + ', ' + test + ')'; } break; case ExpressionNodeType.CONDITIONAL: return '(' + test + ' ? ' + left + ' : ' + right + ')'; case ExpressionNodeType.MEMBER: // This is intended for accessing the components of vector properties. String members aren't supported. // Check for 0.0 rather than 0 because all numbers are previously converted to decimals. if (right === 'r' || right === 'x' || right === '0.0') { return left + '[0]'; } else if (right === 'g' || right === 'y' || right === '1.0') { return left + '[1]'; } else if (right === 'b' || right === 'z' || right === '2.0') { return left + '[2]'; } else if (right === 'a' || right === 'w' || right === '3.0') { return left + '[3]'; } return left + '[int(' + right + ')]'; case ExpressionNodeType.FUNCTION_CALL: throw new RuntimeError('Error generating style shader: "' + value + '" is not supported.'); case ExpressionNodeType.ARRAY: if (value.length === 4) { return 'vec4(' + value[0] + ', ' + value[1] + ', ' + value[2] + ', ' + value[3] + ')'; } else if (value.length === 3) { return 'vec3(' + value[0] + ', ' + value[1] + ', ' + value[2] + ')'; } else if (value.length === 2) { return 'vec2(' + value[0] + ', ' + value[1] + ')'; } throw new RuntimeError( 'Error generating style shader: Invalid array length. Array length should be 2, 3, or 4.' ); case ExpressionNodeType.REGEX: throw new RuntimeError( 'Error generating style shader: Regular expressions are not supported.' ); case ExpressionNodeType.VARIABLE_IN_STRING: throw new RuntimeError( 'Error generating style shader: Converting a variable to a string is not supported.' ); case ExpressionNodeType.LITERAL_NULL: throw new RuntimeError('Error generating style shader: null is not supported.'); case ExpressionNodeType.LITERAL_BOOLEAN: return value ? 'true' : 'false'; case ExpressionNodeType.LITERAL_NUMBER: return numberToString(value); case ExpressionNodeType.LITERAL_STRING: if (defined(parent) && parent._type === ExpressionNodeType.MEMBER) { if ( value === 'r' || value === 'g' || value === 'b' || value === 'a' || value === 'x' || value === 'y' || value === 'z' || value === 'w' ) { return value; } } // Check for css color strings color = Color.fromCssColorString(value, scratchColor); if (defined(color)) { return colorToVec3(color); } throw new RuntimeError('Error generating style shader: String literals are not supported.'); case ExpressionNodeType.LITERAL_COLOR: var args = left; if (value === 'color') { if (!defined(args)) { return 'vec4(1.0)'; } else if (args.length > 1) { var rgb = args[0]; var alpha = args[1]; if (alpha !== '1.0') { shaderState.translucent = true; } return 'vec4(' + rgb + ', ' + alpha + ')'; } return 'vec4(' + args[0] + ', 1.0)'; } else if (value === 'rgb') { color = convertRGBToColor(this); if (defined(color)) { return colorToVec4(color); } return ( 'vec4(' + args[0] + ' / 255.0, ' + args[1] + ' / 255.0, ' + args[2] + ' / 255.0, 1.0)' ); } else if (value === 'rgba') { if (args[3] !== '1.0') { shaderState.translucent = true; } color = convertRGBToColor(this); if (defined(color)) { return colorToVec4(color); } return ( 'vec4(' + args[0] + ' / 255.0, ' + args[1] + ' / 255.0, ' + args[2] + ' / 255.0, ' + args[3] + ')' ); } else if (value === 'hsl') { color = convertHSLToRGB(this); if (defined(color)) { return colorToVec4(color); } return 'vec4(czm_HSLToRGB(vec3(' + args[0] + ', ' + args[1] + ', ' + args[2] + ')), 1.0)'; } else if (value === 'hsla') { color = convertHSLToRGB(this); if (defined(color)) { if (color.alpha !== 1.0) { shaderState.translucent = true; } return colorToVec4(color); } if (args[3] !== '1.0') { shaderState.translucent = true; } return ( 'vec4(czm_HSLToRGB(vec3(' + args[0] + ', ' + args[1] + ', ' + args[2] + ')), ' + args[3] + ')' ); } break; case ExpressionNodeType.LITERAL_VECTOR: //>>includeStart('debug', pragmas.debug); if (!defined(left)) { throw new DeveloperError( 'left should always be defined for type ExpressionNodeType.LITERAL_VECTOR' ); } //>>includeEnd('debug'); var length = left.length; var vectorExpression = value + '('; for (var i = 0; i < length; ++i) { vectorExpression += left[i]; if (i < length - 1) { vectorExpression += ', '; } } vectorExpression += ')'; return vectorExpression; case ExpressionNodeType.LITERAL_REGEX: throw new RuntimeError( 'Error generating style shader: Regular expressions are not supported.' ); case ExpressionNodeType.LITERAL_UNDEFINED: throw new RuntimeError('Error generating style shader: undefined is not supported.'); case ExpressionNodeType.BUILTIN_VARIABLE: if (value === 'tiles3d_tileset_time') { return 'u_time'; } } } } function convertHSLToRGB(ast) { // Check if the color contains any nested expressions to see if the color can be converted here. // E.g. "hsl(0.9, 0.6, 0.7)" is able to convert directly to rgb, "hsl(0.9, 0.6, ${Height})" is not. var channels = ast._left; var length = channels.length; for (var i = 0; i < length; ++i) { if (channels[i]._type !== ExpressionNodeType.LITERAL_NUMBER) { return undefined; } } var h = channels[0]._value; var s = channels[1]._value; var l = channels[2]._value; var a = length === 4 ? channels[3]._value : 1.0; return Color.fromHsl(h, s, l, a, scratchColor); } function convertRGBToColor(ast) { // Check if the color contains any nested expressions to see if the color can be converted here. // E.g. "rgb(255, 255, 255)" is able to convert directly to Color, "rgb(255, 255, ${Height})" is not. var channels = ast._left; var length = channels.length; for (var i = 0; i < length; ++i) { if (channels[i]._type !== ExpressionNodeType.LITERAL_NUMBER) { return undefined; } } var color = scratchColor; color.red = channels[0]._value / 255.0; color.green = channels[1]._value / 255.0; color.blue = channels[2]._value / 255.0; color.alpha = length === 4 ? channels[3]._value : 1.0; return color; } function numberToString(number) { if (number % 1 === 0) { // Add a .0 to whole numbers return number.toFixed(1); } return number.toString(); } function colorToVec3(color) { var r = numberToString(color.red); var g = numberToString(color.green); var b = numberToString(color.blue); return 'vec3(' + r + ', ' + g + ', ' + b + ')'; } function colorToVec4(color) { var r = numberToString(color.red); var g = numberToString(color.green); var b = numberToString(color.blue); var a = numberToString(color.alpha); return 'vec4(' + r + ', ' + g + ', ' + b + ', ' + a + ')'; } function getExpressionArray(array, attributePrefix, shaderState, parent) { var length = array.length; var expressions = new Array(length); for (var i = 0; i < length; ++i) { expressions[i] = array[i].getShaderExpression(attributePrefix, shaderState, parent); } return expressions; } function replaceDefines(expression, defines) { if (!defined(defines)) { return expression; } for (var key in defines) { if (defines.hasOwnProperty(key)) { var definePlaceholder = new RegExp('\\$\\{' + key + '\\}', 'g'); var defineReplace = '(' + defines[key] + ')'; if (defined(defineReplace)) { expression = expression.replace(definePlaceholder, defineReplace); } } } return expression; } function removeBackslashes(expression) { return expression.replace(backslashRegex, backslashReplacement); } function replaceBackslashes(expression) { return expression.replace(replacementRegex, '\\'); } function replaceVariables(expression) { var exp = expression; var result = ''; var i = exp.indexOf('${'); while (i >= 0) { // Check if string is inside quotes var openSingleQuote = exp.indexOf("'"); var openDoubleQuote = exp.indexOf('"'); var closeQuote; if (openSingleQuote >= 0 && openSingleQuote < i) { closeQuote = exp.indexOf("'", openSingleQuote + 1); result += exp.substr(0, closeQuote + 1); exp = exp.substr(closeQuote + 1); i = exp.indexOf('${'); } else if (openDoubleQuote >= 0 && openDoubleQuote < i) { closeQuote = exp.indexOf('"', openDoubleQuote + 1); result += exp.substr(0, closeQuote + 1); exp = exp.substr(closeQuote + 1); i = exp.indexOf('${'); } else { result += exp.substr(0, i); var j = exp.indexOf('}'); if (j < 0) { throw new RuntimeError('Unmatched {.'); } result += 'czm_' + exp.substr(i + 2, j - (i + 2)); exp = exp.substr(j + 1); i = exp.indexOf('${'); } } result += exp; return result; } function parseLiteral(ast) { var type = typeof ast.value; if (ast.value === null) { return new Node(ExpressionNodeType.LITERAL_NULL, null); } else if (type === 'boolean') { return new Node(ExpressionNodeType.LITERAL_BOOLEAN, ast.value); } else if (type === 'number') { return new Node(ExpressionNodeType.LITERAL_NUMBER, ast.value); } else if (type === 'string') { if (ast.value.indexOf('${') >= 0) { return new Node(ExpressionNodeType.VARIABLE_IN_STRING, ast.value); } return new Node(ExpressionNodeType.LITERAL_STRING, replaceBackslashes(ast.value)); } } function parseCall(expression, ast) { var args = ast.arguments; var argsLength = args.length; var call; var val, left, right; // Member function calls if (ast.callee.type === 'MemberExpression') { call = ast.callee.property.name; var object = ast.callee.object; if (call === 'test' || call === 'exec') { // Make sure this is called on a valid type if (object.callee.name !== 'regExp') { throw new RuntimeError(call + ' is not a function.'); } if (argsLength === 0) { if (call === 'test') { return new Node(ExpressionNodeType.LITERAL_BOOLEAN, false); } return new Node(ExpressionNodeType.LITERAL_NULL, null); } left = createRuntimeAst(expression, object); right = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.FUNCTION_CALL, call, left, right); } else if (call === 'toString') { val = createRuntimeAst(expression, object); return new Node(ExpressionNodeType.FUNCTION_CALL, call, val); } throw new RuntimeError('Unexpected function call "' + call + '".'); } // Non-member function calls call = ast.callee.name; if (call === 'color') { if (argsLength === 0) { return new Node(ExpressionNodeType.LITERAL_COLOR, call); } val = createRuntimeAst(expression, args[0]); if (defined(args[1])) { var alpha = createRuntimeAst(expression, args[1]); return new Node(ExpressionNodeType.LITERAL_COLOR, call, [val, alpha]); } return new Node(ExpressionNodeType.LITERAL_COLOR, call, [val]); } else if (call === 'rgb' || call === 'hsl') { if (argsLength < 3) { throw new RuntimeError(call + ' requires three arguments.'); } val = [ createRuntimeAst(expression, args[0]), createRuntimeAst(expression, args[1]), createRuntimeAst(expression, args[2]) ]; return new Node(ExpressionNodeType.LITERAL_COLOR, call, val); } else if (call === 'rgba' || call === 'hsla') { if (argsLength < 4) { throw new RuntimeError(call + ' requires four arguments.'); } val = [ createRuntimeAst(expression, args[0]), createRuntimeAst(expression, args[1]), createRuntimeAst(expression, args[2]), createRuntimeAst(expression, args[3]) ]; return new Node(ExpressionNodeType.LITERAL_COLOR, call, val); } else if (call === 'vec2' || call === 'vec3' || call === 'vec4') { // Check for invalid constructors at evaluation time val = new Array(argsLength); for (var i = 0; i < argsLength; ++i) { val[i] = createRuntimeAst(expression, args[i]); } return new Node(ExpressionNodeType.LITERAL_VECTOR, call, val); } else if (call === 'isNaN' || call === 'isFinite') { if (argsLength === 0) { if (call === 'isNaN') { return new Node(ExpressionNodeType.LITERAL_BOOLEAN, true); } return new Node(ExpressionNodeType.LITERAL_BOOLEAN, false); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (call === 'isExactClass' || call === 'isClass') { if (argsLength < 1 || argsLength > 1) { throw new RuntimeError(call + ' requires exactly one argument.'); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (call === 'getExactClassName') { if (argsLength > 0) { throw new RuntimeError(call + ' does not take any argument.'); } return new Node(ExpressionNodeType.UNARY, call); } else if (defined(unaryFunctions[call])) { if (argsLength !== 1) { throw new RuntimeError(call + ' requires exactly one argument.'); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (defined(binaryFunctions[call])) { if (argsLength !== 2) { throw new RuntimeError(call + ' requires exactly two arguments.'); } left = createRuntimeAst(expression, args[0]); right = createRuntimeAst(expression, args[1]); return new Node(ExpressionNodeType.BINARY, call, left, right); } else if (defined(ternaryFunctions[call])) { if (argsLength !== 3) { throw new RuntimeError(call + ' requires exactly three arguments.'); } left = createRuntimeAst(expression, args[0]); right = createRuntimeAst(expression, args[1]); var test = createRuntimeAst(expression, args[2]); return new Node(ExpressionNodeType.TERNARY, call, left, right, test); } else if (call === 'Boolean') { if (argsLength === 0) { return new Node(ExpressionNodeType.LITERAL_BOOLEAN, false); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (call === 'Number') { if (argsLength === 0) { return new Node(ExpressionNodeType.LITERAL_NUMBER, 0); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (call === 'String') { if (argsLength === 0) { return new Node(ExpressionNodeType.LITERAL_STRING, ''); } val = createRuntimeAst(expression, args[0]); return new Node(ExpressionNodeType.UNARY, call, val); } else if (call === 'regExp') { return parseRegex(expression, ast); } throw new RuntimeError('Unexpected function call "' + call + '".'); } function parseRegex(expression, ast) { var args = ast.arguments; // no arguments, return default regex if (args.length === 0) { return new Node(ExpressionNodeType.LITERAL_REGEX, new RegExp()); } var pattern = createRuntimeAst(expression, args[0]); var exp; // optional flag argument supplied if (args.length > 1) { var flags = createRuntimeAst(expression, args[1]); if (isLiteralType(pattern) && isLiteralType(flags)) { try { exp = new RegExp(replaceBackslashes(String(pattern._value)), flags._value); } catch (e) { throw new RuntimeError(e); } return new Node(ExpressionNodeType.LITERAL_REGEX, exp); } return new Node(ExpressionNodeType.REGEX, pattern, flags); } // only pattern argument supplied if (isLiteralType(pattern)) { try { exp = new RegExp(replaceBackslashes(String(pattern._value))); } catch (e) { throw new RuntimeError(e); } return new Node(ExpressionNodeType.LITERAL_REGEX, exp); } return new Node(ExpressionNodeType.REGEX, pattern); } function parseKeywordsAndVariables(ast) { if (isVariable(ast.name)) { var name = getPropertyName(ast.name); if (name.substr(0, 8) === 'tiles3d_') { return new Node(ExpressionNodeType.BUILTIN_VARIABLE, name); } return new Node(ExpressionNodeType.VARIABLE, name); } else if (ast.name === 'NaN') { return new Node(ExpressionNodeType.LITERAL_NUMBER, NaN); } else if (ast.name === 'Infinity') { return new Node(ExpressionNodeType.LITERAL_NUMBER, Infinity); } else if (ast.name === 'undefined') { return new Node(ExpressionNodeType.LITERAL_UNDEFINED, undefined); } throw new RuntimeError(ast.name + ' is not defined.'); } function parseMathConstant(ast) { var name = ast.property.name; if (name === 'PI') { return new Node(ExpressionNodeType.LITERAL_NUMBER, Math.PI); } else if (name === 'E') { return new Node(ExpressionNodeType.LITERAL_NUMBER, Math.E); } } function parseNumberConstant(ast) { var name = ast.property.name; if (name === 'POSITIVE_INFINITY') { return new Node(ExpressionNodeType.LITERAL_NUMBER, Number.POSITIVE_INFINITY); } } function parseMemberExpression(expression, ast) { if (ast.object.name === 'Math') { return parseMathConstant(ast); } else if (ast.object.name === 'Number') { return parseNumberConstant(ast); } var val; var obj = createRuntimeAst(expression, ast.object); if (ast.computed) { val = createRuntimeAst(expression, ast.property); return new Node(ExpressionNodeType.MEMBER, 'brackets', obj, val); } val = new Node(ExpressionNodeType.LITERAL_STRING, ast.property.name); return new Node(ExpressionNodeType.MEMBER, 'dot', obj, val); } function isLiteralType(node) { return node._type >= ExpressionNodeType.LITERAL_NULL; } function isVariable(name) { return name.substr(0, 4) === 'czm_'; } function getPropertyName(variable) { return variable.substr(4); } function createRuntimeAst(expression, ast) { var node; var op; var left; var right; if (ast.type === 'Literal') { node = parseLiteral(ast); } else if (ast.type === 'CallExpression') { node = parseCall(expression, ast); } else if (ast.type === 'Identifier') { node = parseKeywordsAndVariables(ast); } else if (ast.type === 'UnaryExpression') { op = ast.operator; var child = createRuntimeAst(expression, ast.argument); if (unaryOperators.indexOf(op) > -1) { node = new Node(ExpressionNodeType.UNARY, op, child); } else { throw new RuntimeError('Unexpected operator "' + op + '".'); } } else if (ast.type === 'BinaryExpression') { op = ast.operator; left = createRuntimeAst(expression, ast.left); right = createRuntimeAst(expression, ast.right); if (binaryOperators.indexOf(op) > -1) { node = new Node(ExpressionNodeType.BINARY, op, left, right); } else { throw new RuntimeError('Unexpected operator "' + op + '".'); } } else if (ast.type === 'LogicalExpression') { op = ast.operator; left = createRuntimeAst(expression, ast.left); right = createRuntimeAst(expression, ast.right); if (binaryOperators.indexOf(op) > -1) { node = new Node(ExpressionNodeType.BINARY, op, left, right); } } else if (ast.type === 'ConditionalExpression') { var test = createRuntimeAst(expression, ast.test); left = createRuntimeAst(expression, ast.consequent); right = createRuntimeAst(expression, ast.alternate); node = new Node(ExpressionNodeType.CONDITIONAL, '?', left, right, test); } else if (ast.type === 'MemberExpression') { node = parseMemberExpression(expression, ast); } else if (ast.type === 'ArrayExpression') { var val = []; for (var i = 0; i < ast.elements.length; i++) { val[i] = createRuntimeAst(expression, ast.elements[i]); } node = new Node(ExpressionNodeType.ARRAY, val); } else if (ast.type === 'Compound') { // empty expression or multiple expressions throw new RuntimeError('Provide exactly one expression.'); } else { throw new RuntimeError('Cannot parse expression.'); } return node; } function setEvaluateFunction(node) { if (node._type === ExpressionNodeType.CONDITIONAL) { node.evaluate = node._evaluateConditional; } else if (node._type === ExpressionNodeType.FUNCTION_CALL) { if (node._value === 'test') { node.evaluate = node._evaluateRegExpTest; } else if (node._value === 'exec') { node.evaluate = node._evaluateRegExpExec; } else if (node._value === 'toString') { node.evaluate = node._evaluateToString; } } else if (node._type === ExpressionNodeType.UNARY) { if (node._value === '!') { node.evaluate = node._evaluateNot; } else if (node._value === '-') { node.evaluate = node._evaluateNegative; } else if (node._value === '+') { node.evaluate = node._evaluatePositive; } else if (node._value === 'isNaN') { node.evaluate = node._evaluateNaN; } else if (node._value === 'isFinite') { node.evaluate = node._evaluateIsFinite; } else if (node._value === 'isExactClass') { node.evaluate = node._evaluateIsExactClass; } else if (node._value === 'isClass') { node.evaluate = node._evaluateIsClass; } else if (node._value === 'getExactClassName') { node.evaluate = node._evaluateGetExactClassName; } else if (node._value === 'Boolean') { node.evaluate = node._evaluateBooleanConversion; } else if (node._value === 'Number') { node.evaluate = node._evaluateNumberConversion; } else if (node._value === 'String') { node.evaluate = node._evaluateStringConversion; } else if (defined(unaryFunctions[node._value])) { node.evaluate = getEvaluateUnaryFunction(node._value); } } else if (node._type === ExpressionNodeType.BINARY) { if (node._value === '+') { node.evaluate = node._evaluatePlus; } else if (node._value === '-') { node.evaluate = node._evaluateMinus; } else if (node._value === '*') { node.evaluate = node._evaluateTimes; } else if (node._value === '/') { node.evaluate = node._evaluateDivide; } else if (node._value === '%') { node.evaluate = node._evaluateMod; } else if (node._value === '===') { node.evaluate = node._evaluateEqualsStrict; } else if (node._value === '!==') { node.evaluate = node._evaluateNotEqualsStrict; } else if (node._value === '<') { node.evaluate = node._evaluateLessThan; } else if (node._value === '<=') { node.evaluate = node._evaluateLessThanOrEquals; } else if (node._value === '>') { node.evaluate = node._evaluateGreaterThan; } else if (node._value === '>=') { node.evaluate = node._evaluateGreaterThanOrEquals; } else if (node._value === '&&') { node.evaluate = node._evaluateAnd; } else if (node._value === '||') { node.evaluate = node._evaluateOr; } else if (node._value === '=~') { node.evaluate = node._evaluateRegExpMatch; } else if (node._value === '!~') { node.evaluate = node._evaluateRegExpNotMatch; } else if (defined(binaryFunctions[node._value])) { node.evaluate = getEvaluateBinaryFunction(node._value); } } else if (node._type === ExpressionNodeType.TERNARY) { node.evaluate = getEvaluateTernaryFunction(node._value); } else if (node._type === ExpressionNodeType.MEMBER) { if (node._value === 'brackets') { node.evaluate = node._evaluateMemberBrackets; } else { node.evaluate = node._evaluateMemberDot; } } else if (node._type === ExpressionNodeType.ARRAY) { node.evaluate = node._evaluateArray; } else if (node._type === ExpressionNodeType.VARIABLE) { node.evaluate = node._evaluateVariable; } else if (node._type === ExpressionNodeType.VARIABLE_IN_STRING) { node.evaluate = node._evaluateVariableString; } else if (node._type === ExpressionNodeType.LITERAL_COLOR) { node.evaluate = node._evaluateLiteralColor; } else if (node._type === ExpressionNodeType.LITERAL_VECTOR) { node.evaluate = node._evaluateLiteralVector; } else if (node._type === ExpressionNodeType.LITERAL_STRING) { node.evaluate = node._evaluateLiteralString; } else if (node._type === ExpressionNodeType.REGEX) { node.evaluate = node._evaluateRegExp; } else if (node._type === ExpressionNodeType.BUILTIN_VARIABLE) { if (node._value === 'tiles3d_tileset_time') { node.evaluate = evaluateTilesetTime; } } else { node.evaluate = node._evaluateLiteral; } } function evaluateTilesetTime(feature) { if (!defined(feature)) { return 0.0; } return feature.content.tileset.timeSinceLoad; } function getEvaluateUnaryFunction(call) { var evaluate = unaryFunctions[call]; return function(feature) { var left = this._left.evaluate(feature); return evaluate(call, left); }; } function getEvaluateBinaryFunction(call) { var evaluate = binaryFunctions[call]; return function(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); return evaluate(call, left, right); }; } function getEvaluateTernaryFunction(call) { var evaluate = ternaryFunctions[call]; return function(feature) { var left = this._left.evaluate(feature); var right = this._right.evaluate(feature); var test = this._test.evaluate(feature); return evaluate(call, left, right, test); }; } function getFeatureProperty(feature, name) { // Returns undefined if the feature is not defined or the property name is not defined for that feature if (defined(feature)) { return feature.getProperty(name); } }
the_stack
import "jest"; import React from "react"; import ReactDOM from "react-dom"; import { act, Simulate } from "react-dom/test-utils"; import { inMemory } from "@hickory/in-memory"; import { createRouter, prepareRoutes } from "@curi/router"; import { sleep } from "../../../utils/tests"; import { createRouterComponent, AsyncLink } from "@curi/react-dom"; describe("<AsyncLink>", () => { let node; let router, Router: React.FunctionComponent; let routes = prepareRoutes([ { name: "Test", path: "" }, { name: "Best", path: "best" }, { name: "Catch All", path: "(.*)" } ]); beforeEach(() => { node = document.createElement("div"); router = createRouter(inMemory, routes); Router = createRouterComponent(router); }); afterEach(() => { ReactDOM.unmountComponentAtNode(node); }); describe("anchor", () => { it("renders an <a> by default", () => { ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink>} </Router>, node ); let a = node.querySelector("a"); expect(a).toBeDefined(); }); it("renders the provided component instead of an anchor", () => { let StyledAnchor = props => <a style={{ color: "orange" }} {...props} />; ReactDOM.render( <Router> <AsyncLink anchor={StyledAnchor} name="Test"> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a).toBeDefined(); expect(getComputedStyle(a).color).toBe("orange"); }); }); describe("href", () => { describe("name", () => { it("sets the href attribute using the named route's path", () => { ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink>} </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/"); }); it("has no pathname component if name is not provided", () => { let routes = prepareRoutes([{ name: "Catch All", path: "(.*)" }]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/the-initial-location" }] } }); let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink hash="test">{() => null}</AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("#test"); }); }); describe("params", () => { let router, Router; let routes = prepareRoutes([ { name: "Park", path: "park/:name" }, { name: "Catch All", path: "(.*)" } ]); beforeEach(() => { router = createRouter(inMemory, routes); Router = createRouterComponent(router); }); it("uses params to generate the href", () => { let params = { name: "Glacier" }; ReactDOM.render( <Router> <AsyncLink name="Park" params={params}> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/park/Glacier"); }); it("updates href when props change", () => { let params = { name: "Glacier" }; ReactDOM.render( <Router> <AsyncLink name="Park" params={params}> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/park/Glacier"); let newParams = { name: "Yellowstone" }; ReactDOM.render( <Router> <AsyncLink name="Park" params={newParams}> {() => null} </AsyncLink> </Router>, node ); a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/park/Yellowstone"); }); }); describe("hash & query", () => { it("merges hash & query props with the pathname when creating href", () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test" query="one=two" hash="hashtag"> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/test?one=two#hashtag"); }); }); }); describe("additional props", () => { it("passes additional props to the rendered anchor", () => { ReactDOM.render( <Router> <AsyncLink name="Test" className="hi"> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.classList.contains("hi")).toBe(true); }); it('does not overwrite "native" props set on the rendered element', () => { ReactDOM.render( <Router> <AsyncLink name="Test" href="/oh-no"> {() => <p>Test</p>} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.getAttribute("href")).toBe("/"); }); }); describe("ref", () => { it("returns the anchor's ref, not the link's", () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); let ref = React.createRef(); ReactDOM.render( <Router> <AsyncLink name="Test" ref={ref}> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a).toBe(ref.current); }); }); describe("children", () => { it("is called with the <AsyncLink>'s current navigating state (false on mount)", () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); let children = jest.fn((a: boolean) => null); ReactDOM.render( <Router> <AsyncLink name="Test">{children}</AsyncLink> </Router>, node ); expect(children.mock.calls.length).toBe(1); expect(children.mock.calls[0][0]).toBe(false); }); }); describe("clicking a link", () => { it("calls history.navigate", () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let mockNavigate = jest.fn(); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink> </Router>, node ); let a = node.querySelector("a"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); expect(mockNavigate.mock.calls.length).toBe(1); }); describe("children(navigating)", () => { it("children(true) after clicking", () => { // if a link has no on methods, finished will be called almost // immediately (although this style should only be used for routes // with on methods) let routes = prepareRoutes([ { name: "Test", path: "test", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("done"); }, 100); }); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test"> {navigating => { return <div>{navigating.toString()}</div>; }} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.textContent).toBe("false"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); expect(a.textContent).toBe("true"); }); it("children(false) when navigation is cancelled", () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Slow", path: "slow", resolve() { // takes 500ms to resolve return new Promise(resolve => { setTimeout(() => { resolve("slow"); }, 500); }); } }, { name: "Fast", path: "fast" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); ReactDOM.render( <Router> <React.Fragment> <AsyncLink name="Slow"> {navigating => { return <div>Slow {navigating.toString()}</div>; }} </AsyncLink> <AsyncLink name="Fast"> {navigating => { return <div>Fast {navigating.toString()}</div>; }} </AsyncLink> </React.Fragment> </Router>, node ); let [slowLink, fastLink] = node.querySelectorAll("a"); expect(slowLink.textContent).toBe("Slow false"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(slowLink, leftClickEvent); expect(slowLink.textContent).toBe("Slow true"); Simulate.click(fastLink, leftClickEvent); expect(slowLink.textContent).toBe("Slow false"); }); it("children(false) when navigation is finished", async () => { let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Loader", path: "load", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("done"); }, 25); }); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Loader"> {navigating => { return <div>{navigating.toString()}</div>; }} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.textContent).toBe("false"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; await act(async () => { Simulate.click(a, leftClickEvent); }); // text is changed to true after clicking the link expect(a.textContent).toBe("true"); // wait for the navigation to finish await act(async () => { await sleep(50); }); let { response } = router.current(); expect(response.name).toBe("Loader"); // text has reverted to false expect(a.textContent).toBe("false"); }); it("does not try to update state if component has unmounted", done => { let realError = console.error; let mockError = jest.fn(); console.error = mockError; let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Slow", path: "slow", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("Finally finished"); setTimeout(() => { expect(mockError.mock.calls.length).toBe(0); console.error = realError; done(); }); }, 100); }); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Slow"> {navigating => { return <div>{navigating.toString()}</div>; }} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); expect(a.textContent).toBe("false"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); // unmount the Link to verify that it doesn't call setState() ReactDOM.unmountComponentAtNode(node); }); }); it("includes hash, query, and state in location passed to history.navigate", () => { let mockNavigate = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test" hash="thing" query="one=1" state="yo"> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); let mockURL = mockNavigate.mock.calls[0][0]; expect(mockURL).toMatchObject({ url: "/test?one=1#thing", state: "yo" }); }); describe("onNav", () => { it("calls onNav prop func if provided", () => { let mockNavigate = jest.fn(); let onNav = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test" onNav={onNav}> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); expect(onNav.mock.calls.length).toBe(1); expect(mockNavigate.mock.calls.length).toBe(1); }); it("does not call history.navigate if onNav prevents default", () => { let mockNavigate = jest.fn(); let onNav = jest.fn(event => { event.preventDefault(); }); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test" onNav={onNav}> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); let leftClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, leftClickEvent); expect(onNav.mock.calls.length).toBe(1); expect(mockNavigate.mock.calls.length).toBe(0); }); }); it("doesn't call history.navigate for modified clicks", () => { let mockNavigate = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink> </Router>, node ); let a = node.querySelector("a"); let modifiedClickEvent = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; let modifiers = ["metaKey", "altKey", "ctrlKey", "shiftKey"]; modifiers.forEach(m => { let eventCopy = Object.assign({}, modifiedClickEvent); eventCopy[m] = true; Simulate.click(a, eventCopy); expect(mockNavigate.mock.calls.length).toBe(0); }); }); it("doesn't call history.navigate if event.preventDefault has been called", () => { let mockNavigate = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink> </Router>, node ); let a = node.querySelector("a"); let preventedEvent = { defaultPrevented: true, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; Simulate.click(a, preventedEvent); expect(mockNavigate.mock.calls.length).toBe(0); }); describe("target", () => { it("calls history.navigate if target is not defined", () => { let mockNavigate = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test">{() => null}</AsyncLink> </Router>, node ); let a = node.querySelector("a"); let event = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; act(() => { Simulate.click(a, event); }); expect(mockNavigate.mock.calls.length).toBe(1); }); it("doesn't call history.navigate if target is defined", () => { let mockNavigate = jest.fn(); let routes = prepareRoutes([ { name: "Test", path: "test" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); router.history.navigate = mockNavigate; let Router = createRouterComponent(router); ReactDOM.render( <Router> <AsyncLink name="Test" target="_blank"> {() => null} </AsyncLink> </Router>, node ); let a = node.querySelector("a"); let event = { defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, metaKey: null, altKey: null, ctrlKey: null, shiftKey: null, button: 0 }; act(() => { Simulate.click(a, event); }); expect(mockNavigate.mock.calls.length).toBe(0); }); }); }); });
the_stack
import {BytecodeOptions, HaikuBytecode, IHaikuClock, IHaikuContext, IRenderer} from './api'; import Config from './Config'; import HaikuBase from './HaikuBase'; import HaikuClock from './HaikuClock'; import HaikuComponent from './HaikuComponent'; const pkg = require('./../package.json'); const VERSION = pkg.version; export interface ComponentFactory { (mount: Element, config: BytecodeOptions): HaikuComponent; bytecode?: HaikuBytecode; renderer?: IRenderer; mount?: Element; context?: HaikuContext; component?: HaikuComponent; PLAYER_VERSION?: string; CORE_VERSION?: string; } /** * @class HaikuContext * @description Represents the root of a Haiku component tree within an application. * A Haiku component tree may contain many components, but there is only one context. * The context is where information shared by all components in the tree should go, e.g. clock time. */ // tslint:disable:variable-name export default class HaikuContext extends HaikuBase implements IHaikuContext { clock: IHaikuClock; component: HaikuComponent; config; container; CORE_VERSION; mount; platform; PLAYER_VERSION; renderer; tickables; ticks; unmountedTickables; constructor (mount, renderer, platform, bytecode, config) { super(); if (!renderer) { throw new Error('Context requires a renderer'); } if (!bytecode) { throw new Error('Context requires bytecode'); } this.PLAYER_VERSION = VERSION; // #LEGACY this.CORE_VERSION = VERSION; this.assignConfig(config || {}, null); this.mount = mount; // Make some Haiku internals available on the mount object for hot editing hooks, or for debugging convenience. if (this.mount && !this.mount.haiku) { this.mount.haiku = { context: this, }; } this.renderer = renderer; // Initialize sets up top-level dom listeners so we don't run it if we don't have a mount if (this.mount && this.renderer.initialize) { this.renderer.initialize(); } this.platform = platform; // List of tickable objects managed by this context. These are invoked on every clock tick. // These are removed when context unmounts and re-added in case of re-mount this.tickables = []; // Our own tick method is the main driver for animation inside of this context this.tickables.push({performTick: this.tick.bind(this)}); if (this.config.frame) { this.tickables.push({performTick: this.config.frame}); } this.clock = new HaikuClock(this.tickables, this.config.clock || {}); // We need to start the loop even if we aren't autoplaying, // because we still need time to be calculated even if we don't 'tick'. this.clock.run(); this.container = this.renderer.createContainer({ elementName: bytecode, attributes: {}, children: [bytecode.template], }); this.component = new HaikuComponent( bytecode, this, // context null, // host this.config, this.container, ); // If configured, bootstrap the Haiku right-click context menu if (this.mount && this.renderer.menuize && this.config.contextMenu !== 'disabled') { this.renderer.menuize(this.component); } // By default, Haiku tracks usage by transmitting component metadata to Mixpanel when initialized. // Developers can disable this by setting the `mixpanel` option to a falsy value. // To transmit metadata to your own Mixpanel account, set the `mixpanel` option to your Mixpanel API token. // Don't set up Mixpanel if we're running on localhost since we don't want test data to be tracked if ( this.mount && this.platform && this.platform.location && this.platform.location.hostname !== 'localhost' && this.platform.location.hostname !== '0.0.0.0' ) { // If configured, initialize Mixpanel with the given API token if (this.renderer.mixpanel && this.config.mixpanel) { this.renderer.mixpanel(this.config.mixpanel, this.component); } } // Just a counter for the number of clock ticks that have occurred; used to determine first-frame for mounting this.ticks = 0; // Assuming the user wants the app to mount immediately (the default), let's do the mount. if (this.config.automount) { // Starting the clock has the effect of doing a render at time 0, a.k.a., mounting! this.component.getClock().start(); } } /** * @method getRootComponent * @description Returns the HaikuComponent managed by this context. */ getRootComponent () { return this.component; } /** * @method getClock * @description Returns the HaikuClock instance associated with this context. */ getClock (): IHaikuClock { return this.clock; } /** * @method contextMount * @description Adds this context the global update loop. */ contextMount () { if (this.unmountedTickables) { // Gotta remember to _remove_ the tickables so we don't end up with dupes if we re-mount later const unmounted = this.unmountedTickables.splice(0); for (let i = 0; i < unmounted.length; i++) { this.addTickable(unmounted[i]); } } } /** * @method contextUnmount * @description Removes this context from global update loop. */ contextUnmount () { this.unmountedTickables = this.tickables.splice(0); } destroy () { super.destroy(); this.component.destroy(); this.renderer.destroy(); this.clock.destroy(); } /** * @method addTickable * @description Add a tickable object to the list of those that will be called on every clock tick. * This only adds if the given object isn't already present in the list. */ addTickable (tickable) { let alreadyAdded = false; for (let i = 0; i < this.tickables.length; i++) { if (tickable === this.tickables[i]) { alreadyAdded = true; break; } } if (!alreadyAdded) { this.tickables.push(tickable); } } /** * @method assignConfig * @description Updates internal configuration options, assigning those passed in. * Also updates the configuration of the clock instance and managed component instance. */ assignConfig (config: BytecodeOptions, options?: {skipComponentAssign?: boolean}) { this.config = {...config}; if (this.clock) { // This method may run before the clock is initialized this.clock.assignOptions(this.config.clock); } if (this.component) { // This method may run before the managed component is initialized if (!options || !options.skipComponentAssign) { // Avoid an infinite loop if the managed component is updating us this.component.assignConfig(this.config); } } } /** * @method getContainer * @description Returns the container, a virtual-element-like object that provides sizing * constraints at the topmost/outermost level from which the descendant layout can be calculated. */ getContainer (doForceRecalc = false) { if (doForceRecalc || this.renderer.shouldCreateContainer) { this.renderer.createContainer(this.container); // The container is mutated in place } return this.container; } /** * @method performFullFlushRender * @description Updates the entire component tree, flushing updates to the rendering medium. */ performFullFlushRender () { if (!this.mount) { return; } this.component.performFullFlushRenderWithRenderer( this.renderer, this.config, ); } /** * @method performPatchRender * @description Updates the component tree, but only updating properties we know have changed. */ performPatchRender (skipCache = false) { if (!this.mount) { return; } this.component.performPatchRenderWithRenderer( this.renderer, this.config, skipCache, ); } /** * @method updateMountRootStyles * @description Reconciles the properties of the rendering medium's mount element with any * configuration options that have been passed in, e.g. CSS overflow settings. */ updateMountRootStyles () { if (!this.mount) { return; } // We can assume the mount has only one child since we only mount one component into it (#?) const root = this.mount && this.mount.children[0]; if (root) { if (this.config.position && root.style.position !== this.config.position) { root.style.position = this.config.position; } if (this.config.overflow) { root.style.overflow = this.config.overflow; } else { if ( this.config.overflowX && root.style.overflowX !== this.config.overflowX ) { root.style.overflowX = this.config.overflowX; } if ( this.config.overflowY && root.style.overflowY !== this.config.overflowY ) { root.style.overflowY = this.config.overflowY; } } } } /** * @method tick * @description Advances the component animation by one tick. Note that one tick is not necessarily * equivalent to one frame. If the animation frame loop is running too fast, the clock may wait before * incrementing the frame number. In other words, a tick implies an update but not necessarily a change. */ tick (skipCache = false) { try { let flushed = false; // Only continue ticking and updating if our root component is still activated and awake; // this is mainly a hacky internal hook used during hot editing inside Haiku Desktop if (!this.component.isDeactivated && !this.component.isSleeping) { // This incrementation MUST occur before the blocks below, especially #callRemount, // because #callRemount (and friends?) may result in a 'component:will-mount' action // firing, which in turn may call this.pause()/this.gotoAndStop(). Internally those // methods rely on #tick(), which means they can result in an infinite remount loop. const ticks = this.ticks; this.ticks++; // Perform any necessary updates that have to occur in all copmonents in the scene this.component.visitGuestHierarchy((component) => { // State transitions are bound to clock time, so we update them on every tick component.tickStateTransitions(); // The top-level component isn't controlled through playback status, so we must skip it // otherwise its behavior will not reflect the playback setting specified via options if (component === this.component) { return; } }); // After we've hydrated the tree the first time, we can proceed with patches -- // unless the component indicates it wants a full flush per its internal settings. if (this.component.shouldPerformFullFlush() || this.config.forceFlush || ticks < 1) { this.performFullFlushRender(); flushed = true; } else { this.performPatchRender(skipCache); } // We update the mount root *after* we complete the render pass because configuration // from the top level should unset anything that the component set. // Specifically important wrt overflow, where the component probably defines // overflowX/overflowY: hidden, but our configuration might define them as visible. this.updateMountRootStyles(); // Do any initialization that may need to occur if we happen to be on the very first tick if (ticks < 1) { // If this is the 0th (first) tick, notify anybody listening that we've mounted // If we've already flushed, _don't_ request to trigger a re-flush (second arg) this.component.callRemount(null, flushed); } } } catch (exception) { console.warn('[haiku core] caught error during tick', exception); if (this.component) { this.component.deactivate(); } } } /** * @method getGlobalUserState * @description Since the core renderer is medium-agnostic, we rely on the renderer to provide data * about the current user (the mouse position, for example). This method is just a convenience wrapper. */ getGlobalUserState () { return this.renderer && this.renderer.getUser && this.renderer.getUser(); } /** * @function createComponentFactory * @description Returns a factory function that can create a HaikuComponent and run it upon a mount. * The created instance runs using the passed-in renderer, bytecode, options, and platform. */ static createComponentFactory = ( rendererClass, bytecode, haikuConfigFromFactoryCreator, platform, ): ComponentFactory => { if (!rendererClass) { throw new Error('A runtime renderer class object is required'); } if (!bytecode) { throw new Error('A runtime `bytecode` object is required'); } // Note that haiku Config may be passed at this level, or below at the factory invocation level. const haikuConfigFromTop = Config.build( { // The seed value should remain constant from here on, because it is used for PRNG seed: Config.seed(), // The now-value is used to compute a current date with respect to the current time timestamp: Date.now(), }, // The bytecode itself may contain configuration for playback, etc., but is lower precedence than config passed in bytecode && bytecode.options, haikuConfigFromFactoryCreator, ); /** * @function HaikuComponentFactory * @description Creates a HaikuContext instance, with a component, and returns the component. * The (renderer, bytecode) pair are bootstrapped into the given mount element, and played. */ const HaikuComponentFactory: ComponentFactory = (mount, haikuConfigFromFactory): HaikuComponent => { // Merge any config received "late" with the config we might have already gotten during bootstrapping const haikuConfigMerged = Config.build(haikuConfigFromTop, haikuConfigFromFactory); // Previously these were initialized in the scope above, but I moved them here which seemed to resolve // an initialization/mounting issue when running in React. const renderer = new rendererClass(mount, haikuConfigMerged); const context = new HaikuContext(mount, renderer, platform, bytecode, haikuConfigMerged); const component = context.getRootComponent(); // These properties are added for convenience as hot editing hooks inside Haiku Desktop (and elsewhere?). // It's a bit hacky to just expose these in this way, but it proves pretty convenient downstream. HaikuComponentFactory.bytecode = bytecode; HaikuComponentFactory.renderer = renderer; // Note that these ones could theoretically change if this factory was called more than once; use with care HaikuComponentFactory.mount = mount; HaikuComponentFactory.context = context; HaikuComponentFactory.component = component; // Finally, return the HaikuComponent instance which can also be used for programmatic behavior return component; }; HaikuComponentFactory.PLAYER_VERSION = VERSION; // #LEGACY HaikuComponentFactory.CORE_VERSION = VERSION; return HaikuComponentFactory; }; // Also expose so we can programatically choose an instance on the page static PLAYER_VERSION = VERSION; // #LEGACY static CORE_VERSION = VERSION; // #LEGACY static __name__ = 'HaikuContext'; }
the_stack
import * as path from "path"; const uuidv1 = require("uuid/v1"); import * as vsts from "azure-devops-node-api/WebApi"; import * as wit from "azure-devops-node-api/interfaces/WorkItemTrackingInterfaces"; import * as bi from "azure-devops-node-api/interfaces/BuildInterfaces"; import * as tasks from "azure-pipelines-task-lib"; import { isNullOrWhitespace } from "./inputs"; export interface ReleaseEnvironmentVariables { releaseName: string; releaseId: string; releaseUri: string; } export interface BuildEnvironmentVariables { buildNumber: string; buildId: number; buildName: string; buildRepositoryName: string; buildRepositoryProvider: string; buildRepositoryUri: string; buildSourceVersion: string; } export interface AgentEnvironmentVariables { agentBuildDirectory: string; } export interface SystemEnvironmentVariables { projectName: string; projectId: string; teamCollectionUri: string; defaultWorkingDirectory: string; } export type VstsEnvironmentVariables = ReleaseEnvironmentVariables & BuildEnvironmentVariables & AgentEnvironmentVariables & SystemEnvironmentVariables; export const getVstsEnvironmentVariables = (): VstsEnvironmentVariables => { return { projectId: process.env["SYSTEM_TEAMPROJECTID"], projectName: process.env["SYSTEM_TEAMPROJECT"], buildNumber: process.env["BUILD_BUILDNUMBER"], buildId: Number(process.env["BUILD_BUILDID"]), buildName: process.env["BUILD_DEFINITIONNAME"], buildRepositoryName: process.env["BUILD_REPOSITORY_NAME"], releaseName: process.env["RELEASE_RELEASENAME"], releaseUri: process.env["RELEASE_RELEASEWEBURL"], releaseId: process.env["RELEASE_RELEASEID"], teamCollectionUri: process.env["SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"], defaultWorkingDirectory: process.env["SYSTEM_DEFAULTWORKINGDIRECTORY"], buildRepositoryProvider: process.env["BUILD_REPOSITORY_PROVIDER"], buildRepositoryUri: process.env["BUILD_REPOSITORY_URI"], buildSourceVersion: process.env["BUILD_SOURCEVERSION"], agentBuildDirectory: process.env["AGENT_BUILDDIRECTORY"], }; }; export const generateReleaseNotesContent = (environment: VstsEnvironmentVariables, linkedItemReleaseNote: string, customReleaseNotes: string) => { let notes: string = "Release created by "; const buildUri = `${environment.teamCollectionUri}${encodeURIComponent(environment.projectName)}/_build/index?_a=summary&buildId=${environment.buildId}`; if (!isNullOrWhitespace(environment.releaseId)) { notes += `Release Management Release [${environment.releaseName} #${environment.releaseId}](${environment.releaseUri}) `; } if (environment.buildId) { notes += `Build [${environment.buildName} #${environment.buildNumber}](${buildUri}) from the ${environment.buildRepositoryName} repository `; } notes += `in Team Project ${environment.projectName}`; if (!isNullOrWhitespace(linkedItemReleaseNote)) { notes += `\r\n\r\n${linkedItemReleaseNote}`; } if (!isNullOrWhitespace(customReleaseNotes)) { notes += `\r\n\r\n**Custom Notes:**`; notes += `\r\n\r\n${customReleaseNotes}`; } return notes; }; export const createReleaseNotesFile = (content: () => string, directory: string): string => { const filePath = path.join(directory, `release-notes-${uuidv1()}.md`); tasks.writeFile(filePath, content(), { encoding: "utf8" }); return filePath; }; export const getWorkItemState = (workItem: wit.WorkItem) => { return `<span class='label'>${workItem && workItem.fields ? workItem.fields["System.State"] : ""}</span>`; }; export const getWorkItemTags = (workItem: wit.WorkItem) => { if (workItem && workItem.fields && !isNullOrWhitespace(workItem.fields["System.Tags"])) { const tags = workItem.fields["System.Tags"].split(";"); return tags.reduce((prev: string, current: string) => { return (prev += `<span class='label label-info'>${current}</span>`); }, ""); } return ""; }; export const getLinkedReleaseNotes = async (client: vsts.WebApi, includeComments: boolean, includeWorkItems: boolean) => { const environment = getVstsEnvironmentVariables(); console.log(`Environment = ${environment.buildRepositoryProvider}`); console.log(`Comments = ${includeComments}, WorkItems = ${includeWorkItems}`); try { const changes = await client.getBuildApi().then((x) => x.getBuildChanges(environment.projectName, environment.buildId)); let releaseNotes = ""; let newLine = "\r\n\r\n"; if (includeComments) { if (environment.buildRepositoryProvider === "TfsVersionControl") { console.log("Adding changeset comments to release notes"); releaseNotes += changes.reduce((prev, current) => { return prev + `* [${current.id} - ${current.author.displayName}](${getChangesetUrl(environment, current.location)}): ${current.message}${newLine}`; }, `**Changeset Comments:**${newLine}`); } else if (environment.buildRepositoryProvider === "TfsGit") { /* TfsGit repo has a known URL that individual commits can be linked to, so the release notes have markdown URLs */ console.log("Adding commit message to release notes"); releaseNotes += changes.reduce((prev, current) => { return prev + `* [${current.id} - ${current.author.displayName}](${getCommitUrl(environment, current)}): ${current.message}${newLine}`; }, `**Commit Messages:**${newLine}`); } else { /* This could be any other git repo like Git, GitHub, SVN etc. We don't know how to link to the commits here, so leave out the URLs. */ console.log("Adding commit message to release notes"); releaseNotes += changes.reduce((prev, current) => { return prev + `* ${current.id} - ${current.author.displayName}: ${current.message}${newLine}`; }, `**Commit Messages:**${newLine}`); } } if (includeWorkItems) { console.log("adding work items to release notes"); releaseNotes += `**Work Items:**${newLine}`; const workItemRefs = await client.getBuildApi().then((x) => x.getBuildWorkItemsRefs(environment.projectName, environment.buildId)); if (workItemRefs.length > 0) { var workItems = await client.getWorkItemTrackingApi().then((x) => x.getWorkItems(workItemRefs.map((x) => Number(x.id)))); let workItemEditBaseUri = `${environment.teamCollectionUri}${environment.projectId}/_workitems/edit`; releaseNotes += workItems.reduce((prev, current) => { return (prev += `* [${current.id}](${workItemEditBaseUri}/${current.id}): ${current.fields["System.Title"]} ${getWorkItemState(current)} ${getWorkItemTags(current)} ${newLine}`); }, ""); } } console.log(`Release notes:\r\n${releaseNotes}`); return releaseNotes; } catch (ex) { console.log("An exception was thrown while building the release notes."); console.log(ex); console.log("See https://github.com/OctopusDeploy/OctoTFS/issues/107 for more details."); console.log("The release notes will be empty."); return ""; } }; const getChangesetUrl = (environment: VstsEnvironmentVariables, apiUrl: string) => { let workItemId = apiUrl.substr(apiUrl.lastIndexOf("/") + 1); return `${environment.teamCollectionUri}${environment.projectId}/_versionControl/changeset/${workItemId}`; }; const getCommitUrl = (environment: VstsEnvironmentVariables, change: bi.Change) => { let commitId = change.id; const segments = change.location.split("/"); const repositoryId = segments[segments.length - 3]; return `${environment.teamCollectionUri}${environment.projectId}/_git/${repositoryId}/commit/${commitId}`; }; export const createVstsConnection = (environment: SystemEnvironmentVariables) => { var vstsAuthorization = tasks.getEndpointAuthorization("SystemVssConnection", true); var token = vstsAuthorization.parameters["AccessToken"]; let authHandler = vsts.getPersonalAccessTokenHandler(token); return new vsts.WebApi(environment.teamCollectionUri, authHandler); }; export const getVcsTypeFromProvider = (buildRepositoryProvider: string) => { switch (buildRepositoryProvider) { case "TfsGit": case "GitHub": return "Git"; case "TfsVersionControl": return "TFVC"; default: return buildRepositoryProvider; } }; export const getBuildBranch = async (client: vsts.WebApi) => { const environment = getVstsEnvironmentVariables(); const api = await client.getBuildApi(); return (await api.getBuild(environment.buildId, environment.projectName)).sourceBranch; }; export const getBuildChanges = async (client: vsts.WebApi) => { const environment = getVstsEnvironmentVariables(); const api = await client.getBuildApi(); const gitApi = await client.getGitApi(); const changes = await api.getBuildChanges(environment.projectName, environment.buildId, undefined, 100000); if (environment.buildRepositoryProvider === "TfsGit") { let promises = changes.map(async (x) => { if (x.messageTruncated) { const segments = x.location.split("/"); const repositoryId = segments[segments.length - 3]; try { const commit = await gitApi.getCommit(x.id, repositoryId); x.message = commit.comment; } catch (err) { tasks.warning(`Using a truncated commit message for commit ${x.id}, because an error occurred while fetching the full message. ${err}`); } } return x; }); await Promise.all(promises); } return changes; };
the_stack