text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
module AnimationVerifier { "use strict"; export var rectBefore = null; export var rectAfter = null; export function VerifyEachElementStatusChange(f) { /// <summary> /// Verify each element using the client rectangle before and after the animation/transition. /// </summary> /// <param name="f" type="Function"> /// When verifing translate or scale animations, the input parameters could be either single element or an array of elements. /// This function is used to avoid dupication of code by saying if it is an array, we'll check each element by going through a loop. /// If it is a single element, just check this one. The verification needs the client rectangle of the DOM element(s) /// before and after the animation/transition. /// </param> /// <returns type="bool"/> function compareDouble(d1, d2, precision) { if (Math.abs(d1 - d2) <= precision) { return true; } else { return false; } } var ret = true; if (Array.isArray(AnimationVerifier.rectBefore)) { if (AnimationVerifier.rectBefore.length !== AnimationVerifier.rectAfter.length) { ret = false; } else { for (var i = 0; ret && i < AnimationVerifier.rectBefore.length; i++) { ret = f(AnimationVerifier.rectBefore[i], AnimationVerifier.rectAfter[i], compareDouble); } } } else { ret = f(AnimationVerifier.rectBefore, AnimationVerifier.rectAfter, compareDouble); } return ret; } export function VerifyCoordinateTransitionInProgress(startX, startY, destX, destY, currX, currY) { /// <summary> /// Verify translation mid-animations state /// </summary> /// <param name="startX" type="Integer"> /// Specifies the starting x-coordinate /// </param> /// <param name="startY" type="Integer"> /// Specifies the starting y-coordinate /// </param> /// <param name="destX" type="Integer"> /// Specifies the destination x-coordinate /// </param> /// <param name="destY" type="Integer"> /// Specifies the destination y-coordinate /// </param> /// <param name="currX" type="Integer"> /// Specifies the current x-coordinate /// </param> /// <param name="currY" type="Integer"> /// Specifies the current y-coordinate /// </param> /// <returns type="bool"/> if (currX == 0 && currY == 0) { LiveUnit.LoggingCore.logComment("WARNING: Current X,Y Coordinates are (0,0)"); LiveUnit.LoggingCore.logComment("Likely reason for these coordinates: Animation 'complete' promise returned before 'transitionend' fired. Thus, coordinates test in transitionEndTestHandler() will be non-existant -> (0,0)"); return true; } if (destX === startX) { //if (X isn't moving) make sure Y is in between start and destination coordinates return ((currY >= startY && currY <= destY) || (currY <= startY && currY >= destY)); } else if (destY === startY) { //if (Y isn't moving) make sure X is in between start and destination coordinates return ((currX >= startX && currX <= destX) || (currX <= startX && currX >= destX)); } else { //if (both X && Y are moving) make sure X and Y are in between start and destination coordinates return ((currX <= startX && currX >= destX && currY >= startY && currY <= destY) || //(start >= X >= dest) && (start <= Y <= dest) (currX <= startX && currX >= destX && currY <= startY && currY >= destY) || //(start >= X >= dest) && (start >= Y >= dest) (currX >= startX && currX <= destX && currY >= startY && currY <= destY) || //(start <= X <= dest) && (start <= Y <= dest) (currX >= startX && currX <= destX && currY <= startY && currY >= destY) //(start <= X <= dest) && (start >= Y >= dest) ); } } export function VerifyDestinationCoordinates(refX, refY, actX, actY) { /// <summary> /// Verify translation end state /// </summary> /// <param name="refX" type="Integer"> /// Specifies the intended destination x-coordinate /// </param> /// <param name="refY" type="Integer"> /// Specifies the intended destination y-coordinate /// </param> /// <param name="actX" type="Integer"> /// Specifies the actual destination x-coordinate /// </param> /// <param name="actY" type="Integer"> /// Specifies the actual destination y-coordinate /// </param> /// <returns type="bool"/> var toleranceX = Math.abs(refX * (.05)); var toleranceY = Math.abs(refY * (.05)); var lowerBoundX = refX - toleranceX; var upperBoundX = refX + toleranceX; var lowerBoundY = refY - toleranceY; var upperBoundY = refY + toleranceY; return (lowerBoundX <= actX && upperBoundX >= actX && lowerBoundY <= actY && upperBoundY >= actY); } //Verify translate2D transition, final state should be the same as diffX, diffY export function VerifyTranslate2DTransition(diffX, diffY) { /// <summary> /// Verify translate 2D transition /// </summary> /// <param name="diffX" type="Integer"> /// Specifies the vertical translate distance /// </param> /// <param name="diffY" type="Integer"> /// Specifies the vertical translate distance /// </param> /// <returns type="bool"/> var ret = true; return AnimationVerifier.VerifyEachElementStatusChange(function (before, after, compareDouble) { var hor = after.left - before.left; var ver = after.top - before.top; if (!compareDouble(diffX, hor, 0.05)) { LiveUnit.LoggingCore.logComment("Error:Horizontal move is not correct. should be:" + diffX + " currently:" + hor); ret = false; } if (!compareDouble(diffY, ver, 0.05)) { LiveUnit.LoggingCore.logComment("Error:Vertical move is not correct. Should be:" + diffY + " currently:" + ver); ret = false; } return ret; }); } export function verifyTranslate2DAnimation(diffX, diffY, option) { /// <summary> /// Verify translate 2D animation /// </summary> /// <param name="diffX" type="Integer"> /// Specifies the vertical translate distance /// </param> /// <param name="diffY" type="Integer"> /// Specifies the horizontal translate distance /// </param> /// <param name="option"> /// {isVertical:true/false, isRTL:true/false} /// </param> /// <returns type="bool"/> var ret = true; var hor, ver; //For vertical translate, the default setting can be positive or negative. If default is positive, current state must be between 0 and default (0 < current < default). //If default is negative, current state must be between default and 0 (defautl < current < 0). The horizontal movement should be same as diffY. function verifyEachTranslate(hor, ver, diffX, diffY, compareDouble) { if (!option.isVertical) { if ((diffX > 0) && (hor >= diffX || hor <= 0)) { LiveUnit.LoggingCore.logComment("Error:Horizontal move is not correct. Should be between 0 and:" + diffX + " currently:" + hor); ret = false; } if ((diffX < 0) && (hor <= diffX || hor >= 0)) { LiveUnit.LoggingCore.logComment("Error:Horizontal move is not correct. Should be between 0 and:" + diffX + " currently:" + hor); ret = false; } if (!compareDouble(diffY, ver, 0.01)) { LiveUnit.LoggingCore.logComment("ver:" + ver); LiveUnit.LoggingCore.logComment("Error:Veritical move is not correct. Should be: " + diffY + " currently:" + ver); ret = false; } } else { if ((diffY > 0) && (ver >= diffY || ver <= 0)) { LiveUnit.LoggingCore.logComment("Error:Vertical move is not correct. Should be between 0 and:" + diffY + " currently:" + ver); ret = false; } if ((diffY < 0) && (ver <= diffY || ver >= 0)) { LiveUnit.LoggingCore.logComment("Error:Vertical move is not correct. Should be between 0 and:" + diffY + " currently:" + ver); ret = false; } if (!compareDouble(diffX, hor, 0.01)) { LiveUnit.LoggingCore.logComment("Error:Vertical move is not correct. Should be :" + diffX + " currently:" + hor); ret = false; } } return ret; } return AnimationVerifier.VerifyEachElementStatusChange(function (before, after, compareDouble) { // Horizontal offsets are flipped in RTL. if (option.isRTL) { hor = before.left - after.left; LiveUnit.LoggingCore.logComment("before:" + before.left); LiveUnit.LoggingCore.logComment("after:" + after.left); } else { hor = after.left - before.left; } var ver = after.top - before.top; return verifyEachTranslate(hor, ver, diffX, diffY, compareDouble); }); } export function VerifyScale2DTransition(ratioX, ratioY) { /// <summary> /// Verify scale 2D transition /// </summary> /// <param name="ratioX" type="Integer"> /// Specifies the vertical scaling factor /// </param> /// <param name="ratioY" type="Integer"> /// Specifies the horizontal scaling factor /// </param> /// <returns type="bool"/> var ret = true; return AnimationVerifier.VerifyEachElementStatusChange(function (before, after, compareDouble) { var actualRatioX = (after.right - after.left) / (before.right - before.left); var actualRatioY = (after.bottom - after.top) / (before.bottom - before.top); if (!compareDouble(actualRatioX, ratioX, 0.005)) { LiveUnit.LoggingCore.logComment("Error:Horizontal scale is not correct. should be:" + ratioX + " currently:" + actualRatioX); ret = false; } if (!compareDouble(actualRatioY, ratioY, 0.005)) { LiveUnit.LoggingCore.logComment("Error:Vertical scale is not correct. should be:" + ratioY + " currently:" + actualRatioY); ret = false; } return ret; }); } export function VerifyScale2DAnimation(ratioX, ratioY) { /// <summary> /// Verify scale 2D animation /// </summary> /// <param name="ratioX" type="Integer"> /// Specifies the vertical scaling factor /// </param> /// <param name="ratioY" type="Integer"> /// Specifies the horizontal scaling factor /// </param> /// <returns type="bool"/> var ret = true; return AnimationVerifier.VerifyEachElementStatusChange(function (before, after, compareDouble) { var actualRatioX = (after.right - after.left) / (before.right - before.left); var actualRatioY = (after.bottom - after.top) / (before.bottom - before.top); if ((actualRatioX === 1) || (actualRatioY === 1)) { LiveUnit.LoggingCore.logComment("Error:Horizontal scale is not correct. should between " + ratioX + " and " + ratioY + "currently ratioX=" + actualRatioX + " ratioY=" + actualRatioY); ret = false; } if (actualRatioX <= ratioX || actualRatioY <= ratioY) { LiveUnit.LoggingCore.logComment("Error:Horizontal scale is not correct. should between " + ratioX + " and " + ratioY + "currently ratioX=" + actualRatioX + " ratioY=" + actualRatioY); ret = false; } return ret; }); } export function VerifyOpacityTransition(elem, value) { /// <summary> /// Verify opacity transition. /// </summary> /// <param name="elem" type="object"> /// The DOM element(s) need to be verified. /// </param> /// <param name="value" type="Integer/double/float"> /// Final opacity value. /// </param> /// <returns type="bool"/> /// It verify if the opacity change to the expected value after animation. var ret = true; var opacity: number; if (Array.isArray(elem)) { for (var i = 0; i < elem.length; i++) { opacity = +(window.getComputedStyle(elem[i], null).getPropertyValue('opacity')); if (opacity !== value) { var tolerance = .01; if (opacity > (value + tolerance) || opacity < (value - tolerance)) { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be: " + value + "currently is: " + opacity); ret = false; break; } } } } else { opacity = +(window.getComputedStyle(elem, null).getPropertyValue('opacity')); if (opacity !== value) { var tolerance = .01; if (opacity > (value + tolerance) || opacity < (value - tolerance)) { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be: " + value + "currently is: " + opacity); ret = false; } } } return ret; } export function VerifyOpacityTransitionInProgress(elem) { /// <summary> /// Verify opacity transition. /// </summary> /// <returns type="bool"/> var ret = true; var opacity: number; if (Array.isArray(elem)) { for (var i = 0; i < elem.length; i++) { opacity = +(window.getComputedStyle(elem[i], null).getPropertyValue('opacity')); if (opacity >= 0 && opacity <= 1) { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be between 0 and 1, currently is: " + opacity); ret = false; break; } } } else { opacity = +(window.getComputedStyle(elem, null).getPropertyValue('opacity')); if (opacity >= 0 && opacity <= 1) { ret = true; } else { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be between 0 and 1, currently is: " + opacity); ret = false; } } return ret; } export function VerifyOpacityAnimation(elem) { /// <summary> /// Verify opacity transition. /// </summary> /// <returns type="bool"/> var ret = true; var opacity: number; if (Array.isArray(elem)) { for (var i = 0; i < elem.length; i++) { opacity = +(window.getComputedStyle(elem[i], null).getPropertyValue('opacity')); if (opacity === 0 || opacity === 1) { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be between 0 and 1, currently is: " + opacity); ret = false; break; } } } else { opacity = +(window.getComputedStyle(elem, null).getPropertyValue('opacity')); LiveUnit.LoggingCore.logComment("opacity:" + opacity); if (opacity === 0 || opacity === 1) { LiveUnit.LoggingCore.logComment("Opacity is not correct. Should be between 0 and 1, currently is: " + opacity); ret = false; } } return ret; } }
the_stack
import React, { Component, useLayoutEffect, useState } from 'react'; import { BREAKPOINTS } from '@govuk-react/constants'; import { H2, H4 } from '@govuk-react/heading'; import SectionBreak from '@govuk-react/section-break'; import Table from '@govuk-react/table'; import { MemoryRouter, Route, Link } from 'react-router-dom'; import { useMedia } from 'react-use-media'; import { Tabs } from '.'; const flip2dArray = (prev, next) => next.map((item, index) => [...(prev[index] || []), next[index]]); function setTabIndex(tabIndex: number): void { return this.setState({ tabIndex, }); } function handleClick({ event: e, index }: { event: React.MouseEvent<HTMLAnchorElement>; index: number }): void { /* eslint-disable-next-line no-undef */ const mql = window.matchMedia(`(min-width: ${BREAKPOINTS.TABLET})`); if (mql.matches) { e.preventDefault(); } return this.setTabIndex(index); } const sharedDefaultProps = { defaultIndex: 0, }; interface SharedProps { defaultIndex?: number; } const tableHead = ( <Table.Row> <Table.CellHeader>Case manager</Table.CellHeader> <Table.CellHeader>Cases opened</Table.CellHeader> <Table.CellHeader>Cases closed</Table.CellHeader> </Table.Row> ); const arrTabularTabs = [ { title: 'Past day', arr: [ [3, 1, 2], [0, 0, 0], ], id: 'past-day', }, { title: 'Past week', arr: [ [24, 16, 24], [18, 20, 27], ], id: 'past-week', }, { title: 'Past month', arr: [ [98, 122, 126], [95, 131, 142], ], id: 'past-month', }, { title: 'Past year', arr: [ [1380, 1129, 1539], [1472, 1083, 1265], ], id: 'past-year', }, ]; class TableTabs extends Component<SharedProps, { tabIndex: number }> { static defaultProps = sharedDefaultProps; setTabIndex; handleClick; constructor(props: SharedProps) { super(props); this.state = { tabIndex: props.defaultIndex }; this.setTabIndex = setTabIndex.bind(this); this.handleClick = handleClick.bind(this); } render(): JSX.Element { const { tabIndex } = this.state; return ( <Tabs> <Tabs.Title>Contents</Tabs.Title> <Tabs.List> {arrTabularTabs.map(({ id, title }, index) => ( <Tabs.Tab key={`${title}-tabHeader`} onClick={(event) => this.handleClick({ event, index })} href={`#${id}`} selected={tabIndex === index} > {title} </Tabs.Tab> ))} </Tabs.List> {arrTabularTabs.map(({ arr, id, title }, index) => ( <Tabs.Panel selected={tabIndex === index} key={`${title}-tabPanel`} id={id}> <H2>{title}</H2> <Table head={tableHead}> {[['David Francis', 'Paul Farmer', 'Rita Patel'], ...arr].reduce(flip2dArray, []).map((innerArr) => ( <Table.Row key={`${innerArr.join()}-col`}> {innerArr.map((elem) => ( <Table.Cell key={`${elem}-row`}>{elem}</Table.Cell> ))} </Table.Row> ))} </Table> </Tabs.Panel> ))} </Tabs> ); } } /* eslint-disable-next-line react/no-multi-comp */ class SimpleTabs extends Component<SharedProps, { tabIndex: number }> { static defaultProps = sharedDefaultProps; setTabIndex; handleClick; constructor(props: SharedProps) { super(props); this.state = { tabIndex: props.defaultIndex }; this.setTabIndex = setTabIndex.bind(this); this.handleClick = handleClick.bind(this); } render(): JSX.Element { const { tabIndex } = this.state; return ( <Tabs> <Tabs.Title>Contents</Tabs.Title> <Tabs.List> <Tabs.Tab onClick={(event) => this.handleClick({ event, index: 0 })} selected={tabIndex === 0} href="#first-panel" > Title 1 </Tabs.Tab> <Tabs.Tab onClick={(event) => this.handleClick({ event, index: 1 })} selected={tabIndex === 1} href="#second-panel" > Title 2 </Tabs.Tab> </Tabs.List> <Tabs.Panel selected={tabIndex === 0} id="first-panel"> Panel content 1 </Tabs.Panel> <Tabs.Panel selected={tabIndex === 1} id="second-panel"> Panel content 2 </Tabs.Panel> </Tabs> ); } } const arrSimpleMapped = [ { contentListItem: 'Title 1', contentPanel: 'Mapped Panel content 1', id: 'first-panel', }, { contentListItem: 'Title 2', contentPanel: 'Mapped Panel content 2', id: 'second-panel', }, ]; /* eslint-disable-next-line react/no-multi-comp */ class SimpleMapTabs extends Component<SharedProps, { tabIndex: number }> { static defaultProps = sharedDefaultProps; setTabIndex; handleClick; constructor(props: SharedProps) { super(props); this.state = { tabIndex: props.defaultIndex }; this.setTabIndex = setTabIndex.bind(this); this.handleClick = handleClick.bind(this); } render(): JSX.Element { const { tabIndex } = this.state; return ( <Tabs> <Tabs.Title>Contents</Tabs.Title> <Tabs.List> {arrSimpleMapped.map(({ contentListItem, id }, index) => ( <Tabs.Tab key={`${contentListItem}-simpleMappedListItem`} onClick={(event) => this.handleClick({ event, index })} selected={tabIndex === index} href={`#${id}`} > {contentListItem} </Tabs.Tab> ))} </Tabs.List> {arrSimpleMapped.map(({ contentPanel, id }, index) => ( <Tabs.Panel key={`${contentPanel}-simpleMappedPanel`} selected={tabIndex === index} id={id}> <H4>{contentPanel}</H4> </Tabs.Panel> ))} </Tabs> ); } } const arrProposedBabel = [ { contentListItem: 'Title 1', contentPanel: 'Panel content 1', id: 'first-panel', }, { contentListItem: 'Title 2', contentPanel: 'Panel content 2', id: 'second-panel', }, ]; /* eslint-disable-next-line react/no-multi-comp */ class ProposedClassPropertiesPlugin extends Component<{ defaultIndex: number }, { tabIndex: number }> { static defaultProps = sharedDefaultProps; setTabIndex = setTabIndex; handleClick = handleClick; constructor(props: { defaultIndex: number }) { super(props); const { defaultIndex } = this.props; this.state = { tabIndex: defaultIndex }; } render(): JSX.Element { const { tabIndex } = this.state; return ( <Tabs> <Tabs.Title /> <Tabs.List> {arrProposedBabel.map(({ contentListItem, id }, index) => ( <Tabs.Tab key={`${contentListItem}-babelListItem`} onClick={(event) => this.handleClick({ event, index })} selected={tabIndex === index} href={`#${id}`} > {contentListItem} </Tabs.Tab> ))} </Tabs.List> {arrProposedBabel.map(({ contentPanel, id }, index) => ( <Tabs.Panel key={`${contentPanel}-babelPanel`} selected={tabIndex === index} id={id}> <H2>with Babel Plugin</H2> <SectionBreak level="L" visible /> {contentPanel} </Tabs.Panel> ))} </Tabs> ); } } const HooksExample: React.FC<SharedProps> = ({ defaultIndex }: SharedProps) => { const [tabIndex, setHooksTabIndex] = React.useState(defaultIndex); const handleTabChange = (newTabIndex) => setHooksTabIndex(newTabIndex); function hooksHandleClick({ event: e, index }) { /* eslint-disable-next-line no-undef */ const mql = window.matchMedia(`(min-width: ${BREAKPOINTS.TABLET})`); if (mql.matches) { e.preventDefault(); } return handleTabChange(index); } return ( <Tabs> <Tabs.Title>Content</Tabs.Title> <Tabs.List> {[ { content: 'Hooks Title 1', href: '#first-panel', }, { content: 'Hooks Title 2', href: '#second-panel', }, ].map(({ content, href }, index) => ( <Tabs.Tab key={href} onClick={(event) => hooksHandleClick({ event, index })} selected={tabIndex === index} href={href} > {content} </Tabs.Tab> ))} </Tabs.List> {[ { content: 'Hooks Panel content 1', id: 'first-panel', }, { content: 'Hooks Panel content 2', id: 'second-panel', }, ].map(({ content, id }, index) => ( <Tabs.Panel key={id} selected={tabIndex === index} id={id}> {content} </Tabs.Panel> ))} </Tabs> ); }; HooksExample.defaultProps = sharedDefaultProps; // This example demonstrates one way to use react-router with tabs. // The use of useMedia means it is not suitable for server-side rendering. // When in mobile mode, all panels will be shown but the route will // still be updated to match the last clicked tab title. // NB in this example react-router is in control over which panel is rendered const RouterTabs = ({ // eslint-disable-next-line react/prop-types match: { // eslint-disable-next-line react/prop-types params: { section }, }, }) => { const isTablet = useMedia(`(min-width: ${BREAKPOINTS.TABLET})`); const [prevSection, setPrevSection] = useState(undefined); useLayoutEffect(() => { // scroll to the chosen tab if it's changed if (section !== prevSection && !isTablet) { // eslint-disable-next-line no-undef document.querySelector(`#${section || 'first'}`).scrollIntoView(); } setPrevSection(section); }, [section, isTablet, prevSection]); return ( <Tabs> <Tabs.Title /> <Tabs.List> <Tabs.Tab as={Link} selected={!section} to="/"> First tab </Tabs.Tab> <Tabs.Tab as={Link} selected={section === 'test'} to="/test"> Second tab </Tabs.Tab> </Tabs.List> <Route path={isTablet ? '/' : null} exact={isTablet} render={() => ( <Tabs.Panel id="first" selected> First tab contents </Tabs.Panel> )} /> <Route path={isTablet ? '/test' : null} render={() => ( <Tabs.Panel id="test" selected> Second tab contents </Tabs.Panel> )} /> </Tabs> ); }; const ReactRouterExample: React.FC = () => ( <MemoryRouter> <div> <Route path="/:section?" component={RouterTabs} /> </div> </MemoryRouter> ); // This example demonstrates one way to use tabs with react-router in a way // that is compatible with server-side/universal rendering // NB in this example react-router does not directly control what content/panel is rendered // and on a mobile view the client will not jump to the content for the clicked title const RouterTabsSSR = ({ // eslint-disable-next-line react/prop-types match: { // eslint-disable-next-line react/prop-types params: { section }, }, }) => ( <Tabs> <Tabs.Title /> <Tabs.List> <Tabs.Tab as={Link} selected={!section} to="/"> First tab </Tabs.Tab> <Tabs.Tab as={Link} selected={section === 'test'} to="/test"> Second tab </Tabs.Tab> </Tabs.List> <Tabs.Panel selected={!section}>First tab contents</Tabs.Panel> <Tabs.Panel selected={section === 'test'}>Second tab contents</Tabs.Panel> </Tabs> ); const ReactRouterSSRExample: React.FC = () => ( <MemoryRouter> <div> <Route path="/:section?" component={RouterTabsSSR} /> </div> </MemoryRouter> ); // This example demonstrates another way to use tabs with react-router in a way // that is compatible with server-side/universal rendering // NB in this example react-router controls what content is rendered, and thus // will only show a single panel, even when the screen is at a mobile width const RouterTabsSSRSinglePanel = ({ // eslint-disable-next-line react/prop-types match: { // eslint-disable-next-line react/prop-types params: { section }, }, }) => ( <Tabs> <Tabs.Title /> <Tabs.List> <Tabs.Tab as={Link} selected={!section} to="/"> First tab </Tabs.Tab> <Tabs.Tab as={Link} selected={section === 'test'} to="/test"> Second tab </Tabs.Tab> </Tabs.List> <Route path="/" exact render={() => ( <Tabs.Panel id="first" selected> First tab contents </Tabs.Panel> )} /> <Route path="/test" render={() => ( <Tabs.Panel id="test" selected> Second tab contents </Tabs.Panel> )} /> </Tabs> ); const ReactRouterSSRSinglePanelExample: React.FC = () => ( <MemoryRouter> <div> <Route path="/:section?" component={RouterTabsSSRSinglePanel} /> </div> </MemoryRouter> ); export { HooksExample, ProposedClassPropertiesPlugin, SimpleTabs, SimpleMapTabs, TableTabs, ReactRouterExample, ReactRouterSSRExample, ReactRouterSSRSinglePanelExample, };
the_stack
import {ReactiveElement, PropertyValues} from '@lit/reactive-element'; import {property} from '@lit/reactive-element/decorators/property.js'; import {initialState, Task, TaskStatus, TaskConfig} from '../task.js'; import {generateElementName, nextFrame} from './test-helpers.js'; import {assert} from '@esm-bundle/chai'; // Note, since tests are not built with production support, detect DEV_MODE // by checking if warning API is available. const DEV_MODE = !!ReactiveElement.enableWarning; if (DEV_MODE) { ReactiveElement.disableWarning?.('change-in-update'); } suite('Task', () => { let container: HTMLElement; interface TestElement extends ReactiveElement { task: Task; a: string; b: string; c?: string; resolveTask: () => void; rejectTask: () => void; taskValue?: string; renderedStatus?: string; } const defineTestElement = ( config?: Partial<TaskConfig<unknown[], string>> ) => { class A extends ReactiveElement { task: Task; @property() a = 'a'; @property() b = 'b'; @property() c?: string; resolveTask!: () => void; rejectTask!: () => void; taskValue?: string; renderedStatus?: string; constructor() { super(); const taskConfig = { task: (...args: unknown[]) => new Promise((resolve, reject) => { this.rejectTask = () => reject(`error`); this.resolveTask = () => resolve(args.join(',')); }), }; Object.assign(taskConfig, config); this.task = new Task(this, taskConfig); } override update(changedProperties: PropertyValues): void { super.update(changedProperties); this.taskValue = this.task.value ?? this.task.error; this.task.render({ initial: () => (this.renderedStatus = 'initial'), pending: () => (this.renderedStatus = 'pending'), complete: (value: unknown) => (this.renderedStatus = value as string), error: (error: unknown) => (this.renderedStatus = error as string), }); } } customElements.define(generateElementName(), A); return A; }; const renderElement = async (el: TestElement) => { container.appendChild(el); await el.updateComplete; return el; }; const getTestElement = (config?: Partial<TaskConfig<unknown[], string>>) => { const A = defineTestElement(config); return new A(); }; const tasksUpdateComplete = nextFrame; setup(async () => { container = document.createElement('div'); document.body.appendChild(container); }); teardown(() => { if (container && container.parentNode) { container.parentNode.removeChild(container); } }); test('task without args do not run', async () => { const el = await renderElement(getTestElement()); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); el.requestUpdate(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); }); test('tasks with args run initially', async () => { const el = getTestElement({args: () => [el.a, el.b]}); await renderElement(el); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); }); test('tasks with empty args array run once', async () => { const el = getTestElement({args: () => []}); await renderElement(el); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, ``); // Change a property that provokes an update and check that task is not run. el.a = 'a1'; assert.isTrue(el.isUpdatePending); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, ``); }); test('tasks do not run when args do not change', async () => { const el = getTestElement({args: () => [el.a, el.b]}); await renderElement(el); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); // Provoke an update and check that task does not run. el.c = 'c'; assert.isTrue(el.isUpdatePending); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); }); test('tasks with args run when args change', async () => { const el = getTestElement({args: () => [el.a, el.b]}); await renderElement(el); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); // *** Changing task argument runs task el.a = 'a1'; // Check task pending. await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); // Complete task and check result. el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a1,b`); // *** Changing other task argument runs task el.b = 'b1'; // Check task pending. await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); // Complete task and check result. el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a1,b1`); }); test('tasks do not run when `autoRun` is `false`', async () => { const el = getTestElement({args: () => [el.a, el.b], autoRun: false}); await renderElement(el); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); // Provoke update and check that task is not run. el.a = 'a1'; await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); }); test('task `autoRun` is settable', async () => { const el = getTestElement({args: () => [el.a, el.b], autoRun: false}); await renderElement(el); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); // *** Set `autoRun` to `true` and change a task argument el.task.autoRun = true; el.a = 'a1'; // Check task is pending. await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); el.resolveTask(); // Check task completes. await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a1,b`); // *** Set `autoRun` to `false` and check that task does not run. el.task.autoRun = false; el.b = 'b1'; await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a1,b`); }); test('task runs when `run` called', async () => { const el = getTestElement({args: () => [el.a, el.b], autoRun: false}); await renderElement(el); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); // Task runs when `autoRun` is `false` and `run()` ia called. el.task.run(); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); // Task runs when `autoRun` is `true` and `run()` ia called. el.task.autoRun = true; el.task.run(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.PENDING); assert.equal(el.taskValue, undefined); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); }); test('task `run` optionally accepts args', async () => { const el = getTestElement({args: () => [el.a, el.b], autoRun: false}); await renderElement(el); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.INITIAL); assert.equal(el.taskValue, undefined); // Can specify arguments for this call to `run()`. el.task.run(['d', 'e']); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `d,e`); // When no arguments specified, configured arguments are used. el.task.run(); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, `a,b`); }); test('task reports error status', async () => { const el = getTestElement({args: () => [el.a, el.b]}); await renderElement(el); assert.equal(el.task.status, TaskStatus.PENDING); // Task error reported. el.rejectTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.ERROR); assert.equal(el.task.error, 'error'); assert.equal(el.task.value, undefined); assert.equal(el.taskValue, 'error'); // After error, task can be run again when arguments change. el.a = 'a1'; el.b = 'b1'; await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.PENDING); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.task.error, undefined); let expected = 'a1,b1'; assert.equal(el.task.value, expected); assert.equal(el.taskValue, expected); // After success, an error can be reported. el.a = 'a2'; el.b = 'b2'; await tasksUpdateComplete(); el.rejectTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.ERROR); assert.equal(el.task.error, 'error'); assert.equal(el.task.value, undefined); assert.equal(el.taskValue, 'error'); // After another error, task can be run again when arguments change. el.a = 'a3'; el.b = 'b3'; await tasksUpdateComplete(); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.task.error, undefined); expected = 'a3,b3'; assert.equal(el.task.value, expected); assert.equal(el.taskValue, expected); }); test('reports only most recent value', async () => { const el = getTestElement({args: () => [el.a, el.b]}); await renderElement(el); const initialFinishTask = el.resolveTask; assert.equal(el.task.status, TaskStatus.PENDING); // While 1st task is pending, change arguments, provoking a new task run. el.a = 'a1'; el.b = 'b1'; await tasksUpdateComplete(); // Complete 2nd task. assert.equal(el.task.status, TaskStatus.PENDING); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, 'a1,b1'); // Complete 1st task initialFinishTask(); assert.isFalse(el.isUpdatePending); await tasksUpdateComplete(); assert.equal(el.task.status, TaskStatus.COMPLETE); assert.equal(el.taskValue, 'a1,b1'); }); test('task.render renders current status', async () => { const el = getTestElement({args: () => [el.a, el.b], autoRun: false}); await renderElement(el); // Reports initial status When `autoRun` is `false`. assert.equal(el.renderedStatus, 'initial'); el.task.autoRun = true; // Reports pending after a task argument changes. el.a = 'a1'; await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'pending'); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'a1,b'); el.b = 'b1'; await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'pending'); // Reports error after task rejects. el.rejectTask(); await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'error'); // Reports properly after error. el.a = 'a2'; await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'pending'); el.resolveTask(); await tasksUpdateComplete(); assert.equal(el.renderedStatus, 'a2,b1'); }); test('task functions can return initial state', async () => { class TestEl extends ReactiveElement { @property() state = ''; task = new Task( this, async ([state]) => (state === 'initial' ? initialState : 'A'), () => [this.state] ); } customElements.define(generateElementName(), TestEl); const el = new TestEl(); assert.equal(el.task.status, TaskStatus.INITIAL, 'initial'); container.append(el); // After one microtask we expect the task function to have been // called, but not completed await Promise.resolve(); assert.equal(el.task.status, TaskStatus.PENDING, 'pending'); await el.task.taskComplete; assert.equal(el.task.status, TaskStatus.COMPLETE, 'complete'); assert.equal(el.task.value, 'A'); // Kick off a new task run el.state = 'initial'; // We need to wait for the element to update, and then the task to run, // so we wait a event loop turn: await new Promise((r) => setTimeout(r, 0)); assert.equal(el.task.status, TaskStatus.INITIAL, 'new initial'); }); });
the_stack
import {ActionMenu, Item} from '@react-spectrum/menu'; import assetStyles from '@adobe/spectrum-css-temp/components/asset/vars.css'; import {Avatar} from '@react-spectrum/avatar'; import {Button} from '@react-spectrum/button'; import {Card} from '..'; import {CardBase} from '../src/CardBase'; import {CardViewContext} from '../src/CardViewContext'; import {classNames, useSlotProps, useStyleProps} from '@react-spectrum/utils'; import {Content, Footer} from '@react-spectrum/view'; import {getDescription, getImage} from './utils'; import {Heading, Text} from '@react-spectrum/text'; import {IllustratedMessage} from '@react-spectrum/illustratedmessage'; import {Image} from '@react-spectrum/image'; import {Meta, Story} from '@storybook/react'; import React, {Dispatch, SetStateAction, useState} from 'react'; import {SpectrumCardProps} from '@react-types/card'; import {usePress} from '@react-aria/interactions'; import {useProvider} from '@react-spectrum/provider'; // see https://github.com/storybookjs/storybook/issues/8426#issuecomment-669021940 const StoryFn = ({storyFn}) => storyFn(); const meta: Meta<SpectrumCardProps> = { title: 'Card/default', component: Card, decorators: [storyFn => <StoryFn storyFn={storyFn} />] }; export default meta; const Template = (): Story<SpectrumCardProps> => (args) => ( <div style={{width: '208px'}}> <Card {...args} /> </div> ); /* This is a bit of a funny template, we can't get selected on a Card through context because * if there's context it assumes it's being rendered in a collection. It's just here for a quick check of styles. */ interface ISelectableCard { disabledKeys: Set<any>, selectionManager: { isSelected: () => boolean, select: () => Dispatch<SetStateAction<ISelectableCard>> } } let SelectableCard = (props) => { let [state, setState] = useState<ISelectableCard>({ disabledKeys: new Set(), selectionManager: { isSelected: () => true, select: () => setState(prev => ({ ...prev, selectionManager: { ...prev.selectionManager, isSelected: () => !prev.selectionManager.isSelected() } })) } }); let {pressProps} = usePress({onPress: () => setState(prev => ({ ...prev, selectionManager: { ...prev.selectionManager, isSelected: () => !prev.selectionManager.isSelected() } }))}); return ( <div style={{width: '208px'}} {...pressProps}> <CardViewContext.Provider value={{state}}> <CardBase {...props} /> </CardViewContext.Provider> </div> ); }; const TemplateSelected = (): Story<SpectrumCardProps> => (args) => ( <div style={{width: '208px'}}> <SelectableCard {...args} /> </div> ); export const Default = Template().bind({}); Default.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.jpg" /> <Avatar src="https://mir-s3-cdn-cf.behance.net/project_modules/disp/690bc6105945313.5f84bfc9de488.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const DefaultSquare = Template().bind({}); DefaultSquare.args = {children: ( <> <Image src="https://i.imgur.com/DhygPot.jpg" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const DefaultTall = Template().bind({}); DefaultTall.args = {children: ( <> <Image src="https://i.imgur.com/3lzeoK7.jpg" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const DefaultPreviewAlt = Template().bind({}); DefaultPreviewAlt.args = {children: ( <> <Image alt="preview" src="https://i.imgur.com/Z7AzH2c.jpg" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongContent = Template().bind({}); LongContent.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>This is the description that never ends, it goes on and on my friends. Someone started typing without knowing what it was.</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongContentSquare = Template().bind({}); LongContentSquare.args = {children: ( <> <Image src="https://i.imgur.com/DhygPot.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>This is the description that never ends, it goes on and on my friends. Someone started typing without knowing what it was.</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongContentPoorWordSize = Template().bind({}); LongContentPoorWordSize.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const NoDescription = Template().bind({}); NoDescription.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const NoDescriptionSquare = Template().bind({}); NoDescriptionSquare.args = {children: ( <> <Image src="https://i.imgur.com/DhygPot.jpg" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const NoFooter = Template().bind({}); NoFooter.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; export const NoActionMenu = Template().bind({}); NoActionMenu.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const NoFooterOrDescription = Template().bind({}); NoFooterOrDescription.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.png" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; export const NoImage = Template().bind({}); NoImage.args = {children: ( <> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; export const CardGrid = (props: SpectrumCardProps) => { let {scale} = useProvider(); return ( <div style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: 'auto', justifyContent: 'center', justifyItems: 'center', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={scale === 'medium' ? {width: '208px', height: '293px'} : {width: '208px', height: '355px'}}> <Card {...Default.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="secondary">Button</Button> </Footer> </Card> </div> ); }) } </div> ); }; export const CardWaterfall = (props: SpectrumCardProps) => ( <div style={{ width: '100%', height: '150vh', margin: '50px', display: 'flex', flexDirection: 'column', flexWrap: 'wrap', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{width: '208px', margin: '10px'}}> <Card {...Default.args} {...props} layout="waterfall" key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>{getDescription(index)}</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="secondary">Button</Button> </Footer> </Card> </div> ); }) } </div> ); export const CardFloat = (props: SpectrumCardProps) => ( <div style={{ width: '100%', margin: '50px' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{float: 'left', margin: '10px'}}> <Card {...Default.args} {...props} key={`${index}${url}`}> <Image src={url} /> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="secondary">Button</Button> </Footer> </Card> </div> ); }) } </div> ); export const CardGridMessyText = (props: SpectrumCardProps) => { let {scale} = useProvider(); return ( <div style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: 'auto', justifyContent: 'center', justifyItems: 'center', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={scale === 'medium' ? {width: '208px', height: '293px'} : {width: '208px', height: '355px'}}> <Card {...Default.args} {...props} layout="grid" key={`${index}${url}`}> <Image src={url} /> <Heading>{index} Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </Card> </div> ); }) } </div> ); }; export const CardWaterfallMessyText = (props: SpectrumCardProps) => ( <div style={{ width: '100%', height: '150vh', margin: '50px', display: 'flex', flexDirection: 'column', flexWrap: 'wrap', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{width: '208px', margin: '10px'}}> <Card {...Default.args} {...props} layout="waterfall" key={`${index}${url}`}> <Image src={url} /> <Heading>{index} Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </Card> </div> ); }) } </div> ); export const CardGridNoPreview = (props: SpectrumCardProps) => { let {scale} = useProvider(); return ( <div style={{ width: '100%', margin: '50px', display: 'grid', gap: '20px', gridTemplateColumns: 'repeat(auto-fit, 208px)', gridAutoRows: 'auto', justifyContent: 'center', justifyItems: 'center', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={scale === 'medium' ? {width: '208px', height: '160px'} : {width: '208px', height: '200px'}}> <Card {...Default.args} {...props} layout="grid" key={`${index}${url}`}> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="secondary">Button</Button> </Footer> </Card> </div> ); }) } </div> ); }; export const CardWaterfallNoPreview = (props: SpectrumCardProps) => ( <div style={{ width: '100%', height: '150vh', margin: '50px', display: 'flex', flexDirection: 'column', flexWrap: 'wrap', alignItems: 'start' }}> { (new Array(15).fill(0)).map((_, index) => { let url = getImage(index); return ( <div style={{width: '208px', margin: '10px'}}> <Card {...Default.args} {...props} layout="waterfall" key={`${index}${url}`}> <Heading>Title {index}</Heading> <Text slot="detail">PNG</Text> <Content>{getDescription(index)}</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="secondary">Button</Button> </Footer> </Card> </div> ); }) } </div> ); export const WithIllustration = Template().bind({}); WithIllustration.args = {children: ( <> <File alt="file" slot="illustration" width={50} height={50} /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; export const WithColorfulIllustration = Template().bind({}); WithColorfulIllustration.args = {children: ( <> <IllustrationContainer><ColorfulIllustration /></IllustrationContainer> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; WithColorfulIllustration.decorators = [(Story) => ( <div> <div>{'ignore the no white background, the svg just has a transparent background'}</div> <Story /> </div> )]; // doesn't work right now, Illustrated Message messes with the styles and has some other interference export const WithColorfulIllustratedMessage = Template().bind({}); WithColorfulIllustratedMessage.args = {children: ( <> <IllustratedMessage><ColorfulIllustration /></IllustratedMessage> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> </> )}; WithColorfulIllustratedMessage.decorators = [(Story) => ( <div> <div>{'does not work right now, Illustrated Message messes with the styles and has some other interference. We may not even want to support it this way.'}</div> <Story /> </div> )]; export const LongTitle = Template().bind({}); LongTitle.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.jpg" /> <Heading>This is a long title about how dinosaurs used to rule the earth before a meteor came and wiped them all out</Heading> <Text slot="detail">PNG</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongDescription = Template().bind({}); LongDescription.args = {children: ( <> {/* TODO: what to do about image requiring an alt in TS, Card provides an empty alt so this is fine */} <Image src="https://i.imgur.com/Z7AzH2c.jpg" /> <Heading>Title</Heading> <Text slot="detail">PNG</Text> <Content>This is a long description about the Pterodactyl, a pterosaur of the late Jurassic period, with a long slender head and neck and a very short tail.</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongDetail = Template().bind({}); LongDetail.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.jpg" /> <Heading>Title</Heading> <Text slot="detail">Stats: Genus: Pterodactylus; Rafinesque, 1815 Order: Pterosauria Kingdom: Animalia Phylum: Chordata</Text> <Content>Description</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const LongEverything = Template().bind({}); LongEverything.args = {children: ( <> <Image src="https://i.imgur.com/Z7AzH2c.jpg" /> <Heading>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Heading> <Text slot="detail">Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Text> <Content>Rechtsschutzversicherungsgesellschaften Nahrungsmittelunverträglichkeit Unabhängigkeitserklärungen Freundschaftsbeziehungen</Content> <ActionMenu> <Item>Action 1</Item> <Item>Action 2</Item> </ActionMenu> <Footer> <Button variant="primary">Something</Button> </Footer> </> )}; export const Selected = TemplateSelected().bind({}); Selected.args = {...Default.args}; // actually use Illustration??? // where to get the three asset svgs to use with Illustration function File(props) { props = useSlotProps(props, 'asset'); let {styleProps} = useStyleProps(props); return ( <div className={classNames(assetStyles, styleProps.className)}> <svg viewBox="0 0 128 128" {...styleProps as any} className={classNames(assetStyles, 'spectrum-Asset-file')} aria-label={props.alt} aria-hidden={props.decorative || null} role="img"> <g> <path className={classNames(assetStyles, 'spectrum-Asset-fileBackground')} d="M24,126c-5.5,0-10-4.5-10-10V12c0-5.5,4.5-10,10-10h61.5c2.1,0,4.1,0.8,5.6,2.3l20.5,20.4c1.5,1.5,2.4,3.5,2.4,5.7V116c0,5.5-4.5,10-10,10H24z" /> <g> <path className={classNames(assetStyles, 'spectrum-Asset-fileOutline')} d="M113.1,23.3L92.6,2.9C90.7,1,88.2,0,85.5,0H24c-6.6,0-12,5.4-12,12v104c0,6.6,5.4,12,12,12h80c6.6,0,12-5.4,12-12V30.4C116,27.8,114.9,25.2,113.1,23.3z M90,6l20.1,20H92c-1.1,0-2-0.9-2-2V6z M112,116c0,4.4-3.6,8-8,8H24c-4.4,0-8-3.6-8-8V12c0-4.4,3.6-8,8-8h61.5c0.2,0,0.3,0,0.5,0v20c0,3.3,2.7,6,6,6h20c0,0.1,0,0.3,0,0.4V116z" /> </g> </g> </svg> </div> ); } function IllustrationContainer(props) { props = useSlotProps(props, 'illustration'); let {styleProps} = useStyleProps(props); return ( <div {...styleProps}> {props.children} </div> ); } // disable the rest, it's for show /* eslint-disable */ function ColorfulIllustration(props) { return ( <svg viewBox="0 0 612 792"> <style dangerouslySetInnerHTML={{__html: ` .st0{display:none;} .st1{display:inline;} .st2{display:inline;fill:none;stroke:#000000;stroke-width:3;stroke-miterlimit:10;} .st3{display:inline;fill:none;stroke:#000000;stroke-width:2;stroke-miterlimit:10;} .st4{display:inline;fill:none;stroke:#000000;stroke-miterlimit:10;} .st5{display:inline;fill:none;} .st6{fill:#2D2D2D;} .st7{fill:none;stroke:#000000;stroke-width:3;stroke-miterlimit:10;} .st8{fill:#3F3F3F;} .st9{fill:#FFFFFF;} .st10{fill:#43A547;} .st11{fill:#43A548;} .st12{fill:none;} .st13{fill:none;stroke:#000000;stroke-width:2;stroke-miterlimit:10;} .st14{fill:none;stroke:#000000;stroke-miterlimit:10;} `}} /> <g id="Trace" className="st0"> <path className="st2" d="M284,279c-62.23,0-113.75,45.84-122.64,105.59l18.01-3.33c0,0,17.1-40.07,71.34-42.02 c54.23-1.95,70.85,44.71,61.56,55.21c9.28-1.47,10.26,20.52,6.35,27.85c17.59,5.37,15.15,56.19,6.84,75.73 c2.55,4.15,6.77,12.67,9.39,18.09C377.98,496.71,408,453.36,408,403C408,334.52,352.48,279,284,279z"/> <g className="st1"> <path d="M254.12,428.65c1.9-4.77,3.97-9.47,6.15-14.13c1.09-2.33,2.21-4.65,3.39-6.94c1.16-2.31,2.59-4.47,4.02-6.65 c0.74-1.08,1.51-2.14,2.39-3.16c0.45-0.51,0.92-1.01,1.5-1.47c0.29-0.23,0.61-0.46,1.02-0.64c0.2-0.09,0.44-0.17,0.7-0.22 c0.29-0.05,0.56-0.03,0.8,0.01c0.88,0.18,1.48,0.5,2.09,0.82c0.6,0.33,1.16,0.68,1.72,1.04c1.1,0.73,2.15,1.5,3.18,2.29 c4.1,3.18,7.93,6.61,11.7,10.13c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17 c1.46,2.28,2.53,4.61,3.54,7.03c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93 c0.04,1.33,0.04,2.67-0.29,4.1l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66 c-2.77-1.08-5.53-2.17-8.33-3.18c-2.79-0.98-5.52-2.23-8.3-3.05c-0.34-0.1-0.69-0.19-1.02-0.26c-0.37-0.07-0.5-0.09-0.89-0.02 c-0.67,0.09-1.38,0.29-2.08,0.5c-1.4,0.43-2.78,0.96-4.16,1.51c-2.74,1.13-5.47,2.34-8.15,3.63c2.56-1.53,5.15-3.01,7.83-4.34 c1.34-0.67,2.69-1.31,4.11-1.87c0.71-0.27,1.42-0.54,2.22-0.71c0.21-0.04,0.35-0.1,0.66-0.11c0.25-0.01,0.46,0.01,0.67,0.03 c0.41,0.05,0.79,0.12,1.17,0.2c1.5,0.32,2.94,0.74,4.38,1.17c1.44,0.43,2.87,0.87,4.26,1.42l8.35,3.22 c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72c0.25-1.07,0.28-2.32,0.24-3.54 c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15c-0.97-2.31-2.05-4.66-3.37-6.69 c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8c-3.73-3.48-7.55-6.89-11.55-10c-1-0.77-2.02-1.52-3.06-2.21 c-0.52-0.34-1.04-0.67-1.57-0.96c-0.51-0.28-1.08-0.54-1.46-0.61c-0.08-0.01-0.13-0.01-0.15-0.01c-0.05,0.01-0.12,0.03-0.21,0.07 c-0.18,0.08-0.39,0.21-0.6,0.39c-0.42,0.34-0.84,0.77-1.24,1.22c-0.8,0.92-1.53,1.93-2.24,2.97c-1.44,2.07-2.63,4.32-4,6.47 c-1.34,2.17-2.63,4.37-3.9,6.6C258.93,419.59,256.51,424.11,254.12,428.65z"/> </g> <g className="st1"> <path d="M273.67,476.54l9.84,3.73l-0.24,0.08c1.86-3.18,3.91-6.25,6.27-9.11c1.19-1.42,2.46-2.79,3.95-3.96 c0.74-0.6,1.58-1.09,2.47-1.48c0.88-0.36,1.77-0.67,2.67-0.91c3.59-1.02,7.24-1.61,10.88-2.18c3.65-0.54,7.3-0.98,10.98-1.34 l0.15,1.99c-3.64,0.22-7.29,0.53-10.92,0.93c-3.62,0.43-7.27,0.88-10.78,1.75c-1.77,0.44-3.45,0.95-4.86,2.03 c-1.44,1.04-2.73,2.34-3.95,3.68c-2.42,2.72-4.57,5.7-6.54,8.79l-0.09,0.14l-0.15-0.06L273.67,476.54z"/> </g> <g className="st1"> <path d="M195.49,410.09c1.67-2.31,3.44-4.53,5.24-6.74c2.02-1.98,4.03-3.97,6.12-5.9c1.06-0.97,2.08-1.92,3.3-2.83 c0.15-0.11,0.33-0.23,0.51-0.34c0.1-0.06,0.23-0.13,0.35-0.18c0.11-0.06,0.51-0.17,0.72-0.13c0.59,0.1,0.62,0.2,0.87,0.29 l0.51,0.27c0.64,0.37,1.25,0.75,1.85,1.13c2.4,1.54,4.73,3.12,7.08,4.68c4.69,3.12,9.36,6.31,14.19,9.08 c0.6,0.34,1.21,0.67,1.82,0.96c0.59,0.29,1.26,0.58,1.69,0.66c0.09-0.02-0.02,0.04,0.16-0.01c0.12-0.04,0.23-0.06,0.36-0.11 c0.27-0.12,0.54-0.23,0.83-0.4c0.58-0.28,1.09-0.73,1.67-1.08c2.39-1.36,4.68-3.05,6.97-4.73c-1.74,2.26-3.63,4.39-5.8,6.35 c-0.28,0.24-0.58,0.45-0.91,0.63c-0.32,0.19-0.63,0.4-0.97,0.58c-0.32,0.19-0.71,0.35-1.08,0.51c-0.2,0.08-0.43,0.13-0.65,0.19 c-0.15,0.07-0.63,0.07-0.89,0.03c-0.95-0.19-1.57-0.52-2.25-0.84c-0.67-0.32-1.3-0.67-1.92-1.02c-4.96-2.85-9.62-6.04-14.32-9.16 c-2.35-1.57-4.68-3.15-7.04-4.66c-0.59-0.37-1.18-0.74-1.76-1.08l-0.42-0.23c-0.07-0.05-0.35-0.13-0.11-0.09 c0.02-0.01,0.09,0.01,0.14,0c0.04,0,0.12-0.05,0.08-0.02l-0.12,0.06c-0.12,0.08-0.23,0.15-0.37,0.25 c-1.04,0.78-2.09,1.74-3.12,2.68c-2.05,1.9-4.07,3.87-6.05,5.86C199.95,406.56,197.76,408.35,195.49,410.09z"/> </g> <g className="st1"> <path d="M285.71,397.72l5.31,4.57c1.77,1.52,3.51,3.08,5.27,4.62l-0.71-0.15c1.48-0.63,2.84-1.66,4.12-2.78 c1.28-1.12,2.45-2.38,3.71-3.56c1.26-1.19,2.56-2.36,3.95-3.46c0.7-0.54,1.42-1.08,2.2-1.54c0.39-0.24,0.8-0.44,1.23-0.61 c0.43-0.16,0.91-0.29,1.39-0.22v0.2c-0.79,0.23-1.39,0.86-2,1.44c-0.6,0.6-1.18,1.23-1.76,1.87c-1.16,1.28-2.32,2.58-3.57,3.81 c-1.25,1.23-2.63,2.36-4.06,3.42c-1.44,1.06-2.95,2.08-4.74,2.7l-0.42,0.15l-0.29-0.29c-1.64-1.66-3.29-3.31-4.91-4.99l-4.87-5.04 L285.71,397.72z"/> </g> <path className="st3" d="M201.84,403.73c0,0-1.95,18.57,18.57,22.48c14.68,2.8,19.54-14.17,19.54-14.17"/> <path className="st1" d="M227.06,405.91c-3.52-2.29-7.22-4.8-10.25-6.82c-0.63,2.35-0.88,5.33-0.62,8.56 c0.58,7.23,3.51,12.89,6.54,12.64c3.03-0.24,5.01-6.3,4.42-13.53C227.13,406.48,227.09,406.2,227.06,405.91z M222.87,413.08 c-1.06,0.18-2.26-1.61-2.67-4c-0.41-2.39,0.12-4.48,1.18-4.66c1.06-0.18,2.26,1.61,2.67,4 C224.46,410.8,223.93,412.89,222.87,413.08z"/> <path className="st1" d="M308.48,396.98c-2.86,2.56-6.55,6.66-10.05,9.01c0.49,5.42,3.37,9.59,6.66,9.44c3.45-0.16,6.03-4.99,5.77-10.8 C310.72,401.57,309.81,398.85,308.48,396.98z M304.81,410.66c-1.06,0-1.92-1.32-1.92-2.96c0-1.63,0.86-2.96,1.92-2.96 c1.06,0,1.92,1.32,1.92,2.96C306.73,409.33,305.87,410.66,304.81,410.66z"/> <g className="st1"> <path d="M295.13,493.16c-0.09-1.59-0.04-2.97,0.03-4.43c0.08-1.44,0.23-2.87,0.41-4.29c0.37-2.84,0.93-5.65,1.67-8.41 c1.47-5.52,3.6-10.84,6.29-15.85c2.73-4.99,5.99-9.68,9.7-13.95c3.72-4.27,7.89-8.12,12.34-11.58c4.45-3.46,9.21-6.49,14.15-9.15 c1.25-0.67,2.42-1.36,3.59-2.06l1.76-1.04l1.66-1.19l1.66-1.19c0.55-0.4,1.05-0.88,1.57-1.31c1.04-0.88,2.09-1.76,3.03-2.76 c3.92-3.82,7.24-8.25,10.11-12.95c0.75-1.16,1.37-2.39,2.06-3.59c0.62-1.23,1.28-2.45,1.84-3.71c1.16-2.5,2.22-5.07,3.06-7.68 l0.7,0.19c-0.71,2.73-1.64,5.37-2.74,7.95c-0.52,1.3-1.14,2.56-1.73,3.83c-0.66,1.24-1.23,2.52-1.96,3.73 c-2.74,4.9-6.1,9.48-10.05,13.52c-0.95,1.05-2.02,1.97-3.08,2.91c-0.54,0.46-1.04,0.96-1.61,1.39l-1.7,1.27l-1.71,1.27l-1.82,1.11 c-1.21,0.75-2.43,1.49-3.61,2.16c-4.79,2.72-9.38,5.79-13.64,9.26c-4.26,3.46-8.21,7.29-11.71,11.48 c-3.49,4.21-6.51,8.77-9.01,13.6c-2.46,4.85-4.38,9.96-5.65,15.23c-0.64,2.63-1.11,5.3-1.4,7.98c-0.14,1.34-0.25,2.68-0.29,4.02 c-0.04,1.31-0.05,2.72,0.05,3.9L295.13,493.16z"/> </g> <g className="st1"> <path d="M254.06,449.02c2.54-1.57,5.12-3.07,7.79-4.43c1.34-0.68,2.69-1.34,4.1-1.91c0.72-0.28,1.42-0.56,2.23-0.74 c0.22-0.04,0.35-0.11,0.68-0.12c0.27-0.01,0.48,0.01,0.69,0.03c0.42,0.05,0.81,0.11,1.19,0.19c1.52,0.3,2.96,0.73,4.37,1.25 l4.22,1.52c2.8,1.04,5.58,2.11,8.36,3.2c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72 c0.25-1.07,0.28-2.32,0.24-3.54c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15 c-0.97-2.31-2.05-4.66-3.37-6.69c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8 c-3.72-3.49-7.56-6.87-11.54-10.01c-0.97-0.81-1.96-1.6-2.98-2.33c-0.51-0.37-1.02-0.72-1.54-1.03c-0.51-0.31-1.07-0.6-1.53-0.71 c-0.3-0.11-0.76,0.13-1.23,0.49c-0.46,0.35-0.89,0.79-1.31,1.24c-0.83,0.92-1.59,1.94-2.32,2.97c-2.9,4.17-5.41,8.66-7.85,13.16 c-2.43,4.51-4.77,9.07-7,13.69c2.05-4.7,4.2-9.36,6.47-13.96c2.3-4.59,4.65-9.16,7.46-13.5c0.71-1.08,1.46-2.15,2.31-3.16 c0.43-0.5,0.88-1,1.43-1.45c0.27-0.23,0.57-0.44,0.94-0.61c0.18-0.09,0.39-0.16,0.62-0.2c0.25-0.04,0.48-0.03,0.7-0.01 c0.81,0.14,1.41,0.43,2.03,0.72c0.6,0.3,1.18,0.63,1.74,0.97c1.12,0.68,2.2,1.42,3.26,2.17c4.12,3.15,7.93,6.61,11.71,10.11 c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17c1.46,2.28,2.53,4.61,3.54,7.03 c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93c0.04,1.33,0.04,2.67-0.29,4.1 l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66 c-5.51-2.18-11.13-4.3-16.67-6.06c-0.34-0.11-0.68-0.2-1-0.27c-0.37-0.07-0.45-0.09-0.84-0.03c-0.66,0.08-1.37,0.27-2.06,0.47 c-1.39,0.41-2.78,0.93-4.16,1.47C259.5,446.58,256.77,447.77,254.06,449.02z"/> </g> <g className="st1"> <path d="M339.52,425.68c0.11-0.16,0.15-0.18,0.21-0.24c0.06-0.06,0.11-0.09,0.16-0.13c0.1-0.08,0.2-0.15,0.29-0.19 c0.2-0.12,0.37-0.18,0.56-0.25c0.36-0.12,0.71-0.18,1.05-0.22c0.67-0.07,1.31-0.04,1.93,0.03c1.24,0.14,2.4,0.45,3.54,0.8 c1.14,0.36,2.25,0.77,3.33,1.24c1.09,0.45,2.15,0.96,3.21,1.45c-1.12-0.34-2.24-0.7-3.37-0.98c-1.13-0.3-2.27-0.55-3.4-0.74 c-1.13-0.18-2.28-0.32-3.38-0.28c-0.55,0.01-1.09,0.07-1.57,0.19c-0.24,0.06-0.46,0.14-0.64,0.23c-0.08,0.05-0.18,0.1-0.22,0.15 c-0.03,0.02-0.06,0.05-0.06,0.06c-0.01,0.01-0.02,0.02-0.01,0.01c0.01-0.01-0.01,0.02,0.06-0.08L339.52,425.68z"/> </g> <g className="st1"> <path d="M341.94,424.24c0.21-0.3,0.45-0.79,0.63-1.23c0.2-0.45,0.36-0.93,0.51-1.42c0.29-0.97,0.49-1.99,0.63-3.01 c0.14-1.03,0.19-2.08,0.21-3.13c0.01-1.05-0.05-2.11-0.14-3.17c0.25,1.03,0.48,2.07,0.64,3.13c0.15,1.06,0.27,2.13,0.29,3.21 c0.02,1.08-0.02,2.18-0.16,3.28c-0.08,0.55-0.17,1.1-0.31,1.65c-0.14,0.57-0.28,1.06-0.57,1.7L341.94,424.24z"/> </g> <g className="st1"> <path d="M359.23,408.73c0.16-0.32,0.32-0.87,0.41-1.35c0.11-0.5,0.16-1.02,0.2-1.54c0.07-1.05-0.01-2.12-0.16-3.19 c-0.15-1.07-0.43-2.13-0.75-3.18c-0.17-0.52-0.37-1.03-0.55-1.56l-0.66-1.52l0.88,1.42c0.26,0.49,0.55,0.97,0.79,1.48 c0.48,1.01,0.94,2.05,1.27,3.14c0.33,1.09,0.58,2.22,0.69,3.39c0.05,0.58,0.07,1.17,0.04,1.77c-0.04,0.62-0.08,1.16-0.3,1.89 L359.23,408.73z"/> </g> <g className="st1"> <path d="M362.94,403.96c1.01,0.16,2.12,0.25,3.2,0.28c1.09,0.03,2.18-0.01,3.27-0.1c1.09-0.09,2.17-0.28,3.24-0.54 c1.07-0.25,2.11-0.64,3.14-1.09c-0.94,0.6-1.93,1.14-2.98,1.56c-1.05,0.42-2.13,0.79-3.23,1.05c-1.1,0.27-2.23,0.48-3.36,0.62 c-1.15,0.14-2.26,0.22-3.47,0.21L362.94,403.96z"/> </g> <path className="st4" d="M344.03,417.9c-3.42,0.24-5.05-8.94-7.08-19.54c-1.22-6.35-2.44-13.44-1.47-21.01 c1.47-0.49,10.02,15.64,10.99,20.03C347.45,401.78,347.45,417.66,344.03,417.9z"/> <path className="st4" d="M359.42,400.56c-6.35-1.47-13.19-32.25-10.99-35.91C352.82,366.11,365.77,395.92,359.42,400.56z"/> <path className="st4" d="M367.72,404.22c0,0,8.79-13.19,31.76-10.26C398.26,399.83,371.39,414.48,367.72,404.22z"/> <path className="st4" d="M347.2,425.72c0,0,4.15,9.53,16.12,9.28c11.97-0.24,26.63-7.82,26.87-11.24c-1.71-1.22-15.64,4.4-24.92,2.2 c-4.57-1.08-16.12-1.22-16.12-1.22L347.2,425.72z"/> <path className="st4" d="M386.29,355.12c-3.66,2.2-16.86,18.32-18.32,26.14c-1.47,7.82,5.08,8.73,8.79,4.4 C379.7,382.24,387.02,360.25,386.29,355.12z"/> <g className="st1"> <path d="M292.79,408.06c3.51,2.95,7,5.94,10.38,9.06c1.69,1.56,3.36,3.14,5.02,4.75c1.64,1.64,3.33,3.2,4.69,5.24l-1.01-0.44 c0.72-0.11,1.45-0.4,2.11-0.89c0.67-0.48,1.29-1.1,1.85-1.79c1.12-1.38,2.09-2.99,2.94-4.67l0.19,0.06 c-0.12,0.96-0.39,1.88-0.68,2.8c-0.32,0.92-0.72,1.81-1.22,2.67c-0.52,0.85-1.12,1.68-1.93,2.37c-0.79,0.7-1.8,1.27-2.94,1.47 l-0.6,0.11l-0.41-0.55c-1.28-1.7-2.74-3.49-4.23-5.2c-1.51-1.71-3.08-3.37-4.66-5.02c-3.19-3.28-6.36-6.59-9.62-9.82 L292.79,408.06z"/> </g> </g> <g id="Brushes" className="st0"> <path className="st4" d="M165.41,383.22c5.62,2.5,12.37,0.01,16.97-4.07c4.61-4.08,7.72-9.53,11.52-14.36 c8.7-11.06,21.17-18.92,34.66-22.9c13.5-3.98,27.97-4.19,41.79-1.54c10.69,2.05,21.27,5.92,29.63,12.9 c8.36,6.98,14.25,17.39,14.08,28.28c-0.17,10.89-7.26,21.8-17.72,24.82"/> <path className="st4" d="M286.33,398.45c4.61,1.89,8.66,5.11,11.54,9.18"/> <path className="st4" d="M314.12,384.58c-0.82,4.43,1.18,8.88,3.54,12.71c2.37,3.83,5.19,7.51,6.31,11.87c0.51,1.99,0.57,4.07,0.26,6.1 c-0.36,2.34-2.11,4.43-2.45,6.59c-0.43,2.82,4.76,7.64,6.2,10.48c4,7.89,5.37,17,4.84,25.77c-0.79,12.98-5.34,25.4-9.84,37.61"/> <path className="st4" d="M320.18,492.81c6.13,6.38,10.78,14.17,13.49,22.6"/> <path className="st4" d="M256.3,448.41c3.07-3.17,7.78-4.31,12.18-4.01c4.4,0.3,8.61,1.86,12.74,3.4c12.48,4.66,25.71,9.38,38.19,14.04 c1.34-13.05-4.07-26.07-12.08-36.46s-18.48-18.56-28.84-26.62c-1.26-0.98-2.66-2.01-4.26-1.95c-2.43,0.08-3.99,2.53-5.11,4.68 c-4.62,8.88-9.23,17.76-13.85,26.65"/> <path className="st4" d="M274.39,475.98c2.35,1.38,5,2.8,7.66,2.22c2.87-0.64,4.69-3.36,6.56-5.63c5.89-7.14,15.13-11.38,24.38-11.18" /> <path className="st4" d="M297.62,492.94c-0.68-15.73,4.81-31.66,15.04-43.63c6.24-7.3,14.05-13.06,21.86-18.67 c7.8-5.6,15.73-11.16,22.31-18.16s11.8-15.65,13.01-25.18"/> <path className="st4" d="M342.23,405.49c3.07,5.7,3.61,12.71,1.43,18.81"/> <path className="st4" d="M365.32,434.23c-7.04-5.2-15.71-8.15-24.46-8.31"/> <path className="st4" d="M380.64,400.87c-5.62,1-11.23,1.99-16.85,2.99"/> <path className="st4" d="M355.69,386.92c4.3,6,6.23,13.65,5.29,20.98"/> <path className="st4" d="M337.11,390.92c2.9,4.01,5.81,8.03,8.71,12.04c1.15,1.59,2.31,3.2,3.02,5.03c0.71,1.83,0.91,3.93,0.14,5.74 c-3.43,7.95-8.79-1.72-10.21-5.23c-1.13-2.81-1.85-5.78-2.13-8.8C336.51,398.22,337.73,391.77,337.11,390.92z"/> <path className="st4" d="M351.13,434.48c1.95,1.64,4.54,2.35,7.09,2.54c7.09,0.54,14.36-2.83,18.53-8.59 c-4.64,0.65-9.26-0.97-13.82-2.04c-3.9-0.91-8.45-1.47-12.19,0.37C347.25,428.48,348.42,432.2,351.13,434.48z"/> <path className="st4" d="M349.95,374.81c2.51,3.7,5.86,6.77,8.34,10.49c1.87,2.81,3.62,6.71,2.88,10.17c-0.65,3.02-3.35,5.6-5.92,2.78 c-2.32-2.54-3.11-7.67-3.84-10.91C350.49,383.23,349.99,379.02,349.95,374.81z"/> <path className="st4" d="M391.44,395.99c-0.44,0.02-3.68,5.01-4.33,5.64c-1.8,1.78-3.88,3.3-6.13,4.47c-3.03,1.57-8.29,3.38-9.46-1.17 C368.76,394.27,385.91,396.24,391.44,395.99z"/> <path className="st4" d="M365.56,376.89c1.6-1.94,4.19-2.67,6.49-3.69c4.9-2.18,8.97-6.17,11.25-11.02c1.16,5.68,1.56,11.51,1.18,17.29 c-0.19,2.9-0.66,5.98-2.6,8.14C376.04,394.12,359.15,384.67,365.56,376.89z"/> <path className="st4" d="M249.08,405.11c-2.35,3.54-6.23,6.3-10.48,6.31c-3.85,0.01-7.37-2.19-10.28-4.72s-5.46-5.5-8.71-7.58 c-3.24-2.08-7.49-3.16-10.97-1.5c-1.15,0.55-2.14,1.36-3.13,2.16c-3.65,2.98-7.31,5.95-10.96,8.93"/> </g> <g id="Trace_copy" className="st0"> <path className="st2" d="M284,279c-62.23,0-113.75,45.84-122.64,105.59l18.01-3.33c0,0,17.1-40.07,71.34-42.02 c54.23-1.95,68.57,43.49,61.56,55.21c6.84,2.12,10.26,20.52,6.35,27.85c17.59,5.37,15.15,56.19,6.84,75.73 c2.55,4.15,6.77,12.67,9.39,18.09C377.98,496.71,408,453.36,408,403C408,334.52,352.48,279,284,279z"/> <path className="st1" d="M254.12,428.65c1.9-4.77,3.97-9.47,6.15-14.13c1.09-2.33,2.21-4.65,3.39-6.94c1.16-2.31,2.59-4.47,4.02-6.65 c0.74-1.08,1.51-2.14,2.39-3.16c0.45-0.51,0.92-1.01,1.5-1.47c0.29-0.23,0.61-0.46,1.02-0.64c0.2-0.09,0.44-0.17,0.7-0.22 c0.29-0.05,0.56-0.03,0.8,0.01c0.88,0.18,1.48,0.5,2.09,0.82c0.6,0.33,1.16,0.68,1.72,1.04c1.1,0.73,2.15,1.5,3.18,2.29 c4.1,3.18,7.93,6.61,11.7,10.13c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17 c1.46,2.28,2.53,4.61,3.54,7.03c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93 c0.04,1.33,0.04,2.67-0.29,4.1l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66 c-2.77-1.08-5.53-2.17-8.33-3.18c-2.79-0.98-5.52-2.23-8.3-3.05c-0.34-0.1-0.69-0.19-1.02-0.26c-0.37-0.07-0.5-0.09-0.89-0.02 c-0.67,0.09-1.38,0.29-2.08,0.5c-1.4,0.43-2.78,0.96-4.16,1.51c-2.74,1.13-5.47,2.34-8.15,3.63c2.56-1.53,5.15-3.01,7.83-4.34 c1.34-0.67,2.69-1.31,4.11-1.87c0.71-0.27,1.42-0.54,2.22-0.71c0.21-0.04,0.35-0.1,0.66-0.11c0.25-0.01,0.46,0.01,0.67,0.03 c0.41,0.05,0.79,0.12,1.17,0.2c1.5,0.32,2.94,0.74,4.38,1.17c1.44,0.43,2.87,0.87,4.26,1.42l8.35,3.22 c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72c0.25-1.07,0.28-2.32,0.24-3.54 c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15c-0.97-2.31-2.05-4.66-3.37-6.69 c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8c-3.73-3.48-7.55-6.89-11.55-10c-1-0.77-2.02-1.52-3.06-2.21 c-0.52-0.34-1.04-0.67-1.57-0.96c-0.51-0.28-1.08-0.54-1.46-0.61c-0.08-0.01-0.13-0.01-0.15-0.01c-0.05,0.01-0.12,0.03-0.21,0.07 c-0.18,0.08-0.39,0.21-0.6,0.39c-0.42,0.34-0.84,0.77-1.24,1.22c-0.8,0.92-1.53,1.93-2.24,2.97c-1.44,2.07-2.63,4.32-4,6.47 c-1.34,2.17-2.63,4.37-3.9,6.6C258.93,419.59,256.51,424.11,254.12,428.65z"/> <path className="st1" d="M273.67,476.54l9.84,3.73l-0.24,0.08c1.86-3.18,3.91-6.25,6.27-9.11c1.19-1.42,2.46-2.79,3.95-3.96 c0.74-0.6,1.58-1.09,2.47-1.48c0.88-0.36,1.77-0.67,2.67-0.91c3.59-1.02,7.06-1.87,10.7-2.44c3.65-0.54,5.11-1.11,8.79-1.47 l1.3,1.63c-3.64,0.22-6.14,0.98-9.77,1.38c-3.62,0.43-7.21,1.18-10.72,2.05c-1.77,0.44-3.45,0.95-4.86,2.03 c-1.44,1.04-2.73,2.34-3.95,3.68c-2.42,2.72-4.57,5.7-6.54,8.79l-0.09,0.14l-0.15-0.06L273.67,476.54z"/> <path className="st1" d="M195.49,410.09c1.67-2.31,3.44-4.53,5.24-6.74c2.02-1.98,4.03-3.97,6.12-5.9c1.06-0.97,2.08-1.92,3.3-2.83 c0.15-0.11,0.33-0.23,0.51-0.34c0.1-0.06,0.23-0.13,0.35-0.18c0.11-0.06,0.51-0.17,0.72-0.13c0.59,0.1,0.62,0.2,0.87,0.29 l0.51,0.27c0.64,0.37,1.25,0.75,1.85,1.13c2.4,1.54,4.73,3.12,7.08,4.68c4.69,3.12,9.36,6.31,14.19,9.08 c0.6,0.34,1.21,0.67,1.82,0.96c0.59,0.29,1.26,0.58,1.69,0.66c0.09-0.02-0.02,0.04,0.16-0.01c0.12-0.04,0.23-0.06,0.36-0.11 c0.27-0.12,0.54-0.23,0.83-0.4c0.58-0.28,1.09-0.73,1.67-1.08c2.39-1.36,4.68-3.05,6.97-4.73c-1.74,2.26-3.63,4.39-5.8,6.35 c-0.28,0.24-0.58,0.45-0.91,0.63c-0.32,0.19-0.63,0.4-0.97,0.58c-0.32,0.19-0.71,0.35-1.08,0.51c-0.2,0.08-0.43,0.13-0.65,0.19 c-0.15,0.07-0.63,0.07-0.89,0.03c-0.95-0.19-1.57-0.52-2.25-0.84c-0.67-0.32-1.3-0.67-1.92-1.02c-4.96-2.85-9.62-6.04-14.32-9.16 c-2.35-1.57-4.68-3.15-7.04-4.66c-0.59-0.37-1.18-0.74-1.76-1.08l-0.42-0.23c-0.07-0.05-0.35-0.13-0.11-0.09 c0.02-0.01,0.09,0.01,0.14,0c0.04,0,0.12-0.05,0.08-0.02l-0.12,0.06c-0.12,0.08-0.23,0.15-0.37,0.25 c-1.04,0.78-2.09,1.74-3.12,2.68c-2.05,1.9-4.07,3.87-6.05,5.86C199.95,406.56,197.76,408.35,195.49,410.09z"/> <path className="st1" d="M285.71,397.72l5.31,4.57c1.77,1.52,3.51,3.08,5.27,4.62l-0.71-0.15c1.48-0.63,2.84-1.66,4.12-2.78 c1.28-1.12,2.45-2.38,3.71-3.56c1.26-1.19,2.91-3.08,3.48-3.77c0.58-0.68,1.29-1.49,2.08-1.95c0.39-0.24,1.4,0.29,1.83,0.12 c0.43-0.16,0.91-0.29,1.39-0.22v0.2c-0.79,0.23-1.39,0.86-2,1.44c-0.6,0.6-1.18,1.23-1.76,1.87c-1.16,1.28-2.32,2.58-3.57,3.81 c-1.25,1.23-2.63,2.36-4.06,3.42c-1.44,1.06-2.95,2.08-4.74,2.7l-0.42,0.15l-0.29-0.29c-1.64-1.66-3.29-3.31-4.91-4.99l-4.87-5.04 L285.71,397.72z"/> <path className="st3" d="M201.84,403.73c0,0-1.95,18.57,18.57,22.48c14.68,2.8,19.54-14.17,19.54-14.17"/> <path className="st1" d="M308.48,396.98c-2.86,2.56-6.55,6.66-10.05,9.01c0.49,5.42,3.37,9.59,6.66,9.44c3.45-0.16,6.03-4.99,5.77-10.8 C310.72,401.57,309.81,398.85,308.48,396.98z M303.5,410.48c-1.06,0-1.92-1.32-1.92-2.96c0-1.63,0.86-2.96,1.92-2.96 c1.06,0,1.92,1.32,1.92,2.96C305.43,409.15,304.57,410.48,303.5,410.48z"/> <path className="st1" d="M254.06,449.02c2.54-1.57,5.12-3.07,7.79-4.43c1.34-0.68,2.69-1.34,4.1-1.91c0.72-0.28,1.42-0.56,2.23-0.74 c0.22-0.04,0.35-0.11,0.68-0.12c0.27-0.01,0.48,0.01,0.69,0.03c0.42,0.05,0.81,0.11,1.19,0.19c1.52,0.3,2.96,0.73,4.37,1.25 l4.22,1.52c2.8,1.04,5.58,2.11,8.36,3.2c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72 c0.25-1.07,0.28-2.32,0.24-3.54c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15 c-0.97-2.31-2.05-4.66-3.37-6.69c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8 c-3.72-3.49-7.56-6.87-11.54-10.01c-0.97-0.81-1.96-1.6-2.98-2.33c-0.51-0.37-1.02-0.72-1.54-1.03c-0.51-0.31-1.07-0.6-1.53-0.71 c-0.3-0.11-0.76,0.13-1.23,0.49c-0.46,0.35-0.89,0.79-1.31,1.24c-0.83,0.92-1.59,1.94-2.32,2.97c-2.9,4.17-5.41,8.66-7.85,13.16 c-2.43,4.51-4.77,9.07-7,13.69c2.05-4.7,4.2-9.36,6.47-13.96c2.3-4.59,4.65-9.16,7.46-13.5c0.71-1.08,1.46-2.15,2.31-3.16 c0.43-0.5,0.88-1,1.43-1.45c0.27-0.23,0.57-0.44,0.94-0.61c0.18-0.09,0.39-0.16,0.62-0.2c0.25-0.04,0.48-0.03,0.7-0.01 c0.81,0.14,1.41,0.43,2.03,0.72c0.6,0.3,1.18,0.63,1.74,0.97c1.12,0.68,2.2,1.42,3.26,2.17c4.12,3.15,7.93,6.61,11.71,10.11 c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17c1.46,2.28,2.53,4.61,3.54,7.03 c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93c0.04,1.33,0.04,2.67-0.29,4.1 l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66c-5.51-2.18-11.13-4.3-16.67-6.06 c-0.34-0.11-0.68-0.2-1-0.27c-0.37-0.07-0.45-0.09-0.84-0.03c-0.66,0.08-1.37,0.27-2.06,0.47c-1.39,0.41-2.78,0.93-4.16,1.47 C259.5,446.58,256.77,447.77,254.06,449.02z"/> <path className="st1" d="M339.52,425.68c0.11-0.16,0.15-0.18,0.21-0.24c0.06-0.06,0.11-0.09,0.16-0.13c0.1-0.08,0.2-0.15,0.29-0.19 c0.2-0.12,0.37-0.18,0.56-0.25c0.36-0.12,0.71-0.18,1.05-0.22c0.67-0.07,1.31-0.04,1.93,0.03c1.24,0.14,2.4,0.45,3.54,0.8 c1.14,0.36,2.25,0.77,3.33,1.24c1.09,0.45,2.15,0.96,3.21,1.45c-1.12-0.34-2.24-0.7-3.37-0.98c-1.13-0.3-2.27-0.55-3.4-0.74 c-1.13-0.18-2.28-0.32-3.38-0.28c-0.55,0.01-1.09,0.07-1.57,0.19c-0.24,0.06-0.46,0.14-0.64,0.23c-0.08,0.05-0.18,0.1-0.22,0.15 c-0.03,0.02-0.06,0.05-0.06,0.06c-0.01,0.01-0.02,0.02-0.01,0.01c0.01-0.01-0.01,0.02,0.06-0.08L339.52,425.68z"/> <path className="st1" d="M341.94,424.24c0.21-0.3,0.45-0.79,0.63-1.23c0.2-0.45,0.36-0.93,0.51-1.42c0.29-0.97,0.49-1.99,0.63-3.01 c0.14-1.03,0.19-2.08,0.21-3.13c0.01-1.05-0.05-2.11-0.14-3.17c0.25,1.03,0.48,2.07,0.64,3.13c0.15,1.06,0.27,2.13,0.29,3.21 c0.02,1.08-0.02,2.18-0.16,3.28c-0.08,0.55-0.17,1.1-0.31,1.65c-0.14,0.57-0.28,1.06-0.57,1.7L341.94,424.24z"/> <path className="st1" d="M359.23,408.73c0.16-0.32,0.32-0.87,0.41-1.35c0.11-0.5,0.16-1.02,0.2-1.54c0.07-1.05-0.01-2.12-0.16-3.19 c-0.15-1.07-0.43-2.13-0.75-3.18c-0.17-0.52-0.37-1.03-0.55-1.56l-0.66-1.52l0.88,1.42c0.26,0.49,0.55,0.97,0.79,1.48 c0.48,1.01,0.94,2.05,1.27,3.14c0.33,1.09,0.58,2.22,0.69,3.39c0.05,0.58,0.07,1.17,0.04,1.77c-0.04,0.62-0.6,1.03-0.81,1.76 L359.23,408.73z"/> <path className="st1" d="M362.94,403.96c1.01,0.16,2.12,0.25,3.2,0.28c1.09,0.03,2.18-0.01,3.27-0.1c1.09-0.09,2.17-0.28,3.24-0.54 c1.07-0.25,2.11-0.64,3.14-1.09c-0.94,0.6-1.93,1.14-2.98,1.56c-1.05,0.42-2.13,0.79-3.23,1.05c-1.1,0.27-2.23,0.48-3.36,0.62 c-1.15,0.14-2.26,0.22-3.47,0.21L362.94,403.96z"/> <path className="st4" d="M344.03,417.9c-3.42,0.24-5.05-8.94-7.08-19.54c-1.22-6.35-2.44-13.44-1.47-21.01 c1.47-0.49,10.02,15.64,10.99,20.03C347.45,401.78,347.45,417.66,344.03,417.9z"/> <path className="st4" d="M359.42,400.56c-6.35-1.47-13.19-32.25-10.99-35.91C352.82,366.11,365.77,395.92,359.42,400.56z"/> <path className="st4" d="M367.72,404.22c0,0,8.79-13.19,31.76-10.26C398.26,399.83,371.39,414.48,367.72,404.22z"/> <path className="st4" d="M347.2,425.72c0,0,4.15,9.53,16.12,9.28c11.97-0.24,26.63-7.82,26.87-11.24c-1.71-1.22-15.6,4.23-24.92,2.2 C355.92,423.93,347.2,425.72,347.2,425.72z"/> <path className="st1" d="M292.79,408.06c3.51,2.95,7,5.94,10.38,9.06c1.69,1.56,3.36,3.14,5.02,4.75c1.64,1.64,3.33,3.2,4.69,5.24 l-1.01-0.44c0.72-0.11,1.45-0.4,2.11-0.89c0.67-0.48,1.29-1.1,1.85-1.79c1.12-1.38,2.09-2.99,2.94-4.67l0.19,0.06 c-0.12,0.96-0.39,1.88-0.68,2.8c-0.32,0.92-0.72,1.81-1.22,2.67c-0.52,0.85-1.12,1.68-1.93,2.37c-0.79,0.7-1.8,1.27-2.94,1.47 l-0.6,0.11l-0.41-0.55c-1.28-1.7-2.74-3.49-4.23-5.2c-1.51-1.71-3.08-3.37-4.66-5.02c-3.19-3.28-6.36-6.59-9.62-9.82L292.79,408.06 z"/> <g className="st1"> <path d="M305.69,456.45c-0.75,1.22-1.48,2.46-2.16,3.71c-2.69,5.01-4.82,10.33-6.29,15.85c-0.73,2.76-1.3,5.57-1.67,8.41 c-0.18,1.42-0.33,2.85-0.41,4.29c-0.07,1.46-0.13,2.84-0.03,4.43l3.98-0.35c-0.1-1.18-0.09-2.59-0.05-3.9 c0.05-1.34,0.15-2.68,0.29-4.02c0.29-2.68,0.76-5.35,1.4-7.98c1.27-5.27,3.19-10.38,5.65-15.23c0.71-1.37,1.47-2.71,2.26-4.03 L305.69,456.45z"/> <path d="M370.06,388.01c-0.84,2.61-1.91,5.18-3.06,7.68c-0.56,1.26-1.22,2.48-1.84,3.71c-0.69,1.19-1.3,2.43-2.06,3.59 c-2.87,4.7-6.19,9.13-10.11,12.95c-0.94,1-1.99,1.87-3.03,2.76c-0.53,0.44-1.02,0.91-1.57,1.31l-1.66,1.19l-1.66,1.19l-1.76,1.03 c-1.17,0.69-2.34,1.38-3.59,2.06c-4.94,2.66-9.7,5.69-14.15,9.15c-2.98,2.31-5.81,4.82-8.49,7.49c0.4,0.97,0.78,1.98,1.07,2.85 c2.78-3,5.79-5.79,8.98-8.38c4.25-3.47,8.85-6.53,13.64-9.26c1.18-0.67,2.4-1.42,3.61-2.16l1.82-1.11l1.71-1.27l1.7-1.27 c0.56-0.43,1.07-0.93,1.61-1.39c1.06-0.94,2.13-1.86,3.08-2.91c3.95-4.04,7.31-8.62,10.05-13.52c0.72-1.2,1.3-2.49,1.96-3.73 c0.58-1.28,1.21-2.53,1.73-3.83c1.1-2.58,2.03-5.22,2.74-7.95L370.06,388.01z"/> </g> <path className="st1" d="M228.47,407.89c-0.01-0.29,0.03-0.94,0-1.22c-3.52-2.29-8.63-5.55-11.66-7.57c-0.63,2.35-1.02,5.35-0.62,8.56 c0.68,5.36,3.39,9.64,6.42,9.88C227.13,417.9,228.7,413.52,228.47,407.89z M221.96,411.66c-1.06,0-1.92-1.32-1.92-2.96 c0-1.63,0.86-2.96,1.92-2.96c1.06,0,1.92,1.32,1.92,2.96C223.88,410.33,223.02,411.66,221.96,411.66z"/> <path id="SVGID_x5F_1_x5F_" className="st5" d="M284,519.85c64.43,0,116.85-52.42,116.85-116.85c0-64.43-52.42-116.85-116.85-116.85 c-64.43,0-116.85,52.42-116.85,116.85C167.15,467.43,219.57,519.85,284,519.85z"/> <text className="st1"> <textPath startOffset="1165.844%"> <tspan style={{fontFamily: 'MyriadPro-Regular', fontSize: '16.6923px', letterSpacing: '262px'}}>{'DON’T @HERE ME'}</tspan> </textPath> </text> </g> <g id="Colors"> <path className="st6" d="M333.93,516.09c0.72-0.32,1.44-0.63,2.15-0.97l-2.63-1.23c-1.86-5.77-8.31-15.7-8.31-15.7 s17.92-61.24-5.86-74.92c1.95-3.58,1.95-26.71-7.49-28.34c5.86-8.47-0.98-55.37-57.33-55.05s-74.27,41.04-74.27,41.04l-17.73,3.67 l-1.29-1.41c-0.99,6.31-1.51,12.78-1.51,19.36c0,68.54,55.57,124.11,124.11,124.11c17.82,0,34.76-3.77,50.08-10.54 c0.03-0.01,0.05-0.01,0.08-0.02C333.93,516.11,333.93,516.1,333.93,516.09z"/> <circle className="st7" cx="283.83" cy="403.33" r="124.33"/> <path className="st8" d="M254.12,428.82c2.44-6.76,15.71-31.95,18.89-32.25c3.18-0.3,34.85,25.73,39.09,36.48 c4.23,10.75,9.77,14.33,8.79,29.97c-4.56-3.91-51.96-20.88-51.96-20.88l-14.49,6.88C254.45,449.01,251.6,435.8,254.12,428.82z"/> <path className="st8" d="M315.04,462.69c0,0-12.38,0.98-18.57,3.26c-6.19,2.28-13.1,14.67-13.1,14.67s-6.93-3.03-9.7-4.25 c-2.56-1.13-19.22-27.36-19.22-27.36l14.49-6.88l46.1,18.6V462.69z"/> <path className="st9" d="M211.78,394.94l-10.42,9.45c0,0,0.63,20.78,21.5,22.48c12.05,0.98,16.29-14.33,16.29-14.33L211.78,394.94z"/> <path className="st9" d="M312.43,428.16c0,0,11.15-5.23,6.84-22.48c-3.26-13.03-7.49-10.75-7.49-10.75l-15.64,13.03l-1.63,1.95 L312.43,428.16z"/> <path className="st10" d="M335.72,378.08c0,0-0.86,5.5-0.73,7.7c0.12,2.2,4.52,24.8,4.52,24.8s2.32,6.6,3.18,7.08 c0.86,0.49,2.2-0.12,2.2-0.12l1.71-4.89c0,0,0.86-12.09,0.12-14.17C345.98,396.41,339.51,379.79,335.72,378.08z"/> <polygon className="st10" points="347.94,426.7 350.62,430.49 357.22,434.27 364.67,435 373.59,433.42 383.6,429.39 389.47,425.6 390.08,423.89 387.76,423.64 377.99,425.6 368.7,426.58 360.03,425.11 350.38,424.99 "/> <polygon className="st10" points="367.72,404.34 372.86,399.09 381.04,395.18 387.02,394.08 396.43,393.72 399.48,394.08 397.65,397.02 392.89,400.68 384.34,405.32 378.6,407.15 372.61,407.89 368.82,406.06 "/> <polygon className="st10" points="359.42,400.56 357.22,399.09 354.04,393.72 349.4,378.33 348.06,367.33 348.55,364.65 352.09,368.55 357.22,378.94 361.13,392.62 361.13,397.87 "/> <path className="st11" d="M384.42,360.74c-4.4,7.82-18.08,14.01-20.68,18.73s7.03,8.72,7.03,8.72s7.94,3.47,9.75,1.05 C386.05,381.82,383.12,373.74,384.42,360.74z M377.09,382.6l-5.21-2.97l6.93-5.27L377.09,382.6z"/> <path id="SVGID_x5F_00000080910466905454608670000016559596414473353368_x5F_" className="st12" d="M284,519.85 c64.43,0,116.85-52.42,116.85-116.85c0-64.43-52.42-116.85-116.85-116.85c-64.43,0-116.85,52.42-116.85,116.85 C167.15,467.43,219.57,519.85,284,519.85z"/> <text> <textPath startOffset="1165.844%"> <tspan className="st9" style={{fontFamily: 'MyriadPro-Regular', fontSize: '16.6923px', letterSpacing: '262px'}}>{'DON’T @HERE ME'}</tspan> </textPath> </text> </g> <g id="Trace_w_x2F_shading"> <path className="st7" d="M284,279c-62.23,0-113.75,45.84-122.64,105.59l18.01-3.33c0,0,17.1-40.07,71.34-42.02 c54.23-1.95,68.57,43.49,61.56,55.21c6.84,2.12,10.26,20.52,6.35,27.85c17.59,5.37,15.15,56.19,6.84,75.73 c2.55,4.15,6.77,12.67,9.39,18.09C377.98,496.71,408,453.36,408,403C408,334.52,352.48,279,284,279z"/> <path d="M254.12,428.65c1.9-4.77,3.97-9.47,6.15-14.13c1.09-2.33,2.21-4.65,3.39-6.94c1.16-2.31,2.59-4.47,4.02-6.65 c0.74-1.08,1.51-2.14,2.39-3.16c0.45-0.51,0.92-1.01,1.5-1.47c0.29-0.23,0.61-0.46,1.02-0.64c0.2-0.09,0.44-0.17,0.7-0.22 c0.29-0.05,0.56-0.03,0.8,0.01c0.88,0.18,1.48,0.5,2.09,0.82c0.6,0.33,1.16,0.68,1.72,1.04c1.1,0.73,2.15,1.5,3.18,2.29 c4.1,3.18,7.93,6.61,11.7,10.13c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17 c1.46,2.28,2.53,4.61,3.54,7.03c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93 c0.04,1.33,0.04,2.67-0.29,4.1l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66 c-2.77-1.08-5.53-2.17-8.33-3.18c-2.79-0.98-5.52-2.23-8.3-3.05c-0.34-0.1-0.69-0.19-1.02-0.26c-0.37-0.07-0.5-0.09-0.89-0.02 c-0.67,0.09-1.38,0.29-2.08,0.5c-1.4,0.43-2.78,0.96-4.16,1.51c-2.74,1.13-5.47,2.34-8.15,3.63c2.56-1.53,5.15-3.01,7.83-4.34 c1.34-0.67,2.69-1.31,4.11-1.87c0.71-0.27,1.42-0.54,2.22-0.71c0.21-0.04,0.35-0.1,0.66-0.11c0.25-0.01,0.46,0.01,0.67,0.03 c0.41,0.05,0.79,0.12,1.17,0.2c1.5,0.32,2.94,0.74,4.38,1.17c1.44,0.43,2.87,0.87,4.26,1.42l8.35,3.22 c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72c0.25-1.07,0.28-2.32,0.24-3.54 c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15c-0.97-2.31-2.05-4.66-3.37-6.69 c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8c-3.73-3.48-7.55-6.89-11.55-10c-1-0.77-2.02-1.52-3.06-2.21 c-0.52-0.34-1.04-0.67-1.57-0.96c-0.51-0.28-1.08-0.54-1.46-0.61c-0.08-0.01-0.13-0.01-0.15-0.01c-0.05,0.01-0.12,0.03-0.21,0.07 c-0.18,0.08-0.39,0.21-0.6,0.39c-0.42,0.34-0.84,0.77-1.24,1.22c-0.8,0.92-1.53,1.93-2.24,2.97c-1.44,2.07-2.63,4.32-4,6.47 c-1.34,2.17-2.63,4.37-3.9,6.6C258.93,419.59,256.51,424.11,254.12,428.65z"/> <path d="M273.67,476.54l9.84,3.73l-0.24,0.08c1.86-3.18,3.91-6.25,6.27-9.11c1.19-1.42,2.46-2.79,3.95-3.96 c0.74-0.6,1.58-1.09,2.47-1.48c0.88-0.36,1.77-0.67,2.67-0.91c3.59-1.02,7.06-1.87,10.7-2.44c3.65-0.54,5.11-1.11,8.79-1.47 l1.3,1.63c-3.64,0.22-6.14,0.98-9.77,1.38c-3.62,0.43-7.21,1.18-10.72,2.05c-1.77,0.44-3.45,0.95-4.86,2.03 c-1.44,1.04-2.73,2.34-3.95,3.68c-2.42,2.72-4.57,5.7-6.54,8.79l-0.09,0.14l-0.15-0.06L273.67,476.54z"/> <path d="M195.49,410.09c1.67-2.31,3.44-4.53,5.24-6.74c2.02-1.98,4.03-3.97,6.12-5.9c1.06-0.97,2.08-1.92,3.3-2.83 c0.15-0.11,0.33-0.23,0.51-0.34c0.1-0.06,0.23-0.13,0.35-0.18c0.11-0.06,0.51-0.17,0.72-0.13c0.59,0.1,0.62,0.2,0.87,0.29 l0.51,0.27c0.64,0.37,1.25,0.75,1.85,1.13c2.4,1.54,4.73,3.12,7.08,4.68c4.69,3.12,9.36,6.31,14.19,9.08 c0.6,0.34,1.21,0.67,1.82,0.96c0.59,0.29,1.26,0.58,1.69,0.66c0.09-0.02-0.02,0.04,0.16-0.01c0.12-0.04,0.23-0.06,0.36-0.11 c0.27-0.12,0.54-0.23,0.83-0.4c0.58-0.28,1.09-0.73,1.67-1.08c2.39-1.36,4.68-3.05,6.97-4.73c-1.74,2.26-3.63,4.39-5.8,6.35 c-0.28,0.24-0.58,0.45-0.91,0.63c-0.32,0.19-0.63,0.4-0.97,0.58c-0.32,0.19-0.71,0.35-1.08,0.51c-0.2,0.08-0.43,0.13-0.65,0.19 c-0.15,0.07-0.63,0.07-0.89,0.03c-0.95-0.19-1.57-0.52-2.25-0.84c-0.67-0.32-1.3-0.67-1.92-1.02c-4.96-2.85-9.62-6.04-14.32-9.16 c-2.35-1.57-4.68-3.15-7.04-4.66c-0.59-0.37-1.18-0.74-1.76-1.08l-0.42-0.23c-0.07-0.05-0.35-0.13-0.11-0.09 c0.02-0.01,0.09,0.01,0.14,0c0.04,0,0.12-0.05,0.08-0.02l-0.12,0.06c-0.12,0.08-0.23,0.15-0.37,0.25 c-1.04,0.78-2.09,1.74-3.12,2.68c-2.05,1.9-4.07,3.87-6.05,5.86C199.95,406.56,197.76,408.35,195.49,410.09z"/> <path d="M285.71,397.72l5.31,4.57c1.77,1.52,3.51,3.08,5.27,4.62l-0.71-0.15c1.48-0.63,2.84-1.66,4.12-2.78 c1.28-1.12,2.45-2.38,3.71-3.56c1.26-1.19,2.91-3.08,3.48-3.77c0.58-0.68,1.29-1.49,2.08-1.95c0.39-0.24,1.4,0.29,1.83,0.12 c0.43-0.16,0.91-0.29,1.39-0.22v0.2c-0.79,0.23-1.39,0.86-2,1.44c-0.6,0.6-1.18,1.23-1.76,1.87c-1.16,1.28-2.32,2.58-3.57,3.81 c-1.25,1.23-2.63,2.36-4.06,3.42c-1.44,1.06-2.95,2.08-4.74,2.7l-0.42,0.15l-0.29-0.29c-1.64-1.66-3.29-3.31-4.91-4.99l-4.87-5.04 L285.71,397.72z"/> <path className="st13" d="M201.84,403.73c0,0-1.95,18.57,18.57,22.48c14.68,2.8,19.54-14.17,19.54-14.17"/> <path d="M308.48,396.98c-2.86,2.56-6.55,6.66-10.05,9.01c0.49,5.42,3.37,9.59,6.66,9.44c3.45-0.16,6.03-4.99,5.77-10.8 C310.72,401.57,309.81,398.85,308.48,396.98z M303.5,410.48c-1.06,0-1.92-1.32-1.92-2.96c0-1.63,0.86-2.96,1.92-2.96 c1.06,0,1.92,1.32,1.92,2.96C305.43,409.15,304.57,410.48,303.5,410.48z"/> <path d="M254.06,449.02c2.54-1.57,5.12-3.07,7.79-4.43c1.34-0.68,2.69-1.34,4.1-1.91c0.72-0.28,1.42-0.56,2.23-0.74 c0.22-0.04,0.35-0.11,0.68-0.12c0.27-0.01,0.48,0.01,0.69,0.03c0.42,0.05,0.81,0.11,1.19,0.19c1.52,0.3,2.96,0.73,4.37,1.25 l4.22,1.52c2.8,1.04,5.58,2.11,8.36,3.2c5.55,2.18,11.07,4.42,16.58,6.67l8.27,3.36c2.74,1.09,5.55,2.28,8.24,3.19l-1.26,0.72 c0.25-1.07,0.28-2.32,0.24-3.54c-0.05-1.23-0.18-2.48-0.36-3.72c-0.37-2.48-0.93-4.95-1.61-7.38c-0.69-2.43-1.51-4.82-2.47-7.15 c-0.97-2.31-2.05-4.66-3.37-6.69c-2.81-4.13-6.29-7.93-9.75-11.65c-3.5-3.71-7.13-7.31-10.86-10.8 c-3.72-3.49-7.56-6.87-11.54-10.01c-0.97-0.81-1.96-1.6-2.98-2.33c-0.51-0.37-1.02-0.72-1.54-1.03c-0.51-0.31-1.07-0.6-1.53-0.71 c-0.3-0.11-0.76,0.13-1.23,0.49c-0.46,0.35-0.89,0.79-1.31,1.24c-0.83,0.92-1.59,1.94-2.32,2.97c-2.9,4.17-5.41,8.66-7.85,13.16 c-2.43,4.51-4.77,9.07-7,13.69c2.05-4.7,4.2-9.36,6.47-13.96c2.3-4.59,4.65-9.16,7.46-13.5c0.71-1.08,1.46-2.15,2.31-3.16 c0.43-0.5,0.88-1,1.43-1.45c0.27-0.23,0.57-0.44,0.94-0.61c0.18-0.09,0.39-0.16,0.62-0.2c0.25-0.04,0.48-0.03,0.7-0.01 c0.81,0.14,1.41,0.43,2.03,0.72c0.6,0.3,1.18,0.63,1.74,0.97c1.12,0.68,2.2,1.42,3.26,2.17c4.12,3.15,7.93,6.61,11.71,10.11 c3.75,3.52,7.41,7.14,10.95,10.89c1.77,1.88,3.5,3.78,5.18,5.75c1.68,1.97,3.32,3.97,4.78,6.17c1.46,2.28,2.53,4.61,3.54,7.03 c0.99,2.41,1.84,4.87,2.55,7.37c0.71,2.5,1.28,5.05,1.67,7.63c0.19,1.29,0.33,2.6,0.38,3.93c0.04,1.33,0.04,2.67-0.29,4.1 l-0.25,1.06l-1.01-0.34c-2.95-1-5.63-2.15-8.42-3.25l-8.28-3.37c-5.51-2.25-11.03-4.48-16.56-6.66c-5.51-2.18-11.13-4.3-16.67-6.06 c-0.34-0.11-0.68-0.2-1-0.27c-0.37-0.07-0.45-0.09-0.84-0.03c-0.66,0.08-1.37,0.27-2.06,0.47c-1.39,0.41-2.78,0.93-4.16,1.47 C259.5,446.58,256.77,447.77,254.06,449.02z"/> <path d="M339.52,425.68c0.11-0.16,0.15-0.18,0.21-0.24c0.06-0.06,0.11-0.09,0.16-0.13c0.1-0.08,0.2-0.15,0.29-0.19 c0.2-0.12,0.37-0.18,0.56-0.25c0.36-0.12,0.71-0.18,1.05-0.22c0.67-0.07,1.31-0.04,1.93,0.03c1.24,0.14,2.4,0.45,3.54,0.8 c1.14,0.36,2.25,0.77,3.33,1.24c1.09,0.45,2.15,0.96,3.21,1.45c-1.12-0.34-2.24-0.7-3.37-0.98c-1.13-0.3-2.27-0.55-3.4-0.74 c-1.13-0.18-2.28-0.32-3.38-0.28c-0.55,0.01-1.09,0.07-1.57,0.19c-0.24,0.06-0.46,0.14-0.64,0.23c-0.08,0.05-0.18,0.1-0.22,0.15 c-0.03,0.02-0.06,0.05-0.06,0.06c-0.01,0.01-0.02,0.02-0.01,0.01c0.01-0.01-0.01,0.02,0.06-0.08L339.52,425.68z"/> <path d="M341.94,424.24c0.21-0.3,0.45-0.79,0.63-1.23c0.2-0.45,0.36-0.93,0.51-1.42c0.29-0.97,0.49-1.99,0.63-3.01 c0.14-1.03,0.19-2.08,0.21-3.13c0.01-1.05-0.05-2.11-0.14-3.17c0.25,1.03,0.48,2.07,0.64,3.13c0.15,1.06,0.27,2.13,0.29,3.21 c0.02,1.08-0.02,2.18-0.16,3.28c-0.08,0.55-0.17,1.1-0.31,1.65c-0.14,0.57-0.28,1.06-0.57,1.7L341.94,424.24z"/> <path d="M359.23,408.73c0.16-0.32,0.32-0.87,0.41-1.35c0.11-0.5,0.16-1.02,0.2-1.54c0.07-1.05-0.01-2.12-0.16-3.19 c-0.15-1.07-0.43-2.13-0.75-3.18c-0.17-0.52-0.37-1.03-0.55-1.56l-0.66-1.52l0.88,1.42c0.26,0.49,0.55,0.97,0.79,1.48 c0.48,1.01,0.94,2.05,1.27,3.14c0.33,1.09,0.58,2.22,0.69,3.39c0.05,0.58,0.07,1.17,0.04,1.77c-0.04,0.62-0.6,1.03-0.81,1.76 L359.23,408.73z"/> <path d="M362.94,403.96c1.01,0.16,2.12,0.25,3.2,0.28c1.09,0.03,2.18-0.01,3.27-0.1c1.09-0.09,2.17-0.28,3.24-0.54 c1.07-0.25,2.11-0.64,3.14-1.09c-0.94,0.6-1.93,1.14-2.98,1.56c-1.05,0.42-2.13,0.79-3.23,1.05c-1.1,0.27-2.23,0.48-3.36,0.62 c-1.15,0.14-2.26,0.22-3.47,0.21L362.94,403.96z"/> <path className="st14" d="M344.03,417.9c-3.42,0.24-5.05-8.94-7.08-19.54c-1.22-6.35-2.44-13.44-1.47-21.01 c1.47-0.49,10.02,15.64,10.99,20.03C347.45,401.78,347.45,417.66,344.03,417.9z"/> <path className="st14" d="M359.42,400.56c-6.35-1.47-13.19-32.25-10.99-35.91C352.82,366.11,365.77,395.92,359.42,400.56z"/> <path className="st14" d="M367.72,404.22c0,0,8.79-13.19,31.76-10.26C398.26,399.83,371.39,414.48,367.72,404.22z"/> <path className="st14" d="M347.2,425.72c0,0,4.15,9.53,16.12,9.28c11.97-0.24,26.63-7.82,26.87-11.24c-1.71-1.22-15.6,4.23-24.92,2.2 C355.92,423.93,347.2,425.72,347.2,425.72z"/> <path d="M292.79,408.06c3.51,2.95,7,5.94,10.38,9.06c1.69,1.56,3.36,3.14,5.02,4.75c1.64,1.64,3.33,3.2,4.69,5.24l-1.01-0.44 c0.72-0.11,1.45-0.4,2.11-0.89c0.67-0.48,1.29-1.1,1.85-1.79c1.12-1.38,2.09-2.99,2.94-4.67l0.19,0.06 c-0.12,0.96-0.39,1.88-0.68,2.8c-0.32,0.92-0.72,1.81-1.22,2.67c-0.52,0.85-1.12,1.68-1.93,2.37c-0.79,0.7-1.8,1.27-2.94,1.47 l-0.6,0.11l-0.41-0.55c-1.28-1.7-2.74-3.49-4.23-5.2c-1.51-1.71-3.08-3.37-4.66-5.02c-3.19-3.28-6.36-6.59-9.62-9.82L292.79,408.06 z"/> <g> <path d="M305.69,456.45c-0.75,1.22-1.48,2.46-2.16,3.71c-2.69,5.01-4.82,10.33-6.29,15.85c-0.73,2.76-1.3,5.57-1.67,8.41 c-0.18,1.42-0.33,2.85-0.41,4.29c-0.07,1.46-0.13,2.84-0.03,4.43l3.98-0.35c-0.1-1.18-0.09-2.59-0.05-3.9 c0.05-1.34,0.15-2.68,0.29-4.02c0.29-2.68,0.76-5.35,1.4-7.98c1.27-5.27,3.19-10.38,5.65-15.23c0.71-1.37,1.47-2.71,2.26-4.03 L305.69,456.45z"/> <path d="M370.06,388.01c-0.84,2.61-1.91,5.18-3.06,7.68c-0.56,1.26-1.22,2.48-1.84,3.71c-0.69,1.19-1.3,2.43-2.06,3.59 c-2.87,4.7-6.19,9.13-10.11,12.95c-0.94,1-1.99,1.87-3.03,2.76c-0.53,0.44-1.02,0.91-1.57,1.31l-1.66,1.19l-1.66,1.19l-1.76,1.03 c-1.17,0.69-2.34,1.38-3.59,2.06c-4.94,2.66-9.7,5.69-14.15,9.15c-2.98,2.31-5.81,4.82-8.49,7.49c0.4,0.97,0.78,1.98,1.07,2.85 c2.78-3,5.79-5.79,8.98-8.38c4.25-3.47,8.85-6.53,13.64-9.26c1.18-0.67,2.4-1.42,3.61-2.16l1.82-1.11l1.71-1.27l1.7-1.27 c0.56-0.43,1.07-0.93,1.61-1.39c1.06-0.94,2.13-1.86,3.08-2.91c3.95-4.04,7.31-8.62,10.05-13.52c0.72-1.2,1.3-2.49,1.96-3.73 c0.58-1.28,1.21-2.53,1.73-3.83c1.1-2.58,2.03-5.22,2.74-7.95L370.06,388.01z"/> </g> <path d="M228.47,407.89c-0.01-0.29,0.03-0.94,0-1.22c-3.52-2.29-8.63-5.55-11.66-7.57c-0.63,2.35-1.02,5.35-0.62,8.56 c0.68,5.36,3.39,9.64,6.42,9.88C227.13,417.9,228.7,413.52,228.47,407.89z M221.96,411.66c-1.06,0-1.92-1.32-1.92-2.96 c0-1.63,0.86-2.96,1.92-2.96c1.06,0,1.92,1.32,1.92,2.96C223.88,410.33,223.02,411.66,221.96,411.66z"/> <path className="st14" d="M384.42,360.74c-4.4,7.82-18.08,14.01-20.68,18.73c-2.61,4.72,7.03,8.72,7.03,8.72s7.94,3.47,9.75,1.05 C386.05,381.82,383.12,373.74,384.42,360.74z"/> <polygon className="st14" points="377.09,382.6 371.88,379.63 378.81,374.36 "/> <polygon points="375.3,381.58 375.79,390.1 377.66,382.42 "/> </g> </svg> ); }
the_stack
import fs from 'fs'; import path from 'path'; import * as component from 'common/component'; import { KubeflowConfig, toMegaBytes } from 'common/experimentConfig'; import { ExperimentStartupInfo } from 'common/experimentStartupInfo'; import { EnvironmentInformation } from 'training_service/reusable/environment'; import { KubernetesEnvironmentService } from './kubernetesEnvironmentService'; import { KubeflowOperatorClientFactory } from 'training_service/kubernetes/kubeflow/kubeflowApiClient'; import { KubeflowClusterConfigAzure } from 'training_service/kubernetes/kubeflow/kubeflowConfig'; import { KeyVaultConfig, AzureStorage } from 'training_service/kubernetes/kubernetesConfig'; @component.Singleton export class KubeflowEnvironmentService extends KubernetesEnvironmentService { private config: KubeflowConfig; private createStoragePromise?: Promise<void>; constructor(config: KubeflowConfig, info: ExperimentStartupInfo) { super(config, info); this.experimentId = info.experimentId; this.config = config; // Create kubernetesCRDClient this.kubernetesCRDClient = KubeflowOperatorClientFactory.createClient( this.config.operator, this.config.apiVersion); // Create storage if (this.config.storage.storageType === 'azureStorage') { if (this.config.storage.azureShare === undefined || this.config.storage.azureAccount === undefined || this.config.storage.keyVaultName === undefined || this.config.storage.keyVaultKey === undefined) { throw new Error("Azure storage configuration error!"); } const azureStorage: AzureStorage = new AzureStorage(this.config.storage.azureShare, this.config.storage.azureAccount); const keyValutConfig: KeyVaultConfig = new KeyVaultConfig(this.config.storage.keyVaultName, this.config.storage.keyVaultKey); const azureKubeflowClusterConfig: KubeflowClusterConfigAzure = new KubeflowClusterConfigAzure( this.config.operator, this.config.apiVersion, keyValutConfig, azureStorage); this.azureStorageAccountName = azureKubeflowClusterConfig.azureStorage.accountName; this.azureStorageShare = azureKubeflowClusterConfig.azureStorage.azureShare; this.createStoragePromise = this.createAzureStorage( azureKubeflowClusterConfig.keyVault.vaultName, azureKubeflowClusterConfig.keyVault.name ); } else if (this.config.storage.storageType === 'nfs') { if (this.config.storage.server === undefined || this.config.storage.path === undefined) { throw new Error("NFS storage configuration error!"); } this.createStoragePromise = this.createNFSStorage( this.config.storage.server, this.config.storage.path ); } } public get environmentMaintenceLoopInterval(): number { return 5000; } public get hasStorageService(): boolean { return false; } public get getName(): string { return 'kubeflow'; } public async startEnvironment(environment: EnvironmentInformation): Promise<void> { if (this.kubernetesCRDClient === undefined) { throw new Error("kubernetesCRDClient not initialized!"); } if (this.createStoragePromise) { await this.createStoragePromise; } const expFolder = `${this.CONTAINER_MOUNT_PATH}/nni/${this.experimentId}`; environment.command = `cd ${expFolder} && ${environment.command} \ 1>${expFolder}/envs/${environment.id}/trialrunner_stdout 2>${expFolder}/envs/${environment.id}/trialrunner_stderr`; environment.maxTrialNumberPerGpu = this.config.maxTrialNumberPerGpu; const kubeflowJobName: string = `nniexp${this.experimentId}env${environment.id}`.toLowerCase(); await fs.promises.writeFile(path.join(this.environmentLocalTempFolder, "run.sh"), environment.command, { encoding: 'utf8' }); //upload script files to sotrage const trialJobOutputUrl: string = await this.uploadFolder(this.environmentLocalTempFolder, `nni/${this.experimentId}`); environment.trackingUrl = trialJobOutputUrl; // Generate kubeflow job resource config object const kubeflowJobConfig: any = await this.prepareKubeflowConfig(environment.id, kubeflowJobName); // Create kubeflow job based on generated kubeflow job resource config await this.kubernetesCRDClient.createKubernetesJob(kubeflowJobConfig); } /** * upload local folder to nfs or azureStroage */ private async uploadFolder(srcDirectory: string, destDirectory: string): Promise<string> { if (this.config.storage.storageType === 'azureStorage') { if (this.azureStorageClient === undefined) { throw new Error('azureStorageClient is not initialized'); } return await this.uploadFolderToAzureStorage(srcDirectory, destDirectory, 2); } else { // do not need to upload files to nfs server, temp folder already mounted to nfs return `nfs://${this.config.storage.server}:${destDirectory}`; } } private async prepareKubeflowConfig(envId: string, kubeflowJobName: string): Promise<any> { const workerPodResources: any = {}; if (this.config.worker !== undefined) { workerPodResources.requests = this.generatePodResource(toMegaBytes(this.config.worker.memorySize), this.config.worker.cpuNumber, this.config.worker.gpuNumber); } workerPodResources.limits = {...workerPodResources.requests}; const nonWorkerResources: any = {}; if (this.config.operator === 'tf-operator') { if (this.config.ps !== undefined) { nonWorkerResources.requests = this.generatePodResource(toMegaBytes(this.config.ps.memorySize), this.config.ps.cpuNumber, this.config.ps.gpuNumber); nonWorkerResources.limits = {...nonWorkerResources.requests}; } } else if (this.config.operator === 'pytorch-operator') { if (this.config.master !== undefined) { nonWorkerResources.requests = this.generatePodResource(toMegaBytes(this.config.master.memorySize), this.config.master.cpuNumber, this.config.master.gpuNumber); nonWorkerResources.limits = {...nonWorkerResources.requests}; } } // Generate kubeflow job resource config object const kubeflowJobConfig: any = await this.generateKubeflowJobConfig(envId, kubeflowJobName, workerPodResources, nonWorkerResources); return Promise.resolve(kubeflowJobConfig); } /** * Generate kubeflow resource config file * @param kubeflowJobName job name * @param workerPodResources worker pod template * @param nonWorkerPodResources non-worker pod template, like ps or master */ private async generateKubeflowJobConfig(envId: string, kubeflowJobName: string, workerPodResources: any, nonWorkerPodResources?: any): Promise<any> { if (this.kubernetesCRDClient === undefined) { throw new Error('Kubeflow operator client is not initialized'); } const replicaSpecsObj: any = {}; const replicaSpecsObjMap: Map<string, object> = new Map<string, object>(); if (this.config.operator === 'tf-operator') { if (this.config.worker) { const privateRegistrySecretName = await this.createRegistrySecret(this.config.worker.privateRegistryAuthPath); replicaSpecsObj.Worker = this.generateReplicaConfig(this.config.worker.replicas, this.config.worker.dockerImage, 'run.sh', workerPodResources, privateRegistrySecretName); } if (this.config.ps !== undefined) { const privateRegistrySecretName: string | undefined = await this.createRegistrySecret(this.config.ps.privateRegistryAuthPath); replicaSpecsObj.Ps = this.generateReplicaConfig(this.config.ps.replicas, this.config.ps.dockerImage, 'run.sh', nonWorkerPodResources, privateRegistrySecretName); } replicaSpecsObjMap.set(this.kubernetesCRDClient.jobKind, {tfReplicaSpecs: replicaSpecsObj}); } else if (this.config.operator === 'pytorch-operator') { if (this.config.worker !== undefined) { const privateRegistrySecretName: string | undefined = await this.createRegistrySecret(this.config.worker.privateRegistryAuthPath); replicaSpecsObj.Worker = this.generateReplicaConfig(this.config.worker.replicas, this.config.worker.dockerImage, 'run.sh', workerPodResources, privateRegistrySecretName); } if (this.config.master !== undefined) { const privateRegistrySecretName: string | undefined = await this.createRegistrySecret(this.config.master.privateRegistryAuthPath); replicaSpecsObj.Master = this.generateReplicaConfig(this.config.master.replicas, this.config.master.dockerImage, 'run.sh', nonWorkerPodResources, privateRegistrySecretName); } replicaSpecsObjMap.set(this.kubernetesCRDClient.jobKind, {pytorchReplicaSpecs: replicaSpecsObj}); } return Promise.resolve({ apiVersion: `kubeflow.org/${this.kubernetesCRDClient.apiVersion}`, kind: this.kubernetesCRDClient.jobKind, metadata: { name: kubeflowJobName, namespace: 'default', labels: { app: this.NNI_KUBERNETES_TRIAL_LABEL, expId: this.experimentId, envId: envId } }, spec: replicaSpecsObjMap.get(this.kubernetesCRDClient.jobKind) }); } /** * Generate tf-operator's tfjobs replica config section * @param replicaNumber replica number * @param replicaImage image * @param runScriptFile script file name * @param podResources pod resource config section */ private generateReplicaConfig(replicaNumber: number, replicaImage: string, runScriptFile: string, podResources: any, privateRegistrySecretName: string | undefined): any { if (this.kubernetesCRDClient === undefined) { throw new Error('Kubeflow operator client is not initialized'); } // The config spec for volume field const volumeSpecMap: Map<string, object> = new Map<string, object>(); if (this.config.storage.storageType === 'azureStorage') { volumeSpecMap.set('nniVolumes', [ { name: 'nni-vol', azureFile: { secretName: `${this.azureStorageSecretName}`, shareName: `${this.azureStorageShare}`, readonly: false } }]); } else { volumeSpecMap.set('nniVolumes', [ { name: 'nni-vol', nfs: { server: `${this.config.storage.server}`, path: `${this.config.storage.path}` } }]); } // The config spec for container field const containersSpecMap: Map<string, object> = new Map<string, object>(); containersSpecMap.set('containers', [ { // Kubeflow tensorflow operator requires that containers' name must be tensorflow // TODO: change the name based on operator's type name: this.kubernetesCRDClient.containerName, image: replicaImage, args: ['sh', `${path.join(this.environmentWorkingFolder, runScriptFile)}`], volumeMounts: [ { name: 'nni-vol', mountPath: this.CONTAINER_MOUNT_PATH }], resources: podResources } ]); const spec: any = { containers: containersSpecMap.get('containers'), restartPolicy: 'ExitCode', volumes: volumeSpecMap.get('nniVolumes') } if (privateRegistrySecretName) { spec.imagePullSecrets = [ { name: privateRegistrySecretName }] } return { replicas: replicaNumber, template: { metadata: { creationTimestamp: null }, spec: spec } } } }
the_stack
import { HttpClientModule, HttpResponse } from '@angular/common/http'; import { CommonModule, DatePipe } from '@angular/common'; import { Router, ActivatedRoute } from '@angular/router'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, TestBed, fakeAsync, tick, waitForAsync } from '@angular/core/testing'; import { ToastrModule, ToastrService } from 'ngx-toastr'; import { of, Observable, throwError } from 'rxjs'; import { PackagesService, PackageInteractionService } from '../core'; import { MockedRouter, ToastrMock, MockedActivatedRoute } from '../mocks'; import { PackageListComponent, SearchPeriodComponent, SharePopoverComponent } from '../shared/components'; import { IPackageDownloadHistory } from '../shared/models/package-models'; import { PackagesComponent } from './packages.component'; class PackagesServiceMock { public static mockedDownloadHistory: IPackageDownloadHistory[] = [ { id: 'EntityFramework', downloads: [ { week: new Date('2018-10-28T00:00:00'), count: 51756066 }, { week: new Date('2018-11-04T00:00:00'), count: 52022309 }, { week: new Date('2018-11-11T00:00:00'), count: 52394207 }, ] }, { id: 'Dapper', downloads: [ { week: new Date('2018-10-28T00:00:00'), count: 11659886 }, { week: new Date('2018-11-04T00:00:00'), count: 11816356 }, { week: new Date('2018-11-11T00:00:00'), count: 12043389 }, ] }]; getPackageDownloadHistory(packageId: string, _months: number = 12): Observable<IPackageDownloadHistory> { return of(PackagesServiceMock.mockedDownloadHistory.find(p => p.id === packageId)!); } } describe('PackagesComponent', () => { let component: PackagesComponent; let fixture: ComponentFixture<PackagesComponent>; let activatedRoute: MockedActivatedRoute; let mockedPackageService: PackagesServiceMock; let router: MockedRouter; let mockedToastr: ToastrMock; let packageInteractionService: PackageInteractionService; const queryParamName = 'ids'; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [PackagesComponent, PackageListComponent, SearchPeriodComponent, SharePopoverComponent], imports: [ CommonModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule, RouterTestingModule.withRoutes([]), HttpClientModule, ToastrModule.forRoot({ positionClass: 'toast-bottom-right', preventDuplicates: true, })], providers: [ DatePipe, { provide: PackagesService, useClass: PackagesServiceMock }, { provide: ToastrService, useClass: ToastrMock }, { provide: Router, useClass: MockedRouter }, { provide: ActivatedRoute, useClass: MockedActivatedRoute }, ], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PackagesComponent); component = fixture.componentInstance; activatedRoute = MockedActivatedRoute.injectMockActivatedRoute(); mockedPackageService = TestBed.inject(PackagesService); packageInteractionService = TestBed.inject(PackageInteractionService); router = MockedRouter.injectMockRouter(); mockedToastr = TestBed.inject(ToastrService); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('Load Packages from the URL', () => { it('should skip loading packages if the URL does not contain params', () => { spyOn(mockedPackageService, 'getPackageDownloadHistory').and.callThrough(); spyOn(packageInteractionService, 'addPackage').and.callThrough(); fixture.detectChanges(); expect(mockedPackageService.getPackageDownloadHistory).not.toHaveBeenCalled(); expect(packageInteractionService.addPackage).not.toHaveBeenCalledTimes(1); }); it('should load package history when ids are present in the URL', fakeAsync(() => { spyOn(mockedPackageService, 'getPackageDownloadHistory').and.callThrough(); spyOn(packageInteractionService, 'addPackage').and.callThrough(); spyOn(packageInteractionService, 'plotPackage').and.callThrough(); const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); const actualPackageElements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.tags span'); expect(actualPackageElements.length).toBe(packages.length); expect(mockedPackageService.getPackageDownloadHistory).toHaveBeenCalledTimes(packages.length); expect(packageInteractionService.addPackage).toHaveBeenCalledTimes(packages.length); expect(packageInteractionService.plotPackage).toHaveBeenCalledTimes(packages.length); })); it('should show error message when request fails during initial history load', fakeAsync(() => { // Fake the service returning an error const response = new HttpResponse({ body: '{ "error": ""}', status: 500 }); spyOn(mockedPackageService, 'getPackageDownloadHistory').and.returnValue(throwError(response)); spyOn(mockedToastr, 'error').and.callThrough(); const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); expect(mockedToastr.error).toHaveBeenCalled(); })); }); describe('Period Changed', () => { it('should re-load package history when the period changes', fakeAsync(() => { // Initially start the page with a package in URL const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); spyOn(mockedPackageService, 'getPackageDownloadHistory').and.callThrough(); spyOn(packageInteractionService, 'updatePackage').and.callThrough(); spyOn(packageInteractionService, 'plotPackage').and.callThrough(); // trigger the change of the period via the service const newPeriod = 24; packageInteractionService.changeSearchPeriod(newPeriod); tick(); fixture.detectChanges(); const actualPackageElements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.tags span'); expect(actualPackageElements.length).toBe(packages.length); expect(mockedPackageService.getPackageDownloadHistory).toHaveBeenCalledWith(packages[0], newPeriod); expect(packageInteractionService.updatePackage).toHaveBeenCalledTimes(packages.length); expect(packageInteractionService.plotPackage).toHaveBeenCalledTimes(packages.length); })); it('should skip re-loading package history when the period changes if there are no ids in the URL', fakeAsync(() => { spyOn(mockedPackageService, 'getPackageDownloadHistory').and.callThrough(); spyOn(packageInteractionService, 'updatePackage').and.callThrough(); spyOn(packageInteractionService, 'plotPackage').and.callThrough(); fixture.detectChanges(); // trigger the change of the period via the service const newPeriod = 24; packageInteractionService.changeSearchPeriod(newPeriod); tick(); fixture.detectChanges(); expect(mockedPackageService.getPackageDownloadHistory).not.toHaveBeenCalled(); expect(packageInteractionService.updatePackage).not.toHaveBeenCalled(); expect(packageInteractionService.plotPackage).not.toHaveBeenCalled(); })); it('should show error message when request fails during period change', fakeAsync(() => { // Initially start the page with a package in URL const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); // Fake the service returning an error const response = new HttpResponse({ body: '{ "error": ""}', status: 500 }); spyOn(mockedPackageService, 'getPackageDownloadHistory').and.returnValue(throwError(response)); spyOn(mockedToastr, 'error').and.callThrough(); // trigger the change of the period via the service const newPeriod = 24; packageInteractionService.changeSearchPeriod(newPeriod); tick(); fixture.detectChanges(); expect(mockedToastr.error).toHaveBeenCalled(); })); }); describe('Remove Package', () => { it('should remove package from chart, URL and badge list', fakeAsync(() => { const spy = spyOn(router, 'navigate').and.callThrough(); // Arrange - Page should have been loaded with 2 packages const packages = ['EntityFramework', 'Dapper']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); let actualPackageElements: HTMLElement[] = fixture.nativeElement.querySelectorAll('.tags span'); expect(actualPackageElements.length).toBe(packages.length); // Act - Removes the "Dapper" package const removePackageButtons: Array<HTMLElement> = fixture.nativeElement.querySelectorAll('.tags span button'); removePackageButtons[1].click(); tick(); fixture.detectChanges(); // Assert - navigate should have been called with only EntityFramework actualPackageElements = fixture.nativeElement.querySelectorAll('.tags span'); const expectedUrlIds = ['EntityFramework']; const navigateActualParams: any[] = spy.calls.mostRecent().args; expect(actualPackageElements.length).toBe(expectedUrlIds.length); expect(navigateActualParams[1].queryParams[queryParamName]).toEqual(expectedUrlIds); })); it('should navigate home when the last package is removed', fakeAsync(() => { spyOn(router, 'navigate').and.callThrough(); // Arrange - Initialize the page with 1 package const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); // Act const removePackageButton: HTMLElement = fixture.nativeElement.querySelector('.tags span button'); removePackageButton.click(); tick(); fixture.detectChanges(); expect(router.navigate).toHaveBeenCalledWith(['/']); })); }); describe('Plot Package', () => { it('should react to package plotted event by adding it to the chart', fakeAsync(() => { const spy = spyOn(router, 'navigate').and.callThrough(); fixture.detectChanges(); // Act const entityFrameworkHistory = PackagesServiceMock.mockedDownloadHistory[0]; packageInteractionService.plotPackage(entityFrameworkHistory); tick(); fixture.detectChanges(); // Assert - Only EntityFramework should be in the URL const expectedUrlIds = 'EntityFramework'; const navigateActualParams: any[] = spy.calls.mostRecent().args; expect(navigateActualParams[1].queryParams[queryParamName]).toEqual(expectedUrlIds); expect(navigateActualParams[1].replaceUrl).toBeTruthy(); expect(navigateActualParams[1].queryParamsHandling).toBe('merge'); })); it('should update the URL as new packages are added to the chart', fakeAsync(() => { const spy = spyOn(router, 'navigate').and.callThrough(); fixture.detectChanges(); const packages = ['EntityFramework']; activatedRoute.testParamMap = { months: 12, ids: packages }; fixture.detectChanges(); tick(); fixture.detectChanges(); // Act - Add a second package packageInteractionService.plotPackage(PackagesServiceMock.mockedDownloadHistory[1]); fixture.detectChanges(); tick(); const navigateActualParams: any[] = spy.calls.mostRecent().args; // URL should have been updated expect(navigateActualParams[1].queryParams[queryParamName]).toEqual(['EntityFramework', 'Dapper']); expect(navigateActualParams[1].replaceUrl).toBeTruthy(); expect(navigateActualParams[1].queryParamsHandling).toBe('merge'); })); }); });
the_stack
import {DocPageModel} from 'app/client/models/DocPageModel'; import {reportWarning} from 'app/client/models/errors'; import {normalizeEmail} from 'app/common/emails'; import {GristLoadConfig} from 'app/common/gristUrls'; import * as roles from 'app/common/roles'; import {ANONYMOUS_USER_EMAIL, EVERYONE_EMAIL, PermissionData, PermissionDelta, UserAPI} from 'app/common/UserAPI'; import {getRealAccess} from 'app/common/UserAPI'; import {computed, Computed, Disposable, obsArray, ObsArray, observable, Observable} from 'grainjs'; import some = require('lodash/some'); export interface UserManagerModel { initData: PermissionData; // PermissionData used to initialize the UserManager resourceType: ResourceType; // String representing the access resource userSelectOptions: IMemberSelectOption[]; // Select options for each user's role dropdown orgUserSelectOptions: IOrgMemberSelectOption[]; // Select options for each user's role dropdown on the org inheritSelectOptions: IMemberSelectOption[]; // Select options for the maxInheritedRole dropdown maxInheritedRole: Observable<roles.BasicRole|null>; // Current unsaved maxInheritedRole setting membersEdited: ObsArray<IEditableMember>; // Current unsaved editable array of members publicMember: IEditableMember|null; // Member whose access (VIEWER or null) represents that of // anon@ or everyone@ (depending on the settings and resource). isAnythingChanged: Computed<boolean>; // Indicates whether there are unsaved changes isOrg: boolean; // Indicates if the UserManager is for an org // Resets all unsaved changes reset(): void; // Writes all unsaved changes to the server. save(userApi: UserAPI, resourceId: number|string): Promise<void>; // Adds a member to membersEdited add(email: string, role: roles.Role|null): void; // Removes a member from membersEdited remove(member: IEditableMember): void; // Returns a boolean indicating if the member is the currently active user. isActiveUser(member: IEditableMember): boolean; // Returns the PermissionDelta reflecting the current unsaved changes in the model. getDelta(): PermissionDelta; } export type ResourceType = 'organization'|'workspace'|'document'; export interface IEditableMember { id: number; // Newly invited members do not have ids and are represented by -1 name: string; email: string; picture?: string|null; access: Observable<roles.Role|null>; parentAccess: roles.BasicRole|null; inheritedAccess: Computed<roles.BasicRole|null>; effectiveAccess: Computed<roles.Role|null>; origAccess: roles.Role|null; isNew: boolean; isRemoved: boolean; } // An option for the select elements used in the UserManager. export interface IMemberSelectOption { value: roles.BasicRole|null; label: string; } // An option for the organization select elements used in the UserManager. export interface IOrgMemberSelectOption { value: roles.NonGuestRole|null; label: string; } interface IBuildMemberOptions { id: number; name: string; email: string; picture?: string|null; access: roles.Role|null; parentAccess: roles.BasicRole|null; } /** * */ export class UserManagerModelImpl extends Disposable implements UserManagerModel { // Select options for each individual user's role dropdown. public readonly userSelectOptions: IMemberSelectOption[] = [ { value: roles.OWNER, label: 'Owner' }, { value: roles.EDITOR, label: 'Editor' }, { value: roles.VIEWER, label: 'Viewer' } ]; // Select options for each individual user's role dropdown in the org. public readonly orgUserSelectOptions: IOrgMemberSelectOption[] = [ { value: roles.OWNER, label: 'Owner' }, { value: roles.EDITOR, label: 'Editor' }, { value: roles.VIEWER, label: 'Viewer' }, { value: roles.MEMBER, label: 'No Default Access' }, ]; // Select options for the resource's maxInheritedRole dropdown. public readonly inheritSelectOptions: IMemberSelectOption[] = [ { value: roles.OWNER, label: 'In Full' }, { value: roles.EDITOR, label: 'View & Edit' }, { value: roles.VIEWER, label: 'View Only' }, { value: null, label: 'None' } ]; public maxInheritedRole: Observable<roles.BasicRole|null> = observable(this.initData.maxInheritedRole || null); // The public member's access settings reflect either those of anonymous users (when // shouldSupportAnon() is true) or those of everyone@ (i.e. access granted to all users, // supported for docs only). The member is null when public access is not supported. public publicMember: IEditableMember|null = this._buildPublicMember(); public membersEdited = this.autoDispose(obsArray<IEditableMember>(this._buildAllMembers())); public isOrg: boolean = this.resourceType === 'organization'; // Checks if any members were added/removed/changed, if the max inherited role changed or if the // anonymous access setting changed to enable the confirm button to write changes to the server. public readonly isAnythingChanged: Computed<boolean> = this.autoDispose(computed<boolean>((use) => { const isMemberChangedFn = (m: IEditableMember) => m.isNew || m.isRemoved || use(m.access) !== m.origAccess; const isInheritanceChanged = !this.isOrg && use(this.maxInheritedRole) !== this.initData.maxInheritedRole; return some(use(this.membersEdited), isMemberChangedFn) || isInheritanceChanged || (this.publicMember ? isMemberChangedFn(this.publicMember) : false); })); constructor( public initData: PermissionData, public resourceType: ResourceType, private _activeUserEmail: string|null, private _docPageModel?: DocPageModel, ) { super(); } public reset(): void { this.membersEdited.set(this._buildAllMembers()); } public async save(userApi: UserAPI, resourceId: number|string): Promise<void> { if (this.resourceType === 'organization') { await userApi.updateOrgPermissions(resourceId as number, this.getDelta()); } else if (this.resourceType === 'workspace') { await userApi.updateWorkspacePermissions(resourceId as number, this.getDelta()); } else if (this.resourceType === 'document') { await userApi.updateDocPermissions(resourceId as string, this.getDelta()); } } public add(email: string, role: roles.Role|null): void { email = normalizeEmail(email); const members = this.membersEdited.get(); const index = members.findIndex((m) => m.email === email); const existing = index > -1 ? members[index] : null; if (existing && existing.isRemoved) { // The member is replaced with the isRemoved set to false to trigger an // update to the membersEdited observable array. this.membersEdited.splice(index, 1, {...existing, isRemoved: false}); } else if (existing) { const effective = existing.effectiveAccess.get(); if (effective && effective !== roles.GUEST) { // If the member is visible, throw to inform the user. throw new Error("This user is already in the list"); } // If the member exists but is not visible, update their access to make them visible. // They should be treated as a new user - removing them should make them invisible again. existing.access.set(role); existing.isNew = true; } else { const newMember = this._buildEditableMember({ id: -1, // Use a placeholder for the unknown userId email, name: "", access: role, parentAccess: null }); newMember.isNew = true; this.membersEdited.push(newMember); } } public remove(member: IEditableMember): void { const index = this.membersEdited.get().indexOf(member); if (member.isNew) { this.membersEdited.splice(index, 1); } else { // Keep it in the array with a flag, to simplify comparing "before" and "after" arrays. this.membersEdited.splice(index, 1, {...member, isRemoved: true}); } } public isActiveUser(member: IEditableMember): boolean { return member.email === this._activeUserEmail; } public getDelta(): PermissionDelta { // Construct the permission delta from the changed users/maxInheritedRole. const delta: PermissionDelta = { users: {} }; if (this.resourceType !== 'organization') { const maxInheritedRole = this.maxInheritedRole.get(); if (this.initData.maxInheritedRole !== maxInheritedRole) { delta.maxInheritedRole = maxInheritedRole; } } const members = [...this.membersEdited.get()]; if (this.publicMember) { members.push(this.publicMember); } // Loop through the members and update the delta. for (const m of members) { let access = m.access.get(); if (m === this.publicMember && access === roles.EDITOR && this._docPageModel?.gristDoc.get()?.hasGranularAccessRules()) { access = roles.VIEWER; reportWarning('Public "Editor" access is incompatible with Access Rules. Reduced to "Viewer".'); } if (!roles.isValidRole(access)) { throw new Error(`Cannot update user to invalid role ${access}`); } if (m.isNew || m.isRemoved || m.origAccess !== access) { // Add users whose access changed. delta.users![m.email] = m.isRemoved ? null : access as roles.NonGuestRole; } } return delta; } private _buildAllMembers(): IEditableMember[] { // If the UI supports some public access, strip the supported public user (anon@ or // everyone@). Otherwise, keep it, to allow the non-fancy way of adding/removing public access. let users = this.initData.users; const publicMember = this.publicMember; if (publicMember) { users = users.filter(m => m.email !== publicMember.email); } return users.map(m => this._buildEditableMember({ id: m.id, email: m.email, name: m.name, picture: m.picture, access: m.access, parentAccess: m.parentAccess || null, }) ); } private _buildPublicMember(): IEditableMember|null { // shouldSupportAnon() changes "public" access to "anonymous" access, and enables it for // workspaces and org level. It's currently used for on-premise installs only. // TODO Think through proper public sharing or workspaces/orgs, and get rid of // shouldSupportAnon() exceptions. const email = shouldSupportAnon() ? ANONYMOUS_USER_EMAIL : (this.resourceType === 'document') ? EVERYONE_EMAIL : null; if (!email) { return null; } const user = this.initData.users.find(m => m.email === email); return this._buildEditableMember({ id: user ? user.id : -1, email, name: "", access: user ? user.access : null, parentAccess: user ? (user.parentAccess || null) : null, }); } private _buildEditableMember(member: IBuildMemberOptions): IEditableMember { // Represents the member's access set specifically on the resource of interest. const access = Observable.create(this, member.access); let inheritedAccess: Computed<roles.BasicRole|null>; if (member.email === this._activeUserEmail) { // Note that we currently prevent the active user's role from changing to prevent users from // locking themselves out of resources. We ensure that by setting inheritedAccess to the // active user's initial access level, which is OWNER normally. (It's sometimes possible to // open UserManager by a less-privileged user, e.g. if access was just lowered, in which // case any attempted changes will fail on saving.) const initialAccessBasicRole = roles.getEffectiveRole(getRealAccess(member, this.initData)); // This pretends to be a computed to match the other case, but is really a constant. inheritedAccess = Computed.create(this, (use) => initialAccessBasicRole); } else { // Gives the role inherited from parent taking the maxInheritedRole into account. inheritedAccess = Computed.create(this, this.maxInheritedRole, (use, maxInherited) => roles.getWeakestRole(member.parentAccess, maxInherited)); } // Gives the effective role of the member on the resource, taking everything into account. const effectiveAccess = Computed.create(this, (use) => roles.getStrongestRole(use(access), use(inheritedAccess))); effectiveAccess.onWrite((value) => { // For UI simplicity, we use a single dropdown to represent the effective access level of // the user AND to allow changing it. As a result, we do NOT allow using the dropdown to // write/show values that provide less direct access than what the user already inherits. // It is confusing to show and results in no change in the effective access. const inherited = inheritedAccess.get(); const isAboveInherit = roles.getStrongestRole(value, inherited) !== inherited; access.set(isAboveInherit ? value : null); }); return { id: member.id, email: member.email, name: member.name, picture: member.picture, access, parentAccess: member.parentAccess || null, inheritedAccess, effectiveAccess, origAccess: member.access, isNew: false, isRemoved: false, }; } } export function getResourceParent(resource: ResourceType): ResourceType|null { if (resource === 'workspace') { return 'organization'; } else if (resource === 'document') { return 'workspace'; } else { return null; } } // Check whether anon should be supported in the UI export function shouldSupportAnon(): boolean { const gristConfig: GristLoadConfig = (window as any).gristConfig || {}; return gristConfig.supportAnon || false; }
the_stack
import * as service from '../service'; import { formState, getAddressForSymbol, getAddressAndAmountListForAccount, } from './testData.json'; import * as log from '../../../utils/electronLogger'; import { mockPersistentStore, mockAxios, } from '../../../utils/testUtils/mockUtils'; import * as Utility from '../../../utils/utility'; import { MAINNET } from '../../../constants'; const networkName = MAINNET.toLowerCase(); describe('liquidity page service unit test', () => { it('should check for handleGetPaymentRequest', () => { const PersistentStore = mockPersistentStore(null, null); // service.handleGetPaymentRequest(networkName); expect(true).toBe(true); }); // TODO : check // it.only('should return -(dash) if amount1 is not present', async() => { // const post = jest.fn() // .mockResolvedValue({data:getAddressAndAmountListForAccount}) // .mockResolvedValueOnce({data: getAddressForSymbol}) // .mockResolvedValueOnce({data: getAddressForSymbol}) // .mockResolvedValueOnce({data: {result:"12"}}); // mockAxios(post); // const result = await service.handleTestPoolSwapTo(formState); // console.log(result); // }); it('should check for error handleTestPoolSwapTo', async () => { const spy = jest.spyOn(log, 'error'); try { const post = jest .fn() .mockResolvedValueOnce({ data: getAddressForSymbol }) .mockResolvedValueOnce({ data: getAddressForSymbol }); mockAxios(post); const result = await service.handleTestPoolSwapTo(formState); } catch (err) { expect(err).toBeTruthy(); } }); it('should check for error handleTestPoolSwapFrom', async () => { const spy = jest.spyOn(log, 'error'); try { const post = jest .fn() .mockResolvedValueOnce({ data: getAddressForSymbol }) .mockResolvedValueOnce({ data: getAddressForSymbol }); mockAxios(post); const result = await service.handleTestPoolSwapFrom(formState); } catch (err) { expect(err).toBeTruthy(); } }); it('should check for error handlePoolSwap', async () => { const spy = jest.spyOn(log, 'error'); try { const post = jest .fn() .mockResolvedValueOnce({ data: getAddressForSymbol }) .mockResolvedValueOnce({ data: getAddressForSymbol }); mockAxios(post); const result = await service.handlePoolSwap(formState); } catch (err) { expect(err).toBeTruthy(); } }); // it('should check for ', async () => { // const PersistentStore = mockPersistentStore(null, null); // const data = await service.( // , // networkName // ); // console.log("data=================>", data) // expect(PersistentStore.get).toBeCalledTimes(1); // expect(data).toBeInstanceOf(Array); // expect(data).toEqual(expected.); // }); // it('should check for handleRemoveReceiveTxns', () => { // const PersistentStore = mockPersistentStore( // JSON.stringify(handleRemoveReceiveTxns.localStorageData), // null // ); // const data = service.handleRemoveReceiveTxns( // handleRemoveReceiveTxns.uuid, // networkName // ); // expect(PersistentStore.set).toBeCalledTimes(1); // expect(PersistentStore.get).toBeCalledTimes(1); // expect(data).toBeInstanceOf(Array); // expect(data).toEqual(expected.handleRemoveReceiveTxns); // }); // it('should check for handelFetchWalletTxns', async () => { // const post = jest // .fn() // .mockResolvedValueOnce({ // data: listtransaction, // }) // .mockResolvedValueOnce({ // data: walletInfo, // }); // mockAxios(post); // const test = await service.handelFetchWalletTxns(1, 0); // expect(test).toEqual(expected.handelFetchWalletTxns); // expect(post).toBeCalledTimes(2); // }); // it('should check for handleSendData', async () => { // const post = jest.fn().mockResolvedValueOnce({ // data: getBalance, // }); // mockAxios(post); // const test = await service.handleSendData(); // expect(test).toEqual(expected.handleSendData); // expect(post).toBeCalledTimes(1); // }); // it('should check for handleFetchWalletBalance', async () => { // const post = jest.fn().mockResolvedValueOnce({ // data: getBalance, // }); // mockAxios(post); // const test = await service.handleFetchWalletBalance(); // expect(test).toEqual(expected.handleFetchWalletBalance); // expect(post).toBeCalledTimes(1); // }); // it('should check for handleFetchPendingBalance', async () => { // const post = jest.fn().mockResolvedValueOnce({ // data: getBalances, // }); // mockAxios(post); // const test = await service.handleFetchPendingBalance(); // expect(test).toEqual(expected.handleFetchPendingBalance); // expect(post).toBeCalledTimes(1); // }); // it('should check for isValidAddress', async () => { // const post = jest.fn().mockResolvedValueOnce({ // data: validateAddress, // }); // const param = 'bcrt1qw2grcyqu9jfdwgrggtpasq0vdtwvecty4vf4jk'; // mockAxios(post); // const test = await service.isValidAddress(param); // expect(test).toBeTruthy(); // expect(post).toBeCalledTimes(1); // }); // it('should check for sendToAddress if getTxnSize is 0', async () => { // const utilMock = jest.spyOn(Utility, 'getTxnSize').mockResolvedValueOnce(0); // const post = jest.fn().mockResolvedValueOnce({ // data: sendToAddress, // }); // const toAddress = 'bcrt1qw2grcyqu9jfdwgrggtpasq0vdtwvecty4vf4jk'; // const amount = 10; // mockAxios(post); // const test = await service.sendToAddress(toAddress, amount); // expect(test).toBe(expected.sendToAddress); // expect(post).toBeCalledTimes(1); // expect(utilMock).toBeCalledTimes(1); // }); // it('should check for getNewAddress', async () => { // const post = jest.fn().mockResolvedValueOnce({ // data: getNewAddress, // }); // const label = 'test'; // mockAxios(post); // const test = await service.getNewAddress(label, false); // expect(test).toBe(expected.getNewAddress); // expect(post).toBeCalledTimes(1); // }); // it('should check for error in getNewAddress', async () => { // try { // const post = jest // .fn() // .mockImplementationOnce(() => Promise.reject('Error')); // const label = 'test'; // mockAxios(post); // const test = await service.getNewAddress(label, false); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check for error if invalid data is comming from getNewAddress', async () => { // const spy = jest.spyOn(log, 'error'); // const testData = Object.assign({}, getNewAddress); // delete testData.result; // try { // const post = jest.fn().mockResolvedValueOnce({ // data: testData, // }); // const label = 'test'; // mockAxios(post); // const test = await service.getNewAddress(label, false); // } catch (err) { // expect(spy).toBeCalled(); // expect(err).toBeTruthy(); // } // }); // it('should check for error sendToAddress', async () => { // try { // const post = jest.fn().mockRejectedValueOnce('Error'); // const toAddress = 'bcrt1qw2grcyqu9jfdwgrggtpasq0vdtwvecty4vf4jk'; // const amount = 10; // mockAxios(post); // const test = await service.sendToAddress(toAddress, amount); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check for error isValidAddress', async () => { // try { // const post = jest.fn().mockRejectedValueOnce('Error'); // const param = 'bcrt1qw2grcyqu9jfdwgrggtpasq0vdtwvecty4vf4jk'; // mockAxios(post); // const test = await service.isValidAddress(param); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check for error handleFetchPendingBalance', async () => { // const spy = jest.spyOn(log, 'error'); // const testBalancesData = Object.assign({}, getBalances); // delete testBalancesData.result.mine.immature; // try { // const post = jest.fn().mockResolvedValueOnce({ // data: testBalancesData, // }); // mockAxios(post); // const test = await service.handleFetchPendingBalance(); // } catch (err) { // expect(spy).toBeCalled(); // expect(err).toBeTruthy(); // } // }); // it('should check for error handleFetchWalletBalance', async () => { // const testBalance = Object.assign({}, getBalance); // delete testBalance.result; // const spy = jest.spyOn(log, 'error'); // try { // const post = jest.fn().mockResolvedValueOnce({ // data: { error: null, id: 'curltest' }, // }); // mockAxios(post); // const test = await service.handleFetchWalletBalance(); // } catch (err) { // expect(spy).toBeCalled(); // expect(err).toBeTruthy(); // } // }); // it('should check for error handleFetchWalletBalance', async () => { // try { // const post = jest.fn().mockRejectedValueOnce('error'); // mockAxios(post); // const test = await service.handleFetchWalletBalance(); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check if list of transaction is throwing error handelFetchWalletTxns', async () => { // try { // const post = jest // .fn() // .mockRejectedValueOnce('Error') // .mockResolvedValueOnce({ // data: walletInfo, // }); // mockAxios(post); // const test = await service.handelFetchWalletTxns(1, 0); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check if get balance is throwing error handelFetchWalletTxns', async () => { // try { // const post = jest // .fn() // .mockResolvedValueOnce({ // data: listtransaction, // }) // .mockRejectedValueOnce('Error'); // mockAxios(post); // const test = await service.handelFetchWalletTxns(1, 0); // } catch (err) { // expect(err).toBeTruthy(); // } // }); // it('should check if list data is not valid is throwing error handelFetchWalletTxns', async () => { // const spy = jest.spyOn(log, 'error'); // const testListTransaction = Object.assign({}, listtransaction); // delete testListTransaction.result[0].address; // try { // const post = jest // .fn() // .mockResolvedValueOnce({ // data: testListTransaction, // }) // .mockResolvedValueOnce({ // data: walletInfo, // }); // mockAxios(post); // const test = await service.handelFetchWalletTxns(1, 0); // } catch (err) { // expect(spy).toBeCalled(); // expect(err).toBeTruthy(); // } // }); // it('should check if get wallet data is not valid is throwing error handelFetchWalletTxns', async () => { // const spy = jest.spyOn(log, 'error'); // const testWalletInfo = Object.assign({}, walletInfo); // delete testWalletInfo.result.balance; // try { // const post = jest // .fn() // .mockResolvedValueOnce({ // data: listtransaction, // }) // .mockResolvedValueOnce({ // data: testWalletInfo, // }); // mockAxios(post); // const test = await service.handelFetchWalletTxns(1, 0); // } catch (err) { // expect(spy).toBeCalled(); // expect(err).toBeTruthy(); // } // }); });
the_stack
import { Component, isComponentClass, isComponentInstance, isComponentClassOrInstance, isComponentValueTypeInstance, Attribute, ValueType, isArrayValueTypeInstance, AttributeSelector, createAttributeSelectorFromAttributes, attributeSelectorsAreEqual, mergeAttributeSelectors, removeFromAttributeSelector, traverseAttributeSelector, trimAttributeSelector, normalizeAttributeSelector, IdentifierDescriptor, IdentifierValue, method } from '@layr/component'; import {hasOwnProperty, isPrototypeOf, isPlainObject, getTypeOf, Constructor} from 'core-helpers'; import mapKeys from 'lodash/mapKeys'; import { StorableProperty, StorablePropertyOptions, isStorablePropertyInstance, StorableAttribute, StorableAttributeOptions, isStorableAttributeInstance, StorablePrimaryIdentifierAttribute, StorableSecondaryIdentifierAttribute, StorableAttributeHookName, StorableMethod, StorableMethodOptions, isStorableMethodInstance } from './properties'; import {Index, IndexAttributes, IndexOptions} from './index-class'; import type {Query} from './query'; import type {StoreLike} from './store-like'; import { isStorableInstance, isStorableClassOrInstance, ensureStorableClass, isStorable } from './utilities'; export type SortDescriptor = {[name: string]: SortDirection}; export type SortDirection = 'asc' | 'desc'; /** * Extends a [`Component`](https://layrjs.com/docs/v2/reference/component) class with some storage capabilities. * * #### Usage * * The `Storable()` mixin can be used both in the backend and the frontend. * * ##### Backend Usage * * Call `Storable()` with a [`Component`](https://layrjs.com/docs/v2/reference/component) class to construct a [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) class that you can extend with your data model and business logic. Then, register this class into a store such as [`MongoDBStore`](https://layrjs.com/docs/v2/reference/mongodb-store) by using the [`registerStorable()`](https://layrjs.com/docs/v2/reference/store#register-storable-instance-method) method (or [`registerRootComponent()`](https://layrjs.com/docs/v2/reference/store#register-root-component-instance-method) to register several components at once). * * **Example:** * * ```js * // JS * * import {Component} from '@layr/component'; * import {Storable, primaryIdentifier, attribute} from '@layr/storable'; * import {MongoDBStore} from '@layr/mongodb-store'; * * export class Movie extends Storable(Component) { * @primaryIdentifier() id; * * @attribute() title = ''; * } * * const store = new MongoDBStore('mongodb://user:pass@host:port/db'); * * store.registerStorable(Movie); * ``` * * ```ts * // TS * * import {Component} from '@layr/component'; * import {Storable, primaryIdentifier, attribute} from '@layr/storable'; * import {MongoDBStore} from '@layr/mongodb-store'; * * export class Movie extends Storable(Component) { * @primaryIdentifier() id!: string; * * @attribute() title = ''; * } * * const store = new MongoDBStore('mongodb://user:pass@host:port/db'); * * store.registerStorable(Movie); * ``` * * Once you have a storable component registered into a store, you can use any method provided by the `Storable()` mixin to interact with the database: * * ``` * const movie = new Movie({id: 'abc123', title: 'Inception'}); * * // Save the movie to the database * await movie.save(); * * // Retrieve the movie from the database * await Movie.get('abc123'); // => movie * ``` * * ##### Frontend Usage * * Typically, you construct a storable component in the frontend by "inheriting" a storable component exposed by the backend. To accomplish that, you create a [`ComponentHTTPClient`](https://layrjs.com/docs/v2/reference/component-http-client), and then call the [`getComponent()`](https://layrjs.com/docs/v2/reference/component-http-client#get-component-instance-method) method to construct your frontend component. * * **Example:** * * ``` * import {ComponentHTTPClient} from '@layr/component-http-client'; * import {Storable} from '@layr/storable'; * * (async () => { * const client = new ComponentHTTPClient('https://...', { * mixins: [Storable] * }); * * const Movie = await client.getComponent(); * })(); * ``` * * > Note that you have to pass the `Storable` mixin when you create a `ComponentHTTPClient` that is consuming a storable component. * * Once you have a storable component in the frontend, you can use any method that is exposed by the backend. For example, if the `Movie`'s [`save()`](https://layrjs.com/docs/v2/reference/storable#save-instance-method) method is exposed by the backend, you can call it from the frontend to add a new movie into the database: * * ``` * const movie = new Movie({title: 'Inception 2'}); * * await movie.save(); * ``` * * See the ["Storing Data"](https://layrjs.com/docs/v2/introduction/data-storage) guide for a comprehensive example using the `Storable()` mixin. * * ### StorableComponent <badge type="primary">class</badge> {#storable-component-class} * * *Inherits from [`Component`](https://layrjs.com/docs/v2/reference/component).* * * A `StorableComponent` class is constructed by calling the `Storable()` mixin ([see above](https://layrjs.com/docs/v2/reference/storable#storable-mixin)). * * @mixin */ export function Storable<T extends Constructor<typeof Component>>(Base: T) { if (!isComponentClass(Base)) { throw new Error( `The Storable mixin should be applied on a component class (received type: '${getTypeOf( Base )}')` ); } if (typeof (Base as any).isStorable === 'function') { return Base as T & typeof Storable; } class Storable extends Base { ['constructor']: typeof StorableComponent; // === Component Methods === /** * See the methods that are inherited from the [`Component`](https://layrjs.com/docs/v2/reference/component#creation) class. * * @category Component Methods */ // === Store registration === static __store: StoreLike | undefined; /** * Returns the store in which the storable component is registered. If the storable component is not registered in a store, an error is thrown. * * @returns A [`Store`](https://layrjs.com/docs/v2/reference/store) instance. * * @example * ``` * Movie.getStore(); // => store * ``` * * @category Store Registration */ static getStore() { const store = this.__store; if (store === undefined) { throw new Error( `Cannot get the store of a storable component that is not registered (${this.describeComponent()})` ); } return store; } /** * Returns whether the storable component is registered in a store. * * @returns A boolean. * * @example * ``` * Movie.hasStore(); // => true * ``` * * @category Store Registration */ static hasStore() { return this.__store !== undefined; } static __setStore(store: StoreLike) { Object.defineProperty(this, '__store', {value: store}); } // === Storable properties === static getPropertyClass(type: string) { if (type === 'StorableAttribute') { return StorableAttribute; } if (type === 'StorablePrimaryIdentifierAttribute') { return StorablePrimaryIdentifierAttribute; } if (type === 'StorableSecondaryIdentifierAttribute') { return StorableSecondaryIdentifierAttribute; } if (type === 'StorableMethod') { return StorableMethod; } return super.getPropertyClass(type); } static get getStorableProperty() { return this.prototype.getStorableProperty; } getStorableProperty(name: string, options: {autoFork?: boolean} = {}) { const {autoFork = true} = options; const property = this.__getStorableProperty(name, {autoFork}); if (property === undefined) { throw new Error(`The storable property '${name}' is missing (${this.describeComponent()})`); } return property; } static get hasStorableProperty() { return this.prototype.hasStorableProperty; } hasStorableProperty(name: string) { return this.__getStorableProperty(name, {autoFork: false}) !== undefined; } static get __getStorableProperty() { return this.prototype.__getStorableProperty; } __getStorableProperty(name: string, options: {autoFork: boolean}) { const {autoFork} = options; const property = this.__getProperty(name, {autoFork}); if (property === undefined) { return undefined; } if (!isStorablePropertyInstance(property)) { throw new Error( `A property with the specified name was found, but it is not a storable property (${property.describe()})` ); } return property; } static get setStorableProperty() { return this.prototype.setStorableProperty; } setStorableProperty(name: string, propertyOptions: StorablePropertyOptions = {}) { return this.setProperty(name, StorableProperty, propertyOptions); } getStorablePropertiesWithFinder() { return this.getProperties<StorableProperty>({ filter: (property) => isStorablePropertyInstance(property) && property.hasFinder() }); } // === Storable attributes === static get getStorableAttribute() { return this.prototype.getStorableAttribute; } getStorableAttribute(name: string, options: {autoFork?: boolean} = {}) { const {autoFork = true} = options; const attribute = this.__getStorableAttribute(name, {autoFork}); if (attribute === undefined) { throw new Error( `The storable attribute '${name}' is missing (${this.describeComponent()})` ); } return attribute; } static get hasStorableAttribute() { return this.prototype.hasStorableAttribute; } hasStorableAttribute(name: string) { return this.__getStorableAttribute(name, {autoFork: false}) !== undefined; } static get __getStorableAttribute() { return this.prototype.__getStorableAttribute; } __getStorableAttribute(name: string, options: {autoFork: boolean}) { const {autoFork} = options; const property = this.__getProperty(name, {autoFork}); if (property === undefined) { return undefined; } if (!isStorableAttributeInstance(property)) { throw new Error( `A property with the specified name was found, but it is not a storable attribute (${property.describe()})` ); } return property; } static get setStorableAttribute() { return this.prototype.setStorableAttribute; } setStorableAttribute(name: string, attributeOptions: StorableAttributeOptions = {}) { return this.setProperty(name, StorableAttribute, attributeOptions); } getStorableAttributesWithLoader( options: {attributeSelector?: AttributeSelector; setAttributesOnly?: boolean} = {} ) { const {attributeSelector = true, setAttributesOnly = false} = options; return this.getAttributes<StorableAttribute>({ filter: (attribute) => isStorableAttributeInstance(attribute) && attribute.hasLoader(), attributeSelector, setAttributesOnly }); } getStorableComputedAttributes( options: {attributeSelector?: AttributeSelector; setAttributesOnly?: boolean} = {} ) { const {attributeSelector = true, setAttributesOnly = false} = options; return this.getAttributes<StorableAttribute>({ filter: (attribute) => isStorableAttributeInstance(attribute) && attribute.isComputed(), attributeSelector, setAttributesOnly }); } getStorableAttributesWithHook( name: StorableAttributeHookName, options: {attributeSelector?: AttributeSelector; setAttributesOnly?: boolean} = {} ) { const {attributeSelector = true, setAttributesOnly = false} = options; return this.getAttributes<StorableAttribute>({ filter: (attribute) => isStorableAttributeInstance(attribute) && attribute.hasHook(name), attributeSelector, setAttributesOnly }); } async __callStorableAttributeHooks( name: StorableAttributeHookName, { attributeSelector, setAttributesOnly }: {attributeSelector: AttributeSelector; setAttributesOnly?: boolean} ) { for (const attribute of this.getStorableAttributesWithHook(name, { attributeSelector, setAttributesOnly })) { await attribute.callHook(name); } } // === Indexes === getIndex(attributes: IndexAttributes, options: {autoFork?: boolean} = {}) { const {autoFork = true} = options; const index = this.__getIndex(attributes, {autoFork}); if (index === undefined) { throw new Error( `The index \`${JSON.stringify(attributes)}\` is missing (${this.describeComponent()})` ); } return index; } hasIndex(attributes: IndexAttributes) { return this.__getIndex(attributes, {autoFork: false}) !== undefined; } __getIndex(attributes: IndexAttributes, options: {autoFork: boolean}) { const {autoFork} = options; const indexes = this.__getIndexes(); const key = Index._buildIndexKey(attributes); let index = indexes[key]; if (index === undefined) { return undefined; } if (autoFork && index.getParent() !== this) { index = index.fork(this); indexes[key] = index; } return index; } setIndex(attributes: IndexAttributes, options: IndexOptions = {}): Index { let index = this.hasIndex(attributes) ? this.getIndex(attributes) : undefined; if (index === undefined) { index = new Index(attributes, this, options); const indexes = this.__getIndexes(); const key = Index._buildIndexKey(attributes); indexes[key] = index; } else { index.setOptions(options); } return index; } deleteIndex(attributes: IndexAttributes) { const indexes = this.__getIndexes(); const key = Index._buildIndexKey(attributes); if (!hasOwnProperty(indexes, key)) { return false; } delete indexes[key]; return true; } getIndexes( options: { autoFork?: boolean; } = {} ) { const {autoFork = true} = options; const storable = this; return { *[Symbol.iterator]() { const indexes = storable.__getIndexes({autoCreateOrFork: false}); if (indexes !== undefined) { for (const key in indexes) { const attributes = indexes[key].getAttributes(); const index = storable.getIndex(attributes, {autoFork}); yield index; } } } }; } __indexes?: {[name: string]: Index}; __getIndexes({autoCreateOrFork = true} = {}) { if (autoCreateOrFork) { if (!('__indexes' in this)) { Object.defineProperty(this, '__indexes', {value: Object.create(null)}); } else if (!hasOwnProperty(this, '__indexes')) { Object.defineProperty(this, '__indexes', {value: Object.create(this.__indexes!)}); } } return this.__indexes!; } // === Storable methods === static get getStorableMethod() { return this.prototype.getStorableMethod; } getStorableMethod(name: string, options: {autoFork?: boolean} = {}) { const {autoFork = true} = options; const method = this.__getStorableMethod(name, {autoFork}); if (method === undefined) { throw new Error(`The storable method '${name}' is missing (${this.describeComponent()})`); } return method; } static get hasStorableMethod() { return this.prototype.hasStorableMethod; } hasStorableMethod(name: string) { return this.__getStorableMethod(name, {autoFork: false}) !== undefined; } static get __getStorableMethod() { return this.prototype.__getStorableMethod; } __getStorableMethod(name: string, options: {autoFork: boolean}) { const {autoFork} = options; const property = this.__getProperty(name, {autoFork}); if (property === undefined) { return undefined; } if (!isStorableMethodInstance(property)) { throw new Error( `A property with the specified name was found, but it is not a storable method (${property.describe()})` ); } return property; } static get setStorableMethod() { return this.prototype.setStorableMethod; } setStorableMethod(name: string, methodOptions: StorableMethodOptions = {}) { return this.setProperty(name, StorableMethod, methodOptions); } // === Operations === /** * Retrieves a storable component instance (and possibly, some of its referenced components) from the store. * * > This method uses the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method) method under the hood to load the component's attributes. So if you want to expose the [`get()`](https://layrjs.com/docs/v2/reference/storable#get-class-method) method to the frontend, you will typically have to expose the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method) method as well. * * @param identifier A plain object specifying the identifier of the component you want to retrieve. The shape of the object should be `{[identifierName]: identifierValue}`. Alternatively, you can specify a string or a number representing the value of a [`PrimaryIdentifierAttribute`](https://layrjs.com/docs/v2/reference/primary-identifier-attribute). * @param [attributeSelector] An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the attributes to be loaded (default: `true`, which means that all the attributes will be loaded). * @param [options.reload] A boolean specifying whether a component that has already been loaded should be loaded again from the store (default: `false`). Most of the time you will leave this option off to take advantage of the cache. * @param [options.throwIfMissing] A boolean specifying whether an error should be thrown if there is no component matching the specified `identifier` in the store (default: `true`). * * @returns A [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) instance. * * @example * ``` * // Fully retrieve a movie by its primary identifier * await Movie.get({id: 'abc123'}); * // Same as above, but in a short manner * await Movie.get('abc123'); * * // Fully retrieve a movie by its secondary identifier * await Movie.get({slug: 'inception'}); * * // Partially retrieve a movie by its primary identifier * await Movie.get({id: 'abc123'}, {title: true, rating: true}); * * // Partially retrieve a movie, and fully retrieve its referenced director component * await Movie.get({id: 'abc123'}, {title: true, director: true}); * * // Partially retrieve a movie, and partially retrieve its referenced director component * await Movie.get({id: 'abc123'}, {title: true, director: {fullName: true}}); * ``` * * @category Storage Operations */ static async get<T extends typeof StorableComponent>( this: T, identifierDescriptor: IdentifierDescriptor, attributeSelector: AttributeSelector | undefined, options: {reload?: boolean; throwIfMissing: false; _callerMethodName?: string} ): Promise<InstanceType<T> | undefined>; static async get<T extends typeof StorableComponent>( this: T, identifierDescriptor: IdentifierDescriptor, attributeSelector?: AttributeSelector, options?: {reload?: boolean; throwIfMissing?: boolean; _callerMethodName?: string} ): Promise<InstanceType<T>>; @method() static async get<T extends typeof StorableComponent>( this: T, identifierDescriptor: IdentifierDescriptor, attributeSelector: AttributeSelector = true, options: {reload?: boolean; throwIfMissing?: boolean; _callerMethodName?: string} = {} ) { identifierDescriptor = this.normalizeIdentifierDescriptor(identifierDescriptor); attributeSelector = normalizeAttributeSelector(attributeSelector); const {reload = false, throwIfMissing = true, _callerMethodName} = options; let storable = this.getIdentityMap().getComponent(identifierDescriptor) as | InstanceType<T> | undefined; const hasPrimaryIdentifier = storable?.getPrimaryIdentifierAttribute().isSet() || this.prototype.getPrimaryIdentifierAttribute().getName() in identifierDescriptor; if (!hasPrimaryIdentifier) { if (this.hasStore()) { // Nothing to do, the storable will be loaded by load() } else if (this.hasRemoteMethod('get')) { // Let's fetch the primary identifier storable = await this.callRemoteMethod( 'get', identifierDescriptor, {}, { reload, throwIfMissing } ); if (storable === undefined) { return; } } else { throw new Error( `To be able to execute the get() method${describeCaller( _callerMethodName )} with a secondary identifier, a storable component should be registered in a store or have an exposed get() remote method (${this.describeComponent()})` ); } } let storableHasBeenCreated = false; if (storable === undefined) { storable = this.instantiate(identifierDescriptor); storableHasBeenCreated = true; } const loadedStorable = await storable.load(attributeSelector, { reload, throwIfMissing, _callerMethodName: _callerMethodName ?? 'get' }); if (loadedStorable === undefined && storableHasBeenCreated && storable.isAttached()) { storable.detach(); } return loadedStorable; } /** * Returns whether a storable component instance exists in the store. * * @param identifier A plain object specifying the identifier of the component you want to search. The shape of the object should be `{[identifierName]: identifierValue}`. Alternatively, you can specify a string or a number representing the value of a [`PrimaryIdentifierAttribute`](https://layrjs.com/docs/v2/reference/primary-identifier-attribute). * @param [options.reload] A boolean specifying whether a component that has already been loaded should be searched again from the store (default: `false`). Most of the time you will leave this option off to take advantage of the cache. * * @returns A boolean. * * @example * ``` * // Check if there is a movie with a certain primary identifier * await Movie.has({id: 'abc123'}); // => true * * // Same as above, but in a short manner * await Movie.has('abc123'); // => true * * // Check if there is a movie with a certain secondary identifier * await Movie.has({slug: 'inception'}); // => true * ``` * * @category Storage Operations */ static async has(identifierDescriptor: IdentifierDescriptor, options: {reload?: boolean} = {}) { const {reload = false} = options; const storable: StorableComponent | undefined = await this.get( identifierDescriptor, {}, {reload, throwIfMissing: false, _callerMethodName: 'has'} ); return storable !== undefined; } /** * Loads some attributes of the current storable component instance (and possibly, some of its referenced components) from the store. * * @param [attributeSelector] An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the attributes to be loaded (default: `true`, which means that all the attributes will be loaded). * @param [options.reload] A boolean specifying whether a component that has already been loaded should be loaded again from the store (default: `false`). Most of the time you will leave this option off to take advantage of the cache. * @param [options.throwIfMissing] A boolean specifying whether an error should be thrown if there is no matching component in the store (default: `true`). * * @returns The current [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) instance. * * @example * ``` * // Retrieve a movie with the 'title' attribute only * const movie = await Movie.get('abc123', {title: true}); * * // Load a few more movie's attributes * await movie.load({tags: true, rating: true}); * * // Load some attributes of the movie's director * await movie.load({director: {fullName: true}}); * * // Since the movie's rating has already been loaded, * // it will not be loaded again from the store * await movie.load({rating: true}); * * // Change the movie's rating * movie.rating = 8.5; * * // Since the movie's rating has been modified, * // it will be loaded again from the store * await movie.load({rating: true}); * * // Force reloading the movie's rating * await movie.load({rating: true}, {reload: true}); * ``` * * @category Storage Operations */ async load<T extends StorableComponent>( this: T, attributeSelector: AttributeSelector | undefined, options: {reload?: boolean; throwIfMissing: false; _callerMethodName?: string} ): Promise<T | undefined>; async load<T extends StorableComponent>( this: T, attributeSelector?: AttributeSelector, options?: {reload?: boolean; throwIfMissing?: boolean; _callerMethodName?: string} ): Promise<T>; @method() async load<T extends StorableComponent>( this: T, attributeSelector: AttributeSelector = true, options: {reload?: boolean; throwIfMissing?: boolean; _callerMethodName?: string} = {} ) { const {reload = false, throwIfMissing = true, _callerMethodName} = options; if (this.isNew()) { throw new Error( `Cannot load a storable component that is marked as new (${this.describeComponent()})` ); } let resolvedAttributeSelector = this.resolveAttributeSelector(attributeSelector); if (!reload) { const alreadyLoadedAttributeSelector = this.resolveAttributeSelector( resolvedAttributeSelector, { filter: (attribute: Attribute) => attribute.getValueSource() === 'server' || attribute.getValueSource() === 'store', setAttributesOnly: true, aggregationMode: 'intersection' } ); resolvedAttributeSelector = removeFromAttributeSelector( resolvedAttributeSelector, alreadyLoadedAttributeSelector ); } const computedAttributes = this.getStorableComputedAttributes({ attributeSelector: resolvedAttributeSelector }); let nonComputedAttributeSelector = removeFromAttributeSelector( resolvedAttributeSelector, createAttributeSelectorFromAttributes(computedAttributes) ); nonComputedAttributeSelector = trimAttributeSelector(nonComputedAttributeSelector); let loadedStorable: T | undefined; if (nonComputedAttributeSelector !== false) { await this.beforeLoad(nonComputedAttributeSelector); const constructor = this.constructor as typeof StorableComponent; if (constructor.hasStore()) { loadedStorable = (await constructor.getStore().load(this, { attributeSelector: nonComputedAttributeSelector, throwIfMissing })) as T; } else if (this.hasRemoteMethod('load')) { if (this.getPrimaryIdentifierAttribute().isSet()) { loadedStorable = await this.callRemoteMethod('load', nonComputedAttributeSelector, { reload, throwIfMissing }); } else if (this.constructor.hasRemoteMethod('get')) { loadedStorable = await this.constructor.callRemoteMethod( 'get', this.getIdentifierDescriptor(), nonComputedAttributeSelector, { reload, throwIfMissing } ); } else { throw new Error( `To be able to execute the load() method${describeCaller( _callerMethodName )} when no primary identifier is set, a storable component should be registered in a store or have an exposed get() remote method (${this.constructor.describeComponent()})` ); } } else { throw new Error( `To be able to execute the load() method${describeCaller( _callerMethodName )}, a storable component should be registered in a store or have an exposed load() remote method (${this.describeComponent()})` ); } if (loadedStorable === undefined) { return undefined; } await loadedStorable.afterLoad(nonComputedAttributeSelector); } else { loadedStorable = this; // OPTIMIZATION: There was nothing to load } for (const attribute of loadedStorable.getStorableAttributesWithLoader({ attributeSelector: resolvedAttributeSelector })) { const value = await attribute.callLoader(); attribute.setValue(value, {source: 'store'}); } await loadedStorable.__populate(attributeSelector, { reload, throwIfMissing, _callerMethodName }); return loadedStorable; } async __populate( attributeSelector: AttributeSelector, { reload, throwIfMissing, _callerMethodName }: {reload: boolean; throwIfMissing: boolean; _callerMethodName: string | undefined} ) { const resolvedAttributeSelector = this.resolveAttributeSelector(attributeSelector, { includeReferencedComponents: true }); const storablesWithAttributeSelectors = new Map< typeof StorableComponent | StorableComponent, AttributeSelector >(); traverseAttributeSelector( this, resolvedAttributeSelector, (componentOrObject, subattributeSelector) => { if ( isStorableClassOrInstance(componentOrObject) && !ensureStorableClass(componentOrObject).isEmbedded() ) { const storable = componentOrObject; if (!storablesWithAttributeSelectors.has(storable)) { storablesWithAttributeSelectors.set(storable, subattributeSelector); } else { const mergedAttributeSelector = mergeAttributeSelectors( storablesWithAttributeSelectors.get(storable)!, subattributeSelector ); storablesWithAttributeSelectors.set(storable, mergedAttributeSelector); } } }, {includeSubtrees: true, includeLeafs: false} ); if (storablesWithAttributeSelectors.size > 0) { await Promise.all( Array.from(storablesWithAttributeSelectors).map( ([storable, attributeSelector]) => isStorableInstance(storable) ? storable.load(attributeSelector, {reload, throwIfMissing, _callerMethodName}) : undefined // TODO: Implement class loading ) ); } } /** * Saves the current storable component instance to the store. If the component is new, it will be added to the store with all its attributes. Otherwise, only the attributes that have been modified will be saved to the store. * * @param [attributeSelector] An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the attributes to be saved (default: `true`, which means that all the modified attributes will be saved). * @param [options.throwIfMissing] A boolean specifying whether an error should be thrown if the current component is not new and there is no existing component with the same identifier in the store (default: `true` if the component is not new). * @param [options.throwIfExists] A boolean specifying whether an error should be thrown if the current component is new and there is an existing component with the same identifier in the store (default: `true` if the component is new). * * @returns The current [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) instance. * * @example * ``` * // Retrieve a movie with a few attributes * const movie = await Movie.get('abc123', {title: true, rating: true}); * * // Change the movie's rating * movie.rating = 8; * * // Save the new movie's rating to the store * await movie.save(); * * // Since the movie's rating has not been changed since the previous save(), * // it will not be saved again * await movie.save(); * ``` * * @category Storage Operations */ async save<T extends StorableComponent>( this: T, attributeSelector: AttributeSelector | undefined, options: {throwIfMissing: false; throwIfExists?: boolean} ): Promise<T | undefined>; async save<T extends StorableComponent>( this: T, attributeSelector: AttributeSelector | undefined, options: {throwIfMissing?: boolean; throwIfExists: false} ): Promise<T | undefined>; async save<T extends StorableComponent>( this: T, attributeSelector?: AttributeSelector, options?: {throwIfMissing?: boolean; throwIfExists?: boolean} ): Promise<T>; @method() async save<T extends StorableComponent>( this: T, attributeSelector: AttributeSelector = true, options: {throwIfMissing?: boolean; throwIfExists?: boolean} = {} ) { const isNew = this.isNew(); const {throwIfMissing = !isNew, throwIfExists = isNew} = options; if (throwIfMissing === true && throwIfExists === true) { throw new Error( "The 'throwIfMissing' and 'throwIfExists' options cannot be both set to true" ); } const computedAttributes = this.getStorableComputedAttributes(); const computedAttributeSelector = createAttributeSelectorFromAttributes(computedAttributes); let resolvedAttributeSelector = this.resolveAttributeSelector(attributeSelector, { setAttributesOnly: true, target: 'store', aggregationMode: 'intersection' }); resolvedAttributeSelector = removeFromAttributeSelector( resolvedAttributeSelector, computedAttributeSelector ); if (!isNew && Object.keys(resolvedAttributeSelector).length < 2) { return this; // OPTIMIZATION: There is nothing to save } await this.beforeSave(resolvedAttributeSelector); resolvedAttributeSelector = this.resolveAttributeSelector(attributeSelector, { setAttributesOnly: true, target: 'store', aggregationMode: 'intersection' }); resolvedAttributeSelector = removeFromAttributeSelector( resolvedAttributeSelector, computedAttributeSelector ); if (!isNew && Object.keys(resolvedAttributeSelector).length < 2) { return this; // OPTIMIZATION: There is nothing to save } let savedStorable: T | undefined; const constructor = this.constructor as typeof StorableComponent; if (constructor.hasStore()) { savedStorable = (await constructor.getStore().save(this, { attributeSelector: resolvedAttributeSelector, throwIfMissing, throwIfExists })) as T; } else if (this.hasRemoteMethod('save')) { savedStorable = await this.callRemoteMethod('save', attributeSelector, { throwIfMissing, throwIfExists }); } else { throw new Error( `To be able to execute the save() method, a storable component should be registered in a store or have an exposed save() remote method (${this.describeComponent()})` ); } if (savedStorable === undefined) { return undefined; } await savedStorable.afterSave(resolvedAttributeSelector); return savedStorable; } _assertArrayItemsAreFullyLoaded(attributeSelector: AttributeSelector) { traverseAttributeSelector( this, attributeSelector, (value, attributeSelector, {isArray}) => { if (isArray && isComponentInstance(value)) { const component = value; if (component.constructor.isEmbedded()) { if ( !attributeSelectorsAreEqual( component.resolveAttributeSelector(true), attributeSelector ) ) { throw new Error( `Cannot save an array item that has some unset attributes (${component.describeComponent()})` ); } } } }, {includeSubtrees: true, includeLeafs: false} ); } /** * Deletes the current storable component instance from the store. * * @param [options.throwIfMissing] A boolean specifying whether an error should be thrown if there is no matching component in the store (default: `true`). * * @returns The current [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) instance. * * @example * ``` * // Retrieve a movie * const movie = await Movie.get('abc123'); * * // Delete the movie * await movie.delete(); * ``` * * @category Storage Operations */ async delete<T extends StorableComponent>( this: T, options: {throwIfMissing: false} ): Promise<T | undefined>; async delete<T extends StorableComponent>( this: T, options?: {throwIfMissing?: boolean} ): Promise<T>; @method() async delete<T extends StorableComponent>( this: T, options: {throwIfMissing?: boolean} = {} ) { if (this.isNew()) { throw new Error( `Cannot delete a storable component that is new (${this.describeComponent()})` ); } const {throwIfMissing = true} = options; const attributeSelector = this.resolveAttributeSelector(true); const computedAttributes = this.getStorableComputedAttributes({attributeSelector}); const nonComputedAttributeSelector = removeFromAttributeSelector( attributeSelector, createAttributeSelectorFromAttributes(computedAttributes) ); await this.beforeDelete(nonComputedAttributeSelector); let deletedStorable: T | undefined; const constructor = this.constructor as typeof StorableComponent; if (constructor.hasStore()) { deletedStorable = (await constructor.getStore().delete(this, {throwIfMissing})) as T; } else if (this.hasRemoteMethod('delete')) { deletedStorable = await this.callRemoteMethod('delete', {throwIfMissing}); } else { throw new Error( `To be able to execute the delete() method, a storable component should be registered in a store or have an exposed delete() remote method (${this.describeComponent()})` ); } if (deletedStorable === undefined) { return undefined; } await deletedStorable.afterDelete(nonComputedAttributeSelector); deletedStorable.setIsDeletedMark(true); // TODO: deletedStorable.detach(); return deletedStorable; } /** * Finds some storable component instances matching the specified query in the store, and load all or some of their attributes (and possibly, load some of their referenced components as well). * * > This method uses the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method) method under the hood to load the components' attributes. So if you want to expose the [`find()`](https://layrjs.com/docs/v2/reference/storable#find-class-method) method to the frontend, you will typically have to expose the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method) method as well. * * @param [query] A [`Query`](https://layrjs.com/docs/v2/reference/query) object specifying the criteria to be used when selecting the components from the store (default: `{}`, which means that any component can be selected). * @param [attributeSelector] An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the attributes to be loaded (default: `true`, which means that all the attributes will be loaded). * @param [options.sort] A plain object specifying how the found components should be sorted (default: `undefined`). The shape of the object should be `{[name]: direction}` where `name` is the name of an attribute, and `direction` is the string `'asc'` or `'desc'` representing the sort direction (ascending or descending). * @param [options.skip] A number specifying how many components should be skipped from the found components (default: `0`). * @param [options.limit] A number specifying the maximum number of components that should be returned (default: `undefined`). * @param [options.reload] A boolean specifying whether a component that has already been loaded should be loaded again from the store (default: `false`). Most of the time you will leave this option off to take advantage of the cache. * * @returns An array of [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) instances. * * @example * ``` * // Find all the movies * await Movie.find(); * * // Find the Japanese movies * await Movie.find({country: 'Japan'}); * * // Find the Japanese drama movies * await Movie.find({country: 'Japan', genre: 'drama'}); * * // Find the Tarantino's movies * const tarantino = await Director.get({slug: 'quentin-tarantino'}); * await Movie.find({director: tarantino}); * * // Find the movies released after 2010 * await Movie.find({year: {$greaterThan: 2010}}); * * // Find the top 30 movies * await Movie.find({}, true, {sort: {rating: 'desc'}, limit: 30}); * * // Find the next top 30 movies * await Movie.find({}, true, {sort: {rating: 'desc'}, skip: 30, limit: 30}); * ``` * * @category Storage Operations */ @method() static async find<T extends typeof StorableComponent>( this: T, query: Query = {}, attributeSelector: AttributeSelector = true, options: {sort?: SortDescriptor; skip?: number; limit?: number; reload?: boolean} = {} ) { const {sort, skip, limit, reload = false} = options; query = await this.__callStorablePropertyFindersForQuery(query); query = this.__normalizeQuery(query, {loose: !this.hasStore()}); let foundStorables: InstanceType<T>[]; if (this.hasStore()) { foundStorables = (await this.getStore().find(this, query, { sort, skip, limit })) as InstanceType<T>[]; } else if (this.hasRemoteMethod('find')) { foundStorables = await this.callRemoteMethod('find', query, {}, {sort, skip, limit}); } else { throw new Error( `To be able to execute the find() method, a storable component should be registered in a store or have an exposed find() remote method (${this.describeComponent()})` ); } const loadedStorables = await Promise.all( foundStorables.map((foundStorable) => foundStorable.load(attributeSelector, {reload, _callerMethodName: 'find'}) ) ); return loadedStorables; } /** * Counts the number of storable component instances matching the specified query in the store. * * @param [query] A [`Query`](https://layrjs.com/docs/v2/reference/query) object specifying the criteria to be used when selecting the components from the store (default: `{}`, which means that any component can be selected, and therefore the total number of components available in the store will be returned). * * @returns A number. * * @example * ``` * // Count the total number of movies * await Movie.count(); * * // Count the number of Japanese movies * await Movie.count({country: 'Japan'}); * * // Count the number of Japanese drama movies * await Movie.count({country: 'Japan', genre: 'drama'}); * * // Count the number of Tarantino's movies * const tarantino = await Director.get({slug: 'quentin-tarantino'}) * await Movie.count({director: tarantino}); * * // Count the number of movies released after 2010 * await Movie.count({year: {$greaterThan: 2010}}); * ``` * * @category Storage Operations */ @method() static async count(query: Query = {}) { query = await this.__callStorablePropertyFindersForQuery(query); query = this.__normalizeQuery(query, {loose: !this.hasStore()}); let storablesCount: number; if (this.hasStore()) { storablesCount = await this.getStore().count(this, query); } else if (this.hasRemoteMethod('count')) { storablesCount = await this.callRemoteMethod('count', query); } else { throw new Error( `To be able to execute the count() method, a storable component should be registered in a store or have an exposed count() remote method (${this.describeComponent()})` ); } return storablesCount; } static async __callStorablePropertyFindersForQuery(query: Query) { for (const property of this.prototype.getStorablePropertiesWithFinder()) { const name = property.getName(); if (!hasOwnProperty(query, name)) { continue; // The property finder is not used in the query } const {[name]: value, ...remainingQuery} = query; const finderQuery = await property.callFinder(value); query = {...remainingQuery, ...finderQuery}; } return query; } static __normalizeQuery(query: Query, {loose = false}: {loose?: boolean} = {}) { const normalizeQueryForComponent = function ( query: Query | typeof Component | Component, component: typeof Component | Component ) { if (isComponentClassOrInstance(query)) { if (component === query || isPrototypeOf(component, query)) { return query.toObject({minimize: true}); } throw new Error( `An unexpected component was specified in a query (${component.describeComponent({ componentPrefix: 'expected' })}, ${query.describeComponent({componentPrefix: 'specified'})})` ); } if (!isPlainObject(query)) { throw new Error( `Expected a plain object in a query, but received a value of type '${getTypeOf(query)}'` ); } const normalizedQuery: Query = {}; for (const [name, subquery] of Object.entries<Query>(query)) { if (name === '$some' || name === '$every') { normalizedQuery[name] = normalizeQueryForComponent(subquery, component); continue; } if (name === '$length') { normalizedQuery[name] = subquery; continue; } if (name === '$not') { normalizedQuery[name] = normalizeQueryForComponent(subquery, component); continue; } if (name === '$and' || name === '$or' || name === '$nor') { if (!Array.isArray(subquery)) { throw new Error( `Expected an array as value of the operator '${name}', but received a value of type '${getTypeOf( subquery )}'` ); } const subqueries: Query[] = subquery; normalizedQuery[name] = subqueries.map((subquery) => normalizeQueryForComponent(subquery, component) ); continue; } if (name === '$in') { if (!Array.isArray(subquery)) { throw new Error( `Expected an array as value of the operator '${name}', but received a value of type '${getTypeOf( subquery )}'` ); } if (!isComponentInstance(component)) { throw new Error( `The operator '${name}' cannot be used in the context of a component class` ); } const nestedComponents: Component[] = subquery; const primaryIdentifiers: IdentifierValue[] = nestedComponents.map( (nestedComponent) => { if (!isComponentInstance(nestedComponent)) { throw new Error( `Expected an array of component instances as value of the operator '${name}', but received a value of type '${getTypeOf( nestedComponent )}'` ); } if (!isPrototypeOf(component, nestedComponent)) { throw new Error( `An unexpected item was specified for the operator '${name}' (${component.describeComponent( { componentPrefix: 'expected' } )}, ${nestedComponent.describeComponent({componentPrefix: 'specified'})})` ); } return nestedComponent.getPrimaryIdentifierAttribute().getValue()!; } ); const primaryIdentifierAttributeName = component .getPrimaryIdentifierAttribute() .getName(); normalizedQuery[primaryIdentifierAttributeName] = {[name]: primaryIdentifiers}; continue; } if (component.hasAttribute(name)) { const attribute = component.getAttribute(name); normalizedQuery[name] = normalizeQueryForAttribute(subquery, attribute); } else { if (!loose) { throw new Error( `An unknown attribute was specified in a query (${component.describeComponent()}, attribute: '${name}')` ); } normalizedQuery[name] = subquery; } } return normalizedQuery; }; const normalizeQueryForAttribute = function (query: Query, attribute: Attribute) { const type = attribute.getValueType(); return normalizeQueryForAttributeAndType(query, attribute, type); }; const normalizeQueryForAttributeAndType = function ( query: Query, attribute: Attribute, type: ValueType ): Query { if (isComponentValueTypeInstance(type)) { const component = type.getComponent(attribute); const normalizedQuery = normalizeQueryForComponent(query, component); return normalizedQuery; } if (isArrayValueTypeInstance(type)) { const itemType = type.getItemType(); let normalizedQuery = normalizeQueryForAttributeAndType(query, attribute, itemType); if (isPlainObject(normalizedQuery) && '$includes' in normalizedQuery) { // Make '$includes' an alias of '$some' normalizedQuery = mapKeys(normalizedQuery, (_value, key) => key === '$includes' ? '$some' : key ); } if ( !( isPlainObject(normalizedQuery) && ('$some' in normalizedQuery || '$every' in normalizedQuery || '$length' in normalizedQuery || '$not' in normalizedQuery) ) ) { // Make '$some' implicit normalizedQuery = {$some: normalizedQuery}; } return normalizedQuery; } return query; }; return normalizeQueryForComponent(query, this.prototype); } // === isDeleted Mark === __isDeleted: boolean | undefined; /** * Returns whether the component instance is marked as deleted or not. * * @returns A boolean. * * @example * ``` * movie.getIsDeletedMark(); // => false * await movie.delete(); * movie.getIsDeletedMark(); // => true * ``` * * @category isDeleted Mark */ getIsDeletedMark() { return this.__isDeleted === true; } /** * Sets whether the component instance is marked as deleted or not. * * @param isDeleted A boolean specifying if the component instance should be marked as deleted or not. * * @example * ``` * movie.getIsDeletedMark(); // => false * movie.setIsDeletedMark(true); * movie.getIsDeletedMark(); // => true * ``` * * @category isDeleted Mark */ setIsDeletedMark(isDeleted: boolean) { Object.defineProperty(this, '__isDeleted', {value: isDeleted, configurable: true}); } // === Hooks === /** * A method that you can override to execute some custom logic just before the current storable component instance is loaded from the store. * * This method is automatically called when the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method), [`get()`](https://layrjs.com/docs/v2/reference/storable#get-class-method), or [`find()`](https://layrjs.com/docs/v2/reference/storable#find-class-method) method is called, and there are some attributes to load. If all the attributes have already been loaded by a previous operation, unless the `reload` option is used, this method is not called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that will be loaded. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async beforeLoad(attributeSelector) { * // Don't forget to call the parent method * await super.beforeLoad(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async beforeLoad(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.beforeLoad(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async beforeLoad(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('beforeLoad', {attributeSelector}); } /** * A method that you can override to execute some custom logic just after the current storable component instance has been loaded from the store. * * This method is automatically called when the [`load()`](https://layrjs.com/docs/v2/reference/storable#load-instance-method), [`get()`](https://layrjs.com/docs/v2/reference/storable#get-class-method), or [`find()`](https://layrjs.com/docs/v2/reference/storable#find-class-method) method is called, and there were some attributes to load. If all the attributes have already been loaded by a previous operation, unless the `reload` option is used, this method is not called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that were loaded. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async afterLoad(attributeSelector) { * // Don't forget to call the parent method * await super.afterLoad(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async afterLoad(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.afterLoad(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async afterLoad(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('afterLoad', { attributeSelector, setAttributesOnly: true }); } /** * A method that you can override to execute some custom logic just before the current storable component instance is saved to the store. * * This method is automatically called when the [`save()`](https://layrjs.com/docs/v2/reference/storable#save-instance-method) method is called, and there are some modified attributes to save. If no attributes were modified, this method is not called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that will be saved. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async beforeSave(attributeSelector) { * // Don't forget to call the parent method * await super.beforeSave(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async beforeSave(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.beforeSave(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async beforeSave(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('beforeSave', { attributeSelector, setAttributesOnly: true }); } /** * A method that you can override to execute some custom logic just after the current storable component instance has been saved to the store. * * This method is automatically called when the [`save()`](https://layrjs.com/docs/v2/reference/storable#save-instance-method) method is called, and there were some modified attributes to save. If no attributes were modified, this method is not called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that were saved. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async afterSave(attributeSelector) { * // Don't forget to call the parent method * await super.afterSave(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async afterSave(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.afterSave(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async afterSave(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('afterSave', { attributeSelector, setAttributesOnly: true }); } /** * A method that you can override to execute some custom logic just before the current storable component instance is deleted from the store. * * This method is automatically called when the [`delete()`](https://layrjs.com/docs/v2/reference/storable#delete-instance-method) method is called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that will be deleted. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async beforeDelete(attributeSelector) { * // Don't forget to call the parent method * await super.beforeDelete(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async beforeDelete(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.beforeDelete(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async beforeDelete(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('beforeDelete', { attributeSelector, setAttributesOnly: true }); } /** * A method that you can override to execute some custom logic just after the current storable component instance has been deleted from the store. * * This method is automatically called when the [`delete()`](https://layrjs.com/docs/v2/reference/storable#delete-instance-method) method is called. * * @param attributeSelector An [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) indicating the attributes that were deleted. * * @example * ``` * // JS * * class Movie extends Storable(Component) { * // ... * * async afterDelete(attributeSelector) { * // Don't forget to call the parent method * await super.afterDelete(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @example * ``` * // TS * * class Movie extends Storable(Component) { * // ... * * async afterDelete(attributeSelector: AttributeSelector) { * // Don't forget to call the parent method * await super.afterDelete(attributeSelector); * * // Implement your custom logic here * } * } * ``` * * @category Hooks */ async afterDelete(attributeSelector: AttributeSelector) { await this.__callStorableAttributeHooks('afterDelete', { attributeSelector, setAttributesOnly: true }); } // === Observability === /** * See the methods that are inherited from the [`Observable`](https://layrjs.com/docs/v2/reference/observable#observable-class) class. * * @category Observability */ // === Utilities === static get isStorable() { return this.prototype.isStorable; } isStorable(value: any): value is typeof StorableComponent | StorableComponent { return isStorable(value); } } Object.defineProperty(Storable, '__mixin', {value: 'Storable'}); return Storable; } // Make sure the name of the Storable mixin persists over minification Object.defineProperty(Storable, 'displayName', {value: 'Storable'}); export class StorableComponent extends Storable(Component) {} function describeCaller(callerMethodName: string | undefined) { return callerMethodName !== undefined ? ` (called from ${callerMethodName}())` : ''; }
the_stack
import { create, DefaultMatchEngineOptions, DimensionType } from '../../../src'; import { RockPaperScissorsDesign } from '../../rps'; import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import chaiSubset from 'chai-subset'; import sinonChai from 'sinon-chai'; import sinon from 'sinon'; import 'mocha'; import { Logger, MatchEngine, Match, Agent, Design } from '../../../src'; import { deepCopy } from '../../../src/utils/DeepCopy'; import { stripFunctions } from '../utils/stripfunctions'; import { createCustomDesign } from '../utils/createCustomDesign'; import { AgentCompileTimeoutError, AgentInstallTimeoutError, } from '../../../src/DimensionError'; const expect = chai.expect; chai.should(); chai.use(sinonChai); chai.use(chaiAsPromised); chai.use(chaiSubset); describe('Testing MatchEngine Core', () => { let ddefault: DimensionType; let d: DimensionType; const paper = './tests/kits/js/normal/paper.js'; const rock = './tests/kits/js/normal/rock.js'; const bots = { python: './tests/kits/python/bot.py', js: './tests/kits/js/normal/paper.js', ts: './tests/kits/ts/bot.ts', java: './tests/kits/java/Bot.java', cpp: './tests/kits/cpp/bot.cpp', c: './tests/kits/c/bot.c', go: './tests/kits/go/bot.go', php: './tests/kits/php/bot.php', }; const botList = [rock, paper]; const jsWithSlowInstall = './tests/kits/js/withinstall/rock.js'; const lineCountBotList = [ './tests/kits/js/linecount/rock.js', './tests/kits/js/linecount/paper.js', ]; const twoLineCountBotList = [ './tests/kits/js/linecount/rock.2line.js', './tests/kits/js/linecount/paper.2line.js', ]; const changedOptions = { engineOptions: { timeout: { max: 10000, }, }, }; const rpsDesign = new RockPaperScissorsDesign('RPS'); const rpsDesignChanged = new RockPaperScissorsDesign( 'RPS changed', changedOptions ); const rpsDesignLineCount = new RockPaperScissorsDesign('RPS changed', { engineOptions: { commandFinishPolicy: MatchEngine.COMMAND_FINISH_POLICIES.LINE_COUNT, }, }); const tf = [true, false]; before(() => { ddefault = create(rpsDesign, { activateStation: false, observe: false, id: '123456', loggingLevel: Logger.LEVEL.NONE, defaultMatchConfigs: { storeErrorLogs: false, }, }); d = create(rpsDesignChanged, { activateStation: false, observe: false, id: '12345678', loggingLevel: Logger.LEVEL.NONE, defaultMatchConfigs: { storeErrorLogs: false, }, }); }); describe('Test configurations', () => { it('should be initialized with a match correctly when using defaults', async () => { // create match goes to as far as running initalize functions const match = await ddefault.createMatch(botList, { bestOf: 9, }); const deeped = stripFunctions(deepCopy(DefaultMatchEngineOptions)); expect(match.matchEngine.getEngineOptions()).to.containSubset(deeped); await match.destroy(); }); it('should be initialized with a match correctly when using overriden', async () => { // create match goes to as far as running initalize functions const match = await d.createMatch(botList, { bestOf: 9, }); const deeped = stripFunctions( deepCopy(rpsDesignChanged.getDesignOptions().engineOptions) ); expect(match.matchEngine.getEngineOptions()).to.containSubset(deeped); await match.destroy(); }); }); describe('Test initialization', async () => { let match: Match; before(async () => { match = await d.createMatch(botList, { bestOf: 9, }); }); it('should store relevant processes', () => { for (const agent of match.agents) { expect(agent._getProcess()).to.not.equal( null, 'process should be stored' ); expect(agent._getProcess().stdin.destroyed).to.equal( false, 'stdin should not be destroyed' ); expect(agent._getProcess().stdout.destroyed).to.equal( false, 'stdout should not be destroyed' ); expect(agent._getProcess().stderr.destroyed).to.equal( false, 'stderr should not be destroyed' ); } }); it('should store relevant memory watcher intervals', () => { for (const agent of match.agents) { expect(agent.memoryWatchInterval).to.not.equal( null, 'memory watch interval should be stored and active' ); } }); it('should store idToAgents map in match', () => { expect(match.idToAgentsMap.size).to.equal(2); for (const agent of match.agents) { expect(match.idToAgentsMap.get(agent.id)).to.equal(agent); } }); it('should initialize all agents as running', () => { for (const agent of match.agents) { expect(agent.status).to.equal(Agent.Status.RUNNING); } }); after(async () => { await match.destroy(); }); }); describe('Test running', () => { describe('Test FINISH_SYMBOL policy', () => { it('should handle commands when using the default FINISH_SYMBOL policy', async () => { const match = await d.createMatch(botList, { bestOf: 11, }); expect(match.matchEngine.getEngineOptions().commandStreamType).to.equal( MatchEngine.COMMAND_STREAM_TYPE.SEQUENTIAL ); expect( match.matchEngine.getEngineOptions().commandFinishPolicy ).to.equal(MatchEngine.COMMAND_FINISH_POLICIES.FINISH_SYMBOL); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 11 }); await match.destroy(); }); it('should erase extraneous output after finish symbol', async () => { const results = await d.runMatch( [ './tests/kits/js/normal/rock.withextra.js', './tests/kits/js/normal/paper.js', ], { name: 'erasure of output (1)', bestOf: 9, } ); // rock.withextra.js outputs an scissor afte ending turn, which if not erased would win game // expect paper to still win expect(results.scores).to.eql({ '0': 0, '1': 9 }); }); }); describe('Test LINE_COUNT policy ', () => { let d: DimensionType; before(() => { d = create(rpsDesignLineCount, { activateStation: false, observe: false, id: '1234linecount', loggingLevel: Logger.LEVEL.NONE, defaultMatchConfigs: { storeErrorLogs: false, }, }); }); const verifyLinecountSettings = (match: Match) => { expect(match.matchEngine.getEngineOptions().commandStreamType).to.equal( MatchEngine.COMMAND_STREAM_TYPE.SEQUENTIAL ); expect( match.matchEngine.getEngineOptions().commandFinishPolicy ).to.equal(MatchEngine.COMMAND_FINISH_POLICIES.LINE_COUNT); }; it('should handle commands when using the default configs', async () => { const match = await d.createMatch(lineCountBotList, { bestOf: 11, }); verifyLinecountSettings(match); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 11 }); await match.destroy(); }); it('should handle commands when setting max lines to more than 1', async () => { let match = await d.createMatch(twoLineCountBotList, { bestOf: 11, engineOptions: { commandLines: { max: 2, }, }, }); verifyLinecountSettings(match); let results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 11 }); // rock.extra.js sends a 2nd "S" after the "R", allowed by max 2, and thus wins this const extraOutputBotList = [ './tests/kits/js/linecount/rock.extra.js', './tests/kits/js/linecount/paper.2line.js', ]; match = await d.createMatch(extraOutputBotList, { bestOf: 11, engineOptions: { commandLines: { max: 2, }, }, }); verifyLinecountSettings(match); results = await match.run(); expect(results.scores).to.eql({ '0': 11, '1': 0 }); }); }); it.skip('should allow stderr output from agents', async () => { // TODO: fix this test const match = await d.createMatch( [ './tests/kits/js/normal/rock.withstderr.js', './tests/kits/js/normal/paper.js', ], { bestOf: 11, engineOptions: { noStdErr: false, }, } ); const sandbox = sinon.createSandbox(); const stderrSpy = sandbox.spy(match.matchEngine.getLogger(), 'custom'); const results = await match.run(); expect(stderrSpy).to.be.called('string'); expect(results.scores).to.eql({ '0': 0, '1': 11 }); }); it('should call matchEngine kill twice only for 2 agent matches', async () => { const match = await d.createMatch( ['./tests/kits/js/normal/rock.js', './tests/kits/js/normal/paper.js'], { bestOf: 9, } ); const sandbox = sinon.createSandbox(); const matchEngineKillSpy = sandbox.spy(match.matchEngine, 'kill'); await match.run(); expect(matchEngineKillSpy).to.callCount(2); }); describe('Testing engine processing of agent output commands', () => { // specifically tests line with `agent._buffer.push(strs[strs.length - 1]);` it('should allow for delayed newline characters and use the _buffer store in agent correctly', async () => { const match = await d.createMatch( [ './tests/kits/js/normal/rock.delaynewline.js', './tests/kits/js/normal/paper.delaynewline.js', ], { bestOf: 9, } ); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 9 }); }); it('should ignore extra newlines if newline was already sent', async () => { const match = await d.createMatch( [ './tests/kits/js/normal/rock.extranewlines.js', './tests/kits/js/normal/paper.delaynewline.js', ], { bestOf: 9, } ); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 9 }); }); }); describe(`Testing engine handling of agent 'close' event`, () => { it('should terminate the agent internally as well if agent prematurely exits', async () => { const match = await d.createMatch( ['./tests/kits/js/normal/rock.prematureexit.js', paper], { bestOf: 9, } ); const sandbox = sinon.createSandbox(); const matchEngineKillSpy = sandbox.spy(match.matchEngine, 'kill'); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 1 }); // 3 kill calls, one for premature termination and 2 are always called expect(matchEngineKillSpy).to.be.callCount(3); }); }); }); describe('Test secureMode', () => { it('should initialize correctly', async () => { const match = await d.createMatch(botList, { bestOf: 11, secureMode: true, }); for (const agent of match.agents) { expect(agent.options.secureMode).to.equal(true); } expect(match.configs.secureMode).to.equal(true); await match.destroy(); }); it('should run correctly', async () => { const match = await d.createMatch(botList, { bestOf: 11, secureMode: true, }); const results = await match.run(); expect(results.scores).to.eql({ '0': 0, '1': 11 }); await match.destroy(); }); }); describe('Test compilation step', () => { for (const bool of tf) { it(`should throw error for bot going over compile time limit and mark agent as crashed; secureMode: ${bool}`, async () => { const match = new Match( d.design, [bots.java, bots.js], { bestOf: 11, loggingLevel: 0, secureMode: bool, agentOptions: { maxCompileTime: 100, }, }, d ); await expect(match.initialize()).to.be.rejectedWith( AgentCompileTimeoutError ); expect(match.agents[0].status).to.equal(Agent.Status.CRASHED); expect(match.agents[1].status).to.equal(Agent.Status.KILLED); await match.destroy(); }); } }); describe('Test install step', () => { for (const bool of tf) { it(`should throw error for bot going over install time limit and mark agent as crashed; secureMode: ${bool}`, async () => { const match = new Match( d.design, [jsWithSlowInstall, bots.js], { bestOf: 11, loggingLevel: 0, secureMode: bool, agentOptions: { maxInstallTime: 100, }, }, d ); await expect(match.initialize()).to.be.rejectedWith( AgentInstallTimeoutError ); expect(match.agents[0].status).to.equal(Agent.Status.CRASHED); expect(match.agents[1].status).to.equal(Agent.Status.KILLED); await match.destroy(); }); } }); describe('Test custom designs', () => { let custom: Design; let d: DimensionType; before(() => { custom = createCustomDesign(); d = create(custom, { activateStation: false, observe: false, loggingLevel: Logger.LEVEL.NONE, defaultMatchConfigs: { storeErrorLogs: false, }, }); }); it('should initialize correctly', () => { // TODO }); it('should run correctly', async () => { const results = await d.runMatch(botList); expect(results).to.eql({ ranks: [ { agentID: 0, rank: 1 }, { agentID: 1, rank: 2 }, ], }); }); }); after(async () => { await d.cleanupMatches(); await ddefault.cleanupMatches(); }); });
the_stack
const portscanner = require('portscanner'); import * as fs from 'fs'; import * as path from 'path'; import * as vscode from 'vscode'; import * as crypto from 'crypto'; import * as killProcessTree from 'tree-kill'; import axios from 'axios'; import { spawn, spawnSync, ChildProcess } from 'child_process'; import * as CryptoJS from 'crypto-js'; import { ConnStringUtils } from "./ConnStringUtils"; import * as SharedConstants from './SharedConstants'; import { Settings } from './Settings'; // Responsible for running the backend process export class BackendProcess { constructor(private _binariesFolder: string, private _storageConnectionSettings: StorageConnectionSettings, private _removeMyselfFromList: () => void, private _log: (l: string) => void) { } // Underlying Storage Connection Strings get storageConnectionStrings(): string[] { return this._storageConnectionSettings.storageConnStrings; } // Information about the started backend (if it was successfully started) get backendUrl(): string { return this._backendUrl; } // Folder where backend is run from (might be different, if the backend needs to be published first) get binariesFolder(): string { return this._eventualBinariesFolder; } // Kills the pending backend process cleanup(): Promise<any> { this._backendPromise = null; this._backendUrl = ''; if (!this._funcProcess) { return Promise.resolve(); } console.log('Killing func process...'); return new Promise((resolve) => { // The process is a shell. So to stop func.exe, we need to kill the entire process tree. killProcessTree(this._funcProcess!.pid, resolve); this._funcProcess = null; }); } get backendCommunicationNonce(): string { return this._backendCommunicationNonce; } // Ensures that the backend is running (starts it, if needed) and returns its properties getBackend(): Promise<void> { if (!!this._backendPromise) { return this._backendPromise; } this._backendPromise = new Promise<void>((resolve, reject) => { vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Starting the backend `, cancellable: true }, (progress, token) => new Promise(stopProgress => { // Starting the backend on a first available port portscanner.findAPortNotInUse(37072, 38000).then((portNr: number) => { const backendUrl = Settings().backendBaseUrl.replace('{portNr}', portNr.toString()); progress.report({ message: backendUrl }); // Now running func.exe in backend folder this.startBackendOnPort(portNr, backendUrl, token) .then(resolve, reject) .finally(() => stopProgress(undefined)); }, (err: any) => { stopProgress(undefined); reject(`Failed to choose port for backend: ${err.message}`); }); })); }); // Allowing the user to try again this._backendPromise.catch(() => { // This call is important, without it a typo in connString would persist until vsCode restart this._removeMyselfFromList(); }); return this._backendPromise; } // Reference to the shell instance running func.exe private _funcProcess: ChildProcess | null = null; // Promise that resolves when the backend is started successfully private _backendPromise: Promise<void> | null = null; // Information about the started backend (if it was successfully started) private _backendUrl: string = ''; // Folder where backend is run from (might be different, if the backend needs to be published first) private _eventualBinariesFolder: string = this._binariesFolder; // A nonce for communicating with the backend private _backendCommunicationNonce = crypto.randomBytes(64).toString('base64'); // Runs the backend Function instance on some port private startBackendOnPort(portNr: number, backendUrl: string, cancelToken: vscode.CancellationToken): Promise<void> { return new Promise<void>((resolve, reject) => { this._log(`Attempting to start the backend from ${this._binariesFolder} on ${backendUrl}...`); if (!fs.existsSync(this._binariesFolder)) { reject(`Couldn't find backend binaries in ${this._binariesFolder}`); return; } // If this is a source code project if (fs.readdirSync(this._binariesFolder).some(fn => fn.toLowerCase().endsWith('.csproj'))) { const publishFolder = path.join(this._binariesFolder, 'publish'); // if it wasn't published yet if (!fs.existsSync(publishFolder)) { // publishing it const publishProcess = spawnSync('dotnet', ['publish', '-o', publishFolder], { cwd: this._binariesFolder, encoding: 'utf8' } ); if (!!publishProcess.stdout) { this._log(publishProcess.stdout.toString()); } if (publishProcess.status !== 0) { const err = 'dotnet publish failed. ' + (!!publishProcess.stderr ? publishProcess.stderr.toString() : `status: ${publishProcess.status}`); this._log(`ERROR: ${err}`); reject(err); return; } } this._eventualBinariesFolder = publishFolder; } // Important to inherit the context from VsCode, so that globally installed tools can be found const env = process.env; env[SharedConstants.NonceEnvironmentVariableName] = this._backendCommunicationNonce; if (this._storageConnectionSettings.isMsSql) { env[SharedConstants.MsSqlConnStringEnvironmentVariableName] = this._storageConnectionSettings.storageConnStrings[0]; // For MSSQL just need to set DFM_HUB_NAME to something, doesn't matter what it is so far env[SharedConstants.HubNameEnvironmentVariableName] = this._storageConnectionSettings.hubName; // Also setting AzureWebJobsSecretStorageType to 'files', so that the backend doesn't need Azure Storage env['AzureWebJobsSecretStorageType'] = 'files'; } else { env['AzureWebJobsStorage'] = this._storageConnectionSettings.storageConnStrings[0]; } this._funcProcess = spawn('func', ['start', '--port', portNr.toString(), '--csharp'], { cwd: this._eventualBinariesFolder, shell: true, env }); this._funcProcess.stdout.on('data', (data) => { const msg = data.toString(); this._log(msg); if (msg.toLowerCase().includes('no valid combination of account information found')) { reject('The provided Storage Connection String and/or Hub Name seem to be invalid.'); } }); this._funcProcess!.stderr.on('data', (data) => { const msg = data.toString(); this._log(`ERROR: ${msg}`); reject(`Func: ${msg}`); }); console.log(`Waiting for ${backendUrl} to respond...`); // Waiting for the backend to be ready const timeoutInSeconds = Settings().backendTimeoutInSeconds; const intervalInMs = 500, numOfTries = timeoutInSeconds * 1000 / intervalInMs; var i = numOfTries; const intervalToken = setInterval(() => { const headers: any = {}; headers[SharedConstants.NonceHeaderName] = this._backendCommunicationNonce; // Pinging the backend and returning its URL when ready axios.get(`${backendUrl}/--${this._storageConnectionSettings.hubName}/about`, { headers }).then(response => { console.log(`The backend is now running on ${backendUrl}`); clearInterval(intervalToken); this._backendUrl = backendUrl; resolve(); }, err => { if (!!err.response && err.response.status === 401) { // This typically happens when mistyping Task Hub name clearInterval(intervalToken); reject(err.message); } }); if (cancelToken.isCancellationRequested) { clearInterval(intervalToken); reject(`Cancelled by the user`); } else if (--i <= 0) { console.log(`Timed out waiting for the backend!`); clearInterval(intervalToken); reject(`No response within ${timeoutInSeconds} seconds. Ensure you have the latest Azure Functions Core Tools installed globally.`); } }, intervalInMs); }); } } export class StorageConnectionSettings { get storageConnStrings(): string[] { return this._connStrings; }; get hubName(): string { return this._hubName; }; get connStringHashKey(): string { return this._connStringHashKey; } get hashKey(): string { return this._hashKey; } get isFromLocalSettingsJson(): boolean { return this._fromLocalSettingsJson; } get isMsSql(): boolean { return !!ConnStringUtils.GetSqlServerName(this._connStrings[0]); } constructor(private _connStrings: string[], private _hubName: string, private _fromLocalSettingsJson: boolean = false) { this._connStringHashKey = StorageConnectionSettings.GetConnStringHashKey(this._connStrings); this._hashKey = this._connStringHashKey + this._hubName.toLowerCase(); } static GetConnStringHashKey(connStrings: string[]): string { const sqlServerName = ConnStringUtils.GetSqlServerName(connStrings[0]); if (!!sqlServerName) { return sqlServerName + ConnStringUtils.GetSqlDatabaseName(connStrings[0]); } return ConnStringUtils.GetTableEndpoint(connStrings[0]).toLowerCase(); } static MaskStorageConnString(connString: string): string { return connString.replace(/AccountKey=[^;]+/gi, 'AccountKey=*****'); } private readonly _connStringHashKey: string; private readonly _hashKey: string; } // Creates the SharedKeyLite signature to query Table Storage REST API, also adds other needed headers export function CreateAuthHeadersForTableStorage(accountName: string, accountKey: string, queryUrl: string): {} { const dateInUtc = new Date().toUTCString(); const signature = CryptoJS.HmacSHA256(`${dateInUtc}\n/${accountName}/${queryUrl}`, CryptoJS.enc.Base64.parse(accountKey)); return { 'Authorization': `SharedKeyLite ${accountName}:${signature.toString(CryptoJS.enc.Base64)}`, 'x-ms-date': dateInUtc, 'x-ms-version': '2015-12-11', 'Accept': 'application/json;odata=nometadata' }; }
the_stack
import { hexy } from 'hexy'; import * as monacoEditor from 'monaco-editor'; import { Pivot, PivotItem } from 'office-ui-fabric-react'; import React, { useEffect, useState, useRef } from 'react'; import { ObjectInspector } from 'react-inspector'; import MonacoEditor from 'react-monaco-editor'; import SplitterLayout from 'react-splitter-layout'; import { BodyDataPayload, RequestRecordDetailPayload } from '../../api/IRinCoreHub'; import { createKeyValuePairFromUrlEncoded, getContentType, getMonacoLanguage, isImage, isJson, isText, isWwwFormUrlencoded, } from '../../utilities'; import { KeyValueDetailList } from '../shared/KeyValueDetailList'; import * as styles from './InspectorDetail.RequestResponseView.css'; export interface IInspectorRequestResponseViewProps { record: RequestRecordDetailPayload; generals: { key: string; value: string }[]; headers: { [key: string]: string[] }; trailers: { [key: string]: string[] } | null; body: BodyDataPayload | null; paneSize: number | null; onPaneSizeChange: (newSize: number) => void; } type PreviewType = 'Tree' | 'Source' | 'List' | 'Hex'; export function InspectorDetailRequestResponseView(props: IInspectorRequestResponseViewProps) { const [bodyView, setBodyView] = useState<PreviewType>('Source'); const [paneToken, setPaneToken] = useState(0); const contentType = props.record.IsCompleted ? props.body != null && props.body.PresentationContentType !== '' ? props.body.PresentationContentType : getContentType(props.headers) : null; const isTransformed = props.body != null && props.body.PresentationContentType !== ''; const hasBody = props.body != null && props.body.Body != null && props.body.Body.length > 0; const body = props.body != null && props.body.Body != null && props.body.Body.length > 0 ? props.body.IsBase64Encoded ? atob(props.body.Body) : props.body.Body : ''; const canPreview = (contentType: string) => { return isJson(contentType) || isWwwFormUrlencoded(contentType) || isText(contentType) || isImage(contentType); }; const canPreviewForContentType = (contentType: string, type: PreviewType): boolean => { if (type == 'Hex') { return true; // Hex dump always can be available for any content-type. } if (isJson(contentType) && (type == 'Tree')) { return true; } if (isWwwFormUrlencoded && (type == 'List')) { return true; } if ((isText(contentType) || isImage(contentType)) && (type == 'Source')) { return true; } return false; } const onBodyPivotItemClicked = (item?: PivotItem) => { if (item != null && item.props.itemKey != null) { setBodyView(item.props.itemKey as PreviewType); } }; useEffect(() => { if (hasBody) { // Reset the preview type when content-type has been changed, and the current preview is not supported for it. if (contentType == null) { setBodyView('Hex'); } else if (!canPreviewForContentType(contentType, bodyView)) { setBodyView(canPreview(contentType) ? 'Source' : 'Hex'); } } }, [hasBody, contentType]); const trailers = props.trailers; return ( <div className={styles.inspectorRequestResponseView}> <SplitterLayout vertical={true} percentage={true} secondaryInitialSize={props.paneSize || undefined} onSecondaryPaneSizeChange={(newSize) => { props.onPaneSizeChange(newSize); setPaneToken(paneToken + 1); }} primaryMinSize={10} secondaryMinSize={10} > <div> <div className={styles.inspectorRequestResponseView_General}> {props.generals != null && props.generals.length > 0 && ( <KeyValueDetailList keyName="Name" valueName="Value" items={props.generals} /> )} </div> <div className={styles.inspectorRequestResponseView_Headers}> <KeyValueDetailList keyName="Header" valueName="Value" items={Object.keys(props.headers).map((x) => ({ key: x, value: props.headers[x].join('\n'), }))} /> </div> {trailers != null && Object.keys(trailers).length > 0 && ( <div className={styles.inspectorRequestResponseView_Headers}> <KeyValueDetailList keyName="Trailer" valueName="Value" items={Object.keys(trailers).map((x) => ({ key: x, value: trailers[x].join('\n'), }))} /> </div> )} </div> <div className={styles.inspectorRequestResponseView_Body}> {hasBody && contentType && ( <> <Pivot selectedKey={bodyView} onLinkClick={onBodyPivotItemClicked}> {isJson(contentType) && <PivotItem itemKey="Tree" headerText="Tree" itemIcon="RowsChild" />} {isWwwFormUrlencoded(contentType) && <PivotItem itemKey="List" headerText="List" itemIcon="ViewList" />} {isText(contentType) && <PivotItem itemKey="Source" headerText={isTransformed ? `View as ${contentType}` : 'Source'} itemIcon="Code" />} <PivotItem itemKey="Hex" headerText="Hex" itemIcon="ComplianceAudit" /> </Pivot> {canPreview(contentType) && (<> {bodyView === 'List' && ( <div className={styles.inspectorRequestResponseViewKeyValueDetailList}> <KeyValueDetailList keyName="Key" valueName="Value" items={createKeyValuePairFromUrlEncoded(body)} /> </div> )} {bodyView === 'Tree' && ( <div className={styles.inspectorRequestResponseViewObjectInspector}> <ObjectInspector data={JSON.parse(body)} /> </div> )} {bodyView === 'Source' && ( <> {isText(contentType) && ( <EditorPreview contentType={contentType} body={body} paneResizeToken={paneToken} /> )} {isImage(contentType) && props.body != null && ( <ImagePreview contentType={contentType} bodyAsBase64={props.body.Body} /> )} </> )} </>)} {bodyView === 'Hex' && props.body != null && ( <HexDumpPreview body={props.body.Body} isBase64Encoded={props.body.IsBase64Encoded} paneResizeToken={paneToken} /> )} </> )} </div> </SplitterLayout> </div> ); } function HexDumpPreview(props: { body: string; isBase64Encoded: boolean; paneResizeToken: number }) { function convertBase64StringToUint8Array(data: string) { const binary = atob(data); const array = new Array<number>(binary.length); for (let i = 0; i < binary.length; i++) { array[i] = binary.charCodeAt(i); } return array; } const body = props.isBase64Encoded ? convertBase64StringToUint8Array(props.body) : props.body; const hexed = hexy(body, { format: 'twos', caps: 'upper' }).trimEnd(); return ( <EditorPreview contentType="text/x-rin-hex-dump" language="text/x-rin-hex-dump" body={hexed} paneResizeToken={props.paneResizeToken} theme="rin-hex-dump" /> ); } monacoEditor.editor.defineTheme('rin-hex-dump', { base: 'vs', colors: {}, rules: [{ token: 'address-token', foreground: 'aaaaaa' }], inherit: true, }); monacoEditor.languages.register({ id: 'text/x-rin-hex-dump' }); monacoEditor.languages.setMonarchTokensProvider('text/x-rin-hex-dump', { tokenizer: { root: [[/^[0-9a-fA-F]+:/, 'address-token']], }, }); function EditorPreview(props: { contentType: string; body: string; paneResizeToken: number; theme?: string; language?: string; }) { const [editor, setEditor] = useState<monacoEditor.editor.IStandaloneCodeEditor>(); useEffect(() => { const listener = () => { editor?.layout(); }; window.addEventListener('resize', listener); // force re-layout editor?.layout(); return () => window.removeEventListener('resize', listener); }, [editor, props.paneResizeToken]); const monacoOptions: monacoEditor.editor.IEditorConstructionOptions = { readOnly: true, automaticLayout: true, wordWrap: 'on', }; return ( <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}> <MonacoEditor width="100%" height="100%" options={monacoOptions} theme={props.theme ?? 'vs'} language={props.language ?? getMonacoLanguage(props.contentType)} value={props.body} editorDidMount={(editor) => setEditor(editor)} /> </div> ); } function ImagePreview(props: { contentType: string; bodyAsBase64: string }) { const [imageSize, setImageSize] = useState({ width: 0, height: 0 }); const [loaded, setLoaded] = useState(false); const imagePreviewRef = useRef<HTMLImageElement>(null); useEffect(() => { if (imagePreviewRef.current != null) { const imageE = imagePreviewRef.current; const loaded = () => { setImageSize({ width: imageE.naturalWidth, height: imageE.naturalHeight }); setLoaded(true); }; imageE.addEventListener('load', loaded); return () => imageE.removeEventListener('load', loaded); } }, []); return ( <div className={styles.inspectorRequestResponseViewImagePreview}> <figure> <div className={styles.inspectorRequestResponseViewImagePreview_Image}> <img ref={imagePreviewRef} src={'data:' + props.contentType + ';base64,' + props.bodyAsBase64} /> </div> <figcaption> {loaded && ( <> {imageSize.width} x {imageSize.height} | </> )}{' '} {props.contentType} </figcaption> </figure> </div> ); }
the_stack
import { test, sinon, } from 'tstest' import { MemoryCard, } from '../config.js' import { ContactGender, ContactPayload, ContactType, } from '../schemas/contact.js' import { MessagePayload, MessageQueryFilter, MessageType, } from '../schemas/message.js' import type { RoomPayload, } from '../schemas/room.js' import { PuppetSkeleton } from './puppet-skeleton.js' /** * The Fixture */ import { PuppetTest, } from '../../tests/fixtures/puppet-test/puppet-test.js' test('contactQueryFilterFunction()', async t => { const TEXT_REGEX = 'query by regex' const TEXT_TEXT = 'query by text' const PAYLOAD_LIST: ContactPayload[] = [ { alias : TEXT_TEXT, avatar : 'mock', gender : ContactGender.Unknown, id : 'id1', name : TEXT_REGEX, phone : [], type : ContactType.Individual, }, { alias : TEXT_REGEX, avatar : 'mock', gender : ContactGender.Unknown, id : 'id2', name : TEXT_TEXT, phone : [], type : ContactType.Individual, }, { alias : TEXT_TEXT, avatar : 'mock', gender : ContactGender.Unknown, id : 'id3', name : TEXT_REGEX, phone : [], type : ContactType.Individual, }, { alias : TEXT_REGEX, avatar : 'mock', gender : ContactGender.Unknown, id : 'id4', name : TEXT_TEXT, phone : [], type : ContactType.Individual, }, ] const REGEX_VALUE = new RegExp(TEXT_REGEX) const TEXT_VALUE = TEXT_TEXT const puppet = new PuppetTest() void t.test('filter name by regex', async t => { const QUERY = { name: REGEX_VALUE } const ID_LIST = ['id1', 'id3'] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter the query to id list') }) void t.test('filter name by text', async t => { const QUERY = { name: TEXT_VALUE } const ID_LIST = ['id2', 'id4'] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list') }) void t.test('filter alias by regex', async t => { const QUERY = { alias: REGEX_VALUE } const ID_LIST = ['id2', 'id4'] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list') }) void t.test('filter alias by text', async t => { const QUERY = { alias: TEXT_VALUE } const ID_LIST = ['id1', 'id3'] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list') }) void t.test('filter contact existing id', async t => { const QUERY = { id: 'id1' } const ID_LIST = ['id1'] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list by id') }) void t.test('filter contact non-existing id', async t => { const QUERY = { id: 'fasdfsdfasfas' } const ID_LIST = [] as string[] const func = puppet.contactQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list by id') }) void t.test('throw if filter key unknown', async t => { t.throws(() => puppet.contactQueryFilterFactory({ xxxx: 'test' } as any), 'should throw') }) void t.test('throw if filter key are more than one', async t => { t.throws(() => puppet.contactQueryFilterFactory({ alias : 'test', name : 'test', }), 'should throw') }) }) test('roomQueryFilterFunction()', async t => { const TEXT_REGEX = 'query by regex' const TEXT_TEXT = 'query by text' const PAYLOAD_LIST: RoomPayload[] = [ { adminIdList : [], id : 'id1', memberIdList : [], topic : TEXT_TEXT, }, { adminIdList : [], id : 'id2', memberIdList : [], topic : TEXT_REGEX, }, { adminIdList : [], id : 'id3', memberIdList : [], topic : TEXT_TEXT, }, { adminIdList : [], id : 'id4', memberIdList : [], topic : TEXT_REGEX, }, ] const REGEX_VALUE = new RegExp(TEXT_REGEX) const TEXT_VALUE = TEXT_TEXT const puppet = new PuppetTest() void t.test('filter name by regex', async t => { const QUERY = { topic: REGEX_VALUE } const ID_LIST = ['id2', 'id4'] const func = puppet.roomQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter the query to id list') }) void t.test('filter name by text', async t => { const QUERY = { topic: TEXT_VALUE } const ID_LIST = ['id1', 'id3'] const func = puppet.roomQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list by text') }) void t.test('filter name by existing id', async t => { const QUERY = { id: 'id4' } const ID_LIST = ['id4'] const func = puppet.roomQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list by id') }) void t.test('filter name by non-existing id', async t => { const QUERY = { id: 'fsdfasfasfsdfsaf' } const ID_LIST = [] as string[] const func = puppet.roomQueryFilterFactory(QUERY) const idList = PAYLOAD_LIST.filter(func).map(payload => payload.id) t.same(idList, ID_LIST, 'should filter query to id list by id') }) void t.test('throw if filter key unknown', async t => { t.throws(() => puppet.roomQueryFilterFactory({ xxx: 'test' } as any), 'should throw') }) void t.test('throw if filter key are more than one', async t => { t.throws(() => puppet.roomQueryFilterFactory({ alias: 'test', topic: 'test', } as any), 'should throw') }) }) /** * Huan(202110): remove contactRoomList * because it seems not being used by Wechaty at all * and it is very to be implemented in the user land */ // test('contactRoomList()', async t => { // const puppet = new PuppetTest() // const sandbox = sinon.createSandbox() // const CONTACT_ID_1 = 'contact-id-1' // const CONTACT_ID_2 = 'contact-id-2' // const CONTACT_ID_3 = 'contact-id-3' // const ROOM_ID_1 = 'room-id-1' // const ROOM_ID_2 = 'room-id-2' // const ROOM_PAYLOAD_LIST: RoomPayload[] = [ // { // adminIdList : [], // id: ROOM_ID_1, // memberIdList: [ // CONTACT_ID_1, // CONTACT_ID_2, // ], // topic: 'room-topic-1', // }, // { // adminIdList : [], // id: ROOM_ID_2, // memberIdList: [ // CONTACT_ID_2, // CONTACT_ID_3, // ], // topic: 'room-topic-2', // }, // ] // sandbox.stub(puppet, 'roomList').resolves(ROOM_PAYLOAD_LIST.map(payload => payload.id)) // sandbox.stub(puppet, 'roomPayload').callsFake(async roomId => { // for (const payload of ROOM_PAYLOAD_LIST) { // if (payload.id === roomId) { // return payload // } // } // throw new Error('no payload for room id ' + roomId) // }) // const roomIdList1 = await puppet.contactRoomList(CONTACT_ID_1) // const roomIdList2 = await puppet.contactRoomList(CONTACT_ID_2) // const roomIdList3 = await puppet.contactRoomList(CONTACT_ID_3) // t.same(roomIdList1, [ROOM_ID_1], 'should get room 1 for contact 1') // t.same(roomIdList2, [ROOM_ID_1, ROOM_ID_2], 'should get room 1&2 for contact 2') // t.same(roomIdList3, [ROOM_ID_2], 'should get room 2 for contact 3') // }) /** * Huan(202110): the reset logic has been refactored * See: reset() method and 'reset' event breaking change #157 * https://github.com/wechaty/puppet/issues/157 */ test.skip('reset event throttle for reset()', async t => { const puppet = new PuppetTest({}) const sandbox = sinon.createSandbox() const timer = sandbox.useFakeTimers() const reset = sandbox.stub(puppet as any, 'reset') await puppet.start() puppet.emit('reset', { data: 'testing' }) t.equal(reset.callCount, 1, 'should call reset() immediately') timer.tick(1000 - 1) puppet.emit('reset', { data: 'testing 2' }) t.equal(reset.callCount, 1, 'should not call reset() again in the following 1 second') timer.tick(1000 + 1) puppet.emit('reset', { data: 'testing 2' }) t.equal(reset.callCount, 2, 'should call reset() again after 1 second') sandbox.restore() }) test('set memory() memory with a name', async t => { const puppet = new PuppetTest() const memory = new MemoryCard({ name: 'name' }) t.doesNotThrow(() => puppet.setMemory(memory), 'should not throw when set a named memory first time ') t.throws(() => puppet.setMemory(memory), 'should throw when set a named memory second time') }) test('messageQueryFilterFactory() one condition', async t => { const EXPECTED_TEXT1 = 'text' const EXPECTED_TEXT2 = 'regexp' const EXPECTED_TEXT3 = 'fdsafasdfsdakljhj;lds' const EXPECTED_ID1 = 'id1' const TEXT_QUERY_TEXT = EXPECTED_TEXT1 const TEXT_QUERY_ID = EXPECTED_ID1 const TEXT_QUERY_RE = new RegExp(EXPECTED_TEXT2) const QUERY_TEXT: MessageQueryFilter = { text: TEXT_QUERY_TEXT, } const QUERY_RE: MessageQueryFilter = { text: TEXT_QUERY_RE, } const QUERY_ID: MessageQueryFilter = { id: TEXT_QUERY_ID, } const PAYLOAD_LIST = [ { id: EXPECTED_ID1, text: EXPECTED_TEXT1, }, { text: EXPECTED_TEXT2, }, { text: EXPECTED_TEXT3, }, ] as MessagePayload[] const puppet = new PuppetTest() let filterFuncText let resultPayload filterFuncText = puppet.messageQueryFilterFactory(QUERY_TEXT) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 1, 'should get one result') t.equal(resultPayload[0]!.text, EXPECTED_TEXT1, 'should get text1') filterFuncText = puppet.messageQueryFilterFactory(QUERY_RE) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 1, 'should get one result') t.equal(resultPayload[0]!.text, EXPECTED_TEXT2, 'should get text2') filterFuncText = puppet.messageQueryFilterFactory(QUERY_ID) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 1, 'should get one result') t.equal(resultPayload[0]!.id, EXPECTED_ID1, 'should get id1') }) test('messageQueryFilterFactory() two condition', async t => { const EXPECTED_TEXT_DATA = 'data' const EXPECTED_TEXT_LINK = 'https://google.com' const EXPECTED_TYPE_URL = MessageType.Url const EXPECTED_TYPE_TEXT = MessageType.Text const QUERY_TEXT: MessageQueryFilter = { text: EXPECTED_TEXT_DATA, } const QUERY_TYPE: MessageQueryFilter = { type: EXPECTED_TYPE_URL, } const QUERY_TYPE_TEXT: MessageQueryFilter = { text: EXPECTED_TEXT_DATA, type: EXPECTED_TYPE_URL, } const PAYLOAD_LIST = [ { text: EXPECTED_TEXT_DATA, type: MessageType.Text, }, { text: EXPECTED_TEXT_DATA, type: MessageType.Url, }, { text: EXPECTED_TEXT_LINK, type: MessageType.Text, }, { text: EXPECTED_TEXT_LINK, type: MessageType.Url, }, ] as MessagePayload[] const puppet = new PuppetTest() let filterFuncText let resultPayload filterFuncText = puppet.messageQueryFilterFactory(QUERY_TEXT) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 2, 'should get two result') t.equal(resultPayload[0]!.text, EXPECTED_TEXT_DATA, 'should get text data') t.equal(resultPayload[0]!.type, EXPECTED_TYPE_TEXT, 'should get type text') t.equal(resultPayload[1]!.text, EXPECTED_TEXT_DATA, 'should get text data') t.equal(resultPayload[1]!.type, EXPECTED_TYPE_URL, 'should get type url') filterFuncText = puppet.messageQueryFilterFactory(QUERY_TYPE) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 2, 'should get two result') t.equal(resultPayload[0]!.text, EXPECTED_TEXT_DATA, 'should get text data') t.equal(resultPayload[0]!.type, EXPECTED_TYPE_URL, 'should get type url') t.equal(resultPayload[1]!.text, EXPECTED_TEXT_LINK, 'should get text link') t.equal(resultPayload[1]!.type, EXPECTED_TYPE_URL, 'should get type url ') filterFuncText = puppet.messageQueryFilterFactory(QUERY_TYPE_TEXT) resultPayload = PAYLOAD_LIST.filter(filterFuncText) t.equal(resultPayload.length, 1, 'should get one result') t.equal(resultPayload[0]!.text, EXPECTED_TEXT_DATA, 'should get text data') t.equal(resultPayload[0]!.type, EXPECTED_TYPE_URL, 'should get type url') }) test('name()', async t => { const puppet = new PuppetTest() const name = puppet.name() const EXPECTED_NAME = 'puppet-test' t.equal(name, EXPECTED_NAME, 'should get the child class package name') }) test('version()', async t => { const puppet = new PuppetTest() const version = puppet.version() const EXPECTED_VERSION = '1.0.0' t.equal(version, EXPECTED_VERSION, 'should get the child class package version') }) test('PuppetSkeleton: super.{start,stop}()', async t => { const sandbox = sinon.createSandbox() const startStub = sandbox.stub(PuppetSkeleton.prototype, 'start').resolves() const stopStub = sandbox.stub(PuppetSkeleton.prototype, 'stop').resolves() const puppet = new PuppetTest() t.notOk(startStub.called, 'should init start flag with false') t.notOk(stopStub.called, 'should init stop flag with false') await puppet.start() t.ok(startStub.called, 'should call the skeleton start(), which means all mixin start()s are chained correctly') t.notOk(stopStub.called, 'should keep stop flag with false') await puppet.stop() t.ok(startStub.called, 'should keep start flag with true') t.ok(stopStub.called, 'should call the skeleton stop(), which means all mixin stops()s are chained correctly') sandbox.restore() })
the_stack
import { observable, computed } from 'mobx'; import moment from 'moment'; import { DurableOrchestrationStatus, HistoryEvent } from '../DurableOrchestrationStatus'; import { ErrorMessageState } from '../ErrorMessageState'; import { IBackendClient } from '../../services/IBackendClient'; import { ITypedLocalStorage } from '../ITypedLocalStorage'; import { SequenceDiagramTabState } from './SequenceDiagramTabState'; import { FunctionGraphTabState } from './FunctionGraphTabState'; import { ICustomTabState } from './ICustomTabState'; import { GanttDiagramTabState } from './GanttDiagramTabState'; import { LiquidMarkupTabState } from './LiquidMarkupTabState'; import { CancelToken } from '../../CancelToken'; import { FunctionsMap } from '../az-func-as-a-graph/FunctionsMap'; import { FilterOperatorEnum, toOdataFilterQuery } from '../FilterOperatorEnum'; import { QueryString } from '../QueryString'; import { DateTimeHelpers } from '../../DateTimeHelpers'; // State of OrchestrationDetails view export class OrchestrationDetailsState extends ErrorMessageState { // Tab currently selected @computed get tabIndex(): number { return this._tabIndex; } set tabIndex(val: number) { if (this._tabIndex === val) { return; } this._tabIndex = val; this._localStorage.setItem('tabIndex', val.toString()); if (!!this.selectedTab) { this.loadCustomTab(); } else if (!this._history.length) { this.loadHistory(); } } get selectedTab(): ICustomTabState { return !this._tabIndex ? null : this._tabStates[this._tabIndex - 1]; } @computed get details(): DurableOrchestrationStatus { return this._details; } @computed get history(): HistoryEvent[] { return this._history; } @computed get historyTotalCount(): number { return this._historyTotalCount; } @computed get orchestrationId(): string { return this._orchestrationId; } @computed get loadInProgress(): boolean { return this._cancelToken.inProgress && !this._cancelToken.isCancelled; } @computed get inProgress(): boolean { return this._inProgress || this.loadInProgress; }; @computed get autoRefresh(): number { return this._autoRefresh; } set autoRefresh(val: number) { this._autoRefresh = val; this._localStorage.setItem('autoRefresh', this._autoRefresh.toString()); this.loadDetails(); } @computed get raiseEventDialogOpen(): boolean { return this._raiseEventDialogOpen; } set raiseEventDialogOpen(val: boolean) { this._raiseEventDialogOpen = val; if (!!val) { this.eventName = ''; this.eventData = ''; } } @computed get setCustomStatusDialogOpen(): boolean { return this._setCustomStatusDialogOpen; } set setCustomStatusDialogOpen(val: boolean) { this._setCustomStatusDialogOpen = val; if (!!val) { this.newCustomStatus = !!this._details.customStatus ? JSON.stringify(this._details.customStatus) : ''; } } @computed get restartDialogOpen(): boolean { return this._restartDialogOpen; } set restartDialogOpen(val: boolean) { this._restartDialogOpen = val; if (!!val) { this.restartWithNewInstanceId = true; } } @computed get isCustomStatusDirty(): boolean { if (!this._details.customStatus) { return !!this.newCustomStatus; } return this.newCustomStatus !== JSON.stringify(this._details.customStatus); } @computed get functionNames(): { [name: string]: any } { return this._functionMap; }; @computed get eventNames(): string[] { const result: string[] = []; for (const name in this._functionMap) { const func = this._functionMap[name]; if (!!func.isSignalledBy) { for (const signalledBy of func.isSignalledBy) { result.push(signalledBy.signalName); } } } return result; }; @computed get timeFrom(): moment.Moment { return this._timeFrom; } set timeFrom(val: moment.Moment) { this._timeFrom = val; } @computed get timeFromEnabled(): boolean { return !!this._timeFrom; } set timeFromEnabled(val: boolean) { if (!!val) { if (this._history.length > 0) { this._timeFrom = moment(this._history[0].Timestamp); } else { this._timeFrom = moment(); } } else { this._timeFrom = null; this.reloadHistory(); } } @computed get filterValue(): string { return this._filterValue; } set filterValue(val: string) { this._filterValue = val; } @computed get filterOperator(): FilterOperatorEnum { return this._filterOperator; } set filterOperator(val: FilterOperatorEnum) { this._filterOperator = val; if (!!this._filterValue && this._filteredColumn !== '0') { this.reloadHistory(); } } @computed get filteredColumn(): string { return this._filteredColumn; } set filteredColumn(val: string) { this._filteredColumn = val; if (!this._filterValue) { return; } if (this._filteredColumn === '0') { this._filterValue = ''; } this.reloadHistory(); } @observable rewindConfirmationOpen: boolean = false; @observable terminateConfirmationOpen: boolean = false; @observable purgeConfirmationOpen: boolean = false; @observable eventName: string; @observable eventData: string; @observable newCustomStatus: string; @observable restartWithNewInstanceId: boolean = true; @observable longJsonDialogState = {}; @computed get tabStates(): ICustomTabState[] { return this._tabStates; } get backendClient(): IBackendClient { return this._backendClient; } constructor(private _orchestrationId: string, private _isFunctionGraphAvailable: boolean, private _backendClient: IBackendClient, private _localStorage: ITypedLocalStorage<OrchestrationDetailsState>) { super(); const autoRefreshString = this._localStorage.getItem('autoRefresh'); if (!!autoRefreshString) { this._autoRefresh = Number(autoRefreshString); } const tabIndexString = this._localStorage.getItem('tabIndex'); if (!!tabIndexString) { this._tabIndex = Number(tabIndexString); } // Storing filter in query string only. Don't want it to stick to every instance in VsCode. this.readFilterFromQueryString(); } rewind() { this.rewindConfirmationOpen = false; const uri = `/orchestrations('${this._orchestrationId}')/rewind`; this._inProgress = true; this._backendClient.call('POST', uri).then(() => { this._inProgress = false; this.loadDetails(); }, err => { this._inProgress = false; this.showError('Failed to rewind', err); }); } terminate() { this.terminateConfirmationOpen = false; const uri = `/orchestrations('${this._orchestrationId}')/terminate`; this._inProgress = true; this._backendClient.call('POST', uri).then(() => { this._inProgress = false; this.loadDetails(); }, err => { this._inProgress = false; this.showError('Failed to terminate', err); }); } purge() { this.purgeConfirmationOpen = false; const uri = `/orchestrations('${this._orchestrationId}')/purge`; this._inProgress = true; this._backendClient.call('POST', uri).then(() => { this._inProgress = false; this._history = []; this._details = new DurableOrchestrationStatus(); this._tabStates = []; }, err => { this._inProgress = false; this.showError('Failed to purge', err); }); } restart() { const uri = `/orchestrations('${this._orchestrationId}')/restart`; const requestBody = { restartWithNewInstanceId: this.restartWithNewInstanceId }; this.restartDialogOpen = false; this._inProgress = true; this._backendClient.call('POST', uri, requestBody).then(() => { this._inProgress = false; this.loadDetails(); }, err => { this._inProgress = false; this.showError('Failed to restart', err); }); } raiseEvent() { const uri = `/orchestrations('${this._orchestrationId}')/raise-event`; const requestBody = { name: this.eventName, data: null }; try { requestBody.data = JSON.parse(this.eventData); } catch (err) { this.showError('Failed to parse event data', err); return; } finally { this.raiseEventDialogOpen = false; } this._inProgress = true; this._backendClient.call('POST', uri, requestBody).then(() => { this._inProgress = false; this.loadDetails(); }, err => { this._inProgress = false; this.showError('Failed to raise an event', err); }); } setCustomStatus() { const uri = `/orchestrations('${this._orchestrationId}')/set-custom-status`; var requestBody = null; try { if (!!this.newCustomStatus) { requestBody = JSON.parse(this.newCustomStatus); } } catch (err) { this.showError('Failed to parse custom status', err); return; } finally { this.setCustomStatusDialogOpen = false; } this._inProgress = true; this._backendClient.call('POST', uri, requestBody).then(() => { this._inProgress = false; this.loadDetails(); }, err => { this._inProgress = false; this.showError('Failed to set custom status', err); }); } loadDetails() { if (!!this.inProgress) { // We might end up here, if next timer occurs while a custom tab is still loading // Doing auto-refresh this.setAutoRefresh(); return; } this._inProgress = true; this._noMorePagesToLoad = false; if (!this._autoRefresh && (!this.selectedTab)) { this._history = []; this._historyTotalCount = 0; } const functionMapPromise = !!this._isFunctionGraphAvailable ? this._backendClient.call('GET', `/function-map`) : Promise.resolve(null); const uri = `/orchestrations('${this._orchestrationId}')`; return Promise.all([this._backendClient.call('GET', uri), functionMapPromise]).then(responses => { this._details = responses[0]; const traversalResult = responses[1]; // Doing auto-refresh this.setAutoRefresh(); var tabStateIndex = 0; // Loading sequence diagram tab if (this._details.entityType === "Orchestration") { if (this._tabStates.length <= tabStateIndex) { this._tabStates.push(new SequenceDiagramTabState((orchId) => this.loadAllHistory(orchId))); this._tabStates.push(new GanttDiagramTabState((orchId) => this.loadAllHistory(orchId))); } tabStateIndex += 2; } // Functions Graph tab if (!!traversalResult) { this._functionMap = traversalResult.functions; const functionName = DurableOrchestrationStatus.getFunctionName(this._details); // Entities have their names lowered, so we need to do a case-insensitive match const shownFunctionNames = Object.keys(traversalResult.functions).map(fn => fn.toLowerCase()); // Only showing Functions Graph, if currently opened instance is shown on it if (shownFunctionNames.includes(functionName.toLowerCase())) { if (this._tabStates.length <= tabStateIndex) { this._tabStates.push(new FunctionGraphTabState(this._backendClient, traversalResult, (orchId) => this.loadAllHistory(orchId))); } tabStateIndex++; } } // Loading custom tabs if (!!this._details.tabTemplateNames) { for (var templateName of this._details.tabTemplateNames) { if (this._tabStates.length <= tabStateIndex) { this._tabStates.push(new LiquidMarkupTabState(this._orchestrationId, this._backendClient)); } this._tabStates[tabStateIndex].name = templateName; tabStateIndex++; } } // Ensuring tab index does not go out of sync if (this._tabIndex < 0 || this._tabIndex > this._tabStates.length) { this._tabIndex = 0; } this._inProgress = false; if (!this.selectedTab) { this.loadHistory(!!this._autoRefresh); } else { this.loadCustomTab(); } }, err => { this._inProgress = false; // Cancelling auto-refresh just in case this._autoRefresh = 0; this.showError('Load failed', err); }); } cancel() { this._cancelToken.isCancelled = true; this._cancelToken = new CancelToken(); } reloadHistory(): void { if (!!this.inProgress || !!this.selectedTab) { return; } // If dates are invalid, reverting them to previous valid values if (!!this._timeFrom && !DateTimeHelpers.isValidMoment(this._timeFrom)) { this._timeFrom = this._oldTimeFrom; } // Storing filter in query string only. Don't want it to stick to every instance in VsCode. this.writeFilterToQueryString(); this._noMorePagesToLoad = false; this._history = []; this._historyTotalCount = 0; this.loadHistory(); this._oldFilterValue = this._filterValue; this._oldTimeFrom = this._timeFrom; // Enabling back arrow. // This must be done here and not in the ctor, because onPopState events might be produced by external components and triggered immediately // upon page load (when login state is not initialized yet), which would lead to errors. this.registerOnPopStateHandler(); } loadHistory(isAutoRefresh: boolean = false): void { if (!!this.inProgress || !!this.selectedTab || !!this._noMorePagesToLoad) { return; } const cancelToken = this._cancelToken; cancelToken.inProgress = true; var filter = toOdataFilterQuery(this._filteredColumn, this._filterOperator, this._filterValue); if (!!this._timeFrom) { filter = `timestamp ge '${this._timeFrom.toISOString()}'` + (!!filter ? ` and ${filter}` : '') } // In auto-refresh mode only refreshing the first page const skip = isAutoRefresh ? 0 : this._history.length; var uri = `/orchestrations('${this._orchestrationId}')/history?$top=${this._pageSize}&$skip=${skip}`; if (!!filter) { uri += '&$filter=' + filter; } this._backendClient.call('GET', uri).then(response => { if (cancelToken.isCancelled) { return; } this._historyTotalCount = response.totalCount; if (isAutoRefresh) { this._history = response.history; } else { this._history.push(...response.history); if (response.history.length < this._pageSize) { // Stop the infinite scrolling this._noMorePagesToLoad = true; } } }, err => { // Cancelling auto-refresh just in case this._autoRefresh = 0; if (!cancelToken.isCancelled) { this.showError('Failed to load history', err); } }).finally(() => { cancelToken.inProgress = false; }); } gotoFunctionCode(functionName: string): void { if (this.backendClient.isVsCode) { this.backendClient.call('GotoFunctionCode', functionName).then(() => {}, err => { console.log(`Failed to goto function code: ${err.message}`); }); } else { var func = this._functionMap[functionName]; if (!!func && !!func.filePath) { window.open(func.filePath); } } } showFunctionsGraph(): void { this.backendClient.call('VisualizeFunctionsAsAGraph', '').then(() => {}, err => { console.log(`Failed to goto functions graph: ${err.message}`); }); } applyTimeFrom() { if (DateTimeHelpers.isValidMoment(this._timeFrom) && this._oldTimeFrom !== this._timeFrom) { this.reloadHistory(); } } applyFilterValue() { if (this._oldFilterValue !== this._filterValue) { this.reloadHistory(); } } private loadCustomTab(): void { if (!!this.inProgress) { return; } const cancelToken = this._cancelToken; cancelToken.inProgress = true; this.selectedTab.load(this._details, cancelToken).then(() => {}, err => { // Cancelling auto-refresh just in case this._autoRefresh = 0; if (!cancelToken.isCancelled) { this.showError('Failed to load tab', err); } }).finally(() => { cancelToken.inProgress = false; }); } private setAutoRefresh(): void { if (!this._autoRefresh) { return; } if (!!this._autoRefreshToken) { clearTimeout(this._autoRefreshToken); } this._autoRefreshToken = setTimeout(() => this.loadDetails(), this._autoRefresh * 1000); } private loadAllHistory(orchestrationId: string): Promise<HistoryEvent[]> { const uri = `/orchestrations('${orchestrationId}')/history`; return this._backendClient.call('GET', uri).then(response => response.history); } private readFilterFromQueryString(): void { const queryString = new QueryString(); const timeFromString = queryString.values['timeFrom']; this._timeFrom = !!timeFromString ? moment(timeFromString) : null; this._oldTimeFrom = this._timeFrom; this._filteredColumn = queryString.values['filteredColumn'] ?? '0'; const filterOperatorString = queryString.values['filterOperator']; this._filterOperator = !!filterOperatorString ? FilterOperatorEnum[filterOperatorString] : FilterOperatorEnum.Equals; this._filterValue = queryString.values['filterValue'] ?? ''; this._oldFilterValue = this._filterValue; } private writeFilterToQueryString() { const queryString = new QueryString(); queryString.setValue('timeFrom', !!this._timeFrom ? this._timeFrom.toISOString() : null); queryString.setValue('filteredColumn', this._filteredColumn); queryString.setValue('filterOperator', FilterOperatorEnum[this._filterOperator]); queryString.setValue('filterValue', this._filterValue); queryString.apply(true); } private registerOnPopStateHandler(): void { if (!window.onpopstate) { window.onpopstate = (evt: PopStateEvent) => { this.readFilterFromQueryString(); // This should be loadDetails(), not reloadHistory(). Because reloadHistory() pushes the history state, which shouldn't happen here. this.loadDetails(); } } } @observable private _tabStates: ICustomTabState[] = []; @observable private _details: DurableOrchestrationStatus = new DurableOrchestrationStatus(); @observable private _history: HistoryEvent[] = []; @observable private _tabIndex: number = 0; @observable private _inProgress: boolean = false; @observable private _cancelToken: CancelToken = new CancelToken(); @observable private _raiseEventDialogOpen: boolean = false; @observable private _setCustomStatusDialogOpen: boolean = false; @observable private _restartDialogOpen: boolean = false; @observable private _autoRefresh: number = 0; @observable private _historyTotalCount: number = 0; @observable private _functionMap: FunctionsMap = {}; @observable private _timeFrom: moment.Moment; @observable private _filterValue: string = ''; @observable private _filterOperator: FilterOperatorEnum = FilterOperatorEnum.Equals; @observable private _filteredColumn: string = '0'; private _oldTimeFrom: moment.Moment; private _oldFilterValue: string = ''; private _autoRefreshToken: NodeJS.Timeout; private _noMorePagesToLoad: boolean = false; private readonly _pageSize = 200; }
the_stack
import { expect } from 'chai'; import { TextField } from '@phosphor/datastore'; /** * Return a shuffled copy of an array */ function shuffle<T>(array: ReadonlyArray<T>): T[] { let ret = array.slice(); for (let i = ret.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i [ret[i], ret[j]] = [ret[j], ret[i]]; // swap elements } return ret; } describe('@phosphor/datastore', () => { describe('TextField', () => { let field: TextField; beforeEach(() => { field = new TextField({ description: 'A text field storing strings' }); }); describe('constructor()', () => { it('should create a list field', () => { expect(field).to.be.instanceof(TextField); }); }); describe('type', () => { it('should return the type of the field', () => { expect(field.type).to.equal('text'); }); }); describe('createValue()', () => { it('should create an initial value for the field', () => { expect(field.createValue()).to.equal(''); }); }); describe('createMetadata()', () => { it('should create initial metadata for the field', () => { expect(field.createMetadata()).to.eql({ ids: [], cemetery: {} }); }); }); describe('applyUpdate', () => { it('should return the result of the update', () => { let previous = field.createValue(); let metadata = field.createMetadata(); let splice = { index: 0, remove: 0, text: 'abc' }; let { value, change, patch } = field.applyUpdate({ previous, update: splice, metadata, version: 1, storeId: 1 }); expect(value).to.equal('abc'); expect(change[0]).to.eql({ index: 0, removed: '', inserted: 'abc'}); expect(patch.length).to.equal(1); expect(patch[0].removedText.length).to.equal(splice.remove); expect(patch[0].insertedText).to.equal(splice.text); expect(patch[0].removedIds.length).to.equal(splice.remove); expect(patch[0].insertedIds.length).to.equal(splice.text.length); }); it('should accept multiple splices', () => { let previous = field.createValue(); let metadata = field.createMetadata(); let splice1 = { index: 0, remove: 0, text: 'abc' }; let splice2 = { index: 1, remove: 1, text: 'de' }; let { value, change, patch } = field.applyUpdate({ previous, update: [splice1, splice2], metadata, version: 1, storeId: 1 }); expect(value).to.equal('adec'); expect(change.length).to.eql(2); expect(change[0]).to.eql({ index: 0, removed: '', inserted: 'abc'}); expect(change[1]).to.eql({ index: 1, removed: 'b', inserted: 'de'}); expect(patch.length).to.equal(2); expect(patch[0].removedText.length).to.equal(splice1.remove); expect(patch[0].insertedText).to.eql(splice1.text); expect(patch[0].removedIds.length).to.equal(splice1.remove); expect(patch[0].insertedIds.length).to.equal(splice1.text.length); expect(patch[1].removedText.length).to.equal(splice2.remove); expect(patch[1].insertedText).to.equal(splice2.text); expect(patch[1].removedIds.length).to.equal(splice2.remove); expect(patch[1].insertedIds.length).to.equal(splice2.text.length); }); it('should accept long splices', () => { let previous = field.createValue(); let text = 'a'.repeat(1000000); let metadata = field.createMetadata(); let splice = { index: 0, remove: 0, text }; let { value } = field.applyUpdate({ previous, update: [splice], metadata, version: 1, storeId: 1 }); expect(value).to.equal(text); }); }); describe('applyPatch', () => { it('should return the result of the patch', () => { let previous = field.createValue(); let metadata = field.createMetadata(); // Create a patch let { patch } = field.applyUpdate({ previous, update: { index: 0, remove: 0, text: 'abc' }, metadata, version: 1, storeId: 1 }); // Reset the metadata metadata = field.createMetadata(); let patched = field.applyPatch({ previous, metadata, patch }); expect(patched.value).to.equal('abc'); expect(patched.change[0]).to.eql({index: 0, removed: '', inserted: 'abc'}); }); it('should allow for out-of-order patches', () => { let previous = field.createValue(); let metadata = field.createMetadata(); // Generate some patches. let firstUpdate = field.applyUpdate({ previous, update: { index: 0, remove: 0, text: 'agc' }, metadata, version: 1, storeId: 1 }); let secondUpdate = field.applyUpdate({ previous: firstUpdate.value, update: { index: 1, remove: 1, text: 'b' }, metadata, version: 2, storeId: 1 }); let thirdUpdate = field.applyUpdate({ previous: secondUpdate.value, update: { index: 3, remove: 0, text: 'def' }, metadata, version: 3, storeId: 1 }); expect(thirdUpdate.value).to.equal('abcdef'); // Now apply the patches on another client in a different order. // They should have the same resulting value. metadata = field.createMetadata(); let firstPatch = field.applyPatch({ previous, metadata, patch: thirdUpdate.patch }); expect(firstPatch.change[0]).to.eql({ index: 0, removed: '', inserted: 'def' }); let secondPatch = field.applyPatch({ previous: firstPatch.value, metadata, patch: secondUpdate.patch }); expect(secondPatch.change[0]).to.eql({ index: 0, removed: '', inserted: 'b' }); let thirdPatch = field.applyPatch({ previous: secondPatch.value, metadata, patch: firstUpdate.patch }); expect(thirdPatch.change[0]).to.eql({ index: 1, removed: '', inserted: 'c' }); expect(thirdPatch.change[1]).to.eql({ index: 0, removed: '', inserted: 'a' }); expect(thirdPatch.value).to.equal('abcdef'); }); it('should allow for racing patches', () => { let current = field.createValue(); let metadata = field.createMetadata(); let values = 'abcdefghijk'; let patches: TextField.Patch[] = []; // Recreate the values array one update at a time, // capturing the patches. for (let i = 0, version = 0; i < values.length; i++) { let u1 = field.applyUpdate({ previous: current, metadata, update: { index: i, remove: 0, text: values[i] + values[i] + values[i] }, version, storeId: 1 }); version++; current = u1.value; patches.push(u1.patch); let u2 = field.applyUpdate({ previous: current, metadata, update: { index: i+1, remove: 2, text: '' }, version, storeId: 1 }); version++; current = u2.value; patches.push(u2.patch); } expect(current).to.eql(values); // Shuffle the patches and apply them in a random order to // a new ListField. We try this multiple times to ensure we // don't accidentally get it right. for (let i = 0; i < 10; ++i) { let shuffled = shuffle(patches); current = field.createValue(); metadata = field.createMetadata(); shuffled.forEach(patch => { let { value } = field.applyPatch({ previous: current, metadata, patch }); current = value; }); expect(current).to.eql(values); } }); it('should handle concurrently deleted values', () => { let initial = field.createValue(); let metadata = field.createMetadata(); // First insert some values. let commonUpdate = field.applyUpdate({ previous: initial, metadata, update: { index: 0, remove: 0, text: 'abcd' }, version: 1, storeId: 1 }); // Two collaborators concurrently remove the same value. let metadataA = field.createMetadata(); let patchA = field.applyPatch({ previous: initial, metadata: metadataA, patch: commonUpdate.patch }); let updateA = field.applyUpdate({ previous: patchA.value, metadata: metadataA, update: { index: 1, remove: 2, text: '' }, version: 2, storeId: 2 }); expect(updateA.value).to.eql('ad'); let metadataB = field.createMetadata(); let patchB = field.applyPatch({ previous: initial, metadata: metadataB, patch: commonUpdate.patch }); let updateB = field.applyUpdate({ previous: patchB.value, metadata: metadataB, update: { index: 0, remove: 2, text: '' }, version: 2, storeId: 3 }); expect(updateB.value).to.eql('cd'); // Apply the A patch to the B collaborator let patchB2 = field.applyPatch({ previous: updateB.value, metadata: metadataB, patch: updateA.patch }); expect(patchB2.value).to.eql('d'); // Apply the B patch to the A collaborator let patchA2 = field.applyPatch({ previous: updateA.value, metadata: metadataA, patch: updateB.patch }); expect(patchA2.value).to.eql('d'); // Apply the patches to a third collaborator out-of-order. let metadataC = field.createMetadata(); let patchC1 = field.applyPatch({ previous: initial, metadata: metadataC, patch: updateB.patch }); let patchC2 = field.applyPatch({ previous: patchC1.value, metadata: metadataC, patch: updateA.patch }); let patchC3 = field.applyPatch({ previous: patchC2.value, metadata: metadataC, patch: commonUpdate.patch }); // Check the final value. expect(patchC3.value).to.eql('d'); }); }); describe('unapplyPatch', () => { it('should remove a patch from the history', () => { let previous = field.createValue(); let metadata = field.createMetadata(); // Create a patch let updated1 = field.applyUpdate({ previous, update: { index: 0, remove: 0, text: 'abcp' }, metadata, version: 1, storeId: 1 }); let updated2 = field.applyUpdate({ previous: updated1.value, update: { index: 3, remove: 1, text: 'def' }, metadata, version: 2, storeId: 1 }); expect(updated2.value).to.equal('abcdef'); // Reset the metadata and apply the patches metadata = field.createMetadata(); let patched1 = field.applyPatch({ previous, metadata, patch: updated1.patch }); let patched2 = field.applyPatch({ previous: patched1.value, metadata, patch: updated2.patch }); expect(patched2.value).to.equal('abcdef'); // Unapply the patches out of order. let unpatched1 = field.unapplyPatch({ previous: patched2.value, metadata, patch: updated1.patch }); expect(unpatched1.value).to.equal('def'); expect(unpatched1.change[0]).to.eql({index: 0, removed: 'abc', inserted: ''}); let unpatched2 = field.unapplyPatch({ previous: unpatched1.value, metadata, patch: updated2.patch }); expect(unpatched2.value).to.equal(''); expect(unpatched2.change[0]).to.eql({index: 0, removed: 'def', inserted: ''}); }); it('should handle concurrently deleted text', () => { let previous = field.createValue(); let metadata = field.createMetadata(); // Create a patch let { patch } = field.applyUpdate({ previous, update: { index: 0, remove: 0, text: 'abc' }, metadata, version: 1, storeId: 1 }); // Reset the metadata and unnaply the patch before applying it. metadata = field.createMetadata(); let unpatched = field.unapplyPatch({ previous, metadata, patch }); expect(unpatched.value).to.equal(''); expect(unpatched.change.length).to.equal(0); let patched = field.applyPatch({ previous: unpatched.value, metadata, patch }); expect(patched.value).to.equal(''); expect(patched.change.length).to.equal(0); }); }); describe('mergeChange', () => { it('should merge two successive changes', () => { let change1 = [ { index: 0, removed: '', inserted: 'ab' } ]; let change2 = [ { index: 1, removed: 'b', inserted: 'cd' } ]; let result = field.mergeChange(change1, change2); expect(result).to.eql([...change1, ...change2]); }); }); describe('mergePatch', () => { it('should merge two successive patches', () => { let patch1 = [ { removedIds: [], removedText: '' , insertedIds: ['id-1', 'id-2'], insertedText: 'ab' } ]; let patch2 = [ { removedIds: ['id-2'], removedText: 'b', insertedIds: ['id-3', 'id-4'], insertedText: 'cd' } ]; let result = field.mergePatch(patch1, patch2); expect(result).to.eql([...patch1, ...patch2]); }); }); }); });
the_stack
import chalk from 'chalk' import FS, { promises as FSP } from 'fs' import parseArgs from 'minimist' import { collect, collectError } from '@vuedx/shared' import * as Path from 'path' import readline from 'readline' import TS from 'typescript/lib/tsserverlibrary' import { Position, TextDocument } from 'vscode-languageserver-textdocument' import { AbortController, Diagnostics, getDiagnostics, getDiagnostics2, } from './diagnostics' import { generateCodeFrame } from './generateCodeFrame' const colors = { warning: chalk.yellow, error: chalk.red, suggestion: chalk.green, message: chalk.blueBright, } let directory = process.cwd() const cache = new Map<string, TextDocument>() function print(chunk: string): void { process.stdout.write(chunk) } export async function getTextDocument(file: string): Promise<TextDocument> { return cache.get(file) ?? (await createTextDocument(file)) } function clearScreen(): void { const blank = '\n'.repeat(process.stdout.rows) console.log(blank) readline.cursorTo(process.stdout, 0, 0) readline.clearScreenDown(process.stdout) } async function createTextDocument(file: string): Promise<TextDocument> { const content = await FSP.readFile(Path.resolve(directory, file), { encoding: 'utf-8' }) const fileName = toNormalizedPath(file) const document = TextDocument.create( fileName, Path.posix.extname(file), 0, content, ) cache.set(fileName, document) return document } function toNormalizedPath(fileName: string): string { return TS.server.toNormalizedPath(fileName) } function formatLocation( fileName: string, start: TS.server.protocol.Location, ): string { const relativeFileName = convertToRelativePath(fileName) const line = start.line + 1 const column = start.offset + 1 let output = '' output += chalk.cyan(relativeFileName) output += ':' output += chalk.yellow(`${line}`) output += ':' output += chalk.yellow(`${column}`) return output } function getDiagnosticCategory( diagnostic: Pick<TS.server.protocol.Diagnostic, 'category'>, ): keyof typeof colors { return (/^(warning|error|suggestion|message)$/i.test(diagnostic.category) ? diagnostic.category.toLowerCase() : 'error') as any } function toPosition(loc: TS.server.protocol.Location): Position { return { line: loc.line - 1, character: loc.offset - 1 } } async function formatDiagnosticsWithColorAndContext( fileName: string, diagnostic: TS.server.protocol.Diagnostic, ): Promise<string> { let output = '' output += formatLocation(fileName, diagnostic.start) // TODO: GH#18217 output += ' - ' const category = getDiagnosticCategory(diagnostic) output += colors[category](category) output += chalk.gray(` ${diagnostic.source ?? ''}${diagnostic.code ?? ''}: `) output += diagnostic.text const document = await getTextDocument(fileName) output += '\n' output += generateCodeFrame( document.getText(), document.offsetAt(toPosition(diagnostic.start)), document.offsetAt(toPosition(diagnostic.end)), (underline) => colors[category](underline), (gutter) => chalk.bgWhite(gutter.trimEnd()) + ' ', ) if (diagnostic.relatedInformation != null) { for (const { message, span, category } of diagnostic.relatedInformation) { output += '\n' const color = colors[getDiagnosticCategory({ category })] if (span != null) { output += ' ' + formatLocation(span.file, span.start) const document = await getTextDocument(span.file) output += '\n' output += generateCodeFrame( document.getText(), document.offsetAt(toPosition(span.start)), document.offsetAt(toPosition(span.end)), (underline) => color(underline), (gutter) => chalk.bgWhite(gutter.trimEnd()) + ' ', ) output += '\n' } output += ' ' + message } } output += '\n' return output } function formatDiagnostic( fileName: string, diagnostic: TS.server.protocol.Diagnostic, ): string { const errorMessage = `${diagnostic.category} ${diagnostic.source ?? ''}${ diagnostic.code ?? '' }: ${diagnostic.text}` const relativeFileName = convertToRelativePath(fileName) const line = diagnostic.start.line + 1 const column = diagnostic.start.offset + 1 return `${relativeFileName}(${line},${column}): ${errorMessage}` } const ERROR_RE = /^(error)$/i function getErrorCount(diagnostics: Diagnostics): number { return diagnostics.reduce( (count, diagnostic) => count + diagnostic.diagnostics.filter((diagnostic) => ERROR_RE.test(diagnostic.category), ).length, 0, ) } function convertToRelativePath(fileName: string): string { return Path.isAbsolute(fileName) ? Path.relative(directory, fileName).replace(/\\/g, '/') : fileName } async function _cli(): Promise<void> { const { pretty, vue, help, watch, format, _: argv } = parseArgs( process.argv.slice(2), { boolean: ['json', 'rdjson', 'verbose', 'vue', 'help', 'pretty', 'watch'], string: ['format'], default: { pretty: true, format: 'raw' }, }, ) if (help === true) { console.error( ` Usage: vuedx-typecheck [directory] <options> Options --format One of 'raw', 'json' or 'rdjson' --vue process only vue files --no-pretty Pretty print output --help display help --watch Watch files for changes `.trim(), ) process.exit(0) } directory = argv[0] != null ? Path.isAbsolute(argv[0]) ? argv[0] : Path.resolve(process.cwd(), argv[0]) : process.cwd() if (!FS.existsSync(directory)) { console.error(`Cannot find directory: "${String(argv[0])}"`) process.exit(1) } if (format === 'raw') { console.debug('Running for ' + directory) } if (!FS.statSync(directory).isDirectory()) { console.error( `Expecting a directory, but "${ process.argv[2] ?? '' }" is not a directory.`, ) process.exit(1) } collect('cli exec', { watch, format, vue, pretty, }) if (watch === true) { const controller = new AbortController() for await (const result of getDiagnostics( directory, controller.signal, true, )) { clearScreen() await handleResults(result, { format, pretty, vue }) } } else { const result = await getDiagnostics2(directory) await handleResults(result, { format, pretty, vue }) if (getErrorCount(result) > 0 && format === 'raw') process.exit(2) else process.exit(0) } } export async function cli(): Promise<void> { try { await _cli() } catch (error) { collectError(error) throw error } } /** * Return diagnostic result in Reviewdog Diagnostic Format * @see https://github.com/reviewdog/reviewdog/tree/main/proto/rdf#rdjson */ function encodeRdJSON(result: Diagnostics, pretty: boolean): string { const severityMap = { warning: 'WARNING', error: 'ERROR', suggestion: 'INFO', message: 'INFO', } return JSON.stringify( { source: { name: 'VueDX typecheck', url: 'https://github.com/znck/vue-developer-experience/tree/main/packages/typecheck', }, diagnostics: result.flatMap((sourceFile) => { return sourceFile.diagnostics.map((diagnostic) => ({ message: diagnostic.text, severity: severityMap[diagnostic.category as keyof typeof severityMap], location: { path: sourceFile.fileName, range: { start: { line: diagnostic.start.line, column: diagnostic.start.offset, }, end: { line: diagnostic.end.line, column: diagnostic.end.offset }, }, }, code: { value: `${diagnostic.code ?? ''}`, }, relatedInformation: diagnostic.relatedInformation?.map((info) => ({ message: info.message, severity: severityMap[info.category as keyof typeof severityMap], location: info.span != null ? { path: info.span.file, range: { start: { line: info.span.start.line, column: info.span.start.offset, }, end: { line: info.span.end.line, column: info.span.end.offset, }, }, } : undefined, code: { value: `${info.code ?? ''}`, }, })), })) }), }, null, pretty ? 2 : 0, ) } async function handleResults( result: Diagnostics, { vue, format, pretty, }: { vue: boolean pretty: boolean format: string }, ): Promise<void> { if (vue) { result = result.filter((item) => item.fileName.endsWith('.vue')) } result.forEach((sourceFile) => { sourceFile.fileName = convertToRelativePath(sourceFile.fileName) sourceFile.diagnostics.forEach((diagnostic) => { diagnostic.relatedInformation?.forEach((info) => { if (info.span != null) { info.span.file = convertToRelativePath(info.span.file) } }) }) }) switch (format) { case 'json': print(JSON.stringify(result, null, pretty ? 2 : 0)) break case 'rdjson': print(encodeRdJSON(result, pretty)) break case 'raw': { const fn = pretty ? formatDiagnosticsWithColorAndContext : formatDiagnostic const content = await Promise.all( result.flatMap((sourceFile) => sourceFile.diagnostics.map((diagnostic) => fn(sourceFile.fileName, diagnostic), ), ), ) print(content.join('\n')) const count = getErrorCount(result) print(`\nFound ${count} ${count === 1 ? 'error' : 'errors'}.`) } break default: throw new Error(`Unknown output format: "${format}"`) } }
the_stack
* @module Widget */ import * as React from "react"; import { BadgeType, ConditionalStringValue, PointProps } from "@itwin/appui-abstract"; import { BadgeUtilities, CommonProps, IconHelper, Rectangle, RectangleProps } from "@itwin/core-react"; import { DisabledResizeHandles, DraggedWidgetManagerProps, HandleMode, HorizontalAnchor, Stacked as NZ_WidgetStack, ResizeHandle, Tab, TabGroup, TabMode, TabSeparator, VerticalAnchor, VerticalAnchorHelpers, WidgetZoneId, } from "@itwin/appui-layout-react"; import { WidgetChangeHandler } from "../frontstage/FrontstageComposer"; import { UiShowHideManager } from "../utils/UiShowHideManager"; // cSpell:ignore Timedout /** Properties for a [[WidgetStack]] Tab. * @internal */ export interface WidgetTab { readonly iconSpec?: string | ConditionalStringValue | React.ReactNode; readonly title: string; readonly badgeType?: BadgeType; } /** Properties for a Widget in a [[WidgetStack]]. * @internal */ export type WidgetTabs = { readonly [id in WidgetZoneId]: ReadonlyArray<WidgetTab> }; // eslint-disable-line deprecation/deprecation /** Properties for the [[WidgetStack]] React component. * @internal */ export interface WidgetStackProps extends CommonProps { activeTabIndex: number; disabledResizeHandles: DisabledResizeHandles | undefined; draggedWidget: DraggedWidgetManagerProps | undefined; fillZone: boolean; getWidgetContentRef: (id: WidgetZoneId) => React.Ref<HTMLDivElement>; // eslint-disable-line deprecation/deprecation horizontalAnchor: HorizontalAnchor; // eslint-disable-line deprecation/deprecation isCollapsed: boolean; isFloating: boolean; isInStagePanel: boolean; openWidgetId: WidgetZoneId | undefined; // eslint-disable-line deprecation/deprecation verticalAnchor: VerticalAnchor; widgetChangeHandler: WidgetChangeHandler; // eslint-disable-line deprecation/deprecation widgets: ReadonlyArray<WidgetZoneId>; // eslint-disable-line deprecation/deprecation widgetTabs: WidgetTabs; } /** Widget stack React component. * @internal */ export class WidgetStack extends React.PureComponent<WidgetStackProps> { private _widgetStack = React.createRef<NZ_WidgetStack>(); public override render(): React.ReactNode { const tabCount = this.props.widgets.reduce((acc, widgetId) => { const tabs = this.props.widgetTabs[widgetId]; return acc + tabs.length; }, 0); if (tabCount === 0) return null; return ( <NZ_WidgetStack className={this.props.className} contentRef={this.props.openWidgetId ? this.props.getWidgetContentRef(this.props.openWidgetId) : undefined} disabledResizeHandles={this.props.disabledResizeHandles} fillZone={this.props.fillZone || this.props.isInStagePanel} horizontalAnchor={this.props.horizontalAnchor} isCollapsed={this.props.isCollapsed} isTabBarVisible={this.props.isInStagePanel} isDragged={!!this.props.draggedWidget} isFloating={this.props.isFloating} isOpen={!!this.props.openWidgetId} onMouseEnter={UiShowHideManager.handleWidgetMouseEnter} onResize={this.props.isInStagePanel ? undefined : this._handleOnWidgetResize} ref={this._widgetStack} style={this.props.style} tabs={<WidgetStackTabs activeTabIndex={this.props.activeTabIndex} draggedWidget={this.props.draggedWidget} horizontalAnchor={this.props.horizontalAnchor} isCollapsed={this.props.isCollapsed} isProtruding={!this.props.isInStagePanel} onTabClick={this._handleTabClick} onTabDrag={this._handleTabDrag} onTabDragEnd={this._handleTabDragEnd} onTabDragStart={this._handleTabDragStart} openWidgetId={this.props.openWidgetId} verticalAnchor={this.props.verticalAnchor} widgets={this.props.widgets} widgetTabs={this.props.widgetTabs} />} verticalAnchor={this.props.verticalAnchor} /> ); } private _handleOnWidgetResize = (resizeBy: number, handle: ResizeHandle, filledHeightDiff: number) => { this.props.widgetChangeHandler.handleResize(this.props.widgets[0], resizeBy, handle, filledHeightDiff); }; // eslint-disable-next-line deprecation/deprecation private _handleTabDragStart = (widgetId: WidgetZoneId, tabIndex: number, initialPosition: PointProps, firstTabBounds: RectangleProps) => { if (!this._widgetStack.current) return; const tabBounds = Rectangle.create(firstTabBounds); const stackedWidgetBounds = Rectangle.create(this._widgetStack.current.getBounds()); const offsetToFirstTab = stackedWidgetBounds.topLeft().getOffsetTo(tabBounds.topLeft()); const isHorizontal = this.props.verticalAnchor === VerticalAnchor.BottomPanel || this.props.verticalAnchor === VerticalAnchor.TopPanel; let widgetBounds; if (isHorizontal) widgetBounds = stackedWidgetBounds.offsetX(offsetToFirstTab.x); else widgetBounds = stackedWidgetBounds.offsetY(offsetToFirstTab.y); this.props.widgetChangeHandler.handleTabDragStart(widgetId, tabIndex, initialPosition, widgetBounds); }; private _handleTabDragEnd = () => { this.props.widgetChangeHandler.handleTabDragEnd(); }; // eslint-disable-next-line deprecation/deprecation private _handleTabClick = (widgetId: WidgetZoneId, tabIndex: number) => { this.props.widgetChangeHandler.handleTabClick(widgetId, tabIndex); }; private _handleTabDrag = (dragged: PointProps) => { this.props.widgetChangeHandler.handleTabDrag(dragged); }; } /** Properties for the [[WidgetStackTabs]] component. * @internal */ export interface WidgetStackTabsProps { activeTabIndex: number; draggedWidget: DraggedWidgetManagerProps | undefined; horizontalAnchor: HorizontalAnchor; // eslint-disable-line deprecation/deprecation isCollapsed: boolean; isProtruding: boolean; onTabClick: (widgetId: WidgetZoneId, tabIndex: number) => void; // eslint-disable-line deprecation/deprecation onTabDrag: (dragged: PointProps) => void; onTabDragEnd: () => void; // eslint-disable-next-line deprecation/deprecation onTabDragStart: (widgetId: WidgetZoneId, tabIndex: number, initialPosition: PointProps, firstTabBounds: RectangleProps) => void; openWidgetId: WidgetZoneId | undefined; // eslint-disable-line deprecation/deprecation verticalAnchor: VerticalAnchor; widgets: ReadonlyArray<WidgetZoneId>; // eslint-disable-line deprecation/deprecation widgetTabs: WidgetTabs; } /** Tabs of [[WidgetStack]] component. * @internal */ export class WidgetStackTabs extends React.PureComponent<WidgetStackTabsProps> { public override render(): React.ReactNode { let renderIndex = -1; return this.props.widgets.map((widgetId) => { const tabs = this.props.widgetTabs[widgetId]; if (tabs.length <= 0) return null; renderIndex++; // istanbul ignore next return ( <React.Fragment key={widgetId}> {renderIndex < 1 ? undefined : <TabSeparator isHorizontal={VerticalAnchorHelpers.isHorizontal(this.props.verticalAnchor)} />} <WidgetStackTabGroup activeTabIndex={this.props.activeTabIndex} draggedWidget={this.props.draggedWidget} horizontalAnchor={this.props.horizontalAnchor} isCollapsed={this.props.isCollapsed} isProtruding={this.props.isProtruding} isStacked={this.props.widgets.length > 1} onTabClick={this.props.onTabClick} onTabDrag={this.props.onTabDrag} onTabDragEnd={this.props.onTabDragEnd} onTabDragStart={this.props.onTabDragStart} openWidgetId={this.props.openWidgetId} tabs={tabs} verticalAnchor={this.props.verticalAnchor} widgetId={widgetId} /> </React.Fragment> ); }); } } /** Properties for the [[WidgetStackTabGroup]] component. * @internal */ export interface WidgetStackTabGroupProps { activeTabIndex: number; draggedWidget: DraggedWidgetManagerProps | undefined; horizontalAnchor: HorizontalAnchor; // eslint-disable-line deprecation/deprecation isCollapsed: boolean; isProtruding: boolean; isStacked: boolean; onTabClick: (widgetId: WidgetZoneId, tabIndex: number) => void; // eslint-disable-line deprecation/deprecation onTabDrag: (dragged: PointProps) => void; onTabDragEnd: () => void; // eslint-disable-next-line deprecation/deprecation onTabDragStart: (widgetId: WidgetZoneId, tabIndex: number, initialPosition: PointProps, firstTabBounds: RectangleProps) => void; openWidgetId: WidgetZoneId | undefined; // eslint-disable-line deprecation/deprecation tabs: ReadonlyArray<WidgetTab>; verticalAnchor: VerticalAnchor; widgetId: WidgetZoneId; // eslint-disable-line deprecation/deprecation } /** Widget tab group used in [[WidgetStackTabs]] component. * @internal */ export class WidgetStackTabGroup extends React.PureComponent<WidgetStackTabGroupProps> { private _firstTab = React.createRef<Tab>(); public override render(): React.ReactNode { const lastPosition = this.props.draggedWidget ? this.props.draggedWidget.lastPosition : undefined; const isWidgetStackOpen = !!this.props.openWidgetId; const isWidgetOpen = this.props.openWidgetId === this.props.widgetId; const tabs = this.props.tabs.map((tab, index) => { const mode = !isWidgetStackOpen ? TabMode.Closed : isWidgetOpen && this.props.activeTabIndex === index ? TabMode.Active : TabMode.Open; return ( <WidgetStackTab horizontalAnchor={this.props.horizontalAnchor} iconSpec={tab.iconSpec} index={index} badgeType={tab.badgeType} isCollapsed={this.props.isCollapsed} isProtruding={this.props.isProtruding} key={`${this.props.widgetId}-${index}`} lastPosition={lastPosition} mode={mode} onClick={this._handleTabClick} onDrag={this.props.onTabDrag} onDragEnd={this.props.onTabDragEnd} onDragStart={this._handleTabDragStart} tabRef={index === 0 ? this._firstTab : undefined} title={tab.title} verticalAnchor={this.props.verticalAnchor} /> ); }); if (tabs.length > 1) { return ( <TabGroup handle={this.getTabHandleMode()} horizontalAnchor={this.props.horizontalAnchor} isCollapsed={this.props.isCollapsed} verticalAnchor={this.props.verticalAnchor} > {tabs} </TabGroup> ); } return tabs; } private getTabHandleMode() { if (this.props.draggedWidget && this.props.draggedWidget.id === this.props.widgetId && this.props.draggedWidget.isUnmerge) return HandleMode.Visible; if (this.props.isStacked) return HandleMode.Hovered; return HandleMode.Timedout; } private _handleTabDragStart = (tabIndex: number, initialPosition: PointProps) => { if (!this._firstTab.current) return; const firstTabBounds = Rectangle.create(this._firstTab.current.getBounds()).toProps(); this.props.onTabDragStart(this.props.widgetId, tabIndex, initialPosition, firstTabBounds); }; private _handleTabClick = (tabIndex: number) => { this.props.onTabClick(this.props.widgetId, tabIndex); }; } /** Properties for the [[WidgetStackTab]] component. * @internal */ export interface WidgetStackTabProps { horizontalAnchor: HorizontalAnchor; // eslint-disable-line deprecation/deprecation iconSpec?: string | ConditionalStringValue | React.ReactNode; index: number; badgeType?: BadgeType; isCollapsed: boolean; isProtruding: boolean; lastPosition: PointProps | undefined; mode: TabMode; onClick: (index: number) => void; onDrag: (dragged: PointProps) => void; onDragEnd: () => void; onDragStart: (index: number, initialPosition: PointProps) => void; tabRef?: React.Ref<Tab>; title: string; verticalAnchor: VerticalAnchor; } /** Tab used in [[WidgetStackTabGroup]] component. * @internal */ export class WidgetStackTab extends React.PureComponent<WidgetStackTabProps> { public override render(): React.ReactNode { return ( <Tab badge={BadgeUtilities.getComponentForBadgeType(this.props.badgeType)} horizontalAnchor={this.props.horizontalAnchor} isCollapsed={this.props.isCollapsed} isProtruding={this.props.isProtruding} lastPosition={this.props.lastPosition} mode={this.props.mode} onClick={this._handleClick} onDrag={this.props.onDrag} onDragEnd={this.props.onDragEnd} onDragStart={this._handleDragStart} ref={this.props.tabRef} title={this.props.title} verticalAnchor={this.props.verticalAnchor} > {IconHelper.getIconReactNode(this.props.iconSpec)} </Tab> ); } private _handleDragStart = (initialPosition: PointProps) => { this.props.onDragStart(this.props.index, initialPosition); }; private _handleClick = () => { this.props.onClick(this.props.index); }; }
the_stack
import debounce from 'lodash/debounce'; import type vscode from 'vscode'; import { IRPCProtocol } from '@opensumi/ide-connection'; import { ISelection, Emitter, Event, IRange, getDebugLogger, Disposable } from '@opensumi/ide-core-common'; import { ISingleEditOperation, IDecorationApplyOptions, IResourceOpenOptions } from '@opensumi/ide-editor'; import { IExtensionHostEditorService, ExtensionDocumentDataManager, MainThreadAPIIdentifier, } from '../../../../common/vscode'; import * as TypeConverts from '../../../../common/vscode/converter'; import { IEditorStatusChangeDTO, IEditorChangeDTO, TextEditorSelectionChangeKind, IEditorCreatedDTO, IResolvedTextEditorConfiguration, IMainThreadEditorsService, ITextEditorUpdateConfiguration, TextEditorCursorStyle, } from '../../../../common/vscode/editor'; import { Uri, Position, Range, Selection, TextEditorLineNumbersStyle } from '../../../../common/vscode/ext-types'; import { TextEditorEdit } from './edit.builder'; export class ExtensionHostEditorService implements IExtensionHostEditorService { private _editors: Map<string, TextEditorData> = new Map(); private _activeEditorId: string | undefined; private decorationIdCount = 0; public readonly _onDidChangeActiveTextEditor: Emitter<vscode.TextEditor | undefined> = new Emitter(); public readonly _onDidChangeVisibleTextEditors: Emitter<vscode.TextEditor[]> = new Emitter(); public readonly _onDidChangeTextEditorSelection: Emitter<vscode.TextEditorSelectionChangeEvent> = new Emitter(); public readonly _onDidChangeTextEditorVisibleRanges: Emitter<vscode.TextEditorVisibleRangesChangeEvent> = new Emitter(); public readonly _onDidChangeTextEditorOptions: Emitter<vscode.TextEditorOptionsChangeEvent> = new Emitter(); public readonly _onDidChangeTextEditorViewColumn: Emitter<vscode.TextEditorViewColumnChangeEvent> = new Emitter(); public readonly onDidChangeActiveTextEditor: Event<vscode.TextEditor | undefined> = this._onDidChangeActiveTextEditor.event; public readonly onDidChangeVisibleTextEditors: Event<vscode.TextEditor[]> = this._onDidChangeVisibleTextEditors.event; public readonly onDidChangeTextEditorSelection: Event<vscode.TextEditorSelectionChangeEvent> = this._onDidChangeTextEditorSelection.event; public readonly onDidChangeTextEditorVisibleRanges: Event<vscode.TextEditorVisibleRangesChangeEvent> = this._onDidChangeTextEditorVisibleRanges.event; public readonly onDidChangeTextEditorOptions: Event<vscode.TextEditorOptionsChangeEvent> = this._onDidChangeTextEditorOptions.event; public readonly onDidChangeTextEditorViewColumn: Event<vscode.TextEditorViewColumnChangeEvent> = this._onDidChangeTextEditorViewColumn.event; public readonly _proxy: IMainThreadEditorsService; private _onEditorCreated: Emitter<string> = new Emitter(); private onEditorCreated: Event<string> = this._onEditorCreated.event; constructor(rpcProtocol: IRPCProtocol, public readonly documents: ExtensionDocumentDataManager) { this._proxy = rpcProtocol.getProxy(MainThreadAPIIdentifier.MainThreadEditors); // this._proxy.$getInitialState().then((change) => { // console.log('$getInitialState', change); // this.$acceptChange(change); // }); } $acceptChange(change: IEditorChangeDTO) { if (change.created) { change.created.forEach((created) => { this._editors.set(created.id, new TextEditorData(created, this, this.documents)); this._onEditorCreated.fire(created.id); if (!change.actived && created.id === this._activeEditorId) { if (this.activeEditor) { this._onDidChangeActiveTextEditor.fire(this.activeEditor ? this.activeEditor!.textEditor : undefined); } } }); } if (change.removed) { change.removed.forEach((id) => { this._editors.delete(id); }); } if (change.actived) { if (change.actived === '-1') { this._activeEditorId = undefined; this._onDidChangeActiveTextEditor.fire(undefined); } else { this._activeEditorId = change.actived; if (this.activeEditor) { this._onDidChangeActiveTextEditor.fire(this.activeEditor ? this.activeEditor!.textEditor : undefined); } } } if (change.created || change.removed) { this._onDidChangeVisibleTextEditors.fire(this.visibleEditors); } } async openResource(uri: Uri, options: IResourceOpenOptions): Promise<vscode.TextEditor> { const id = await this._proxy.$openResource(uri.toString(), options); if (this.getEditor(id)) { return this.getEditor(id)!.textEditor; } else { return new Promise((resolve, reject) => { let resolved = false; const disposer = this.onEditorCreated((created) => { if (created === id && this.getEditor(id)) { resolve(this.getEditor(id)!.textEditor); resolved = true; disposer.dispose(); } }); setTimeout(() => { if (!resolved) { reject(new Error(`Timout opening textDocument uri ${uri.toString()}`)); } }, 5000); }); } } async showTextDocument( documentOrUri: vscode.TextDocument | Uri, columnOrOptions?: vscode.ViewColumn | vscode.TextDocumentShowOptions, preserveFocus?: boolean, ): Promise<vscode.TextEditor> { let uri: Uri; if (Uri.isUri(documentOrUri)) { uri = documentOrUri; } else { uri = documentOrUri.uri; } let options: IResourceOpenOptions; if (typeof columnOrOptions === 'number') { options = { ...TypeConverts.viewColumnToResourceOpenOptions(columnOrOptions), preserveFocus, }; } else if (typeof columnOrOptions === 'object') { options = { ...TypeConverts.viewColumnToResourceOpenOptions(columnOrOptions.viewColumn), preserveFocus: columnOrOptions.preserveFocus, range: typeof columnOrOptions.selection === 'object' ? TypeConverts.Range.from(columnOrOptions.selection) : undefined, preview: typeof columnOrOptions.preview === 'boolean' ? columnOrOptions.preview : undefined, }; } else { options = { preserveFocus: false, }; } return this.openResource(uri, options); } $acceptPropertiesChange(change: IEditorStatusChangeDTO) { if (this._editors.get(change.id)) { this._editors.get(change.id)!.acceptStatusChange(change); } } getEditor(id: string): TextEditorData | undefined { return this._editors.get(id); } get activeEditor(): TextEditorData | undefined { if (!this._activeEditorId) { return undefined; } else { return this._editors.get(this._activeEditorId); } } get visibleEditors(): vscode.TextEditor[] { return Array.from(this._editors.values()).map((e) => e.textEditor); } closeEditor(editor: TextEditorData): void { if (editor.id !== this._activeEditorId) { return; } this._proxy.$closeEditor(editor.id); } getNextId() { this.decorationIdCount++; return 'textEditor-decoration-' + this.decorationIdCount; } createTextEditorDecorationType( extensionId: string, options: vscode.DecorationRenderOptions, ): vscode.TextEditorDecorationType { const resolved = TypeConverts.DecorationRenderOptions.from(options); // 添加 extensionId 以更好定位是哪个插件创建的decoration const key = extensionId.replace(/\./g, '-') + '-' + this.getNextId(); this._proxy.$createTextEditorDecorationType(key, resolved); return new ExtHostTextEditorDecorationType(key, this._proxy); } getDiffInformation(id: string): Promise<vscode.LineChange[]> { return Promise.resolve(this._proxy.$getDiffInformation(id)); } } export class ExtHostTextEditorDecorationType extends Disposable implements vscode.TextEditorDecorationType { constructor(public readonly key: string, _proxy: IMainThreadEditorsService) { super(); this.addDispose({ dispose: () => { _proxy.$deleteTextEditorDecorationType(key); }, }); } } export class TextEditorData { public readonly id: string; public readonly group: string; constructor( created: IEditorCreatedDTO, public readonly editorService: ExtensionHostEditorService, public readonly documents: ExtensionDocumentDataManager, ) { this.uri = Uri.parse(created.uri); this.id = created.id; this._acceptSelections(created.selections); this._acceptVisibleRanges(created.visibleRanges); this._acceptViewColumn(created.viewColumn); this.options = new ExtHostTextEditorOptions(this.editorService._proxy, this.id, created.options); } readonly uri: Uri; selections: vscode.Selection[]; visibleRanges: vscode.Range[]; options: ExtHostTextEditorOptions; viewColumn?: vscode.ViewColumn | undefined; private _textEditor: vscode.TextEditor; edit( callback: (editBuilder: vscode.TextEditorEdit) => void, options: { undoStopBefore: boolean; undoStopAfter: boolean } = { undoStopBefore: true, undoStopAfter: true }, ): Promise<boolean> { const document = this.documents.getDocument(this.uri); if (!document) { throw new Error('document not found when editing'); } const edit = new TextEditorEdit(document, options); callback(edit); return this._applyEdit(edit); } private _applyEdit(editBuilder: TextEditorEdit): Promise<boolean> { const editData = editBuilder.finalize(); // return when there is nothing to do if (editData.edits.length === 0 && !editData.setEndOfLine) { return Promise.resolve(true); } // check that the edits are not overlapping (i.e. illegal) const editRanges = editData.edits.map((edit) => edit.range); // sort ascending (by end and then by start) editRanges.sort((a, b) => { if (a.end.line === b.end.line) { if (a.end.character === b.end.character) { if (a.start.line === b.start.line) { return a.start.character - b.start.character; } return a.start.line - b.start.line; } return a.end.character - b.end.character; } return a.end.line - b.end.line; }); // check that no edits are overlapping for (let i = 0, count = editRanges.length - 1; i < count; i++) { const rangeEnd = editRanges[i].end; const nextRangeStart = editRanges[i + 1].start; if (nextRangeStart.isBefore(rangeEnd)) { // overlapping ranges return Promise.reject(new Error('Overlapping ranges are not allowed!')); } } // prepare data for serialization const edits = editData.edits.map( (edit): ISingleEditOperation => ({ range: TypeConverts.Range.from(edit.range), text: edit.text, forceMoveMarkers: edit.forceMoveMarkers, }), ); return this.editorService._proxy.$applyEdits(this.id, editData.documentVersionId, edits, { setEndOfLine: typeof editData.setEndOfLine === 'number' ? TypeConverts.EndOfLine.from(editData.setEndOfLine) : undefined, undoStopBefore: editData.undoStopBefore, undoStopAfter: editData.undoStopAfter, }); } async insertSnippet( snippet: vscode.SnippetString, location?: Range | Position | Position[] | Range[] | undefined, options?: { undoStopBefore: boolean; undoStopAfter: boolean } | undefined, ): Promise<boolean> { try { let _location: IRange[] = []; if (!location || (Array.isArray(location) && location.length === 0)) { _location = this.selections.map((s) => TypeConverts.Range.from(s)); } else if (location instanceof Position) { const { lineNumber, column } = TypeConverts.fromPosition(location); _location = [ { startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column }, ]; } else if (location instanceof Range) { _location = [TypeConverts.Range.from(location)!]; } else { _location = []; for (const posOrRange of location) { if (posOrRange instanceof Range) { _location.push(TypeConverts.Range.from(posOrRange)!); } else { const { lineNumber, column } = TypeConverts.fromPosition(posOrRange); _location.push({ startLineNumber: lineNumber, startColumn: column, endLineNumber: lineNumber, endColumn: column, }); } } } this.editorService._proxy.$insertSnippet(this.id, snippet.value, _location, options); return true; } catch (e) { getDebugLogger().error(e); return false; } } setDecorations( decorationType: ExtHostTextEditorDecorationType, rangesOrOptions: vscode.Range[] | vscode.DecorationOptions[], ): void { if (decorationType.disposed) { getDebugLogger().warn(`decorationType with key ${decorationType.key} has been disposed!`); return; } let resolved: IDecorationApplyOptions[] = []; if (rangesOrOptions.length !== 0) { if (Range.isRange(rangesOrOptions[0])) { resolved = (rangesOrOptions as vscode.Range[]).map((r) => ({ range: TypeConverts.Range.from(r), })); } else if (Range.isRange((rangesOrOptions[0]! as any).range)) { resolved = (rangesOrOptions as vscode.DecorationOptions[]).map((r) => ({ range: TypeConverts.Range.from(r.range), renderOptions: r.renderOptions ? TypeConverts.DecorationRenderOptions.from(r.renderOptions) : undefined, hoverMessage: r.hoverMessage as any, })); } } this.editorService._proxy.$applyDecoration(this.id, decorationType.key, resolved); } revealRange(range: vscode.Range, revealType?: vscode.TextEditorRevealType | undefined): void { this.editorService._proxy.$revealRange(this.id, TypeConverts.Range.from(range), revealType); } show(column?: vscode.ViewColumn | undefined): void { getDebugLogger().warn('TextEditor.show is Deprecated'); } hide(): void { this.editorService.closeEditor(this); } _acceptSelections(selections: ISelection[] = []) { this.selections = selections.map((selection) => TypeConverts.Selection.to(selection)); } _acceptOptions(options: IResolvedTextEditorConfiguration) { this.options._accept(options); } _acceptVisibleRanges(value: IRange[]): void { this.visibleRanges = value.map((v) => TypeConverts.Range.to(v)).filter((v) => !!v) as vscode.Range[]; } _acceptViewColumn(value: number): void { this.viewColumn = value; } acceptStatusChange(change: IEditorStatusChangeDTO) { if (change.selections) { this._acceptSelections(change.selections.selections); this.editorService._onDidChangeTextEditorSelection.fire({ kind: TextEditorSelectionChangeKind.fromValue(change.selections.source), selections: this.selections, textEditor: this.textEditor, }); } if (change.options) { this._acceptOptions(change.options); this.editorService._onDidChangeTextEditorOptions.fire({ textEditor: this.textEditor, options: this.options, }); } if (change.visibleRanges) { this._acceptVisibleRanges(change.visibleRanges); this.editorService._onDidChangeTextEditorVisibleRanges.fire({ textEditor: this.textEditor, visibleRanges: this.visibleRanges, }); } if (change.viewColumn) { this._acceptViewColumn(change.viewColumn); this.editorService._onDidChangeTextEditorViewColumn.fire({ textEditor: this.textEditor, viewColumn: this.viewColumn!, }); } } public doSetSelection: () => void = debounce( () => { this.editorService._proxy.$setSelections( this.id, this.selections.map((selection) => TypeConverts.Selection.from(selection)), ); }, 50, { maxWait: 200, leading: true, trailing: true }, ); get textEditor(): vscode.TextEditor { if (!this._textEditor) { const data = this; this._textEditor = { // vscode 有这个属性,但是接口未定义 get id() { return data.id; }, get document() { return data.documents.getDocument(data.uri)!; }, set selection(val) { data.selections = [val]; data.doSetSelection(); }, get selections() { return data.selections; }, set selections(val) { data.selections = val; data.editorService._proxy.$setSelections( data.id, data.selections.map((selection) => TypeConverts.Selection.from(selection)), ); }, get selection() { return data.selections && data.selections[0]; }, get options() { return data.options; }, get visibleRanges() { return data.visibleRanges; }, get viewColumn() { return data.viewColumn; }, set options(value: vscode.TextEditorOptions) { data.options.assign(value); // }, edit: data.edit.bind(data), insertSnippet: data.insertSnippet.bind(data), setDecorations: data.setDecorations.bind(data), revealRange: data.revealRange.bind(data), show: data.show.bind(data), hide: data.hide.bind(data), } as vscode.TextEditor; } return this._textEditor; } } export function toIRange(range: vscode.Range | vscode.Selection | vscode.Position): IRange { if (Range.isRange(range)) { // vscode.Range return TypeConverts.Range.from(range); } else if (Selection.isSelection(range)) { // vscode.Selection const r = range as vscode.Selection; if (r.active.isBeforeOrEqual(r.anchor)) { return { startLineNumber: r.active.line + 1, startColumn: r.active.character + 1, endLineNumber: r.anchor.line + 1, endColumn: r.anchor.character + 1, }; } else { return { startLineNumber: r.anchor.line + 1, startColumn: r.anchor.character + 1, endLineNumber: r.active.line + 1, endColumn: r.active.character + 1, }; } } else if (Position.isPosition(range)) { const r = range as vscode.Position; return { startLineNumber: r.line + 1, startColumn: r.character + 1, endLineNumber: r.line + 1, endColumn: r.character + 1, }; } return { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1, }; } export class ExtHostTextEditorOptions implements vscode.TextEditorOptions { private _proxy: IMainThreadEditorsService; private _id: string; private _tabSize: number; private _indentSize: number; private _insertSpaces: boolean; private _cursorStyle: TextEditorCursorStyle; private _lineNumbers: TextEditorLineNumbersStyle; constructor(proxy: IMainThreadEditorsService, id: string, source: IResolvedTextEditorConfiguration) { this._proxy = proxy; this._id = id; this._accept(source); } public _accept(source: IResolvedTextEditorConfiguration): void { this._tabSize = source.tabSize; this._indentSize = source.indentSize; this._insertSpaces = source.insertSpaces; this._cursorStyle = source.cursorStyle; this._lineNumbers = TypeConverts.TextEditorLineNumbersStyle.to(source.lineNumbers); } public get tabSize(): number | string { return this._tabSize; } public set tabSize(value: number | string) { const tabSize = this._validateTabSize(value); if (tabSize === null) { // ignore invalid call return; } if (typeof tabSize === 'number') { if (this._tabSize === tabSize) { // nothing to do return; } // reflect the new tabSize value immediately this._tabSize = tabSize; } this._proxy.$updateOptions(this._id, { tabSize, }); } private _validateTabSize(value: number | string): number | 'auto' | null { if (value === 'auto') { return 'auto'; } if (typeof value === 'number') { const r = Math.floor(value); return r > 0 ? r : null; } if (typeof value === 'string') { const r = parseInt(value, 10); if (isNaN(r)) { return null; } return r > 0 ? r : null; } return null; } public get indentSize(): number | string { return this._indentSize; } public set indentSize(value: number | string) { const indentSize = this._validateIndentSize(value); if (indentSize === null) { // ignore invalid call return; } if (typeof indentSize === 'number') { if (this._indentSize === indentSize) { // nothing to do return; } // reflect the new indentSize value immediately this._indentSize = indentSize; } this._proxy.$updateOptions(this._id, { indentSize, }); } private _validateIndentSize(value: number | string): number | 'tabSize' | null { if (value === 'tabSize') { return 'tabSize'; } if (typeof value === 'number') { const r = Math.floor(value); return r > 0 ? r : null; } if (typeof value === 'string') { const r = parseInt(value, 10); if (isNaN(r)) { return null; } return r > 0 ? r : null; } return null; } public get insertSpaces(): boolean | string { return this._insertSpaces; } public set insertSpaces(value: boolean | string) { const insertSpaces = this._validateInsertSpaces(value); if (typeof insertSpaces === 'boolean') { if (this._insertSpaces === insertSpaces) { // nothing to do return; } // reflect the new insertSpaces value immediately this._insertSpaces = insertSpaces; } this._proxy.$updateOptions(this._id, { insertSpaces, }); } private _validateInsertSpaces(value: boolean | string): boolean | 'auto' { if (value === 'auto') { return 'auto'; } return value === 'false' ? false : Boolean(value); } public get cursorStyle(): TextEditorCursorStyle { return this._cursorStyle; } public set cursorStyle(value: TextEditorCursorStyle) { if (this._cursorStyle === value) { // nothing to do return; } this._cursorStyle = value; this._proxy.$updateOptions(this._id, { cursorStyle: value, }); } public get lineNumbers(): TextEditorLineNumbersStyle { return this._lineNumbers; } public set lineNumbers(value: TextEditorLineNumbersStyle) { if (this._lineNumbers === value) { // nothing to do return; } this._lineNumbers = value; this._proxy.$updateOptions(this._id, { lineNumbers: TypeConverts.TextEditorLineNumbersStyle.from(value), }); } public assign(newOptions: vscode.TextEditorOptions) { const bulkConfigurationUpdate: ITextEditorUpdateConfiguration = {}; let hasUpdate = false; if (typeof newOptions.tabSize !== 'undefined') { const tabSize = this._validateTabSize(newOptions.tabSize); if (tabSize === 'auto') { hasUpdate = true; bulkConfigurationUpdate.tabSize = tabSize; } else if (typeof tabSize === 'number' && this._tabSize !== tabSize) { // reflect the new tabSize value immediately this._tabSize = tabSize; hasUpdate = true; bulkConfigurationUpdate.tabSize = tabSize; } } // if (typeof newOptions.indentSize !== 'undefined') { // const indentSize = this._validateIndentSize(newOptions.indentSize); // if (indentSize === 'tabSize') { // hasUpdate = true; // bulkConfigurationUpdate.indentSize = indentSize; // } else if (typeof indentSize === 'number' && this._indentSize !== indentSize) { // // reflect the new indentSize value immediately // this._indentSize = indentSize; // hasUpdate = true; // bulkConfigurationUpdate.indentSize = indentSize; // } // } if (typeof newOptions.insertSpaces !== 'undefined') { const insertSpaces = this._validateInsertSpaces(newOptions.insertSpaces); if (insertSpaces === 'auto') { hasUpdate = true; bulkConfigurationUpdate.insertSpaces = insertSpaces; } else if (this._insertSpaces !== insertSpaces) { // reflect the new insertSpaces value immediately this._insertSpaces = insertSpaces; hasUpdate = true; bulkConfigurationUpdate.insertSpaces = insertSpaces; } } if (typeof newOptions.cursorStyle !== 'undefined') { if (this._cursorStyle !== newOptions.cursorStyle) { this._cursorStyle = newOptions.cursorStyle; hasUpdate = true; bulkConfigurationUpdate.cursorStyle = newOptions.cursorStyle; } } if (typeof newOptions.lineNumbers !== 'undefined') { if (this._lineNumbers !== newOptions.lineNumbers) { this._lineNumbers = newOptions.lineNumbers; hasUpdate = true; bulkConfigurationUpdate.lineNumbers = TypeConverts.TextEditorLineNumbersStyle.from(newOptions.lineNumbers); } } if (hasUpdate) { this._proxy.$updateOptions(this._id, bulkConfigurationUpdate); } } }
the_stack
import * as React from 'react'; import { GridEvents } from '../../../constants/eventsConstants'; import { GridComponentProps } from '../../../GridComponentProps'; import { GridApiRef } from '../../../models/api/gridApiRef'; import { GridSelectionApi } from '../../../models/api/gridSelectionApi'; import { GridRowParams } from '../../../models/params/gridRowParams'; import { GridRowId } from '../../../models/gridRows'; import { useGridApiEventHandler } from '../../utils/useGridApiEventHandler'; import { useGridApiMethod } from '../../utils/useGridApiMethod'; import { useGridLogger } from '../../utils/useGridLogger'; import { useGridState } from '../../utils/useGridState'; import { gridRowsLookupSelector } from '../rows/gridRowsSelector'; import { gridSelectionStateSelector, selectedGridRowsSelector, selectedIdsLookupSelector, } from './gridSelectionSelector'; import { gridPaginatedVisibleSortedGridRowIdsSelector } from '../pagination'; import { visibleSortedGridRowIdsSelector } from '../filter/gridFilterSelector'; import { GridHeaderSelectionCheckboxParams } from '../../../models/params/gridHeaderSelectionCheckboxParams'; import { GridCellParams } from '../../../models/params/gridCellParams'; import { GridRowSelectionCheckboxParams } from '../../../models/params/gridRowSelectionCheckboxParams'; import { GridColumnsPreProcessing } from '../../core/columnsPreProcessing'; import { GRID_CHECKBOX_SELECTION_COL_DEF, GridColDef } from '../../../models'; import { composeClasses } from '../../../utils/material-ui-utils'; import { getDataGridUtilityClass } from '../../../gridClasses'; import { useGridStateInit } from '../../utils/useGridStateInit'; import { useFirstRender } from '../../utils/useFirstRender'; type OwnerState = { classes: GridComponentProps['classes'] }; const useUtilityClasses = (ownerState: OwnerState) => { const { classes } = ownerState; return React.useMemo(() => { const slots = { cellCheckbox: ['cellCheckbox'], columnHeaderCheckbox: ['columnHeaderCheckbox'], }; return composeClasses(slots, getDataGridUtilityClass, classes); }, [classes]); }; /** * @requires useGridRows (state, method) * @requires useGridParamsApi (method) * @requires useGridControlState (method) */ export const useGridSelection = ( apiRef: GridApiRef, props: Pick< GridComponentProps, | 'checkboxSelection' | 'selectionModel' | 'onSelectionModelChange' | 'disableMultipleSelection' | 'disableSelectionOnClick' | 'isRowSelectable' | 'checkboxSelectionVisibleOnly' | 'pagination' | 'classes' >, ): void => { const logger = useGridLogger(apiRef, 'useGridSelection'); const propSelectionModel = React.useMemo(() => { if (props.selectionModel == null) { return props.selectionModel; } if (Array.isArray(props.selectionModel)) { return props.selectionModel; } return [props.selectionModel]; }, [props.selectionModel]); useGridStateInit(apiRef, (state) => ({ ...state, selection: propSelectionModel ?? [] })); const [, setGridState, forceUpdate] = useGridState(apiRef); const ownerState = { classes: props.classes }; const classes = useUtilityClasses(ownerState); const lastRowToggled = React.useRef<GridRowId | null>(null); apiRef.current.updateControlState({ stateId: 'selection', propModel: propSelectionModel, propOnChange: props.onSelectionModelChange, stateSelector: gridSelectionStateSelector, changeEvent: GridEvents.selectionChange, }); const { checkboxSelection, disableMultipleSelection, disableSelectionOnClick, isRowSelectable } = props; const canHaveMultipleSelection = !disableMultipleSelection || checkboxSelection; const getSelectedRows = React.useCallback<GridSelectionApi['getSelectedRows']>( () => selectedGridRowsSelector(apiRef.current.state), [apiRef], ); const selectRow = React.useCallback<GridSelectionApi['selectRow']>( (id, isSelected = true, resetSelection = false) => { if (isRowSelectable && !isRowSelectable(apiRef.current.getRowParams(id))) { return; } lastRowToggled.current = id; if (resetSelection) { logger.debug(`Setting selection for row ${id}`); apiRef.current.setSelectionModel(isSelected ? [id] : []); } else { logger.debug(`Toggling selection for row ${id}`); const selection = gridSelectionStateSelector(apiRef.current.state); const newSelection: GridRowId[] = selection.filter((el) => el !== id); if (isSelected) { newSelection.push(id); } const isSelectionValid = newSelection.length < 2 || canHaveMultipleSelection; if (isSelectionValid) { apiRef.current.setSelectionModel(newSelection); } } }, [apiRef, isRowSelectable, logger, canHaveMultipleSelection], ); const selectRows = React.useCallback<GridSelectionApi['selectRows']>( (ids: GridRowId[], isSelected = true, resetSelection = false) => { logger.debug(`Setting selection for several rows`); const selectableIds = isRowSelectable ? ids.filter((id) => isRowSelectable(apiRef.current.getRowParams(id))) : ids; let newSelection: GridRowId[]; if (resetSelection) { newSelection = isSelected ? selectableIds : []; } else { // We clone the existing object to avoid mutating the same object returned by the selector to others part of the project const selectionLookup = { ...selectedIdsLookupSelector(apiRef.current.state) }; selectableIds.forEach((id) => { if (isSelected) { selectionLookup[id] = id; } else { delete selectionLookup[id]; } }); newSelection = Object.values(selectionLookup); } const isSelectionValid = newSelection.length < 2 || canHaveMultipleSelection; if (isSelectionValid) { apiRef.current.setSelectionModel(newSelection); } }, [apiRef, isRowSelectable, logger, canHaveMultipleSelection], ); const selectRowRange = React.useCallback<GridSelectionApi['selectRowRange']>( ( { startId, endId, }: { startId: GridRowId; endId: GridRowId; }, isSelected = true, resetSelection, ) => { if (!apiRef.current.getRow(startId) || !apiRef.current.getRow(endId)) { return; } logger.debug(`Expanding selection from row ${startId} to row ${endId}`); const visibleRowIds = visibleSortedGridRowIdsSelector(apiRef.current.state); const startIndex = visibleRowIds.indexOf(startId); const endIndex = visibleRowIds.indexOf(endId); const [start, end] = startIndex > endIndex ? [endIndex, startIndex] : [startIndex, endIndex]; const rowsBetweenStartAndEnd = visibleRowIds.slice(start, end + 1); apiRef.current.selectRows(rowsBetweenStartAndEnd, isSelected, resetSelection); }, [apiRef, logger], ); const expandRowRangeSelection = React.useCallback( (id: GridRowId) => { let endId = id; const startId = lastRowToggled.current ?? id; const isSelected = apiRef.current.isRowSelected(id); if (isSelected) { const visibleRowIds = visibleSortedGridRowIdsSelector(apiRef.current.state); const startIndex = visibleRowIds.findIndex((rowId) => rowId === startId); const endIndex = visibleRowIds.findIndex((rowId) => rowId === endId); if (startIndex > endIndex) { endId = visibleRowIds[endIndex + 1]; } else { endId = visibleRowIds[endIndex - 1]; } } lastRowToggled.current = id; apiRef.current.selectRowRange({ startId, endId }, !isSelected); }, [apiRef], ); const setSelectionModel = React.useCallback<GridSelectionApi['setSelectionModel']>( (model) => { const currentModel = gridSelectionStateSelector(apiRef.current.state); if (currentModel !== model) { logger.debug(`Setting selection model`); setGridState((state) => ({ ...state, selection: model })); forceUpdate(); } }, [apiRef, setGridState, forceUpdate, logger], ); const isRowSelected = React.useCallback<GridSelectionApi['isRowSelected']>( (id) => gridSelectionStateSelector(apiRef.current.state).includes(id), [apiRef], ); const removeOutdatedSelection = React.useCallback(() => { const currentSelection = gridSelectionStateSelector(apiRef.current.state); const rowsLookup = gridRowsLookupSelector(apiRef.current.state); // We clone the existing object to avoid mutating the same object returned by the selector to others part of the project const selectionLookup = { ...selectedIdsLookupSelector(apiRef.current.state) }; let hasChanged = false; currentSelection.forEach((id: GridRowId) => { if (!rowsLookup[id]) { delete selectionLookup[id]; hasChanged = true; } }); if (hasChanged) { apiRef.current.setSelectionModel(Object.values(selectionLookup)); } }, [apiRef]); const handleRowClick = React.useCallback( (params: GridRowParams, event: React.MouseEvent) => { if (disableSelectionOnClick) { return; } const hasCtrlKey = event.metaKey || event.ctrlKey; if (event.shiftKey && (canHaveMultipleSelection || checkboxSelection)) { expandRowRangeSelection(params.id); } else { // Without checkboxSelection, multiple selection is only allowed if CTRL is pressed const isMultipleSelectionDisabled = !checkboxSelection && !hasCtrlKey; const resetSelection = !canHaveMultipleSelection || isMultipleSelectionDisabled; if (resetSelection) { apiRef.current.selectRow( params.id, hasCtrlKey || checkboxSelection ? !apiRef.current.isRowSelected(params.id) : true, true, ); } else { apiRef.current.selectRow(params.id, !apiRef.current.isRowSelected(params.id), false); } } }, [ apiRef, expandRowRangeSelection, canHaveMultipleSelection, disableSelectionOnClick, checkboxSelection, ], ); const preventSelectionOnShift = React.useCallback( (params: GridCellParams, event: React.MouseEvent) => { if (canHaveMultipleSelection && event.shiftKey) { window.getSelection()?.removeAllRanges(); } }, [canHaveMultipleSelection], ); const handleRowSelectionCheckboxChange = React.useCallback( (params: GridRowSelectionCheckboxParams, event: React.ChangeEvent) => { if ((event.nativeEvent as any).shiftKey) { expandRowRangeSelection(params.id); } else { apiRef.current.selectRow(params.id, params.value); } }, [apiRef, expandRowRangeSelection], ); const handleHeaderSelectionCheckboxChange = React.useCallback( (params: GridHeaderSelectionCheckboxParams) => { const shouldLimitSelectionToCurrentPage = props.checkboxSelectionVisibleOnly && props.pagination; const rowsToBeSelected = shouldLimitSelectionToCurrentPage ? gridPaginatedVisibleSortedGridRowIdsSelector(apiRef.current.state) : visibleSortedGridRowIdsSelector(apiRef.current.state); apiRef.current.selectRows(rowsToBeSelected, params.value); }, [apiRef, props.checkboxSelectionVisibleOnly, props.pagination], ); useGridApiEventHandler(apiRef, GridEvents.visibleRowsSet, removeOutdatedSelection); useGridApiEventHandler(apiRef, GridEvents.rowClick, handleRowClick); useGridApiEventHandler( apiRef, GridEvents.rowSelectionCheckboxChange, handleRowSelectionCheckboxChange, ); useGridApiEventHandler( apiRef, GridEvents.headerSelectionCheckboxChange, handleHeaderSelectionCheckboxChange, ); useGridApiEventHandler(apiRef, GridEvents.cellMouseDown, preventSelectionOnShift); const selectionApi: GridSelectionApi = { selectRow, selectRows, selectRowRange, setSelectionModel, getSelectedRows, isRowSelected, }; useGridApiMethod(apiRef, selectionApi, 'GridSelectionApi'); React.useEffect(() => { if (propSelectionModel !== undefined) { apiRef.current.setSelectionModel(propSelectionModel); } }, [apiRef, propSelectionModel]); const isStateControlled = propSelectionModel != null; React.useEffect(() => { if (isStateControlled) { return; } // isRowSelectable changed const currentSelection = gridSelectionStateSelector(apiRef.current.state); if (isRowSelectable) { const newSelection = currentSelection.filter((id) => isRowSelectable(apiRef.current.getRowParams(id)), ); if (newSelection.length < currentSelection.length) { apiRef.current.setSelectionModel(newSelection); } } }, [apiRef, isRowSelectable, isStateControlled]); const updateColumnsPreProcessing = React.useCallback(() => { const addCheckboxColumn: GridColumnsPreProcessing = (columns) => { if (!props.checkboxSelection) { return columns; } const groupingColumn: GridColDef = { ...GRID_CHECKBOX_SELECTION_COL_DEF, cellClassName: classes.cellCheckbox, headerClassName: classes.columnHeaderCheckbox, headerName: apiRef.current.getLocaleText('checkboxSelectionHeaderName'), }; return [groupingColumn, ...columns]; }; apiRef.current.UNSTABLE_registerColumnPreProcessing('selection', addCheckboxColumn); }, [apiRef, props.checkboxSelection, classes]); useFirstRender(() => { updateColumnsPreProcessing(); }); const isFirstRender = React.useRef(true); React.useEffect(() => { if (isFirstRender.current) { isFirstRender.current = false; return; } updateColumnsPreProcessing(); }, [updateColumnsPreProcessing]); };
the_stack
import { IBounds, PredictionTypes } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { AccessibleChart, chartColors } from "@responsible-ai/mlchartlib"; import _ from "lodash"; import { getTheme, Stack } from "office-ui-fabric-react"; import React from "react"; import { BarPlotlyProps } from "../BarPlotlyProps"; import { IErrorPickerProps, IFeatureBinPickerPropsV2, IPerformancePickerPropsV2 } from "../FairnessWizard"; import { IMetrics } from "../IMetrics"; import { SharedStyles } from "../Shared.styles"; import { FormatMetrics } from "./../util/FormatMetrics"; import { IFairnessContext } from "./../util/IFairnessContext"; import { CalloutHelpBar } from "./CalloutHelpBar"; import { buildFalseNegativeErrorBounds, buildFalsePositiveErrorBounds, buildCustomTooltips } from "./PerformancePlotHelper"; import { PerformancePlotLegend } from "./PerformancePlotLegend"; interface IPerformancePlotProps { dashboardContext: IFairnessContext; metrics: IMetrics; areaHeights: number; performancePickerProps: IPerformancePickerPropsV2; featureBinPickerProps: IFeatureBinPickerPropsV2; errorPickerProps: IErrorPickerProps; fairnessBounds?: Array<IBounds | undefined>; performanceBounds?: Array<IBounds | undefined>; outcomeBounds?: Array<IBounds | undefined>; falsePositiveBounds?: Array<IBounds | undefined>; falseNegativeBounds?: Array<IBounds | undefined>; parentErrorChanged: { (event: React.MouseEvent<HTMLElement>, checked?: boolean): void; }; } export class PerformancePlot extends React.PureComponent<IPerformancePlotProps> { public render(): React.ReactNode { const barPlotlyProps = new BarPlotlyProps(); const theme = getTheme(); const sharedStyles = SharedStyles(); let performanceChartCalloutHelpBarStrings: string[] = []; const groupNamesWithBuffer = this.props.dashboardContext.groupNames.map( (name) => { return `${name} `; } ); if ( this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.BinaryClassification ) { barPlotlyProps.data = [ { color: chartColors[0], hoverinfo: "skip", name: localization.Fairness.Metrics.falsePositiveRate, orientation: "h", text: this.props.metrics.falsePositiveRates?.bins.map((num) => FormatMetrics.formatNumbers(num, "fallout_rate", false, 2) ), textposition: "auto", type: "bar", width: 0.5, x: this.props.metrics.falsePositiveRates?.bins, y: groupNamesWithBuffer } as any, { color: chartColors[1], hoverinfo: "skip", name: localization.Fairness.Metrics.falseNegativeRate, orientation: "h", text: this.props.metrics.falseNegativeRates?.bins.map((num) => FormatMetrics.formatNumbers(num, "miss_rate", false, 2) ), textposition: "auto", type: "bar", width: 0.5, x: this.props.metrics.falseNegativeRates?.bins.map((x) => -1 * x), y: groupNamesWithBuffer } ]; // Plot Error Bars if ( this.props.errorPickerProps.errorBarsEnabled && this.props.metrics.falsePositiveRates !== undefined ) { barPlotlyProps.data[0].error_x = buildFalsePositiveErrorBounds( this.props.metrics.falsePositiveRates ); barPlotlyProps.data[0].textposition = "none"; } if ( this.props.errorPickerProps.errorBarsEnabled && this.props.metrics.falseNegativeRates !== undefined ) { barPlotlyProps.data[1].error_x = buildFalseNegativeErrorBounds( this.props.metrics.falseNegativeRates ); barPlotlyProps.data[1].textposition = "none"; } // Annotations for both sides of the chart if (barPlotlyProps.layout) { barPlotlyProps.layout.annotations = [ { font: { color: theme.semanticColors.bodySubtext, size: 10 }, showarrow: false, text: localization.Fairness.Report.falseNegativeRate, x: 0.02, xref: "paper", y: 1, yref: "paper" }, { font: { color: theme.semanticColors.bodySubtext, size: 10 }, showarrow: false, text: localization.Fairness.Report.falsePositiveRate, x: 0.98, xref: "paper", y: 1, yref: "paper" } ]; } if (barPlotlyProps.layout?.xaxis) { barPlotlyProps.layout.xaxis.tickformat = ",.0%"; } performanceChartCalloutHelpBarStrings = [ localization.Fairness.Report.classificationPerformanceHowToReadV2 ]; } if ( this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.Probability ) { barPlotlyProps.data = [ { color: chartColors[0], hoverinfo: "skip", name: localization.Fairness.Metrics.overprediction, orientation: "h", text: this.props.metrics.overpredictions?.bins.map((num) => FormatMetrics.formatNumbers(num, "overprediction", false, 2) ), textposition: "auto", type: "bar", width: 0.5, x: this.props.metrics.overpredictions?.bins, y: groupNamesWithBuffer } as any, { color: chartColors[1], hoverinfo: "skip", name: localization.Fairness.Metrics.underprediction, orientation: "h", text: this.props.metrics.underpredictions?.bins.map((num) => FormatMetrics.formatNumbers(num, "underprediction", false, 2) ), textposition: "auto", type: "bar", width: 0.5, x: this.props.metrics.underpredictions?.bins.map((x) => -1 * x), y: groupNamesWithBuffer } ]; if (barPlotlyProps.layout) { barPlotlyProps.layout.annotations = [ { font: { color: theme.semanticColors.bodySubtext, size: 10 }, showarrow: false, text: localization.Fairness.Report.underestimationError, x: 0.1, xref: "paper", y: 1, yref: "paper" }, { font: { color: theme.semanticColors.bodySubtext, size: 10 }, showarrow: false, text: localization.Fairness.Report.overestimationError, x: 0.9, xref: "paper", y: 1, yref: "paper" } ]; } performanceChartCalloutHelpBarStrings = [ localization.Fairness.Report.probabilityPerformanceHowToRead1, localization.Fairness.Report.probabilityPerformanceHowToRead2, localization.Fairness.Report.probabilityPerformanceHowToRead3 ]; } if ( this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.Regression ) { const performanceText = this.props.metrics.predictions?.map( (val, index) => { return `${localization.formatString( localization.Fairness.Report.tooltipError, FormatMetrics.formatNumbers( this.props.metrics?.errors?.[index], "average", false, 3 ) )}<br>${localization.formatString( localization.Fairness.Report.tooltipPrediction, FormatMetrics.formatNumbers(val, "average", false, 3) )}`; } ); barPlotlyProps.data = [ { boxmean: true, boxpoints: "all", color: chartColors[0], hoverinfo: "text", hoveron: "points", jitter: 0.4, orientation: "h", pointpos: 0, text: performanceText, type: "box", x: this.props.metrics.errors, y: this.props.dashboardContext.binVector.map( (binIndex) => groupNamesWithBuffer[binIndex] ) } as any ]; performanceChartCalloutHelpBarStrings = [ localization.Fairness.Report.regressionPerformanceHowToRead ]; } // Create custom hover tooltips if ( this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.BinaryClassification ) { buildCustomTooltips(barPlotlyProps, this.props.dashboardContext); } return ( <Stack id="performancePlot"> <div className={sharedStyles.presentationArea} style={{ height: `${this.props.areaHeights}px` }} > <div className={sharedStyles.chartWrapper}> <CalloutHelpBar graphCalloutStrings={performanceChartCalloutHelpBarStrings} errorPickerProps={this.props.errorPickerProps} fairnessBounds={this.props.fairnessBounds} performanceBounds={this.props.performanceBounds} outcomeBounds={this.props.outcomeBounds} falsePositiveBounds={this.props.falsePositiveBounds} falseNegativeBounds={this.props.falseNegativeBounds} parentErrorChanged={this.props.parentErrorChanged} /> <div className={sharedStyles.chartBody}> <AccessibleChart plotlyProps={barPlotlyProps} theme={theme} themeOverride={{ axisGridColor: theme.semanticColors.disabledBorder }} /> </div> </div> </div> {this.props.dashboardContext.modelMetadata.PredictionType !== PredictionTypes.Regression && ( <PerformancePlotLegend showSubtitle={ this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.BinaryClassification } useOverUnderPrediction={ this.props.dashboardContext.modelMetadata.PredictionType === PredictionTypes.Probability } /> )} </Stack> ); } } export interface IPerformancePlotLegendProps { showSubtitle: boolean; useOverUnderPrediction: boolean; }
the_stack
import { Parser, UpdateMap, Literal, Shape, } from '../../src/expression-parsers/updates'; import { DynamoDBSet, createSet } from '../../src/document-client'; type TestType = { a: number; b: string; c: boolean; d: Shape<{ e: string; f: number; g: { h: boolean; }; }>; i: string[]; j: DynamoDBSet; }; const getValueName = (entries: [string, unknown][]) => ( value: unknown ): string => (entries.find(([, v]) => v === value) as [string, unknown])[0]; const hexadecimalKey = /^:[\da-f]{40}$/i; describe('SET expressions', () => { describe('plain expressions', () => { const i = ['hello']; const updates: UpdateMap<TestType> = { set: [{ a: 2, b: '3', i }], }; const parser = new Parser(updates); it('gets attribute names from set expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', '#b': 'b', '#i': 'i', }); }); it('gets attribute values from set expressions', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(3); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(2); expect(values).toContain('3'); expect(values).toContain(i); }); it('parses SET expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual( `SET #a = ${valueName(2)}, #b = ${valueName('3')}, #i = ${valueName(i)}` ); }); }); describe('with conditional updates', () => { const updates: UpdateMap<TestType> = { set: [ { a: 2, b: '3' }, { b: '4', c: true }, ], }; const parser = new Parser(updates); it('gets attribute names from set expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', '#b': 'b', '#c': 'c', }); }); it('gets attribute values from set expressions and prioritizes conditional values', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(3); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(2); expect(values).toContain('4'); expect(values).toContain(true); }); it('parses SET expressions prioritizing conditional updates', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual( `SET #a = ${valueName(2)}, ` + `#b = if_not_exists(#b, ${valueName('4')}), ` + `#c = if_not_exists(#c, ${valueName(true)})` ); }); }); describe('with nested updates', () => { const updates: UpdateMap<TestType> = { set: [{ a: 2, d: { e: 'hello', f: 8, g: { h: false } } }], }; const parser = new Parser(updates); it('gets nested attribute names from set expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', '#d': 'd', '#e': 'e', '#f': 'f', '#g': 'g', '#h': 'h', }); }); it('gets nested attribute values from set expressions', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(4); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(2); expect(values).toContain('hello'); expect(values).toContain(8); expect(values).toContain(false); }); it('parses nested SET expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual( `SET #a = ${valueName(2)}, ` + `#d.#e = ${valueName('hello')}, ` + `#d.#f = ${valueName(8)}, ` + `#d.#g.#h = ${valueName(false)}` ); }); }); describe('with conditional nested updates', () => { const updates: UpdateMap<TestType> = { set: [ { a: 2, d: { e: 'hello' } }, { b: 'new-value', d: { f: 8, g: { h: false } } }, ], }; const parser = new Parser(updates); it('gets nested attribute names from set expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', '#b': 'b', '#d': 'd', '#e': 'e', '#f': 'f', '#g': 'g', '#h': 'h', }); }); it('gets nested attribute values from set expressions', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(5); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(2); expect(values).toContain('hello'); expect(values).toContain('new-value'); expect(values).toContain(8); expect(values).toContain(false); }); it('parses nested SET expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual( `SET #a = ${valueName(2)}, ` + `#d.#e = ${valueName('hello')}, ` + `#b = if_not_exists(#b, ${valueName('new-value')}), ` + `#d.#f = if_not_exists(#d.#f, ${valueName(8)}), ` + `#d.#g.#h = if_not_exists(#d.#g.#h, ${valueName(false)})` ); }); }); describe('with literal object values', () => { const d = { e: 'hello', f: 8, g: { h: false } }; const updates: UpdateMap<TestType> = { set: [{ d: Literal(d) }], }; const parser = new Parser(updates); it('gets nested attribute names from set expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#d': 'd', }); }); it('gets nested attribute values from set expressions', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(1); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(d); }); it('parses nested SET expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual(`SET #d = ${valueName(d)}`); }); }); }); describe('REMOVE expressions', () => { describe('plain expressions', () => { const updates: UpdateMap<TestType> = { remove: { a: true, b: true }, }; const parser = new Parser(updates); it('gets attribute names from REMOVE expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', '#b': 'b', }); }); it('returns an empty object for attribute values', () => { expect(parser.expressionAttributeValues).toEqual({}); }); it('parses REMOVE expressions', () => { expect(parser.expression).toEqual('REMOVE #a, #b'); }); }); describe('nested expressions', () => { const updates: UpdateMap<TestType> = { remove: { d: { e: true, g: { h: true } } }, }; const parser = new Parser(updates); it('gets attribute names from REMOVE expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#d': 'd', '#e': 'e', '#g': 'g', '#h': 'h', }); }); it('returns an empty object for attribute values', () => { expect(parser.expressionAttributeValues).toEqual({}); }); it('parses REMOVE expressions', () => { expect(parser.expression).toEqual('REMOVE #d.#e, #d.#g.#h'); }); }); }); describe('ADD expressions', () => { describe('plain expressions with numbers', () => { const updates: UpdateMap<TestType> = { add: { a: 9 }, }; const parser = new Parser(updates); it('gets attribute names from ADD expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#a': 'a', }); }); it('gets attribute values from ADD operations', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(1); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(9); }); it('parses ADD expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual(`ADD #a ${valueName(9)}`); }); }); }); describe('DELETE expressions', () => { describe('plain expressions with numbers', () => { const j = createSet(['hello']); const updates: UpdateMap<TestType> = { delete: { j }, }; const parser = new Parser(updates); it('gets attribute names from DELETE expressions', () => { expect(parser.expressionAttributeNames).toEqual({ '#j': 'j', }); }); it('gets attribute values from DELETE operations', () => { const keys = Object.keys(parser.expressionAttributeValues); // all keys are random hexadecimal strings expect(keys.length).toBe(1); keys.forEach((key) => { expect(key).toMatch(hexadecimalKey); }); // all values should be present const values = Object.values(parser.expressionAttributeValues); expect(values).toContain(j); }); it('parses DELETE expressions', () => { const valueName = getValueName( Object.entries(parser.expressionAttributeValues) ); expect(parser.expression).toEqual(`DELETE #j ${valueName(j)}`); }); }); });
the_stack
import classnames from 'classnames'; import React, { useRef } from 'react'; import { type DripTableDriver, type DripTableExtraOptions, type DripTableFilters, type DripTablePagination, type DripTableReactComponentProps, type DripTableRecordTypeBase, type DripTableRecordTypeWithSubtable, type DripTableSchema, type DripTableTableInformation, type SchemaObject, } from '@/types'; import { type DripTableDriverTableProps } from '@/types/driver/table'; import { AjvOptions, validateDripTableColumnSchema, validateDripTableProps } from '@/utils/ajv'; import ErrorBoundary from '@/components/error-boundary'; import GenericRender, { DripTableGenericRenderElement } from '@/components/generic-render'; import RichText from '@/components/rich-text'; import { useState, useTable } from '@/hooks'; import DripTableWrapper from '..'; import DripTableBuiltInComponents, { DripTableBuiltInColumnSchema, DripTableBuiltInComponentEvent, DripTableComponentProps } from './components'; import VirtualTable from './virtual-table'; import styles from './index.module.less'; export interface DripTableProps< RecordType extends DripTableRecordTypeWithSubtable<DripTableRecordTypeBase, NonNullable<ExtraOptions['SubtableDataSourceKey']>>, ExtraOptions extends Partial<DripTableExtraOptions> = never, > { /** * 底层组件驱动 */ driver: DripTableDriver; /** * 样式表类名 */ className?: string; /** * 自定义样式表 */ style?: React.CSSProperties; /** * 表单 Schema */ schema: DripTableSchema<NonNullable<ExtraOptions['CustomColumnSchema']>, NonNullable<ExtraOptions['SubtableDataSourceKey']>>; /** * 数据源 */ dataSource: RecordType[]; /** * 当前选中的行键 */ selectedRowKeys?: React.Key[]; /** * 当前显示的列键 */ displayColumnKeys?: React.Key[]; /** * 数据源总条数 */ total?: number; /** * 当前页码 */ currentPage?: number; /** * 加载中 */ loading?: boolean; /** * 粘性头部和滚动条设置项 */ sticky?: { offsetHeader?: number; offsetScroll?: number; getContainer?: () => HTMLElement; }; /** * 表格单元格组件库 */ components?: { [libName: string]: { [componentName: string]: React.JSXElementConstructor< DripTableComponentProps< RecordType, NonNullable<ExtraOptions['CustomColumnSchema']>, NonNullable<ExtraOptions['CustomComponentEvent']>, NonNullable<ExtraOptions['CustomComponentExtraData']> > > & { schema?: SchemaObject }; }; }; /** * 组件插槽,可通过 Schema 控制自定义区域渲染 */ slots?: { [componentType: string]: React.JSXElementConstructor<{ style?: React.CSSProperties; className?: string; slotType: string; driver: DripTableDriver; schema: DripTableSchema<NonNullable<ExtraOptions['CustomColumnSchema']>, NonNullable<ExtraOptions['SubtableDataSourceKey']>>; dataSource: readonly RecordType[]; onSearch: (searchParams: Record<string, unknown>) => void; }>; }; /** * Schema 校验配置项 */ ajv?: AjvOptions | false; /** * 自定义组件附加透传数据 */ ext?: NonNullable<ExtraOptions['CustomComponentExtraData']>; /** * 顶部自定义渲染函数 */ title?: (data: readonly RecordType[]) => React.ReactNode; /** * 底部自定义渲染函数 */ footer?: (data: readonly RecordType[]) => React.ReactNode; /** * 子表顶部自定义渲染函数 */ subtableTitle?: ( record: RecordType, recordIndex: number, parentTable: DripTableTableInformation<RecordType>, subtable: DripTableTableInformation<RecordType>, ) => React.ReactNode; /** * 子表底部自定义渲染函数 */ subtableFooter?: ( record: RecordType, recordIndex: number, parentTable: DripTableTableInformation<RecordType>, subtable: DripTableTableInformation<RecordType>, ) => React.ReactNode; /** * 获取指定行是否可展开 */ rowExpandable?: ( record: RecordType, parentTable: DripTableTableInformation<RecordType>, ) => boolean; /** * 行展开自定义渲染函数 */ expandedRowRender?: ( record: RecordType, index: number, parentTable: DripTableTableInformation<RecordType>, ) => React.ReactNode; /** * 生命周期:组件加载完成 */ componentDidMount?: (currentTable: DripTableTableInformation<RecordType>) => void; /** * 生命周期:组件更新完成 */ componentDidUpdate?: (currentTable: DripTableTableInformation<RecordType>) => void; /** * 生命周期:组件即将卸载 */ componentWillUnmount?: (currentTable: DripTableTableInformation<RecordType>) => void; /** * 点击行 */ onRowClick?: ( record: RecordType | RecordType[], index: number | string | (number | string)[], parentTable: DripTableTableInformation<RecordType>, ) => void; /** * 双击行 */ onRowDoubleClick?: ( record: RecordType | RecordType[], index: number | string | (number | string)[], parentTable: DripTableTableInformation<RecordType>, ) => void; /** * 选择行变化 */ onSelectionChange?: ( selectedKeys: React.Key[], selectedRows: RecordType[], currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 搜索触发 */ onSearch?: ( searchParams: { searchKey?: number | string; searchStr: string } | Record<string, unknown>, currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 点击添加按钮触发 */ onInsertButtonClick?: ( event: React.MouseEvent<HTMLElement, MouseEvent>, currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 过滤器触发 */ onFilterChange?: ( filters: DripTableFilters, currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 页码/页大小变化 */ onPageChange?: ( currentPage: number, pageSize: number, currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 过滤器、分页器 等配置变化 */ onChange?: ( options: { pagination: DripTablePagination; filters: DripTableFilters; }, currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 用户修改展示的列时 */ onDisplayColumnKeysChange?: ( displayColumnKeys: React.Key[], currentTable: DripTableTableInformation<RecordType>, ) => void; /** * 通用事件机制 */ onEvent?: ( event: DripTableBuiltInComponentEvent | NonNullable<ExtraOptions['CustomComponentEvent']>, record: RecordType, index: number, currentTable: DripTableTableInformation<RecordType>, ) => void; } const DripTable = < RecordType extends DripTableRecordTypeWithSubtable<DripTableRecordTypeBase, NonNullable<ExtraOptions['SubtableDataSourceKey']>>, ExtraOptions extends Partial<DripTableExtraOptions> = never, >(props: DripTableProps<RecordType, ExtraOptions>): JSX.Element => { if (props.schema && props.schema.columns.some(c => c['ui:type'] || c['ui:props'])) { props = { ...props, schema: { ...props.schema, columns: props.schema.columns.map((column) => { // 兼容旧版本数据 if ('ui:type' in column || 'ui:props' in column) { const key = column.key; if ('ui:type' in column) { console.warn(`[DripTable] Column ${key} "ui:type" is deprecated, please use "component" instead.`); } if ('ui:props' in column) { console.warn(`[DripTable] Column ${key} "ui:props" is deprecated, please use "options" instead.`); } return { ...Object.fromEntries(Object.entries(column).filter(([k]) => k !== 'ui:type' && k !== 'ui:props')), options: column['ui:props'] || column.options || void 0, component: column['ui:type'] || column.component, } as typeof column; } return column; }), }, }; } if (props.ajv !== false) { const errorMessage = validateDripTableProps(props, props.ajv); if (errorMessage) { return ( <div className={styles['ajv-error']}> { `Props validate failed: ${errorMessage}` } </div> ); } } const Table = props.driver.components?.Table; const Popover = props.driver.components?.Popover; const QuestionCircleOutlined = props.driver.icons?.QuestionCircleOutlined; type TableColumn = NonNullable<DripTableReactComponentProps<typeof Table>['columns']>[number]; const initialState = useTable(); const initialPagination = props.schema?.pagination || void 0; const [tableState, setTableState] = initialState._CTX_SOURCE === 'CONTEXT' ? useState(initialState) : [initialState, initialState.setTableState]; const rootRef = useRef<HTMLDivElement>(null); // ProTable组件的ref const tableInfo = React.useMemo((): DripTableTableInformation<RecordType> => ({ id: props.schema.id, dataSource: props.dataSource }), [props.schema.id, props.dataSource]); React.useEffect(() => { setTableState(state => ({ pagination: { ...state.pagination, pageSize: initialPagination?.pageSize || 10, }, })); }, [initialPagination?.pageSize]); React.useEffect(() => { setTableState(state => ({ displayColumnKeys: props.displayColumnKeys || props.schema.columns.filter(c => c.hidable).map(c => c.key), })); }, [props.displayColumnKeys]); React.useEffect(() => { props.componentDidMount?.(tableInfo); return () => { props.componentWillUnmount?.(tableInfo); }; }); React.useEffect(() => { props.componentDidUpdate?.(tableInfo); }, [props]); /** * 根据组件类型,生成表格渲染器 * @param schema Schema * @returns 表格 */ const renderGenerator = (schema: DripTableBuiltInColumnSchema | NonNullable<ExtraOptions['CustomColumnSchema']>): (value: unknown, record: RecordType, index: number) => JSX.Element | string | null => { if ('component' in schema) { const BuiltInComponent = DripTableBuiltInComponents[schema.component] as React.JSXElementConstructor<DripTableComponentProps<RecordType, DripTableBuiltInColumnSchema>> & { schema?: SchemaObject }; if (BuiltInComponent) { if (props.ajv !== false) { const errorMessage = validateDripTableColumnSchema(schema, BuiltInComponent.schema, props.ajv); if (errorMessage) { return () => ( <div className={styles['ajv-error']}> { `Schema validate failed: ${errorMessage}` } </div> ); } } return (value, record, index) => ( <BuiltInComponent driver={props.driver} value={value ?? schema.defaultValue} data={record} schema={schema as unknown as DripTableBuiltInColumnSchema} ext={props.ext} fireEvent={event => props.onEvent?.(event, record, index, tableInfo)} /> ); } const [libName, componentName] = schema.component.split('::'); if (libName && componentName) { const ExtraComponent = props.components?.[libName]?.[componentName]; if (ExtraComponent) { if (props.ajv !== false) { const errorMessage = validateDripTableColumnSchema(schema, ExtraComponent.schema, props.ajv); if (errorMessage) { return () => ( <div className={styles['ajv-error']}> { `Schema validate failed: ${errorMessage}` } </div> ); } } return (value, record, index) => ( <ExtraComponent driver={props.driver} value={value ?? schema.defaultValue} data={record} schema={schema as NonNullable<ExtraOptions['CustomColumnSchema']>} ext={props.ext} fireEvent={event => props.onEvent?.(event, record, index, tableInfo)} /> ); } } } return () => <div className={styles['ajv-error']}>{ `Unknown column component: ${schema.component}` }</div>; }; /** * 根据列 Schema,生成表格列配置 * @param schemaColumn Schema Column * @returns 表格列配置 */ const columnGenerator = (schemaColumn: DripTableBuiltInColumnSchema | NonNullable<ExtraOptions['CustomColumnSchema']>): TableColumn => { let width = String(schemaColumn.width).trim(); if ((/^[0-9]+$/uig).test(width)) { width += 'px'; } const column: TableColumn = { width, className: classnames(props.className, { [styles[`drip-table-vertical-${schemaColumn.verticalAlign}`]]: schemaColumn.verticalAlign, }), align: schemaColumn.align, title: schemaColumn.title, dataIndex: schemaColumn.dataIndex, fixed: schemaColumn.fixed, filters: schemaColumn.filters, defaultFilteredValue: schemaColumn.defaultFilteredValue, }; if (schemaColumn.description) { column.title = ( <div> <span style={{ marginRight: '6px' }}>{ schemaColumn.title }</span> <Popover placement="top" title="" content={<RichText html={schemaColumn.description} />}> <QuestionCircleOutlined /> </Popover> </div> ); } if (props.schema.ellipsis) { column.ellipsis = true; } if (!column.render) { column.render = renderGenerator(schemaColumn) as TableColumn['render']; } return column; }; const tableProps: DripTableDriverTableProps<RecordType> = { className: props.schema.innerClassName, style: props.schema.innerStyle, rowKey: props.schema.rowKey ?? 'key', columns: React.useMemo( () => props.schema.columns .filter(column => !column.hidable || tableState.displayColumnKeys.includes(column.key)) .map(columnGenerator), [props.schema.columns, tableState.displayColumnKeys], ), dataSource: React.useMemo( () => props.dataSource.map((item, index) => { const rowKey = props.schema.rowKey ?? 'key'; return { ...item, [rowKey]: typeof item[rowKey] === 'undefined' ? index : item[rowKey], }; }), [props.dataSource, props.schema.rowKey], ), pagination: props.schema.pagination === false ? false as const : { size: props.schema.pagination?.size === void 0 ? 'small' : props.schema.pagination.size, pageSize: tableState.pagination.pageSize, total: props.total === void 0 ? props.dataSource.length : props.total, current: props.currentPage || tableState.pagination.current, position: [props.schema.pagination?.position || 'bottomRight'], showLessItems: props.schema.pagination?.showLessItems, showQuickJumper: props.schema.pagination?.showQuickJumper, showSizeChanger: props.schema.pagination?.showSizeChanger, hideOnSinglePage: props.schema.pagination?.hideOnSinglePage, }, scroll: props.schema.scroll, loading: props.loading, size: props.schema.size, bordered: props.schema.bordered, showHeader: props.schema.showHeader, sticky: props.schema.sticky ? props.sticky ?? true : false, title: props.title, footer: props.footer, expandable: React.useMemo( () => { const subtable = props.schema.subtable; const expandedRowRender = props.expandedRowRender; const rowExpandable = props.rowExpandable; if (subtable || expandedRowRender) { return { expandedRowRender: (record, index) => ( <React.Fragment> { subtable && Array.isArray(record[subtable.dataSourceKey]) ? ( <DripTableWrapper<RecordType, ExtraOptions> {...props} schema={ Object.fromEntries( Object.entries(subtable) .filter(([key]) => key !== 'dataSourceKey'), ) as DripTableSchema<NonNullable<ExtraOptions['CustomColumnSchema']>, NonNullable<ExtraOptions['SubtableDataSourceKey']>> } dataSource={record[subtable.dataSourceKey] as RecordType[]} title={ props.subtableTitle ? subtableData => props.subtableTitle?.( record, index, tableInfo, { id: subtable.id, dataSource: subtableData }, ) : void 0 } footer={ props.subtableFooter ? subtableData => props.subtableFooter?.( record, index, tableInfo, { id: subtable.id, dataSource: subtableData }, ) : void 0 } /> ) : void 0 } { expandedRowRender?.(record, index, tableInfo) } </React.Fragment> ), rowExpandable: (record) => { if (rowExpandable?.(record, tableInfo)) { return true; } if (subtable) { const ds = record[subtable.dataSourceKey]; return Array.isArray(ds) && ds.length > 0; } return false; }, }; } return void 0; }, [props.schema.subtable, props.expandedRowRender, props.rowExpandable], ), rowSelection: props.schema.rowSelection && !props.schema.virtual ? { selectedRowKeys: props.selectedRowKeys || tableState.selectedRowKeys, onChange: (selectedKeys, selectedRows) => { setTableState({ selectedRowKeys: [...selectedKeys] }); props.onSelectionChange?.(selectedKeys, selectedRows, tableInfo); }, } : void 0, onChange: (pagination, filters) => { const current = pagination.current ?? tableState.pagination.current; const pageSize = pagination.pageSize ?? tableState.pagination.pageSize; setTableState({ pagination: { ...tableState.pagination, current, pageSize }, filters }); props.onFilterChange?.(filters, tableInfo); props.onPageChange?.(current, pageSize, tableInfo); props.onChange?.({ pagination, filters }, tableInfo); }, }; const header = React.useMemo<{ style?: React.CSSProperties; schemas: DripTableGenericRenderElement[] } | null>( () => { if (props.schema.header === true) { return { schemas: [ { type: 'display-column-selector', selectorButtonType: 'primary' }, { type: 'spacer', span: 'flex-auto' }, { type: 'search' }, { type: 'insert-button', showIcon: true }, ], }; } if (!props.schema.header || !props.schema.header.elements?.length) { return null; } return { style: props.schema.header.style, schemas: props.schema.header.elements, }; }, [props.schema.header], ); const footer = React.useMemo<{ style?: React.CSSProperties; schemas: DripTableGenericRenderElement[] } | null>( () => { if (props.schema.footer === true) { return { schemas: [ { type: 'display-column-selector', span: 8 }, { type: 'search', span: 8 }, { type: 'insert-button', span: 4 }, ], }; } if (!props.schema.footer || !props.schema.footer.elements?.length) { return null; } return { style: props.schema.footer.style, schemas: props.schema.footer.elements, }; }, [props.schema.footer], ); return ( <ErrorBoundary driver={props.driver}> <div className={classnames(props.className, props.schema.className)} style={Object.assign({}, props.style, props.schema.style)} ref={rootRef} > { header ? ( <GenericRender style={header.style} schemas={header.schemas} tableProps={props} tableState={tableState} setTableState={setTableState} /> ) : null } { props.schema.virtual ? ( <VirtualTable {...tableProps} driver={props.driver} scroll={{ ...props.schema.scroll, x: props.schema.scroll?.x || '100vw', y: props.schema.scroll?.y || 300, }} /> ) : <Table {...tableProps} /> } { footer ? ( <GenericRender style={footer.style} schemas={footer.schemas} tableProps={props} tableState={tableState} setTableState={setTableState} /> ) : null } </div> </ErrorBoundary> ); }; export default DripTable;
the_stack
import { VssueAPI } from 'vssue'; import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'; import { buildURL, concatURL, getCleanURL, parseQuery } from '@vssue/utils'; import { normalizeUser, normalizeIssue, normalizeComment, normalizeReactions, mapReactionName, } from './utils'; import { ResponseAccessToken, ResponseUser, ResponseIssue, ResponseComment, ResponseReaction, ResponseSearch, } from './types'; /** * Github REST API v3 * * @see https://developer.github.com/v3/ * @see https://developer.github.com/apps/building-oauth-apps/ */ export default class GithubV3 implements VssueAPI.Instance { baseURL: string; owner: string; repo: string; labels: Array<string>; clientId: string; clientSecret: string; state: string; proxy: string | ((url: string) => string); $http: AxiosInstance; constructor({ baseURL = 'https://github.com', owner, repo, labels, clientId, clientSecret, state, proxy, }: VssueAPI.Options) { /* istanbul ignore if */ if (typeof clientSecret === 'undefined' || typeof proxy === 'undefined') { throw new Error('clientSecret and proxy is required for GitHub V3'); } this.baseURL = baseURL; this.owner = owner; this.repo = repo; this.labels = labels; this.clientId = clientId; this.clientSecret = clientSecret; this.state = state; this.proxy = proxy; this.$http = axios.create({ baseURL: baseURL === 'https://github.com' ? 'https://api.github.com' : concatURL(baseURL, 'api/v3'), headers: { Accept: 'application/vnd.github.v3+json', }, }); this.$http.interceptors.response.use( response => { if (response.data && response.data.error) { return Promise.reject(new Error(response.data.error_description)); } return response; }, error => { // 403 rate limit exceeded in OPTIONS request will cause a Network Error // here we always treat Network Error as 403 rate limit exceeded // @see https://github.com/axios/axios/issues/838 /* istanbul ignore next */ if ( typeof error.response === 'undefined' && error.message === 'Network Error' ) { error.response = { status: 403, }; } return Promise.reject(error); } ); } /** * The platform api info */ get platform(): VssueAPI.Platform { return { name: 'GitHub', link: this.baseURL, version: 'v3', meta: { reactable: true, sortable: false, }, }; } /** * Redirect to the authorization page of platform. * * @see https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#1-request-a-users-github-identity */ redirectAuth(): void { window.location.href = buildURL( concatURL(this.baseURL, 'login/oauth/authorize'), { client_id: this.clientId, redirect_uri: window.location.href, scope: 'public_repo', state: this.state, } ); } /** * Handle authorization. * * @see https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/ * * @remarks * If the `code` and `state` exist in the query, and the `state` matches, remove them from query, and try to get the access token. */ async handleAuth(): Promise<VssueAPI.AccessToken> { const query = parseQuery(window.location.search); if (query.code) { if (query.state !== this.state) { return null; } const code = query.code; delete query.code; delete query.state; const replaceURL = buildURL(getCleanURL(window.location.href), query) + window.location.hash; window.history.replaceState(null, '', replaceURL); const accessToken = await this.getAccessToken({ code }); return accessToken; } return null; } /** * Get user access token via `code` * * @see https://developer.github.com/apps/building-oauth-apps/authorizing-oauth-apps/#2-users-are-redirected-back-to-your-site-by-github */ async getAccessToken({ code }: { code: string }): Promise<string> { /** * access_token api does not support cors * @see https://github.com/isaacs/github/issues/330 */ const originalURL = concatURL(this.baseURL, 'login/oauth/access_token'); const proxyURL = typeof this.proxy === 'function' ? this.proxy(originalURL) : this.proxy; const { data } = await this.$http.post<ResponseAccessToken>( proxyURL, { client_id: this.clientId, client_secret: this.clientSecret, code, /** * useless but mentioned in docs */ // redirect_uri: window.location.href, // state: this.state, }, { headers: { Accept: 'application/json', }, } ); return data.access_token; } /** * Get the logged-in user with access token. * * @see https://developer.github.com/v3/users/#get-the-authenticated-user */ async getUser({ accessToken, }: { accessToken: VssueAPI.AccessToken; }): Promise<VssueAPI.User> { const { data } = await this.$http.get<ResponseUser>('user', { headers: { Authorization: `token ${accessToken}` }, }); return normalizeUser(data); } /** * Get issue of this page according to the issue id or the issue title * * @see https://developer.github.com/v3/issues/#list-issues-for-a-repository * @see https://developer.github.com/v3/issues/#get-a-single-issue * @see https://developer.github.com/v3/#pagination * @see https://developer.github.com/v3/search/#search-issues-and-pull-requests */ async getIssue({ accessToken, issueId, issueTitle, }: { accessToken: VssueAPI.AccessToken; issueId?: string | number; issueTitle?: string; }): Promise<VssueAPI.Issue | null> { const options: AxiosRequestConfig = {}; if (accessToken) { options.headers = { Authorization: `token ${accessToken}`, }; } if (issueId) { try { options.params = { // to avoid caching timestamp: Date.now(), }; const { data } = await this.$http.get<ResponseIssue>( `repos/${this.owner}/${this.repo}/issues/${issueId}`, options ); return normalizeIssue(data); } catch (e) { if (e.response && e.response.status === 404) { return null; } else { throw e; } } } else { options.params = { q: [ `"${issueTitle}"`, `is:issue`, `in:title`, `repo:${this.owner}/${this.repo}`, `is:public`, ...this.labels.map(label => `label:${label}`), ].join(' '), // to avoid caching timestamp: Date.now(), }; const { data } = await this.$http.get<ResponseSearch<ResponseIssue>>( `search/issues`, options ); const issue = data.items .map(normalizeIssue) .find(item => item.title === issueTitle); return issue || null; } } /** * Create a new issue * * @see https://developer.github.com/v3/issues/#create-an-issue */ async postIssue({ accessToken, title, content, }: { accessToken: VssueAPI.AccessToken; title: string; content: string; }): Promise<VssueAPI.Issue> { const { data } = await this.$http.post<ResponseIssue>( `repos/${this.owner}/${this.repo}/issues`, { title, body: content, labels: this.labels, }, { headers: { Authorization: `token ${accessToken}` }, } ); return normalizeIssue(data); } /** * Get comments of this page according to the issue id * * @see https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue * @see https://developer.github.com/v3/#pagination * * @remarks * Github V3 does not support sort for issue comments now. * Github V3 have to request the parent issue to get the count of comments. */ async getComments({ accessToken, issueId, query: { page = 1, perPage = 10 /*, sort = 'desc' */ } = {}, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; query?: Partial<VssueAPI.Query>; }): Promise<VssueAPI.Comments> { const issueOptions: AxiosRequestConfig = { params: { // to avoid caching timestamp: Date.now(), }, }; const commentsOptions: AxiosRequestConfig = { params: { // pagination page: page, per_page: perPage, /** * github v3 api does not support sort for issue comments * have sent feedback to github support */ // 'sort': 'created', // 'direction': sort, // to avoid caching timestamp: Date.now(), }, headers: { Accept: [ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ], }, }; if (accessToken) { issueOptions.headers = { Authorization: `token ${accessToken}`, }; commentsOptions.headers.Authorization = `token ${accessToken}`; } // github v3 have to get the total count of comments by requesting the issue const [issueRes, commentsRes] = await Promise.all([ this.$http.get<ResponseIssue>( `repos/${this.owner}/${this.repo}/issues/${issueId}`, issueOptions ), this.$http.get<ResponseComment[]>( `repos/${this.owner}/${this.repo}/issues/${issueId}/comments`, commentsOptions ), ]); // it's annoying that have to get the page and per_page from the `Link` header const linkHeader = commentsRes.headers.link || null; /* istanbul ignore next */ const thisPage = /rel="next"/.test(linkHeader) ? Number(linkHeader.replace(/^.*[^_]page=(\d*).*rel="next".*$/, '$1')) - 1 : /rel="prev"/.test(linkHeader) ? Number(linkHeader.replace(/^.*[^_]page=(\d*).*rel="prev".*$/, '$1')) + 1 : 1; /* istanbul ignore next */ const thisPerPage = linkHeader ? Number(linkHeader.replace(/^.*per_page=(\d*).*$/, '$1')) : perPage; return { count: Number(issueRes.data.comments), page: thisPage, perPage: thisPerPage, data: commentsRes.data.map(normalizeComment), }; } /** * Create a new comment * * @see https://developer.github.com/v3/issues/comments/#create-a-comment */ async postComment({ accessToken, issueId, content, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; content: string; }): Promise<VssueAPI.Comment> { const { data } = await this.$http.post<ResponseComment>( `repos/${this.owner}/${this.repo}/issues/${issueId}/comments`, { body: content, }, { headers: { Authorization: `token ${accessToken}`, Accept: [ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ], }, } ); return normalizeComment(data); } /** * Edit a comment * * @see https://developer.github.com/v3/issues/comments/#edit-a-comment */ async putComment({ accessToken, commentId, content, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; content: string; }): Promise<VssueAPI.Comment> { const { data } = await this.$http.patch<ResponseComment>( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}`, { body: content, }, { headers: { Authorization: `token ${accessToken}`, Accept: [ 'application/vnd.github.v3.raw+json', 'application/vnd.github.v3.html+json', 'application/vnd.github.squirrel-girl-preview', ], }, } ); return normalizeComment(data); } /** * Delete a comment * * @see https://developer.github.com/v3/issues/comments/#delete-a-comment */ async deleteComment({ accessToken, commentId, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; }): Promise<boolean> { const { status } = await this.$http.delete( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}`, { headers: { Authorization: `token ${accessToken}` }, } ); return status === 204; } /** * Get reactions of a comment * * @see https://developer.github.com/v3/issues/comments/#get-a-single-comment * @see https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment * * @remarks * The `List reactions for an issue comment` API also returns author of each reaction. * As we only need the count, use the `Get a single comment` API is much simpler. */ async getCommentReactions({ accessToken, commentId, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; }): Promise<VssueAPI.Reactions> { const { data } = await this.$http.get<ResponseComment>( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}`, { params: { // to avoid caching timestamp: Date.now(), }, headers: { Authorization: `token ${accessToken}`, Accept: 'application/vnd.github.squirrel-girl-preview', }, } ); return normalizeReactions(data.reactions); } /** * Create a new reaction of a comment * * @see https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment */ async postCommentReaction({ accessToken, commentId, reaction, }: { accessToken: VssueAPI.AccessToken; issueId: string | number; commentId: string | number; reaction: keyof VssueAPI.Reactions; }): Promise<boolean> { const response = await this.$http.post<ResponseReaction>( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}/reactions`, { content: mapReactionName(reaction), }, { headers: { Authorization: `token ${accessToken}`, Accept: 'application/vnd.github.squirrel-girl-preview', }, } ); // 200 OK if the reaction is already token if (response.status === 200) { return this.deleteCommentReaction({ accessToken, commentId, reactionId: response.data.id, }); } // 201 CREATED return response.status === 201; } /** * Delete a reaction of a comment * * @see https://developer.github.com/v3/reactions/#delete-a-reaction */ async deleteCommentReaction({ accessToken, commentId, reactionId, }: { accessToken: VssueAPI.AccessToken; commentId: string | number; reactionId: string | number; }): Promise<boolean> { const response = await this.$http.delete( `repos/${this.owner}/${this.repo}/issues/comments/${commentId}/reactions/${reactionId}`, { headers: { Authorization: `token ${accessToken}`, Accept: 'application/vnd.github.squirrel-girl-preview', }, } ); return response.status === 204; } }
the_stack
import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { PromiEvent, TransactionReceipt, EventResponse, EventData, Web3ContractContext, } from 'ethereum-abi-types-generator'; export interface CallOptions { from?: string; gasPrice?: string; gas?: number; } export interface SendOptions { from: string; value?: number | string | BN | BigNumber; gasPrice?: string; gas?: number; } export interface EstimateGasOptions { from?: string; value?: number | string | BN | BigNumber; gas?: number; } export interface MethodPayableReturnContext { send(options: SendOptions): PromiEvent<TransactionReceipt>; send( options: SendOptions, callback: (error: Error, result: any) => void ): PromiEvent<TransactionReceipt>; estimateGas(options: EstimateGasOptions): Promise<number>; estimateGas( options: EstimateGasOptions, callback: (error: Error, result: any) => void ): Promise<number>; encodeABI(): string; } export interface MethodConstantReturnContext<TCallReturn> { call(): Promise<TCallReturn>; call(options: CallOptions): Promise<TCallReturn>; call( options: CallOptions, callback: (error: Error, result: TCallReturn) => void ): Promise<TCallReturn>; encodeABI(): string; } export interface MethodReturnContext extends MethodPayableReturnContext {} export type ContractContext = Web3ContractContext< SwapFlashLoan, SwapFlashLoanMethodNames, SwapFlashLoanEventsContext, SwapFlashLoanEvents >; export type SwapFlashLoanEvents = | 'AddLiquidity' | 'FlashLoan' | 'NewAdminFee' | 'NewSwapFee' | 'OwnershipTransferred' | 'Paused' | 'RampA' | 'RemoveLiquidity' | 'RemoveLiquidityImbalance' | 'RemoveLiquidityOne' | 'StopRampA' | 'TokenSwap' | 'Unpaused'; export interface SwapFlashLoanEventsContext { AddLiquidity( parameters: { filter?: { provider?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; FlashLoan( parameters: { filter?: { receiver?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; NewAdminFee( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; NewSwapFee( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; OwnershipTransferred( parameters: { filter?: { previousOwner?: string | string[]; newOwner?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Paused( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RampA( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RemoveLiquidity( parameters: { filter?: { provider?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RemoveLiquidityImbalance( parameters: { filter?: { provider?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RemoveLiquidityOne( parameters: { filter?: { provider?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; StopRampA( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; TokenSwap( parameters: { filter?: { buyer?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Unpaused( parameters: { filter?: {}; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; } export type SwapFlashLoanMethodNames = | 'MAX_BPS' | 'addLiquidity' | 'calculateRemoveLiquidity' | 'calculateRemoveLiquidityOneToken' | 'calculateSwap' | 'calculateTokenAmount' | 'flashLoan' | 'flashLoanFeeBPS' | 'getA' | 'getAPrecise' | 'getAdminBalance' | 'getToken' | 'getTokenBalance' | 'getTokenIndex' | 'getVirtualPrice' | 'initialize' | 'owner' | 'pause' | 'paused' | 'protocolFeeShareBPS' | 'rampA' | 'removeLiquidity' | 'removeLiquidityImbalance' | 'removeLiquidityOneToken' | 'renounceOwnership' | 'setAdminFee' | 'setFlashLoanFees' | 'setSwapFee' | 'stopRampA' | 'swap' | 'swapStorage' | 'transferOwnership' | 'unpause' | 'withdrawAdminFees'; export interface SwapStorageResponse { initialA: string; futureA: string; initialATime: string; futureATime: string; swapFee: string; adminFee: string; lpToken: string; } export interface SwapFlashLoan { /** * Payable: false * Constant: true * StateMutability: view * Type: function */ MAX_BPS(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amounts Type: uint256[], Indexed: false * @param minToMint Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ addLiquidity(amounts: string[], minToMint: string, deadline: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param amount Type: uint256, Indexed: false */ calculateRemoveLiquidity(amount: string): MethodConstantReturnContext<string[]>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param tokenAmount Type: uint256, Indexed: false * @param tokenIndex Type: uint8, Indexed: false */ calculateRemoveLiquidityOneToken( tokenAmount: string, tokenIndex: string | number ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param tokenIndexFrom Type: uint8, Indexed: false * @param tokenIndexTo Type: uint8, Indexed: false * @param dx Type: uint256, Indexed: false */ calculateSwap( tokenIndexFrom: string | number, tokenIndexTo: string | number, dx: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param amounts Type: uint256[], Indexed: false * @param deposit Type: bool, Indexed: false */ calculateTokenAmount(amounts: string[], deposit: boolean): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param receiver Type: address, Indexed: false * @param token Type: address, Indexed: false * @param amount Type: uint256, Indexed: false * @param params Type: bytes, Indexed: false */ flashLoan( receiver: string, token: string, amount: string, params: string | number[] ): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ flashLoanFeeBPS(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getA(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getAPrecise(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param index Type: uint256, Indexed: false */ getAdminBalance(index: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param index Type: uint8, Indexed: false */ getToken(index: string | number): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param index Type: uint8, Indexed: false */ getTokenBalance(index: string | number): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function * @param tokenAddress Type: address, Indexed: false */ getTokenIndex(tokenAddress: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ getVirtualPrice(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param _pooledTokens Type: address[], Indexed: false * @param decimals Type: uint8[], Indexed: false * @param lpTokenName Type: string, Indexed: false * @param lpTokenSymbol Type: string, Indexed: false * @param _a Type: uint256, Indexed: false * @param _fee Type: uint256, Indexed: false * @param _adminFee Type: uint256, Indexed: false * @param lpTokenTargetAddress Type: address, Indexed: false */ initialize( _pooledTokens: string[], decimals: string | number[], lpTokenName: string, lpTokenSymbol: string, _a: string, _fee: string, _adminFee: string, lpTokenTargetAddress: string ): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ owner(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ pause(): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ paused(): MethodConstantReturnContext<boolean>; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ protocolFeeShareBPS(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param futureA Type: uint256, Indexed: false * @param futureTime Type: uint256, Indexed: false */ rampA(futureA: string, futureTime: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amount Type: uint256, Indexed: false * @param minAmounts Type: uint256[], Indexed: false * @param deadline Type: uint256, Indexed: false */ removeLiquidity(amount: string, minAmounts: string[], deadline: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param amounts Type: uint256[], Indexed: false * @param maxBurnAmount Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ removeLiquidityImbalance( amounts: string[], maxBurnAmount: string, deadline: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param tokenAmount Type: uint256, Indexed: false * @param tokenIndex Type: uint8, Indexed: false * @param minAmount Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ removeLiquidityOneToken( tokenAmount: string, tokenIndex: string | number, minAmount: string, deadline: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ renounceOwnership(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param newAdminFee Type: uint256, Indexed: false */ setAdminFee(newAdminFee: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param newFlashLoanFeeBPS Type: uint256, Indexed: false * @param newProtocolFeeShareBPS Type: uint256, Indexed: false */ setFlashLoanFees(newFlashLoanFeeBPS: string, newProtocolFeeShareBPS: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param newSwapFee Type: uint256, Indexed: false */ setSwapFee(newSwapFee: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ stopRampA(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param tokenIndexFrom Type: uint8, Indexed: false * @param tokenIndexTo Type: uint8, Indexed: false * @param dx Type: uint256, Indexed: false * @param minDy Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ swap( tokenIndexFrom: string | number, tokenIndexTo: string | number, dx: string, minDy: string, deadline: string ): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: view * Type: function */ swapStorage(): MethodConstantReturnContext<SwapStorageResponse>; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function * @param newOwner Type: address, Indexed: false */ transferOwnership(newOwner: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ unpause(): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: nonpayable * Type: function */ withdrawAdminFees(): MethodReturnContext; }
the_stack
import Application from "./application" import https from 'https' export default class xCloudClient { _application _host:string _token:string _type:'home'|'cloud' _sessionPath:string constructor(application:Application, host:string, token: string, type:'home'|'cloud' = 'home'){ this._application = application this._host = host this._token = token this._type = type } get(url: string) { return new Promise((resolve, reject) => { fetch(url, { method: 'GET', // *GET, POST, PUT, DELETE, etc. headers: { 'Authorization': 'Bearer '+this._token, 'Accept-Language': 'en-US', } }).then((response) => { if(response.status !== 200){ console.log('Error fetching consoles. Status:', response.status, 'Body:', response.body) } else { response.json().then((data) => { resolve(data) }).catch((error) => { reject(error) }) } }).catch((error) => { reject(error) }); }) } getTitles() { return this.get('https://' + this._host + '/v1/titles') } getConsoles() { return new Promise((resolve, reject) => { let responseData = '' const req = https.request({ host: this._host, path: '/v6/servers/home', method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token }, }, (response:any) => { response.on('data', (data:any) => { console.log('data', data) responseData += data }); response.on('end', (data:any) => { if(response.statusCode === 200){ resolve(JSON.parse(responseData)) } else { reject({ status: response.statusCode }) } }); }) req.on('error', (error) => { reject(error) }); req.end(); }) } startSession(inputId:string){ return new Promise((resolve, reject) => { let postData if(this._type === 'home'){ postData = { "titleId":"", "systemUpdateGroup":"", "settings": { "nanoVersion":"V3;RtcdcTransport.dll", "enableTextToSpeech":false, "highContrast":0, "locale":"en-US", "useIceConnection":false, "timezoneOffsetMinutes":120, "sdkType":"web", "osName":"windows" }, "serverId": inputId, "fallbackRegionNames": [Array] } } else { postData = { "titleId": inputId, "systemUpdateGroup":"", "settings": { "nanoVersion":"V3;RtcdcTransport.dll", "enableTextToSpeech":false, "highContrast":0, "locale":"en-US", "useIceConnection":false, "timezoneOffsetMinutes":120, "sdkType":"web", "osName":"windows" }, "serverId": "", "fallbackRegionNames": [Array] } } const req = https.request({ // fetch('https://'+this._host+'/v5/sessions/'+this._type+'/play', { host: this._host, path: '/v5/sessions/'+this._type+'/play', method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token // 'Content-Type': 'application/x-www-form-urlencoded', } }, (response) => { let body = '' response.on('data', (chunk) => { body += chunk }); response.on('end', () => { if(response.statusCode !== 200 && response.statusCode !== 202){ console.log('Error fetching consoles. Status:', response.statusCode, 'Body:', body) reject({ status: response.statusCode, body: body }) } else { const data = JSON.parse(body) // console.log('resObject', resObject) // response.json().then((data) => { this.isProvisioningReady('/'+data.sessionPath+'/state').then((state:any) => { this._sessionPath = data.sessionPath // resolve(state) // Console can be in 2 states now: Provisioned and ReadyToConnect if(state.state === 'ReadyToConnect'){ // We need to authenticate with the MSAL token this.xcloudAuth(this._application._tokenStore._msalToken, data.sessionPath).then((authResponse) => { // Authentication ok. Lets connect! this.isProvisioningReady('/'+data.sessionPath+'/state').then((state:any) => { resolve(state) }).catch((error) =>{ reject(error) }) }).catch((error) =>{ reject(error) }) } else { // Lets connect resolve(state) } }).catch((error:any) => { reject(error) }) // }).catch((error) => { // reject(error) // }) } }); }) req.on('error', (error) => { reject(error) }); req.write(JSON.stringify(postData)) req.end() }) } isExchangeReady(url:string) { return new Promise((resolve, reject) => { // fetch('https://'+this._host+''+url, { const req = https.request({ host: this._host, path: url, method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token }, }, response => { let body = '' response.on('data', (chunk) => { body += chunk }); response.on('end', () => { if(response.statusCode !== 200){ console.log('StreamClient.js - '+url+' - Waiting...') setTimeout(() => { this.isExchangeReady(url).then((data) => { resolve(data) }).catch((error) => { reject(error) }) }, 1000) } else { const data = JSON.parse(body) console.log('StreamClient.js - '+url+' - Ready! Got data:', data) resolve(data) } }) }) req.on('error', (error) => { reject(error) }); req.end() }) } isProvisioningReady(url:string) { return new Promise((resolve, reject) => { const req = https.request({ host: this._host, path: url, method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token }, }, (response) => { let body = '' response.on('data', (chunk) => { body += chunk }); response.on('end', () => { if(response.statusCode !== 200){ console.log('xCloudPlayer Client - '+url+' - Waiting...') setTimeout(() => { this.isProvisioningReady(url).then((data:any) => { resolve(data) }).catch((error:any) => { reject(error) }) }, 1000) } else { const data = JSON.parse(body) if(data.state === 'Provisioned' || data.state === 'ReadyToConnect'){ console.log('xCloudPlayer Client - '+url+' - Ready! Got data:', data) resolve(data) } else { setTimeout(() => { this.isProvisioningReady(url).then((data:any) => { resolve(data) }).catch((error:any) => { reject(error) }) }, 1000) } } }) }) req.on('error', (error) => { reject(error) }); // req.write(JSON.stringify(postData)) req.end() }) } xcloudAuth(userToken:string, sessionPath:string){ return new Promise((resolve, reject) => { const postData = { "userToken": userToken } // console.log('tokens set: ', this._application._tokenStore) // fetch('https://'+this._host+'/'+sessionPath+'/connect', { const req = https.request({ host: this._host, path: '/'+sessionPath+'/connect', method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+ this._token } }, (response) => { let body = '' response.on('data', (chunk) => { body += chunk }) response.on('end', () => { if(response.statusCode !== 200 && response.statusCode !== 202){ console.log('Error sending login command. Status:', response.statusCode, 'Body:', body) reject('/connect call failed') } else { // console.log('OK:', response.status, 'Body:', response.body) resolve(response.statusCode) } }) }) req.on('error', (error:any) => { reject(error) }); req.write(JSON.stringify(postData)) req.end() }) } sendSdp(sdp: string){ return new Promise((resolve, reject) => { const postData = { "messageType":"offer", "sdp": sdp, "configuration":{ // "containerizeVideo":true, // "requestedH264Profile":2, "chatConfiguration":{ "bytesPerSample":2, "expectedClipDurationMs":100, "format":{ "codec":"opus", "container":"webm" }, "numChannels":1, "sampleFrequencyHz":24000 }, "audio":{ "minVersion":1, "maxVersion":1 }, "chat":{ "minVersion":1, "maxVersion":1 }, "control":{ "minVersion":1, "maxVersion":1 }, "input":{ "minVersion":1, "maxVersion":4 }, "message":{ "minVersion":1, "maxVersion":1 }, "video":{ "minVersion":1, "maxVersion":2 } } } // fetch('https://'+this._host+'/'+this._sessionPath+'/sdp', { const req = https.request({ host: this._host, path: '/'+this._sessionPath+'/sdp', method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token }, }, (response) => { if(response.statusCode !== 202){ console.log('StreamClient.js: Error sending SDP state. Status:', response.statusCode) reject({ status: response.statusCode }) } else { console.log('StreamClient.js: SDP State send ok. Status:', response.statusCode) this.isExchangeReady('/'+this._sessionPath+'/sdp').then((data:any) => { console.log('StreamClient.js: Loop done? resolve now...') const response = JSON.parse(data.exchangeResponse) resolve(response) }).catch((error) => { reject(error) }) } }) req.on('error', (error:any) => { reject(error) }); req.write(JSON.stringify(postData)) req.end() }) } sendIce(ice: string){ return new Promise((resolve, reject) => { const postData = { "messageType": "iceCandidate", "candidate": ice } // fetch('https://'+this._host+'/'+this._sessionPath+'/ice', { const req = https.request({ host: this._host, path: '/'+this._sessionPath+'/ice', method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token }, // body: JSON.stringify(postData) }, (response) => { if(response.statusCode !== 202){ console.log('StreamClient.js: Error sending ICE candidate. Status:', response.statusCode) reject({ status: response.statusCode, }) } else { this.isExchangeReady('/'+this._sessionPath+'/ice').then((data:any) => { const response = JSON.parse(data.exchangeResponse) resolve(response) }).catch((error) => { reject(error) }) } }) req.on('error', (error:any) => { reject(error) }); req.write(JSON.stringify(postData)) req.end() }) } sendKeepalive(){ return new Promise((resolve, reject) => { const req = https.request({ host: this._host, path: '/'+this._sessionPath+'/keepalive', method: 'POST', // *GET, POST, PUT, DELETE, etc. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '+this._token } }, (response) => { if(response.statusCode !== 200){ console.log('StreamClient.js: Error sending keepalive signal. Status:', response.statusCode) reject({ status: response.statusCode }) } else { resolve('ok') } }) req.on('error', (error:any) => { reject(error) }); req.write('') req.end() }) } }
the_stack
import { Directive, EventEmitter, Input, OnDestroy, Output, } from "@angular/core"; import { Control, ControlPosition, LeafletEvent, LeafletMouseEvent, Map, } from "leaflet"; import { ATTRIBUTION_PREFIX } from "./consts"; import { MapProvider } from "./map.provider"; import { enhanceMouseEvent } from "./mouse-event-helper"; /** * Angular2 directive for the attribution-control of Leaflet. * * *You can use this directive in an Angular2 template after importing `YagaModule`.* * * How to use in a template: * ```html * <yaga-map> * <yaga-attribution-control * [(display)]="..." * [(zIndex)]="..." * [(position)]="..." * [(prefix)]="..." * [(attributions)]="..." * * (add)="..." * (remove)="..." * (click)="..." * (dblclick)="..." * (mousedown)="..." * (mouseover)="..." * (mouseout)="..." * > * </yaga-attribution-control> * </yaga-map> * ``` * * @link http://leafletjs.com/reference-1.2.0.html#control-attribution Original Leaflet documentation * @link https://leaflet-ng2.yagajs.org/latest/browser-test?grep=Attribution-Control%20Directive Unit-Test * @link https://leaflet-ng2.yagajs.org/latest/coverage/lcov-report/lib/attribution-control.directive.js.html * Test coverage * @link https://leaflet-ng2.yagajs.org/latest/typedoc/classes/attributioncontroldirective.html API documentation * @example https://leaflet-ng2.yagajs.org/latest/examples/attribution-control-directive/ */ @Directive({ selector: "yaga-attribution-control", }) export class AttributionControlDirective extends Control.Attribution implements OnDestroy { /** * Two-Way bound property for the display status of the control. * Use it with `<yaga-attribution-control [(display)]="someValue">` * or `<yaga-attribution-control (displayChange)="processEvent($event)">` */ @Output() public displayChange: EventEmitter<boolean> = new EventEmitter(); /** * Two-Way bound property for the position of the control. * Use it with `<yaga-attribution-control [(position)]="someValue">` * or `<yaga-attribution-control (positionChange)="processEvent($event)">` */ @Output() public positionChange: EventEmitter<ControlPosition> = new EventEmitter(); /** * Two-Way bound property for the prefix of the control. * Use it with `<yaga-attribution-control [(prefix)]="someValue">` * or `<yaga-attribution-control (prefixChange)="processEvent($event)">` */ @Output() public prefixChange: EventEmitter<string> = new EventEmitter(); /** * Two-Way bound property for the list of attributions of the control. * Use it with `<yaga-attribution-control [(attributions)]="someValue">` * or `<yaga-attribution-control (attributionsChange)="processEvent($event)">` */ @Output() public attributionsChange: EventEmitter<string[]> = new EventEmitter(); /** * From leaflet fired add event. * Use it with `<yaga-attribution-control (add)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-add Original Leaflet documentation */ @Output("add") public addEvent: EventEmitter<LeafletEvent> = new EventEmitter(); /** * From leaflet fired remove event. * Use it with `<yaga-attribution-control (remove)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-remove Original Leaflet documentation */ @Output("remove") public removeEvent: EventEmitter<LeafletEvent> = new EventEmitter(); /** * From leaflet fired click event. * Use it with `<yaga-attribution-control (click)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-click Original Leaflet documentation */ @Output("click") public clickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter(); /** * From leaflet fired dblclick event. * Use it with `<yaga-attribution-control (dblclick)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-dblclick Original Leaflet documentation */ @Output("dblclick") public dblclickEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter(); /** * From leaflet fired mousedown event. * Use it with `<yaga-attribution-control (mousedown)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-mousedown Original Leaflet documentation */ @Output("mousedown") public mousedownEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter(); /** * From leaflet fired mouseover event. * Use it with `<yaga-attribution-control (mouseover)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-mouseover Original Leaflet documentation */ @Output("mouseover") public mouseoverEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter(); /** * From leaflet fired mouseout event. * Use it with `<yaga-attribution-control (mouseout)="processEvent($event)">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-mouseout Original Leaflet documentation */ @Output("mouseout") public mouseoutEvent: EventEmitter<LeafletMouseEvent> = new EventEmitter(); constructor( protected mapProvider: MapProvider, ) { super({prefix: ATTRIBUTION_PREFIX}); mapProvider.ref!.addControl(this); // Events this.getContainer()!.addEventListener("click", (event: MouseEvent) => { this.clickEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map)); }); this.getContainer()!.addEventListener("dblclick", (event: MouseEvent) => { this.dblclickEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map)); }); this.getContainer()!.addEventListener("mousedown", (event: MouseEvent) => { this.mousedownEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map)); }); this.getContainer()!.addEventListener("mouseover", (event: MouseEvent) => { this.mouseoverEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map)); }); this.getContainer()!.addEventListener("mouseout", (event: MouseEvent) => { this.mouseoutEvent.emit(enhanceMouseEvent(event, (this as any)._map as Map)); }); } /** * Internal method to provide the removal of the control in Leaflet, when removing it from the Angular template */ public ngOnDestroy(): void { this.mapProvider.ref!.removeControl(this); } /** * Derived remove function */ public remove(): this { /* tslint:disable */ super.remove(); this.displayChange.emit(false); this.removeEvent.emit({target: this, type: "remove"}); return this; } /** * Derived addTo function */ public addTo(map: Map) { /* tslint:disable */ super.addTo(map); this.displayChange.emit(true); this.addEvent.emit({target: this, type: "add"}); return this; } /** * Derived method of the original setPosition. * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-setposition Original Leaflet documentation */ public setPosition(val: ControlPosition): this { super.setPosition(val); this.positionChange.emit(val); return this; } /** * Two-Way bound property for the opacity. * Use it with `<yaga-attribution-control [(opacity)]="someValue">` * or `<yaga-attribution-control [opacity]="someValue">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-opacity Original Leaflet documentation */ @Input() public set opacity(val: number | undefined) { if (typeof val === "number") { this.getContainer()!.style.opacity = val.toString(); return; } this.getContainer()!.style.opacity = null; } public get opacity(): number | undefined { if (this.getContainer()!.style.opacity !== undefined && this.getContainer()!.style.opacity !== null) { return parseFloat(this.getContainer()!.style.opacity!); } return; } /** * Two-Way bound property for the display state. * Use it with `<yaga-attribution-control [(display)]="someValue">` * or `<yaga-attribution-control [display]="someValue">` */ @Input() public set display(val: boolean) { if (!(this as any)._map) { // No map available... return; } if (val) { this.getContainer()!.style.display = ""; return; } this.getContainer()!.style.display = "none"; return; } public get display(): boolean { return !!(this as any)._map && this.getContainer()!.style.display !== "none"; } /** * Two-Way bound property for the position. * Use it with `<yaga-attribution-control [(position)]="someValue">` * or `<yaga-attribution-control [position]="someValue">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-position Original Leaflet documentation */ @Input() public set position(val: ControlPosition) { this.setPosition(val); } public get position(): ControlPosition { return this.getPosition(); } /** * Input for the zIndex of the control. * Use it with `<yaga-attribution-control [zIndex]="someValue">` */ @Input() public set zIndex(zIndex: number | undefined) { if (typeof zIndex === "number") { this.getContainer()!.style.zIndex = zIndex.toString(); return; } this.getContainer()!.style.zIndex = null; } public get zIndex(): number | undefined { if (this.getContainer()!.style.zIndex !== undefined && this.getContainer()!.style.zIndex !== null) { return parseInt(this.getContainer()!.style.zIndex!, 10); } } /** * Derived method of the original setPrefix. * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-setprefix Original Leaflet documentation */ public setPrefix(prefix: string): this { super.setPrefix(prefix); this.prefixChange.emit(prefix); return this; } /** * Two-Way bound property for the prefix. * Use it with `<yaga-attribution-control [(prefix)]="someValue">` * or `<yaga-attribution-control [prefix]="someValue">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-prefix Original Leaflet documentation */ @Input() public set prefix(val: string) { this.setPrefix(val); } public get prefix(): string { return (this.options.prefix as string); } /** * Derived method of the original addAttribution. * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-addattribution Original Leaflet documentation */ public addAttribution(val: string): this { super.addAttribution(val); this.attributionsChange.emit(this.attributions); return this; } /** * Derived method of the original removeAttribution. * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-removeattribution * Original Leaflet documentation */ public removeAttribution(val: string): this { super.removeAttribution(val); this.attributionsChange.emit(this.attributions); return this; } /** * Two-Way bound property for the attributions. * Use it with `<yaga-attribution-control [(attributions)]="someValue">` * or `<yaga-attribution-control [attributions]="someValue">` * @link http://leafletjs.com/reference-1.2.0.html#control-attribution-attributions Original Leaflet documentation */ @Input() public set attributions(val: string[]) { this.removeAllAttributions(true); for (const attr of val) { super.addAttribution(attr); } this.attributionsChange.emit(this.attributions); } public get attributions(): string[] { const keys: string[] = Object.keys((this as any)._attributions); const arr: string[] = []; for (const key of keys) { if ((this as any)._attributions[key] === 1) { arr.push(key); } } return arr; } /** * Self written method to provide the removal of all attributions in a single step */ public removeAllAttributions(silent?: boolean): this { const keys: string[] = Object.keys((this as any)._attributions); for (const key of keys) { super.removeAttribution(key); } if (silent) { return this; } this.attributionsChange.emit([]); return this; } }
the_stack
* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {customMatchers} from '../../matchers/custom-matchers'; import {LoginPage} from '../../login/login.po'; import {TreeViewPage} from './tree-view.po'; import {MetronAlertsPage} from '../alerts-list.po'; import {loadTestData, deleteTestData} from '../../utils/e2e_util'; describe('Test spec for tree view', function () { let page: TreeViewPage; let listPage: MetronAlertsPage; let loginPage: LoginPage; beforeAll(async function() : Promise<any> { loginPage = new LoginPage(); page = new TreeViewPage(); listPage = new MetronAlertsPage(); await loadTestData(); await loginPage.login(); jasmine.addMatchers(customMatchers); }); afterAll(async function() : Promise<any> { await loginPage.logout(); await deleteTestData(); }); beforeEach(() => { }); it('should have all group by elements', async function() : Promise<any> { let groupByItems = { 'source:type': '1', 'ip_dst_addr': '8', 'enrichm...:country': '3', 'ip_src_addr': '6' }; expect(await listPage.getChangesAlertTableTitle('Alerts (0)')).toEqualBcoz('Alerts (169)', 'for alerts title'); expect(await page.getGroupByCount()).toEqualBcoz(Object.keys(groupByItems).length, '4 Group By Elements should be present'); expect(await page.getGroupByItemNames()).toEqualBcoz(Object.keys(groupByItems), 'Group By Elements names should be present'); expect(await page.getGroupByItemCounts()).toEqualBcoz(Object.keys(groupByItems).map(key => groupByItems[key]), '4 Group By Elements values should be present'); }); // HTML5 Drag and Drop with Selenium Webdriver issue effects this test: // https://github.com/SeleniumHQ/selenium-google-code-issue-archive/issues/3604 xit('drag and drop should change group order', async function() : Promise<any> { let before = { 'firstDashRow': ['0', 'alerts_ui_e2e', 'ALERTS', '169'], 'firstSubGroup': '0 US (22)', 'secondSubGroup': '0 RU (44)', 'thirdSubGroup': '0 FR (25)' }; let after = { 'firstDashRow': ['0', 'US', 'ALERTS', '22'], 'secondDashRow': ['0', 'RU', 'ALERTS', '44'], 'thirdDashRow': ['0', 'FR', 'ALERTS', '25'], 'firstDashSubGroup': '0 alerts_ui_e2e (22)', 'secondDashSubGroup': '0 alerts_ui_e2e (44)', 'thirdDashSubGroup': '0 alerts_ui_e2e (25)' }; await page.selectGroup('source:type'); await page.selectGroup('enrichments:geo:ip_dst_addr:country'); expect(await page.getDashGroupValues('alerts_ui_e2e')).toEqualBcoz(before.firstDashRow, 'First Dash Row should be correct'); await page.expandDashGroup('alerts_ui_e2e'); expect(await page.getSubGroupValues('alerts_ui_e2e', 'US')).toEqualBcoz(before.firstSubGroup, 'Dash Group Values should be correct for US'); expect(await page.getSubGroupValues('alerts_ui_e2e', 'RU')).toEqualBcoz(before.secondSubGroup, 'Dash Group Values should be present for RU'); expect(await page.getSubGroupValues('alerts_ui_e2e', 'FR')).toEqualBcoz(before.thirdSubGroup, 'Dash Group Values should be present for FR'); await page.simulateDragAndDrop('source:type', 'ip_src_addr'); expect(await page.getDashGroupValues('US')).toEqualBcoz(after.firstDashRow, 'First Dash Row after ' + 'reorder should be correct'); expect(await page.getDashGroupValues('RU')).toEqualBcoz(after.secondDashRow, 'Second Dash Row after ' + 'reorder should be correct'); expect(await page.getDashGroupValues('FR')).toEqualBcoz(after.thirdDashRow, 'Third Dash Row after ' + 'reorder should be correct'); await page.expandDashGroup('US'); expect(await page.getSubGroupValues('US', 'alerts_ui_e2e')).toEqualBcoz(after.firstDashSubGroup, 'First Dash Group Values should be present for alerts_ui_e2e'); await page.expandDashGroup('RU'); expect(await page.getSubGroupValues('RU', 'alerts_ui_e2e')).toEqualBcoz(after.secondDashSubGroup, 'Second Dash Group Values should be present for alerts_ui_e2e'); await page.expandDashGroup('FR'); expect(await page.getSubGroupValues('FR', 'alerts_ui_e2e')).toEqualBcoz(after.thirdDashSubGroup, 'Third Dash Group Values should be present for alerts_ui_e2e'); await page.simulateDragAndDrop('source:type', 'ip_dst_addr'); await page.unGroup(); }); // Test cannot pass until issue with missing dash score is resolved: https://issues.apache.org/jira/browse/METRON-1631 xit('should have group details for single group by', async function() : Promise<any> { let dashRowValues = ['0', 'alerts_ui_e2e', 'ALERTS', '169']; let row1_page1 = ['-','acf5a641-9...a316e14fbe', '2017-09-13 17:59:35', 'alerts_ui_e2e', '192.168.66.1', '', '192.168.66.121', 'node1', 'NEW']; let row1_page2 = ['-', '3097a3d9-f...1cfb870355', '2017-09-13 18:00:22', 'alerts_ui_e2e', '192.168.66.1', '','192.168.66.121', 'node1', 'NEW']; await page.unGroup(); await page.selectGroup('source:type'); expect(await page.getActiveGroups()).toEqualBcoz(['source:type'], 'only source type group should be selected'); expect(await page.getDashGroupValues('alerts_ui_e2e')).toEqualBcoz(dashRowValues, 'Dash Group Values should be present'); await page.expandDashGroup('alerts_ui_e2e'); expect(await page.getTableValuesByRowId('alerts_ui_e2e', 0, 'acf5a641-9...a316e14fbe')).toEqualBcoz(row1_page1, 'Dash Group Values should be present'); await page.clickOnNextPage('alerts_ui_e2e'); expect(await page.getTableValuesByRowId('alerts_ui_e2e', 0, '3097a3d9-f...1cfb870355')).toEqualBcoz(row1_page2, 'Dash Group Values should be present'); await page.unGroup(); expect(await page.getActiveGroups()).toEqualBcoz([], 'no groups should be selected'); }); it('should have group details for multiple group by', async function() : Promise<any> { let usGroupIds = ['a651f7c3-1...a97d4966c9', '5cfff1c7-6...ef3d766fc7', '7022e863-5...3c1fb629ed', '5404950f-9...86ce704b22', '8eb077ae-3...b77fed1ab4']; let frGroupIds = ['07b29c29-9...ff19eaa888', 'c27f0bd2-3...697eaf8692', 'ba44eb73-6...6f9c15b261', '6a437817-e...dd0b37d280', '48fc3a55-4...3479974d34']; await page.unGroup(); await page.selectGroup('source:type'); await page.selectGroup('ip_dst_addr'); await page.selectGroup('enrichments:geo:ip_dst_addr:country'); expect(await page.getActiveGroups()).toEqualBcoz(['source:type', 'ip_dst_addr', 'enrichm...:country'], '3 groups should be selected'); expect(await page.getDashGroupValues('alerts_ui_e2e')).toEqualBcoz(['36', 'alerts_ui_e2e', 'ALERTS', '169'], 'Top Level Group Values should be present for alerts_ui_e2e'); await page.expandDashGroup('alerts_ui_e2e'); expect(await page.getSubGroupValuesByPosition('alerts_ui_e2e', '204.152.254.221', 0)).toEqualBcoz('0 204.152.254.221 (13)', 'Second Level Group Values should be present for 204.152.254.221'); await page.expandSubGroupByPosition('alerts_ui_e2e', '204.152.254.221', 0); expect(await page.getSubGroupValuesByPosition('alerts_ui_e2e', 'US', 0)).toEqualBcoz('0 US (13)', 'Third Level Group Values should be present for US'); await page.expandSubGroup('alerts_ui_e2e', 'US'); expect(await page.getSubGroupValuesByPosition('alerts_ui_e2e', 'US', 0)).toEqualBcoz('0 US (13)', 'Third Level Group Values should not change when expanded for US'); expect(await page.getCellValuesFromTable('alerts_ui_e2e', 'id', 'a651f7c3-1...a97d4966c9')).toEqual(usGroupIds, 'rows should be present for US'); await page.expandSubGroup('alerts_ui_e2e', '62.75.195.236'); expect(await page.getSubGroupValuesByPosition('alerts_ui_e2e', 'FR', 1)).toEqualBcoz('0 FR (23)', 'Third Level Group Values should be present for FR'); await page.expandSubGroupByPosition('alerts_ui_e2e', 'FR', 1); expect(await page.getSubGroupValuesByPosition('alerts_ui_e2e', 'FR', 1)).toEqualBcoz('0 FR (23)', 'Third Level Group Values should not change when expanded for FR'); expect(await page.getCellValuesFromTable('alerts_ui_e2e', 'id', '07b29c29-9...ff19eaa888')).toEqual(usGroupIds.concat(frGroupIds), 'rows should be present for FR'); await page.unGroup(); expect(await page.getActiveGroups()).toEqualBcoz([], 'no groups should be selected'); }); it('should have sort working for group details for multiple sub groups', async function() : Promise<any> { let usTSCol = ['2017-09-13 17:59:32', '2017-09-13 17:59:42', '2017-09-13 17:59:53', '2017-09-13 18:00:02', '2017-09-13 18:00:14']; let ruTSCol = ['2017-09-13 17:59:33', '2017-09-13 17:59:48', '2017-09-13 17:59:51', '2017-09-13 17:59:54', '2017-09-13 17:59:57']; let frTSCol = ['2017-09-13 17:59:37', '2017-09-13 17:59:46', '2017-09-13 18:00:31', '2017-09-13 18:00:33', '2017-09-13 18:00:37']; let usSortedTSCol = ['2017-09-13 18:02:19', '2017-09-13 18:02:16', '2017-09-13 18:02:09', '2017-09-13 18:01:58', '2017-09-13 18:01:52']; let ruSortedTSCol = ['2017-09-14 06:29:40', '2017-09-14 06:29:40', '2017-09-14 06:29:40', '2017-09-14 06:29:40', '2017-09-13 18:02:13']; let frSortedTSCol = ['2017-09-14 06:29:40', '2017-09-14 04:29:40', '2017-09-13 18:02:20', '2017-09-13 18:02:05', '2017-09-13 18:02:04']; await page.unGroup(); await page.selectGroup('source:type'); await page.selectGroup('enrichments:geo:ip_dst_addr:country'); await page.expandDashGroup('alerts_ui_e2e'); await page.expandSubGroup('alerts_ui_e2e', 'US'); await page.expandSubGroup('alerts_ui_e2e', 'RU'); await page.expandSubGroup('alerts_ui_e2e', 'FR'); let unsortedTS = [...usTSCol, ...ruTSCol, ...frTSCol]; let sortedTS = [...usSortedTSCol, ...ruSortedTSCol, ...frSortedTSCol]; await page.sortSubGroup('alerts_ui_e2e', 'timestamp'); expect(await page.getCellValuesFromTable('alerts_ui_e2e', 'timestamp', '2017-09-13 18:00:37')).toEqual(unsortedTS, 'timestamp should be sorted asc'); await page.sortSubGroup('alerts_ui_e2e', 'timestamp'); expect(await page.getCellValuesFromTable('alerts_ui_e2e', 'timestamp', '2017-09-13 18:02:04')).toEqual(sortedTS, 'timestamp should be sorted dsc'); await page.unGroup(); expect(page.getActiveGroups()).toEqualBcoz([], 'no groups should be selected'); }); it('should have search working for group details for multiple sub groups', async function() : Promise<any> { await page.unGroup(); await listPage.setSearchText('enrichments:geo:ip_dst_addr:country:FR'); expect(await listPage.getChangesAlertTableTitle('Alerts (169)')).toEqual('Alerts (25)'); await page.selectGroup('source:type'); await page.selectGroup('enrichments:geo:ip_dst_addr:country'); await page.expandDashGroup('alerts_ui_e2e'); expect(await page.getNumOfSubGroups('alerts_ui_e2e')).toEqual(1, 'three sub groups should be present'); await page.expandSubGroup('alerts_ui_e2e', 'FR'); let expected = ['FR', 'FR', 'FR', 'FR', 'FR']; expect(await page.getCellValuesFromTable('alerts_ui_e2e', 'enrichments:geo:ip_dst_addr:country', 'FR')).toEqual(expected, 'id should be sorted'); await page.unGroup(); }); });
the_stack
import { StorageTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import ethereumEntriesToIpfsContent from '../src/ethereum-entries-to-ipfs-content'; import IgnoredDataIndex from '../src/ignored-dataIds'; import IpfsConnectionError from '../src/ipfs-connection-error'; /* eslint-disable no-magic-numbers */ let ignoredDataIndex: IgnoredDataIndex; let ipfsManager: any; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('ethereum-entries-to-ipfs-content', () => { beforeEach(async () => { ignoredDataIndex = new IgnoredDataIndex(); ipfsManager = {}; }); it('can retry the right hashes', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); const connectionErrorSpy = jest.fn(() => { throw new IpfsConnectionError(`Ipfs read request response error: test purpose`); }); const incorrectErrorSpy = jest.fn(() => { throw new Error('Incorrect file test'); }); const biggerErrorSpy = jest.fn(() => ({ content: 'bigger', ipfsLinks: [], ipfsSize: 5, })); const okSpy = jest.fn(() => ({ content: 'ok', ipfsLinks: [], ipfsSize: 2, })); ipfsManager.read = jest.fn(async (hash: string): Promise<StorageTypes.IIpfsObject> => { if (hash === 'hConnectionError') { return connectionErrorSpy(); } else if (hash === 'hIncorrectFile') { return incorrectErrorSpy(); } else if (hash === 'hBiggerFile') { return biggerErrorSpy(); } else { return okSpy(); } }); const ethereumEntriesToProcess: StorageTypes.IEthereumEntry[] = [ { hash: 'hConnectionError', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hIncorrectFile', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hBiggerFile', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hOk', feesParameters: { contentSize: 3 }, meta: {} as any }, ]; const result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(1); expect(result[0]!.content).toBe('ok'); expect(result[0]!.id).toBe('hOk'); const ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({ hBiggerFile: { entry: { error: { message: 'Incorrect declared size', type: StorageTypes.ErrorEntries.WRONG_FEES, }, feesParameters: { contentSize: 3, }, hash: 'hBiggerFile', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: false, }, hConnectionError: { entry: { error: { message: 'Ipfs read request response error: test purpose', type: StorageTypes.ErrorEntries.IPFS_CONNECTION_ERROR, }, feesParameters: { contentSize: 3, }, hash: 'hConnectionError', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: true, }, hIncorrectFile: { entry: { error: { message: 'Incorrect file test', type: StorageTypes.ErrorEntries.INCORRECT_FILE, }, feesParameters: { contentSize: 3, }, hash: 'hIncorrectFile', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: false, }, }); expect(ipfsManager.read).toHaveBeenCalledTimes(5); expect(connectionErrorSpy).toHaveBeenCalledTimes(2); expect(incorrectErrorSpy).toHaveBeenCalledTimes(1); expect(biggerErrorSpy).toHaveBeenCalledTimes(1); expect(okSpy).toHaveBeenCalledTimes(1); jest.useRealTimers(); }); it('can retry right hashes but find it after the retry', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); const connectionErrorSpy = jest.fn(() => { throw new IpfsConnectionError(`Ipfs read request response error: test purpose`); }); const incorrectErrorSpy = jest.fn(() => { throw new Error('Incorrect file test'); }); const biggerErrorSpy = jest.fn(() => ({ content: 'bigger', ipfsLinks: [], ipfsSize: 5, })); const okSpy = jest.fn(() => ({ content: 'ok', ipfsLinks: [], ipfsSize: 2, })); let tryCount = 0; ipfsManager.read = jest.fn(async (hash: string): Promise<StorageTypes.IIpfsObject> => { if (hash === 'hConnectionError' && tryCount === 0) { tryCount++; return connectionErrorSpy(); } else if (hash === 'hIncorrectFile') { return incorrectErrorSpy(); } else if (hash === 'hBiggerFile') { return biggerErrorSpy(); } else { return okSpy(); } }); const ethereumEntriesToProcess: StorageTypes.IEthereumEntry[] = [ { hash: 'hConnectionError', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hIncorrectFile', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hBiggerFile', feesParameters: { contentSize: 3 }, meta: {} as any }, { hash: 'hOk', feesParameters: { contentSize: 3 }, meta: {} as any }, ]; const result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(2); expect(result[0]!.content).toBe('ok'); expect(result[0]!.id).toBe('hOk'); expect(result[1]!.content).toBe('ok'); expect(result[1]!.id).toBe('hConnectionError'); const ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({ hBiggerFile: { entry: { error: { message: 'Incorrect declared size', type: StorageTypes.ErrorEntries.WRONG_FEES, }, feesParameters: { contentSize: 3, }, hash: 'hBiggerFile', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: false, }, hIncorrectFile: { entry: { error: { message: 'Incorrect file test', type: StorageTypes.ErrorEntries.INCORRECT_FILE, }, feesParameters: { contentSize: 3, }, hash: 'hIncorrectFile', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: false, }, }); expect(ipfsManager.read).toHaveBeenCalledTimes(5); expect(connectionErrorSpy).toHaveBeenCalledTimes(1); expect(incorrectErrorSpy).toHaveBeenCalledTimes(1); expect(biggerErrorSpy).toHaveBeenCalledTimes(1); expect(okSpy).toHaveBeenCalledTimes(2); jest.useRealTimers(); }); it('can store hash as ignored then remove it', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); ipfsManager.read = jest.fn(() => { throw new IpfsConnectionError(`Ipfs read request response error: test purpose`); }); const ethereumEntriesToProcess: StorageTypes.IEthereumEntry[] = [ { hash: 'hConnectionError', feesParameters: { contentSize: 3 }, meta: {} as any }, ]; let result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(0); let ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({ hConnectionError: { entry: { error: { message: 'Ipfs read request response error: test purpose', type: StorageTypes.ErrorEntries.IPFS_CONNECTION_ERROR, }, feesParameters: { contentSize: 3, }, hash: 'hConnectionError', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: true, }, }); expect(ipfsManager.read).toHaveBeenCalledTimes(2); // Then we find it: ipfsManager.read = jest.fn( async (_hash: string): Promise<StorageTypes.IIpfsObject> => ({ content: 'ok', ipfsLinks: [], ipfsSize: 2, }), ); result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(1); expect(result[0]!.content).toBe('ok'); expect(result[0]!.id).toBe('hConnectionError'); ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({}); jest.useRealTimers(); }); it('can store hash as ignored it twice', async () => { jest.useFakeTimers('modern'); jest.setSystemTime(0); ipfsManager.read = jest.fn(() => { throw new IpfsConnectionError(`Ipfs read request response error: test purpose`); }); const ethereumEntriesToProcess: StorageTypes.IEthereumEntry[] = [ { hash: 'hConnectionError', feesParameters: { contentSize: 3 }, meta: {} as any }, ]; let result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(0); let ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({ hConnectionError: { entry: { error: { message: 'Ipfs read request response error: test purpose', type: StorageTypes.ErrorEntries.IPFS_CONNECTION_ERROR, }, feesParameters: { contentSize: 3, }, hash: 'hConnectionError', meta: {}, }, iteration: 1, lastTryTimestamp: 0, toRetry: true, }, }); expect(ipfsManager.read).toHaveBeenCalledTimes(2); jest.advanceTimersByTime(100); result = await ethereumEntriesToIpfsContent( ethereumEntriesToProcess, ipfsManager, ignoredDataIndex, new Utils.SimpleLogger(), 5, ); expect(result.length).toBe(0); ignoredData = await ignoredDataIndex.getDataIdsWithReasons(); expect(ignoredData).toEqual({ hConnectionError: { entry: { error: { message: 'Ipfs read request response error: test purpose', type: StorageTypes.ErrorEntries.IPFS_CONNECTION_ERROR, }, feesParameters: { contentSize: 3, }, hash: 'hConnectionError', meta: {}, }, iteration: 2, lastTryTimestamp: 100, toRetry: true, }, }); jest.useRealTimers(); }); });
the_stack
import { exec, spawn, ChildProcessByStdio } from "child_process"; import * as fs from "fs"; import glob from "glob"; import * as path from "path"; import stringArgv from "string-argv"; import * as util from "util"; import which from "which"; import * as chalk_ from "chalk"; const chalk = chalk_.default; class ErrorPathDoesNotExists extends Error { constructor(p: string) { super(`Path ${p} does not exist`); } } const pathExists = (p: string) => new Promise<boolean>((resolve) => { fs.access(p, (err) => resolve(err === null)); }); const runExternal = (extCmd: string): Promise<[string, Error]> => new Promise((resolve) => { exec(extCmd, (err, stdout) => { resolve([stdout.trim(), err]); }); }); const resolveBin = async (name: string): Promise<[string, Error]> => { const [binsPath, err] = await runExternal("npm bin"); if (err) { return ["", err]; } const binPath = path.join(binsPath, name); if (!await pathExists(binPath)) { return ["", new ErrorPathDoesNotExists(binPath)]; } return [binPath, null]; }; interface IGlobMatch { Errs: Error[]; Matches: string[]; } const runGlob = async (pattern: string, options: glob.IOptions) => new Promise<IGlobMatch>((resolve) => { glob(pattern, options, (err, matches) => resolve({Errs: err ? [err] : null, Matches: matches})); }); const runGlobs = async (globs: string[], options: glob.IOptions) => { const r = await Promise.all(globs.map((g) => runGlob(g, options))); return { Errs: [].concat(r.filter((x) => !!x.Errs)), Matches: [].concat(...r.map((x) => x.Matches)), }; }; export type Domain = null | string | string[]; export interface IFactor { readonly Input: Domain; readonly Output: Domain; readonly MustRun: boolean; run(argv?: string[]): Promise<Error>; factor(input: Domain, output?: Domain): IFactor; must(): IFactor; } const norm = (d: Domain): string[] => { const dom = !d ? [] : typeof d === "string" ? [d] : d; if (dom.length < 2) { return dom; } const tab: {[name in string]: boolean} = {}; for (const s of dom) { tab[s] = true; } return Object.getOwnPropertyNames(tab); }; const fileStat = util.promisify(fs.stat); function printErrors(errs: Error[]) { for (const err of errs) { console.error(err); } } export interface IReportedError extends Error { reported: boolean; } export const isReported = (e: Error): e is IReportedError => !!((e as IReportedError).reported); export class ErrorNothingToDo extends Error implements IReportedError { constructor(public nothingToDo: boolean = true, public reported: boolean = true) { super(""); } } export const isNothingToDo = (e: Error): e is ErrorNothingToDo => !!((e as ErrorNothingToDo).nothingToDo); const trgPrefix = chalk.blue.bold("TARGET: "); const cmdPrefix = chalk.gray.bold("COMMAND: "); const tskPrefix = chalk.green.bold("TASK: "); const sccPrefix = chalk.blue.bold("SUCCEED: "); const errPrefix = chalk.redBright.bold("ERROR IN: "); const notPrefix = chalk.blue.bold("NO TASKS: "); export class Factor implements IFactor { private name: string = null; private taskInfo: string = null; private mustRun: boolean = false; constructor( readonly Input: Domain, readonly Output: Domain, private runf: (argv?: string[]) => Promise<Error>, ) {} public async run(argv?: string[]): Promise<Error> { if (this.name) { console.log("\n" + trgPrefix + this.name); } if (this.taskInfo) { console.log(`${tskPrefix}${this.taskInfo}`); } const err = await this.runf(argv); if (this.name) { if (err) { if (err instanceof ErrorNothingToDo) { console.log(`${notPrefix}${this.name}`); } else if (!isReported(err)) { (err as IReportedError).reported = true; console.log(`${errPrefix}${this.name}, ${err}`); } } else { console.log(sccPrefix + this.name); } } return err; } public factor(input: Domain, output?: Domain): IFactor { return factor(this, input, output); } public get MustRun(): boolean { return this.mustRun; } public must(): IFactor { this.mustRun = true; return this; } public named(name: string) { // DO NOT CALL THIS INSIDE FAQTOR LIBRARY! this.name = name; return this; } public task(info: string) { // DO NOT CALL THIS INSIDE FAQTOR LIBRARY! this.taskInfo = info; return this; } } export function factor(f: IFactor, input: Domain, output: Domain = null): IFactor { const inp = norm(norm(input).concat(norm(f.Input))); const outp = norm(norm(output).concat(norm(f.Output))); const run = async (argv?: string[]) => { // always run factor if no input globs: if (!inp.length) { return await f.run(argv); } const filesIn = await runGlobs(inp, {}); if (filesIn.Errs.length) { printErrors(filesIn.Errs); } // nothing to do if has globs but no files: if (!filesIn.Matches.length) { return new ErrorNothingToDo(); } // always run factor if no output files: if (!outp.length) { return await f.run(argv); } const filesOut = await runGlobs(outp, {}); if (filesOut.Errs.length) { printErrors(filesOut.Errs); } // always run factor if has output globs but no files: if (!filesOut.Matches.length) { return await f.run(argv); } const statsIn = await Promise.all(filesIn.Matches.map(async (x) => fileStat(x))); const statsOut = await Promise.all(filesOut.Matches.map(async (x) => fileStat(x))); const inModified = Math.max(...statsIn.map((x) => x.mtime.getTime())); const outModified = Math.max(...statsOut.map((x) => x.mtime.getTime())); if (inModified > outModified) { return await f.run(argv); } return new ErrorNothingToDo(); }; return new Factor(inp, outp, run); } class ErrorNonZeroExitCode extends Error { constructor(cmdName: string, code: number) { super(`Process ${cmdName} exited with code ${code}`); } } async function runCommand(extCmd: string, ...args: string[]): Promise<Error> { return await new Promise((resolve) => { let proc: ChildProcessByStdio<null, null, null> = null; if (!/^win/.test(process.platform)) { // linux proc = spawn(extCmd, args, {stdio: [process.stdin, process.stdout, process.stderr]}); } else { // windows proc = spawn('cmd', ['/s', '/c', path.basename(extCmd), ...args], {stdio: [process.stdin, process.stdout, process.stderr]}); } proc.on("exit", (code) => resolve(code ? new ErrorNonZeroExitCode(extCmd, code) : null)); proc.on("error", (err) => resolve(err)); }); } export const func = ( f: (argv?: string[]) => Promise<Error>, input: Domain = null, output: Domain = null): IFactor => new Factor(input, output, f); export const cmd = (s: string): IFactor => { s = s.trim(); const argv = stringArgv(s); const run = async (args?: string[]) => { args = args ? argv.concat(args) : argv; if (!args.length) { return null; } let err: Error = null; let rpath: string; [rpath, err] = await resolveBin(args[0]); if (!err) { const extCmd = rpath; const intCmd = args[0]; const txt = (extCmd + " " + s.replace(intCmd, "")).trim() console.log(cmdPrefix + txt); return await runCommand(rpath, ...args.slice(1)); } [err, rpath] = await new Promise((resolve) => { which(args[0], (e, p) => resolve([e, p])); }); if (!err) { const extCmd = rpath; const intCmd = args[0]; const txt = (extCmd + " " + s.replace(intCmd, "")).trim() console.log(cmdPrefix + txt); return await runCommand(rpath, ...args.slice(1)); } return err; }; return new Factor(null, null, run); }; export const seq = (...factors: IFactor[]): IFactor => { let depends: Domain = []; let results: Domain = []; for (const f of factors) { depends = norm(depends.concat(norm(f.Input))); results = norm(results.concat(norm(f.Output))); } const run = async (argv?: string[]) => { let err: Error = null; let i = 0; for (; i < factors.length; i++) { const f = factors[i]; if (err && !isNothingToDo(err)) { if (f.MustRun) await f.run(); } else { err = await f.run(); } } return err; }; return new Factor(depends, results, run); }; export const cmds = (...c: string[]): IFactor => seq(...c.map((s) => cmd(s))); const errorsToString = (errors: Error[]): string => { let msg = "Errors occured:\n"; for (const e of errors) { msg += `\t${e}\n` } return msg; } class CompoundError extends Error { constructor(errors: Error[]) { super(errorsToString(errors)); } } export const all = (...tsk: IFactor[]): IFactor => { const run = async (argv?: string[]): Promise<Error> => { let result = await Promise.all(tsk.map((t) => t.run(argv))); result = result.filter((e) => e && !isReported(e)); if (result.length) return new CompoundError(result); return null; } return func(run); } export let production = true; export let mode = "production"; export const setMode = (name?: string) => { if (name) { mode = name; const prodSyn = {prod: 1, production: 1}; production = mode in prodSyn; } } setMode((global as any).FAQTOR_MODE);
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormOmnichannel_session_form { interface Header extends DevKit.Controls.IHeader { /** Status of the activity. */ StateCode: DevKit.Controls.OptionSet; } interface tab__E74AC0DC_7C2F_4E02_9235_A56E038611BA_Sections { } interface tab__E74AC0DC_7C2F_4E02_9235_A56E038611BA extends DevKit.Controls.ITab { Section: tab__E74AC0DC_7C2F_4E02_9235_A56E038611BA_Sections; } interface Tabs { _E74AC0DC_7C2F_4E02_9235_A56E038611BA: tab__E74AC0DC_7C2F_4E02_9235_A56E038611BA; } interface Body { Tab: Tabs; /** Date and time when session was accepted by agent */ msdyn_agentacceptedon: DevKit.Controls.DateTime; /** Date and time when session was assigned to agent */ msdyn_agentassignedon: DevKit.Controls.DateTime; /** The channel type of the session */ msdyn_channel: DevKit.Controls.OptionSet; /** Unique Identifier of Conversation associated to the session */ msdyn_liveworkitemid: DevKit.Controls.Lookup; /** Date and time when session was closed */ msdyn_sessionclosedon: DevKit.Controls.DateTime; /** Date and time when session was created */ msdyn_sessioncreatedon: DevKit.Controls.DateTime; /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the object with which the activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Subject associated with the activity. */ Subject: DevKit.Controls.String; } interface Navigation { nav_msdyn_msdyn_ocsession_msdyn_ocliveworkitem_lastsessionid: DevKit.Controls.NavigationItem, nav_msdyn_ocsession_sessionevent_nested: DevKit.Controls.NavigationItem, nav_msdyn_ocsession_sessionparticipant_nested: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem } interface Grid { session_participants: DevKit.Controls.Grid; } } class FormOmnichannel_session_form extends DevKit.IForm { /** * DynamicsCrm.DevKit form Omnichannel_session_form * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Omnichannel_session_form */ Body: DevKit.FormOmnichannel_session_form.Body; /** The Header section of form Omnichannel_session_form */ Header: DevKit.FormOmnichannel_session_form.Header; /** The Navigation of form Omnichannel_session_form */ Navigation: DevKit.FormOmnichannel_session_form.Navigation; /** The Grid of form Omnichannel_session_form */ Grid: DevKit.FormOmnichannel_session_form.Grid; } class msdyn_ocsessionApi { /** * DynamicsCrm.DevKit msdyn_ocsessionApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Additional information provided by the external application as JSON. For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Actual duration of the activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Actual end time of the activity. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Actual start time of the activity. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Description of the activity. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Information regarding whether the activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information regarding whether the activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the activitypointer. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when session was accepted by agent */ msdyn_agentacceptedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Date and time when session was assigned to agent */ msdyn_agentassignedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Indicates when a bot was engaged */ msdyn_botengagementmode: DevKit.WebApi.OptionSetValue; /** Unique identifier for Queue associated with Session. */ msdyn_cdsqueueid: DevKit.WebApi.LookupValue; /** The channel type of the session */ msdyn_channel: DevKit.WebApi.OptionSetValue; /** Reason for session closure */ msdyn_closurereason: DevKit.WebApi.OptionSetValue; /** Unique Identifier of Conversation associated to the session */ msdyn_liveworkitemid: DevKit.WebApi.LookupValue; /** Reference to primary session. */ msdyn_primarysession: DevKit.WebApi.LookupValue; /** Date and time when queue was assigned to session */ msdyn_queueassignedon_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Queue associated to the session */ msdyn_queueid: DevKit.WebApi.LookupValue; /** Date and time when session was closed */ msdyn_sessionclosedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Date and time when session was created */ msdyn_sessioncreatedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique Identifier of Session */ msdyn_sessionid: DevKit.WebApi.StringValue; /** Date and time when session was last modified */ msdyn_sessionmodifiedon_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** (Deprecated) */ msdyn_state: DevKit.WebApi.OptionSetValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of the activity. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_account_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebooking_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebookingheader_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bulkoperation_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaign_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaignactivity_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contact_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contract_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlement_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlementtemplate_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_incident_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_new_interactionforemail_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_invoice_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgearticle_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgebaserecord_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_lead_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreement_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingrule_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_customerasset_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryjournal_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventorytransfer_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_payment_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentdetail_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentmethod_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentterm_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_playbookinstance_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalbum_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalcode_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_processnotes_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_productinventory_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_projectteam_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorder_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingincident_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservice_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_resourceterritory_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rma_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmaproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceipt_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmasubstatus_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtv_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_shipvia_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroup_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroupdetail_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timeoffrequest_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_warehouse_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorder_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderincident_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderproduct_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservice_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservicetask_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_opportunity_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_quote_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_salesorder_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_site_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_action_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_hostedapplication_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_nonhostedapplication_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_option_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_savedsession_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflowstep_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_msdyn_ocsession: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Scheduled duration of the activity, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Scheduled end time of the activity. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Scheduled start time of the activity. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of an associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Status of the activity. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the activity. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Subject associated with the activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the activitypointer. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace msdyn_ocsession { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum msdyn_botengagementmode { /** 192350000 */ Default, /** 192350003 */ OffBusinessHour, /** 192350002 */ PostConverstation, /** 192350001 */ PreConversation } enum msdyn_channel { /** 192390000 */ Co_browse, /** 192350002 */ Custom, /** 192350000 */ Entity_Records, /** 192330000 */ Facebook, /** 192310000 */ LINE, /** 192360000 */ Live_chat, /** 19241000 */ Microsoft_Teams, /** 192400000 */ Screen_sharing, /** 192340000 */ SMS, /** 192350001 */ Twitter, /** 192380000 */ Video, /** 192370000 */ Voice, /** 192320000 */ WeChat, /** 192300000 */ WhatsApp } enum msdyn_closurereason { /** 192350004 */ AgentClosed, /** 192350007 */ AgentDisconnected, /** 192350001 */ AgentReject, /** 192350008 */ AgentReRouted, /** 192350002 */ AgentTimeout, /** 192350006 */ AgentTransfered, /** 192350010 */ AgentTransferToQueue, /** 192350005 */ ConversationClosed, /** 192350003 */ ConversationTimeout, /** 192350000 */ Default, /** 192350011 */ SupervisorAssignToQueue, /** 192350009 */ VirtualAgentClosed } enum msdyn_state { /** 192350001 */ Active, /** 192350002 */ Closed, /** 192350000 */ Default, /** 192350003 */ New } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open, /** 3 */ Scheduled } enum StatusCode { /** 3 */ Canceled, /** 2 */ Completed, /** 1 */ Open, /** 4 */ Scheduled } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Omnichannel session form'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import {AnimationCall, AnimationFlags, TweenStep} from "../../velocity.d"; // Project import {now} from "../utility"; import Velocity from "../velocity"; import {completeCall} from "./complete"; import {removeNestedCalc} from "./css/removeNestedCalc"; import {setPropertyValue} from "./css/setPropertyValue"; import {Data} from "./data"; import {defaults} from "./defaults"; import {linearEasing} from "./easing/easings"; import {freeAnimationCall} from "./queue"; import {State} from "./state"; import {validateTweens} from "./tweens"; /** * Call the begin method of an animation in a separate function so it can * benefit from JIT compiling while still having a try/catch block. */ export function beginCall(activeCall: AnimationCall) { const callback = activeCall.begin || activeCall.options.begin; if (callback) { try { const elements = activeCall.elements; callback.call(elements, elements, activeCall); } catch (error) { setTimeout(() => { throw error; }, 1); } } } /** * Call the progress method of an animation in a separate function so it can * benefit from JIT compiling while still having a try/catch block. */ function progressCall(activeCall: AnimationCall) { const callback = activeCall.progress || activeCall.options.progress; if (callback) { try { const elements = activeCall.elements, percentComplete = activeCall.percentComplete, options = activeCall.options, tweenValue = activeCall.tween; callback.call(elements, elements, percentComplete, Math.max(0, activeCall.timeStart + (activeCall.duration != null ? activeCall.duration : options.duration != null ? options.duration : defaults.duration) - lastTick), tweenValue !== undefined ? tweenValue : String(percentComplete * 100), activeCall); } catch (error) { setTimeout(() => { throw error; }, 1); } } } /** * Call callbacks, potentially run async with the main animation thread. */ function asyncCallbacks() { for (const activeCall of progressed) { progressCall(activeCall); } progressed.clear(); for (const activeCall of completed) { completeCall(activeCall); } completed.clear(); } /************** Timing **************/ const FRAME_TIME = 1000 / 60, /** * Animations with a Complete callback. */ completed = new Set<AnimationCall>(), /** * Animations with a Progress callback. */ progressed = new Set<AnimationCall>(), /** * Shim for window.performance in case it doesn't exist */ performance = (() => { const perf = window.performance || {} as Performance; if (typeof perf.now !== "function") { const nowOffset = perf.timing && perf.timing.navigationStart ? perf.timing.navigationStart : now(); perf.now = () => { return now() - nowOffset; }; } return perf; })(), /** * Proxy function for when rAF is not available. * * This should hopefully never be used as the browsers often throttle * this to less than one frame per second in the background, making it * completely unusable. */ rAFProxy = (callback: FrameRequestCallback) => { return setTimeout(callback, Math.max(0, FRAME_TIME - (performance.now() - lastTick))); }, /** * Either requestAnimationFrame, or a shim for it. */ rAFShim = window.requestAnimationFrame || rAFProxy; /** * Set if we are currently inside a tick() to prevent double-calling. */ let ticking: boolean, /** * A background WebWorker that sends us framerate messages when we're in * the background. Without this we cannot maintain frame accuracy. */ worker: Worker; /** * The time that the last animation frame ran at. Set from tick(), and used * for missing rAF (ie, when not in focus etc). */ export let lastTick: number = 0; /** * WebWorker background function. * * When we're in the background this will send us a msg every tick, when in * the foreground it won't. * * When running in the background the browser reduces allowed CPU etc, so * we raun at 30fps instead of 60fps. */ function workerFn(this: Worker) { let interval: any; this.onmessage = (e) => { switch (e.data) { case true: if (!interval) { interval = setInterval(() => { this.postMessage(true); }, 1000 / 30); } break; case false: if (interval) { clearInterval(interval); interval = 0; } break; default: this.postMessage(e.data); break; } }; } try { // Create the worker - this might not be supported, hence the try/catch. worker = new Worker(URL.createObjectURL(new Blob([`(${workerFn})()`]))); // Whenever the worker sends a message we tick() worker.onmessage = (e: MessageEvent) => { if (e.data === true) { tick(); } else { asyncCallbacks(); } }; // And watch for going to the background to start the WebWorker running. if (!State.isMobile && document.hidden !== undefined) { document.addEventListener("visibilitychange", () => { worker.postMessage(State.isTicking && document.hidden); }); } } catch (e) { /* * WebWorkers are not supported in this format. This can happen in IE10 * where it can't create one from a blob this way. We fallback, but make * no guarantees towards accuracy in this case. */ } /** * Called on every tick, preferably through rAF. This is reponsible for * initialising any new animations, then starting any that need starting. * Finally it will expand any tweens and set the properties relating to * them. If there are any callbacks relating to the animations then they * will attempt to call at the end (with the exception of "begin"). */ export function tick(timestamp?: number | boolean) { if (ticking) { // Should never happen - but if we've swapped back from hidden to // visibile then we want to make sure return; } ticking = true; /* An empty timestamp argument indicates that this is the first tick occurence since ticking was turned on. We leverage this metadata to fully ignore the first tick pass since RAF's initial pass is fired whenever the browser's next tick sync time occurs, which results in the first elements subjected to Velocity calls being animated out of sync with any elements animated immediately thereafter. In short, we ignore the first RAF tick pass so that elements being immediately consecutively animated -- instead of simultaneously animated by the same Velocity call -- are properly batched into the same initial RAF tick and consequently remain in sync thereafter. */ if (timestamp !== false) { const timeCurrent = performance.now(), deltaTime = lastTick ? timeCurrent - lastTick : FRAME_TIME, defaultSpeed = defaults.speed, defaultEasing = defaults.easing, defaultDuration = defaults.duration; let activeCall: AnimationCall, nextCall: AnimationCall; if (deltaTime >= defaults.minFrameTime || !lastTick) { lastTick = timeCurrent; /******************** Call Iteration ********************/ // Expand any tweens that might need it. while (State.firstNew) { validateTweens(State.firstNew); } // Iterate through each active call. for (activeCall = State.first; activeCall && activeCall !== State.firstNew; activeCall = activeCall._next) { const element = activeCall.element, data = Data(element); // Check to see if this element has been deleted midway // through the animation. If it's gone then end this // animation. if (!element.parentNode || !data) { // TODO: Remove safely - decrease count, delete data, remove from arrays freeAnimationCall(activeCall); continue; } // Don't bother getting until we can use these. const options = activeCall.options, flags = activeCall._flags; let timeStart = activeCall.timeStart; // If this is the first time that this call has been // processed by tick() then we assign timeStart now so that // it's value is as close to the real animation start time // as possible. if (!timeStart) { const queue = activeCall.queue != null ? activeCall.queue : options.queue; timeStart = timeCurrent - deltaTime; if (queue !== false) { timeStart = Math.max(timeStart, data.lastFinishList[queue] || 0); } activeCall.timeStart = timeStart; } // If this animation is paused then skip processing unless // it has been set to resume. if (flags & AnimationFlags.PAUSED) { // tslint:disable-line:no-bitwise // Update the time start to accomodate the paused // completion amount. activeCall.timeStart += deltaTime; continue; } // Check if this animation is ready - if it's synced then it // needs to wait for all other animations in the sync if (!(flags & AnimationFlags.READY)) { // tslint:disable-line:no-bitwise activeCall._flags |= AnimationFlags.READY; // tslint:disable-line:no-bitwise options._ready++; } } // Need to split the loop, as ready sync animations must all get // the same start time. for (activeCall = State.first; activeCall && activeCall !== State.firstNew; activeCall = nextCall) { const flags = activeCall._flags; nextCall = activeCall._next; if (!(flags & AnimationFlags.READY) || (flags & AnimationFlags.PAUSED)) { // tslint:disable-line:no-bitwise continue; } const options = activeCall.options; if ((flags & AnimationFlags.SYNC) && options._ready < options._total) { // tslint:disable-line:no-bitwise activeCall.timeStart += deltaTime; continue; } const speed = activeCall.speed != null ? activeCall.speed : options.speed != null ? options.speed : defaultSpeed; let timeStart = activeCall.timeStart; // Don't bother getting until we can use these. if (!(flags & AnimationFlags.STARTED)) { // tslint:disable-line:no-bitwise const delay = activeCall.delay != null ? activeCall.delay : options.delay; // Make sure anything we've delayed doesn't start // animating yet, there might still be an active delay // after something has been un-paused if (delay) { if (timeStart + (delay / speed) > timeCurrent) { continue; } activeCall.timeStart = timeStart += delay / (delay > 0 ? speed : 1); } activeCall._flags |= AnimationFlags.STARTED; // tslint:disable-line:no-bitwise // The begin callback is fired once per call, not once // per element, and is passed the full raw DOM element // set as both its context and its first argument. if (options._started++ === 0) { options._first = activeCall; if (options.begin) { // Pass to an external fn with a try/catch block for optimisation beginCall(activeCall); // Only called once, even if reversed or repeated options.begin = undefined; } } } if (speed !== 1) { // On the first frame we may have a shorter delta // const delta = Math.min(deltaTime, timeCurrent - timeStart); activeCall.timeStart = timeStart += Math.min(deltaTime, timeCurrent - timeStart) * (1 - speed); } const activeEasing = activeCall.easing != null ? activeCall.easing : options.easing != null ? options.easing : defaultEasing, millisecondsEllapsed = activeCall.ellapsedTime = timeCurrent - timeStart, duration = activeCall.duration != null ? activeCall.duration : options.duration != null ? options.duration : defaultDuration, percentComplete = activeCall.percentComplete = Velocity.mock ? 1 : Math.min(millisecondsEllapsed / duration, 1), tweens = activeCall.tweens, reverse = flags & AnimationFlags.REVERSE; // tslint:disable-line:no-bitwise if (activeCall.progress || (options._first === activeCall && options.progress)) { progressed.add(activeCall); } if (percentComplete === 1) { completed.add(activeCall); } // tslint:disable-next-line:forin for (const property in tweens) { // For every element, iterate through each property. const tween = tweens[property], sequence = tween.sequence, pattern = sequence.pattern; let currentValue = "", i = 0; if (pattern) { const easingComplete = (tween.easing || activeEasing)(percentComplete, 0, 1, property); let best = 0; for (let j = 0; j < sequence.length - 1; j++) { if (sequence[j].percent < easingComplete) { best = j; } } const tweenFrom: TweenStep = sequence[best], tweenTo: TweenStep = sequence[best + 1] || tweenFrom, rawPercent = (percentComplete - tweenFrom.percent) / (tweenTo.percent - tweenFrom.percent), tweenPercent = reverse ? 1 - rawPercent : rawPercent, easing = tweenTo.easing || activeEasing || linearEasing; for (; i < pattern.length; i++) { const startValue = tweenFrom[i]; if (startValue == null) { currentValue += pattern[i]; } else { const endValue = tweenTo[i]; if (startValue === endValue) { currentValue += startValue; } else { // All easings must deal with numbers except for our internal ones. const result = easing(tweenPercent, startValue as number, endValue as number, property); currentValue += pattern[i] !== true ? result : Math.round(result); } } } if (property !== "tween") { if (percentComplete === 1) { currentValue = removeNestedCalc(currentValue); } // TODO: To solve an IE<=8 positioning bug, the unit type must be dropped when setting a property value of 0 - add normalisations to legacy setPropertyValue(activeCall.element, property, currentValue, tween.fn); } else { // Skip the fake 'tween' property as that is only // passed into the progress callback. activeCall.tween = currentValue; } } else { console.warn(`VelocityJS: Missing pattern:`, property, JSON.stringify(tween[property])); delete tweens[property]; } } } if (progressed.size || completed.size) { if (!document.hidden) { asyncCallbacks(); } else if (worker) { worker.postMessage(""); } else { setTimeout(asyncCallbacks, 1); } } } } if (State.first) { State.isTicking = true; if (!document.hidden) { rAFShim(tick); } else if (!worker) { rAFProxy(tick); } else if (timestamp === false) { // Make sure we turn on the messages. worker.postMessage(true); } } else { State.isTicking = false; lastTick = 0; if (document.hidden && worker) { // Make sure we turn off the messages. worker.postMessage(false); } } ticking = false; }
the_stack
import { $TSAny, $TSContext, AmplifySupportedService, stateManager } from 'amplify-cli-core'; import { prompter } from 'amplify-prompts'; import * as uuid from 'uuid'; import { AmplifyS3ResourceStackTransform } from '../../../../provider-utils/awscloudformation/cdk-stack-builder/s3-stack-transform'; import { S3AccessType, S3PermissionType, S3TriggerFunctionType, S3UserInputs, } from '../../../../provider-utils/awscloudformation/service-walkthrough-types/s3-user-input-types'; import * as s3AuthAPI from '../../../../provider-utils/awscloudformation/service-walkthroughs/s3-auth-api'; import { S3CLITriggerUpdateMenuOptions, UserPermissionTypeOptions, } from '../../../../provider-utils/awscloudformation/service-walkthroughs/s3-questions'; import { MigrationParams, S3InputState } from '../../../../provider-utils/awscloudformation/service-walkthroughs/s3-user-input-state'; import { addWalkthrough, updateWalkthrough } from '../../../../provider-utils/awscloudformation/service-walkthroughs/s3-walkthrough'; jest.mock('amplify-cli-core'); jest.mock('amplify-prompts'); jest.mock('../../../../provider-utils/awscloudformation/service-walkthroughs/s3-user-input-state'); jest.mock('../../../../provider-utils/awscloudformation/cdk-stack-builder/s3-stack-transform'); jest.mock('../../../../provider-utils/awscloudformation/service-walkthroughs/s3-auth-api'); jest.mock('uuid'); jest.mock('path'); jest.mock('fs-extra'); describe('add s3 walkthrough tests', () => { let mockContext: $TSContext; beforeEach(() => { //Mock: UUID generation jest.spyOn(uuid, 'v4').mockReturnValue(S3MockDataBuilder.mockPolicyUUID); //Mock: Context/Amplify-Meta mockContext = { amplify: { getProjectDetails: () => { return { projectConfig: { projectName: 'mockProject', }, amplifyMeta: { auth: S3MockDataBuilder.mockAuthMeta, }, }; }, getUserPoolGroupList: () => { return []; }, // eslint-disable-next-line getResourceStatus: () => { return { allResources: S3MockDataBuilder.getMockGetAllResourcesNoExistingLambdas() }; }, //eslint-disable-line copyBatch: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), updateamplifyMetaAfterResourceAdd: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), pathManager: { getBackendDirPath: jest.fn().mockReturnValue('mockTargetDir'), }, }, } as unknown as $TSContext; }); afterEach(() => { jest.clearAllMocks(); }); it('addWalkthrough() simple-auth test', async () => { jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); jest.spyOn(s3AuthAPI, 'migrateAuthDependencyResource').mockReturnValue( new Promise((resolve, _reject) => { process.nextTick(() => resolve(true)); }), ); const mockDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.getCLIInputs(); //Simple Auth CLI walkthrough prompter.input = jest .fn() .mockReturnValueOnce(S3MockDataBuilder.mockResourceName) // Provide a friendly name .mockResolvedValueOnce(S3MockDataBuilder.mockBucketName) // Provide bucket name .mockResolvedValueOnce(false); // Do you want to add Lambda Trigger prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]); // What kind of permissions prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta); let options = {}; const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('addWalkthrough() simple-auth+guest test', async () => { jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); const mockDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.addGuestAccess(undefined).getCLIInputs(); //Simple Auth CLI walkthrough prompter.input = jest .fn() .mockReturnValueOnce(S3MockDataBuilder.mockResourceName) // Provide a friendly name .mockResolvedValueOnce(S3MockDataBuilder.mockBucketName) // Provide bucket name .mockResolvedValueOnce(false); // Do you want to add Lambda Trigger prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_AND_GUEST) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]) // What kind of permissions (Auth) .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]); // What kind of permissions (Guest) prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta); let options = {}; const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('addWalkthrough() simple-auth + trigger (new function) test', async () => { jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); const mockDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.addMockTriggerFunction(undefined).getCLIInputs(); //Simple Auth CLI walkthrough prompter.input = jest .fn() .mockReturnValueOnce(S3MockDataBuilder.mockResourceName) // Provide a friendly name .mockResolvedValueOnce(S3MockDataBuilder.mockBucketName) // Provide bucket name .mockResolvedValueOnce(false); prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]); // What kind of permissions (Auth) prompter.yesOrNo = jest .fn() .mockReturnValueOnce(true) //Do you want to add a Lambda Trigger ? .mockResolvedValueOnce(false); //Do you want to edit the lamdba function now? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta); let options = {}; const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('addWalkthrough() simple-auth + trigger (existing function) test', async () => { jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //Add Existing Lambda functions in resource status mockContext.amplify.getResourceStatus = () => { return { allResources: S3MockDataBuilder.getMockGetAllResources2ExistingLambdas() }; }; const mockDataBuilder = new S3MockDataBuilder(undefined); //Select the first existing function from the list presented above in allResources const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder .addMockTriggerFunction(S3MockDataBuilder.mockExistingFunctionName1) .getCLIInputs(); //Simple Auth CLI walkthrough prompter.input = jest .fn() .mockReturnValueOnce(S3MockDataBuilder.mockResourceName) // Provide a friendly name .mockResolvedValueOnce(S3MockDataBuilder.mockBucketName) // Provide bucket name .mockResolvedValueOnce(false); prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]) // What kind of permissions (Auth) .mockResolvedValueOnce(S3TriggerFunctionType.EXISTING_FUNCTION) .mockResolvedValueOnce(S3MockDataBuilder.mockExistingFunctionName1); //Selected the First Existing function from the list. prompter.yesOrNo = jest .fn() .mockReturnValueOnce(true) //Do you want to add a Lambda Trigger ? .mockResolvedValueOnce(false); //Do you want to edit the lamdba function now? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMeta); let options = {}; const returnedResourcename = await addWalkthrough(mockContext, S3MockDataBuilder.mockFilePath, mockContext, options); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); }); describe('update s3 permission walkthrough tests', () => { let mockContext: $TSContext; beforeEach(() => { //Mock: UUID generation jest.spyOn(uuid, 'v4').mockReturnValue(S3MockDataBuilder.mockPolicyUUID); //Mock: Context/Amplify-Meta mockContext = { amplify: { getUserPoolGroupList: () => [], getProjectDetails: () => { return { projectConfig: { projectName: 'mockProject', }, amplifyMeta: { auth: S3MockDataBuilder.mockAuthMeta, storage: { [S3MockDataBuilder.mockResourceName]: { service: 'S3', providerPlugin: 'awscloudformation', dependsOn: [], }, }, }, }; }, // eslint-disable-next-line getResourceStatus: () => { return { allResources: S3MockDataBuilder.getMockGetAllResourcesNoExistingLambdas() }; }, //eslint-disable-line copyBatch: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), updateamplifyMetaAfterResourceAdd: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), pathManager: { getBackendDirPath: jest.fn().mockReturnValue('mockTargetDir'), }, }, input: { options: {}, }, } as unknown as $TSContext; }); afterEach(() => { jest.clearAllMocks(); }); /** * Update Auth + Guest Tests */ it('updateWalkthrough() simple-auth + update auth-permission', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.removeAuthPermission(S3PermissionType.DELETE).getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]); /** Update Auth Permission in CLI */ prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() simple-auth + update auth+guest permission', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder .removeAuthPermission(S3PermissionType.DELETE) .addGuestAccess([S3PermissionType.READ]) .getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_AND_GUEST) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]) /** Update Auth Permission in CLI */ .mockResolvedValueOnce([S3PermissionType.READ]); /** Update Guest Permission in CLI */ prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() auth+guest + update remove guest permission ', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); //start with auth+guest permissions const currentCLIInputs = mockDataBuilder .removeMockTriggerFunction() .addGuestAccess(undefined) //default guest access permissions .getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.removeGuestAccess().getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce(mockDataBuilder.defaultAuthPerms); /** Update Auth Permission in CLI */ prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); /** * Update Group Permission Checks */ it('updateWalkthrough() simple-auth + update add group(individual) permission ', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); //start with simple auth permissions const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); //Update Group list function in context mockContext.amplify.getUserPoolGroupList = () => Object.keys(mockDataBuilder.mockGroupAccess); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.removeAuthAccess().addGroupAccess().getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(UserPermissionTypeOptions.INDIVIDUAL_GROUPS) // Restrict Access By .mockResolvedValueOnce(['mockAdminGroup', 'mockGuestGroup']) //Select Groups .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]) //what kind of access do you want for the admin group .mockResolvedValueOnce([S3PermissionType.READ]); //what kind of access fo you want for the guest group prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('addWalkthrough() simple-auth + update add (both) group and auth+guest permission ', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); //start with simple auth permissions const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); //Update Group list function in context mockContext.amplify.getUserPoolGroupList = () => Object.keys(mockDataBuilder.mockGroupAccess); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //** Add GuestAccess, GroupAccess const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.addGuestAccess(undefined).addGroupAccess().getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(UserPermissionTypeOptions.BOTH) // Restrict Access By .mockResolvedValueOnce(S3AccessType.AUTH_AND_GUEST) // Restrict Access By .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]) //select Auth permissions .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]) //select Guest permissions .mockResolvedValueOnce(['mockAdminGroup', 'mockGuestGroup']) //Select Groups .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]) //select admin group permissions .mockResolvedValueOnce([S3PermissionType.READ]); //select guest group permissions prompter.confirmContinue = jest.fn().mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); }); describe('update s3 lambda-trigger walkthrough tests', () => { let mockContext: $TSContext; beforeEach(() => { //Mock: UUID generation jest.spyOn(uuid, 'v4').mockReturnValue(S3MockDataBuilder.mockPolicyUUID); //Mock: Context/Amplify-Meta mockContext = { amplify: { getUserPoolGroupList: () => [], getProjectDetails: () => { return { projectConfig: { projectName: 'mockProject', }, amplifyMeta: { auth: S3MockDataBuilder.mockAuthMeta, storage: { [S3MockDataBuilder.mockResourceName]: { service: 'S3', providerPlugin: 'awscloudformation', dependsOn: [], }, }, }, }; }, // eslint-disable-next-line getResourceStatus: () => { return { allResources: S3MockDataBuilder.getMockGetAllResourcesNoExistingLambdas() }; }, //eslint-disable-line copyBatch: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), updateamplifyMetaAfterResourceAdd: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), pathManager: { getBackendDirPath: jest.fn().mockReturnValue('mockTargetDir'), }, }, input: { options: {}, }, } as unknown as $TSContext; }); afterEach(() => { jest.clearAllMocks(); }); /** * Update Auth + Guest Tests */ it('updateWalkthrough() simple auth + update add trigger ( new lambda)', async () => { const mockDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.addMockTriggerFunction(undefined).getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([ S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE, ]); /** Update Auth Permission in CLI */ prompter.confirmContinue = jest .fn() .mockReturnValueOnce(true) //Do you want to add a Lambda Trigger ? .mockResolvedValueOnce(false); //Do you want to edit the lamdba function now? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthroughLambda); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() simple auth + new lambda + update remove trigger ', async () => { //Given we have cliInputs with simple auth + Lambda trigger [ existingDataBuilder ] //When we use CLI to remove Lambda trigger. //Then we expect that the saveCliInputPayload is called with no Lambda trigger [ expectedCLIInputsJSON ] const existingDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = existingDataBuilder.addMockTriggerFunction(undefined).getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set simple auth and remove triggerFunction const mockExpectedDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockExpectedDataBuilder.removeMockTriggerFunction().getCLIInputs(); //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([ S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE, ]) /** Update Auth Permission in CLI */ .mockResolvedValueOnce(S3CLITriggerUpdateMenuOptions.REMOVE); /** Select one of Update/Remove Skip*/ stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthroughLambda); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() simple auth + new lambda + update change trigger (existing function)', async () => { //Given we have auth with multiple existing functions //and cliInputs with simple auth + Lambda trigger [ existingDataBuilder ] //When we use CLI to change Lambda trigger with one of the existing functtions. //Then we expect that the saveCliInputPayload is called with the newly selected Lambda trigger [ expectedCLIInputsJSON ] //Add Existing Lambda functions in resource status mockContext.amplify.getResourceStatus = () => { return { allResources: S3MockDataBuilder.getMockGetAllResources2ExistingLambdas() }; }; const existingDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = existingDataBuilder.addMockTriggerFunction(undefined).getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set simple-auth and set mockExistingFunctionName1 as the new trigger function const mockExpectedDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockExpectedDataBuilder .addMockTriggerFunction(S3MockDataBuilder.mockExistingFunctionName1) .getCLIInputs(); //Update CLI walkthrough (update trigger function with existing function) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([ S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE, ]) /** Update Auth Permission in CLI */ .mockResolvedValueOnce(S3CLITriggerUpdateMenuOptions.UPDATE) /** Select one of Update/Remove Skip*/ .mockResolvedValueOnce(S3TriggerFunctionType.EXISTING_FUNCTION) .mockResolvedValueOnce(S3MockDataBuilder.mockExistingFunctionName1); stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthroughLambda); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() simple auth + new lambda + update change trigger (existing function)', async () => { //Given we have auth with multiple existing functions //and cliInputs with simple auth + Lambda trigger (one of the existing trigger functions) [ existingDataBuilder ] //When we use CLI to change Lambda trigger with a new lambda function. //Then we expect that the saveCliInputPayload is called with the newly created lambda function trigger[ expectedCLIInputsJSON ] //Add Existing Lambda functions in resource status mockContext.amplify.getResourceStatus = () => { return { allResources: S3MockDataBuilder.getMockGetAllResources2ExistingLambdas() }; }; const existingDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = existingDataBuilder.addMockTriggerFunction(S3MockDataBuilder.mockExistingFunctionName1).getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set simple-auth and set mockExistingFunctionName1 as the new trigger function const mockExpectedDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockExpectedDataBuilder .addMockTriggerFunction(S3MockDataBuilder.mockFunctionName) .getCLIInputs(); //Update CLI walkthrough (update trigger function with existing function) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([ S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE, ]) /** Update Auth Permission in CLI */ .mockResolvedValueOnce(S3CLITriggerUpdateMenuOptions.UPDATE) /** Select one of Update/Remove Skip*/ .mockResolvedValueOnce(S3TriggerFunctionType.NEW_FUNCTION); //add new function prompter.confirmContinue = jest.fn().mockResolvedValueOnce(false); //Do you want to edit the lamdba function now? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthroughLambda); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); it('updateWalkthrough() simple auth + new lambda + update change trigger (new function)', async () => { //Given we have auth with multiple existing functions //and cliInputs with simple auth + Lambda trigger (new trigger function) [ existingDataBuilder ] //When we use CLI to change Lambda trigger with a new lambda function. //Then we expect that the saveCliInputPayload is called with the newly created lambda function trigger[ expectedCLIInputsJSON ] //Add Existing Lambda functions in resource status mockContext.amplify.getResourceStatus = () => { return { allResources: S3MockDataBuilder.getMockGetAllResources2ExistingLambdas() }; }; const existingDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = existingDataBuilder.addMockTriggerFunction(undefined).getCLIInputs(); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => true); //CLI Input exists jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set simple-auth and set mockExistingFunctionName1 as the new trigger function const mockExpectedDataBuilder = new S3MockDataBuilder(undefined); const expectedCLIInputsJSON: S3UserInputs = mockExpectedDataBuilder .addMockTriggerFunction(S3MockDataBuilder.mockFunctioName2) .getCLIInputs(); //Update CLI walkthrough (update trigger function with existing function) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([ S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE, ]) /** Update Auth Permission in CLI */ .mockResolvedValueOnce(S3CLITriggerUpdateMenuOptions.UPDATE) /** Select one of Update/Remove Skip*/ .mockResolvedValueOnce(S3TriggerFunctionType.NEW_FUNCTION); //add new function prompter.confirmContinue = jest.fn().mockResolvedValueOnce(false); //Do you want to edit the lamdba function now? stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthroughLambda); //The newly generated function-name should use UUID2 jest.spyOn(uuid, 'v4').mockReturnValueOnce(S3MockDataBuilder.mockPolicyUUID2); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); }); describe('migrate s3 and update s3 permission walkthrough tests', () => { let mockContext: $TSContext; beforeEach(() => { //Mock: UUID generation jest.spyOn(uuid, 'v4').mockReturnValue(S3MockDataBuilder.mockPolicyUUID); //Mock: Context/Amplify-Meta mockContext = { amplify: { getUserPoolGroupList: () => [], getProjectDetails: () => { return { projectConfig: { projectName: 'mockProject', }, amplifyMeta: { auth: S3MockDataBuilder.mockAuthMeta, storage: { [S3MockDataBuilder.mockResourceName]: { service: 'S3', providerPlugin: 'awscloudformation', dependsOn: [], }, }, }, }; }, // eslint-disable-next-line getResourceStatus: () => { return { allResources: S3MockDataBuilder.getMockGetAllResourcesNoExistingLambdas() }; }, //eslint-disable-line copyBatch: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), updateamplifyMetaAfterResourceAdd: jest.fn().mockReturnValue(new Promise((resolve, reject) => resolve(true))), pathManager: { getBackendDirPath: jest.fn().mockReturnValue('mockTargetDir'), }, }, input: { options: {}, }, } as unknown as $TSContext; }); afterEach(() => { jest.clearAllMocks(); }); /** * Update + Migrate + Auth + Guest Tests */ it('updateWalkthrough() simple-auth + migrate + update + auth-permission', async () => { const mockParamsJSON = getMigrationMockParametersJSON(); const mockStorageParams = {}; //used only for userpools const mockCFN = {}; //currently not used const oldParams: MigrationParams = { parametersFilepath: 'mockParamsfilePath', cfnFilepath: 'mockOldCFNFilepath', storageParamsFilepath: 'oldStorageParamsFilepath', parameters: mockParamsJSON, cfn: mockCFN, storageParams: mockStorageParams, }; const mockDataBuilder = new S3MockDataBuilder(undefined); const currentCLIInputs = mockDataBuilder.removeMockTriggerFunction().getCLIInputs(); jest.spyOn(S3InputState.prototype, 'migrate'); jest.spyOn(S3InputState.prototype, 'getOldS3ParamsForMigration').mockImplementation(() => oldParams); jest.spyOn(S3InputState.prototype, 'cliInputFileExists').mockImplementation(() => false); //CLI Input doesnt exist - requires migration jest.spyOn(S3InputState.prototype, 'getUserInput').mockImplementation(() => currentCLIInputs); //simple-auth jest.spyOn(S3InputState.prototype, 'saveCliInputPayload').mockImplementation(async () => { return; }); jest.spyOn(AmplifyS3ResourceStackTransform.prototype, 'transform').mockImplementation(() => Promise.resolve()); //**Set Auth permissions in Expected Output (without Delete permissions) const expectedCLIInputsJSON: S3UserInputs = mockDataBuilder.removeAuthPermission(S3PermissionType.DELETE).getCLIInputs(); prompter.yesOrNo = jest .fn() .mockReturnValueOnce(true) // Do you want to migrate...? .mockReturnValueOnce(false); // Do you want to add a Lambda Trigger ? //Update CLI walkthrough (update auth permission) prompter.pick = jest .fn() .mockResolvedValueOnce(S3AccessType.AUTH_ONLY) // who should have access .mockResolvedValueOnce([S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]); /** Update Auth Permission in CLI */ // stateManager.getMeta = jest.fn().mockReturnValue(S3MockDataBuilder.mockAmplifyMetaForUpdateWalkthrough); const returnedResourcename = await updateWalkthrough(mockContext); expect(returnedResourcename).toEqual(S3MockDataBuilder.mockResourceName); expect(S3InputState.prototype.saveCliInputPayload).toHaveBeenCalledWith(expectedCLIInputsJSON); }); }); function getMigrationMockParametersJSON(): $TSAny { const mockParametersJSON = { bucketName: 'migratefix2c53c1f2a55574207949d2bb7a88258a4', authPolicyName: 's3_amplify_81ce520f', unauthPolicyName: 's3_amplify_81ce520f', authRoleName: { Ref: 'AuthRoleName', }, unauthRoleName: { Ref: 'UnauthRoleName', }, selectedGuestPermissions: ['s3:GetObject', 's3:ListBucket'], selectedAuthenticatedPermissions: ['s3:PutObject', 's3:GetObject', 's3:ListBucket', 's3:DeleteObject'], s3PermissionsAuthenticatedPublic: 's3:PutObject,s3:GetObject,s3:DeleteObject', s3PublicPolicy: 'Public_policy_217e732f', s3PermissionsAuthenticatedUploads: 's3:PutObject', s3UploadsPolicy: 'Uploads_policy_217e732f', s3PermissionsAuthenticatedProtected: 's3:PutObject,s3:GetObject,s3:DeleteObject', s3ProtectedPolicy: 'Protected_policy_217e732f', s3PermissionsAuthenticatedPrivate: 's3:PutObject,s3:GetObject,s3:DeleteObject', s3PrivatePolicy: 'Private_policy_217e732f', AuthenticatedAllowList: 'ALLOW', s3ReadPolicy: 'read_policy_217e732f', s3PermissionsGuestPublic: 'DISALLOW', s3PermissionsGuestUploads: 'DISALLOW', GuestAllowList: 'DISALLOW', triggerFunction: 'NONE', }; return mockParametersJSON; } //Helper class to start with Simple Auth and mutate the CLI Inputs based on Test-Case class S3MockDataBuilder { static mockBucketName = 'mockBucketName'; static mockResourceName = 'mockResourceName'; static mockPolicyUUID = 'cafe2021'; static mockPolicyUUID2 = 'cafe2022'; static mockFunctionName = `S3Trigger${S3MockDataBuilder.mockPolicyUUID}`; static mockFunctioName2 = `S3Trigger${S3MockDataBuilder.mockPolicyUUID2}`; static mockExistingFunctionName1 = 'triggerHandlerFunction1'; static mockExistingFunctionName2 = 'triggerHandlerFunction2'; static mockFilePath = ''; static mockAuthMeta = { service: 'Cognito', providerPlugin: 'awscloudformation', dependsOn: [], customAuth: false, frontendAuthConfig: { loginMechanisms: ['PREFERRED_USERNAME'], signupAttributes: ['EMAIL'], passwordProtectionSettings: { passwordPolicyMinLength: 8, passwordPolicyCharacters: [], }, mfaConfiguration: 'OFF', mfaTypes: ['SMS'], verificationMechanisms: ['EMAIL'], }, }; static mockAmplifyMeta = { auth: { mockAuthName: S3MockDataBuilder.mockAuthMeta, }, }; static mockAmplifyMetaForUpdateWalkthrough = { auth: { mockAuthName: S3MockDataBuilder.mockAuthMeta, }, storage: { [S3MockDataBuilder.mockResourceName]: { service: 'S3', providerPlugin: 'awscloudformation', dependsOn: [], }, }, }; static mockAmplifyMetaForUpdateWalkthroughLambda = { auth: { mockAuthName: S3MockDataBuilder.mockAuthMeta, }, storage: { [S3MockDataBuilder.mockResourceName]: { service: 'S3', providerPlugin: 'awscloudformation', dependsOn: [ { category: 'function', resourceName: S3MockDataBuilder.mockFunctionName, attributes: ['Name', 'Arn', 'LambdaExecutionRole'], }, ], }, }, }; mockGroupAccess = { mockAdminGroup: [S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE], mockGuestGroup: [S3PermissionType.READ], }; defaultAuthPerms = [S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ, S3PermissionType.DELETE]; defaultGuestPerms = [S3PermissionType.CREATE_AND_UPDATE, S3PermissionType.READ]; simpleAuth: S3UserInputs = { resourceName: S3MockDataBuilder.mockResourceName, bucketName: S3MockDataBuilder.mockBucketName, policyUUID: S3MockDataBuilder.mockPolicyUUID, storageAccess: S3AccessType.AUTH_ONLY, guestAccess: [], authAccess: this.defaultAuthPerms, groupAccess: {}, triggerFunction: 'NONE', }; cliInputs: S3UserInputs = { resourceName: undefined, bucketName: undefined, policyUUID: undefined, storageAccess: undefined, guestAccess: [], authAccess: [], triggerFunction: undefined, groupAccess: undefined, }; constructor(startCliInputState: S3UserInputs | undefined) { if (startCliInputState) { this.cliInputs = startCliInputState; } else { Object.assign(this.cliInputs, this.simpleAuth); } } static getMockGetAllResources2ExistingLambdas() { return [ { service: 'Cognito', serviceType: 'managed' }, { service: AmplifySupportedService.LAMBDA, resourceName: S3MockDataBuilder.mockExistingFunctionName1, }, { service: AmplifySupportedService.LAMBDA, resourceName: S3MockDataBuilder.mockExistingFunctionName2, }, ]; } static getMockGetAllResourcesNoExistingLambdas() { return [{ service: 'Cognito', serviceType: 'managed' }]; } addGuestAccess(guestAccess: Array<S3PermissionType> | undefined): S3MockDataBuilder { this.cliInputs.storageAccess = S3AccessType.AUTH_AND_GUEST; if (guestAccess) { this.cliInputs.guestAccess = guestAccess; } else { this.cliInputs.guestAccess = this.defaultGuestPerms; } return this; } removeGuestAccess(): S3MockDataBuilder { this.cliInputs.storageAccess = S3AccessType.AUTH_ONLY; this.cliInputs.guestAccess = []; return this; } addMockTriggerFunction(customMockFunctionName: string | undefined): S3MockDataBuilder { if (customMockFunctionName) { this.cliInputs.triggerFunction = customMockFunctionName; } else { this.cliInputs.triggerFunction = S3MockDataBuilder.mockFunctionName; } return this; } removeMockTriggerFunction(): S3MockDataBuilder { this.cliInputs.triggerFunction = undefined; return this; } removeAuthAccess(): S3MockDataBuilder { this.cliInputs.authAccess = []; return this; } removeAuthPermission(permissionToBeRemoved: S3PermissionType): S3MockDataBuilder { const newPermissions = this.defaultAuthPerms.filter(permission => permission !== permissionToBeRemoved); this.cliInputs.authAccess = newPermissions; return this; } addGroupAccess(): S3MockDataBuilder { this.cliInputs.groupAccess = this.mockGroupAccess; return this; } removeGroupAccess(): S3MockDataBuilder { this.cliInputs.groupAccess = undefined; return this; } getCLIInputs(): S3UserInputs { return this.cliInputs; } }
the_stack
import defaultDispenserABI from '@oceanprotocol/contracts/artifacts/Dispenser.json' import { TransactionReceipt } from 'web3-core' import { Contract } from 'web3-eth-contract' import { AbiItem } from 'web3-utils/types' import Web3 from 'web3' import { SubscribablePromise, Logger, getFairGasPrice } from '../utils' import { DataTokens } from '../datatokens/Datatokens' import Decimal from 'decimal.js' export interface DispenserToken { active: boolean owner: string minterApproved: boolean isTrueMinter: boolean maxTokens: string maxBalance: string balance: string } export enum DispenserMakeMinterProgressStep { // eslint-disable-next-line no-unused-vars MakeDispenserMinter, // eslint-disable-next-line no-unused-vars AcceptingNewMinter } export enum DispenserCancelMinterProgressStep { // eslint-disable-next-line no-unused-vars MakeOwnerMinter, // eslint-disable-next-line no-unused-vars AcceptingNewMinter } export class OceanDispenser { public GASLIMIT_DEFAULT = 1000000 /** Ocean related functions */ public dispenserAddress: string public dispenserABI: AbiItem | AbiItem[] public web3: Web3 public contract: Contract = null private logger: Logger public datatokens: DataTokens public startBlock: number /** * Instantiate Dispenser * @param {any} web3 * @param {String} dispenserAddress * @param {any} dispenserABI */ constructor( web3: Web3, logger: Logger, dispenserAddress: string = null, dispenserABI: AbiItem | AbiItem[] = null, datatokens: DataTokens, startBlock?: number ) { this.web3 = web3 this.dispenserAddress = dispenserAddress if (startBlock) this.startBlock = startBlock else this.startBlock = 0 this.dispenserABI = dispenserABI || (defaultDispenserABI.abi as AbiItem[]) this.datatokens = datatokens if (web3) this.contract = new this.web3.eth.Contract(this.dispenserABI, this.dispenserAddress) this.logger = logger } /** * Get dispenser status for a datatoken * @param {String} dataTokenAddress * @return {Promise<FixedPricedExchange>} Exchange details */ public async status(dataTokenAddress: string): Promise<DispenserToken> { try { const result: DispenserToken = await this.contract.methods .status(dataTokenAddress) .call() result.maxTokens = this.web3.utils.fromWei(result.maxTokens) result.maxBalance = this.web3.utils.fromWei(result.maxBalance) result.balance = this.web3.utils.fromWei(result.balance) return result } catch (e) { this.logger.warn(`No dispenser available for data token: ${dataTokenAddress}`) } return null } /** * Activates a new dispener. * @param {String} dataToken * @param {Number} maxTokens max amount of tokens to dispense * @param {Number} maxBalance max balance of user. If user balance is >, then dispense will be rejected * @param {String} address User address (must be owner of the dataToken) * @return {Promise<TransactionReceipt>} TransactionReceipt */ public async activate( dataToken: string, maxTokens: string, maxBalance: string, address: string ): Promise<TransactionReceipt> { let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT try { estGas = await this.contract.methods .activate( dataToken, this.web3.utils.toWei(maxTokens), this.web3.utils.toWei(maxBalance) ) .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods .activate( dataToken, this.web3.utils.toWei(maxTokens), this.web3.utils.toWei(maxBalance) ) .send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to activate dispenser: ${e.message}`) } return trxReceipt } /** * Deactivates a dispener. * @param {String} dataToken * @param {String} address User address (must be owner of the dispenser) * @return {Promise<TransactionReceipt>} TransactionReceipt */ public async deactivate( dataToken: string, address: string ): Promise<TransactionReceipt> { let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT try { estGas = await this.contract.methods .deactivate(dataToken) .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods.deactivate(dataToken).send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to deactivate dispenser: ${e.message}`) } return trxReceipt } /** * Make the dispenser minter of the datatoken * @param {String} dataToken * @param {String} address User address (must be owner of the datatoken) * @return {Promise<TransactionReceipt>} TransactionReceipt */ public makeMinter( dataToken: string, address: string ): SubscribablePromise<DispenserMakeMinterProgressStep, TransactionReceipt> { return new SubscribablePromise(async (observer) => { observer.next(DispenserMakeMinterProgressStep.MakeDispenserMinter) let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT const minterTx = await this.datatokens.proposeMinter( dataToken, this.dispenserAddress, address ) if (!minterTx) { return null } observer.next(DispenserMakeMinterProgressStep.AcceptingNewMinter) try { estGas = await this.contract.methods .acceptMinter(dataToken) .estimateGas({ from: address }, (err, estGas) => err ? gasLimitDefault : estGas ) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods.acceptMinter(dataToken).send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to accept minter role: ${e.message}`) } return trxReceipt }) } /** * Cancel minter role of dispenser and make the owner minter of the datatoken * @param {String} dataToken * @param {String} address User address (must be owner of the dispenser) * @return {Promise<TransactionReceipt>} TransactionReceipt */ public cancelMinter( dataToken: string, address: string ): SubscribablePromise<DispenserCancelMinterProgressStep, TransactionReceipt> { return new SubscribablePromise(async (observer) => { observer.next(DispenserCancelMinterProgressStep.MakeOwnerMinter) let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT try { estGas = await this.contract.methods .removeMinter(dataToken) .estimateGas({ from: address }, (err, estGas) => err ? gasLimitDefault : estGas ) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods.removeMinter(dataToken).send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to remove minter role: ${e.message}`) } if (!trxReceipt) { return null } observer.next(DispenserCancelMinterProgressStep.AcceptingNewMinter) const minterTx = await this.datatokens.approveMinter(dataToken, address) return minterTx }) } /** * Request tokens from dispenser * @param {String} dataToken * @param {String} amount * @param {String} address User address * @return {Promise<TransactionReceipt>} TransactionReceipt */ public async dispense( dataToken: string, address: string, amount: string = '1' ): Promise<TransactionReceipt> { let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT try { estGas = await this.contract.methods .dispense(dataToken, this.web3.utils.toWei(amount)) .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods .dispense(dataToken, this.web3.utils.toWei(amount)) .send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to dispense tokens: ${e.message}`) } return trxReceipt } /** * Withdraw all tokens from the dispenser (if any) * @param {String} dataToken * @param {String} address User address (must be owner of the dispenser) * @return {Promise<TransactionReceipt>} TransactionReceipt */ public async ownerWithdraw( dataToken: string, address: string ): Promise<TransactionReceipt> { let estGas const gasLimitDefault = this.GASLIMIT_DEFAULT try { estGas = await this.contract.methods .ownerWithdraw(dataToken) .estimateGas({ from: address }, (err, estGas) => (err ? gasLimitDefault : estGas)) } catch (e) { estGas = gasLimitDefault } let trxReceipt = null try { trxReceipt = await this.contract.methods.ownerWithdraw(dataToken).send({ from: address, gas: estGas + 1, gasPrice: await getFairGasPrice(this.web3) }) } catch (e) { this.logger.error(`ERROR: Failed to withdraw tokens: ${e.message}`) } return trxReceipt } /** * Check if tokens can be dispensed * @param {String} dataToken * @param {String} address User address that will receive datatokens * @return {Promise<Boolean>} */ public async isDispensable( dataToken: string, address: string, amount: string = '1' ): Promise<Boolean> { const status = await this.status(dataToken) if (!status) return false // check active if (status.active === false) return false // check maxBalance const userBalance = new Decimal(await this.datatokens.balance(dataToken, address)) if (userBalance.greaterThanOrEqualTo(status.maxBalance)) return false // check maxAmount if (new Decimal(String(amount)).greaterThan(status.maxTokens)) return false // check dispenser balance const contractBalance = new Decimal(status.balance) if (contractBalance.greaterThanOrEqualTo(amount) || status.isTrueMinter === true) return true return false } }
the_stack
module Kiwi { /** * A State in Kiwi.JS is the main class that developers use when wanting to create a Game. * States in Kiwi are used keep different sections of a game seperated. So a single game maybe comprised of many different States. * Such as one for the menu, in-game, leaderboard, e.t.c. * There can only ever be a single State active at a given time. * * @class State * @namespace Kiwi * @extends Kiwi.Group * @constructor * @param name {String} Name of this State. Should be unique to differentiate itself from other States. * @return {Kiwi.State} */ export class State extends Group { constructor(name: string) { super(null, name); this.config = new Kiwi.StateConfig(this, name); this.components = new Kiwi.ComponentManager(Kiwi.STATE, this); this.transform.parent = null; this._trackingList = []; } /** * Returns the type of object this state is. * @method objType * @return {String} "State" * @public */ public objType() { return "State"; } /** * Returns the type of child this is. * @method childType * @return {Number} Kiwi.GROUP * @public */ public childType() { return Kiwi.GROUP; } /** * The configuration object for this State. * @property config * @type Kiwi.StateConfig * @public */ public config: Kiwi.StateConfig; /** * A reference to the Kiwi.Game that this State belongs to. * @property game * @type Kiwi.Game * @public */ public game: Kiwi.Game = null; /** * The library that this state use's for the loading of textures. * @property textureLibrary * @type Kiwi.Textures.TextureLibrary * @public */ public textureLibrary: Kiwi.Textures.TextureLibrary; /** * The library that this state use's for the loading of audio. * @property audioLibrary * @type Kiwi.Sound.AudioLibrary * @public */ public audioLibrary: Kiwi.Sound.AudioLibrary; /** * The library that this state use's for the loading of data. * @property dataLibrary * @type Kiwi.Files.DataLibrary * @public */ public dataLibrary: Kiwi.Files.DataLibrary; /** * Holds all of the textures that are avaiable to be accessed once this state has been loaded. * E.g. If you loaded a image and named it 'flower', once everything has loaded you can then access the flower image by saying this.textures.flower * @property textures * @type Object * @public */ public textures; /** * Holds all of the audio that are avaiable to be accessed once this state has been loaded. * E.g. If you loaded a piece of audio and named it 'lazerz', once everything has loaded you can then access the lazers (pew pew) by saying this.audio.lazerz * @property audio * @type Object * @public */ public audio; /** * Holds all of the data that are avaiable to be accessed once this state has been loaded. * E.g. If you loaded a piece of data and named it 'cookieLocation', once everything has loaded you can then access the cookies by saying this.data.cookieLocation * @property data * @type Object * @public */ public data; /** * This method is executed when this State is about to be switched too. This is the first method to be executed, and happens before the Init method. * Is called each time a State is switched to. * @method boot * @public */ public boot() { this.textureLibrary = new Kiwi.Textures.TextureLibrary(this.game); this.textures = this.textureLibrary.textures; this.audioLibrary = new Kiwi.Sound.AudioLibrary(this.game); this.audio = this.audioLibrary.audio; this.dataLibrary = new Kiwi.Files.DataLibrary(this.game); this.data = this.dataLibrary.data; } /* * Currently unused. */ public setType(value: number) { if (this.config.isInitialised === false) { this.config.type = value; } } /* *-------------- * Methods that are to be Over-Ridden by Devs. *-------------- */ /** * Gets executed when the state has been initalised and gets switched to for the first time. * This method only ever gets called once and it is before the preload method. * Can have parameters passed to it by the previous state that switched to it. * @method init * @param [values] { Any } * @public */ public init(...paramsArr: any[]) { } /** * This method is where you would load of all the assets that are requried for this state or in the entire game. * * @method preload * @public */ public preload() { } /** * This method is progressively called whilst loading files and is executed each time a file has been loaded. * This can be used to create a 'progress' bar during the loading stage of a game. * @method loadProgress * @param percent {Number} The percent of files that have been loaded so far. This is a number from 0 - 1. * @param bytesLoaded {Number} The number of bytes that have been loaded so far. * @param file {Kiwi.Files.File} The last file to have been loaded. * @public */ public loadProgress(percent: number, bytesLoaded: number, file: Kiwi.Files.File) { } /** * Gets executed when the game is finished loading and it is about to 'create' the state. * @method loadComplete * @public */ public loadComplete() { } /** * The game loop that gets executed while the game is loading. * @method loadUpdate * @public */ public loadUpdate() { for (var i = 0; i < this.members.length; i++) { if (this.members[i].active === true) { this.members[i].update(); } } } /** * Is executed once all of the assets have loaded and the game is ready to be 'created'. * @method create * @param [values]* {Any} * @public */ public create(...paramsArr: any[]) { } /** * Is called every frame before the update loop. When overriding make sure you include a super call. * @method preUpdate * @public */ public preUpdate() { this.components.preUpdate(); } /** * The update loop that is executed every frame while the game is 'playing'. When overriding make sure you include a super call too. * @method update * @public */ public update() { this.components.update(); for (var i = 0; i < this.members.length; i++) { //Should the update loop be executed? if (this.members[i].active === true) { this.members[i].update(); } //Does the child need to be destroyed? if (this.members[i].exists === false) { this.members[i].destroy( true ); } } } /** * The post update loop is executed every frame after the update method. * When overriding make sure you include a super call at the end of the method. * @method postUpdate * @public */ public postUpdate() { this.components.postUpdate(); } /** * Called after all of the layers have rendered themselves, useful for debugging. * @method postRender * @public */ public postRender() { } /** * Called just before this State is going to be Shut Down and another one is going to be switched too. * @method shutDown * @public */ public shutDown() { } /* *-------------- * Loading Methods *-------------- */ /** * Adds a new image file that is be loaded when the state gets up to the loading all of the assets. * * @method addImage * @param key {String} A key for this image so that you can access it when the loading has finished. * @param url {String} The location of the image. * @param [storeAsGlobal=true] {boolean} If the image should be deleted when switching to another state or if the other states should still be able to access this image. * @param [width] {Number} The width of the image. If not passed the width will be automatically calculated. * @param [height] {Number} The height of the image. If not passed the height will be automatically calculated. * @param [offsetX] {Number} The offset of the image when rendering on the x axis. * @param [offsetY] {Number} The offset of the image when rendering on the y axis. * @public */ public addImage(key: string, url: string, storeAsGlobal: boolean = true, width?: number, height?: number, offsetX?: number, offsetY?: number) { return this.game.loader.addImage(key, url, width, height, offsetX, offsetY, storeAsGlobal); } /** * Adds a new spritesheet image file that is be loaded when the state gets up to the loading all of the assets. * * @method addSpriteSheet * @param key {String} A key for this image so that you can access it when the loading has finished. * @param url {String} The location of the image. * @param frameWidth {Number} The width of a single frame in the spritesheet * @param frameHeight {Number} The height of a single frame in the spritesheet * @param [storeAsGlobal=true] {boolean} If the image should be deleted when switching to another state or if the other states should still be able to access this image. * @param [numCells] {Number} The number of cells/frames that are in the spritesheet. If not specified will calculate this based of the width/height of the image. * @param [rows] {Number} The number of cells that are in a row. If not specified will calculate this based of the width/height of the image. * @param [cols] {Number} The number of cells that are in a column. If not specified will calculate this based of the width/height of the image. * @param [sheetOffsetX=0] {Number} The offset of the whole spritesheet on the x axis. * @param [sheetOffsetY=0] {Number} The offset of the whole spritesheet on the y axis. * @param [cellOffsetX=0] {Number} The spacing between cells on the x axis. * @param [cellOffsetY=0] {Number} The spacing between cells on the y axis. * @public */ public addSpriteSheet(key: string, url: string, frameWidth: number, frameHeight: number, storeAsGlobal: boolean = true, numCells?: number, rows?: number, cols?: number, sheetOffsetX?: number, sheetOffsetY?: number, cellOffsetX?: number, cellOffsetY?: number) { return this.game.loader.addSpriteSheet(key, url, frameWidth, frameHeight, numCells, rows, cols, sheetOffsetX, sheetOffsetY, cellOffsetX, cellOffsetY, storeAsGlobal); } /** * Adds a new texture atlas that is to be loaded when the states gets up to the stage of loading the assets. * * @method addTextureAtlas * @param key {String} A key for this image so that you can access it when the loading has finished. * @param imageURL {String} The location of the image. * @param [jsonID] {String} The id for the json file that is to be loaded. So that you can access it outside of the texture atlas. * @param [jsonURL] {String} The location of the json file you have loaded. * @param [storeAsGlobal=true] {boolean} If the image should be delete when switching to another state or if the other states should still be able to access this image. * @public */ public addTextureAtlas(key: string, imageURL: string, jsonID?: string, jsonURL?: string, storeAsGlobal: boolean = true) { return this.game.loader.addTextureAtlas(key, imageURL, jsonID, jsonURL, storeAsGlobal); } /** * Adds a json file that is to be loaded when the state gets up to the stage of loading the assets. * * @method addJSON * @param key {string} A key for this json so that you can access it when the loading has finished * @param url {string} The location of the JSON file. * @param [storeAsGlobal=true] {boolean} If the json should be deleted when switching to another state or if the other states should still be able to access this json. * @public */ public addJSON(key: string, url: string, storeAsGlobal: boolean = true) { return this.game.loader.addJSON(key, url, storeAsGlobal); } /** * Adds a new audio file that is to be loaded when the state gets up to the stage of loading the assets. * * @method addAudio * @param key {string} A key for this audio so that you can access it when the loading has finished * @param url {string} The location of the audio file. You can pass a array of urls, in which case the first supported filetype will be used. * @param [storeAsGlobal=true] {boolean} If the audio should be deleted when switching to another state or if the other states should still be able to access this audio. */ public addAudio(key: string, url: any, storeAsGlobal: boolean = true) { return this.game.loader.addAudio(key, url, storeAsGlobal); } /* *---------------- * Garbage Collection *---------------- */ /** * Contains a reference to all of the Objects that have ever been created for this state. Generally Kiwi.Entities or Kiwi.Groups. * Useful for keeping track of sprites that are not used any more and need to be destroyed. * @property trackingList * @type Array * @private */ private _trackingList: Kiwi.IChild[]; /** * Adds a new Objects to the tracking list. * This is an INTERNAL Kiwi method and DEVS shouldn't need to worry about it. * @method addToTrackingList * @param child {Object} The Object which you are adding to the tracking list. * @public */ public addToTrackingList(child: Kiwi.IChild) { //check to see that its not already in the tracking list. if (this._trackingList.indexOf(child) !== -1) return; //add to the list this._trackingList.push(child); } /** * Removes a Object from the tracking list. This should only need to happen when a child is being destroyed. * This is an INTERNAL Kiwi method and DEVS shouldn't really need to worry about it. * @method removeFromTrackingList * @param child {Object} The object which is being removed from the tracking list. * @public */ public removeFromTrackingList(child:Kiwi.IChild) { //check to see that it is in the tracking list. var n = this._trackingList.indexOf(child); if (n > -1) { this._trackingList.splice(n, 1); } } /** * Destroys all of Objects in the tracking list that are not currently on stage. * All that currently don't have this STATE as an ancestor. * Returns the number of Objects removed. * @method destroyUnused * @return {Number} The amount of objects removed. * @public */ public destroyUnused():number { var d = 0; for (var i = 0; i < this._trackingList.length; i++) { if (this.containsAncestor(this._trackingList[i], this) === false) { this._trackingList[i].destroy(); this._trackingList.splice(i, 1); i--; d++; } } return d; } /** * Used to mark all Entities that have been created for deletion, regardless of it they are on the stage or not. * @method destroy * @param [deleteAll=true] If all of the Objects ever created should have the destroy method executed also. * @public */ public destroy(deleteAll: boolean=true) { if (deleteAll == true) { //destroy all of the tracking list while( this._trackingList.length > 0 ) { //If the item is a group then we don't want it to destroy it's children, as this method will do that eventually anyway. this._trackingList[0].destroy( true , false ); } this._trackingList = []; //destroy all of the groups members. Usually they would be apart of the trackingList while (this.members.length > 0) { //If the item is a group then we don't want it to destroy it's children, as this method will do that eventually anyway. this.members[0].destroy(true, false); } this.members = []; } } /** * Recursively goes through a child given and runs the destroy method on all that are passed. * @method _destroyChildren * @param child {Object} * @private */ private _destroyChildren(child: any) { if (child.childType() == Kiwi.GROUP) { for (var i = 0; i < child.members.length; i++) { this._destroyChildren(child.members[i]); } } child.destroy( true ); } } }
the_stack
import { version as v } from "../package.json"; const version: string = v; import isObj from "lodash.isplainobject"; import { arrayiffy } from "arrayiffy-if-string"; import { matchLeftIncl, matchRightIncl } from "string-match-left-right"; import { Ranges } from "ranges-push"; import { rApply } from "ranges-apply"; import { trimSpaces } from "string-trim-spaces-only"; interface Opts { heads: string[]; tails: string[]; } // allows strings as well (which will end up arrayiffied) interface LenientOpts { heads: string | string[]; tails: string | string[]; } const defaults: Opts = { heads: ["{{"], tails: ["}}"], }; function remDup(str: string, originalOpts?: LenientOpts): string { // const has = Object.prototype.hasOwnProperty; // ===================== insurance ===================== if (str === undefined) { throw new Error( "string-remove-duplicate-heads-tails: [THROW_ID_01] The input is missing!" ); } if (typeof str !== "string") { return str; } if (originalOpts && !isObj(originalOpts)) { throw new Error( `string-remove-duplicate-heads-tails: [THROW_ID_03] The given options are not a plain object but ${typeof originalOpts}!` ); } // at this point, we can clone the originalOpts const clonedOriginalOpts: Opts = { ...originalOpts } as Opts; if (clonedOriginalOpts && has.call(clonedOriginalOpts, "heads")) { if ( !arrayiffy(clonedOriginalOpts.heads as any).every( (val: any) => typeof val === "string" || Array.isArray(val) ) ) { throw new Error( "string-remove-duplicate-heads-tails: [THROW_ID_04] The opts.heads contains elements which are not string-type!" ); } else if (typeof clonedOriginalOpts.heads === "string") { clonedOriginalOpts.heads = arrayiffy(clonedOriginalOpts.heads as string); } } if (clonedOriginalOpts && has.call(clonedOriginalOpts, "tails")) { if ( !arrayiffy(clonedOriginalOpts.tails as any).every( (val: any) => typeof val === "string" || Array.isArray(val) ) ) { throw new Error( "string-remove-duplicate-heads-tails: [THROW_ID_05] The opts.tails contains elements which are not string-type!" ); } else if (typeof clonedOriginalOpts.tails === "string") { clonedOriginalOpts.tails = arrayiffy(clonedOriginalOpts.tails); } } // trim but only if it's not trimmable to zero length (in that case return intact) const temp = trimSpaces(str).res; if (temp.length === 0) { return str; } str = temp; const defaults: Opts = { heads: ["{{"], tails: ["}}"], }; const opts: Opts = { ...defaults, ...clonedOriginalOpts }; // first, let's trim heads and tails' array elements: opts.heads = opts.heads.map((el) => el.trim()); opts.tails = opts.tails.map((el) => el.trim()); // P R E P A R A T I O N S // this flag is on after the first non-heads/tails chunk let firstNonMarkerChunkFound = false; // When second non-heads/tails chunk is met, this flag is turned on. // It wipes all conditional ranges and after that, only second heads/tails-onwards // that leads to string-end or whitespace and string-end will be moved to real slices // ranges array. let secondNonMarkerChunkFound = false; // Real ranges array is the array that we'll process in the end, cropping pieces // out of the string: const realRanges = new Ranges({ limitToBeAddedWhitespace: true }); // Conditional ranges array depends of the conditions what follows them. If the // condition is satisfied, range is merged into realRanges[]; if not, it's deleted. // For example, for leading head chunks, condition would be other heads/tails following // precisely after (not counting whitespace). For another example, for trailing // chunks, condition would be end of the string or other heads/tails that leads to // the end of the string: const conditionalRanges = new Ranges({ limitToBeAddedWhitespace: true, }); // this flag is requirement for cases where there are at least two chunks // wrapped with heads/tails, and we can't "peel off" the first tail that follows // the last chunk - each chunk has its wrapping: // {{ {{ chunk1}} {{chunk2}} }} // ^^ That's these tails we're talking about. // We don't want these deleted! let itsFirstTail = true; // This is a flag to mark the first letter in a non-head/tail/whitespace chunk. // Otherwise, second letter would trigger "secondNonMarkerChunkFound = true" and // we don't want that. let itsFirstLetter = true; // = heads or tails: let lastMatched = ""; // P A R T I // delete leading empty head-tail clumps as in "((()))((())) a" function delLeadingEmptyHeadTailChunks(str1: string, opts1: Opts) { let noteDownTheIndex: number | undefined; // do heads, from beginning of the input string: console.log("140 calling matchRightIncl()"); const resultOfAttemptToMatchHeads = matchRightIncl(str1, 0, opts1.heads, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { noteDownTheIndex = index; return true; }, }); if (!resultOfAttemptToMatchHeads) { // if heads were not matched, bail - there's no point matching trailing tails return str1; } // do tails now: console.log("153 calling matchRightIncl()"); const resultOfAttemptToMatchTails = matchRightIncl( str1, noteDownTheIndex as number, opts1.tails, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { // reassign noteDownTheIndex to new value, this time shifted right by // the width of matched tails noteDownTheIndex = index; return true; }, } ); if (resultOfAttemptToMatchTails) { return str1.slice(noteDownTheIndex); } return str1; } // action while (str !== delLeadingEmptyHeadTailChunks(str, opts)) { str = trimSpaces(delLeadingEmptyHeadTailChunks(str, opts)).res; } // delete trailing empty head-tail clumps as in "a ((()))((()))" function delTrailingEmptyHeadTailChunks(str1: string, opts1: Opts) { let noteDownTheIndex; // do tails now - match from the end of a string, trimming along: console.log("182 calling matchLeftIncl()"); const resultOfAttemptToMatchTails = matchLeftIncl( str1, str1.length - 1, opts1.tails, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { noteDownTheIndex = index; return true; }, } ); if (!resultOfAttemptToMatchTails || !noteDownTheIndex) { // if tails were not matched, bail - there's no point checking preceding heads return str1; } // do heads that precede those tails: console.log("200 calling matchLeftIncl()"); const resultOfAttemptToMatchHeads = matchLeftIncl( str1, noteDownTheIndex, opts1.heads, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { // reassign noteDownTheIndex to new value, this time shifted left by // the width of matched heads noteDownTheIndex = index; return true; }, } ); if (resultOfAttemptToMatchHeads) { return str1.slice(0, (noteDownTheIndex as number) + 1); } return str1; } // action while (str !== delTrailingEmptyHeadTailChunks(str, opts)) { str = trimSpaces(delTrailingEmptyHeadTailChunks(str, opts)).res; } // E A R L Y E N D I N G console.log("227 calling both matchRightIncl() and matchLeftIncl()"); if ( !opts.heads.length || !matchRightIncl(str, 0, opts.heads, { trimBeforeMatching: true, }) || !opts.tails.length || !matchLeftIncl(str, str.length - 1, opts.tails, { trimBeforeMatching: true, }) ) { console.log( `\u001b[${33}m${"211 STRING IS NOT WRAPPED WITH HEADS AND TAILS! Bye."}\u001b[${39}m` ); return trimSpaces(str).res; } // P A R T II // iterate the input string for (let i = 0, len = str.length; i < len; i++) { // // console log bits for development console.log( `\u001b[${33}m${`--------------------------------------- ${ str[i].trim() === "" ? "space" : ` ${str[i]} ` } ---[${i < 10 ? `0${i}` : i}]---`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* conditional ranges: ${JSON.stringify( conditionalRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* real ranges: ${JSON.stringify( realRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* firstNonMarkerChunkFound = ${JSON.stringify( firstNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* secondNonMarkerChunkFound = ${JSON.stringify( secondNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* itsFirstTail = ${JSON.stringify( itsFirstTail, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* lastMatched = ${JSON.stringify( lastMatched, null, 4 )}\n`}\u001b[${39}m` ); // catch whitespace if (str[i].trim() === "") { console.log("! skip"); } else { // so it's not a whitespace character. // "beginning" is a special state which lasts until first non-head/tail // character is met. // For example: {{{ }}} {{{ {{{ something }}} }}} // ------------> <---------------- // ^^^ indexes where "beginning" is "true" // match heads let noteDownTheIndex; console.log("312 calling matchRightIncl()"); const resultOfAttemptToMatchHeads = matchRightIncl(str, i, opts.heads, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { noteDownTheIndex = index; return true; }, }); if (resultOfAttemptToMatchHeads && noteDownTheIndex) { // reset marker itsFirstLetter = true; // reset firstTails if (itsFirstTail) { itsFirstTail = true; } console.log(`328 HEADS MATCHED: ${resultOfAttemptToMatchHeads}`); // 0. Just in case, check maybe there are tails following right away, // in that case definitely remove both let tempIndexUpTo; console.log("333 calling matchRightIncl()"); const resultOfAttemptToMatchTails = matchRightIncl( str, noteDownTheIndex, opts.tails, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { tempIndexUpTo = index; return true; }, } ); if (resultOfAttemptToMatchTails) { realRanges.push(i, tempIndexUpTo); } // 1. At this moment, in case {{ hi {{ name }}! }} // when we reach the second "{{", first "{{" are still in conditional // holding array. We'll evaluate the situation by "lastMatched" variable. if ( conditionalRanges.current() && firstNonMarkerChunkFound && lastMatched !== "tails" ) { console.log(`\u001b[${33}m${"329 wiping conditional"}\u001b[${39}m`); realRanges.push(conditionalRanges.current() as any); } // 2. let's evaluate the situation and possibly submit this range of indexes // to conditional ranges array. // if it's the beginning of a file, where no non-head/tail character was // met yet, add it to conditionals array: if (!firstNonMarkerChunkFound) { // deal with any existing content in the conditionals: if (conditionalRanges.current()) { // first, if there are any conditional ranges, they become real-ones: console.log( `\u001b[${33}m${"343 pushing conditionals into real"}\u001b[${39}m` ); realRanges.push(conditionalRanges.current() as any); // then, wipe conditionals: console.log( `\u001b[${33}m${"348 wiping conditionals"}\u001b[${39}m` ); conditionalRanges.wipe(); } console.log( `\u001b[${33}m${`369 adding new conditional range: [${i},${noteDownTheIndex}]`}\u001b[${39}m` ); // then, add this new range: conditionalRanges.push(i, noteDownTheIndex); } else { // Every heads or tails go to conditional array. First encountered // non-head/tail wipes all. console.log( `\u001b[${33}m${`377 adding new range: [${i},${noteDownTheIndex}]`}\u001b[${39}m` ); conditionalRanges.push(i, noteDownTheIndex); } // 3. set the new lastMatched lastMatched = "heads"; // 4. offset the index console.log( `\u001b[${33}m${`387 offsetting i to ${ (noteDownTheIndex as number) - 1 }`}\u001b[${39}m` ); i = (noteDownTheIndex as number) - 1; console.log( `\u001b[${36}m${`\n* * *\nENDED WITH\n* conditional ranges:\n${JSON.stringify( conditionalRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* real ranges: ${JSON.stringify( realRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* firstNonMarkerChunkFound = ${JSON.stringify( firstNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* secondNonMarkerChunkFound = ${JSON.stringify( secondNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* lastMatched = ${JSON.stringify( lastMatched, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* itsFirstTail = ${JSON.stringify( itsFirstTail, null, 4 )}`}\u001b[${39}m` ); continue; } // match tails console.log("454 calling matchRightIncl()"); const resultOfAttemptToMatchTails = matchRightIncl(str, i, opts.tails, { trimBeforeMatching: true, cb: (_char, _theRemainderOfTheString, index) => { noteDownTheIndex = Number.isInteger(index) ? index : str.length; return true; }, }); if (resultOfAttemptToMatchTails && noteDownTheIndex) { // reset marker itsFirstLetter = true; console.log(`TAILS MATCHED: ${resultOfAttemptToMatchTails}`); if (!itsFirstTail) { // if that's a second chunk, this means each chunk will be wrapped // and we can't peel of those wrappings, hence only the second tail // can be added to conditionals' array. console.log( `\u001b[${33}m${`458 pushing into conditionals: [${i}, ${noteDownTheIndex}]`}\u001b[${39}m` ); conditionalRanges.push(i, noteDownTheIndex); } else { // 1. console.log( `${`\u001b[${33}m${"447 lastMatched"}\u001b[${39}m`} = ${JSON.stringify( lastMatched, null, 4 )}` ); if (lastMatched === "heads") { console.log( `\u001b[${33}m${"455 WIPING CONDITIONALS"}\u001b[${39}m` ); conditionalRanges.wipe(); } // 2. if it's just the first tail, do nothing, but turn off the flag console.log( `\u001b[${33}m${"462 itsFirstTail = false"}\u001b[${39}m` ); itsFirstTail = false; } // set lastMatched lastMatched = "tails"; // 2. offset the index console.log( `\u001b[${33}m${`489 offsetting i to ${ noteDownTheIndex - 1 }`}\u001b[${39}m` ); i = noteDownTheIndex - 1; console.log( `\u001b[${36}m${`\n* * *\nENDED WITH\n* conditional ranges:\n${JSON.stringify( conditionalRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* real ranges: ${JSON.stringify( realRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* firstNonMarkerChunkFound = ${JSON.stringify( firstNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* secondNonMarkerChunkFound = ${JSON.stringify( secondNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* lastMatched = ${JSON.stringify( lastMatched, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* itsFirstTail = ${JSON.stringify( itsFirstTail, null, 4 )}`}\u001b[${39}m` ); continue; } // if we reached this point, this means, it's neither head nor tail, also // not a whitespace if (itsFirstTail) { itsFirstTail = true; } if (itsFirstLetter && !firstNonMarkerChunkFound) { console.log( `\u001b[${33}m${"530 firstNonMarkerChunkFound = true"}\u001b[${39}m` ); // wipe the conditionals: // conditionalRanges.wipe() // set the flags: firstNonMarkerChunkFound = true; itsFirstLetter = false; } else if (itsFirstLetter && !secondNonMarkerChunkFound) { console.log( `\u001b[${33}m${"540 secondNonMarkerChunkFound = true"}\u001b[${39}m` ); console.log(`\u001b[${33}m${"542 itsFirstTail = true"}\u001b[${39}m`); secondNonMarkerChunkFound = true; itsFirstTail = true; itsFirstLetter = false; // wipe the conditionals. // That's for example where we reached "n" in "{{ hi {{ name }}! }}" if (lastMatched === "heads") { conditionalRanges.wipe(); } } else if (itsFirstLetter && secondNonMarkerChunkFound) { // in this case we reached "!" in "{{ hi }} name {{! }}", for example. // Let's wipe the conditionals conditionalRanges.wipe(); } } console.log( `\u001b[${36}m${`\n* * *\nENDED WITH\n* conditional ranges:\n${JSON.stringify( conditionalRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* real ranges: ${JSON.stringify( realRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* firstNonMarkerChunkFound = ${JSON.stringify( firstNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* secondNonMarkerChunkFound = ${JSON.stringify( secondNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* lastMatched = ${JSON.stringify( lastMatched, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* itsFirstTail = ${JSON.stringify( itsFirstTail, null, 4 )}`}\u001b[${39}m` ); // } console.log( `\u001b[${36}m${`\n================\n\n* * *\nENDED WITH\n* conditional ranges:\n${JSON.stringify( conditionalRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* real ranges: ${JSON.stringify( realRanges.current(), null, 0 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* firstNonMarkerChunkFound = ${JSON.stringify( firstNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* secondNonMarkerChunkFound = ${JSON.stringify( secondNonMarkerChunkFound, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* lastMatched = ${JSON.stringify( lastMatched, null, 4 )}`}\u001b[${39}m` ); console.log( `\u001b[${36}m${`* itsFirstTail = ${JSON.stringify( itsFirstTail, null, 4 )}`}\u001b[${39}m` ); if (conditionalRanges.current()) { realRanges.push(conditionalRanges.current() as any); } if (realRanges.current()) { return rApply(str, realRanges.current()).trim(); } return str.trim(); } export { remDup, defaults, version };
the_stack
import { Stringish } from "flow2dts-flow-types-polyfill"; import { $Diff } from "utility-types"; import $1 from "../../DeprecatedPropTypes/DeprecatedTextInputPropTypes"; import $2 from "react"; import $3 from "./TextInputState"; import { TextStyleProp } from "../../StyleSheet/StyleSheet"; import { ViewStyleProp } from "../../StyleSheet/StyleSheet"; import { ColorValue } from "../../StyleSheet/StyleSheet"; import { ViewProps } from "../View/ViewPropTypes"; import { SyntheticEvent } from "../../Types/CoreEventTypes"; import { ScrollEvent } from "../../Types/CoreEventTypes"; import { PressEvent } from "../../Types/CoreEventTypes"; import { HostComponent } from "../../Renderer/shims/ReactNativeTypes"; declare type ReactRefSetter<T> = { current: null | T; } | ((ref: null | T) => unknown); declare type ChangeEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { eventCount: number; target: number; text: string; }>>; declare type TextInputEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { eventCount: number; previousText: string; range: Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { start: number; end: number; }>; target: number; text: string; }>>; declare type ContentSizeChangeEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { target: number; contentSize: Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { width: number; height: number; }>; }>>; declare type TargetEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { target: number; }>>; declare type BlurEvent = TargetEvent; declare type FocusEvent = TargetEvent; declare type Selection = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { start: number; end: number; }>; declare type SelectionChangeEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { selection: Selection; target: number; }>>; declare type KeyPressEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { key: string; target?: null | undefined | number; eventCount?: null | undefined | number; }>>; declare type EditingEvent = SyntheticEvent<Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { eventCount: number; text: string; target: number; }>>; declare type DataDetectorTypesType = "phoneNumber" | "link" | "address" | "calendarEvent" | "none" | "all"; declare type KeyboardType = // Cross Platform "default" | "email-address" | "numeric" | "phone-pad" | "number-pad" | "decimal-pad" // iOS-only | "ascii-capable" | "numbers-and-punctuation" | "url" | "name-phone-pad" | "twitter" | "web-search" // iOS 10+ only | "ascii-capable-number-pad" // Android-only | "visible-password"; declare type ReturnKeyType = // Cross Platform "done" | "go" | "next" | "search" | "send" // Android-only | "none" | "previous" // iOS-only | "default" | "emergency-call" | "google" | "join" | "route" | "yahoo"; declare type AutoCapitalize = "none" | "sentences" | "words" | "characters"; declare type TextContentType = "none" | "URL" | "addressCity" | "addressCityAndState" | "addressState" | "countryName" | "creditCardNumber" | "emailAddress" | "familyName" | "fullStreetAddress" | "givenName" | "jobTitle" | "location" | "middleName" | "name" | "namePrefix" | "nameSuffix" | "nickname" | "organizationName" | "postalCode" | "streetAddressLine1" | "streetAddressLine2" | "sublocality" | "telephoneNumber" | "username" | "password" | "newPassword" | "oneTimeCode"; declare type PasswordRules = string; declare type IOSProps = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { /** * If `false`, disables spell-check style (i.e. red underlines). * The default value is inherited from `autoCorrect`. * @platform ios */ spellCheck?: null | undefined | boolean; /** * Determines the color of the keyboard. * @platform ios */ keyboardAppearance?: null | undefined | ("default" | "light" | "dark"); /** * If `true`, the keyboard disables the return key when there is no text and * automatically enables it when there is text. The default value is `false`. * @platform ios */ enablesReturnKeyAutomatically?: null | undefined | boolean; /** * When the clear button should appear on the right side of the text view. * This property is supported only for single-line TextInput component. * @platform ios */ clearButtonMode?: null | undefined | ("never" | "while-editing" | "unless-editing" | "always"); /** * If `true`, clears the text field automatically when editing begins. * @platform ios */ clearTextOnFocus?: null | undefined | boolean; /** * Determines the types of data converted to clickable URLs in the text input. * Only valid if `multiline={true}` and `editable={false}`. * By default no data types are detected. * * You can provide one type or an array of many types. * * Possible values for `dataDetectorTypes` are: * * - `'phoneNumber'` * - `'link'` * - `'address'` * - `'calendarEvent'` * - `'none'` * - `'all'` * * @platform ios */ dataDetectorTypes?: (null | undefined | DataDetectorTypesType) | ReadonlyArray<DataDetectorTypesType>; /** * An optional identifier which links a custom InputAccessoryView to * this text input. The InputAccessoryView is rendered above the * keyboard when this text input is focused. * @platform ios */ inputAccessoryViewID?: null | undefined | string; /** * Give the keyboard and the system information about the * expected semantic meaning for the content that users enter. * @platform ios */ textContentType?: null | undefined | TextContentType; /** * Provide rules for your password. * For example, say you want to require a password with at least eight characters consisting of a mix of uppercase and lowercase letters, at least one number, and at most two consecutive characters. * "required: upper; required: lower; required: digit; max-consecutive: 2; minlength: 8;" * @platform ios */ passwordRules?: null | undefined | PasswordRules; /* * If `true`, allows TextInput to pass touch events to the parent component. * This allows components to be swipeable from the TextInput on iOS, * as is the case on Android by default. * If `false`, TextInput always asks to handle the input (except when disabled). * @platform ios */ rejectResponderTermination?: null | undefined | boolean; /** * If `false`, scrolling of the text view will be disabled. * The default value is `true`. Does only work with 'multiline={true}'. * @platform ios */ scrollEnabled?: null | undefined | boolean; }>; declare type AndroidProps = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { /** * Determines which content to suggest on auto complete, e.g.`username`. * To disable auto complete, use `off`. * * *Android Only* * * The following values work on Android only: * * - `username` * - `password` * - `email` * - `name` * - `tel` * - `street-address` * - `postal-code` * - `cc-number` * - `cc-csc` * - `cc-exp` * - `cc-exp-month` * - `cc-exp-year` * - `off` * * @platform android */ autoCompleteType?: null | undefined | ("cc-csc" | "cc-exp" | "cc-exp-month" | "cc-exp-year" | "cc-number" | "email" | "name" | "password" | "postal-code" | "street-address" | "tel" | "username" | "off"); /** * Sets the return key to the label. Use it instead of `returnKeyType`. * @platform android */ returnKeyLabel?: null | undefined | string; /** * Sets the number of lines for a `TextInput`. Use it with multiline set to * `true` to be able to fill the lines. * @platform android */ numberOfLines?: null | undefined | number; /** * When `false`, if there is a small amount of space available around a text input * (e.g. landscape orientation on a phone), the OS may choose to have the user edit * the text inside of a full screen text input mode. When `true`, this feature is * disabled and users will always edit the text directly inside of the text input. * Defaults to `false`. * @platform android */ disableFullscreenUI?: null | undefined | boolean; /** * Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced` * The default value is `simple`. * @platform android */ textBreakStrategy?: null | undefined | ("simple" | "highQuality" | "balanced"); /** * The color of the `TextInput` underline. * @platform android */ underlineColorAndroid?: null | undefined | ColorValue; /** * If defined, the provided image resource will be rendered on the left. * The image resource must be inside `/android/app/src/main/res/drawable` and referenced * like * ``` * <TextInput * inlineImageLeft='search_icon' * /> * ``` * @platform android */ inlineImageLeft?: null | undefined | string; /** * Padding between the inline image, if any, and the text input itself. * @platform android */ inlineImagePadding?: null | undefined | number; importantForAutofill?: null | undefined | ("auto" | "no" | "noExcludeDescendants" | "yes" | "yesExcludeDescendants"); /** * When `false`, it will prevent the soft keyboard from showing when the field is focused. * Defaults to `true`. */ showSoftInputOnFocus?: null | undefined | boolean; }>; declare type Props = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ $Diff<ViewProps, Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { style?: null | undefined | ViewStyleProp; }>> & IOSProps & AndroidProps & { /** * Can tell `TextInput` to automatically capitalize certain characters. * * - `characters`: all characters. * - `words`: first letter of each word. * - `sentences`: first letter of each sentence (*default*). * - `none`: don't auto capitalize anything. */ autoCapitalize?: null | undefined | AutoCapitalize; /** * If `false`, disables auto-correct. The default value is `true`. */ autoCorrect?: null | undefined | boolean; /** * If `true`, focuses the input on `componentDidMount`. * The default value is `false`. */ autoFocus?: null | undefined | boolean; /** * Specifies whether fonts should scale to respect Text Size accessibility settings. The * default is `true`. */ allowFontScaling?: null | undefined | boolean; /** * Specifies largest possible scale a font can reach when `allowFontScaling` is enabled. * Possible values: * `null/undefined` (default): inherit from the parent node or the global default (0) * `0`: no max, ignore parent/global default * `>= 1`: sets the maxFontSizeMultiplier of this node to this value */ maxFontSizeMultiplier?: null | undefined | number; /** * If `false`, text is not editable. The default value is `true`. */ editable?: null | undefined | boolean; /** * Determines which keyboard to open, e.g.`numeric`. * * The following values work across platforms: * * - `default` * - `numeric` * - `number-pad` * - `decimal-pad` * - `email-address` * - `phone-pad` * * *iOS Only* * * The following values work on iOS only: * * - `ascii-capable` * - `numbers-and-punctuation` * - `url` * - `name-phone-pad` * - `twitter` * - `web-search` * * *Android Only* * * The following values work on Android only: * * - `visible-password` * */ keyboardType?: null | undefined | KeyboardType; /** * Determines how the return key should look. On Android you can also use * `returnKeyLabel`. * * *Cross platform* * * The following values work across platforms: * * - `done` * - `go` * - `next` * - `search` * - `send` * * *Android Only* * * The following values work on Android only: * * - `none` * - `previous` * * *iOS Only* * * The following values work on iOS only: * * - `default` * - `emergency-call` * - `google` * - `join` * - `route` * - `yahoo` */ returnKeyType?: null | undefined | ReturnKeyType; /** * Limits the maximum number of characters that can be entered. Use this * instead of implementing the logic in JS to avoid flicker. */ maxLength?: null | undefined | number; /** * If `true`, the text input can be multiple lines. * The default value is `false`. */ multiline?: null | undefined | boolean; /** * Callback that is called when the text input is blurred. */ onBlur?: null | undefined | ((e: BlurEvent) => unknown); /** * Callback that is called when the text input is focused. */ onFocus?: null | undefined | ((e: FocusEvent) => unknown); /** * Callback that is called when the text input's text changes. */ onChange?: null | undefined | ((e: ChangeEvent) => unknown); /** * Callback that is called when the text input's text changes. * Changed text is passed as an argument to the callback handler. */ onChangeText?: null | undefined | ((text: string) => unknown); /** * Callback that is called when the text input's content size changes. * This will be called with * `{ nativeEvent: { contentSize: { width, height } } }`. * * Only called for multiline text inputs. */ onContentSizeChange?: null | undefined | ((e: ContentSizeChangeEvent) => unknown); /** * Callback that is called when text input ends. */ onEndEditing?: null | undefined | ((e: EditingEvent) => unknown); /** * Called when a touch is engaged. */ onPressIn?: null | undefined | ((event: PressEvent) => unknown); /** * Called when a touch is released. */ onPressOut?: null | undefined | ((event: PressEvent) => unknown); /** * Callback that is called when the text input selection is changed. * This will be called with * `{ nativeEvent: { selection: { start, end } } }`. */ onSelectionChange?: null | undefined | ((e: SelectionChangeEvent) => unknown); /** * Callback that is called when the text input's submit button is pressed. * Invalid if `multiline={true}` is specified. */ onSubmitEditing?: null | undefined | ((e: EditingEvent) => unknown); /** * Callback that is called when a key is pressed. * This will be called with `{ nativeEvent: { key: keyValue } }` * where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and * the typed-in character otherwise including `' '` for space. * Fires before `onChange` callbacks. */ onKeyPress?: null | undefined | ((e: KeyPressEvent) => unknown); /** * Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`. * May also contain other properties from ScrollEvent but on Android contentSize * is not provided for performance reasons. */ onScroll?: null | undefined | ((e: ScrollEvent) => unknown); /** * The string that will be rendered before text input has been entered. */ placeholder?: null | undefined | Stringish; /** * The text color of the placeholder string. */ placeholderTextColor?: null | undefined | ColorValue; /** * If `true`, the text input obscures the text entered so that sensitive text * like passwords stay secure. The default value is `false`. Does not work with 'multiline={true}'. */ secureTextEntry?: null | undefined | boolean; /** * The highlight and cursor color of the text input. */ selectionColor?: null | undefined | ColorValue; /** * The start and end of the text input's selection. Set start and end to * the same value to position the cursor. */ selection?: null | undefined | Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { start: number; end?: null | undefined | number; }>; /** * The value to show for the text input. `TextInput` is a controlled * component, which means the native value will be forced to match this * value prop if provided. For most uses, this works great, but in some * cases this may cause flickering - one common cause is preventing edits * by keeping value the same. In addition to simply setting the same value, * either set `editable={false}`, or set/update `maxLength` to prevent * unwanted edits without flicker. */ value?: null | undefined | Stringish; /** * Provides an initial value that will change when the user starts typing. * Useful for simple use-cases where you do not want to deal with listening * to events and updating the value prop to keep the controlled state in sync. */ defaultValue?: null | undefined | Stringish; /** * If `true`, all text will automatically be selected on focus. */ selectTextOnFocus?: null | undefined | boolean; /** * If `true`, the text field will blur when submitted. * The default value is true for single-line fields and false for * multiline fields. Note that for multiline fields, setting `blurOnSubmit` * to `true` means that pressing return will blur the field and trigger the * `onSubmitEditing` event instead of inserting a newline into the field. */ blurOnSubmit?: null | undefined | boolean; /** * Note that not all Text styles are supported, an incomplete list of what is not supported includes: * * - `borderLeftWidth` * - `borderTopWidth` * - `borderRightWidth` * - `borderBottomWidth` * - `borderTopLeftRadius` * - `borderTopRightRadius` * - `borderBottomRightRadius` * - `borderBottomLeftRadius` * * see [Issue#7070](https://github.com/facebook/react-native/issues/7070) * for more detail. * * [Styles](docs/style.html) */ style?: null | undefined | TextStyleProp; /** * If `true`, caret is hidden. The default value is `false`. * * On Android devices manufactured by Xiaomi with Android Q, * when keyboardType equals 'email-address'this will be set * in native to 'true' to prevent a system related crash. This * will cause cursor to be diabled as a side-effect. * */ caretHidden?: null | undefined | boolean; /* * If `true`, contextMenuHidden is hidden. The default value is `false`. */ contextMenuHidden?: null | undefined | boolean; forwardedRef?: null | undefined | ReactRefSetter<$2.ElementRef<HostComponent<{}>> & ImperativeMethods>; }>; declare type ImperativeMethods = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { clear: () => void; isFocused: () => boolean; getNativeRef: () => null | undefined | $2.ElementRef<HostComponent<{}>>; }>; declare function InternalTextInput(props: Props): $2.Element<Props>; declare type TextInputComponentStatics = Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { State: Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ { currentlyFocusedInput: typeof $3.currentlyFocusedInput; currentlyFocusedField: typeof $3.currentlyFocusedField; focusTextInput: typeof $3.focusTextInput; blurTextInput: typeof $3.blurTextInput; }>; }>; export type { ChangeEvent }; export type { TextInputEvent }; export type { ContentSizeChangeEvent }; export type { BlurEvent }; export type { FocusEvent }; export type { SelectionChangeEvent }; export type { KeyPressEvent }; export type { EditingEvent }; export type { KeyboardType }; export type { ReturnKeyType }; export type { AutoCapitalize }; export type { TextContentType }; export type { Props }; declare const $f2tExportDefault: $2.AbstractComponent<$2.ElementConfig<typeof InternalTextInput>, Readonly< /*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/ $2.ElementRef<HostComponent<{}>> & ImperativeMethods & {}>> & TextInputComponentStatics; export default $f2tExportDefault;
the_stack
import { BlockFactory, SerializedElementAnalysis } from "@css-blocks/core"; import { ObjectDictionary } from "@opticss/util"; import { assert } from "chai"; import { GlimmerAnalyzer } from "../src"; import { fixture, moduleConfig } from "./fixtures"; type ElementsAnalysis = ObjectDictionary<SerializedElementAnalysis>; describe("Stylesheet analysis", function () { it("analyzes styles from the implicit block", function () { let analyzer = new GlimmerAnalyzer(new BlockFactory({}), {}, moduleConfig); return analyzer.analyze(fixture("styled-app"), ["my-app"]).then((analyzer: GlimmerAnalyzer) => { let analysis = analyzer.getAnalysis(0); let serializedAnalysis = analysis.serialize(); assert.equal(analysis.template.identifier, "template:/styled-app/components/my-app"); assert.deepEqual(serializedAnalysis.blocks, { "default": fixture("styled-app/src/ui/components/my-app/stylesheet.css"), }); assert.deepEqual(serializedAnalysis.stylesFound, ["default.editor", "default.editor[disabled]", "default:scope", "default:scope[is-loading]"]); let expected: ElementsAnalysis = { a: { tagName: "div", staticStyles: [2, 3], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 1, column: 0, "filename": "template:/styled-app/components/my-app" }, end: { line: 4, column: 6, "filename": "template:/styled-app/components/my-app" } } }, b: { tagName: "page-banner", staticStyles: [], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 2, column: 2, "filename": "template:/styled-app/components/my-app" }, end: { line: 2, column: 17, "filename": "template:/styled-app/components/my-app" } } }, c: { tagName: "text-editor", staticStyles: [0, 1], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 3, column: 2, "filename": "template:/styled-app/components/my-app" }, end: { line: 3, column: 61, "filename": "template:/styled-app/components/my-app" } } }, }; assert.deepEqual(serializedAnalysis.elements, expected); // // deserialize and re-serialize to make sure it creates the same representation. // let factory = new BlockFactory(analyzer.project.cssBlocksOpts, postcss); // return TemplateAnalysis.deserialize<TEMPLATE_TYPE>(serializedAnalysis, factory).then(recreatedAnalysis => { // let reserializedAnalysis = recreatedAnalysis.serialize(); // assert.deepEqual(reserializedAnalysis, serializedAnalysis); // }); }).catch((error) => { console.error(error); throw error; }); }); it("analyzes styles from a referenced block", function () { let projectDir = fixture("styled-app"); let analyzer = new GlimmerAnalyzer(new BlockFactory({}), {}, moduleConfig); return analyzer.analyze(projectDir, ["with-multiple-blocks"]).then((analyzer: GlimmerAnalyzer) => { let analysis = analyzer.getAnalysis(0).serialize(); assert.equal(analysis.template.identifier, "template:/styled-app/components/with-multiple-blocks"); assert.deepEqual(analysis.blocks, { "default": fixture("styled-app/src/ui/components/with-multiple-blocks/stylesheet.css"), "h": fixture("styled-app/src/ui/components/with-multiple-blocks/header.css"), }); assert.deepEqual(analysis.stylesFound, ["default.world", "default.world[thick]", "default:scope", "default>h.emphasis", "default>h.emphasis[extra]", "default>h:scope"]); assert.deepEqual(analysis.elements, { a: { tagName: "div", staticStyles: [2], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 1, column: 0, "filename": "template:/styled-app/components/with-multiple-blocks" }, end: { line: 3, column: 6, "filename": "template:/styled-app/components/with-multiple-blocks" } } }, b: { tagName: "h1", staticStyles: [5], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 2, column: 2, "filename": "template:/styled-app/components/with-multiple-blocks" }, end: { line: 2, column: 104, "filename": "template:/styled-app/components/with-multiple-blocks" } } }, c: { tagName: "span", staticStyles: [0, 1, 3, 4], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 2, column: 21, "filename": "template:/styled-app/components/with-multiple-blocks" }, end: { line: 2, column: 98, "filename": "template:/styled-app/components/with-multiple-blocks" } } }, }); }).catch((error) => { console.error(error); throw error; }); }); it("analyzes styles from built-ins", function () { let projectDir = fixture("styled-app"); let analyzer = new GlimmerAnalyzer(new BlockFactory({}), {}, moduleConfig); return analyzer.analyze(projectDir, ["with-link-to"]).then((analyzer: GlimmerAnalyzer) => { let analysis = analyzer.getAnalysis(0).serialize(); assert.equal(analysis.template.identifier, "template:/styled-app/components/with-link-to"); assert.deepEqual(analysis.blocks, { "default": fixture("styled-app/src/ui/components/with-link-to/stylesheet.css"), "external": fixture("styled-app/src/ui/components/with-link-to/external.css"), "util": fixture("styled-app/src/ui/components/with-link-to/util.css"), }); assert.deepEqual(analysis.stylesFound, [ "default.link-1", "default.link-2", "default.link-2[active]", "default.link-4", "default.link-4[active]", "default.link-4[disabled]", "default.link-4[loading]", "default:scope", "default>external.link-3", "default>external.link-3[active]", "util.util", ]); assert.deepEqual(analysis.elements, { "a": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "filename": "template:/styled-app/components/with-link-to", "line": 20, "column": 6, }, "start": { "filename": "template:/styled-app/components/with-link-to", "line": 1, "column": 0, }, }, "staticStyles": [ 7, ], "tagName": "div", }, "b": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 62, "filename": "template:/styled-app/components/with-link-to", "line": 2, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 2, }, }, "staticStyles": [ 0, ], "tagName": "link-to", }, "c": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 88, "filename": "template:/styled-app/components/with-link-to", "line": 3, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 3, }, }, "staticStyles": [ 0, 10, ], "tagName": "link-to", }, "d": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 69, "filename": "template:/styled-app/components/with-link-to", "line": 5, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 5, }, }, "staticStyles": [ 1, ], "tagName": "link-to", }, "e": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 69, "filename": "template:/styled-app/components/with-link-to", "line": 5, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 5, }, }, "staticStyles": [ 1, 2, ], "tagName": "link-to", }, "f": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 77, "filename": "template:/styled-app/components/with-link-to", "line": 6, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 6, }, }, "staticStyles": [ 1, ], "tagName": "link-to", }, "g": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 77, "filename": "template:/styled-app/components/with-link-to", "line": 6, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 6, }, }, "staticStyles": [ 1, 2, ], "tagName": "link-to", }, "h": { "dynamicAttributes": [], "dynamicClasses": [ { "condition": true, "whenTrue": [ 1, ], }, ], "sourceLocation": { "end": { "column": 115, "filename": "template:/styled-app/components/with-link-to", "line": 8, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 8, }, }, "staticStyles": [], "tagName": "link-to", }, "i": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 115, "filename": "template:/styled-app/components/with-link-to", "line": 8, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 8, }, }, "staticStyles": [ 1, 2, ], "tagName": "link-to", }, "j": { "dynamicAttributes": [], "dynamicClasses": [ { "condition": true, "whenTrue": [ 1, ], }, ], "sourceLocation": { "end": { "column": 100, "filename": "template:/styled-app/components/with-link-to", "line": 9, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 9, }, }, "staticStyles": [], "tagName": "link-to", }, "k": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 100, "filename": "template:/styled-app/components/with-link-to", "line": 9, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 9, }, }, "staticStyles": [ 1, 2, ], "tagName": "link-to", }, "l": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 109, "filename": "template:/styled-app/components/with-link-to", "line": 11, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 11, }, }, "staticStyles": [ 8, ], "tagName": "link-to", }, "m": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 109, "filename": "template:/styled-app/components/with-link-to", "line": 11, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 11, }, }, "staticStyles": [ 8, 9, ], "tagName": "link-to", }, "n": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 94, "filename": "template:/styled-app/components/with-link-to", "line": 12, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 12, }, }, "staticStyles": [ 8, ], "tagName": "link-to", }, "o": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 94, "filename": "template:/styled-app/components/with-link-to", "line": 12, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 12, }, }, "staticStyles": [ 8, 9, ], "tagName": "link-to", }, "p": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 111, "filename": "template:/styled-app/components/with-link-to", "line": 14, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 14, }, }, "staticStyles": [ 8, ], "tagName": "link-to", }, "q": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 111, "filename": "template:/styled-app/components/with-link-to", "line": 14, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 14, }, }, "staticStyles": [ 8, 9, ], "tagName": "link-to", }, "r": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 96, "filename": "template:/styled-app/components/with-link-to", "line": 15, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 15, }, }, "staticStyles": [ 8, ], "tagName": "link-to", }, "s": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 96, "filename": "template:/styled-app/components/with-link-to", "line": 15, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 15, }, }, "staticStyles": [ 8, 9, ], "tagName": "link-to", }, "t": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 105, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, }, "staticStyles": [ 3, ], "tagName": "link-to", }, "u": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 105, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, }, "staticStyles": [ 3, 4, ], "tagName": "link-to", }, "v": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 105, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, }, "staticStyles": [ 3, 6, ], "tagName": "link-to", }, "w": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 105, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 17, }, }, "staticStyles": [ 3, 5, ], "tagName": "link-to", }, "x": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 114, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, }, "staticStyles": [ 3, ], "tagName": "link-to", }, "y": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 114, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, }, "staticStyles": [ 3, 4, ], "tagName": "link-to", }, "z": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 114, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, }, "staticStyles": [ 3, 6, ], "tagName": "link-to", }, "A": { "dynamicAttributes": [], "dynamicClasses": [], "sourceLocation": { "end": { "column": 114, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, "start": { "column": 2, "filename": "template:/styled-app/components/with-link-to", "line": 18, }, }, "staticStyles": [ 3, 5, ], "tagName": "link-to", }, }); }).catch((error) => { console.error(error); throw error; }); }); it("analyzes styles from a referenced block with dynamic state", function () { let projectDir = fixture("styled-app"); let analyzer = new GlimmerAnalyzer(new BlockFactory({}), {}, moduleConfig); return analyzer.analyze(projectDir, ["with-dynamic-states"]).then((analyzer: GlimmerAnalyzer) => { let analysis = analyzer.getAnalysis(0).serialize(); assert.equal(analysis.template.identifier, "template:/styled-app/components/with-dynamic-states"); assert.deepEqual(analysis.blocks, { "default": fixture("styled-app/src/ui/components/with-dynamic-states/stylesheet.css"), "h": fixture("styled-app/src/ui/components/with-dynamic-states/header.css"), }); assert.deepEqual(analysis.stylesFound, [ "default.world", "default.world[thick]", "default:scope", "h.emphasis", "h.emphasis[style=bold]", "h.emphasis[style=italic]", "h:scope", ]); assert.deepEqual(analysis.elements, { a: { tagName: "div", staticStyles: [2], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 1, column: 0, "filename": "template:/styled-app/components/with-dynamic-states" }, end: { line: 3, column: 6, "filename": "template:/styled-app/components/with-dynamic-states" } }, }, b: { tagName: "h1", staticStyles: [6], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 2, column: 2, "filename": "template:/styled-app/components/with-dynamic-states" }, end: { line: 2, column: 130, "filename": "template:/styled-app/components/with-dynamic-states" } }, }, c: { tagName: "span", staticStyles: [0, 3], dynamicClasses: [], dynamicAttributes: [ { condition: true, value: [1] }, { stringExpression: true, group: { bold: 4, italic: 5 }, value: [] }, ], sourceLocation: { start: { line: 2, column: 21, "filename": "template:/styled-app/components/with-dynamic-states" }, end: { line: 2, column: 124, "filename": "template:/styled-app/components/with-dynamic-states" } }, }, }); }).catch((error) => { console.error(error); throw error; }); }); it("analyzes styles from a referenced block with dynamic classes", function () { let projectDir = fixture("styled-app"); let analyzer = new GlimmerAnalyzer(new BlockFactory({}), {}, moduleConfig); return analyzer.analyze(projectDir, ["with-dynamic-classes"]).then((analyzer) => { let analysis = analyzer.getAnalysis(0).serialize(); assert.equal(analysis.template.identifier, "template:/styled-app/components/with-dynamic-classes"); assert.deepEqual(analysis.blocks, { "default": fixture("styled-app/src/ui/components/with-dynamic-classes/stylesheet.css"), "h": fixture("styled-app/src/ui/components/with-dynamic-classes/header.css"), "t": fixture("styled-app/src/ui/components/with-dynamic-classes/typography.css"), }); assert.deepEqual(analysis.stylesFound, [ "default.planet", "default.world", "default.world[thick]", "default:scope", "default>h.emphasis", "default>h.emphasis[style=bold]", "default>h.emphasis[style=italic]", "default>h:scope", "default>t.underline", ]); assert.deepEqual(analysis.elements, { a: { tagName: "div", staticStyles: [3], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 1, column: 0, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 7, column: 6, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, b: { tagName: "h1", staticStyles: [7], dynamicClasses: [], dynamicAttributes: [], sourceLocation: { start: { line: 2, column: 2, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 2, column: 176, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, c: { tagName: "span", staticStyles: [4, 8], dynamicClasses: [{ condition: true, whenTrue: [1] }], dynamicAttributes: [ { condition: true, value: [2], container: 1 }, { stringExpression: true, group: { bold: 5, italic: 6 }, value: [] }, ], sourceLocation: { start: { line: 2, column: 21, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 2, column: 170, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, d: { tagName: "div", staticStyles: [], dynamicClasses: [{ condition: true, whenTrue: [1], whenFalse: [0] }], dynamicAttributes: [], sourceLocation: { start: { line: 3, column: 2, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 3, column: 68, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, e: { tagName: "div", staticStyles: [], dynamicClasses: [{ condition: true, whenTrue: [0], whenFalse: [1] }], dynamicAttributes: [], sourceLocation: { start: { line: 4, column: 2, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 4, column: 72, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, f: { tagName: "div", staticStyles: [], dynamicClasses: [{ condition: true, whenFalse: [1] }], dynamicAttributes: [], sourceLocation: { start: { line: 5, column: 2, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 5, column: 63, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, g: { tagName: "h2", staticStyles: [], dynamicClasses: [{ condition: true, whenTrue: [7] }], dynamicAttributes: [], sourceLocation: { start: { line: 6, column: 2, "filename": "template:/styled-app/components/with-dynamic-classes" }, end: { line: 6, column: 44, "filename": "template:/styled-app/components/with-dynamic-classes" } }, }, }); }).catch((error) => { console.error(error); throw error; }); }); });
the_stack
import FontFaceObserver from 'fontfaceobserver-es'; // Constants import { ASSET_LOADED, ASSETS_LOADED } from '../constants'; // Events import { eventEmitter } from '../events/EventEmitter'; // Features import getBrowserType from '../features/browserFeatures/getBrowserType'; import getWebGLFeatures from '../features/browserFeatures/getWebGLFeatures'; import isImageBitmapSupported from '../features/browserFeatures/isImageBitmapSupported'; import isImageDecodeSupported from '../features/browserFeatures/isImageDecodeSupported'; import isWebAssemblySupported from '../features/browserFeatures/isWebAssemblySupported'; // Utilities import { assert, convertBlobToArrayBuffer } from '../utilities'; // Types import { TNullable, TUndefinable, TVoidable } from '../types'; import { ELoaderKey, IAssetLoaderOptions, IByDeviceTypeOptions, IBySupportedCompressedTextureOptions, ILoadItem, } from './types'; /** * Loader types and the extensions they handle * Allows the omission of the loader key for some generic extensions used on the web */ const LOADER_EXTENSIONS_MAP = new Map([ [ELoaderKey.ArrayBuffer, { extensions: ['bin'] }], [ELoaderKey.Audio, { extensions: ['mp3', 'm4a', 'ogg', 'wav', 'flac'] }], [ELoaderKey.Audiopack, { extensions: ['audiopack'] }], [ELoaderKey.Binpack, { extensions: ['binpack'] }], [ELoaderKey.Font, { extensions: ['woff2', 'woff', 'ttf', 'otf', 'eot'] }], [ELoaderKey.Image, { extensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'] }], [ELoaderKey.ImageBitmap, { extensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'] }], [ELoaderKey.ImageCompressed, { extensions: ['ktx'] }], [ELoaderKey.JSON, { extensions: ['json'] }], [ELoaderKey.Text, { extensions: ['txt', 'm3u8'] }], [ELoaderKey.Video, { extensions: ['webm', 'ogg', 'mp4'] }], [ELoaderKey.WebAssembly, { extensions: ['wasm', 'wat'] }], [ ELoaderKey.XML, { defaultMimeType: 'text/xml', extensions: ['xml', 'svg', 'html'], mimeType: { html: 'text/html', svg: 'image/svg+xml', xml: 'text/xml', }, }, ], ]); // Safari does not fire `canplaythrough` preventing it from resolving naturally // A workaround is to not wait for the `canplaythrough` event but rather resolve early and hope for the best const IS_MEDIA_PRELOAD_SUPPORTED = !getBrowserType.isSafari; /** * Asynchronous asset preloader */ export class AssetLoader { public assets: Map<string, Promise<Response>> = new Map(); private options: IAssetLoaderOptions; private domParser = new DOMParser(); constructor(options: IAssetLoaderOptions) { this.options = options; } /** * Load conditionally based on device type */ public byDeviceType = (data: IByDeviceTypeOptions): TUndefinable<string> => data.DESKTOP && getBrowserType.isDesktop ? data.DESKTOP : data.TABLET && getBrowserType.isTablet ? data.TABLET : data.MOBILE; /** * Load conditionally based on supported compressed texture */ public bySupportedCompressedTexture = ( data: IBySupportedCompressedTextureOptions ): TUndefinable<string> => { if (getWebGLFeatures) { return data.ASTC && getWebGLFeatures.extensions.compressedTextureASTCExtension ? data.ASTC : data.ETC && getWebGLFeatures.extensions.compressedTextureETCExtension ? data.ETC : data.PVRTC && getWebGLFeatures.extensions.compressedTexturePVRTCExtension ? data.PVRTC : data.S3TC && getWebGLFeatures.extensions.compressedTextureS3TCExtension ? data.S3TC : data.FALLBACK; } else { return data.FALLBACK; } }; /** * Load the specified manifest (array of items) * * @param items Items to load */ public loadAssets = (items: ILoadItem[]): Promise<any> => { const loadingAssets = items .filter(item => item) .map(item => { const startTime = window.performance.now(); return new Promise((resolve): void => { const cacheHit = this.assets.get(item.src); if (cacheHit) { resolve({ fromCache: true, id: item.id || item.src, item: cacheHit, timeToLoad: window.performance.now() - startTime, }); } const loaderType = item.loader || this.getLoaderByFileExtension(item.src); let loadedItem; switch (loaderType) { case ELoaderKey.ArrayBuffer: loadedItem = this.loadArrayBuffer(item); break; case ELoaderKey.Audio: loadedItem = this.loadAudio(item); break; case ELoaderKey.Audiopack: loadedItem = this.loadAudiopack(item); break; case ELoaderKey.Binpack: loadedItem = this.loadBinpack(item); break; case ELoaderKey.Blob: loadedItem = this.loadBlob(item); break; case ELoaderKey.Font: loadedItem = this.loadFont(item); break; case ELoaderKey.Image: loadedItem = this.loadImage(item); break; case ELoaderKey.ImageBitmap: loadedItem = this.loadImageBitmap(item); break; case ELoaderKey.ImageCompressed: loadedItem = this.loadImageCompressed(item); break; case ELoaderKey.JSON: loadedItem = this.loadJSON(item); break; case ELoaderKey.Text: loadedItem = this.loadText(item); break; case ELoaderKey.Video: loadedItem = this.loadVideo(item); break; case ELoaderKey.WebAssembly: loadedItem = this.loadWebAssembly(item); break; case ELoaderKey.XML: loadedItem = this.loadXML(item); break; default: console.warn('AssetLoader -> Missing loader, falling back to loading as ArrayBuffer'); loadedItem = this.loadArrayBuffer(item); break; } loadedItem.then((asset: any) => { this.assets.set(item.src, asset); resolve({ fromCache: false, id: item.id || item.src, item: asset, loaderType, persistent: item.persistent, timeToLoad: window.performance.now() - startTime, }); }); }); }); const loadedAssets = Promise.all(loadingAssets); let progress = 0; loadingAssets.forEach((promise: Promise<any>) => promise.then(asset => { progress++; if (asset.persistent && (!this.options || !this.options.persistentCache)) { console.warn( 'AssetLoader -> Persistent caching requires an instance of a PersistentCache to be passed to the AssetLoader constructor' ); } if (this.options && this.options.persistentCache && asset.persistent) { switch (asset.loaderType) { case ELoaderKey.ArrayBuffer: this.options.persistentCache.set(asset.id, asset.item); break; case ELoaderKey.Blob: // Safari iOS does not permit storing file blobs and must be converted to ArrayBuffers // SEE: https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/indexeddb-best-practices convertBlobToArrayBuffer(asset.item).then(buffer => { if (this.options && this.options.persistentCache) { this.options.persistentCache.set(asset.id, buffer); } }); break; default: console.warn( 'AssetLoader -> Persistent caching is currently only possible with ArrayBuffer and Blob loaders' ); } } eventEmitter.emit(ASSET_LOADED, { id: asset.id, progress: `${(progress / loadingAssets.length).toFixed(2)}`, timeToLoad: `${asset.timeToLoad.toFixed(2)}ms`, }); }) ); return loadedAssets.then(assets => { const assetMap = new Map(); assets.forEach((asset: any) => { if (assetMap.get(asset.id)) { console.warn("AssetLoader -> Detected duplicate id, please use unique id's"); } assetMap.set(asset.id, asset.item); }); eventEmitter.emit(ASSETS_LOADED, { assetMap, }); return assetMap; }); }; /** * Get a file extension from a full asset path * * @param path Path to asset */ private getFileExtension = (path: string): string => { const basename = path.split(/[\\/]/).pop(); if (!basename) { return ''; } const seperator = basename.lastIndexOf('.'); if (seperator < 1) { return ''; } return basename.slice(seperator + 1); }; /** * Retrieve mime type from extension * * @param loaderKey Loader key * @param extension extension */ private getMimeType = (loaderKey: ELoaderKey, extension: string): string => { const loader: any = LOADER_EXTENSIONS_MAP.get(loaderKey); return loader.mimeType[extension] || loader.defaultMimeType; }; /** * Retrieve loader key from extension (when the loader option isn't specified) * * @param path File path */ private getLoaderByFileExtension = (path: string): string => { const fileExtension = this.getFileExtension(path); const loader = Array.from(LOADER_EXTENSIONS_MAP).find(type => type[1].extensions.includes(fileExtension) ); return loader ? loader[0] : ELoaderKey.ArrayBuffer; }; /** * Fetch wrapper for loading an item, to be processed by a specific loader afterwards * * @param item Item to fetch */ private fetchItem = (item: ILoadItem): Promise<Response> => fetch(item.src, item.options || {}); /** * Load an item and parse the Response as arrayBuffer * * @param item Item to load */ private loadArrayBuffer = (item: ILoadItem): Promise<ArrayBuffer | void> => this.fetchItem(item) .then(response => response.arrayBuffer()) .catch(err => { console.warn(err.message); }); /** * Load an item and parse the Response as <audio> element * * @param item Item to load */ private loadAudio = (item: ILoadItem): Promise<any> => this.fetchItem(item) .then(response => response.blob()) .then( blob => new Promise((resolve, reject): void => { const audio = document.createElement('audio'); if (item.loaderOptions && item.loaderOptions.crossOrigin) { audio.crossOrigin = 'anonymous'; } audio.preload = 'auto'; audio.autoplay = false; if (IS_MEDIA_PRELOAD_SUPPORTED) { audio.addEventListener('canplaythrough', function handler(): void { audio.removeEventListener('canplaythrough', handler); URL.revokeObjectURL(audio.src); resolve(audio); }); audio.addEventListener('error', function handler(): void { audio.removeEventListener('error', handler); URL.revokeObjectURL(audio.src); reject(audio); }); } audio.src = URL.createObjectURL(blob); if (!IS_MEDIA_PRELOAD_SUPPORTED) { // Force the audio to load but resolve immediately as `canplaythrough` event will never be fired audio.load(); resolve(audio); } }) ) .catch(err => { console.error(err); }); /** * Load an item and parse the Response as Audiopack * * @param item Item to load */ private loadAudiopack = (item: ILoadItem): Promise<any> => this.loadArrayBuffer(item).then((data: TVoidable<ArrayBuffer>): any => { if (data) { let content: TNullable<string> = null; let contentArray: TNullable<Uint8Array> = null; let binaryChunk: TNullable<ArrayBuffer> = null; let byteOffset: number = 0; let chunkIndex: number = 0; let chunkLength: number = 0; let chunkType: TNullable<number> = null; const headerMagic = new Uint8Array(data, 0, 4).reduce( (magic, char) => (magic += String.fromCharCode(char)), '' ); assert(headerMagic === 'AUDP', 'AssetLoader -> Unsupported Audiopacker header'); const chunkView = new DataView(data, 12); while (chunkIndex < chunkView.byteLength) { chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === 0x4e4f534a) { contentArray = new Uint8Array(data, 12 + chunkIndex, chunkLength); content = contentArray.reduce((str, char) => (str += String.fromCharCode(char)), ''); } else if (chunkType === 0x004e4942) { byteOffset = 12 + chunkIndex; binaryChunk = data.slice(byteOffset, byteOffset + chunkLength); } chunkIndex += chunkLength; } assert(content !== null, 'AssetLoader -> JSON content chunk not found'); if (content) { const jsonChunk = JSON.parse(content); const binary = binaryChunk && binaryChunk.slice(jsonChunk.bufferStart, jsonChunk.bufferEnd); assert(binary !== null, 'AssetLoader -> Binary content chunk not found'); const blob = binary && new Blob([new Uint8Array(binary)], { type: jsonChunk.mimeType, }); if (blob) { return Promise.resolve( this.loadAudio({ src: URL.createObjectURL(blob), id: item.src }) ).then(audio => { return { audio, data: jsonChunk.data, mimeType: jsonChunk.mimeType, }; }); } } } }); /** * Load an item and parse the Response as Binpack * * @param item Item to load */ private loadBinpack = (item: ILoadItem): Promise<any> => this.loadArrayBuffer(item).then((data: TVoidable<ArrayBuffer>): any => { if (data) { let content: TNullable<string> = null; let contentArray: TNullable<Uint8Array> = null; let binaryChunk: TNullable<ArrayBuffer> = null; let byteOffset: number = 0; let chunkIndex: number = 0; let chunkLength: number = 0; let chunkType: TNullable<number> = null; const headerMagic = new Uint8Array(data, 0, 4).reduce( (magic, char) => (magic += String.fromCharCode(char)), '' ); assert(headerMagic === 'BINP', 'AssetLoader -> Unsupported Binpacker header'); const chunkView = new DataView(data, 12); while (chunkIndex < chunkView.byteLength) { chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === 0x4e4f534a) { contentArray = new Uint8Array(data, 12 + chunkIndex, chunkLength); content = contentArray.reduce((str, char) => (str += String.fromCharCode(char)), ''); } else if (chunkType === 0x004e4942) { byteOffset = 12 + chunkIndex; binaryChunk = data.slice(byteOffset, byteOffset + chunkLength); } chunkIndex += chunkLength; } assert(content !== null, 'AssetLoader -> JSON content chunk not found'); if (content && binaryChunk) { const jsonChunk = JSON.parse(content); return Promise.all( jsonChunk.map( (entry: { name: string; mimeType: string; bufferStart: number; bufferEnd: number; }) => { const { name, mimeType } = entry; const binary = binaryChunk && binaryChunk.slice(entry.bufferStart, entry.bufferEnd); assert(binary !== null, 'AssetLoader -> Binary content chunk not found'); const blob = binary && new Blob([new Uint8Array(binary)], { type: mimeType, }); const loaderType = this.getLoaderByFileExtension(name); const url = URL.createObjectURL(blob); switch (loaderType) { case ELoaderKey.Image: return this.loadImage({ src: url, id: name }); case ELoaderKey.JSON: return this.loadJSON({ src: url, id: name }); case ELoaderKey.Text: return this.loadText({ src: url, id: name }); case ELoaderKey.XML: return this.loadXML({ src: url, id: name }); default: throw new Error( 'AssetLoader -> Binpack currently only supports images, JSON, plain text and XML (SVG)' ); } } ) ).then((assets: any[]) => { return Object.assign( {}, ...jsonChunk.map((entry: any, index: number) => { return { [entry.name]: assets[index] }; }) ); }); } } }); /** * Load an item and parse the Response as blob * * @param item Item to load */ private loadBlob = (item: ILoadItem): Promise<Blob | void> => this.fetchItem(item) .then(response => response.blob()) .catch(err => { console.error(err); }); /** * Load an item and parse the Response as a FontFace * * @param item Item to load */ private loadFont = (item: ILoadItem): Promise<any> => new FontFaceObserver(item.id, item.options || {}).load(); /** * Load an item and parse the Response as <image> element * * @param item Item to load */ private loadImage = (item: ILoadItem): Promise<HTMLImageElement> => new Promise((resolve, reject): void => { const image = new Image(); if (item.loaderOptions && item.loaderOptions.crossOrigin) { image.crossOrigin = 'anonymous'; } // Check if we can decode non-blocking by loading the image asynchronously using image.decode().then(() => ...) // SEE: https://www.chromestatus.com/feature/5637156160667648 (Chrome | Safari | Safari iOS) if (isImageDecodeSupported) { image.src = item.src; image .decode() .then(() => { resolve(image); }) .catch(err => { reject(err); }); } else { // Fallback solution // Decode as synchronous blocking on the main thread // This is the least favorable method and should preferably only be used in old browsers (Edge | Firefox) image.onload = (): void => { resolve(image); }; image.onerror = (err): void => { reject(err); }; image.src = item.src; } }); /** * Load an item and parse the Response as ImageBitmap element * * NOTE: Please be cautious when using loadImageBitmap as browser support is still spotty and unreliable * * SEE: * - https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-createimagebitmap * - https://caniuse.com/createimagebitmap * - https://bugzilla.mozilla.org/show_bug.cgi?id=1335594 * - https://bugzilla.mozilla.org/show_bug.cgi?id=1363861 * * @param item Item to load */ private loadImageBitmap = (item: ILoadItem): Promise<ImageBitmap | HTMLImageElement> => { if (isImageBitmapSupported) { return this.loadBlob(item).then(data => { if (data) { if (item.loaderOptions) { const { sx, sy, sw, sh, options } = item.loaderOptions; if (sx !== undefined && sy !== undefined && sw !== undefined && sh !== undefined) { if (options !== undefined) { // NOTE: Firefox does not yet support passing options (at least as second parameter) to createImageBitmap and throws // SEE: https://bugzilla.mozilla.org/show_bug.cgi?id=1335594 // SEE: https://www.khronos.org/registry/webgl/specs/latest/1.0/#PIXEL_STORAGE_PARAMETERS // @ts-ignore createImageBitmap expects 1 or 5 parameters but now optionally supports 6 return createImageBitmap(data, sx, sy, sw, sh, options); } else { return createImageBitmap(data, sx, sy, sw, sh); } } else if (options !== undefined) { // NOTE: Firefox does not yet support passing options (at least as second parameter) to createImageBitmap and throws // SEE: https://bugzilla.mozilla.org/show_bug.cgi?id=1335594 // SEE: https://www.khronos.org/registry/webgl/specs/latest/1.0/#PIXEL_STORAGE_PARAMETERS // @ts-ignore createImageBitmap expects 1 or 5 parameters but now optionally supports 2 return createImageBitmap(data, options); } else { return createImageBitmap(data); } } else { return createImageBitmap(data); } } else { // In case something went wrong with loading the blob or corrupted data // Fallback to default image loader console.warn( 'AssetLoader -> Received no or corrupt data, falling back to default image loader' ); return this.loadImage(item); } }); } else { // Fallback to default image loader return this.loadImage(item); } }; /** * Load an item and parse the Response as compressed image (KTX container) * * @param item Item to load */ private loadImageCompressed = ( item: ILoadItem ): Promise< TUndefinable<{ baseInternalFormat: GLenum; height: number; internalFormat: GLenum; isCompressed: boolean; isCubemap: boolean; mipmapCount: number; mipmaps: any; width: number; }> > => this.loadArrayBuffer(item).then(data => { if (data) { // Switch endianness of value const switchEndianness = (value: number): number => ((value & 0xff) << 24) | ((value & 0xff00) << 8) | ((value >> 8) & 0xff00) | ((value >> 24) & 0xff); // Test that it is a ktx formatted file, based on the first 12 bytes: // '´', 'K', 'T', 'X', ' ', '1', '1', 'ª', '\r', '\n', '\x1A', '\n' // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A const identifier = new Uint8Array(data, 0, 12); assert( identifier[0] === 0xab && identifier[1] === 0x4b && identifier[2] === 0x54 && identifier[3] === 0x58 && identifier[4] === 0x20 && identifier[5] === 0x31 && identifier[6] === 0x31 && identifier[7] === 0xbb && identifier[8] === 0x0d && identifier[9] === 0x0a && identifier[10] === 0x1a && identifier[11] === 0x0a, 'AssetLoader -> Texture missing KTX identifier, currently only supporting KTX containers' ); // Load the rest of the header in 32 bit int const header = new Int32Array(data, 12, 13); // Determine of the remaining header values are recorded // in the opposite endianness and require conversion const isBigEndian = header[0] === 0x01020304; // Must be 0 for compressed textures const glType = isBigEndian ? switchEndianness(header[1]) : header[1]; // Must be 1 for compressed textures // const glTypeSize = isBigEndian ? switchEndianness(header[2]) : header[2]; // Must be 0 for compressed textures // const glFormat = isBigEndian ? switchEndianness(header[3]) : header[3]; // The value to be passed to gl.compressedTexImage2D(,,x,,,,) const glInternalFormat = isBigEndian ? switchEndianness(header[4]) : header[4]; // Specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only) const glBaseInternalFormat = isBigEndian ? switchEndianness(header[5]) : header[5]; // Level 0 value to be passed to gl.compressedTexImage2D(,,,x,,,) const pixelWidth = isBigEndian ? switchEndianness(header[6]) : header[6]; // Level 0 value to be passed to gl.compressedTexImage2D(,,,,x,,) const pixelHeight = isBigEndian ? switchEndianness(header[7]) : header[7]; // Level 0 value to be passed to gl.compressedTexImage3D(,,,,,x,,) const pixelDepth = isBigEndian ? switchEndianness(header[8]) : header[8]; // Used for texture arrays const numberOfArrayElements = isBigEndian ? switchEndianness(header[9]) : header[9]; // Used for cubemap textures, should either be 1 or 6 const numberOfFaces = isBigEndian ? switchEndianness(header[10]) : header[10]; // Number of levels; disregard possibility of 0 for compressed textures let numberOfMipmapLevels = isBigEndian ? switchEndianness(header[11]) : header[11]; // The amount of space after the header for meta-data const bytesOfKeyValueData = isBigEndian ? switchEndianness(header[12]) : header[12]; // Value of zero is an indication to generate mipmaps at runtime. // Not usually allowed for compressed, so disregard. numberOfMipmapLevels = Math.max(1, numberOfMipmapLevels); // Check for 2D texture assert( pixelHeight !== 0 && pixelDepth === 0, 'AssetLoader -> Only 2D textures currently supported' ); // Check for texture arrays, currently not supported assert( numberOfArrayElements === 0, 'AssetLoader -> Texture arrays not currently supported' ); const mipmaps = []; // Identifier + header elements (not including key value meta-data pairs) let dataOffset = 64 + bytesOfKeyValueData; let width = pixelWidth; let height = pixelHeight; const mipmapCount = numberOfMipmapLevels || 1; for (let level = 0; level < mipmapCount; level++) { // Size per face, since not supporting array cubemaps const imageSize = new Int32Array(data, dataOffset, 1)[0]; // Image data starts from next multiple of 4 offset // Each face refers to same imagesize field above dataOffset += 4; for (let face = 0; face < numberOfFaces; face++) { const byteArray = new Uint8Array(data, dataOffset, imageSize); mipmaps.push({ data: byteArray, height, width, }); // Add size of the image for the next face & mipmap dataOffset += imageSize; // Add padding for odd sized image dataOffset += 3 - ((imageSize + 3) % 4); } width = Math.max(1.0, width * 0.5); height = Math.max(1.0, height * 0.5); } return { baseInternalFormat: glBaseInternalFormat, height: pixelHeight, internalFormat: glInternalFormat, isCompressed: !glType, isCubemap: numberOfFaces === 6, mipmapCount: numberOfMipmapLevels, mipmaps, width: pixelWidth, }; } }); /** * Load an item and parse the Response as JSON * * @param item Item to load */ private loadJSON = (item: ILoadItem): Promise<JSON> => this.fetchItem(item) .then(response => response.json()) .catch(err => { console.error(err); }); /** * Load an item and parse the Response as plain text * * @param item Item to load */ private loadText = (item: ILoadItem): Promise<string | void> => this.fetchItem(item) .then(response => response.text()) .catch(err => { console.error(err); }); /** * Load an item and parse the Response as <video> element * * @param item Item to load */ private loadVideo = (item: ILoadItem): Promise<any> => this.fetchItem(item) .then(response => response.blob()) .then( blob => new Promise((resolve, reject): void => { const video = document.createElement('video'); if (item.loaderOptions && item.loaderOptions.crossOrigin) { video.crossOrigin = 'anonymous'; } video.preload = 'auto'; video.autoplay = false; // @ts-ignore playsInline is not recognized as a valid type but it is valid syntax video.playsInline = true; if (IS_MEDIA_PRELOAD_SUPPORTED) { video.addEventListener('canplaythrough', function handler(): void { video.removeEventListener('canplaythrough', handler); URL.revokeObjectURL(video.src); resolve(video); }); video.addEventListener('error', function handler(): void { video.removeEventListener('error', handler); URL.revokeObjectURL(video.src); reject(video); }); } video.src = URL.createObjectURL(blob); if (!IS_MEDIA_PRELOAD_SUPPORTED) { // Force the audio to load but resolve immediately as `canplaythrough` event will never be fired video.load(); resolve(video); } }) ) .catch(err => { console.error(err); }); /** * Load an item and parse the Response as ArrayBuffer (ready to instantiate) * * @param item Item to load */ private loadWebAssembly = (item: ILoadItem): Promise<TVoidable<WebAssembly.Instance>> => { if (isWebAssemblySupported) { if ((window as any).WebAssembly.instantiateStreaming) { return (window as any).WebAssembly.instantiateStreaming( this.fetchItem(item), item.loaderOptions.importObject ); } else { return this.fetchItem(item) .then(response => response.arrayBuffer()) .then(data => (window as any).WebAssembly.instantiate(data, item.loaderOptions.importObject) ) .catch(err => { console.error(err); }); } } else { console.warn('AssetLoader -> WebAssembly is not supported'); return Promise.resolve(); } }; /** * Load an item and parse the Response as XML * * @param item Item to load */ private loadXML = (item: ILoadItem): Promise<any> => { if (!item.mimeType) { const extension: string = this.getFileExtension(item.src); item = { ...item, mimeType: this.getMimeType(ELoaderKey.XML, extension) as SupportedType, }; } return this.fetchItem(item) .then(response => response.text()) .then(data => { if (item.mimeType) { return this.domParser.parseFromString(data, item.mimeType); } }) .catch(err => { console.error(err); }); }; }
the_stack
import parseImport, { ImportDeclaration } from 'parse-import-es6'; import * as vscode from 'vscode'; import strip from 'parse-comment-es6'; import { isIndexFile, isWin, getImportOption } from './help'; import ImportStatement, { EditChange } from './importStatement'; import JsImport from './jsImport'; import { ImportObj } from './rootScanner'; import { Uri } from 'vscode'; const path = require('path'); var open = require("open"); function getImportDeclaration(importedDefaultBinding, nameSpaceImport, namedImports, importPath: string, position: vscode.Position): ImportDeclaration { return { importedDefaultBinding, namedImports, nameSpaceImport, loc: { start: { line: position.line, column: position.character, }, end: { line: position.line, column: position.character, }, }, range: null, raw: '', middleComments: [], leadComments: [], trailingComments: [], moduleSpecifier: importPath, error: 0, } } export default class ImportFixer { eol: string; doc: vscode.TextDocument; importObj: ImportObj; range: vscode.Range; options; constructor(importObj: ImportObj, doc: vscode.TextDocument, range: vscode.Range, options) { this.importObj = importObj; this.doc = doc; this.range = range; if (doc != null) { this.eol = doc.eol === vscode.EndOfLine.LF ? '\n' : '\r\n'; } this.options = options; } public fix() { try { let importPath; if (this.importObj.isNodeModule) { importPath = this.extractImportPathFromNodeModules(this.importObj); } else { importPath = this.extractImportPathFromAlias(this.importObj, this.doc.uri.fsPath); if (importPath === null) { importPath = this.extractImportFromRoot(this.importObj, this.doc.uri.fsPath); } } this.resolveImport(importPath); } catch (error) { JsImport.consoleError(error); let body = ''; body = this.doc.getText() + '\n\n'; if (error && error.stack) { body += error.stack; } open('https://github.com/wangtao0101/vscode-js-import/issues/new?title=new&body=' + encodeURIComponent(body)); } } public extractImportPathFromNodeModules(importObj: ImportObj) { return importObj.path; } public extractImportPathFromAlias(importObj: ImportObj, fsPath: string) { let aliasMatch = null; let aliasKey = null; const uri = Uri.file(fsPath); const rootPath = vscode.workspace.getWorkspaceFolder(uri).uri.fsPath; /** * pick up the first alias, currently not support nested alias */ const alias = this.options.alias; for (const key of Object.keys(alias)) { if (importObj.path.startsWith(path.join(rootPath, alias[key]))) { aliasMatch = alias[key]; aliasKey = key; } } let importPath = null; if (aliasMatch !== null) { const filename = path.basename(importObj.path); /** * absolute path of current alias module */ const aliasPath = path.join(rootPath, aliasMatch); if (fsPath.startsWith(aliasPath)) { /** * use relative path if doc.uri is in aliasPath */ return this.extractImportFromRoot(importObj, fsPath); } let relativePath = path.relative(aliasPath, path.dirname(importObj.path)); if (isWin()) { relativePath = relativePath.replace(/\\/g, '/'); } if (!importObj.module.isPlainFile && isIndexFile(filename)) { importPath = relativePath === '' ? aliasKey : `${aliasKey}/${relativePath}` } else { const parsePath = path.parse(importObj.path); const filename = importObj.module.isPlainFile ? parsePath.base : parsePath.name; importPath = relativePath === '' ? `${aliasKey}/${filename}` : `${aliasKey}/${relativePath}/${filename}` } } return importPath; } public extractImportFromRoot(importObj: ImportObj, filePath: string) { const rootPath = vscode.workspace.getWorkspaceFolder(Uri.file(filePath)); let importPath = path.relative(filePath, importObj.path); const parsePath = path.parse(importPath); /** * normalize dir */ let dir = parsePath.dir; if (isWin()) { dir = dir.replace(/\\/g, '/'); } dir = dir.replace(/../, '.'); if (dir.startsWith('./..')) { dir = dir.substr(2, dir.length - 2); } if (!importObj.module.isPlainFile && isIndexFile(parsePath.base)) { importPath = `${dir}` } else { const name = importObj.module.isPlainFile ? parsePath.base : parsePath.name; importPath = `${dir}/${name}`; } return importPath; } public resolveImport(importPath) { const imports = parseImport(this.doc.getText()); // TODO: here we can normalize moduleSpecifier const filteredImports = imports.filter(imp => imp.error === 0 && imp.moduleSpecifier === importPath); let importStatement: ImportStatement = null; if (filteredImports.length === 0) { const position = this.getNewImportPositoin(imports); // TODO: skip name === 'name as cc' if (this.importObj.module.isNotMember) { importStatement = new ImportStatement( getImportDeclaration(null, null, [], importPath, position), getImportOption(this.eol, true, this.options), ); } else if (this.importObj.module.default) { importStatement = new ImportStatement( getImportDeclaration(this.importObj.module.name, null, [], importPath, position), getImportOption(this.eol, true, this.options), ); } else { importStatement = new ImportStatement( getImportDeclaration(null, null, [this.importObj.module.name], importPath, position), getImportOption(this.eol, true, this.options), ); } } else { // TODO: merge import const imp = filteredImports[0]; if (this.importObj.module.isNotMember) { return; } if (this.importObj.module.default) { if (imp.importedDefaultBinding !== null && imp.importedDefaultBinding === this.importObj.module.name) { // TODO: we can format code return; } else if (imp.importedDefaultBinding !== null && imp.importedDefaultBinding !== this.importObj.module.name) { // error , two default import return; } else { // imp.importedDefaultBinding === null importStatement = new ImportStatement( Object.assign(imp, { importedDefaultBinding: this.importObj.module.name }), getImportOption(this.eol, false, this.options), ); } } else { if (imp.nameSpaceImport !== null) { // error return; } if (imp.namedImports.includes(this.importObj.module.name)) { // TODO: we can format code return; } importStatement = new ImportStatement( Object.assign(imp, { namedImports: imp.namedImports.concat([this.importObj.module.name]) }), getImportOption(this.eol, false, this.options), ); } } const iec: EditChange = importStatement.getEditChange(); let edit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit(); edit.replace(this.doc.uri, new vscode.Range(iec.startLine, iec.startColumn, iec.endLine, iec.endColumn), iec.text); vscode.workspace.applyEdit(edit); } public getNewImportPositoin(imports) { let position: vscode.Position = null; let pos = this.options.insertPosition; if (pos !== 'first' && pos !== 'last') { pos = 'last' } if (pos === 'last' && imports.length !== 0) { const imp = imports[imports.length - 1]; if (imp.trailingComments.length === 0) { position = new vscode.Position(imp.loc.end.line + 1, 0); } else { position = new vscode.Position(imp.trailingComments[imp.trailingComments.length - 1].loc.end.line + 1, 0); } } if (imports.length === 0) { const comments = strip(this.doc.getText(), { comment: true, range: true, loc: true, raw: true }).comments; if (comments.length === 0) { position = new vscode.Position(0, 0); } else { // exculde the first leading comment of the first import, if exist 'flow' 'Copyright' 'LICENSE' const ignoreComment = /@flow|license|copyright/i; let index = 0; let comment; for (; index < comments.length; index += 1) { comment = comments[index]; if (!ignoreComment.test(comments[index].raw)) { break; } } if (index === comments.length) { position = new vscode.Position(comment.loc.end.line + 1, 0); } else { if (index === 0) { position = new vscode.Position(0, 0); } else { comment = comments[index - 1]; position = new vscode.Position(comment.loc.end.line + 1, 0); } } } } return position; } } // TODO: sort all import statement by eslint rules
the_stack
import { ShapeType } from "../collision/Shape"; import common from '../util/common'; import Math from '../common/Math'; import Vec2 from '../common/Vec2'; import Transform from '../common/Transform'; import Mat22 from '../common/Mat22'; import Rot from '../common/Rot'; import Settings from '../Settings'; import Manifold, { ManifoldType, WorldManifold } from '../collision/Manifold'; import { testOverlap } from '../collision/Distance'; import Fixture from "./Fixture"; import Body from "./Body"; import { ContactImpulse, TimeStep } from "./Solver"; const _ASSERT = typeof ASSERT === 'undefined' ? false : ASSERT; const DEBUG_SOLVER = false; /** * A contact edge is used to connect bodies and contacts together in a contact * graph where each body is a node and each contact is an edge. A contact edge * belongs to a doubly linked list maintained in each attached body. Each * contact has two contact nodes, one for each attached body. * * @prop {Contact} contact The contact * @prop {ContactEdge} prev The previous contact edge in the body's contact list * @prop {ContactEdge} next The next contact edge in the body's contact list * @prop {Body} other Provides quick access to the other body attached. */ export class ContactEdge { contact: Contact; prev: ContactEdge | undefined; next: ContactEdge | undefined; other: Body | undefined; constructor(contact: Contact) { this.contact = contact; } } export type EvaluateFunction = ( manifold: Manifold, xfA: Transform, fixtureA: Fixture, indexA: number, xfB: Transform, fixtureB: Fixture, indexB: number ) => void; export type ContactCallback = ( manifold: Manifold, xfA: Transform, fixtureA: Fixture, indexA: number, xfB: Transform, fixtureB: Fixture, indexB: number ) => void /* & { destroyFcn?: (contact: Contact) => void }*/; /** * Friction mixing law. The idea is to allow either fixture to drive the * restitution to zero. For example, anything slides on ice. */ export function mixFriction(friction1: number, friction2: number): number { return Math.sqrt(friction1 * friction2); } /** * Restitution mixing law. The idea is allow for anything to bounce off an * inelastic surface. For example, a superball bounces on anything. */ export function mixRestitution(restitution1: number, restitution2: number): number { return restitution1 > restitution2 ? restitution1 : restitution2; } // TODO: move this to Settings? const s_registers = []; // TODO: merge with ManifoldPoint? export class VelocityConstraintPoint { rA: Vec2 = Vec2.zero(); rB: Vec2 = Vec2.zero(); normalImpulse: number = 0; tangentImpulse: number = 0; normalMass: number = 0; tangentMass: number = 0; velocityBias: number = 0; } /** * The class manages contact between two shapes. A contact exists for each * overlapping AABB in the broad-phase (except if filtered). Therefore a contact * object may exist that has no contact points. */ export default class Contact { /** @internal */ m_nodeA: ContactEdge; /** @internal */ m_nodeB: ContactEdge; /** @internal */ m_fixtureA: Fixture; /** @internal */ m_fixtureB: Fixture; /** @internal */ m_indexA: number; /** @internal */ m_indexB: number; /** @internal */ m_evaluateFcn: EvaluateFunction; /** @internal */ m_manifold: Manifold = new Manifold(); /** @internal */ m_prev: Contact | null = null; /** @internal */ m_next: Contact | null = null; /** @internal */ m_toi: number = 1.0; /** @internal */ m_toiCount: number = 0; /** @internal This contact has a valid TOI in m_toi */ m_toiFlag: boolean = false; /** @internal */ m_friction: number; /** @internal */ m_restitution: number; /** @internal */ m_tangentSpeed: number = 0.0; /** @internal This contact can be disabled (by user) */ m_enabledFlag: boolean = true; /** @internal Used when crawling contact graph when forming islands. */ m_islandFlag: boolean = false; /** @internal Set when the shapes are touching. */ m_touchingFlag: boolean = false; /** @internal This contact needs filtering because a fixture filter was changed. */ m_filterFlag: boolean = false; /** @internal This bullet contact had a TOI event */ m_bulletHitFlag: boolean = false; /** @internal Contact reporting impulse object cache */ m_impulse: ContactImpulse = new ContactImpulse(this); // VelocityConstraint /** @internal */ v_points: VelocityConstraintPoint[] = []; // [maxManifoldPoints]; /** @internal */ v_normal: Vec2 = Vec2.zero(); /** @internal */ v_normalMass: Mat22 = new Mat22(); /** @internal */ v_K: Mat22 = new Mat22(); /** @internal */ v_pointCount: number; /** @internal */ v_tangentSpeed: number | undefined; /** @internal */ v_friction: number | undefined; /** @internal */ v_restitution: number | undefined; /** @internal */ v_invMassA: number | undefined; /** @internal */ v_invMassB: number | undefined; /** @internal */ v_invIA: number | undefined; /** @internal */ v_invIB: number | undefined; // PositionConstraint /** @internal */ p_localPoints: Vec2[] = []; // [maxManifoldPoints]; /** @internal */ p_localNormal: Vec2 = Vec2.zero(); /** @internal */ p_localPoint: Vec2 = Vec2.zero(); /** @internal */ p_localCenterA: Vec2 = Vec2.zero(); /** @internal */ p_localCenterB: Vec2 = Vec2.zero(); /** @internal */ p_type: ManifoldType | undefined; /** @internal */ p_radiusA: number | undefined; /** @internal */ p_radiusB: number | undefined; /** @internal */ p_pointCount: number | undefined; /** @internal */ p_invMassA: number | undefined; /** @internal */ p_invMassB: number | undefined; /** @internal */ p_invIA: number | undefined; /** @internal */ p_invIB: number | undefined; constructor(fA: Fixture, indexA: number, fB: Fixture, indexB: number, evaluateFcn: EvaluateFunction) { // Nodes for connecting bodies. this.m_nodeA = new ContactEdge(this); this.m_nodeB = new ContactEdge(this); this.m_fixtureA = fA; this.m_fixtureB = fB; this.m_indexA = indexA; this.m_indexB = indexB; this.m_evaluateFcn = evaluateFcn; this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); } initConstraint(step: TimeStep): void { const fixtureA = this.m_fixtureA; const fixtureB = this.m_fixtureB; const shapeA = fixtureA.getShape(); const shapeB = fixtureB.getShape(); const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); const manifold = this.getManifold(); const pointCount = manifold.pointCount; _ASSERT && common.assert(pointCount > 0); this.v_invMassA = bodyA.m_invMass; this.v_invMassB = bodyB.m_invMass; this.v_invIA = bodyA.m_invI; this.v_invIB = bodyB.m_invI; this.v_friction = this.m_friction; this.v_restitution = this.m_restitution; this.v_tangentSpeed = this.m_tangentSpeed; this.v_pointCount = pointCount; this.v_K.setZero(); this.v_normalMass.setZero(); this.p_invMassA = bodyA.m_invMass; this.p_invMassB = bodyB.m_invMass; this.p_invIA = bodyA.m_invI; this.p_invIB = bodyB.m_invI; this.p_localCenterA = Vec2.clone(bodyA.m_sweep.localCenter); this.p_localCenterB = Vec2.clone(bodyB.m_sweep.localCenter); this.p_radiusA = shapeA.m_radius; this.p_radiusB = shapeB.m_radius; this.p_type = manifold.type; this.p_localNormal = Vec2.clone(manifold.localNormal); this.p_localPoint = Vec2.clone(manifold.localPoint); this.p_pointCount = pointCount; for (let j = 0; j < pointCount; ++j) { const cp = manifold.points[j]; const vcp = this.v_points[j] = new VelocityConstraintPoint(); if (step.warmStarting) { vcp.normalImpulse = step.dtRatio * cp.normalImpulse; vcp.tangentImpulse = step.dtRatio * cp.tangentImpulse; } else { vcp.normalImpulse = 0.0; vcp.tangentImpulse = 0.0; } vcp.rA.setZero(); vcp.rB.setZero(); vcp.normalMass = 0.0; vcp.tangentMass = 0.0; vcp.velocityBias = 0.0; this.p_localPoints[j] = Vec2.clone(cp.localPoint); } } /** * Get the contact manifold. Do not modify the manifold unless you understand * the internals of the library. */ getManifold(): Manifold { return this.m_manifold; } /** * Get the world manifold. */ getWorldManifold(worldManifold: WorldManifold | null | undefined): WorldManifold | undefined { const bodyA = this.m_fixtureA.getBody(); const bodyB = this.m_fixtureB.getBody(); const shapeA = this.m_fixtureA.getShape(); const shapeB = this.m_fixtureB.getShape(); return this.m_manifold.getWorldManifold(worldManifold, bodyA.getTransform(), shapeA.m_radius, bodyB.getTransform(), shapeB.m_radius); } /** * Enable/disable this contact. This can be used inside the pre-solve contact * listener. The contact is only disabled for the current time step (or sub-step * in continuous collisions). */ setEnabled(flag: boolean): void { this.m_enabledFlag = !!flag; } /** * Has this contact been disabled? */ isEnabled(): boolean { return this.m_enabledFlag; } /** * Is this contact touching? */ isTouching(): boolean { return this.m_touchingFlag; } /** * Get the next contact in the world's contact list. */ getNext(): Contact | null { return this.m_next; } /** * Get fixture A in this contact. */ getFixtureA(): Fixture { return this.m_fixtureA; } /** * Get fixture B in this contact. */ getFixtureB(): Fixture { return this.m_fixtureB; } /** * Get the child primitive index for fixture A. */ getChildIndexA(): number { return this.m_indexA; } /** * Get the child primitive index for fixture B. */ getChildIndexB(): number { return this.m_indexB; } /** * Flag this contact for filtering. Filtering will occur the next time step. */ flagForFiltering(): void { this.m_filterFlag = true; } /** * Override the default friction mixture. You can call this in * ContactListener.preSolve. This value persists until set or reset. */ setFriction(friction: number): void { this.m_friction = friction; } /** * Get the friction. */ getFriction(): number { return this.m_friction; } /** * Reset the friction mixture to the default value. */ resetFriction(): void { this.m_friction = mixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction); } /** * Override the default restitution mixture. You can call this in * ContactListener.preSolve. The value persists until you set or reset. */ setRestitution(restitution: number): void { this.m_restitution = restitution; } /** * Get the restitution. */ getRestitution(): number { return this.m_restitution; } /** * Reset the restitution to the default value. */ resetRestitution(): void { this.m_restitution = mixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution); } /** * Set the desired tangent speed for a conveyor belt behavior. In meters per * second. */ setTangentSpeed(speed: number): void { this.m_tangentSpeed = speed; } /** * Get the desired tangent speed. In meters per second. */ getTangentSpeed(): number { return this.m_tangentSpeed; } /** * Called by Update method, and implemented by subclasses. */ evaluate(manifold: Manifold, xfA: Transform, xfB: Transform): void { this.m_evaluateFcn(manifold, xfA, this.m_fixtureA, this.m_indexA, xfB, this.m_fixtureB, this.m_indexB); } /** * Updates the contact manifold and touching status. * * Note: do not assume the fixture AABBs are overlapping or are valid. * * @param listener.beginContact * @param listener.endContact * @param listener.preSolve */ update(listener?: { beginContact(contact: Contact): void, endContact(contact: Contact): void, preSolve(contact: Contact, oldManifold: Manifold): void }): void { // Re-enable this contact. this.m_enabledFlag = true; let touching = false; const wasTouching = this.m_touchingFlag; const sensorA = this.m_fixtureA.isSensor(); const sensorB = this.m_fixtureB.isSensor(); const sensor = sensorA || sensorB; const bodyA = this.m_fixtureA.getBody(); const bodyB = this.m_fixtureB.getBody(); const xfA = bodyA.getTransform(); const xfB = bodyB.getTransform(); let oldManifold; // Is this contact a sensor? if (sensor) { const shapeA = this.m_fixtureA.getShape(); const shapeB = this.m_fixtureB.getShape(); touching = testOverlap(shapeA, this.m_indexA, shapeB, this.m_indexB, xfA, xfB); // Sensors don't generate manifolds. this.m_manifold.pointCount = 0; } else { // TODO reuse manifold oldManifold = this.m_manifold; this.m_manifold = new Manifold(); this.evaluate(this.m_manifold, xfA, xfB); touching = this.m_manifold.pointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (let i = 0; i < this.m_manifold.pointCount; ++i) { const nmp = this.m_manifold.points[i]; nmp.normalImpulse = 0.0; nmp.tangentImpulse = 0.0; for (let j = 0; j < oldManifold.pointCount; ++j) { const omp = oldManifold.points[j]; if (omp.id.key == nmp.id.key) { nmp.normalImpulse = omp.normalImpulse; nmp.tangentImpulse = omp.tangentImpulse; break; } } } if (touching != wasTouching) { bodyA.setAwake(true); bodyB.setAwake(true); } } this.m_touchingFlag = touching; if (!wasTouching && touching && listener) { listener.beginContact(this); } if (wasTouching && !touching && listener) { listener.endContact(this); } if (!sensor && touching && listener) { listener.preSolve(this, oldManifold); } } solvePositionConstraint(step: TimeStep): number { return this._solvePositionConstraint(step); } solvePositionConstraintTOI(step: TimeStep, toiA: Body, toiB: Body): number { return this._solvePositionConstraint(step, toiA, toiB); } private _solvePositionConstraint(step: TimeStep, toiA?: Body, toiB?: Body): number { const toi: boolean = !!toiA && !!toiB; const fixtureA = this.m_fixtureA; const fixtureB = this.m_fixtureB; const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); const velocityA = bodyA.c_velocity; const velocityB = bodyB.c_velocity; const positionA = bodyA.c_position; const positionB = bodyB.c_position; const localCenterA = Vec2.clone(this.p_localCenterA); const localCenterB = Vec2.clone(this.p_localCenterB); let mA = 0.0; let iA = 0.0; if (!toi || (bodyA == toiA || bodyA == toiB)) { mA = this.p_invMassA; iA = this.p_invIA; } let mB = 0.0; let iB = 0.0; if (!toi || (bodyB == toiA || bodyB == toiB)) { mB = this.p_invMassB; iB = this.p_invIB; } const cA = Vec2.clone(positionA.c); let aA = positionA.a; const cB = Vec2.clone(positionB.c); let aB = positionB.a; let minSeparation = 0.0; // Solve normal constraints for (let j = 0; j < this.p_pointCount; ++j) { const xfA = Transform.identity(); const xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p = Vec2.sub(cA, Rot.mulVec2(xfA.q, localCenterA)); xfB.p = Vec2.sub(cB, Rot.mulVec2(xfB.q, localCenterB)); // PositionSolverManifold let normal; let point; let separation; switch (this.p_type) { case ManifoldType.e_circles: { const pointA = Transform.mulVec2(xfA, this.p_localPoint); const pointB = Transform.mulVec2(xfB, this.p_localPoints[0]); normal = Vec2.sub(pointB, pointA); normal.normalize(); point = Vec2.combine(0.5, pointA, 0.5, pointB); separation = Vec2.dot(Vec2.sub(pointB, pointA), normal) - this.p_radiusA - this.p_radiusB; break; } case ManifoldType.e_faceA: { normal = Rot.mulVec2(xfA.q, this.p_localNormal); const planePoint = Transform.mulVec2(xfA, this.p_localPoint); const clipPoint = Transform.mulVec2(xfB, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; break; } case ManifoldType.e_faceB: { normal = Rot.mulVec2(xfB.q, this.p_localNormal); const planePoint = Transform.mulVec2(xfB, this.p_localPoint); const clipPoint = Transform.mulVec2(xfA, this.p_localPoints[j]); separation = Vec2.dot(Vec2.sub(clipPoint, planePoint), normal) - this.p_radiusA - this.p_radiusB; point = clipPoint; // Ensure normal points from A to B normal.mul(-1); break; } } const rA = Vec2.sub(point, cA); const rB = Vec2.sub(point, cB); // Track max constraint error. minSeparation = Math.min(minSeparation, separation); const baumgarte = toi ? Settings.toiBaugarte : Settings.baumgarte; const linearSlop = Settings.linearSlop; const maxLinearCorrection = Settings.maxLinearCorrection; // Prevent large corrections and allow slop. const C = Math.clamp(baumgarte * (separation + linearSlop), -maxLinearCorrection, 0.0); // Compute the effective mass. const rnA = Vec2.cross(rA, normal); const rnB = Vec2.cross(rB, normal); const K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; // Compute normal impulse const impulse = K > 0.0 ? -C / K : 0.0; const P = Vec2.mul(impulse, normal); cA.subMul(mA, P); aA -= iA * Vec2.cross(rA, P); cB.addMul(mB, P); aB += iB * Vec2.cross(rB, P); } positionA.c.set(cA); positionA.a = aA; positionB.c.set(cB); positionB.a = aB; return minSeparation; } initVelocityConstraint(step: TimeStep): void { const fixtureA = this.m_fixtureA; const fixtureB = this.m_fixtureB; const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); const velocityA = bodyA.c_velocity; const velocityB = bodyB.c_velocity; const positionA = bodyA.c_position; const positionB = bodyB.c_position; const radiusA = this.p_radiusA; const radiusB = this.p_radiusB; const manifold = this.getManifold(); const mA = this.v_invMassA; const mB = this.v_invMassB; const iA = this.v_invIA; const iB = this.v_invIB; const localCenterA = Vec2.clone(this.p_localCenterA); const localCenterB = Vec2.clone(this.p_localCenterB); const cA = Vec2.clone(positionA.c); const aA = positionA.a; const vA = Vec2.clone(velocityA.v); const wA = velocityA.w; const cB = Vec2.clone(positionB.c); const aB = positionB.a; const vB = Vec2.clone(velocityB.v); const wB = velocityB.w; _ASSERT && common.assert(manifold.pointCount > 0); const xfA = Transform.identity(); const xfB = Transform.identity(); xfA.q.set(aA); xfB.q.set(aB); xfA.p.setCombine(1, cA, -1, Rot.mulVec2(xfA.q, localCenterA)); xfB.p.setCombine(1, cB, -1, Rot.mulVec2(xfB.q, localCenterB)); const worldManifold = manifold.getWorldManifold(null, xfA, radiusA, xfB, radiusB); this.v_normal.set(worldManifold.normal); for (let j = 0; j < this.v_pointCount; ++j) { const vcp = this.v_points[j]; // VelocityConstraintPoint vcp.rA.set(Vec2.sub(worldManifold.points[j], cA)); vcp.rB.set(Vec2.sub(worldManifold.points[j], cB)); const rnA = Vec2.cross(vcp.rA, this.v_normal); const rnB = Vec2.cross(vcp.rB, this.v_normal); const kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; vcp.normalMass = kNormal > 0.0 ? 1.0 / kNormal : 0.0; const tangent = Vec2.cross(this.v_normal, 1.0); const rtA = Vec2.cross(vcp.rA, tangent); const rtB = Vec2.cross(vcp.rB, tangent); const kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; vcp.tangentMass = kTangent > 0.0 ? 1.0 / kTangent : 0.0; // Setup a velocity bias for restitution. vcp.velocityBias = 0.0; const vRel = Vec2.dot(this.v_normal, vB) + Vec2.dot(this.v_normal, Vec2.cross(wB, vcp.rB)) - Vec2.dot(this.v_normal, vA) - Vec2.dot(this.v_normal, Vec2.cross(wA, vcp.rA)); if (vRel < -Settings.velocityThreshold) { vcp.velocityBias = -this.v_restitution * vRel; } } // If we have two points, then prepare the block solver. if (this.v_pointCount == 2 && step.blockSolve) { const vcp1 = this.v_points[0]; // VelocityConstraintPoint const vcp2 = this.v_points[1]; // VelocityConstraintPoint const rn1A = Vec2.cross(vcp1.rA, this.v_normal); const rn1B = Vec2.cross(vcp1.rB, this.v_normal); const rn2A = Vec2.cross(vcp2.rA, this.v_normal); const rn2B = Vec2.cross(vcp2.rB, this.v_normal); const k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; const k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; const k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; // Ensure a reasonable condition number. const k_maxConditionNumber = 1000.0; if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) { // K is safe to invert. this.v_K.ex.set(k11, k12); this.v_K.ey.set(k12, k22); this.v_normalMass.set(this.v_K.getInverse()); } else { // The constraints are redundant, just use one. // TODO_ERIN use deepest? this.v_pointCount = 1; } } positionA.c.set(cA); positionA.a = aA; velocityA.v.set(vA); velocityA.w = wA; positionB.c.set(cB); positionB.a = aB; velocityB.v.set(vB); velocityB.w = wB; } warmStartConstraint(step: TimeStep): void { const fixtureA = this.m_fixtureA; const fixtureB = this.m_fixtureB; const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); const velocityA = bodyA.c_velocity; const velocityB = bodyB.c_velocity; const positionA = bodyA.c_position; const positionB = bodyB.c_position; const mA = this.v_invMassA; const iA = this.v_invIA; const mB = this.v_invMassB; const iB = this.v_invIB; const vA = Vec2.clone(velocityA.v); let wA = velocityA.w; const vB = Vec2.clone(velocityB.v); let wB = velocityB.w; const normal = this.v_normal; const tangent = Vec2.cross(normal, 1.0); for (let j = 0; j < this.v_pointCount; ++j) { const vcp = this.v_points[j]; // VelocityConstraintPoint const P = Vec2.combine(vcp.normalImpulse, normal, vcp.tangentImpulse, tangent); wA -= iA * Vec2.cross(vcp.rA, P); vA.subMul(mA, P); wB += iB * Vec2.cross(vcp.rB, P); vB.addMul(mB, P); } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; } storeConstraintImpulses(step: TimeStep): void { const manifold = this.m_manifold; for (let j = 0; j < this.v_pointCount; ++j) { manifold.points[j].normalImpulse = this.v_points[j].normalImpulse; manifold.points[j].tangentImpulse = this.v_points[j].tangentImpulse; } } solveVelocityConstraint(step: TimeStep): void { const bodyA = this.m_fixtureA.m_body; const bodyB = this.m_fixtureB.m_body; const velocityA = bodyA.c_velocity; const positionA = bodyA.c_position; const velocityB = bodyB.c_velocity; const positionB = bodyB.c_position; const mA = this.v_invMassA; const iA = this.v_invIA; const mB = this.v_invMassB; const iB = this.v_invIB; const vA = Vec2.clone(velocityA.v); let wA = velocityA.w; const vB = Vec2.clone(velocityB.v); let wB = velocityB.w; const normal = this.v_normal; const tangent = Vec2.cross(normal, 1.0); const friction = this.v_friction; _ASSERT && common.assert(this.v_pointCount == 1 || this.v_pointCount == 2); // Solve tangent constraints first because non-penetration is more important // than friction. for (let j = 0; j < this.v_pointCount; ++j) { const vcp = this.v_points[j]; // VelocityConstraintPoint // Relative velocity at contact const dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); // Compute tangent force const vt = Vec2.dot(dv, tangent) - this.v_tangentSpeed; let lambda = vcp.tangentMass * (-vt); // Clamp the accumulated force const maxFriction = friction * vcp.normalImpulse; const newImpulse = Math.clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction); lambda = newImpulse - vcp.tangentImpulse; vcp.tangentImpulse = newImpulse; // Apply contact impulse const P = Vec2.mul(lambda, tangent); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } // Solve normal constraints if (this.v_pointCount == 1 || step.blockSolve == false) { for (let i = 0; i < this.v_pointCount; ++i) { const vcp = this.v_points[i]; // VelocityConstraintPoint // Relative velocity at contact const dv = Vec2.zero(); dv.addCombine(1, vB, 1, Vec2.cross(wB, vcp.rB)); dv.subCombine(1, vA, 1, Vec2.cross(wA, vcp.rA)); // Compute normal impulse const vn = Vec2.dot(dv, normal); let lambda = -vcp.normalMass * (vn - vcp.velocityBias); // Clamp the accumulated impulse const newImpulse = Math.max(vcp.normalImpulse + lambda, 0.0); lambda = newImpulse - vcp.normalImpulse; vcp.normalImpulse = newImpulse; // Apply contact impulse const P = Vec2.mul(lambda, normal); vA.subMul(mA, P); wA -= iA * Vec2.cross(vcp.rA, P); vB.addMul(mB, P); wB += iB * Vec2.cross(vcp.rB, P); } } else { // Block solver developed in collaboration with Dirk Gregorius (back in // 01/07 on Box2D_Lite). // Build the mini LCP for this contact patch // // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = // 1..2 // // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) // b = vn0 - velocityBias // // The system is solved using the "Total enumeration method" (s. Murty). // The complementary constraint vn_i * x_i // implies that we must have in any solution either vn_i = 0 or x_i = 0. // So for the 2D contact problem the cases // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and // vn1 = 0 need to be tested. The first valid // solution that satisfies the problem is chosen. // // In order to account of the accumulated impulse 'a' (because of the // iterative nature of the solver which only requires // that the accumulated impulse is clamped and not the incremental // impulse) we change the impulse variable (x_i). // // Substitute: // // x = a + d // // a := old total impulse // x := new total impulse // d := incremental impulse // // For the current iteration we extend the formula for the incremental // impulse // to compute the new total impulse: // // vn = A * d + b // = A * (x - a) + b // = A * x + b - A * a // = A * x + b' // b' = b - A * a; const vcp1 = this.v_points[0]; // VelocityConstraintPoint const vcp2 = this.v_points[1]; // VelocityConstraintPoint const a = Vec2.neo(vcp1.normalImpulse, vcp2.normalImpulse); _ASSERT && common.assert(a.x >= 0.0 && a.y >= 0.0); // Relative velocity at contact let dv1 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp1.rB)).sub(vA).sub(Vec2.cross(wA, vcp1.rA)); let dv2 = Vec2.zero().add(vB).add(Vec2.cross(wB, vcp2.rB)).sub(vA).sub(Vec2.cross(wA, vcp2.rA)); // Compute normal velocity let vn1 = Vec2.dot(dv1, normal); let vn2 = Vec2.dot(dv2, normal); const b = Vec2.neo(vn1 - vcp1.velocityBias, vn2 - vcp2.velocityBias); // Compute b' b.sub(Mat22.mulVec2(this.v_K, a)); const k_errorTol = 1e-3; // NOT_USED(k_errorTol); while (true) { // // Case 1: vn = 0 // // 0 = A * x + b' // // Solve for x: // // x = - inv(A) * b' // const x = Mat22.mulVec2(this.v_normalMass, b).neg(); if (x.x >= 0.0 && x.y >= 0.0) { // Get the incremental impulse const d = Vec2.sub(x, a); // Apply incremental impulse const P1 = Vec2.mul(d.x, normal); const P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions dv1 = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, vcp1.rB)), Vec2.add(vA, Vec2.cross(wA, vcp1.rA))); dv2 = Vec2.sub(Vec2.add(vB, Vec2.cross(wB, vcp2.rB)), Vec2.add(vA, Vec2.cross(wA, vcp2.rA))); // Compute normal velocity vn1 = Vec2.dot(dv1, normal); vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } // // Case 2: vn1 = 0 and x2 = 0 // // 0 = a11 * x1 + a12 * 0 + b1' // vn2 = a21 * x1 + a22 * 0 + b2' // x.x = -vcp1.normalMass * b.x; x.y = 0.0; vn1 = 0.0; vn2 = this.v_K.ex.y * x.x + b.y; if (x.x >= 0.0 && vn2 >= 0.0) { // Get the incremental impulse const d = Vec2.sub(x, a); // Apply incremental impulse const P1 = Vec2.mul(d.x, normal); const P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions const dv1B = Vec2.add(vB, Vec2.cross(wB, vcp1.rB)); const dv1A = Vec2.add(vA, Vec2.cross(wA, vcp1.rA)); const dv1 = Vec2.sub(dv1B, dv1A); // Compute normal velocity vn1 = Vec2.dot(dv1, normal); _ASSERT && common.assert(Math.abs(vn1 - vcp1.velocityBias) < k_errorTol); } break; } // // Case 3: vn2 = 0 and x1 = 0 // // vn1 = a11 * 0 + a12 * x2 + b1' // 0 = a21 * 0 + a22 * x2 + b2' // x.x = 0.0; x.y = -vcp2.normalMass * b.y; vn1 = this.v_K.ey.x * x.y + b.x; vn2 = 0.0; if (x.y >= 0.0 && vn1 >= 0.0) { // Resubstitute for the incremental impulse const d = Vec2.sub(x, a); // Apply incremental impulse const P1 = Vec2.mul(d.x, normal); const P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; if (DEBUG_SOLVER) { // Postconditions const dv2B = Vec2.add(vB, Vec2.cross(wB, vcp2.rB)); const dv2A = Vec2.add(vA, Vec2.cross(wA, vcp2.rA)); const dv1 = Vec2.sub(dv2B, dv2A); // Compute normal velocity vn2 = Vec2.dot(dv2, normal); _ASSERT && common.assert(Math.abs(vn2 - vcp2.velocityBias) < k_errorTol); } break; } // // Case 4: x1 = 0 and x2 = 0 // // vn1 = b1 // vn2 = b2; // x.x = 0.0; x.y = 0.0; vn1 = b.x; vn2 = b.y; if (vn1 >= 0.0 && vn2 >= 0.0) { // Resubstitute for the incremental impulse const d = Vec2.sub(x, a); // Apply incremental impulse const P1 = Vec2.mul(d.x, normal); const P2 = Vec2.mul(d.y, normal); vA.subCombine(mA, P1, mA, P2); wA -= iA * (Vec2.cross(vcp1.rA, P1) + Vec2.cross(vcp2.rA, P2)); vB.addCombine(mB, P1, mB, P2); wB += iB * (Vec2.cross(vcp1.rB, P1) + Vec2.cross(vcp2.rB, P2)); // Accumulate vcp1.normalImpulse = x.x; vcp2.normalImpulse = x.y; break; } // No solution, give up. This is hit sometimes, but it doesn't seem to // matter. break; } } velocityA.v.set(vA); velocityA.w = wA; velocityB.v.set(vB); velocityB.w = wB; } /** * @internal */ static addType(type1: ShapeType, type2: ShapeType, callback: ContactCallback): void { s_registers[type1] = s_registers[type1] || {}; s_registers[type1][type2] = callback; } /** * @internal */ static create(fixtureA: Fixture, indexA: number, fixtureB: Fixture, indexB: number): Contact | null { const typeA = fixtureA.getType(); const typeB = fixtureB.getType(); // TODO: pool contacts let contact; let evaluateFcn; if (evaluateFcn = s_registers[typeA] && s_registers[typeA][typeB]) { contact = new Contact(fixtureA, indexA, fixtureB, indexB, evaluateFcn); } else if (evaluateFcn = s_registers[typeB] && s_registers[typeB][typeA]) { contact = new Contact(fixtureB, indexB, fixtureA, indexA, evaluateFcn); } else { return null; } // Contact creation may swap fixtures. fixtureA = contact.getFixtureA(); fixtureB = contact.getFixtureB(); indexA = contact.getChildIndexA(); indexB = contact.getChildIndexB(); const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); // Connect to body A contact.m_nodeA.contact = contact; contact.m_nodeA.other = bodyB; contact.m_nodeA.prev = null; contact.m_nodeA.next = bodyA.m_contactList; if (bodyA.m_contactList != null) { bodyA.m_contactList.prev = contact.m_nodeA; } bodyA.m_contactList = contact.m_nodeA; // Connect to body B contact.m_nodeB.contact = contact; contact.m_nodeB.other = bodyA; contact.m_nodeB.prev = null; contact.m_nodeB.next = bodyB.m_contactList; if (bodyB.m_contactList != null) { bodyB.m_contactList.prev = contact.m_nodeB; } bodyB.m_contactList = contact.m_nodeB; // Wake up the bodies if (fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } return contact; } /** * @internal */ static destroy(contact: Contact, listener: { endContact: (contact: Contact) => void }): void { const fixtureA = contact.m_fixtureA; const fixtureB = contact.m_fixtureB; const bodyA = fixtureA.getBody(); const bodyB = fixtureB.getBody(); if (contact.isTouching()) { listener.endContact(contact); } // Remove from body 1 if (contact.m_nodeA.prev) { contact.m_nodeA.prev.next = contact.m_nodeA.next; } if (contact.m_nodeA.next) { contact.m_nodeA.next.prev = contact.m_nodeA.prev; } if (contact.m_nodeA == bodyA.m_contactList) { bodyA.m_contactList = contact.m_nodeA.next; } // Remove from body 2 if (contact.m_nodeB.prev) { contact.m_nodeB.prev.next = contact.m_nodeB.next; } if (contact.m_nodeB.next) { contact.m_nodeB.next.prev = contact.m_nodeB.prev; } if (contact.m_nodeB == bodyB.m_contactList) { bodyB.m_contactList = contact.m_nodeB.next; } if (contact.m_manifold.pointCount > 0 && fixtureA.isSensor() == false && fixtureB.isSensor() == false) { bodyA.setAwake(true); bodyB.setAwake(true); } const typeA = fixtureA.getType(); const typeB = fixtureB.getType(); // const destroyFcn = s_registers[typeA][typeB].destroyFcn; // if (typeof destroyFcn === 'function') { // destroyFcn(contact); // } } }
the_stack
// tslint:disable: prefer-template max-func-body-length import * as assert from "assert"; import { areDecoupledChildAndParent, getResourcesInfo, IResourceInfo } from "../extension.bundle"; import { IDeploymentTemplateResource, IPartialDeploymentTemplate } from "./support/diagnostics"; import { parseTemplate } from "./support/parseTemplate"; import { testLog } from "./support/testLog"; suite("areDecoupledChildAndParent", () => { suite("areDecoupledChildAndParent", () => { function createChildParentTestFromArray( name: string, template: IPartialDeploymentTemplate, parentNameExpression: string, childNameExpression: string, expected: boolean, expectedReverse: boolean ): void { test(`${name ? name + ':' : ''}child=${childNameExpression}, parent=${parentNameExpression}`, async () => { const dt = parseTemplate(template, []); const infos = getResourcesInfo({ scope: dt.topLevelScope, recognizeDecoupledChildren: false }); testLog.writeLine(`Resource Infos found:\n` + infos.map(i => `${i.getFullNameExpression()} (${i.getFullTypeExpression()})`).join('\n')); const child = infos.find(i => i.getFullNameExpression() === childNameExpression); assert(!!child, `Could not find resource with full name "${childNameExpression}"`); const parent = infos.find(i => i.getFullNameExpression() === parentNameExpression); assert(!!parent, `Could not find resource with full name "${parentNameExpression}"`); testAreDecoupledChildAndParent(child, parent, expected, expectedReverse); }); } function createChildParentTest( name: string, parent: Partial<IDeploymentTemplateResource>, child: Partial<IDeploymentTemplateResource>, expected: boolean, expectedReverse: boolean ): void { test(`${name ? name + ': ' : ''}child=${child.name}, parent=${parent.name}`, async () => { let keepNameInClosure = name; keepNameInClosure = keepNameInClosure; const template: IPartialDeploymentTemplate = { resources: [ child, parent ] }; const dt = parseTemplate(template); const infos = getResourcesInfo({ scope: dt.topLevelScope, recognizeDecoupledChildren: true }); testLog.writeLine(`Resource Infos found:\n` + infos.map(i => `${i.getFullNameExpression()} (${i.getFullTypeExpression()})`).join('\n')); testAreDecoupledChildAndParent(infos[0], infos[1], expected, expectedReverse); }); } function testAreDecoupledChildAndParent( child: IResourceInfo, parent: IResourceInfo, expected: boolean, expectedReverse?: boolean ): void { const result = areDecoupledChildAndParent(child, parent); const reverseResult = areDecoupledChildAndParent(parent, child); assert.strictEqual(result, expected, `areChildAndParent: expected ${expected} but received ${result}`); if (typeof expectedReverse === 'boolean') { assert.strictEqual(reverseResult, expectedReverse, `reversed areChildAndParent: expected ${expectedReverse} but received ${reverseResult}`); } } suite("false for self", () => { const template: IPartialDeploymentTemplate = { resources: [ { name: "self", type: "microsoft.abc/def" } ] }; createChildParentTestFromArray( "", template, `'self'`, `'self'`, false, false); }); suite("false for nested", () => { const template: IPartialDeploymentTemplate = { resources: [ { name: "parent", type: "microsoft.abc/def", resources: [ { name: "child", type: "ghi" } ] } ] }; createChildParentTestFromArray( "", template, `'parent'`, `'parent/child'`, false, false); }); suite("incorrect segment lenghs", () => { createChildParentTest( "incorrect name segments length - same", { name: "resource1", type: "microsoft.abc/def" }, { name: "resource2", type: "microsoft.abc/def/ghi" }, false, false); createChildParentTest( "incorrect name segments length -- too many", { name: "resource1", type: "microsoft.abc/def" }, { name: "resource1/resource2/resource3", type: "microsoft.abc/def/ghi" }, false, false); createChildParentTest( "incorrect type segments length - same", { name: "resource1", type: "microsoft.abc/def" }, { name: "resource1/resource2", type: "microsoft.abc/def" }, false, false); createChildParentTest( "incorrect type segments length - too many", { name: "resource1", type: "microsoft.abc/def" }, { name: "resource1/resource2", type: "microsoft.abc/def/ghi/jkl" }, false, false); }); suite("string literals, one level", () => { createChildParentTest( "match", { name: "resource1", type: "Microsoft.abc/def" }, { name: "resource1/resource2", type: "Microsoft.abc/def/ghi" }, true, false); createChildParentTest( "match case insensitive", { name: "resource1", type: "microsoft.abc/DEF" }, { name: "RESOURCE1/resource2", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "names don't match", { name: "resource1", type: "microsoft.abc/def" }, { name: "resource2/resource2", type: "microsoft.abc/def/ghi" }, false, false); createChildParentTest( "number of type segments doesn't match number of name segments", { name: "resource1", type: "microsoft.abc/def/ghi" }, { name: "resource1/resource2", type: "microsoft.abc/def/ghi/lmn" }, false, false); }); suite("string literals, two levels", () => { createChildParentTest( "match", { name: "resource1/RESOURCE2", type: "microsoft.abc/def/ghi" }, { name: "resource1/resource2/resource3", type: "microsoft.abc/def/ghi/jkl" }, true, false); }); suite("expressions", () => { suite("name expressions", () => { createChildParentTest( "name expr 1", { name: "resource1", type: "microsoft.abc/DEF" }, { name: "[concat('RESOURCE1', '/resource2')]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name expr 2", { name: "resource1", type: "microsoft.abc/DEF" }, { name: "[concat('RESOURCE1/', 'resource2')]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name expr 3", { name: "resource1", type: "microsoft.abc/DEF" }, { name: "[concat('RESOURCE1', '/', 'resource2')]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name expr 4", { name: "[variables('parent')]", type: "microsoft.abc/DEF" }, { name: "[concat(variables('parent'), '/', 'resource2')]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name expr 5", { name: "[variables('parent')]", type: "microsoft.abc/DEF" }, { name: "[concat(variables('parent'), '/', add(1, 2))]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name expr 6", { name: "parent", type: "microsoft.abc/DEF" }, { name: "[concat('parent/', add(1, 2))]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "match whitespace differs", { name: "[variables('parent')]", type: "microsoft.abc/DEF" }, { name: "[ concat(variables( 'parent'),'/',add( 1, 2) ) ]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "match case insensitive", { name: "[variables('PARENT')]", type: "microsoft.abc/DEF" }, { name: "[CONCAT(variables('parent'), '/', ADD(1, 2))]", type: "MICROSOFT.abc/def/ghi" }, true, false); createChildParentTest( "name exprs don't match", { name: "[variables('PARENT')]", type: "microsoft.abc/DEF" }, { name: "[CONCAT(variables('parent2'), '/', mul(1, 2))]", type: "MICROSOFT.abc/def/ghi" }, false, false); }); suite("type expressions", () => { createChildParentTest( "type expr 1", { type: "microsoft.abc/DEF", name: "resource1" }, { type: "[concat('MICROSOFT.abc/def', '/ghi')]", name: "resource1/resource2" }, true, false); createChildParentTest( "type expr 2", { type: "[variables('parent')]", name: "resource1" }, { type: "[concat(variables('parent'), '/', 'type2')]", name: "resource1/resource2" }, true, false); createChildParentTest( "type expr 2b - expression shouldn't match against a string literal", { type: "variables('parent')", name: "resource1" }, { type: "[concat(variables('parent'), '/', 'type2')]", name: "resource1/resource2" }, false, false); createChildParentTest( "type expr 3", { type: "[variables('parent')]", name: "name1" }, { type: "[concat(variables('parent'), '/', add(1, 2))]", name: "name1/ghi" }, true, false); createChildParentTest( "match whitespace differs", { type: "[variables('parent')]", name: "name1" }, { type: "[ concat(variables( 'parent'),'/',add( 1, 2) ) ]", name: "name1/name2" }, true, false); createChildParentTest( "match case insensitive", { type: "[variables('PARENT')]", name: "name1" }, { type: "[CONCAT(variables('parent'), '/', ADD(1, 2))]", name: "NAME1/name2" }, true, false); createChildParentTest( "type exprs don't match", { type: "[variables('PARENT')]", name: "name1" }, { type: "[CONCAT(variables('parent2'), '/', mul(1, 2))]", name: "name2" }, false, false); }); }); }); });
the_stack
import { FUNDING_RATE_MAX_ABS_VALUE, FUNDING_RATE_MAX_ABS_DIFF_PER_SECOND, INTEGERS, } from '../src/lib/Constants'; import { BaseValue, BigNumberable, FundingRate, Price, address, } from '../src/lib/types'; import { fastForward } from './helpers/EVM'; import { expect, expectAddressesEqual, expectBaseValueEqual, expectBaseValueNotEqual, expectThrow, } from './helpers/Expect'; import initializePerpetual from './helpers/initializePerpetual'; import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe'; const minUnit = INTEGERS.ONE.shiftedBy(-18); const oraclePrice = new Price(100); let admin: address; let fundingRateProvider: address; let rando: address; async function init(ctx: ITestContext): Promise<void> { await initializePerpetual(ctx); admin = ctx.accounts[0]; fundingRateProvider = ctx.accounts[1]; rando = ctx.accounts[2]; await ctx.perpetual.testing.oracle.setPrice(oraclePrice); } perpetualDescribe('P1FundingOracle', init, (ctx: ITestContext) => { describe('constants', () => { it('the bounds are set as expected', async () => { const bounds = await ctx.perpetual.fundingOracle.getBounds(); expectBaseValueEqual(bounds.maxAbsValue, FUNDING_RATE_MAX_ABS_VALUE); expectBaseValueEqual(bounds.maxAbsDiffPerSecond, FUNDING_RATE_MAX_ABS_DIFF_PER_SECOND); }); }); describe('setFundingRateProvider', () => { it('sets the funding rate provider', async () => { // Check that provider can't set the rate at first. await expectThrow( ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10')), 'The funding rate can only be set by the funding rate provider', ); // Set the provider. const txResult = await ctx.perpetual.fundingOracle.setFundingRateProvider( fundingRateProvider, { from: admin }, ); // Check that the provider can set the rate after. await ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10')); // Check getter. const providerAfter = await ctx.perpetual.fundingOracle.getFundingRateProvider(); expect(providerAfter).to.equal(fundingRateProvider); // Check logs. const logs = ctx.perpetual.logs.parseLogs(txResult); expect(logs.length).to.equal(1); const log = logs[0]; expect(log.name).to.equal('LogFundingRateProviderSet'); expectAddressesEqual(log.args.fundingRateProvider, fundingRateProvider); // Set another provider. await ctx.perpetual.fundingOracle.setFundingRateProvider( rando, { from: admin }, ); // Check that the provider can set the rate after. await ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10'), { from: rando }); }); it('fails if the caller is not the admin', async () => { // Call from a random address. await expectThrow( ctx.perpetual.fundingOracle.setFundingRateProvider(fundingRateProvider, { from: rando }), 'Ownable: caller is not the owner', ); // Set the provider as admin, and then call from the provider address. await ctx.perpetual.fundingOracle.setFundingRateProvider( fundingRateProvider, { from: admin }, ); await expectThrow( ctx.perpetual.fundingOracle.setFundingRateProvider( fundingRateProvider, { from: fundingRateProvider }, ), 'Ownable: caller is not the owner', ); }); }); describe('getFunding()', () => { it('initially returns zero', async () => { await expectFunding(1000, 0); }); it('gets funding as a function of time elapsed', async () => { // Set a funding rate. await ctx.perpetual.fundingOracle.setFundingRateProvider( fundingRateProvider, { from: admin }, ); await ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10')); // Check funding amount for different time periods. await expectFunding(1230, '1.23e-7'); await expectFunding(12300, '1.23e-6'); await expectFunding(123000, '1.23e-5'); }); }); describe('setFundingRate()', () => { beforeEach(async () => { await ctx.perpetual.fundingOracle.setFundingRateProvider( fundingRateProvider, { from: admin }, ); }); it('sets a positive funding rate', async () => { await setFundingRate(new FundingRate('1e-10')); await setFundingRate(new FundingRate('1e-15')); }); it('sets a negative funding rate', async () => { await setFundingRate(new FundingRate('-1e-10')); await setFundingRate(new FundingRate('-1e-15')); }); it('sets a very small or zero funding rate', async () => { await setFundingRate(new FundingRate('-1e-16')); await setFundingRate(new FundingRate('-1e-18')); await setFundingRate(new FundingRate(0)); }); it('fails if not called by the funding rate provider', async () => { await expectThrow( ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10'), { from: rando }), 'The funding rate can only be set by the funding rate provider', ); await expectThrow( ctx.perpetual.fundingOracle.setFundingRate(new FundingRate('1e-10'), { from: admin }), 'The funding rate can only be set by the funding rate provider', ); }); describe('funding rate bounds', () => { it('cannot exceed the max value', async () => { // Set to max value, while obeying the per-update speed limit. await setFundingRate(FUNDING_RATE_MAX_ABS_VALUE); // Try to set above max value. await setFundingRate( FUNDING_RATE_MAX_ABS_VALUE.plus(minUnit), { expectedRate: FUNDING_RATE_MAX_ABS_VALUE }, ); }); it('cannot exceed the min value', async () => { const minFundingRate = FUNDING_RATE_MAX_ABS_VALUE.negated(); // Set to min value, while obeying the per-update speed limit. await setFundingRate(minFundingRate); // Try to set below min value. await setFundingRate( minFundingRate.minus(minUnit), { expectedRate: minFundingRate }, ); }); it('cannot increase faster than the per second limit', async () => { const quarterHour = 60 * 15; const quarterHourMaxDiff = FUNDING_RATE_MAX_ABS_DIFF_PER_SECOND.times(quarterHour); const initialRate = FundingRate.fromEightHourRate('0.00123'); const targetRate = initialRate.plus(quarterHourMaxDiff.value); // Update the funding rate timestamp so we can more accurately estimate the // time elapsed between updates. await setFundingRate(initialRate); // Elapse less than a quarter hour. Assume this test case takes less than 15 seconds. await fastForward(quarterHour - 15); // Expect the bounded rate to be slightly lower than the requested rate. const boundedRate = await getBoundedFundingRate(targetRate); expectBaseValueNotEqual(boundedRate, targetRate); // Error should be at most (15 seconds) / (15 minutes) = 1 / 60. const actualDiff = boundedRate.minus(initialRate.value); const ratio = actualDiff.value.div(quarterHourMaxDiff.value).toNumber(); expect(ratio).to.be.lessThan(1); // sanity check expect(ratio).to.be.gte(59 / 60 - 0.0000000001); // Allow tolerance for rounding error. }); it('cannot decrease faster than the per second limit', async () => { const quarterHour = 60 * 15; const quarterHourMaxDiff = FUNDING_RATE_MAX_ABS_DIFF_PER_SECOND.times(quarterHour); const initialRate = FundingRate.fromEightHourRate('0.00123'); const targetRate = initialRate.minus(quarterHourMaxDiff.value); // Update the funding rate timestamp so we can more accurately estimate the // time elapsed between updates. await setFundingRate(initialRate); // Elapse less than a quarter hour. Assume this test case takes less than 15 seconds. await fastForward(quarterHour - 15); // Expect the bounded rate to be slightly greater than the requested rate. const boundedRate = await getBoundedFundingRate(targetRate); expectBaseValueNotEqual(boundedRate, targetRate); // Error should be at most (15 seconds) / (15 minutes) = 1 / 60. const actualDiff = boundedRate.minus(initialRate.value); const ratio = actualDiff.value.div(quarterHourMaxDiff.value).negated().toNumber(); expect(ratio).to.be.lessThan(1); // sanity check expect(ratio).to.be.gte(59 / 60 - 0.0000000001); // Allow tolerance for rounding error. }); }); }); async function expectFunding( timeDelta: BigNumberable, expectedFunding: BigNumberable, ): Promise<void> { const funding: BaseValue = await ctx.perpetual.fundingOracle.getFunding(timeDelta); expectBaseValueEqual(funding, new BaseValue(expectedFunding)); } /** * Get the bounded funding rate as the funding rate provider. */ async function getBoundedFundingRate(fundingRate: FundingRate): Promise<FundingRate> { return ctx.perpetual.fundingOracle.getBoundedFundingRate( fundingRate, { from: fundingRateProvider }, ); } /** * Set the funding rate and verify the emitted logs. */ async function setFundingRate( fundingRate: FundingRate, options: { from?: address, expectedRate?: FundingRate, } = {}, ): Promise<void> { // Elapse enough time so that the speed limit does not take effect. await fastForward(INTEGERS.ONE_HOUR_IN_SECONDS.toNumber()); // Verify the return value is as expected. const simulatedResult = await getBoundedFundingRate(fundingRate); const expectedRate = options.expectedRate || fundingRate; expectBaseValueEqual(simulatedResult, expectedRate, 'simulated result'); // Set the funding rate. const txResult = await ctx.perpetual.fundingOracle.setFundingRate( fundingRate, { from: options.from || fundingRateProvider }, ); // Check the actual rate as returned by getFunding(). const actualRate = await ctx.perpetual.fundingOracle.getFundingRate(); expectBaseValueEqual(actualRate, expectedRate, 'actual rate'); // Check logs. const logs = ctx.perpetual.logs.parseLogs(txResult); expect(logs.length, 'logs length').to.equal(1); expect(logs[0].name).to.equal('LogFundingRateUpdated'); expectBaseValueEqual( logs[0].args.fundingRate.baseValue, expectedRate, 'funding rate', ); } });
the_stack
import { BlockPortRegData, BlockRegData, } from "./BlockDef"; import { BlockPortDirection, BlockPort } from "./Port"; import { BlockRunner } from "../Runner/Runner"; import { EventHandler } from "../../utils/EventHandler"; import { BlockGraphDocunment } from "./BlockDocunment"; import { BlockEditor } from "../Editor/BlockEditor"; import logger from "../../utils/Logger"; import CommonUtils from "../../utils/CommonUtils"; import { Connector } from "./Connector"; import ParamTypeServiceInstance from "../../sevices/ParamTypeService"; import { BlockPortEditor } from "../Editor/BlockPortEditor"; import { BlockParameterSetType, BlockParameterType, cloneParameterTypeFromString, createParameterTypeFromString } from "./BlockParameterType"; import { CustomStorageObject } from "./CommonDefine"; import BlockServiceInstance from "@/sevices/BlockService"; import { BlockRunContextData } from "../Runner/BlockRunContextData"; /** * 基础单元定义 */ export class Block { /** * 单元的GUID */ public guid = "0"; /** * 单元的唯一ID */ public uid = "" /** * 自定义单元属性供代码使用(全局)(会保存至文件中) */ public options : CustomStorageObject = {}; /** * 自定义单元数据供代码使用(全局)(不会保存至文件中) */ public data : CustomStorageObject = {}; /** * 自定义单元变量供代码使用(单元局部)(不会保存至文件中) */ public variables(context ?: BlockRunContextData) : CustomStorageObject { if(!CommonUtils.isDefined(context)) context = this.currentRunningContext; //遍历调用栈 do { if(this.stack < context.graphBlockStack.length) { let variables = context.graphBlockStack[this.stack]; if(variables) return variables.variables; } else if(context != null && context.parentContext != null) context = context.parentContext.graph == context.graph ? context.parentContext : null;//同一个图表中才能互相访问 else context = null; } while(context != null); return undefined; } public stack = -1; private stackRepeat = 0; /** * 单元进入,参数,变量压栈 * @param context 当前上下文 */ public pushBlockStack(context: BlockRunContextData, port: BlockPort) { if(this.currentRunningContext === null) { this.currentRunningContext = context; //准备所有参数栈 let argCount = 0; this.allPorts.forEach((port) => { if(!port.paramType.isExecute()) { if(!(port.paramRefPassing && port.direction === 'input')) { context.graphBlockParamIndexs[port.stack] = context.pushParam( CommonUtils.isDefined(port.paramUserSetValue) ? port.paramUserSetValue : port.paramDefaultValue ); argCount++; } } }); context.pushParam(argCount);//保存argCount } else { this.stackRepeat ++;//防止错误的释放栈 } } /** * 单元结束,参数,变量弹栈 * @param context 当前上下文 */ public popBlockStack(context: BlockRunContextData) { if(this.stackRepeat > 0) { this.stackRepeat--; return;//防止错误的释放栈 } let argCount = context.popParam() as number; context.stackPointer -= argCount; this.currentRunningContext = null; } /** * 块的类型 */ public type : BlockType = 'normal'; /** * 块的断点触发设置 */ public breakpoint : BlockBreakPoint = 'none'; public userCanResize = false; public constructor(regData ?: BlockRegData, editorBlock = false) { this.uid = CommonUtils.genNonDuplicateIDHEX(16); this.isEditorBlock = editorBlock; if(regData) this.regData = regData; } /** * 获取名称 */ public getName(withUid = false) { return this.regData.baseInfo.name + (withUid ? `(UID: ${this.uid})` : ''); } public createBase() { if(this.regData) { this.guid = this.regData.guid; this.type = this.regData.type; this.data = this.regData.settings.data; if(typeof this.regData.callbacks.onCreate == 'function') this.onCreate.addListener(this,this.regData.callbacks.onCreate); if(typeof this.regData.callbacks.onDestroy == 'function') this.onDestroy.addListener(this,this.regData.callbacks.onDestroy); if(this.isEditorBlock && typeof this.regData.callbacks.onEditorCreate == 'function') this.onEditorCreate.addListener(this,this.regData.callbacks.onEditorCreate); if(typeof this.regData.callbacks.onStartRun == 'function') this.onStartRun.addListener(this,this.regData.callbacks.onStartRun); if(typeof this.regData.callbacks.onPortExecuteIn == 'function') this.onPortExecuteIn.addListener(this,this.regData.callbacks.onPortExecuteIn); if(typeof this.regData.callbacks.onPortParamRequest == 'function') this.onPortParamRequest.addListener(this,this.regData.callbacks.onPortParamRequest); if(this.isEditorBlock){ if(typeof this.regData.callbacks.onPortAdd == 'function') this.onPortAdd.addListener(this,this.regData.callbacks.onPortAdd); if(typeof this.regData.callbacks.onPortRemove == 'function') this.onPortRemove.addListener(this,this.regData.callbacks.onPortRemove); if(typeof this.regData.callbacks.onPortConnect == 'function') this.onPortConnect.addListener(this,this.regData.callbacks.onPortConnect); if(typeof this.regData.callbacks.onPortUnConnect == 'function') this.onPortUnConnect.addListener(this,this.regData.callbacks.onPortUnConnect); if(typeof this.regData.callbacks.onPortConnectCheck == 'function') this.onPortConnectCheck.addListener(this,this.regData.callbacks.onPortConnectCheck); this.userCanResize = this.regData.blockStyle.userCanResize; } if(this.regData.ports.length > 0) this.regData.ports.forEach(element => this.addPort(element, false)); } this.isPlatformSupport = this.regData.supportPlatform.contains('all') || this.regData.supportPlatform.contains(BlockServiceInstance.getCurrentPlatform()); this.onCreate.invoke(this); } public regData : BlockRegData = null; /** * 获取当前单元是不是在编辑器模式中 */ public isEditorBlock = false; /** * 当前单元所在的运行上下文 */ public currentRunningContext : BlockRunContextData = null; /** * 当前单元所在的运行器 */ public currentRunner : BlockRunner = null; /** * 当前单元所在的图文档 */ public currentGraph : BlockGraphDocunment = null; /** * 获取当前块是否支持当前平台s */ public isPlatformSupport = false; //单元控制事件 //=========================== public onCreate = new EventHandler<OnBlockEventCallback>(); public onEditorCreate = new EventHandler<OnBlockEditorEventCallback>(); public onDestroy = new EventHandler<OnBlockEventCallback>(); public onStartRun = new EventHandler<OnBlockEventCallback>(); public onPortExecuteIn = new EventHandler<OnPortEventCallback>(); public onPortParamRequest = new EventHandler<OnPortRequestCallback>(); public onPortAdd = new EventHandler<OnPortEventCallback>(); public onPortRemove = new EventHandler<OnPortEditorEventCallback>(); public portUpdateLock = false; public blockCurrentCreateNewContext = false; //上下文运行操作 //=========================== //进入块时的操作 public enterBlock(port: BlockPort, context : BlockRunContextData) { context.stackCalls.push({ block: this, port: port, childContext: null, }); this.onEnterBlock.invoke(); if(this.isEditorBlock) this.allPorts.forEach((port) => { if(port.connectedFromPort.length == 1) this.onPortConnectorActive.invoke(port, port.connectedFromPort[0].connector); }) } //退出块时的操作 public leaveBlock(context : BlockRunContextData) { this.onLeaveBlock.invoke(); } //节点操作 //=========================== public inputPorts : { [index: string]: BlockPort; } = {}; public outputPorts : { [index: string]: BlockPort; } = {}; public inputPortCount = 0; public outputPortCount = 0; public allPorts : Array<BlockPort> = []; public allPortsMap : Map<string, BlockPort> = new Map<string, BlockPort>(); /** * 添加行为端口 * @param data 行为端口数据 * @param isDyamicAdd 是否是动态添加。动态添加的端口会被保存至文件中。 */ public addPort(data : BlockPortRegData, isDyamicAdd = true, initialValue : any = null, forceChangeDirection ?: BlockPortDirection) { let oldData = this.getPort(data.guid, data.direction); if(oldData != null && oldData != undefined) { logger.warning(this.getName() + ".addPort", data.direction + " port " + data.name + " (" + data.guid + ") alreday exist !", { srcBlock: this }); return oldData; } let newPort = this.isEditorBlock ? new BlockPortEditor(<BlockEditor><any>this) : new BlockPort(this); newPort.name = data.name ? data.name : ''; newPort.description = data.description ? data.description : ''; newPort.isDyamicAdd = isDyamicAdd; newPort.guid = data.guid; newPort.direction = CommonUtils.isDefinedAndNotNull(forceChangeDirection) ? forceChangeDirection : data.direction; newPort.regData = data; if(typeof data.paramType == 'string') newPort.paramType = createParameterTypeFromString(data.paramType); else newPort.paramType = cloneParameterTypeFromString(data.paramType); if(CommonUtils.isDefinedAndNotNull(data.paramRefPassing)) newPort.paramRefPassing = data.paramRefPassing; if(CommonUtils.isDefinedAndNotNull(data.executeInNewContext)) newPort.executeInNewContext = data.executeInNewContext; newPort.paramDefaultValue = CommonUtils.isDefinedAndNotNull(data.paramDefaultValue) ? data.paramDefaultValue : ParamTypeServiceInstance.getTypeDefaultValue(newPort.paramType); if (newPort.direction == 'input') { newPort.paramUserSetValue = CommonUtils.isDefined(initialValue) ? initialValue : data.paramDefaultValue; newPort.forceNoEditorControl = data.forceNoEditorControl; } else newPort.paramUserSetValue = initialValue; if(CommonUtils.isDefinedAndNotNull(data.portAnyFlexable)) newPort.portAnyFlexable = data.portAnyFlexable; if(CommonUtils.isDefinedAndNotNull(data.paramStatic)) newPort.paramStatic = data.paramStatic; if(CommonUtils.isDefinedAndNotNull(data.paramSetType)) newPort.paramSetType = data.paramSetType; if(CommonUtils.isDefinedAndNotNull(data.paramDictionaryKeyType)) { if(typeof data.paramDictionaryKeyType == 'string') newPort.paramDictionaryKeyType = createParameterTypeFromString(data.paramDictionaryKeyType); else newPort.paramDictionaryKeyType = cloneParameterTypeFromString(data.paramDictionaryKeyType); } newPort.forceEditorControlOutput = data.forceEditorControlOutput || false; newPort.forceNoCycleDetection = data.forceNoCycleDetection || false; newPort.data = CommonUtils.isDefinedAndNotNull(data.data) ? data.data : {}; if(newPort.direction == 'input') { this.inputPorts[newPort.guid] = newPort; this.inputPortCount++; } else if(newPort.direction == 'output') { this.outputPorts[newPort.guid] = newPort; this.outputPortCount++; } if(data.defaultConnectPort) this.allPorts.unshift(newPort); else this.allPorts.push(newPort); this.allPortsMap.set(newPort.guid, newPort); this.onAddPortElement.invoke(this, newPort); this.onPortAdd.invoke(this, newPort); return newPort; } /** * 删除行为端口 * @param guid 端口GUID * @param direction 端口方向 */ public deletePort(guid : string|BlockPort, direction ?: BlockPortDirection) { let oldData = typeof guid == 'string' ? this.getPort(guid, direction) : guid; if(oldData == null || oldData == undefined) { logger.warning(this.getName() + ".deletePort", guid + " port not exist !", { srcBlock: this, }); return; } this.allPorts.remove(oldData); this.allPortsMap.delete(oldData.guid); this.onRemovePortElement.invoke(this, oldData); this.onPortRemove.invoke(this, oldData); if(direction == 'input') { delete(this.inputPorts[typeof guid == 'string' ? guid : guid.guid]); this.inputPortCount--; } else if(direction == 'output') { delete(this.outputPorts[typeof guid == 'string' ? guid : guid.guid]); this.outputPortCount--; } } /** * 获取某个行为端口 * @param guid 端口GUID * @param direction 端口方向 */ public getPort(guid : string, direction ?: BlockPortDirection) : BlockPort { if(direction == 'input') return this.inputPorts[guid]; else if(direction == 'output') return this.outputPorts[guid]; else return this.getPortByGUID(guid); } /** * 根据GUID获取某个端口 * @param guid */ public getPortByGUID(guid : string) { if(this.allPortsMap.has(guid)) return this.allPortsMap.get(guid); return null; } /** * 按方向和类型获取一个端口 * @param direction 方向 * @param type 定义类型 * @param customType 自定义类型 * @param includeAny 是否包括通配符的端口 */ public getOnePortByDirectionAndType(direction : BlockPortDirection, type : BlockParameterType, keyType : BlockParameterType, setType : BlockParameterSetType = 'variable', includeAny = true) { if(type.isExecute()) { for(let i = 0, c = this.allPorts.length; i < c;i++) if(this.allPorts[i].direction == direction && this.allPorts[i].paramType.isExecute()) return this.allPorts[i]; }else { for(let i = 0, c = this.allPorts.length; i < c;i++) if(this.allPorts[i].direction == direction) { if(setType == 'dictionary' && this.allPorts[i].paramSetType == 'dictionary') { if(includeAny && type.isAny() && keyType.isAny()) return this.allPorts[i]; if(includeAny && (this.allPorts[i]).paramType.isAny() && (this.allPorts[i]).paramDictionaryKeyType.isAny()) return this.allPorts[i]; if(this.allPorts[i].paramType.equals(type) && this.allPorts[i].paramDictionaryKeyType.equals(type)) return this.allPorts[i]; } else if( (includeAny && type.isAny()) || (this.allPorts[i].paramType.equals(type) && this.allPorts[i].paramSetType == setType) || (includeAny && this.allPorts[i].paramType.isAny() && this.allPorts[i].paramSetType == setType) ) return this.allPorts[i]; } } return null; } /** * 更改参数端口的数据类型 * @param port 参数端口 * @param newType 新的数据类型 * @param newCustomType 新的自定义类型 */ public changePortParamType(port : BlockPort, newType : BlockParameterType|string, newSetType ?: BlockParameterSetType, newKeyType ?: BlockParameterType|string) { if(!port) logger.error(this.getName(true), 'changePortParamType: Must provide port'); else if(port.parent == this) { if(CommonUtils.isDefined(newType)) if(typeof newType == 'string') port.paramType = createParameterTypeFromString(newType); else port.paramType.set(newType); if(CommonUtils.isDefined(newKeyType)) if(typeof newKeyType == 'string') port.paramDictionaryKeyType = createParameterTypeFromString(newKeyType); else port.paramDictionaryKeyType.set(newKeyType); if(CommonUtils.isDefinedAndNotNull(newSetType)) port.paramSetType = newSetType; this.onUpdatePortElement.invoke(this, port); } } /** * 获取输入参数端口的数据 * @param guid 参数端口GUID */ public getInputParamValue(guid : string|BlockPort, context ?: BlockRunContextData) { let port = typeof guid == 'string' ? <BlockPort>this.inputPorts[guid] : guid; if(port && !port.paramType.isExecute()) return port.rquestInputValue(context ? context : this.currentRunningContext); return undefined; } /** * 检查输入参数端口的数据是否更改 * @param guid 参数端口GUID */ public checkInputParamValueChanged(guid : string|BlockPort, context ?: BlockRunContextData) { let port = typeof guid == 'string' ? <BlockPort>this.inputPorts[guid] : guid; if(port && !port.paramType.isExecute()) return port.checkInputValueChanged(context ? context : this.currentRunningContext); return undefined; } /** * 更新输出参数端口的数据 * @param guid 参数端口GUID */ public setOutputParamValue(guid : string|BlockPort, value : any, context ?: BlockRunContextData) { let port = typeof guid == 'string' ? <BlockPort>this.outputPorts[guid] : guid; if(port && !port.paramType.isExecute()) port.updateOnputValue(context ? context : this.currentRunningContext, value); } /** * 获取输出参数端口的数据 * @param guid 参数端口GUID */ public getOutputParamValue(guid : string|BlockPort, context ?: BlockRunContextData) { let port = typeof guid == 'string' ? <BlockPort>this.outputPorts[guid] : guid; if(port && !port.paramType.isExecute()) return port.getValue(context ? context : this.currentRunningContext); return null; } /** * 在当前上下文激活某一个输出行为端口 * @param guid 行为端口GUID */ public activeOutputPort(guid : string|BlockPort, context ?: BlockRunContextData) { let port = typeof guid == 'string' ? <BlockPort>this.outputPorts[guid] : guid; if(port) port.active(context ? context : this.currentRunningContext); else logger.warning(this.getName(true), 'activeOutputPort: Not found port ' + guid); } /** * 在新的上下文中激活某一个输出行为端口(适用于接收事件) * @param guid 行为端口GUID */ public activeOutputPortInNewContext(guid : string|BlockPort) { let port = typeof guid == 'string' ? <BlockPort>this.outputPorts[guid] : guid; if(port) port.activeInNewContext(); else logger.warning(this.getName(true), 'activeOutputPort: Not found port ' + guid); } public onEnterBlock = new EventHandler<OnBlockEventCallback>(); public onLeaveBlock = new EventHandler<OnBlockEventCallback>(); public onAddPortElement = new EventHandler<OnPortEditorEventCallback>(); public onUpdatePortElement = new EventHandler<OnPortEditorEventCallback>(); public onRemovePortElement = new EventHandler<OnPortEditorEventCallback>(); public onPortValueUpdate = new EventHandler<OnPortEventCallback>(); public onPortConnectorActive = new EventHandler<(port : BlockPort, connector : Connector) => void>(); public onPortConnectCheck = new EventHandler<OnPortConnectCheckCallback>(); public onPortConnect = new EventHandler<OnPortConnectCallback>(); public onPortUnConnect = new EventHandler<OnPortEditorEventCallback>(); /** * 抛出本单元的错误 * @param err 错误字符串 * @param port 发生的端口(可选) * @param level 发生错误的等级 * @param breakFlow 是否终止当前流的运行。 * 注意,终止后流图将停止运行。单元内部请勿继续调用其他端口。 */ public throwError(err : string, port ?: BlockPort, level : 'warning'|'error' = 'error', breakFlow = false) { let errorString = `单元 ${this.getName()} (${this.uid}) ${port?port.getName(false):''} 发生错误: ${err}`; switch(level) { case 'error': logger.error('单元错误', errorString, { srcBlock: this, srcPort: port }); break; case 'warning': logger.warning('单元警告', errorString, { srcBlock: this, srcPort: port }); break; default: logger.log('单元警告', errorString, { srcBlock: this, srcPort: port }); break; } //触发断点 if(breakFlow) { if(this.currentRunningContext) { this.currentRunningContext.runner.markInterrupt( this.currentRunningContext, null, this ) } throw new Error(errorString); } } } export type OnBlockEventCallback = (block : Block) => void; export type OnPortEventCallback = (block : Block, port : BlockPort) => void; export type OnPortEditorEventCallback = (block : BlockEditor, port : BlockPort) => void; export type OnPortUpdateCallback = (block : Block, port : BlockPort, portSource : BlockPort) => void; export type OnPortConnectCallback = (block : BlockEditor, port : BlockPort, portSource : BlockPort) => void; export type OnPortConnectCheckCallback = (block : BlockEditor, port : BlockPort, portSource : BlockPort) => string; export type OnPortRequestCallback = (block : Block, port : BlockPort, context : BlockRunContextData) => any; export type OnBlockEditorEventCallback = (block : BlockEditor) => void; export type OnUserAddPortCallback = (block : BlockEditor, direction : BlockPortDirection, type : 'execute'|'param') => BlockPortRegData|BlockPortRegData[]; export type OnAddBlockCheckCallback = (block : BlockRegData, graph : BlockGraphDocunment) => string|null; /** * 断点类型。 * enable:启用, * disable:禁用, * none:未设置 */ export type BlockBreakPoint = 'enable'|'disable'|'none'; /** * 单元类型 * normal:普通, * base:基础单元, * variable:参数单元 */ export type BlockType = 'normal'|'base'|'variable'; /** * 该单元支持运行的平台类型 * all: 表示所有单元都支持 * web:表示用于Web平台 * electron:表示用于Elecron平台,这既包含Web平台的html功能,也包含nodejs支持 * nodejs:nodejs平台,不包含html功能 */ export type BlockSupportPlatform = 'all'|'web'|'electron'|'nodejs';
the_stack
import Map from '@dojo/framework/shim/Map'; import { create, tsx } from '@dojo/framework/core/vdom'; import theme from '../middleware/theme'; import { padStart } from '@dojo/framework/shim/string'; import { List, ListOption } from '../list'; import focus from '@dojo/framework/core/middleware/focus'; import * as css from '../theme/default/time-picker.m.css'; import * as inputCss from '../theme/default/text-input.m.css'; import TriggerPopup from '../trigger-popup'; import TextInput from '../text-input'; import Icon from '../icon'; import { createICacheMiddleware } from '@dojo/framework/core/middleware/icache'; import { Keys } from '../common/util'; import bundle from './nls/TimePicker'; import i18n from '@dojo/framework/core/middleware/i18n'; import { createResourceTemplate, createResourceMiddleware } from '@dojo/framework/core/middleware/resources'; import { RenderResult } from '@dojo/framework/core/interfaces'; export interface TimePickerProperties { /** Set the disabled property of the control */ disabled?: boolean; /** Callback to determine if a particular time entry should be disabled */ timeDisabled?: (time: Date) => boolean; /** The name of the field */ name?: string; /** The initial selected value */ initialValue?: string; /** Controlled value property */ value?: string; /** Called when the value changes */ onValue?(value: string): void; /** Indicates the input is required to complete the form */ required?: boolean; /** Callabck when valid state has changed */ onValidate?(valid: boolean, message: string): void; /** The maximum time to display in the menu (defaults to '23:59:59') */ max?: string; /** The minimum time to display in the menu (defaults to '00:00:00') */ min?: string; /** The number of seconds between each option in the menu (defaults to 1800) */ step?: number; /** How the time is formatted. 24 hour, 12 hour */ format?: '24' | '12'; /** Property to determine how many items to render. Defaults to 10 */ itemsInView?: number; /** The kind of time picker input */ kind?: 'outlined' | 'filled'; } export interface TimePickerChildren { /** The label to be displayed above the input */ label?: RenderResult; } export interface TimePickerICache { value?: string; lastValue: string; nextValue: string; inputValue: string; validationMessage: string | undefined; focusNode: 'input' | 'menu'; inputValid?: boolean; inputValidMessage?: string; isValid?: boolean; initialValue?: string; min: string; max: string; step: number; options: (ListOption & { dt: number })[]; dirty: boolean; callOnValue: void; } const resource = createResourceMiddleware(); const factory = create({ resource, theme, i18n, focus, icache: createICacheMiddleware<TimePickerICache>() }) .properties<TimePickerProperties>() .children<TimePickerChildren | RenderResult | undefined>(); export interface TimeParser { regex: RegExp; positions: { hour?: number; minute?: number; second?: number; amPm?: number; }; } const formats: Record<string, TimeParser> = { hh: { regex: /^(\d{1,2})$/i, positions: { hour: 1 } }, hhmm: { regex: /^(\d{1,2}):(\d{1,2})$/, positions: { hour: 1, minute: 2 } }, hhmmss: { regex: /^(\d{1,2}):(\d{1,2}):(\d{1,2})$/, positions: { hour: 1, minute: 2, second: 3 } }, hham: { regex: /^(\d{1,2})\s*([ap]\.?m\.?)$/i, positions: { hour: 1, amPm: 2 } }, hhmmam: { regex: /^(\d{1,2}):(\d{1,2})\s*([ap]\.?m\.?)$/i, positions: { hour: 1, minute: 2, amPm: 3 } }, hhmmssam: { regex: /^(\d{1,2}):(\d{1,2}):(\d{1,2})\s*([ap]\.?m\.?)$/i, positions: { hour: 1, minute: 2, second: 3, amPm: 4 } } }; const formats24 = ['hh', 'hhmm', 'hhmmss']; const formats12 = ['hh', 'hhmm', 'hhmmss', 'hham', 'hhmmam', 'hhmmssam']; const template = createResourceTemplate<ListOption>('value'); export function parseTime(time: string | undefined, hour12: boolean) { if (!time) { return undefined; } const timeFormats = hour12 ? formats12 : formats24; for (const key of timeFormats) { const format = formats[key] as TimeParser; const match = format.regex.exec(time); if (match) { let hours = format.positions.hour ? parseInt(match[format.positions.hour], 0) : 0; const minutes = format.positions.minute ? parseInt(match[format.positions.minute], 0) : 0; const seconds = format.positions.second ? parseInt(match[format.positions.second], 0) : 0; if ( hour12 && format.positions.amPm && match[format.positions.amPm].toLocaleLowerCase()[0] === 'p' && hours !== 12 ) { // special case for "12pm", which is just 12 hours += 12; } else if ( hour12 && format.positions.amPm && match[format.positions.amPm].toLocaleLowerCase()[0] === 'a' && hours === 12 ) { // special case of "12am", which we want to be hour 0 hours = 0; } if (hours === undefined || isNaN(hours) || isNaN(minutes) || isNaN(seconds)) { return undefined; } return new Date(1970, 0, 1, hours, minutes, seconds, 0); } } return undefined; } export function format24HourTime(dt: Date) { return `${padStart(String(dt.getHours()), 2, '0')}:${padStart( String(dt.getMinutes()), 2, '0' )}:${padStart(String(dt.getSeconds()), 2, '0')}`; } function isTimePickerChildren(children: any): children is TimePickerChildren { // In order to not make this a breaking change, check for an edge case where an object // with a label property that would have been used as a label might instead be treated as a render result return children && children.hasOwnProperty && children.hasOwnProperty('label'); } const optionsCache = new Map<string, (ListOption & { dt: number })[]>(); export const TimePicker = factory(function TimePicker({ id, middleware: { theme, icache, focus, i18n, resource }, properties, children }) { const themedCss = theme.classes(css); const { messages } = i18n.localize(bundle); const formatTime = (time: Date) => { const { format = '24', step = 1800 } = properties(); const hideSeconds = step >= 60 && time.getSeconds() === 0; // Use a new, local date so that display formatting does not offset based on timezone const newTime = new Date(); newTime.setHours(time.getHours()); newTime.setMinutes(time.getMinutes()); newTime.setSeconds(time.getSeconds()); if (format === '24') { return newTime .toLocaleTimeString(undefined, { hour12: false, hour: 'numeric', minute: 'numeric', second: hideSeconds ? undefined : 'numeric' }) .replace(/[^a-zA-Z\d\s:.]/g, ''); } else { return newTime .toLocaleTimeString(undefined, { hour12: true, hour: 'numeric', minute: 'numeric', second: hideSeconds ? undefined : 'numeric' }) .replace(/[^a-zA-Z\d\s:.]/g, ''); } }; const { initialValue, format = '24', value: controlledValue, min = '00:00:00', max = '23:59:59', step = 1800, timeDisabled, itemsInView } = properties(); if ( initialValue !== undefined && controlledValue === undefined && icache.get('initialValue') !== initialValue ) { const parsed = initialValue && parseTime(initialValue, format === '12'); icache.set('inputValue', parsed ? formatTime(parsed) : ''); icache.set('initialValue', initialValue); icache.delete('callOnValue'); } if (controlledValue !== undefined && icache.get('lastValue') !== controlledValue) { const parsed = controlledValue && parseTime(controlledValue, format === '12'); icache.set('inputValue', parsed ? formatTime(parsed) : ''); icache.set('value', parsed ? format24HourTime(parsed) : ''); icache.set('lastValue', controlledValue); } const shouldFocus = focus.shouldFocus(); const focusNode = icache.getOrSet('focusNode', 'input'); function callOnValue() { const inputValue = icache.get('inputValue'); const testValue = icache.get('nextValue') || inputValue; const { onValidate, onValue, format } = properties(); const max = parseTime(properties().max, format === '12'); const min = parseTime(properties().min, format === '12'); let isValid = icache.get('inputValid'); let validationMessages: string[] = []; if (icache.get('inputValidMessage')) { validationMessages.push(icache.get('inputValidMessage') || ''); } if (min && max && min > max) { validationMessages.push(messages.invalidProps); isValid = false; } else { const newTime = parseTime(testValue, format === '12'); if (newTime !== undefined) { if (min && newTime < min) { validationMessages.push(messages.tooEarly); } else if (max && newTime > max) { validationMessages.push(messages.tooLate); } else { const twentyFourHourTime = format24HourTime(newTime); if (controlledValue === undefined) { icache.set('value', twentyFourHourTime); icache.set('inputValue', formatTime(newTime)); } if (onValue) { onValue(twentyFourHourTime); } } } else { if (inputValue) { validationMessages.push(messages.invalidTime); } } isValid = isValid === undefined ? validationMessages.length === 0 : isValid; icache.set('isValid', isValid); } const validationMessage = validationMessages.join('; '); onValidate && onValidate(isValid, validationMessage); icache.set('validationMessage', validationMessage); icache.set('dirty', false); } icache.getOrSet('callOnValue', () => callOnValue()); if (min !== icache.get('min') || max !== icache.get('max') || step !== icache.get('step')) { icache.set('options', () => { const key = `${min}-${max}-${step}`; const cached = optionsCache.get(key); if (cached) { return cached; } const options: (ListOption & { dt: number })[] = []; const dt = parseTime(min, false) || new Date(1970, 0, 1, 0, 0, 0, 0); const end = parseTime(max, false) || new Date(1970, 0, 1, 23, 59, 59, 99); while (dt.getDate() === 1 && dt <= end) { const value = formatTime(dt); options.push({ dt: dt.getTime(), label: value, value: value }); dt.setSeconds(dt.getSeconds() + step); } optionsCache.set(key, options); return options; }); icache.set('min', min); icache.set('max', max); icache.set('step', step); } const options = icache.getOrSet('options', []).map(({ label, value, dt }) => ({ label, value, disabled: timeDisabled ? timeDisabled(new Date(dt)) : false })); const { name, theme: themeProp, classes, variant, kind } = properties(); const [labelChild] = children(); const label = isTimePickerChildren(labelChild) ? labelChild.label : labelChild; return ( <div classes={[theme.variant(), themedCss.root]}> <input type="hidden" name={name} value={icache.getOrSet('value', '')} aria-hidden="true" /> <TriggerPopup key="popup" theme={themeProp} classes={classes} variant={variant}> {{ trigger: (toggleOpen) => { function openMenu() { icache.set('focusNode', 'menu'); focus.focus(); toggleOpen(); } const { disabled, required } = properties(); return ( <div classes={themedCss.input}> <TextInput key="input" disabled={disabled} required={required} focus={() => shouldFocus && focusNode === 'input'} theme={theme.compose( inputCss, css, 'input' )} classes={classes} variant={variant} initialValue={icache.getOrSet('inputValue', '')} onBlur={() => { if (icache.get('dirty')) { callOnValue(); } }} onValue={(v) => controlledValue === undefined ? icache.set('inputValue', v || '') : icache.set('nextValue', v || '') } onFocus={() => { icache.set('dirty', true); }} helperText={icache.get('validationMessage')} valid={icache.get('isValid') && icache.get('inputValid')} onValidate={(valid, message) => { if (valid !== icache.get('inputValid')) { icache.set('inputValid', valid); if (icache.get('dirty')) { icache.set('inputValidMessage', message); } callOnValue(); } }} onKeyDown={(key) => { if (key === Keys.Down || key === Keys.Enter) { if (key === Keys.Enter) { callOnValue(); } openMenu(); } }} type="text" kind={kind} > {{ label, trailing: ( <button disabled={disabled} key="clockIcon" onclick={(e) => { e.stopPropagation(); openMenu(); }} classes={themedCss.toggleMenuButton} type="button" > <Icon type="clockIcon" /> </button> ) }} </TextInput> </div> ); }, content: (onClose) => { function closeMenu() { icache.set('focusNode', 'input'); focus.focus(); onClose(); } return ( <div key="menu-wrapper" classes={themedCss.menuWrapper}> <List itemsInView={itemsInView} height="auto" theme={themeProp} classes={classes} variant={variant} key="menu" focus={() => shouldFocus && focusNode === 'menu'} resource={resource({ template: template({ id, data: options }) })} onValue={(value) => { if (controlledValue === undefined) { icache.set('inputValue', value.value); } else { icache.set('nextValue', value.value); } callOnValue(); closeMenu(); }} onRequestClose={closeMenu} onBlur={closeMenu} initialValue={''} menu /> </div> ); } }} </TriggerPopup> </div> ); }); export default TimePicker;
the_stack
namespace phasereditor2d.scene.ui { import controls = colibri.ui.controls; import ide = colibri.ui.ide; import io = colibri.core.io; import json = core.json; import FileUtils = colibri.ui.ide.FileUtils; export class SceneMaker extends BaseSceneMaker { private _editorScene: Scene; constructor(scene: Scene) { super(scene); this._editorScene = scene; } afterDropObjects(prefabObj: sceneobjects.ISceneGameObject, sprites: sceneobjects.ISceneGameObject[]) { let container: sceneobjects.Container; let layer: sceneobjects.Layer; for (const sprite of this._editorScene.getEditor().getSelectedGameObjects()) { let sprite2 = sprite; if (sprite2.getEditorSupport().isPrefabInstance()) { sprite2 = sceneobjects.getObjectParent(sprite2.getEditorSupport().getOwnerPrefabInstance()); } if (sprite2) { if (sprite2 instanceof sceneobjects.Container) { container = sprite2; } else if (sprite2.parentContainer) { container = sprite2.parentContainer as sceneobjects.Container; } else if (sprite2 instanceof sceneobjects.Layer) { layer = sprite2; } else if (sprite2.displayList instanceof sceneobjects.Layer) { layer = sprite2.displayList; } } } if (container) { for (const obj of sprites) { if (obj instanceof sceneobjects.Layer) { continue; } const sprite = obj as sceneobjects.Sprite; const p = new Phaser.Math.Vector2(); sprite.getWorldTransformMatrix().transformPoint(0, 0, p); this._editorScene.sys.displayList.remove(sprite); container.add(sprite); container.getWorldTransformMatrix().applyInverse(p.x, p.y, p); sprite.x = p.x; sprite.y = p.y; } } else if (layer) { for (const obj of sprites) { layer.add(obj); } } else { this.afterDropObjectsInPrefabScene(prefabObj, sprites); } } private afterDropObjectsInPrefabScene(prefabObj: sceneobjects.ISceneGameObject, sprites: sceneobjects.ISceneGameObject[]) { if (!prefabObj) { return; } const scene = prefabObj.getEditorSupport().getScene(); if (!scene.isPrefabSceneType()) { return; } let parent: sceneobjects.Container | sceneobjects.Layer; if (scene.isPrefabSceneType()) { if (sprites.length > 0) { if (!prefabObj.getEditorSupport().isPrefabInstance() && (prefabObj instanceof sceneobjects.Container || prefabObj instanceof sceneobjects.Layer)) { parent = prefabObj; } else { [parent] = sceneobjects.ContainerExtension.getInstance().createDefaultSceneObject({ scene: scene, x: 0, y: 0 }); parent.getEditorSupport().setLabel(scene.makeNewName("container")); scene.sys.displayList.remove(prefabObj); parent.add(prefabObj); } if (parent) { for (const sprite of sprites) { if (parent instanceof sceneobjects.Container) { if (sprite.getEditorSupport().hasComponent(sceneobjects.TransformComponent)) { (sprite as sceneobjects.Sprite).x -= parent.x; (sprite as sceneobjects.Sprite).y -= parent.y; } } scene.sys.displayList.remove(sprite); parent.add(sprite); } if (parent !== prefabObj && parent instanceof sceneobjects.Container) { parent.getEditorSupport().trim(); } } } } } static acceptDropFile(dropFile: io.FilePath, editorFile: io.FilePath) { if (dropFile.getFullName() === editorFile.getFullName()) { return false; } const sceneFinder = ScenePlugin.getInstance().getSceneFinder(); const sceneData = sceneFinder.getSceneData(dropFile); if (sceneData) { if (sceneData.sceneType !== core.json.SceneType.PREFAB) { return false; } if (sceneData.displayList.length === 0) { return false; } const objData = sceneData.displayList[sceneData.displayList.length - 1]; if (objData.prefabId) { const prefabFile = sceneFinder.getPrefabFile(objData.prefabId); if (prefabFile) { return this.acceptDropFile(prefabFile, editorFile); } } return true; } return false; } static isValidSceneDataFormat(data: json.ISceneData) { return "displayList" in data && Array.isArray(data.displayList); } async buildDependenciesHash() { const builder = new phasereditor2d.ide.core.MultiHashBuilder(); for (const obj of this._editorScene.getDisplayListChildren()) { await obj.getEditorSupport().buildDependencyHash({ builder }); } this._editorScene.getPackCache().buildAssetsDependenciesHash(builder); const hash = builder.build(); return hash; } isPrefabFile(file: io.FilePath) { const ct = colibri.Platform.getWorkbench().getContentTypeRegistry().getCachedContentType(file); if (ct === core.CONTENT_TYPE_SCENE) { const finder = ScenePlugin.getInstance().getSceneFinder(); const data = finder.getSceneData(file); return data && data.sceneType === json.SceneType.PREFAB; } return false; } async createPrefabInstanceWithFile(file: io.FilePath) { const content = await FileUtils.preloadAndGetFileString(file); if (!content) { return null; } try { const prefabData = JSON.parse(content) as json.ISceneData; const obj = this.createObject({ id: Phaser.Utils.String.UUID(), prefabId: prefabData.id, label: "temporal" }); if (obj.getEditorSupport().isUnlockedProperty(sceneobjects.TransformComponent.x)) { const { x, y } = this.getCanvasCenterPoint(); const sprite = obj as unknown as sceneobjects.ITransformLikeObject; sprite.x = x; sprite.y = y; } return obj; } catch (e) { console.error(e); return null; } } getSerializer(data: json.IObjectData) { return new json.Serializer(data); } createScene(sceneData: json.ISceneData, errors?: string[]) { if (sceneData.meta.version === undefined || sceneData.meta.version === 1) { // old version, perform unlock x & y migration new json.Version1ToVersion2Migration().migrate(sceneData); } if (sceneData.settings) { this._editorScene.getSettings().readJSON(sceneData.settings); } if (sceneData.lists) { this._editorScene.getObjectLists().readJSON(sceneData); } if (sceneData.plainObjects) { this._editorScene.readPlainObjects(sceneData.plainObjects); } if (sceneData.prefabProperties) { this._editorScene.getPrefabUserProperties().readJSON(sceneData.prefabProperties); } this._editorScene.setSceneType(sceneData.sceneType || core.json.SceneType.SCENE); // removes this condition, it is used temporal for compatibility this._editorScene.setId(sceneData.id); for (const objData of sceneData.displayList) { this.createObject(objData, errors); } } async updateSceneLoader(sceneData: json.ISceneData, monitor?: controls.IProgressMonitor) { const finder = new pack.core.PackFinder(); await finder.preload(); await this.updateSceneLoaderWithGameObjectDataList(finder, sceneData.displayList, monitor); await this.updateSceneLoaderWithPlainObjDataList(finder, sceneData.plainObjects, monitor); } async updateSceneLoaderWithPlainObjDataList(finder: pack.core.PackFinder, list: json.IScenePlainObjectData[], monitor?: controls.IProgressMonitor) { if (!list) { return; } const assets = []; for (const data of list) { try { const type = data.type; const ext = ScenePlugin.getInstance().getPlainObjectExtensionByObjectType(type); if (ext) { const result = await ext.getAssetsFromObjectData({ scene: this._editorScene, finder, data }); assets.push(...result); } } catch (e) { console.error(e); } } await this.updateSceneLoaderWithAssets(assets, monitor); } async updateSceneLoaderWithGameObjectDataList(finder: pack.core.PackFinder, list: json.IObjectData[], monitor?: controls.IProgressMonitor) { const assets = []; for (const objData of list) { try { const ser = this.getSerializer(objData); const type = ser.getType(); const ext = ScenePlugin.getInstance().getGameObjectExtensionByObjectType(type); if (ext) { const objAssets = await ext.getAssetsFromObjectData({ serializer: ser, finder: finder, scene: this._editorScene }); assets.push(...objAssets); } } catch (e) { console.error(e); } } await this.updateSceneLoaderWithAssets(assets, monitor); } async updateSceneLoaderWithAssets(assets: any[], monitor?: controls.IProgressMonitor) { if (monitor) { monitor.addTotal(assets.length); } for (const asset of assets) { const updater = ScenePlugin.getInstance().getLoaderUpdaterForAsset(asset); if (updater) { await updater.updateLoader(this._editorScene, asset); if (monitor) { monitor.step(); } } } } getCanvasCenterPoint() { const canvas = this._editorScene.game.canvas; let x = canvas.width / 2; let y = canvas.height / 2; const worldPoint = this._editorScene.getCamera().getWorldPoint(x, y); x = Math.floor(worldPoint.x); y = Math.floor(worldPoint.y); return { x, y }; } createDefaultObject(ext: sceneobjects.SceneObjectExtension, extraData?: any, x?: number, y?: number) { if (x === undefined) { const point = this.getCanvasCenterPoint(); x = point.x; y = point.y; } const newObjects = ext.createDefaultSceneObject({ scene: this._editorScene, x, y, extraData }); const nameMaker = new ide.utils.NameMaker(obj => { return (obj as sceneobjects.ISceneGameObject).getEditorSupport().getLabel(); }); for (const newObject of newObjects) { this._editorScene.visit(obj => { if (obj !== newObject) { nameMaker.update([obj]); } }); const oldLabel = newObject.getEditorSupport().getLabel(); const newLabel = nameMaker.makeName(oldLabel); newObject.getEditorSupport().setLabel(newLabel); } return newObjects; } createObject(data: json.IObjectData, errors?: string[], parent?: sceneobjects.ISceneGameObject) { try { const ser = this.getSerializer(data); const type = ser.getType(); const ext = ScenePlugin.getInstance().getGameObjectExtensionByObjectType(type); if (ext) { const sprite = ext.createGameObjectWithData({ data: data, scene: this._editorScene }); return sprite; } else { const msg = `SceneMaker: no extension is registered for type "${type}".`; if (errors) { errors.push(msg); } console.error(msg); } return null; } catch (e) { const msg = (e as Error).message; if (errors) { errors.push(msg); } console.error(e); return null; } } } }
the_stack
import {Injectable} from '@angular/core' import { DataStore, DataStoreState, EffectiveItemInfo, generateSubtreeRepetition, getQueuePriorityProxy, QueuePriorityProxy, queuePriorityProxyCompare, SubtreeRepetitionInfo, } from './data-store' import {BehaviorSubject} from 'rxjs' import { DayID, DEFAULT_REPEATERS, INF_DAY_ID, Item, ItemID, ItemStatus, NEG_INF_DAY_ID, Repeater, SessionType, } from './common' import {debounceTime} from 'rxjs/operators' import { arrayToMap, Counter, getOrCreate, optionalClamp, PriorityQueue, } from '../util/util' const ANALYZER_UPDATE_DELAY = 500 const MIN_QUOTA_PERIOD = 7 const MAX_QUOTA_PERIOD = 30 const EMPTY_LIST_CREATOR = (): any[] => [] export interface Task { itemID: ItemID /** * The residual cost of the item. */ cost: number /** * Defer date. */ start?: DayID /** * Due date. */ end?: DayID progress?: number pastProgress?: number plannedProgress?: number inactive?: boolean } export interface TaskSchedulingInfo { itemID: ItemID task: Task priorityProxy: QueuePriorityProxy unplannedCost: number } export interface TaskSchedulingEndpoint { taskInfo: TaskSchedulingInfo dayID: DayID isEnd: boolean } export interface ProjectionResult { sessions: Map<DayID, Map<ItemID, number>> impossibleTasks: Task[] } export abstract class ProjectionStrategy { /** * @param firstDayID * @param lastDayID * @param taskInfoList * @param taskInfoEndpoints Must be sorted in ascending order by time. * Also, due dates must be 1 + original value. * @param sessionSlots */ abstract generate(firstDayID: DayID, lastDayID: DayID, taskInfoList: TaskSchedulingInfo[], taskInfoEndpoints: TaskSchedulingEndpoint[], sessionSlots: Map<DayID, number>): ProjectionResult } export class GreedyProjectionStrategy extends ProjectionStrategy { /** * @param backward Use backward scheduling strategy. * Forward scheduling uses the queue priority, while backward scheduling * uses the due and defer dates. * Additionally, backward scheduling ignores all tasks that are not due * within the scheduling range. */ constructor( readonly backward: boolean, ) { super() } generate(firstDayID: DayID, lastDayID: DayID, taskInfoList: TaskSchedulingInfo[], taskInfoEndpoints: TaskSchedulingEndpoint[], sessionSlots: Map<DayID, number>): ProjectionResult { const result: ProjectionResult = { sessions: new Map<DayID, Map<ItemID, number>>(), impossibleTasks: [], } const {sessions, impossibleTasks} = result const q = new PriorityQueue<TaskSchedulingInfo>({ comparator: this.backward ? (a, b) => { // Latest defer date first const aStart = a.task.start const bStart = b.task.start let result = (bStart === undefined ? NEG_INF_DAY_ID : bStart) - (aStart === undefined ? NEG_INF_DAY_ID : aStart) if (result !== 0) return result if (a.unplannedCost !== b.unplannedCost) { return a.unplannedCost - b.unplannedCost } return a.itemID - b.itemID } : (a, b) => queuePriorityProxyCompare( a.priorityProxy, b.priorityProxy), }) // Next event to process let endpointPtr = this.backward ? taskInfoEndpoints.length - 1 : 0 const sessionOfDayCreator = () => new Map<ItemID, number>() interface AuxiliaryInfo { deleted: boolean, /** * Number of projected sessions planned */ plannedCount: number, } const auxiliaryInfoCreator = (): AuxiliaryInfo => ({ deleted: false, plannedCount: 0, }) const auxiliaryInfoMap = new Map<TaskSchedulingInfo, AuxiliaryInfo>() let start = this.backward ? lastDayID : firstDayID let stop = this.backward ? firstDayID : lastDayID let step = this.backward ? -1 : 1 for (let d = start; d >= firstDayID && d <= lastDayID; d += step) { // Process endpoints while (this.backward ? (endpointPtr >= 0) : (endpointPtr < taskInfoEndpoints.length)) { const endpoint = taskInfoEndpoints[endpointPtr] if (this.backward ? (endpoint.dayID <= d) : (endpoint.dayID > d)) { break } if (this.backward ? (!endpoint.isEnd) : endpoint.isEnd) { // TODO optimize: this is not necessary at all for backward scheduling getOrCreate( auxiliaryInfoMap, endpoint.taskInfo, auxiliaryInfoCreator).deleted = true } else { if (!this.backward || endpoint.dayID - 1 <= lastDayID) { // When scheduling backward, keep only tasks that are due within // the scheduling range // Keep in mind that the end endpoint has dayID being 1 more than // actual due date q.queue(endpoint.taskInfo) } } endpointPtr += step } let quota = sessionSlots.get(d) || 0 while (quota > 0) { while ( q.length > 0 && getOrCreate(auxiliaryInfoMap, q.peek(), auxiliaryInfoCreator).deleted ) { q.dequeue() } if (q.length <= 0) break const info = q.peek() const auxInfo = getOrCreate( auxiliaryInfoMap, info, auxiliaryInfoCreator) let count = Math.min( Math.max(info.unplannedCost - auxInfo.plannedCount, 0), quota) if (count > 0) { const sessionsOfDay = getOrCreate(sessions, d, sessionOfDayCreator) sessionsOfDay.set( info.itemID, (sessionsOfDay.get(info.itemID) || 0) + count) quota -= count auxInfo.plannedCount += count } if (auxInfo.plannedCount >= info.unplannedCost) { const itemID = info.itemID q.dequeue() } } } // Compute impossible tasks taskInfoList.forEach(info => { const auxInfo = getOrCreate(auxiliaryInfoMap, info, auxiliaryInfoCreator) if (info.task.end !== undefined && info.task.end <= lastDayID && auxInfo.plannedCount < info.unplannedCost) { impossibleTasks.push(info.task) // Add the unplanned sessions const d = Math.max(info.task.end, firstDayID) const sessionsOfDay = getOrCreate(sessions, d, sessionOfDayCreator) const amountLeft = (info.unplannedCost - auxInfo.plannedCount) sessionsOfDay.set( info.itemID, (sessionsOfDay.get(info.itemID) || 0) + amountLeft) } }) return result } } export enum AnalyzerProjectionStrategy { FORWARD, BACKWARD, } export class FreeTimeInfo { quotaPeriod = 1 totalQuota = 0 freeQuota = 0 lastWeekDailyCompletion = 0 constructor() { } clear() { this.quotaPeriod = 1 this.totalQuota = 0 this.freeQuota = 0 this.lastWeekDailyCompletion = 0 } } export enum TaskProblemType { /** * The task cannot be completed when scheduling according to the queue. */ IMPOSSIBLE_BY_QUEUE, /** * The task cannot be completed when scheduling according to the late strategy * which attempts to maximize completion of all tasks with due dates. * This state takes precedence over IMPOSSIBLE_BY_QUEUE. */ IMPOSSIBLE_BY_LATE, } export interface TaskProblem { task: Task type: TaskProblemType } export interface AlertActionContext { showItemInItems?: (itemID: ItemID) => void showItemInQueue?: (itemID: ItemID) => void dataStore?: DataStore editItem?: (itemID: ItemID) => void } export interface AlertAction { displayName: string isSupported(ctx: AlertActionContext) execute(data: any, ctx: AlertActionContext) } export interface Alert { type: string data: any icon: string color: 'primary' | 'warn' | 'accent' actions: AlertAction[] } const SHOW_IN_ITEMS_ACTION: AlertAction = { displayName: 'Show in Items', isSupported(ctx: AlertActionContext) { return ctx.showItemInItems !== undefined }, execute(data: any, ctx: AlertActionContext) { const itemID = data.itemID if (itemID === undefined) return ctx.showItemInItems!(itemID) }, } const SHOW_IN_QUEUE_ACTION: AlertAction = { displayName: 'Show in Queue', isSupported(ctx: AlertActionContext) { return ctx.showItemInQueue !== undefined }, execute(data: any, ctx: AlertActionContext) { const itemID = data.itemID if (itemID === undefined) return ctx.showItemInQueue!(itemID) }, } const MARK_ITEM_COMPLETE_ACTION: AlertAction = { displayName: 'Mark Item as Completed', isSupported(ctx: AlertActionContext) { return ctx.dataStore !== undefined }, execute(data: any, ctx: AlertActionContext) { const itemID = data.itemID if (itemID === undefined) return const dataStore = ctx.dataStore! const item = dataStore.getItem(itemID) if (item === undefined) return const draft = item.toDraft() draft.status = ItemStatus.COMPLETED dataStore.updateItem(draft) }, } const EDIT_ITEM_ACTION: AlertAction = { displayName: 'Edit Item', isSupported(ctx: AlertActionContext) { return ctx.editItem !== undefined }, execute(data: any, ctx: AlertActionContext) { const itemID = data.itemID if (itemID === undefined) return ctx.editItem!(itemID) }, } /** * NOTE: When data store updates, any user of analyzer data must query the * analyzer again, since the information might be out of date. * * This task also need to make sure that when it's not up to date, any query * result should still *make sense*. */ @Injectable() export class DataAnalyzer { private onChangeSubject = new BehaviorSubject<DataAnalyzer>(this) onChange = this.onChangeSubject.asObservable() private currentDataStoreState?: DataStoreState private repeaters = new Map<string, Repeater>() private maxProjectionRange = 365 private itemIDToTasks = new Map<ItemID, Task[]>() private projectedSessions = new Map<AnalyzerProjectionStrategy, Map<DayID, Map<ItemID, number>>>() private estimatedDoneDates = new Map<ItemID, DayID>() private effectiveProgress = new Map<ItemID, number>() private freeTimeInfo = new FreeTimeInfo() // Guaranteed to be sorted by task order private taskProblems = new Map<ItemID, TaskProblem[]>() private itemDueDateMap = new Map<DayID, Set<ItemID>>() private alerts: Alert[] = [] constructor( private readonly dataStore: DataStore, ) { this.subscribeToDataStore() this.registerDefaultRepeaters() } private subscribeToDataStore() { this.dataStore.onChange.pipe( debounceTime(ANALYZER_UPDATE_DELAY), ).subscribe(dataStore => { this.processDataStore() }) this.dataStore.onReload.subscribe(dataStore => { this.clearAll() }) } private registerDefaultRepeaters() { for (const {type, repeater} of DEFAULT_REPEATERS) { this.repeaters.set(type, repeater) } } private clearAll() { this.itemIDToTasks.clear() this.projectedSessions.clear() this.estimatedDoneDates.clear() this.effectiveProgress.clear() this.freeTimeInfo.clear() this.taskProblems.clear() this.itemDueDateMap.clear() this.alerts = [] } private processDataStore() { // TODO use web worker // Clean-up // TODO make this less bug prone by making each subroutine return things // instead of writing to a shared state inside the analyzer this.clearAll() // Caching auxiliary info const currentDate = this.dataStore.getCurrentDayID() const maxProjectionEndDate = currentDate + this.maxProjectionRange const effectiveInfoCache = this.dataStore.getAllEffectiveInfo() const postOrderIndices = this.dataStore.getPostOrderIndices() // const parentChains = this.cacheParentChains() const quotaInfo = this.dataStore.getQuota(currentDate, maxProjectionEndDate) const sessionSlots = this.cacheSessionSlots( quotaInfo, currentDate, maxProjectionEndDate) // Generate tasks this.generateTasks( effectiveInfoCache, currentDate, maxProjectionEndDate) const tasks: Task[] = [] this.itemIDToTasks.forEach(list => { for (let i = 0; i < list.length; i++) { tasks.push(list[i]) } }) this.updateDueDates(tasks) // console.log(tasks) // TODO remove me // Track progress. Modifies tasks in-place this.computeProgress(tasks, currentDate, maxProjectionEndDate) // Compute effective progress this.computeEffectiveProgress(this.itemIDToTasks) // Generate projections. Modifies projections. this.generateProjections( this.itemIDToTasks, postOrderIndices, sessionSlots, currentDate, maxProjectionEndDate, ) // Estimate done dates this.estimateDoneDates(this.itemIDToTasks, this.projectedSessions.get(AnalyzerProjectionStrategy.FORWARD)!, currentDate, maxProjectionEndDate, ) // Compute free time this.computeFreeTimeInfo( this.projectedSessions.get(AnalyzerProjectionStrategy.BACKWARD)!, quotaInfo, sessionSlots, currentDate, maxProjectionEndDate, this.freeTimeInfo, ) // Compute alerts this.computeAlerts( this.taskProblems, effectiveInfoCache, this.effectiveProgress, currentDate, ) // Finalize this.currentDataStoreState = this.dataStore.state this.onChangeSubject.next(this) } private computeProgress(tasks: Task[], currentDate: DayID, maxProjectionEndDate: DayID) { const doneCounter = new Counter<ItemID>() const pastDoneCounter = new Counter<ItemID>() const plannedCounter = new Counter<ItemID>() // TODO improve this const earliestDayID = this.dataStore.state.timelineData.getEarliestDayID() if (earliestDayID === undefined) { // There is no record at all. tasks.forEach(task => { task.progress = 0 task.plannedProgress = 0 }) return } interface Endpoint { task: Task doneCount: number pastDoneCount: number plannedCount: number dayID: DayID startEndpoint?: Endpoint // If undefined, this endpoint is a due date // endpoint } // Start of search range let searchStartDayID: number | undefined = undefined let endpoints: Endpoint[] = [] let count = tasks.length for (let i = 0; i < count; i++) { const task = tasks[i] const end = task.end === undefined ? maxProjectionEndDate : task.end const startDayID = task.start === undefined ? Math.min(earliestDayID, end) : task.start if (searchStartDayID === undefined || startDayID < searchStartDayID) { searchStartDayID = startDayID } const startEndpoint = { doneCount: 0, pastDoneCount: 0, plannedCount: 0, dayID: startDayID, task, } endpoints.push(startEndpoint) endpoints.push({ doneCount: 0, pastDoneCount: 0, plannedCount: 0, dayID: end + 1, // Note that we add 1 here so the due date // endpoint comes after counting the progress on // the due date. startEndpoint, task, }) } endpoints.sort((a, b) => a.dayID - b.dayID) let ptr = searchStartDayID === undefined ? earliestDayID : Math.max(searchStartDayID, earliestDayID) count = endpoints.length for (let i = 0; i < count; i++) { const endpoint = endpoints[i] // TODO optimize: maybe use map key access to skip over empty day data while (ptr < endpoint.dayID) { const dayData = this.dataStore.getDayData(ptr) dayData.sessions.get(SessionType.COMPLETED) ?.forEach((count, itemID) => { if (ptr < currentDate) { pastDoneCounter.add(itemID, count) } doneCounter.add(itemID, count) plannedCounter.add(itemID, count) }) if (ptr >= currentDate) { // Past scheduled sessions do not count as planned progress dayData.sessions.get(SessionType.SCHEDULED) ?.forEach((count, itemID) => { plannedCounter.add(itemID, count) }) } ptr++ } if (endpoint.startEndpoint !== undefined) { endpoint.task.progress = doneCounter.get(endpoint.task.itemID) - endpoint.startEndpoint.doneCount endpoint.task.pastProgress = pastDoneCounter.get(endpoint.task.itemID) - endpoint.startEndpoint.pastDoneCount endpoint.task.plannedProgress = plannedCounter.get(endpoint.task.itemID) - endpoint.startEndpoint.plannedCount } else { endpoint.doneCount = doneCounter.get(endpoint.task.itemID) endpoint.pastDoneCount = pastDoneCounter.get(endpoint.task.itemID) endpoint.plannedCount = plannedCounter.get(endpoint.task.itemID) } } } /** * NOTE: The tasks are generated in due date order per each item */ private generateTasks(effectiveInfoCache: Map<ItemID, EffectiveItemInfo>, currentDate: DayID, maxProjectionEndDate: DayID) { this.dataStore.state.items.forEach(item => { this.generateFirstTaskForItem( item, effectiveInfoCache, this.itemIDToTasks) }) this.dataStore.state.items.forEach(item => { const tasks = this.itemIDToTasks.get(item.id) if (tasks === undefined || tasks.length === 0) return this.generateRepeatedTasksForItem( item, tasks[0], effectiveInfoCache, currentDate, maxProjectionEndDate, this.itemIDToTasks, ) }) } private generateFirstTaskForItem(item: Item, effectiveInfoCache: Map<ItemID, EffectiveItemInfo>, result: Map<ItemID, Task[]>) { const itemInfo = effectiveInfoCache.get(item.id) if (itemInfo === undefined) return const firstTask = { itemID: item.id, cost: item.residualCost, start: itemInfo.deferDate, end: itemInfo.dueDate, inactive: item.status === ItemStatus.COMPLETED, } if (firstTask.start !== undefined && firstTask.end !== undefined) { firstTask.start = Math.min(firstTask.start, firstTask.end) } getOrCreate(result, item.id, EMPTY_LIST_CREATOR).push(firstTask) } private generateRepeatedTasksForItem(item: Item, firstTask: Task, effectiveInfoCache: Map<ItemID, EffectiveItemInfo>, currentDate: DayID, maxProjectionEndDate: DayID, result: Map<ItemID, Task[]>) { const itemInfo = effectiveInfoCache.get(item.id) if (itemInfo === undefined) return if (itemInfo.repeat === undefined || itemInfo.hasAncestorRepeat || firstTask.end === undefined) { // Cannot self repeat return } // if (itemInfo.repeat === undefined || // (!itemInfo.hasActiveAncestorRepeat && // item.status === ItemStatus.COMPLETED)) { // return // } const repeater = this.repeaters.get(itemInfo.repeat.type) if (repeater === undefined) { console.log( `WARNING: Repeater for repeat type ${itemInfo.repeat.type} not found`) return } const r = repeater(firstTask, itemInfo, maxProjectionEndDate) const subtree = this.dataStore.getSubtreeItems(item.id) const subtreeInfo: SubtreeRepetitionInfo[] = [] const count = subtree.length for (let i = 0; i < count; i++) { const subtreeItemID = subtree[i] const subtreeItem = this.dataStore.getItem(subtreeItemID) if (subtreeItem === undefined) continue const subtreeItemInfo = this.dataStore.getRelativeEffectiveDateRange( subtreeItem, item.id) if (subtreeItemID === item.id) { // Is root item const startOffset = subtreeItem.repeatDeferOffset === undefined ? undefined : subtreeItem.repeatDeferOffset const endOffset = 0 subtreeInfo.push({ itemID: subtreeItemID, startOffset, endOffset, }) } else { const startOffset = subtreeItemInfo.deferDate === undefined ? undefined : firstTask.end - subtreeItemInfo.deferDate const endOffset = subtreeItemInfo.dueDate === undefined ? 0 : firstTask.end - subtreeItemInfo.dueDate subtreeInfo.push({ itemID: subtreeItemID, startOffset, endOffset, }) } } while (true) { const nextTask = r() if (nextTask === undefined) break // Skip tasks ending before today if (!(nextTask.end === undefined || nextTask.end >= currentDate)) { continue } const repetitionResults = generateSubtreeRepetition( nextTask, item.id, subtreeInfo) // if (subtreeInfo.length === 1) { // No children // getOrCreate(result, item.id, EMPTY_LIST_CREATOR).push(nextTask) // } const numResults = repetitionResults.length for (let i = 0; i < numResults; ++i) { const repResult = repetitionResults[i] const subtreeItem = this.dataStore.getItem(repResult.itemID) if (subtreeItem === undefined) continue getOrCreate(result, subtreeItem.id, EMPTY_LIST_CREATOR).push({ itemID: subtreeItem.id, cost: subtreeItem.residualCost, start: repResult.deferDate === undefined ? nextTask.start : optionalClamp(repResult.deferDate, nextTask.start, nextTask.end), end: repResult.dueDate === undefined ? nextTask.end : optionalClamp(repResult.dueDate, nextTask.start, nextTask.end), }) } } } private isUpToDate() { return this.currentDataStoreState === this.dataStore.state } getTasks(itemID: ItemID): Task[] | undefined { if (!this.dataStore.hasItem(itemID)) { return undefined } return this.itemIDToTasks.get(itemID) } getProjections(strategy: AnalyzerProjectionStrategy, dayID: DayID): Map<ItemID, number> | undefined { const result = this.projectedSessions.get(strategy)?.get(dayID) if (result === undefined) return undefined let invalidItemIDs: number[] | null = null result.forEach((_, itemID) => { if (!this.dataStore.hasItem(itemID)) { if (invalidItemIDs === null) invalidItemIDs = [] invalidItemIDs.push(itemID) } }) if (invalidItemIDs !== null) { // NOTE: There's a compiler issue forcing the use of ! here. invalidItemIDs!.forEach(itemID => result.delete(itemID)) } return result } getEstimatedDoneDate(itemID: ItemID): DayID | undefined { if (!this.dataStore.hasItem(itemID)) { return undefined } return this.estimatedDoneDates.get(itemID) } getFreeTimeInfo() { return this.freeTimeInfo } getTaskProblems(itemID: ItemID): TaskProblem[] | undefined { if (!this.dataStore.hasItem(itemID)) { return undefined } return this.taskProblems.get(itemID) } getEffectiveProgress(itemID: ItemID): number | undefined { if (!this.dataStore.hasItem(itemID)) { return undefined } return this.effectiveProgress.get(itemID) } getAlerts(): Alert[] { if (!this.isUpToDate()) { return [] } return this.alerts } isItemDueOn(itemID: ItemID, dayID: DayID) { const set = this.itemDueDateMap.get(dayID) if (set === undefined) return false return set.has(itemID) } private generateProjections(itemIDToTasks: Map<ItemID, Task[]>, postOrderIndices: Map<ItemID, number>, sessionSlots: Map<DayID, number>, currentDate: DayID, maxProjectionEndDate: DayID) { const existingPriorityProxiesMap = arrayToMap( this.dataStore.computeQueuePriorityProxies( this.dataStore.state.queue, postOrderIndices, ), item => item.itemID, item => item.priorityProxy) const taskInfoList: TaskSchedulingInfo[] = [] const taskInfoEndpoints: TaskSchedulingEndpoint[] = [] itemIDToTasks.forEach((tasks, itemID) => { let isFirstTask = true const size = tasks.length for (let i = 0; i < size; ++i) { const task = tasks[i] if (task.inactive) { isFirstTask = false continue } const existingPriorityProxy = existingPriorityProxiesMap.get(itemID) const taskInfo: TaskSchedulingInfo = { itemID, task, priorityProxy: isFirstTask && existingPriorityProxy !== undefined ? existingPriorityProxy : getQueuePriorityProxy(task.end, postOrderIndices.get(itemID) || 0), unplannedCost: Math.max(0, task.cost - (task.plannedProgress || 0)), } taskInfoList.push(taskInfo) // Left endpoint taskInfoEndpoints.push({ taskInfo, dayID: task.start === undefined ? NEG_INF_DAY_ID : task.start, isEnd: false, }) // Right endpoint taskInfoEndpoints.push({ taskInfo, dayID: task.end === undefined ? INF_DAY_ID : task.end + 1, isEnd: true, }) isFirstTask = false } }) taskInfoEndpoints.sort((a, b) => { return a.dayID - b.dayID }) const forwardStrategy = new GreedyProjectionStrategy(false) const forwardResult = forwardStrategy.generate( currentDate, maxProjectionEndDate, taskInfoList, taskInfoEndpoints, sessionSlots, ) this.projectedSessions.set( AnalyzerProjectionStrategy.FORWARD, forwardResult.sessions) // console.log(taskInfoEndpoints) // TODO remove me const backwardStrategy = new GreedyProjectionStrategy(true) const backwardResult = backwardStrategy.generate( currentDate, maxProjectionEndDate, taskInfoList, taskInfoEndpoints, sessionSlots, ) this.projectedSessions.set( AnalyzerProjectionStrategy.BACKWARD, backwardResult.sessions) // Collecting task problems const impossibleByQueue = new Set<Task>(forwardResult.impossibleTasks) const impossibleByLate = new Set<Task>(backwardResult.impossibleTasks) itemIDToTasks.forEach(tasks => { tasks.forEach(task => { let problemType: TaskProblemType | null = null if (impossibleByLate.has(task)) { problemType = TaskProblemType.IMPOSSIBLE_BY_LATE } else if (impossibleByQueue.has(task)) { problemType = TaskProblemType.IMPOSSIBLE_BY_QUEUE } if (problemType !== null) { getOrCreate( this.taskProblems, task.itemID, (EMPTY_LIST_CREATOR as () => TaskProblem[]), ).push({ task, type: problemType, }) } }) }) } private estimateDoneDates(itemIDToTasks: Map<ItemID, Task[]>, projectedSessions: Map<DayID, Map<ItemID, number>>, currentDate: DayID, maxProjectionEndDate: DayID) { const progressCounter = new Counter<ItemID>() interface Endpoint { task: Task dayID: DayID isEnd: boolean } let endpoints: Endpoint[] = [] const itemIDToFirstTask = new Map<ItemID, Task>() const firstTaskActive = new Set<ItemID>() itemIDToTasks.forEach((tasks, itemID) => { if (tasks.length > 0) { const task = tasks[0] itemIDToFirstTask.set(itemID, tasks[0]) progressCounter.add(itemID, task.pastProgress || 0) const start = task.start === undefined ? currentDate : task.start const end = task.end === undefined ? maxProjectionEndDate : task.end endpoints.push({ dayID: start, task, isEnd: false, }) endpoints.push({ dayID: end + 1, // Note that we add 1 here so the due date // endpoint comes after counting the progress on // the due date. task, isEnd: true, }) } }) endpoints.sort((a, b) => a.dayID - b.dayID) let ptr = currentDate const processSession = (count: number, itemID: ItemID) => { if (!firstTaskActive.has(itemID)) return progressCounter.add(itemID, count) const currentCount = progressCounter.get(itemID) const firstTask = itemIDToFirstTask.get(itemID) if (firstTask !== undefined && currentCount >= firstTask.cost && !this.estimatedDoneDates.has(itemID)) { this.estimatedDoneDates.set(itemID, ptr) } } const count = endpoints.length for (let i = 0; i < count; i++) { const endpoint = endpoints[i] // TODO optimize: maybe use map key access to skip over empty day data while (ptr < endpoint.dayID) { const dayData = this.dataStore.getDayData(ptr) dayData.sessions.get(SessionType.COMPLETED)?.forEach(processSession) dayData.sessions.get(SessionType.SCHEDULED)?.forEach(processSession) projectedSessions.get(ptr)?.forEach(processSession) ptr++ } if (endpoint.isEnd) { firstTaskActive.delete(endpoint.task.itemID) } else { firstTaskActive.add(endpoint.task.itemID) } } this.dataStore.state.rootItemIDs.forEach(itemID => { this.computeEffectiveDoneDates(itemID) }) } private computeEffectiveDoneDates(itemID: ItemID) { const item = this.dataStore.getItem(itemID) if (item === undefined) return const numChildren = item.childrenIDs.length let doneDate = this.estimatedDoneDates.get(itemID) for (let i = 0; i < numChildren; i++) { const childID = item.childrenIDs[i] this.computeEffectiveDoneDates(childID) const childDoneDate = this.estimatedDoneDates.get(childID) if (childDoneDate === undefined) continue if (doneDate === undefined) { doneDate = childDoneDate } else { doneDate = Math.max(doneDate, childDoneDate) } } if (doneDate !== undefined) { this.estimatedDoneDates.set(itemID, doneDate) } } /** * @deprecated */ private cacheParentChains() { // TODO optimize with DFS, and try not to access done tasks? const result = new Map<ItemID, ItemID[]>() this.dataStore.state.items.forEach(item => { if (!result.has(item.id)) { result.set(item.id, this.dataStore.getAncestorsPlusSelf(item.id)) } }) return result } /** * Cache the unused quota of each day. All types of sessions (except * projection) count as using the quota. */ private cacheSessionSlots(quotaInfo: Map<DayID, number>, currentDate: DayID, maxProjectionEndDate: DayID) { const result = new Map<DayID, number>() for (let d = currentDate; d <= maxProjectionEndDate; ++d) { const dayData = this.dataStore.getDayData(d) let quota = quotaInfo.get(d) || 0 dayData.sessions.forEach(sessions => { sessions.forEach(count => { quota = Math.max(0, quota - count) }) }) result.set(d, quota) } return result } private computeFreeTimeInfo(projectedSessions: Map<DayID, Map<ItemID, number>>, quotaInfo: Map<DayID, number>, sessionSlots: Map<DayID, number>, currentDate: DayID, maxProjectionEndDate: DayID, result: FreeTimeInfo) { const rangeStart = currentDate // TODO change the hard-coded 30 days const rangeEnd = Math.min( rangeStart + MAX_QUOTA_PERIOD - 1, maxProjectionEndDate) let bestRatio = -1 let totalQuota = 0 let freeQuota = 0 let totalQuotaExcludingFirst = 0 let freeQuotaExcludingFirst = 0 let bestTotalQuota = 0 let bestFreeQuota = 0 for (let d = rangeStart; d <= rangeEnd; ++d) { const quota = (quotaInfo.get(d) || 0) let usedQuota = 0 totalQuota += quota if (d > rangeStart) { totalQuotaExcludingFirst += quota } usedQuota += quota - (sessionSlots.get(d) || 0) const sessionsOfDay = projectedSessions.get(d) if (sessionsOfDay !== undefined) { sessionsOfDay.forEach(count => { usedQuota += count }) } freeQuota += Math.max(0, quota - usedQuota) if (d > rangeStart) { freeQuotaExcludingFirst += Math.max(0, quota - usedQuota) } const ratio = totalQuotaExcludingFirst === 0 ? 0 : (freeQuotaExcludingFirst / totalQuotaExcludingFirst) if (d - rangeStart + 1 >= MIN_QUOTA_PERIOD && (bestRatio < 0 || ratio < bestRatio)) { bestRatio = ratio bestTotalQuota = totalQuota bestFreeQuota = freeQuota result.quotaPeriod = d - rangeStart + 1 } } result.totalQuota = bestTotalQuota result.freeQuota = bestFreeQuota // TODO change the hard-coded 7 days const pastDays = 7 result.lastWeekDailyCompletion = 0 for (let i = 1; i <= pastDays; ++i) { const d = currentDate - i const dayData = this.dataStore.getDayData(d) dayData.sessions.forEach(sessions => { sessions.forEach(count => { result.lastWeekDailyCompletion += count }) }) } result.lastWeekDailyCompletion /= pastDays } private computeEffectiveProgress(itemIDToTasks: Map<ItemID, Task[]>) { this.dataStore.state.rootItemIDs.forEach(itemID => { this.computeEffectiveProgressInternal(itemID, itemIDToTasks) }) } /** * Return the contribution to parent's effective progress. */ private computeEffectiveProgressInternal(itemID: ItemID, itemIDToTasks: Map<ItemID, Task[]>): number { const item = this.dataStore.getItem(itemID) if (item === undefined) return 0 const numChildren = item.childrenIDs.length let tasks = this.itemIDToTasks.get(itemID) let progress = (tasks !== undefined && tasks.length > 0) ? (tasks[0].progress || 0) : 0 for (let i = 0; i < numChildren; i++) { const childID = item.childrenIDs[i] const childContribution = this.computeEffectiveProgressInternal( childID, itemIDToTasks) progress += childContribution } this.effectiveProgress.set(itemID, progress) if (item.status === ItemStatus.COMPLETED) { return item.effectiveCost } return Math.min(progress, item.effectiveCost) } private computeAlerts(taskProblems: Map<ItemID, TaskProblem[]>, effectiveInfoCache: Map<ItemID, EffectiveItemInfo>, effectiveProgress: Map<ItemID, number>, currentDate: DayID) { // Task problems taskProblems.forEach(problems => { problems.forEach(problem => { let alertType: string | undefined = undefined let icon: string | undefined = undefined if (problem.type === TaskProblemType.IMPOSSIBLE_BY_QUEUE) { alertType = 'taskConflict' icon = 'warning' } else if (problem.type === TaskProblemType.IMPOSSIBLE_BY_LATE) { alertType = 'taskImpossible' icon = 'error' } else { return } const alert: Alert = { color: 'warn', icon: icon, type: alertType, data: { itemID: problem.task.itemID, task: problem.task, }, actions: [ EDIT_ITEM_ACTION, SHOW_IN_ITEMS_ACTION, SHOW_IN_QUEUE_ACTION, ], } this.alerts.push(alert) }) }) // Item cost completed or overdue this.dataStore.state.items.forEach(item => { const progress = effectiveProgress.get(item.id) || 0 if (item.status !== ItemStatus.COMPLETED) { if (item.effectiveCost > 0 && progress >= item.effectiveCost) { const alert: Alert = { color: 'primary', icon: 'check_circle_outline', type: 'itemCostCompleted', data: { itemID: item.id, }, actions: [ MARK_ITEM_COMPLETE_ACTION, EDIT_ITEM_ACTION, SHOW_IN_ITEMS_ACTION, SHOW_IN_QUEUE_ACTION, ], } this.alerts.push(alert) } const info = effectiveInfoCache.get(item.id) if (info !== undefined && info.dueDate !== undefined && info.dueDate < currentDate) { const alert: Alert = { color: 'warn', icon: 'alarm', type: 'itemOverdue', data: { itemID: item.id, dueDate: info.dueDate, }, actions: [ MARK_ITEM_COMPLETE_ACTION, EDIT_ITEM_ACTION, SHOW_IN_ITEMS_ACTION, SHOW_IN_QUEUE_ACTION, ], } this.alerts.push(alert) } } }) } private updateDueDates(tasks: Task[]) { tasks.forEach(task => { if (task.end !== undefined) { getOrCreate(this.itemDueDateMap, task.end, () => new Set<ItemID>()) .add(task.itemID) } }) } }
the_stack
// TODO: Spatial type type Spatial = any; interface SerializedMap { name: string; mapID: number; numLevels: number; mapScript: /* SerializedScript */ any; objects: /* SerializedObj */ any[][]; spatials: /* SerializedSpatial */ any[][]; floorMap: string[][]; roofMap: string[][]; mapObj: any; // required? } class GameMap { name: string = null; startingPosition: Point; startingElevation: number; numLevels: number; currentElevation: number = 0 // current map elevation floorMap: string[][] = null // Floor tilemap roofMap: string[][] = null // Roof tilemap mapScript: any = null; // Current map script object objects: Obj[][] = null; // Map objects on all levels spatials: any[][] = null; // Spatials on all levels mapObj: any = null; mapID: number; getObjects(level?: number): Obj[] { return this.objects[level === undefined ? this.currentElevation : level] } getSpatials(level?: number): any[] { return this.spatials[level === undefined ? this.currentElevation : level] } getObjectsAndSpatials(level?: number): Obj[] { return this.getObjects().concat(this.getSpatials()) } addObject(obj: Obj, level?: number): void { this.objects[level === undefined ? this.currentElevation : level].push(obj) } removeObject(obj: Obj): void { // remove `obj` from the map // it would be pretty hard to remove it anywhere else without either // a walk of the object graph or a `parent` reference. // // so we're only going to remove it from the global object list, if present. // TODO: use a removal queue instead of removing directory (indexing problems) // TODO: better object equality testing for(var level = 0; level < this.numLevels; level++) { var objects = this.objects[level] for(var i = 0; i < objects.length; i++) { if(objects[i] === obj) { console.log("removeObject: destroying index %d (%o/%o)", i, obj, objects[i]) this.objects[level].splice(i, 1) return } } } console.log("removeObject: couldn't find object on map") console.trace() } destroyObject(obj: Obj): void { this.removeObject(obj) // TODO: notify scripts with destroy_p_proc } hasRoofAt(pos: Point, elevation?: number): boolean { if(elevation === undefined) elevation = this.currentElevation; const tilePos = hexToTile(pos); return this.mapObj.levels[elevation].tiles.roof[tilePos.y][tilePos.x] !== "grid000"; } updateMap(): void { Scripting.updateMap(this.mapScript, this.getObjectsAndSpatials(), this.currentElevation) } changeElevation(level: number, updateScripts: boolean=false, isMapLoading: boolean=false) { var oldElevation = this.currentElevation this.currentElevation = level currentElevation = level // TODO: Get rid of this global this.floorMap = this.mapObj.levels[level].tiles.floor this.roofMap = this.mapObj.levels[level].tiles.roof //this.spatials = this.mapObj.levels[level]["spatials"] // If we're in combat, end it since we're moving off of that elevation if(inCombat) combat.end(); player.clearAnim(); // Remove player & party (unless we're loading a new map, in which case they're not present) // and place them on the new map for(const obj of gParty.getPartyMembersAndPlayer()) { if(!isMapLoading) arrayRemove(this.objects[oldElevation], obj); // Only add the member once, in case changeElevation is called multiple times if(this.objects[level].indexOf(obj) === -1) this.objects[level].push(obj); } this.placeParty(); // set up renderer data renderer.initData(this.roofMap, this.floorMap, this.getObjects()) if(updateScripts) { // TODO: we need some kind of active/inactive flag on scripts to toggle here, // since scripts should already be loaded //loadObjectScripts(gObjects) Scripting.updateMap(this.mapScript, this.getObjectsAndSpatials(), level) } // rebuild the lightmap if(Config.engine.doFloorLighting) { Lightmap.resetLight() Lightmap.rebuildLight() } centerCamera(player.position) Events.emit("elevationChanged", { elevation: level, oldElevation, isMapLoading }) } placeParty() { // set up party members' positions gParty.getPartyMembers().forEach((obj: Critter) => { // attempt party member placement around player var placed = false for(var dist = 1; dist < 3; dist++) { for(var dir = 0; dir < 6; dir++) { var pos = hexInDirectionDistance(player.position, dir, dist) if(objectsAtPosition(pos).length === 0) { obj.position = pos console.log("placed %o @ %o", obj, pos) placed = true break } } if(placed) break } if(!placed) console.log("couldn't place %o (player position: %o)", obj, player.position) }) } doEnterNewMap(isFirstRun: boolean): void { // Tell scripts they've entered the new map const objectsAndSpatials = this.getObjectsAndSpatials() const overridenStartPos = Scripting.enterMap(this.mapScript, objectsAndSpatials, this.currentElevation, this.mapID, isFirstRun) if(overridenStartPos) { // Starting position was overridden by map_enter_p_proc -- use the new one console.log("Starting position overriden to %o", overridenStartPos) player.position = overridenStartPos.position player.orientation = overridenStartPos.orientation this.currentElevation = currentElevation = overridenStartPos.elevation } // place party again, so if the map script overrided the start position we're in the right place this.placeParty() // Tell objects' scripts that they're now on the map // TODO: Does this apply to all levels or just the current elevation? this.objects.forEach(level => level.forEach(obj => obj.enterMap())) this.spatials.forEach(level => level.forEach(spatial => Scripting.objectEnterMap(spatial, this.currentElevation, this.mapID))) Scripting.updateMap(this.mapScript, objectsAndSpatials, this.currentElevation) } loadMap(mapName: string, startingPosition?: Point, startingElevation: number=0, loadedCallback?: () => void): void { if(Config.engine.doSaveDirtyMaps && this.name !== null) { // if a map is already loaded, save it to the dirty map cache before loading console.log(`[Main] Serializing map ${this.name} and committing to dirty map cache`); dirtyMapCache[this.name] = this.serialize(); } if(mapName in dirtyMapCache) { // Previously loaded; load from dirty map cache console.log(`[Main] Loading map ${mapName} from dirty map cache`); Events.emit("loadMapPre"); const map = dirtyMapCache[mapName]; this.deserialize(map); // Set position and orientation if(startingPosition !== undefined) player.position = startingPosition; else // Use default map starting position player.position = map.mapObj.startPosition; player.orientation = map.mapObj.startOrientation; // Set elevation this.currentElevation = currentElevation = startingElevation; // Change to our new elevation (sets up map state) this.changeElevation(this.currentElevation, false, true); // Enter map this.doEnterNewMap(false); // Change elevation again this.changeElevation(this.currentElevation, true, false); // Done console.log(`[Main] Loaded from dirty map cache`); loadedCallback && loadedCallback(); Events.emit("loadMapPost"); } else { console.log(`[Main] Loading map ${mapName} from clean load`); this.loadNewMap(mapName, startingPosition, startingElevation, loadedCallback); } } loadNewMap(mapName: string, startingPosition?: Point, startingElevation?: number, loadedCallback?: () => void) { function load(file: string, callback?: (x:any) => void) { if(images[file] !== undefined) return // don't load more than once loadingAssetsTotal++ heart.graphics.newImage(file+".png", (r: HeartImage) => { images[file] = r loadingAssetsLoaded++ if(callback) callback(r) }) } this.name = mapName.toLowerCase() Events.emit("loadMapPre"); isLoading = true loadingAssetsTotal = 1 // this will remain +1 until we load the map, preventing it from exiting early loadingAssetsLoaded = 0 loadingLoadedCallback = loadedCallback || null // clear any previous objects/events this.objects = null this.mapScript = null Scripting.reset(this.name) // reset player animation status (to idle) player.clearAnim() console.log("loading map " + mapName) var mapImages = getFileJSON("maps/" + mapName + ".images.json") for(var i = 0; i < mapImages.length; i++) load(mapImages[i]) console.log("loading " + mapImages.length + " images") var map = getFileJSON("maps/"+mapName+".json") this.mapObj = map this.mapID = map.mapID this.numLevels = map.levels.length var elevation = (startingElevation !== undefined) ? startingElevation : 0 if(Config.engine.doLoadScripts) { Scripting.init(mapName) try { this.mapScript = Scripting.loadScript(mapName) Scripting.setMapScript(this.mapScript) } catch(e) { this.mapScript = null console.log("ERROR LOADING MAP SCRIPT:", e.message) } } else this.mapScript = null // warp to the default position (may be overridden by map script) player.position = startingPosition || map.startPosition player.orientation = map.startOrientation if(Config.engine.doSpatials) { this.spatials = map.levels.map((level: any) => level.spatials) if(Config.engine.doLoadScripts) { // initialize spatial scripts this.spatials.forEach((level: any) => level.forEach((spatial: Spatial) => { var script = Scripting.loadScript(spatial.script) if(script === null) console.log("load script failed for spatial " + spatial.script) else { spatial._script = script // no need to initialize here because spatials only use spatial_p_proc } spatial.isSpatial = true spatial.position = fromTileNum(spatial.tileNum) })) } } else // TODO: Spatial type this.spatials = map.levels.map((_: any) => [] as Spatial[]) // Load map objects. Note that these need to be loaded *after* the map so that object scripts // have access to the map script object. this.objects = new Array(map.levels.length) for(var level = 0; level < map.levels.length; level++) { this.objects[level] = map.levels[level].objects.map((obj: any) => objFromMapObject(obj)) } // change to our new elevation (sets up map state) this.changeElevation(elevation, false, true) // TODO: when exactly are these called? // TODO: when objectsAndSpatials is updated, the scripting engine won't know var objectsAndSpatials = this.getObjectsAndSpatials() if(Config.engine.doLoadScripts) { // party member NPCs get the new map script gParty.getPartyMembers().forEach((obj: Critter) => { obj._script._mapScript = this.mapScript }) this.doEnterNewMap(true) elevation = this.currentElevation // change elevation with script updates this.changeElevation(this.currentElevation, true, true) } // TODO: is map_enter_p_proc called on elevation change? console.log("loaded (" + map.levels.length + " levels, " +this.getObjects().length + " objects on elevation " + elevation + ")") // load some testing art load("art/critters/hmjmpsat") load("hex_outline", (r: any) => { hexOverlay = r }) loadingAssetsTotal-- // we should know all of the assets we need by now // clear audio and use the map music var curMapInfo = getCurrentMapInfo() audioEngine.stopAll() if(curMapInfo && curMapInfo.music) audioEngine.playMusic(curMapInfo.music) Events.emit("loadMapPost"); } loadMapByID(mapID: number, startingPosition?: Point, startingElevation?: number): void { var mapName = lookupMapName(mapID) if(mapName !== null) this.loadMap(mapName, startingPosition, startingElevation) else console.log("couldn't lookup map name for map ID " + mapID) } serialize(): SerializedMap { return { name: this.name, mapID: this.mapID, numLevels: this.numLevels, mapObj: { levels: this.mapObj.levels.map((level: any) => ({tiles: level.tiles})) , startPosition: this.mapObj.startPosition , startOrientation: this.mapObj.startOrientation }, // roof/floor maps roofMap: this.roofMap, floorMap: this.floorMap, mapScript: this.mapScript ? this.mapScript._serialize() : null, objects: this.objects.map((level: Obj[]) => arrayWithout(level, player).map(obj => obj.serialize())), // TODO: Should be without entire party? spatials: null //this.spatials.map(level => level.map(spatial:> spatial.serialize())) } } deserialize(obj: SerializedMap): void { this.name = obj.name this.mapID = obj.mapID this.numLevels = obj.numLevels this.mapObj = obj.mapObj this.mapScript = obj.mapScript ? Scripting.deserializeScript(obj.mapScript) : null this.objects = obj.objects.map(level => level.map(obj => deserializeObj(obj))) this.spatials = [[],[],[]] //obj.spatials // TODO: deserialize this.roofMap = obj.roofMap this.floorMap = obj.floorMap this.currentElevation = 0 // TODO //this.mapObj = {levels: [{tiles: {floor: this.floorMap, roof: this.roofMap}}]} // TODO: add dimension to roofMap // TODO: reset scriptingEngine? } }
the_stack
import { generateProof } from '@/invitation' import * as keysets from 'crdx' import * as teams from '@/team' import { setup } from '@/util/testing' import { createKeyset } from 'crdx' const { USER, DEVICE } = keysets.KeyType describe('Team', () => { describe('invitations', () => { describe('members', () => { it('accepts valid proof of invitation', () => { const { alice, bob } = setup('alice', { user: 'bob', member: false }) // 👩🏾 Alice invites 👨🏻‍🦲 Bob by sending him a random secret key const { seed } = alice.team.inviteMember() // 👨🏻‍🦲 Bob accepts the invitation const proofOfInvitation = generateProof(seed) // 👨🏻‍🦲 Bob shows 👩🏾 Alice his proof of invitation, and she lets him in, associating // him with the public keys he's provided alice.team.admitMember(proofOfInvitation, bob.user.keys) // ✅ 👨🏻‍🦲 Bob is now on the team. Congratulations, Bob! expect(alice.team.has('bob')).toBe(true) }) it('lets you use a key of your choosing', () => { const { alice, bob } = setup('alice', { user: 'bob', member: false }) // 👩🏾 Alice invites 👨🏻‍🦲 Bob by sending him a secret key of her choosing const seed = 'passw0rd' alice.team.inviteMember({ seed }) const proofOfInvitation = generateProof(seed) alice.team.admitMember(proofOfInvitation, bob.user.keys) // ✅ Still works expect(alice.team.has('bob')).toBe(true) }) it('normalizes the secret key', () => { const { alice, bob } = setup('alice', { user: 'bob', member: false }) // 👩🏾 Alice invites 👨🏻‍🦲 Bob const seed = 'abc def ghi' alice.team.inviteMember({ seed }) // 👨🏻‍🦲 Bob accepts the invitation using a url-friendlier version of the key const proofOfInvitation = generateProof('abc+def+ghi') alice.team.admitMember(proofOfInvitation, bob.user.keys) // ✅ Bob is on the team expect(alice.team.has('bob')).toBe(true) }) it('allows non-admins to accept an invitation', () => { let { alice, bob, charlie } = setup( 'alice', { user: 'bob', admin: false }, { user: 'charlie', member: false } ) // 👩🏾 Alice invites 👳🏽‍♂️ Charlie by sending him a secret key const { seed } = alice.team.inviteMember() // 👳🏽‍♂️ Charlie accepts the invitation const proofOfInvitation = generateProof(seed) // later, 👩🏾 Alice is no longer around, but 👨🏻‍🦲 Bob is online let persistedTeam = alice.team.save() const bobsTeam = teams.load(persistedTeam, bob.localContext) // just to confirm: 👨🏻‍🦲 Bob isn't an admin expect(bobsTeam.memberIsAdmin('bob')).toBe(false) // 👳🏽‍♂️ Charlie shows 👨🏻‍🦲 Bob his proof of invitation bobsTeam.admitMember(proofOfInvitation, charlie.user.keys) // 👍👳🏽‍♂️ Charlie is now on the team expect(bobsTeam.has('charlie')).toBe(true) // ✅ 👩🏾 Alice can now see that 👳🏽‍♂️ Charlie is on the team. Congratulations, Charlie! persistedTeam = bobsTeam.save() alice.team = teams.load(persistedTeam, alice.localContext) expect(alice.team.has('charlie')).toBe(true) }) it(`will use an invitation that hasn't expired yet`, () => { const { alice, bob } = setup('alice', { user: 'bob', member: false }) // 👩🏾 Alice invites 👨🏻‍🦲 Bob with a future expiration date const expiration = new Date(Date.UTC(2999, 12, 25)).valueOf() // NOTE 👩‍🚀 this test will fail if run in the distant future const { seed } = alice.team.inviteMember({ expiration }) const proofOfInvitation = generateProof(seed) alice.team.admitMember(proofOfInvitation, bob.user.keys) // ✅ 👨🏻‍🦲 Bob's invitation has not expired so he is on the team expect(alice.team.has('bob')).toBe(true) }) it(`won't use an expired invitation`, () => { const { alice, bob } = setup('alice', { user: 'bob', member: false }) // A long time ago 👩🏾 Alice invited 👨🏻‍🦲 Bob const expiration = new Date(Date.UTC(2020, 12, 25)).valueOf() const { seed } = alice.team.inviteMember({ expiration }) const proofOfInvitation = generateProof(seed) const tryToAdmitBob = () => alice.team.admitMember(proofOfInvitation, bob.user.keys) // 👎 👨🏻‍🦲 Bob's invitation has expired so he can't get in expect(tryToAdmitBob).toThrowError(/expired/) // ❌ 👨🏻‍🦲 Bob is not on the team expect(alice.team.has('bob')).toBe(false) }) it(`can use an invitation multiple times`, () => { const { alice, bob, charlie } = setup( 'alice', { user: 'bob', member: false }, { user: 'charlie', member: false } ) const { seed } = alice.team.inviteMember({ maxUses: 2 }) // 👨🏻‍🦲 Bob and 👳🏽‍♂️ Charlie both generate the same proof of invitation from the seed const proofOfInvitation = generateProof(seed) // 👩🏾 Alice admits them both alice.team.admitMember(proofOfInvitation, bob.user.keys) alice.team.admitMember(proofOfInvitation, charlie.user.keys) // ✅ 👨🏻‍🦲 Bob and 👳🏽‍♂️ Charlie are both on the team expect(alice.team.has('bob')).toBe(true) expect(alice.team.has('charlie')).toBe(true) }) it(`can use an invitation infinite uses when maxUses is zero`, () => { const { alice } = setup('alice') // 👩🏾 Alice makes an invitation that anyone can use const { seed } = alice.team.inviteMember({ maxUses: 0 }) // no limit const proofOfInvitation = generateProof(seed) // A bunch of people use the same invitation and 👩🏾 Alice admits them all const invitees = ` amanda, bob, charlie, dwight, edwin, frida, gertrude, herbert, ignaszi, joão, krishna, lashawn, mary, ngunda, oprah, phil, quân, rainbow, steve, thad, uriah, vanessa, wade, xerxes, yazmin, zelda` .replace(/\s/g, '') .split(',') for (const userName of invitees) { const userKeys = createKeyset({ type: USER, name: userName }) const deviceKeys = createKeyset({ type: DEVICE, name: `${userName}'s laptop` }) alice.team.admitMember(proofOfInvitation, userKeys) } // ✅ they're all on the team for (const userName of invitees) expect(alice.team.has(userName)).toBe(true) }) it(`won't use an invitation more than the maximum uses defined`, () => { const { alice, bob, charlie } = setup( 'alice', { user: 'bob', member: false }, { user: 'charlie', member: false } ) const { seed } = alice.team.inviteMember({ maxUses: 1 }) // 👨🏻‍🦲 Bob and 👳🏽‍♂️ Charlie both generate the same proof of invitation from the seed const proofOfInvitation = generateProof(seed) const tryToAdmitBob = () => alice.team.admitMember(proofOfInvitation, bob.user.keys) const tryToAdmitCharlie = () => alice.team.admitMember(proofOfInvitation, charlie.user.keys) // 👍 👨🏻‍🦲 Bob uses the invitation first and he gets in expect(tryToAdmitBob).not.toThrow() // 👎 👳🏽‍♂️ Charlie also tries to use the invitation, but it can only be used once expect(tryToAdmitCharlie).toThrow(/used/) // ✅ 👨🏻‍🦲 Bob is on the team expect(alice.team.has('bob')).toBe(true) // ❌ 👳🏽‍♂️ Charlie is not on the team expect(alice.team.has('charlie')).toBe(false) }) it(`won't use a revoked invitation`, () => { const { alice, bob, charlie } = setup( 'alice', { user: 'bob', admin: false }, { user: 'charlie', member: false } ) // 👩🏾 Alice invites 👳🏽‍♂️ Charlie by sending him a secret key const { seed, id } = alice.team.inviteMember() // 👳🏽‍♂️ Charlie accepts the invitation const proofOfInvitation = generateProof(seed) // 👩🏾 Alice changes her mind and revokes the invitation alice.team.revokeInvitation(id) // later, 👩🏾 Alice is no longer around, but 👨🏻‍🦲 Bob is online const persistedTeam = alice.team.save() bob.team = teams.load(persistedTeam, bob.localContext) // 👳🏽‍♂️ Charlie shows 👨🏻‍🦲 Bob his proof of invitation const tryToAdmitCharlie = () => bob.team.admitMember(proofOfInvitation, charlie.user.keys) // 👎 But the invitation is rejected because it was revoked expect(tryToAdmitCharlie).toThrowError(/revoked/) // ❌ 👳🏽‍♂️ Charlie is not on the team expect(bob.team.has('charlie')).toBe(false) }) }) describe('devices', () => { it('creates and accepts an invitation for a device', () => { const { alice } = setup('alice') // 👩🏾 Alice only has 💻 one device on the signature chain expect(alice.team.members('alice').devices).toHaveLength(1) // 💻 on her laptop, Alice generates an invitation for her phone const { seed } = alice.team.inviteDevice() // 📱 Alice gets the seed to her phone, perhaps by typing it in or by scanning a QR code. // Alice's phone uses the seed to generate her starter keys and her proof of invitation const proofOfInvitation = generateProof(seed) // 📱 Alice's phone connects with 💻 her laptop and presents the proof alice.team.admitDevice(proofOfInvitation, alice.phone) // 👍 The proof was good, so the laptop sends the phone the team's signature chain const savedTeam = alice.team.save() const phoneTeam = teams.load(savedTeam, alice.localContext) // 📱 Alice's phone joins the team phoneTeam.joinAsDevice('alice') // ✅ Now Alice has 💻📱 two devices on the signature chain expect(phoneTeam.members('alice').devices).toHaveLength(2) expect(alice.team.members('alice').devices).toHaveLength(2) }) it(`doesn't let someone else admit Alice's device`, () => { const { alice, bob } = setup('alice', 'bob') // 👩🏾 Alice only has 💻 one device on the signature chain expect(alice.team.members('alice').devices).toHaveLength(1) // 💻 on her laptop, Alice generates an invitation for her phone const { seed } = alice.team.inviteDevice() // 📱 Alice gets the seed to her phone, perhaps by typing it in or by scanning a QR code. // Alice's phone uses the seed to generate her starter keys and her proof of invitation const proofOfInvitation = generateProof(seed) // 👨🏻‍🦲 Bob syncs up with Alice const savedTeam = alice.team.save() bob.team = teams.load(savedTeam, bob.localContext) // 📱 Alice's phone connects with 👨🏻‍🦲 Bob and she presents the proof const tryToAdmitPhone = () => bob.team.admitDevice(proofOfInvitation, alice.phone) // ❌ Alice's phone can only present its invitation to one of Alice's other devices expect(tryToAdmitPhone).toThrow(`Can't admit someone else's device`) }) }) }) })
the_stack
import * as msRest from "@azure/ms-rest-js"; export const MultiLanguageInput: msRest.CompositeMapper = { serializedName: "MultiLanguageInput", type: { name: "Composite", className: "MultiLanguageInput", modelProperties: { language: { serializedName: "language", type: { name: "String" } }, id: { serializedName: "id", type: { name: "String" } }, text: { serializedName: "text", type: { name: "String" } } } } }; export const MultiLanguageBatchInput: msRest.CompositeMapper = { serializedName: "MultiLanguageBatchInput", type: { name: "Composite", className: "MultiLanguageBatchInput", modelProperties: { documents: { serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "MultiLanguageInput" } } } } } } }; export const MatchRecord: msRest.CompositeMapper = { serializedName: "MatchRecord", type: { name: "Composite", className: "MatchRecord", modelProperties: { wikipediaScore: { serializedName: "wikipediaScore", type: { name: "Number" } }, entityTypeScore: { serializedName: "entityTypeScore", type: { name: "Number" } }, text: { serializedName: "text", type: { name: "String" } }, offset: { serializedName: "offset", type: { name: "Number" } }, length: { serializedName: "length", type: { name: "Number" } } } } }; export const EntityRecord: msRest.CompositeMapper = { serializedName: "EntityRecord", type: { name: "Composite", className: "EntityRecord", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, matches: { serializedName: "matches", type: { name: "Sequence", element: { type: { name: "Composite", className: "MatchRecord" } } } }, wikipediaLanguage: { serializedName: "wikipediaLanguage", type: { name: "String" } }, wikipediaId: { serializedName: "wikipediaId", type: { name: "String" } }, wikipediaUrl: { readOnly: true, serializedName: "wikipediaUrl", type: { name: "String" } }, bingId: { serializedName: "bingId", type: { name: "String" } }, type: { serializedName: "type", type: { name: "String" } }, subType: { serializedName: "subType", type: { name: "String" } } } } }; export const DocumentStatistics: msRest.CompositeMapper = { serializedName: "DocumentStatistics", type: { name: "Composite", className: "DocumentStatistics", modelProperties: { charactersCount: { serializedName: "charactersCount", type: { name: "Number" } }, transactionsCount: { serializedName: "transactionsCount", type: { name: "Number" } } } } }; export const EntitiesBatchResultItem: msRest.CompositeMapper = { serializedName: "EntitiesBatchResultItem", type: { name: "Composite", className: "EntitiesBatchResultItem", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, entities: { readOnly: true, serializedName: "entities", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntityRecord" } } } }, statistics: { serializedName: "statistics", type: { name: "Composite", className: "DocumentStatistics" } } } } }; export const ErrorRecord: msRest.CompositeMapper = { serializedName: "ErrorRecord", type: { name: "Composite", className: "ErrorRecord", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const RequestStatistics: msRest.CompositeMapper = { serializedName: "RequestStatistics", type: { name: "Composite", className: "RequestStatistics", modelProperties: { documentsCount: { serializedName: "documentsCount", type: { name: "Number" } }, validDocumentsCount: { serializedName: "validDocumentsCount", type: { name: "Number" } }, erroneousDocumentsCount: { serializedName: "erroneousDocumentsCount", type: { name: "Number" } }, transactionsCount: { serializedName: "transactionsCount", type: { name: "Number" } } } } }; export const EntitiesBatchResult: msRest.CompositeMapper = { serializedName: "EntitiesBatchResult", type: { name: "Composite", className: "EntitiesBatchResult", modelProperties: { documents: { readOnly: true, serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "EntitiesBatchResultItem" } } } }, errors: { readOnly: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorRecord" } } } }, statistics: { readOnly: true, serializedName: "statistics", type: { name: "Composite", className: "RequestStatistics" } } } } }; export const InternalError: msRest.CompositeMapper = { serializedName: "InternalError", type: { name: "Composite", className: "InternalError", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } }, innerError: { serializedName: "innerError", type: { name: "Composite", className: "InternalError" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } }, target: { serializedName: "target", type: { name: "String" } }, innerError: { serializedName: "innerError", type: { name: "Composite", className: "InternalError" } } } } }; export const KeyPhraseBatchResultItem: msRest.CompositeMapper = { serializedName: "KeyPhraseBatchResultItem", type: { name: "Composite", className: "KeyPhraseBatchResultItem", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, keyPhrases: { readOnly: true, serializedName: "keyPhrases", type: { name: "Sequence", element: { type: { name: "String" } } } }, statistics: { serializedName: "statistics", type: { name: "Composite", className: "DocumentStatistics" } } } } }; export const KeyPhraseBatchResult: msRest.CompositeMapper = { serializedName: "KeyPhraseBatchResult", type: { name: "Composite", className: "KeyPhraseBatchResult", modelProperties: { documents: { readOnly: true, serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "KeyPhraseBatchResultItem" } } } }, errors: { readOnly: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorRecord" } } } }, statistics: { readOnly: true, serializedName: "statistics", type: { name: "Composite", className: "RequestStatistics" } } } } }; export const LanguageInput: msRest.CompositeMapper = { serializedName: "LanguageInput", type: { name: "Composite", className: "LanguageInput", modelProperties: { countryHint: { serializedName: "countryHint", type: { name: "String" } }, id: { serializedName: "id", type: { name: "String" } }, text: { serializedName: "text", type: { name: "String" } } } } }; export const LanguageBatchInput: msRest.CompositeMapper = { serializedName: "LanguageBatchInput", type: { name: "Composite", className: "LanguageBatchInput", modelProperties: { documents: { serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "LanguageInput" } } } } } } }; export const DetectedLanguage: msRest.CompositeMapper = { serializedName: "DetectedLanguage", type: { name: "Composite", className: "DetectedLanguage", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, iso6391Name: { serializedName: "iso6391Name", type: { name: "String" } }, score: { serializedName: "score", type: { name: "Number" } } } } }; export const LanguageBatchResultItem: msRest.CompositeMapper = { serializedName: "LanguageBatchResultItem", type: { name: "Composite", className: "LanguageBatchResultItem", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, detectedLanguages: { serializedName: "detectedLanguages", type: { name: "Sequence", element: { type: { name: "Composite", className: "DetectedLanguage" } } } }, statistics: { serializedName: "statistics", type: { name: "Composite", className: "DocumentStatistics" } } } } }; export const LanguageBatchResult: msRest.CompositeMapper = { serializedName: "LanguageBatchResult", type: { name: "Composite", className: "LanguageBatchResult", modelProperties: { documents: { readOnly: true, serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "LanguageBatchResultItem" } } } }, errors: { readOnly: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorRecord" } } } }, statistics: { readOnly: true, serializedName: "statistics", type: { name: "Composite", className: "RequestStatistics" } } } } }; export const SentimentBatchResultItem: msRest.CompositeMapper = { serializedName: "SentimentBatchResultItem", type: { name: "Composite", className: "SentimentBatchResultItem", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, score: { serializedName: "score", type: { name: "Number" } }, statistics: { serializedName: "statistics", type: { name: "Composite", className: "DocumentStatistics" } } } } }; export const SentimentBatchResult: msRest.CompositeMapper = { serializedName: "SentimentBatchResult", type: { name: "Composite", className: "SentimentBatchResult", modelProperties: { documents: { readOnly: true, serializedName: "documents", type: { name: "Sequence", element: { type: { name: "Composite", className: "SentimentBatchResultItem" } } } }, errors: { readOnly: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorRecord" } } } }, statistics: { readOnly: true, serializedName: "statistics", type: { name: "Composite", className: "RequestStatistics" } } } } };
the_stack
import * as functions from 'firebase-functions'; import * as express from 'express'; import * as admin from 'firebase-admin'; import * as HttpStatus from 'http-status-codes'; import * as Firestoree from '@google-cloud/firestore'; import { UserType } from './UserType'; import * as atomicFunction from './Functions'; interface IUserRequest extends express.Request { user: any } admin.initializeApp(functions.config().firebase); const app = express(); // const loginCredentialsCheck = express(); export const db = admin.firestore(); export const autoStudentParentEntry = functions.firestore.document('Schools/{country}/{schoolCode}/Profile/Student/{studentId}').onWrite(async (eventSnapshot, context) => { return atomicFunction.studentParentAutoEntry(eventSnapshot, context); }); export const autoTeacherEntry = functions.firestore.document('Schools/{country}/{schoolCode}/Profile/Parent-Teacher/{teacherId}').onWrite(async (eventSnapshot, context) => { return atomicFunction.teacherAutoEntry(eventSnapshot, context); }); export const autoMessageIdEntry = functions.firestore.document('/Schools/{country}/{schoolCode}/Chats/{standard}/Chat/{chatId}/{messageId}').onCreate(async (eventSnapshot, context) => { return atomicFunction.messageIdAutoEntry(eventSnapshot, context); }); exports.webApi = functions.https.onRequest(app); // exports.loginApi = functions.https.onRequest(loginCredentialsCheck); //To Check if user is authenticated or not // @ts-ignore const validateFirebaseIdToken = async (req: express.Request, res: express.Response, next: express.NextFunction) => { console.log('Check if request is authorized with Firebase ID token'); if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) && !(req.cookies && req.cookies.__session)) { console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.', 'Make sure you authorize your request by providing the following HTTP header:', 'Authorization: Bearer <Firebase ID Token>', 'or by passing a "__session" cookie.'); res.status(HttpStatus.UNAUTHORIZED).send('Unauthorized'); return; } var idToken; if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) { console.log('Found "Authorization" header'); // Read the ID Token from the Authorization header. idToken = req.headers.authorization.split('Bearer ')[1]; } else if (req.cookies) { console.log('Found "__session" cookie'); // Read the ID Token from cookie. idToken = req.cookies.__session; } else { // No cookie res.status(HttpStatus.UNAUTHORIZED).send('Unauthorized'); return; } try { const decodedIdToken = await admin.auth().verifyIdToken(idToken); console.log('ID Token correctly decoded', decodedIdToken); console.log('ID Token correctly decoded: Email', decodedIdToken.email); var requestWrapper: IUserRequest = <IUserRequest>req; requestWrapper.user = decodedIdToken; next(); return; } catch (error) { console.error('Error while verifying Firebase ID token:', error); res.status(HttpStatus.UNAUTHORIZED).send('Unauthorized'); return; } }; //To add Profile data app.post('/profileupdate', async (req: express.Request, res: express.Response) => { try { // console.log("code" + req.body.schoolCode); console.log('In Try'); const { schoolCode, profileData, userType, country } = req.body; const data = { schoolCode, profileData, userType, country } // console.log('Here'); // console.log(data.country); // console.log(data.userType); // console.log(data.country); const profileDataMap = data.profileData as Map<String, any>; const id = data.profileData.id; // console.log(id); const ref = await getProfileRef(data.schoolCode, data.country, data.userType, id); await ref.set(profileDataMap, { merge: true }).then((success) => { res.status(HttpStatus.OK).send(profileData); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); // res.status(HttpStatus.OK).send("Profile Updated " + HttpStatus.getStatusText(HttpStatus.OK)); } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)); } }); //Method to get User Data //get methid not working so post is used app.post('/userdata', async (req: express.Request, res: express.Response) => { try { // console.log("In User data code :" + req.body.schoolCode); // console.log('In Try'); const { schoolCode, id, userType, country } = req.body; const data = { schoolCode, id, userType, country } // console.log('Here'); // console.log(id); const ref = await getProfileRef(data.schoolCode, data.country, data.userType, data.id); await ref.get().then((documentSnapshot) => { // console.log('JSON Data : '); var inJsonFormat = Object.assign(documentSnapshot.data(), { id: documentSnapshot.id }); // console.log(inJsonFormat); // console.log('Data : '+ documentSnapshot); // console.log('Data2 : '+ documentSnapshot.data); res.status(HttpStatus.OK).send(inJsonFormat); }, (onFailure) => { res.status(HttpStatus.NOT_FOUND).send(HttpStatus.getStatusText(HttpStatus.NOT_FOUND)); }); // res.status(HttpStatus.OK).send("User Data Received " + HttpStatus.getStatusText(HttpStatus.OK)); } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)); } }); export function _getSchoolRef(schoolCode: string, country: string): Firestoree.CollectionReference { return db.collection('Schools').doc(country).collection(schoolCode); } export async function getProfileRef(schoolCode: string, country: string, userType: string, id: string): Promise<Firestoree.DocumentReference> { const _profileRef = _getSchoolRef(schoolCode, country).doc('Profile'); let res: Firestoree.DocumentReference; if (userType == UserType.STUDENT) { res = await _profileRef.collection('Student').doc(id); } else if (userType == UserType.TEACHER || userType == UserType.PARENT) { res = await _profileRef.collection('Parent-Teacher').doc(id); } else { res = await _profileRef.collection('Unknown').doc(id); res.get; } return res; } app.post('/postAnnouncement', async (req: express.Request, res: express.Response) => { try { // console.log('in Post Announcement Function'); const { announcement, schoolCode, country } = req.body; const data = { announcement, schoolCode, country } // console.log('below data'); let announcementMap = data.announcement; announcementMap = Object.assign(announcementMap, { timeStamp: Firestoree.Timestamp.now() }); const std = data.announcement.forClass == 'Global' ? 'Global' : data.announcement.forClass + data.announcement.forDiv; console.log(data.schoolCode + " " + data.announcement.forClass + " " + data.announcement.forDiv + " " + data.country); const _announcementRef = db.collection("Schools").doc(data.country).collection(data.schoolCode).doc("Posts").collection(std); await _announcementRef.add(announcementMap).then((success) => { success.get().then((documentSnapshot) => { var inJsonFormat = Object.assign(documentSnapshot.data(), { id: documentSnapshot.id }); res.status(HttpStatus.OK).json(inJsonFormat); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)); } }); app.post('/addAssignment', async (req: express.Request, res: express.Response) => { try { // console.log('in add Assignment Function'); const { assignment, schoolCode, country } = req.body; const data = { assignment, schoolCode, country } // console.log('below data'); let assignmemtMap = data.assignment; assignmemtMap = Object.assign(assignmemtMap, { timeStamp: Firestoree.Timestamp.now() }); const std = data.assignment.standard == 'Global' ? 'Global' : data.assignment.standard + data.assignment.div; // console.log(data.schoolCode + " " + data.assignment.standard + " " + data.assignment.div + " " + data.country); const _announcementRef = db.collection("Schools").doc(data.country).collection(data.schoolCode).doc("Assignments").collection(std); await _announcementRef.add(assignmemtMap).then((success) => { success.get().then((documentSnapshot) => { var inJsonFormat = Object.assign(documentSnapshot.data(), { id: documentSnapshot.id }); res.status(HttpStatus.OK).json(inJsonFormat); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)); } }); app.get('/jsonModel', async (req: express.Request, res: express.Response) => { try { db.collection("Schools").doc("India").collection("AMBE001").doc("Login").collection("Student").doc("5YBx4YxiQoVQNsKhtj1P").get().then((success) => { var inJson = Object.assign(success.data(), { id: success.id }); res.status(HttpStatus.OK).json(inJson); }, (failure) => { res.status(HttpStatus.BAD_REQUEST).send('Failure : ' + HttpStatus.getStatusText(HttpStatus.BAD_REQUEST)); }); } catch (e) { res.status(HttpStatus.INTERNAL_SERVER_ERROR).send(HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)); } });
the_stack
import BigNumber from 'bignumber.js'; import { HttpProvider, IpcProvider, WebsocketProvider, Log, EventLog, } from 'web3-core'; import { TransactionReceipt, } from 'web3-eth'; // ============ Types ============ export type address = string; export type TypedSignature = string; export type Provider = HttpProvider | IpcProvider | WebsocketProvider; export type BigNumberable = BigNumber | number | string; // ============ Enums ============ export enum PerpetualMarket { PBTC_USDC = 'PBTC-USDC', WETH_PUSD = 'WETH-PUSD', PLINK_USDC = 'PLINK-USDC', } export enum ConfirmationType { Hash = 0, Confirmed = 1, Both = 2, Simulate = 3, } export enum SigningMethod { Compatibility = 'Compatibility', // picks intelligently between UnsafeHash and Hash UnsafeHash = 'UnsafeHash', // raw hash signed Hash = 'Hash', // hash prepended according to EIP-191 TypedData = 'TypedData', // order hashed according to EIP-712 MetaMask = 'MetaMask', // order hashed according to EIP-712 (MetaMask-only) MetaMaskLatest = 'MetaMaskLatest', // ... according to latest version of EIP-712 (MetaMask-only) CoinbaseWallet = 'CoinbaseWallet', // ... according to latest version of EIP-712 (CoinbaseWallet) } export enum OrderStatus { Null = 0, Approved = 1, Canceled = 2, } export interface OrderState { status: OrderStatus; filledAmount: BigNumber; } export enum SoloBridgeTransferMode { SOME_TO_PERPETUAL = 0, SOME_TO_SOLO = 1, ALL_TO_PERPETUAL = 2, } // ============ Constants ============ export const Networks = { MAINNET: 1, KOVAN: 42, }; // ============ Initialization Options ============ export interface PerpetualOptions { defaultAccount?: address; sendOptions?: SendOptions; apiOptions?: ApiOptions; accounts?: EthereumAccount[]; } export interface ApiOptions { endpoint?: string; timeout?: number; } // ============ Interfaces ============ export interface EthereumAccount { address?: string; privateKey: string; } export interface TxResult { transactionHash?: string; transactionIndex?: number; blockHash?: string; blockNumber?: number; from?: string; to?: string; contractAddress?: string; cumulativeGasUsed?: number; gasUsed?: number; logs?: Log[]; events?: { [eventName: string]: EventLog; }; status?: boolean; nonce?: number; // non-standard field, returned only through dYdX Sender service confirmation?: Promise<TransactionReceipt>; gasEstimate?: number; gas?: number; } export interface TxOptions { from?: address; value?: number | string; } export interface NativeSendOptions extends TxOptions { gasPrice?: number | string; gas?: number | string; nonce?: string | number; } export interface SendOptions extends NativeSendOptions { confirmations?: number; confirmationType?: ConfirmationType; gasMultiplier?: number; } export interface CallOptions extends TxOptions { blockNumber?: number; } export interface PosAndNegValues { positiveValue: BigNumber; negativeValue: BigNumber; } // ============ Solidity Interfaces ============ export interface SignedIntStruct { value: string; isPositive: boolean; } export interface BalanceStruct { marginIsPositive: boolean; positionIsPositive: boolean; margin: string; position: string; } export interface FundingRateStruct { timestamp: BigNumber; isPositive: boolean; value: BigNumber; } export interface TradeArg { makerIndex: number; takerIndex: number; trader: address; data: string; } export interface TradeResult { marginAmount: BigNumber; positionAmount: BigNumber; isBuy: boolean; traderFlags: BigNumber; } export interface FundingRateBounds { maxAbsValue: FundingRate; maxAbsDiffPerSecond: FundingRate; } export interface LoggedFundingRate { timestamp: BigNumber; baseValue: BaseValue; } export interface Index { timestamp: BigNumber; baseValue: BaseValue; } export interface Order { isBuy: boolean; isDecreaseOnly: boolean; amount: BigNumber; limitPrice: Price; triggerPrice: Price; limitFee: Fee; maker: address; taker: address; expiration: BigNumber; salt: BigNumber; } export interface SignedOrder extends Order { typedSignature: string; } export interface MakerOracleMessage { price: Price; timestamp: BigNumber; signature: string; } export interface SoloBridgeTransfer { account: address; perpetual: address; soloAccountNumber: BigNumberable; soloMarketId: BigNumberable; amount: BigNumberable; transferMode: SoloBridgeTransferMode; expiration?: BigNumberable; salt?: BigNumberable; } export interface SignedSoloBridgeTransfer extends SoloBridgeTransfer { typedSignature: string; } // ============ Helper Functions ============ export function bnToSoliditySignedInt(value: BigNumberable): SignedIntStruct { const bn = new BigNumber(value); return { value: bn.abs().toFixed(0), isPositive: bn.isPositive(), }; } export function bnFromSoliditySignedInt(struct: SignedIntStruct): BigNumber { if (struct.isPositive) { return new BigNumber(struct.value); } return new BigNumber(struct.value).negated(); } // ============ Classes ============ export class Balance { public margin: BigNumber; public position: BigNumber; constructor(margin: BigNumberable, position: BigNumberable) { this.margin = new BigNumber(margin); this.position = new BigNumber(position); } static fromSolidity(struct: BalanceStruct): Balance { const marginBN = new BigNumber(struct.margin); const positionBN = new BigNumber(struct.position); return new Balance( struct.marginIsPositive ? marginBN : marginBN.negated(), struct.positionIsPositive ? positionBN : positionBN.negated(), ); } public toSolidity(): BalanceStruct { return { marginIsPositive: this.margin.isPositive(), positionIsPositive: this.position.isPositive(), margin: this.margin.abs().toFixed(0), position: this.position.abs().toFixed(0), }; } public copy(): Balance { return new Balance(this.margin, this.position); } /** * Get the positive and negative values (in terms of margin-token) of the balance, * given an oracle price. */ public getPositiveAndNegativeValues(price: Price): PosAndNegValues { let positiveValue = new BigNumber(0); let negativeValue = new BigNumber(0); const marginValue = this.margin.abs(); if (this.margin.isPositive()) { positiveValue = marginValue; } else { negativeValue = marginValue; } const positionValue = this.position.times(price.value).abs(); if (this.position.isPositive()) { positiveValue = positiveValue.plus(positionValue); } else { negativeValue = negativeValue.plus(positionValue); } return { positiveValue, negativeValue }; } /** * Get the collateralization ratio of the balance, given an oracle price. * * Returns BigNumber(Infinity) if there are no negative balances. */ public getCollateralization(price: Price): BigNumber { const values = this.getPositiveAndNegativeValues(price); if (values.negativeValue.isZero()) { return new BigNumber(Infinity); } return values.positiveValue.div(values.negativeValue); } } // From BaseMath.sol. export const BASE_DECIMALS = 18; /** * A value that is represented on the smart contract by an integer shifted by `BASE` decimal places. */ export class BaseValue { readonly value: BigNumber; constructor(value: BigNumberable) { this.value = new BigNumber(value); } public toSolidity(): string { return this.value.abs().shiftedBy(BASE_DECIMALS).toFixed(0); } public toSoliditySignedInt(): SignedIntStruct { return { value: this.toSolidity(), isPositive: this.isPositive(), }; } static fromSolidity(solidityValue: BigNumberable, isPositive: boolean = true): BaseValue { // Help to detect errors in the parsing and typing of Solidity data. if (typeof isPositive !== 'boolean') { throw new Error('Error in BaseValue.fromSolidity: isPositive was not a boolean'); } let value = new BigNumber(solidityValue).shiftedBy(-BASE_DECIMALS); if (!isPositive) { value = value.negated(); } return new BaseValue(value); } /** * Return the BaseValue, rounded down to the nearest Solidity-representable value. */ public roundedDown(): BaseValue { return new BaseValue(this.value.decimalPlaces(BASE_DECIMALS, BigNumber.ROUND_DOWN)); } public times(value: BigNumberable): BaseValue { return new BaseValue(this.value.times(value)); } public div(value: BigNumberable): BaseValue { return new BaseValue(this.value.div(value)); } public plus(value: BigNumberable): BaseValue { return new BaseValue(this.value.plus(value)); } public minus(value: BigNumberable): BaseValue { return new BaseValue(this.value.minus(value)); } public abs(): BaseValue { return new BaseValue(this.value.abs()); } public negated(): BaseValue { return new BaseValue(this.value.negated()); } public isPositive(): boolean { return this.value.isPositive(); } public isNegative(): boolean { return this.value.isNegative(); } } export class Price extends BaseValue { } export class Fee extends BaseValue { static fromBips(value: BigNumberable): Fee { return new Fee(new BigNumber('1e-4').times(value)); } } export class FundingRate extends BaseValue { /** * Given a daily rate, returns funding rate represented as a per-second rate. * * Note: Funding interest does not compound, as the interest affects margin balances but * is calculated based on position balances. */ static fromEightHourRate(rate: BigNumberable): FundingRate { return new FundingRate(new BigNumber(rate).div(8 * 60 * 60)); } } export enum ApiOrderStatus { PENDING = 'PENDING', OPEN = 'OPEN', FILLED = 'FILLED', PARTIALLY_FILLED = 'PARTIALLY_FILLED', CANCELED = 'CANCELED', UNTRIGGERED = 'UNTRIGGERED', } export enum ApiOrderType { PERPETUAL_CROSS = 'PERPETUAL_CROSS', PERPETUAL_STOP_LIMIT = 'PERPETUAL_STOP_LIMIT', } export enum ApiMarketName { PBTC_USDC = 'PBTC-USDC', WETH_PUSD = 'WETH-PUSD', PLINK_USDC = 'PLINK-USDC', } export enum ApiSide { BUY = 'BUY', SELL = 'SELL', } export enum ApiOrderCancelReason { EXPIRED = 'EXPIRED', UNDERCOLLATERALIZED = 'UNDERCOLLATERALIZED', CANCELED_ON_CHAIN = 'CANCELED_ON_CHAIN', USER_CANCELED = 'USER_CANCELED', SELF_TRADE = 'SELF_TRADE', FAILED = 'FAILED', COULD_NOT_FILL = 'COULD_NOT_FILL', POST_ONLY_WOULD_CROSS = 'POST_ONLY_WOULD_CROSS', } export interface ApiOrder { uuid: string; id: string; status: ApiOrderStatus; accountOwner: string; accountNumber: string; orderType: ApiOrderType; fillOrKill: boolean; market: ApiMarketName; side: ApiSide; baseAmount: string; quoteAmount: string; filledAmount: string; price: string; cancelReason: ApiOrderCancelReason; } export interface ApiOrderOnOrderbook { id: string; uuid: string; amount: string; price: string; } export interface ApiBalance { margin: string; position: string; indexValue: string; indexTimestamp: string; pendingMargin: string; pendingPosition: string; } export interface ApiMarketMessage { createdAt: string; updatedAt: string; market: ApiMarketName; oraclePrice: string; fundingRate: string; globalIndexValue: string; globalIndexTimeStamp: string; } export interface ApiAccount { owner: string; uuid: string; balances: { [market: string]: ApiBalance, }; } // ============ Funding API ============ export interface ApiFundingRate { market: ApiMarketName; effectiveAt: string; fundingRate: string; fundingRate8Hr: string; averagePremiumComponent: string; averagePremiumComponent8Hr: string; } // Per-market response from /funding-rates export interface ApiFundingRates { current: ApiFundingRate; predicted: ApiFundingRate | null; } // Per-market response from /historical-funding-rates export interface ApiHistoricalFundingRates { history: ApiFundingRate[]; } // Per-market response from /index-price export interface ApiIndexPrice { price: string; } export enum RequestMethod { GET = 'get', POST = 'post', DELETE = 'delete', }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormAsyncOperation_Information { interface tab_generaltab_Sections { custom: DevKit.Controls.Section; general: DevKit.Controls.Section; systemlinksection: DevKit.Controls.Section; } interface tab_generaltab extends DevKit.Controls.ITab { Section: tab_generaltab_Sections; } interface Tabs { generaltab: tab_generaltab; } interface Body { Tab: Tabs; /** Date and time when the system job was completed. */ CompletedOn: DevKit.Controls.DateTime; /** Date and time when the system job was created. */ CreatedOn: DevKit.Controls.DateTime; /** Message provided by the system job. */ FriendlyMessage: DevKit.Controls.String; /** Message related to the system job. */ Message: DevKit.Controls.String; /** Name of the system job. */ Name: DevKit.Controls.String; /** Type of the system job. */ OperationType: DevKit.Controls.OptionSet; /** Unique identifier of the user or team who owns the system job. */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the object with which the system job is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Number of times to retry the system job. */ RetryCount: DevKit.Controls.Integer; WebResource_systemjob: DevKit.Controls.WebResource; } } class FormAsyncOperation_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form AsyncOperation_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form AsyncOperation_Information */ Body: DevKit.FormAsyncOperation_Information.Body; } class AsyncOperationApi { /** * DynamicsCrm.DevKit AsyncOperationApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the system job. */ AsyncOperationId: DevKit.WebApi.GuidValue; /** The breadcrumb record ID. */ BreadcrumbId: DevKit.WebApi.GuidValue; /** The origin of the caller. */ CallerOrigin: DevKit.WebApi.StringValue; /** Date and time when the system job was completed. */ CompletedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier used to correlate between multiple SDK requests and system jobs. */ CorrelationId: DevKit.WebApi.GuidValue; /** Last time the correlation depth was updated. */ CorrelationUpdatedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the user who created the system job. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the system job was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the asyncoperation. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unstructured data associated with the system job. */ Data: DevKit.WebApi.StringValue; DataBlobId_Name: DevKit.WebApi.StringValueReadonly; /** Execution of all operations with the same dependency token is serialized. */ DependencyToken: DevKit.WebApi.StringValue; /** Number of SDK calls made since the first call. */ Depth: DevKit.WebApi.IntegerValue; /** Error code returned from a canceled system job. */ ErrorCode: DevKit.WebApi.IntegerValueReadonly; /** Time that the system job has taken to execute. */ ExecutionTimeSpan: DevKit.WebApi.DoubleValueReadonly; /** The datetime when the Expander pipeline started. */ ExpanderStartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Message provided by the system job. */ FriendlyMessage: DevKit.WebApi.StringValue; /** Unique identifier of the host that owns this system job. */ HostId: DevKit.WebApi.StringValue; /** Indicates that the system job is waiting for an event. */ IsWaitingForEvent: DevKit.WebApi.BooleanValueReadonly; /** Message related to the system job. */ Message: DevKit.WebApi.StringValueReadonly; /** Name of the message that started this system job. */ MessageName: DevKit.WebApi.StringValue; /** Unique identifier of the user who last modified the system job. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the system job was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the asyncoperation. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the system job. */ Name: DevKit.WebApi.StringValue; /** Type of the system job. */ OperationType: DevKit.WebApi.OptionSetValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the system job. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the owning extension with which the system job is associated. */ OwningExtensionId: DevKit.WebApi.LookupValue; /** Unique identifier of the team who owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; ParentPluginExecutionId: DevKit.WebApi.GuidValue; /** Indicates whether the system job should run only after the specified date and time. */ PostponeUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Pattern of the system job's recurrence. */ RecurrencePattern: DevKit.WebApi.StringValue; /** Starting time in UTC for the recurrence pattern. */ RecurrenceStartTime_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_accountleads: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activitymimeattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activitymonitor: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_activitypointer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_adminsettingsentity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_annotation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_annualfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appelement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_applicationuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appnotification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_appusersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_attributemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresource: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcebooking: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcebookingexchangesyncidmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcebookingheader: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcecategoryassn: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookableresourcegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bookingstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bot: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_botcomponent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bulkoperation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_bulkoperationlog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_businessunit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_businessunitnewsarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_calendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_campaign: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_campaignactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_campaignactivityitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_campaignitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_campaignresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_catalog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_catalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ channelaccessprofile_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_characteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_childincidentcount: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_commitment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_competitor: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_competitoraddress: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_competitorproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_competitorsalesliterature: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connection: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connectionreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connectionrole: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_connector: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_constraintbasedgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contactinvoices: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contactleads: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contactorders: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contactquotes: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contract: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contractdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_contracttemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_convertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapi: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customeraddress: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customeropportunityrole: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_customerrelationship: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakefolder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_discount: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_discounttype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_displaystring: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_dynamicproperty: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_dynamicpropertyassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_dynamicpropertyinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_dynamicpropertyoptionsetitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_email: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_emailserverprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementchannel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementcontacts: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementproducts: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementtemplatechannel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitlementtemplateproducts: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_entitymap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_equipment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ externalparty_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ externalpartyitem_asyncoperations: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_fixedmonthlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowmachine: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_flowsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_goalrollupquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_import: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importlog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_importmap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_incident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_incidentknowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_incidentresolution: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_new_interactionforemail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_invoice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_invoicedetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_isvconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticlecomment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_kbarticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_knowledgearticleincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_lead: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_leadaddress: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_leadcompetitors: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_leadproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_leadtoopportunitysalesprocess: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_list: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_listmember: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_listoperation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_mailbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_mailmergetemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_managedidentity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_marketingformdisplayattributes: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_metric: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_monthlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynsm_marketingsitemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynsm_salessitemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynsm_servicessitemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdynsm_settingssitemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_3dmodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_accountpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_actioncardregarding: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_actioncardrolesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_actual: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_adaptivecardconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_adminappstate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agentstatushistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analysiscomponent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analysisjob: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analysisresult: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analytics: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analyticsadminsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_analyticsforcs: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_appconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_applicationextension: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_approval: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_assetcategorytemplateassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_assettemplateassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_authenticationsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_autocapturerule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_autocapturesettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_batchjob: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingchange: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingsetupmetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_477c16f59170487b8b4dc895c5dcd09b: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_665e73aa18c247d886bfc50499c73b82: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_989e9b1857e24af18787d5143b67523b: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_baa0a411a239410cb8bded8b5fdd88e3: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_d3d97bac8c294105840e99e37a9d1c39: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_bpf_d8f9dc7f099f44db9d641dd81fbd470d: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_businessclosure: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_callablecontext: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_cannedmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_capacityprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_caseenrichment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_casesuggestionrequestpayload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_casetopic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_casetopicsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_casetopicsummary: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_casetopic_incident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_cdsentityengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_channel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_channelcapability: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_channelprovider: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_chatansweroption: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_chatquestionnaireresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_chatquestionnaireresponseitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ciprovider: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_clientextension: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_collabgraphresource: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_configuration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_consoleappparameterdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_contactpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_contractperformance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationinsight: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationtopic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationtopicsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationtopicsummary: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_conversationtopic_conversation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_customengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_customerasset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_customerassetattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_customerassetcategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataanalyticsreport: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataanalyticsreport_csrmanager: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataanalyticsreport_ksinsights: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataanalyticsreport_oc: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataanalyticsreport_ocvoice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_databaseversion: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataexport: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_datainsightsandanalyticsfeature: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_decisioncontract: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_decisionruleset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_delegation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dimension: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_entitlementapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_entityconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_entityconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_entityrankingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_entityroutingconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_estimate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_estimateline: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_expense: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_expensecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_expensereceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_facebookengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fact: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fieldcomputation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fieldservicesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fieldserviceslaconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_fieldservicesystemjob: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_findworkevent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_flowcardtype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_forecastdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_forecastinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_functionallocation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_gdprdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_geofence: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_geofenceevent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_geofencingsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_geolocationsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_geolocationtracking: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_icebreakersconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inspection: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inspectionattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inspectioninstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inspectionresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_integrationjob: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_integrationjobdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inventoryjournal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_invoicefrequency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotalert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotprovider: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iotsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_iottocaseprocess: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_journal: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_journalline: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kbenrichment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kpieventdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_lineengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_livechatconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_livechatengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_livechatwidgetlocation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_liveconversation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_liveworkstream: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_macrosession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_maskingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_migrationtracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_mlresultcache: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_msteamssetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_msteamssettingsv2: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_notesanalysisconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_notificationfield: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_notificationtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocfbapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocfbpage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_oclanguage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkitemsentiment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocphonenumber: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsessionsentiment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsimltraining: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsitdskill: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_octag: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_octwitterapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_octwitterhandle: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_omnichannelpersonalization: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_omnichannelqueue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_operatinghour: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_orderpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_organizationalunit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_paneconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_payment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_paymentdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_paymentmethod: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_paymentterm: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_personalmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_playbookactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_playbookcategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_playbookinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_playbooktemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_postalbum: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_postalcode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_postconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_postruleconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_presence: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_priority: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_problematicasset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_processnotes: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productinventory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivityagentscript: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_project: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectapproval: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectpricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projecttask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectteam: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_property: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_propertyassetassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_propertylog: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_propertytemplateassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_provider: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_questionsequence: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotebookingservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_quotepricelist: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementdependency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementrelationship: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_requirementstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resolution: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourceassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcepaytype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcerequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcerequirement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_resourceterritory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rma: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rmaproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rmasubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_roleutilization: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_routingconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_routingrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rtv: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rtvproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_scenario: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_schedulingparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_searchconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sentimentanalysis: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_servicetasktype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sessiondata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sessionevent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sessionparticipant: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sessiontemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_shipvia: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_siconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_sikeyvalueconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_skillattachmenttarget: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_smartassistconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_smsengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_smsnumber: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_soundfile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_suggestioninteraction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_suggestionrequestpayload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_suggestionsmodelsummary: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_suggestionssetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_surveyquestion: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_taxcode: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_taxcodedetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_teamscollaboration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_templateforproperties: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_templateparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_templatetags: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timeentry: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timeentrysetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_timeoffrequest: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactioncategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactionconnection: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactionorigin: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transactiontype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_transcript: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_uniquenumber: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_untrackedappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_upgraderun: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_upgradestep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_upgradeversion: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_usersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_userworkhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_visitorjourney: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_wallsavedquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_wallsavedqueryusersettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_warehouse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_wechatengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_whatsappengagementctx: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workhourtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderresolution: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workordersubstatus: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyn_workordertype: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_actioncallworkflow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_answer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_auditanddiagnosticssetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_configuration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_customizationfiles: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_entityassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_entitysearch: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_form: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_languagemodule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_scriptlet: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_scripttasktrigger: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_search: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_sessioninformation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_sessiontransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_ucisettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_uiievent: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_usersettings: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msdyusd_windowroute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_alert: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_alertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_emailtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_fileresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_localizedemailtemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_project: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_question: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_questionresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_satisfactionmetric: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_survey: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_surveyreminder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_surveyresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_msfp_unsubscribedrecipient: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_opportunity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_opportunityclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_opportunitycompetitors: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_opportunityproduct: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_opportunitysalesprocess: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_orderclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organization: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_organizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_package: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_pdfsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_phonetocaseprocess: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_position: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_post: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_postfollow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_pricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_privilege: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_processstageparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_product: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_productassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_productpricelevel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_productsalesliterature: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_productsubstitute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_quarterlyfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_queue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_queueitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_quote: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_quoteclose: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_quotedetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_ratingmodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_ratingvalue: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshiprole: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_relationshiprolemap: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_report: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_resource: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_resourcegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_resourcegroupexpansion: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_resourcespec: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_role: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_rollupfield: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_routingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_routingruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_salesliterature: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_salesliteratureitem: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_salesorder: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_salesorderdetail: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_salesprocessinstance: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_savedquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_semiannualfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_service: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_servicecontractcontacts: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_serviceplan: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_settingdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sharepointsite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_similarityrule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_site: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_sla: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_socialprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_subject: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemform: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemuser: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_task: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_team: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_template: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_territory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_theme: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_topic: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_topichistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_topicmodel: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_topicmodelconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_topicmodelexecutionhistory: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_transactioncurrency: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_action: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_audit: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_context: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_hostedapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_nonhostedapplication: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_option: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_savedsession: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_sessiontransfer: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_workflow: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_workflowstep: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uom: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_uomschedule: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_userform: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_usermapping: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_userquery: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the system job is associated. */ regardingobjectid_workflowbinary: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Unique identifier of the request that generated the system job. */ RequestId: DevKit.WebApi.GuidValue; /** Retain job history. */ RetainJobHistory: DevKit.WebApi.BooleanValue; /** Number of times to retry the system job. */ RetryCount: DevKit.WebApi.IntegerValueReadonly; /** Root execution context of the job that trigerred async job. */ RootExecutionContext: DevKit.WebApi.StringValue; /** Order in which operations were submitted. */ Sequence: DevKit.WebApi.BigIntValueReadonly; /** Date and time when the system job was started. */ StartedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Status of the system job. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the system job. */ StatusCode: DevKit.WebApi.OptionSetValue; /** The Subtype of the Async Job */ Subtype: DevKit.WebApi.IntegerValueReadonly; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Unique identifier of the workflow activation related to the system job. */ WorkflowActivationId: DevKit.WebApi.LookupValue; /** Indicates whether the workflow instance was blocked when it was persisted. */ WorkflowIsBlocked: DevKit.WebApi.BooleanValueReadonly; /** Name of a workflow stage. */ WorkflowStageName: DevKit.WebApi.StringValueReadonly; /** State of the workflow job. */ WorkflowState: DevKit.WebApi.StringValueReadonly; /** The workload name. */ Workload: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace AsyncOperation { enum OperationType { /** 6 */ Activity_Propagation, /** 190690092 */ AI_Builder_Prediction_Events, /** 190690091 */ AI_Builder_Training_Events, /** 73 */ ALM_Anomaly_Detection_Operation, /** 72 */ App_Module_Metadata_Operation, /** 41 */ Audit_Partition_Creation, /** 13 */ Bulk_Delete, /** 94 */ Bulk_Delete_File_Attachment, /** 23 */ Bulk_Delete_Subprocess, /** 8 */ Bulk_Duplicate_Detection, /** 2 */ Bulk_Email, /** 22 */ Calculate_Organization_Maximum_Storage_Size, /** 18 */ Calculate_Organization_Storage_Size, /** 57 */ Calculate_Rollup_Field, /** 79 */ CallbackRegistration_Expander_Operation, /** 100 */ Cascade_FlowSession_Permissions_Async_Operation, /** 12801 */ Cascade_Grant_or_Revoke_Access_Version_Tracking_Async_Operation, /** 90 */ CascadeAssign, /** 91 */ CascadeDelete, /** 42 */ Check_For_Language_Pack_Updates, /** 32 */ Cleanup_inactive_workflow_assemblies, /** 71 */ Cleanup_Solution_Components, /** 19 */ Collect_Organization_Database_Statistics, /** 16 */ Collect_Organization_Statistics, /** 20 */ Collection_Organization_Size_Statistics, /** 62 */ Convert_Date_And_Time_Behavior, /** 98 */ Create_Or_Refresh_Virtual_Entity, /** 26 */ Database_log_backup, /** 21 */ Database_Tuning, /** 28 */ DBCC_SHRINKDATABASE_maintenance_job, /** 29 */ DBCC_SHRINKFILE_maintenance_job, /** 14 */ Deletion_Service, /** 7 */ Duplicate_Detection_Rule_Publish, /** 53 */ Encryption_Health_Check, /** 63 */ EntityKey_Index_Creation, /** 92 */ Event_Expander_Operation, /** 54 */ Execute_Async_Request, /** 202 */ Export_Solution_Async_Operation, /** 75 */ Flow_Notification, /** 40 */ Goal_Roll_Up, /** 5 */ Import, /** 3 */ Import_File_Parse, /** 38 */ Import_Sample_Data, /** 203 */ Import_Solution_Async_Operation, /** 93 */ Import_Solution_Metadata, /** 17 */ Import_Subprocess, /** 59 */ Import_Translation, /** 51 */ Incoming_Email_Processing, /** 15 */ Index_Management, /** 52 */ Mailbox_Test_Access, /** 58 */ Mass_Calculate_Rollup_Field, /** 12 */ Matchcode_Update, /** 25 */ Organization_Full_Text_Catalog_Index, /** 50 */ Outgoing_Activity, /** 49 */ Post_to_Yammer, /** 201 */ Provision_language_for_user, /** 43 */ Provision_Language_Pack, /** 11 */ Quick_Campaign, /** 35 */ Recurring_Series_Expansion, /** 95 */ Refresh_Business_Unit_for_Records_Owned_By_Principal, /** 250 */ Refresh_Runtime_Integration_Components_Async_Operation, /** 46 */ Regenerate_Entity_Row_Count_Snapshot_Data, /** 47 */ Regenerate_Read_Share_Snapshot_Data, /** 30 */ Reindex_all_indices_maintenance_job, /** 69 */ Relationship_Assistant_Cards, /** 68 */ Resource_Booking_Sync, /** 96 */ Revoke_Inherited_Access, /** 76 */ Ribbon_Client_Metadata_Operation, /** 9 */ SQM_Data_Collection, /** 31 */ Storage_Limit_Notification, /** 1 */ System_Event, /** 4 */ Transform_Parse_Data, /** 27 */ Update_Contract_States, /** 56 */ Update_Entitlement_States, /** 65 */ Update_Knowledge_Article_States, /** 101 */ Update_Modern_Flow_Async_Operation, /** 44 */ Update_Organization_Database, /** 45 */ Update_Solution, /** 24 */ Update_Statistic_Intervals, /** 10 */ Workflow } enum StateCode { /** 3 */ Completed, /** 2 */ Locked, /** 0 */ Ready, /** 1 */ Suspended } enum StatusCode { /** 32 */ Canceled, /** 22 */ Canceling, /** 31 */ Failed, /** 20 */ In_Progress, /** 21 */ Pausing, /** 30 */ Succeeded, /** 10 */ Waiting, /** 0 */ Waiting_For_Resources } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
const argv_original = process.argv.slice(); /** * 受け取った引数をコマンドライン引数として、atcoder-cliのコマンドラインからの呼び出しを再現する * @param args accに渡される引数(可変長) */ const run = (...args: Array<string>) => { process.argv = ["node", "acc", ...args]; require("../../src/cli/index"); process.argv = argv_original; }; // コマンドラインからの呼び出しに対して、想定通りの関数が想定通りの引数で呼ばれていることをテストする describe("command calls", () => { beforeEach(() => { // jest.resetModules()でcommandsも毎回別物になるので、jest.mockで毎回mockしなおす // そのためjest.clearAllMocks()は呼ばなくてもよい jest.mock("../../src/commands"); }); afterEach(() => { // cli/indexは一度しか呼べないため、テストのたびにリセットする jest.resetModules(); }); describe("acc new", () => { test("new abc100", () => { const commands = require("../../src/commands"); run("new", "abc100"); expect(commands.setup).toBeCalledWith("abc100", expect.anything()); expect(commands.setup).not.toBeCalledWith("abc101", expect.anything()); }); test("n abc102 -c next -f", () => { const commands = require("../../src/commands"); run("n", "abc102", "-c", "next", "-f"); expect(commands.setup).toBeCalledWith("abc102", expect.objectContaining({tests: true, force: true, choice: "next"})); expect(commands.setup).toBeCalledWith("abc102", expect.not.objectContaining({template: expect.anything()})); }); test("new abc103 --no-tests --no-template", () => { const commands = require("../../src/commands"); run("new", "abc103", "--no-tests", "--no-template"); expect(commands.setup).toBeCalledWith("abc103", expect.objectContaining({tests: false, template: false})); expect(commands.setup).toBeCalledWith("abc103", expect.not.objectContaining({choice: expect.anything()})); }); test("new abc104 -t {TASKLABEL}", () => { const commands = require("../../src/commands"); run("new", "abc104", "-t", "{TASKLABEL}"); expect(commands.setup).toBeCalledWith("abc104", expect.objectContaining({taskDirnameFormat: "{TASKLABEL}"})); }); test("new abc105 -d {ContestTitle}", () => { const commands = require("../../src/commands"); run("new", "abc105", "-d", "{ContestTitle}"); expect(commands.setup).toBeCalledWith("abc105", expect.objectContaining({contestDirnameFormat: "{ContestTitle}"})); }); }); describe("acc add", () => { test("add", () => { const commands = require("../../src/commands"); run("add"); expect(commands.add).toBeCalledWith(expect.anything()); }); test("a -c next -f", () => { const commands = require("../../src/commands"); run("a", "-c", "next", "-f"); expect(commands.add).toBeCalledWith(expect.objectContaining({tests: true, force: true, choice: "next"})); expect(commands.add).toBeCalledWith(expect.not.objectContaining({template: expect.anything()})); }); test("add -t {TASKLABEL}", () => { const commands = require("../../src/commands"); run("a", "-t", "{TASKLABEL}"); expect(commands.add).toBeCalledWith(expect.objectContaining({taskDirnameFormat: "{TASKLABEL}"})); }); test("add --no-tests --no-template", () => { const commands = require("../../src/commands"); run("add", "--no-tests", "--no-template"); expect(commands.add).toBeCalledWith(expect.objectContaining({tests: false, template: false})); expect(commands.add).toBeCalledWith(expect.not.objectContaining({choice: expect.anything()})); }); }); describe("acc submit", () => { test("submit", () => { const commands = require("../../src/commands"); run("submit"); expect(commands.submit).toBeCalledWith(undefined, [], expect.anything()); }); test("s main.cpp", () => { const commands = require("../../src/commands"); run("s", "main.cpp"); expect(commands.submit).toBeCalledWith("main.cpp", [], expect.anything()); expect(commands.submit).toBeCalledWith("main.cpp", [], expect.not.objectContaining({contest: expect.anything(), task: expect.anything(), skipFilename: expect.anything()})); }); test("s main.cpp -- -y", () => { const commands = require("../../src/commands"); run("s", "main.cpp", "--", "-y"); expect(commands.submit).toBeCalledWith("main.cpp", ["-y"], expect.anything()); expect(commands.submit).toBeCalledWith("main.cpp", ["-y"], expect.not.objectContaining({contest: expect.anything(), task: expect.anything(), skipFilename: expect.anything()})); }); test("s -s -- -y --no-open -w 10", () => { const commands = require("../../src/commands"); run("s", "-s", "--", "-y", "--no-open", "-w", "10"); expect(commands.submit).toBeCalledWith("-y", ["--no-open", "-w", "10"], expect.anything()); expect(commands.submit).toBeCalledWith("-y", ["--no-open", "-w", "10"], expect.objectContaining({skipFilename: true})); expect(commands.submit).toBeCalledWith("-y", ["--no-open", "-w", "10"], expect.not.objectContaining({contest: expect.anything(), task: expect.anything()})); }); test("s -s --", () => { const commands = require("../../src/commands"); run("s", "-s", "--"); expect(commands.submit).toBeCalledWith(undefined, [], expect.anything()); expect(commands.submit).toBeCalledWith(undefined, [], expect.objectContaining({skipFilename: true})); expect(commands.submit).toBeCalledWith(undefined, [], expect.not.objectContaining({contest: expect.anything(), task: expect.anything()})); }); test("s -c abc100 -t abc100_a", () => { const commands = require("../../src/commands"); run("s", "-c", "abc100", "-t", "abc100_a"); expect(commands.submit).toBeCalledWith(undefined, [], expect.objectContaining({contest: "abc100", task: "abc100_a"})); expect(commands.submit).toBeCalledWith(undefined, [], expect.not.objectContaining({skipFilename: expect.anything()})); }); }); describe("acc login", () => { test("login", () => { const commands = require("../../src/commands"); run("login"); expect(commands.login).toBeCalledWith(expect.anything()); }); }); describe("acc logout", () => { test("logout", () => { const commands = require("../../src/commands"); run("logout"); expect(commands.logout).toBeCalledWith(expect.anything()); }); }); describe("acc session", () => { test("session", () => { const commands = require("../../src/commands"); run("session"); expect(commands.session).toBeCalledWith(expect.anything()); }); }); describe("acc contest", () => { test("contest", () => { const commands = require("../../src/commands"); run("contest"); expect(commands.contest).toBeCalledWith(undefined, expect.not.objectContaining({id: true})); }); test("contest abc100", () => { const commands = require("../../src/commands"); run("contest", "abc100"); expect(commands.contest).toBeCalledWith("abc100", expect.not.objectContaining({id: true})); }); test("contest -i abc101", () => { const commands = require("../../src/commands"); run("contest", "-i", "abc101"); expect(commands.contest).toBeCalledWith("abc101", expect.objectContaining({id: true})); }); }); describe("acc task", () => { test("task", () => { const commands = require("../../src/commands"); run("task"); expect(commands.task).toBeCalledWith(undefined, undefined, expect.not.objectContaining({id: true})); }); test("task abc100", () => { const commands = require("../../src/commands"); run("task", "abc100"); expect(commands.task).toBeCalledWith("abc100", undefined, expect.not.objectContaining({id: true})); }); test("task -i abc101 abc101_b", () => { const commands = require("../../src/commands"); run("task", "-i", "abc101", "abc101_b"); expect(commands.task).toBeCalledWith("abc101", "abc101_b", expect.objectContaining({id: true})); }); }); describe("acc tasks", () => { test("tasks abc101", () => { const commands = require("../../src/commands"); run("tasks", "abc101"); expect(commands.tasks).toBeCalledWith("abc101", expect.not.objectContaining({id: true})); }); test("tasks -i abc101", () => { const commands = require("../../src/commands"); run("tasks", "-i", "abc101"); expect(commands.tasks).toBeCalledWith("abc101", expect.objectContaining({id: true})); }); }); describe("acc url", () => { test("url", () => { const commands = require("../../src/commands"); run("url"); expect(commands.url).toBeCalledWith(undefined, undefined, expect.not.objectContaining({check: true})); }); test("url abc102", () => { const commands = require("../../src/commands"); run("url", "abc102"); expect(commands.url).toBeCalledWith("abc102", undefined, expect.not.objectContaining({check: true})); }); test("url -c abc102", () => { const commands = require("../../src/commands"); run("url", "-c", "abc102"); expect(commands.url).toBeCalledWith("abc102", undefined, expect.objectContaining({check: true})); }); test("url -c abc102 abc102_a", () => { const commands = require("../../src/commands"); run("url", "-c", "abc102", "abc102_a"); expect(commands.url).toBeCalledWith("abc102", "abc102_a", expect.objectContaining({check: true})); }); }); describe("acc format", () => { test("format \"{ContestID} - {ContestTitle}\" abc110", () => { const commands = require("../../src/commands"); run("format", "{ContestID} - {ContestTitle}", "abc110"); expect(commands.format).toBeCalledWith("{ContestID} - {ContestTitle}", "abc110", undefined, expect.anything()); }); test("format \"{index1} {TaskLabel}: {TaskTitle} ({ContestID})\" abc111 abc111_b", () => { const commands = require("../../src/commands"); run("format", "{index1} {TaskLabel}: {TaskTitle} ({ContestID})", "abc111", "abc111_b"); expect(commands.format).toBeCalledWith("{index1} {TaskLabel}: {TaskTitle} ({ContestID})", "abc111", "abc111_b", expect.anything()); }); }); describe("acc check-oj", () => { test("check-oj", () => { const commands = require("../../src/commands"); run("check-oj"); expect(commands.checkOJAvailable).toBeCalledWith(expect.anything()); }); }); describe("acc config", () => { test("config", () => { const commands = require("../../src/commands"); run("config"); expect(commands.config).toBeCalledWith(undefined, undefined, expect.not.objectContaining({D: true})); }); test("config default-template", () => { const commands = require("../../src/commands"); run("config", "default-template"); expect(commands.config).toBeCalledWith("default-template", undefined, expect.not.objectContaining({D: true})); }); // TODO: -d だけでなく --delete も受け付けるようにする test("config -d default-template", () => { const commands = require("../../src/commands"); run("config", "-d", "default-template"); expect(commands.config).toBeCalledWith("default-template", undefined, expect.objectContaining({D: true})); }); test("config default-task-choice next", () => { const commands = require("../../src/commands"); run("config", "default-task-choice", "next"); expect(commands.config).toBeCalledWith("default-task-choice", "next", expect.not.objectContaining({D: true})); }); }); describe("acc config-dir", () => { test("config-dir", () => { const commands = require("../../src/commands"); run("config-dir"); expect(commands.configDir).toBeCalledWith(expect.anything()); }); }); describe("acc templates", () => { test("templates", () => { const commands = require("../../src/commands"); run("templates"); expect(commands.getTemplateList).toBeCalledWith(expect.anything()); }); }); });
the_stack
import * as argparse from 'argparse'; import * as fs from 'fs'; import * as util from 'util'; import * as path from 'path'; import csvstringify from 'csv-stringify'; import JSONStream from 'JSONStream'; import * as I18N from '../../../lib/i18n'; import { argnameFromLabel, readJson, dumpMap, Domains } from './utils'; import * as StreamUtils from '../../../lib/utils/stream-utils'; const INSTANCE_OF_PROP = "P31"; const SYMMETRIC_PROPERTY_MIN_EXAMPLES = 10; const SYMMETRIC_PROPERTY_THRESHOLD = 0.85; interface EntityParameterData { value : string, name : string, canonical : string } interface ParameterDatasetGeneratorOptions { locale : string, domains : Domains, typeSystem : 'entity-plain' | 'entity-hierarchical' | 'string', wikidata : string, wikidataEntities : string, wikidataProperties : string, subtypes : string, filteredProperties : string, symmetricProperties : string, bootlegTypes : string, bootlegTypeCanonical : string, maxValueLength : number, manifest : string, outputDir : string } class ParamDatasetGenerator { private _locale : string; private _domains : Domains; private _typeSystem : string; private _maxValueLength : number; private _paths : Record<string, string>; private _wikidataProperties : Map<string, string>; private _bootlegTypes : Map<string, string[]>; private _items : Map<string, Map<string, string>>; private _predicates : Map<string, Map<string, string[]>>; private _values : Map<string, string>; private _types : Map<string, string>; private _subtypes : Map<string, string[]>; private _filteredPropertiesByDomain : Map<string, string[]>; private _thingtalkEntityTypes : Map<string, string>; private _valueSets : Map<string, Array<string[]|EntityParameterData>>; private _manifest : NodeJS.WritableStream; private _tokenizer : I18N.BaseTokenizer; constructor(options : ParameterDatasetGeneratorOptions) { this._locale = options.locale; this._domains = options.domains; this._typeSystem = options.typeSystem; this._maxValueLength = options.maxValueLength; this._paths = { dir: path.dirname(options.manifest), manifest: options.manifest, parameterDataset: options.outputDir, wikidata: options.wikidata, wikidataEntities: options.wikidataEntities, wikidataProperties: options.wikidataProperties, subtypes: options.subtypes, filteredProperties: options.filteredProperties, symmetricProperties: options.symmetricProperties, bootlegTypes: options.bootlegTypes, bootlegTypeCanonical: options.bootlegTypeCanonical }; // wikidata information this._wikidataProperties = new Map(); // labels for all properties this._bootlegTypes = new Map(); // in domain information this._items = new Map(); // items (subjects) by domain this._predicates = new Map(); // predicates by domain this._values = new Map(); // all values appeared in all domains' predicates this._types = new Map(); // types for all entities this._subtypes = new Map(); // subtype information for all types this._filteredPropertiesByDomain = new Map(); // final list of properties by domain this._thingtalkEntityTypes = new Map(); // final thingtalk types of all values this._valueSets = new Map(); // parameter value sets by type this._manifest = fs.createWriteStream(this._paths.manifest); this._tokenizer = I18N.get(options.locale).getTokenizer(); // init items, predicates, properties for (const domain of this._domains.domains) { this._items.set(domain, new Map()); this._predicates.set(domain, new Map()); this._filteredPropertiesByDomain.set(domain, []); } } private async _outputEntityValueSet(type : string, data : EntityParameterData[]) { const outputPath = path.join(this._paths.parameterDataset, `${type}.json`); const manifestEntry = `entity\t${this._locale}\t${type}\tparameter-datasets/${type}.json\n`; if (fs.existsSync(outputPath)) { // skip domain entities, no need to add if (this._domains.domains.map((d) => `org.wikidata:${d}`).includes(type)) return; const savedData = await readJson(outputPath); // Just keep unique values data = Array.from(new Set(savedData.get('data').concat(data))); } await util.promisify(fs.writeFile)(outputPath, JSON.stringify({ result: 'ok', data }, undefined, 2), { encoding: 'utf8' }); this._manifest.write(manifestEntry); } private async _outputStringValueSet(type : string, data : string[][]) { const outputPath = path.join(this._paths.parameterDataset, `${type}.tsv`); const output = csvstringify({ header: false, delimiter: '\t' }); output.pipe(fs.createWriteStream(outputPath, { encoding: 'utf8' })); const manifestEntry = `string\t${this._locale}\t${type}\tparameter-datasets/${type}.tsv\n`; for (const row of data) output.write(row); StreamUtils.waitFinish(output); this._manifest.write(manifestEntry); } private async _loadPredicates() { // loading predicates from kb files for (const kbFile of this._paths.wikidata) { const pipeline = fs.createReadStream(kbFile).pipe(JSONStream.parse('$*')); pipeline.on('data', async (item) => { const predicates : Record<string, string[]> = item.value; // skip entities with no "instance of" property if (!(INSTANCE_OF_PROP in predicates)) return; // skip reading predicates for entities that do not have one of the // in-domain wikidata types as its types "instance of" const entityTypes = predicates[INSTANCE_OF_PROP]; let match = false; for (const domain of this._domains.wikidataTypes) { if (entityTypes.includes(domain)) match = true; } if (!match) return; const domains = this._domains.getDomainsByWikidataTypes(entityTypes); for (const domain of domains) { // add wikidata item in the domain // set QID as label as fallback, and update with labels later const items = this._items.get(domain)!; items.set(item.key, item.key); // add predicates for (const [property, values] of Object.entries(predicates)) { if (!this._wikidataProperties.has(property)) continue; if (!this._predicates.get(domain)!.has(property)) this._predicates.get(domain)!.set(property, []); const predicate = this._predicates.get(domain)!.get(property)!; for (const value of values) { predicate.push(value); // add values // set QID as label as fallback, and update with labels later this._values.set(value, value); } } } }); pipeline.on('error', (error) => console.error(error)); await StreamUtils.waitEnd(pipeline); } } private async _loadWikidataTypes() { for (const kbFile of this._paths.wikidata) { const pipeline = fs.createReadStream(kbFile).pipe(JSONStream.parse('$*')); pipeline.on('data', async (item) => { const predicates = item.value; // skip entities with no type information if (!predicates[INSTANCE_OF_PROP]) return; if (this._values.has(item.key)) this._types.set(item.key, predicates[INSTANCE_OF_PROP]); }); pipeline.on('error', (error) => console.error(error)); await StreamUtils.waitEnd(pipeline); } } private async _identifySymmetricProperties() { const relations = new Map(); for (const kbFile of this._paths.wikidata) { const pipeline = fs.createReadStream(kbFile).pipe(JSONStream.parse('$*')); pipeline.on('data', async (item) => { for (const domain of this._domains.domains) { if (!this._items.get(domain)!.has(item.key)) return; for (const property in item.value) { if (!this._predicates.get(domain)!.has(property)) continue; if (!relations.has(property)) relations.set(property, new Map()); relations.get(property).set(item.key, item.value[property]); } } }); pipeline.on('error', (error) => console.error(error)); await StreamUtils.waitEnd(pipeline); } const symmetricProperties = []; for (const [property, maps] of relations) { let count_bidirectional = 0; let count_unidirectional = 0; for (const [subject, objects] of maps) { for (const object of objects) { if (!maps.has(object)) { count_unidirectional += 1; break; } if (!maps.get(object).includes(subject)) { count_unidirectional += 1; break; } count_bidirectional +=1; } } const total = (count_bidirectional + count_unidirectional) / 2; if (total < SYMMETRIC_PROPERTY_MIN_EXAMPLES) continue; if (count_bidirectional / 2 / total > SYMMETRIC_PROPERTY_THRESHOLD) symmetricProperties.push(property); } await util.promisify(fs.writeFile)(this._paths.symmetricProperties, symmetricProperties.join(','), { encoding: 'utf8' }); } private async _loadBootlegTypes() { const bootlegTypeCanonical = await readJson(this._paths.bootlegTypeCanonical); const pipeline = fs.createReadStream(this._paths.bootlegTypes).pipe(JSONStream.parse('$*')); pipeline.on('data', async (item) => { if (this._values.has(item.key)) this._bootlegTypes.set(item.key, item.value.map((qid : string) => bootlegTypeCanonical.get(qid))); }); pipeline.on('error', (error) => console.error(error)); await StreamUtils.waitEnd(pipeline); } private async _loadLabels() { const pipeline = fs.createReadStream(this._paths.wikidataEntities).pipe(JSONStream.parse('$*')); const valueTypes = new Set(Array.from(this._types.values()).flat()); pipeline.on('data', async (entity) => { const qid = String(entity.key); const label = String(entity.value); for (const domain of this._domains.domains) { if (this._items.get(domain)!.has(qid)) this._items.get(domain)!.set(qid, label); } if (this._values.has(qid) || valueTypes.has(qid)) this._values.set(qid, label); }); pipeline.on('error', (error) => console.error(error)); await StreamUtils.waitEnd(pipeline); } private _addToValueSet(type : string, entry : string[]|EntityParameterData) { if (this._valueSets.has(type)) this._valueSets.get(type)!.push(entry); else this._valueSets.set(type, [entry]); } private _getEntityType(qid : string) : string|null { const bootlegTypes = this._bootlegTypes.get(qid); // return the first type in bootleg if (bootlegTypes && bootlegTypes.length > 0) return argnameFromLabel(bootlegTypes[0]); // fallback to the first wikidata type with label const wikidataTypes = this._types.get(qid); if (!wikidataTypes) return null; for (const type of wikidataTypes) { const entityType = this._values.get(type); if (entityType) { console.warn(`Bootleg does not have ${qid}, fall back to CSQA type`); return argnameFromLabel(entityType); } } return null; } /** * Generates paramter-datasets. Iterate through each domain properties. * Find data type and value and output corresponding json/tsv files. */ private async _generateParameterDatasets() { await this._outputDomainValueSet(); await this._outputParameterValueSet(); this._manifest.end(); await StreamUtils.waitFinish(this._manifest); } private async _outputDomainValueSet() { for (const domain of this._domains.domains) { console.log('Processing entities for domain:', domain); const data = []; for (const [value, label] of this._items.get(domain)!) { const tokenized = this._tokenizer.tokenize(label).tokens.join(' '); data.push({ value, name: label, canonical: tokenized }); } await this._outputEntityValueSet(`org.wikidata:${domain}`, data); } } private async _outputParameterValueSet() { for (const domain of this._domains.domains) { console.log('Processing properties for domain:', domain); for (const [property, values] of this._predicates.get(domain)!) { // all properties in CSQA has entity values, skip if no value has been found if (values.length === 0) continue; const propertyLabel = this._wikidataProperties.get(property)!; const thingtalkPropertyType = 'p_' + argnameFromLabel(propertyLabel); console.log('Processing property:', propertyLabel); const thingtalkEntityTypes : Set<string> = new Set(); for (const value of values) { const valueLabel = this._values.get(value)!; // Tokenizer throws error. if (valueLabel.includes('æ')) continue; const tokens = this._tokenizer.tokenize(valueLabel).tokens; if (this._maxValueLength && tokens.length > this._maxValueLength) continue; const tokenized = tokens.join(' '); if (this._typeSystem === 'string') { this._addToValueSet(thingtalkPropertyType, [valueLabel, tokenized, "1"]); continue; } const entry = { value, name: valueLabel, canonical: tokenized }; // add to property value set this._addToValueSet(thingtalkPropertyType, entry); this._thingtalkEntityTypes.set(value, thingtalkPropertyType); if (this._typeSystem === 'entity-hierarchical') { // skip entities with no type information if (!this._types.has(value)) continue; const valueType = this._getEntityType(value); // value does not have value for "instance of" field if (!valueType) continue; // add to entity type value set thingtalkEntityTypes.add(valueType); this._addToValueSet(valueType, entry); this._thingtalkEntityTypes.set(value, valueType); } } if (this._typeSystem === 'entity-hierarchical') this._subtypes.set(thingtalkPropertyType, Array.from(thingtalkEntityTypes)); this._filteredPropertiesByDomain.get(domain)!.push(property); } } for (const [valueType, examples] of this._valueSets) { if (this._typeSystem === 'string') { await this._outputStringValueSet(valueType, examples as string[][]); } else { const type = `org.wikidata:${valueType}`; await this._outputEntityValueSet(type, examples as EntityParameterData[]); } } } async run() { console.log('loading property labels ...'); this._wikidataProperties = await readJson(this._paths.wikidataProperties); console.log('loading predicates ...'); await this._loadPredicates(); console.log('loading value types ...'); await this._loadWikidataTypes(); console.log('loading entity labels ...'); await this._loadLabels(); console.log('identifying symmetric properties ...'); await this._identifySymmetricProperties(); if (this._paths.bootlegTypes) { console.log('loading bootleg types ...'); await this._loadBootlegTypes(); } console.log('generating parameter datasets ...'); await this._generateParameterDatasets(); console.log('dumping files'); await dumpMap(this._paths.subtypes, this._subtypes); await dumpMap(this._paths.filteredProperties, this._filteredPropertiesByDomain); await dumpMap(path.join(this._paths.dir, 'values.json'), this._values); await dumpMap(path.join(this._paths.dir, 'items.json'), this._items); await dumpMap(path.join(this._paths.dir, 'types.json'), this._thingtalkEntityTypes); } } module.exports = { initArgparse(subparsers : argparse.SubParser) { const parser = subparsers.add_parser('wikidata-preprocess-knowledge-base', { add_help: true, description: "Generate parameter-datasets.tsv from processed wikidata dump. " }); parser.add_argument('--locale', { required: false, default: 'en-US' }); parser.add_argument('--domains', { required: true, help: 'the path to the file containing type mapping for all domains to include' }); parser.add_argument('--type-system', { required: true, choices: ['entity-plain', 'entity-hierarchical', 'string'], help: 'design choices for the type system:\n' + 'entity-plain: one entity type per property\n' + 'entity-hierarchical: one entity type for each value, and the property type is the supertype of all types of its values\n' + 'string: all property has a string type except id', default: 'entity-hierarchical' }); parser.add_argument('--wikidata', { required: false, nargs: '+', help: "full knowledge base of wikidata, named wikidata_short_1.json and wikidata_short_2.json" }); parser.add_argument('--wikidata-entity-list', { required: false, help: "full list of entities in the wikidata dump, named items_wikidata_n.json in CSQA, " + "in the form of a dictionary with QID as keys and canonical as values." }); parser.add_argument('--wikidata-property-list', { required: true, help: "full list of properties in the wikidata dump, named filtered_property_wikidata4.json" + "in CSQA, in the form of a dictionary with PID as keys and canonical as values." }); parser.add_argument('--subtypes', { required: true, help: "Path to output a json file containing the sub type information for properties" }); parser.add_argument('--filtered-properties', { required: true, help: "Path to output a json file containing properties available for each domain" }); parser.add_argument('--symmetric-properties', { required: true, help: "Path to output a txt file containing symmetric properties for the domain, split by comma" }); parser.add_argument('--bootleg-types', { required: false, help: "Path to types used for each entity in Bootleg" }); parser.add_argument('--bootleg-type-canonicals', { required: false, help: "Path to the json file containing canoncial for each bootleg type" }); parser.add_argument('--max-value-length', { required: false, help: 'Maximum number of tokens for parameter values' }); parser.add_argument('--manifest', { required: true, help: 'Path to the parameter dataset manifest' }); parser.add_argument('-d', '--output-dir', { required: true, help: 'Path to the directory for all in-domain parameter dataset files' }); }, async execute(args : any) { const domains = new Domains({ path: args.domains }); await domains.init(); const paramDatasetGenerator = new ParamDatasetGenerator({ locale: args.locale, domains, typeSystem: args.type_system, wikidata: args.wikidata, wikidataEntities: args.wikidata_entity_list, wikidataProperties: args.wikidata_property_list, subtypes: args.subtypes, filteredProperties: args.filtered_properties, symmetricProperties: args.symmetric_properties, bootlegTypes: args.bootleg_types, bootlegTypeCanonical: args.bootleg_type_canonicals, maxValueLength: args.max_value_length, manifest: args.manifest, outputDir: args.output_dir }); paramDatasetGenerator.run(); } };
the_stack
declare module Peasy { /** Represents a data store abstraction */ interface IDataProxy<T, TKey> { /** Accepts the id of the object to be queried and returns it asynchronously. * @param id The id of the object to query by. * @returns A promise that when resolved, returns the queried object. */ getById(id: TKey): Promise<T> /** Asynchronously returns all values from a data source and is especially useful for lookup data. * @returns A promise that when resolved, returns an array of all of the objects from a data source. */ getAll(): Promise<T[]> /** Accepts an object and asynchronously inserts it into the data store.. * @param data The object to insert. * @returns A promise that when resolved, returns an updated version of the object as a result of the insert operation. */ insert(data: T): Promise<T> /** Accepts an object and asynchronously updates it in the data store. * @param data The object to update. * @returns A promise that when resolved, returns an updated version of the object as a result of the update operation. */ update(data: T): Promise<T> /** Accepts the id of the object to be deleted and asynchronously deletes it from the data store. * @param id The id of the object to delete. * @returns A resolvable promise. */ destroy(id: TKey): Promise<void> } /** Represents a handled error */ class PeasyError { /** (Optional) The field that the message is associated with. */ association?: string; /** The error message. */ message: string; } /** Serves as optional arguments to the constructor of a Command */ class CommandArgs<T> { /** (Optional) Used to perform initialization logic before rules are executed. * @returns An awaitable promise. * @param context An object that can be used as a property bag throughout this command's execution pipeline. */ _onInitialization?: (context: any) => Promise<void>; /** (Optional) Used to return a list of rules whose execution outcome will determine whether or not to invoke _onValidateSuccess. * @returns An awaitable array of IRule. * @param context An object that can be used as a property bag throughout this command's execution pipeline. */ _getRules?: (context: any) => Promise<IRule[]>; /** Primarily used to interact with data proxies, workflow logic, etc. * @returns An awaitable promise. * @param context An object that can be used as a property bag throughout this command's execution pipeline. */ _onValidationSuccess: (context: any) => Promise<T> } /** Contains peasy-js configuration settings */ class Configuration { /** if true, will wrap command function results in promises */ static autoPromiseWrap: boolean; } /** Represents a business service abstraction */ interface IBusinessService<T, TKey> { /** Accepts the id of the object to be queried and returns a command. * @param id The id of the object to query by. * @returns A command that when executed, retrieves the object associated with the supplied id argument upon successful rule validation. */ getByIdCommand(id: TKey): ICommand<T>; /** Returns a command that delivers all values from a data source and is especially useful for lookup data. * @returns A command that when executed, retrieves all of the objects upon successful rule validation. */ getAllCommand(): ICommand<T[]>; /** @param data The object to insert. * @returns A command that when executed, inserts the object upon successful rule validation. */ insertCommand(data: T): ICommand<T>; /** @param data The object to update. * @returns A command that when executed, updates the object upon successful rule validation. */ updateCommand(data: T): ICommand<T>; /** @param id The id of the object to delete. * @returns A command that when executed, deletes the object associated with the supplied id argument upon successful rule validation. */ destroyCommand(id: TKey): ICommand<null>; } /** Base class for all business services */ abstract class BusinessService<T, TKey> implements IBusinessService<T, TKey> { protected dataProxy: IDataProxy<T, TKey>; /** @param dataProxy The data store abstraction. */ constructor(dataProxy: IDataProxy<T, TKey>); /** Accepts the id of the object to be queried and returns a command. * @param id The id of the object to query by. * @returns A command that when executed, retrieves the object associated with the supplied id argument upon successful rule validation. */ getByIdCommand(id: TKey): ICommand<T>; /** Returns a command that delivers all values from a data source and is especially useful for lookup data. * @returns A command that when executed, retrieves all of the objects upon successful rule validation. */ getAllCommand(): ICommand<T[]>; /** Accepts an object to be inserted into a data store and returns a command. * @param data The object to insert. * @returns A command that when executed, inserts the object upon successful rule validation. */ insertCommand(data: T): ICommand<T>; /** Accepts an object to be updated within a data store and returns a command. * @param data The object to update. * @returns A command that when executed, updates the object upon successful rule validation. */ updateCommand(data: T): ICommand<T>; /** Accepts the id of the object to be deleted from a data store and returns a command. * @param id The id of the object to delete. * @returns A command that when executed, deletes the object associated with the supplied id argument upon successful rule validation. */ destroyCommand(id: TKey): ICommand<null>; /** Override this function to perform initialization logic before rule validations for getByIDCommand are performed. * @param id The id of the object to query by. * @param context An object that can be used as a property bag throughout the getByIdCommand execution pipeline. * @returns An awaitable promise. */ protected _onGetByIdCommandInitialization(id: TKey, context: any): Promise<void>; /** Override this function to perform initialization logic before rule validations for getAllCommand are performed. * @param context An object that can be used as a property bag throughout the getAllCommand execution pipeline. * @returns An awaitable promise. */ protected _onGetAllCommandInitialization(context: any): Promise<void>; /** Override this function to perform initialization logic before rule validations for insertCommand are performed. * @param data The object to save (insert). * @param context An object that can be used as a property bag throughout the insertCommand execution pipeline. * @returns An awaitable promise. */ protected _onInsertCommandInitialization(data: T, context: any): Promise<void>; /** Override this function to perform initialization logic before rule validations for updateCommand are performed. * @param data The object to save (update). * @param context An object that can be used as a property bag throughout the updateCommand execution pipeline. * @returns An awaitable promise. */ protected _onUpdateCommandInitialization(data: T, context: any): Promise<void>; /** Override this function to perform initialization logic before rule validations for destroyCommand are performed. * @param id The id of the object to delete. * @param context An object that can be used as a property bag throughout the destroyCommand execution pipeline. * @returns An awaitable promise. */ protected _onDestroyCommandInitialization(id: TKey, context: any): Promise<void>; /** Override this function to supply custom business rules to getByIdCommand. * @param id The id of the object to query by. * @param context An object that can be used as a property bag throughout the getByIdCommand execution pipeline. * @returns An awaitable array of IRule. */ protected _getRulesForGetByIdCommand(id: TKey, context: any): Promise<IRule[]>; /** Override this function to supply custom business rules to getAllCommand. * @param context An object that can be used as a property bag throughout the getAllCommand execution pipeline. * @returns An awaitable array of IRule. */ protected _getRulesForGetAllCommand(context: any): Promise<IRule[]>; /** Override this function to supply custom business rules to insertCommand. * @param data The object to save (insert). * @param context An object that can be used as a property bag throughout the insertCommand execution pipeline. * @returns An awaitable array of IRule. */ protected _getRulesForInsertCommand(data: T, context: any): Promise<IRule[]>; /** Override this function to supply custom business rules to updateCommand. * @param data The object to save (update). * @param context An object that can be used as a property bag throughout the updateCommand execution pipeline. * @returns An awaitable array of IRule. */ protected _getRulesForUpdateCommand(data: T, context: any): Promise<IRule[]>; /** Override this function to supply custom business rules to destroyCommand. * @param id The id of the object to delete. * @param context An object that can be used as a property bag throughout the destroyCommand execution pipeline. * @returns An awaitable array of IRule. */ protected _getRulesForDestroyCommand(id: TKey, context: any): Promise<IRule[]>; /** Invoked by the command returned from getByIdCommand() if validation and business rules execute successfully. * @param id The id of the object to query by. * @param context An object that has been passed through the getByIdCommand execution pipeline. * @returns An awaitable promise. */ protected _getById(id: TKey, context: any): Promise<T>; /** Invoked by the command returned from getAllCommand() if validation and business rules execute successfully. * @param context An object that has been passed through the getAllCommand execution pipeline. * @returns An awaitable promise. */ protected _getAll(context: any): Promise<T[]>; /** Invoked by the command returned from insertCommand() if validation and business rules execute successfully. * @param data The object to save (insert). * @param context An object that has been passed through the insertCommand execution pipeline. * @returns An awaitable promise. */ protected _insert(data: T, context: any): Promise<T>; /** Invoked by the command returned from updateCommand() if validation and business rules execute successfully. * @param data The object to save (update). * @param context An object that has been passed through the updateCommand execution pipeline. * @returns An awaitable promise. */ protected _update(data: T, context: any): Promise<T>; /** Invoked by the command returned from destroyCommand() if validation and business rules execute successfully. * @param id The id of the object to delete. * @param context An object that has been passed through the deleteCommand execution pipeline. * @returns An awaitable promise. */ protected _destroy(id: TKey, context: any): Promise<void>; } /** Exceptions of this type are explicitly caught and handled by commands during execution. * If caught, the command will return a failed execution result with error messages. * ServiceException can be used in many situations, but is especially helpful to throw within data proxies * See https://github.com/peasy/peasy-js-samples for examples on usage */ class ServiceException { /** @param The error message to display. */ constructor(message: string); /** These errors will be added to a failed execution result's error collection. */ errors: PeasyError[]; /** The error message to display. */ readonly message: string; } /** Serves as the result of a command's execution. */ class ExecutionResult<T> { /** @param success States whether the command execution was successful. * @param value Represents the data returned as a result of command execution. * @param errors Represents the errors returned from failed rules (if any). */ constructor(success: boolean, value?: T, errors?: PeasyError[]); /** Determines whether the command execution was successful. */ readonly success: boolean; /** Represents the data returned as a result of command execution. */ readonly value: T; /** Represents the errors returned from failed rules (if any). */ readonly errors: PeasyError[]; } /** Represents a command abstraction */ interface ICommand<T> { /** Executes validation/business rule execution. * @returns An array of errors if validation fails. */ getErrors(): Promise<PeasyError[]>; /** Executes initialization logic, validation/business rule execution, and command logic. * @returns An execution result. */ execute(): Promise<ExecutionResult<T>>; } /** Responsible for orchestrating the execution of initialization logic, validation/business rule execution, and command logic */ class Command<T> implements ICommand<T> { /** Executes an array of commands and returns after all have completed. * @param commands An array of commands. * @returns An array of execution results. */ static executeAll<T>(commands: Command<T>[]): Promise<ExecutionResult<T>[]>; /** @param args (Optional) Functions that an instance of this command will use. */ constructor(args?: CommandArgs<T>); /** Executes validation/business rule execution. * @returns An array of errors if validation fails. */ getErrors(): Promise<PeasyError[]>; /** Executes initialization logic, validation/business rule execution, and command logic. * @returns An execution result. */ execute(): Promise<ExecutionResult<T>>; /** Used to perform initialization logic before rules are executed. * @returns An awaitable promise. */ protected _onInitialization(context: any): Promise<void>; /** Used to return a list of rules whose execution outcome will determine whether or not to invoke _onValidateSuccess. * @returns An awaitable array of IRule. */ protected _getRules(context: any): Promise<IRule[]>; /** Primarily used to interact with data proxies, workflow logic, etc. * @returns An awaitable promise. */ protected _onValidationSuccess(context: any): Promise<T>; } class ifAllValidResult { /** @param func A function that when executed, returns an awaitable array of rules. * @returns A executable rule. */ thenGetRules(func: () => Promise<Rule[]>): Rule } /** Represents a rule abstraction */ interface IRule { /** Associates an instance of the rule with a field. */ association: string; /** A list of errors resulting from failed validation. */ errors: PeasyError[]; /** Indicates whether the rule is successful after validation. */ valid: boolean; /** Invokes the rule. * @returns An awaitable promise. */ validate(): Promise<void>; } /** Represents a container for business logic. */ abstract class Rule implements IRule { /** Extracts all rules from an array of commands. * @param commands An array of commands. * @returns An awaitable rule. */ static getAllRulesFrom<T>(commands: Command<T>[]): Promise<IRule>; /** Extracts all rules from an array of commands. * @param commands An spread of commands. * @returns An awaitable rule. */ static getAllRulesFrom<T>(...commands: Command<T>[]): Promise<IRule>; /** Returns a function that upon execution, will only return the next set of rules on successful validation of the initial set. * @param rules An array of rules. * @returns An ifAllValidResult. */ static ifAllValid(rules: IRule[]): ifAllValidResult; /** Returns a function that upon execution, will only return the next set of rules on successful validation of the initial set. * @param rules A spread of rules. * @returns An ifAllValidResult. */ static ifAllValid(...rules: IRule[]): ifAllValidResult; /** Override this function to perform the business/validation logic. Invoke _invalidate() if the logic fails validation. * @returns An awaitable promise. */ protected abstract _onValidate(): Promise<void>; /** Override this function to gain more control as to how validation is performed. * @param message The validation failure error message. */ protected _invalidate(message: string): void; /** Associates an instance of the rule with a field. */ association: string; /** Indicates whether the rule is successful after validation. */ readonly valid: boolean; /** A list of errors resulting from failed validation. */ readonly errors: PeasyError[]; /** Invokes the rule. On completion, _valid_ and _errors_ (if applicable) will be set. * @returns An awaitable promise. */ validate(): Promise<void> /** Invokes the supplied set of rules if the validation of this rule is successful. * @param rules A spread of rules. * @returns A reference to this rule. */ ifValidThenValidate(...rules: Rule[]): Rule; /** Invokes the supplied set of rules if the validation of this rule is successful. * @param rules An array of rules. * @returns A reference to this rule. */ ifValidThenValidate(rules: Rule[]): Rule; /** Invokes the supplied set of rules if the validation of this rule fails. * @param rules A spread of rules. * @returns A reference to this rule. */ ifInvalidThenValidate(...rules: Rule[]): Rule; /** Invokes the supplied set of rules if the validation of this rule fails. * @param rules An array of rules. * @returns A reference to this rule. */ ifInvalidThenValidate(rules: Rule[]): Rule; /** Invokes the supplied function if the validation of this rule is successful. * @param func A function to execute that receives a reference to the invoking rule * @returns A reference to this rule. */ ifValidThenExecute(func: (rule: Rule) => void): Rule /** Invokes the supplied function if the validation of this rule fails. * @param func A function to execute that receives a reference to the invoking rule * @returns A reference to this rule. */ ifInvalidThenExecute(func: (rule: Rule) => void): Rule /** Invokes the supplied function if the validation of this rule is successful. * @param func A function that returns an awaitable array of rules. * @returns A reference to this rule. */ ifValidThenGetRules(func: () => Promise<Rule[]>): Rule } } export = Peasy;
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://www.googleapis.com/discovery/v1/apis/blogger/v3/rest /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Blogger API v3 */ function load(name: "blogger", version: "v3"): PromiseLike<void>; function load(name: "blogger", version: "v3", callback: () => any): void; const blogUserInfos: blogger.BlogUserInfosResource; const blogs: blogger.BlogsResource; const comments: blogger.CommentsResource; const pageViews: blogger.PageViewsResource; const pages: blogger.PagesResource; const postUserInfos: blogger.PostUserInfosResource; const posts: blogger.PostsResource; const users: blogger.UsersResource; namespace blogger { interface Blog { /** The JSON custom meta-data for the Blog */ customMetaData?: string; /** The description of this blog. This is displayed underneath the title. */ description?: string; /** The identifier for this resource. */ id?: string; /** The kind of this entry. Always blogger#blog */ kind?: string; /** The locale this Blog is set to. */ locale?: { /** The country this blog's locale is set to. */ country?: string; /** The language this blog is authored in. */ language?: string; /** The language variant this blog is authored in. */ variant?: string; }; /** The name of this blog. This is displayed as the title. */ name?: string; /** The container of pages in this blog. */ pages?: { /** The URL of the container for pages in this blog. */ selfLink?: string; /** The count of pages in this blog. */ totalItems?: number; }; /** The container of posts in this blog. */ posts?: { /** The List of Posts for this Blog. */ items?: Post[]; /** The URL of the container for posts in this blog. */ selfLink?: string; /** The count of posts in this blog. */ totalItems?: number; }; /** RFC 3339 date-time when this blog was published. */ published?: string; /** The API REST URL to fetch this resource from. */ selfLink?: string; /** The status of the blog. */ status?: string; /** RFC 3339 date-time when this blog was last updated. */ updated?: string; /** The URL where this blog is published. */ url?: string; } interface BlogList { /** Admin level list of blog per-user information */ blogUserInfos?: BlogUserInfo[]; /** The list of Blogs this user has Authorship or Admin rights over. */ items?: Blog[]; /** The kind of this entity. Always blogger#blogList */ kind?: string; } interface BlogPerUserInfo { /** ID of the Blog resource */ blogId?: string; /** True if the user has Admin level access to the blog. */ hasAdminAccess?: boolean; /** The kind of this entity. Always blogger#blogPerUserInfo */ kind?: string; /** The Photo Album Key for the user when adding photos to the blog */ photosAlbumKey?: string; /** Access permissions that the user has for the blog (ADMIN, AUTHOR, or READER). */ role?: string; /** ID of the User */ userId?: string; } interface BlogUserInfo { /** The Blog resource. */ blog?: Blog; /** Information about a User for the Blog. */ blog_user_info?: BlogPerUserInfo; /** The kind of this entity. Always blogger#blogUserInfo */ kind?: string; } interface Comment { /** The author of this Comment. */ author?: { /** The display name. */ displayName?: string; /** The identifier of the Comment creator. */ id?: string; /** The comment creator's avatar. */ image?: { /** The comment creator's avatar URL. */ url?: string; }; /** The URL of the Comment creator's Profile page. */ url?: string; }; /** Data about the blog containing this comment. */ blog?: { /** The identifier of the blog containing this comment. */ id?: string; }; /** The actual content of the comment. May include HTML markup. */ content?: string; /** The identifier for this resource. */ id?: string; /** Data about the comment this is in reply to. */ inReplyTo?: { /** The identified of the parent of this comment. */ id?: string; }; /** The kind of this entry. Always blogger#comment */ kind?: string; /** Data about the post containing this comment. */ post?: { /** The identifier of the post containing this comment. */ id?: string; }; /** RFC 3339 date-time when this comment was published. */ published?: string; /** The API REST URL to fetch this resource from. */ selfLink?: string; /** The status of the comment (only populated for admin users) */ status?: string; /** RFC 3339 date-time when this comment was last updated. */ updated?: string; } interface CommentList { /** Etag of the response. */ etag?: string; /** The List of Comments for a Post. */ items?: Comment[]; /** The kind of this entry. Always blogger#commentList */ kind?: string; /** Pagination token to fetch the next page, if one exists. */ nextPageToken?: string; /** Pagination token to fetch the previous page, if one exists. */ prevPageToken?: string; } interface Page { /** The author of this Page. */ author?: { /** The display name. */ displayName?: string; /** The identifier of the Page creator. */ id?: string; /** The page author's avatar. */ image?: { /** The page author's avatar URL. */ url?: string; }; /** The URL of the Page creator's Profile page. */ url?: string; }; /** Data about the blog containing this Page. */ blog?: { /** The identifier of the blog containing this page. */ id?: string; }; /** The body content of this Page, in HTML. */ content?: string; /** Etag of the resource. */ etag?: string; /** The identifier for this resource. */ id?: string; /** The kind of this entity. Always blogger#page */ kind?: string; /** RFC 3339 date-time when this Page was published. */ published?: string; /** The API REST URL to fetch this resource from. */ selfLink?: string; /** The status of the page for admin resources (either LIVE or DRAFT). */ status?: string; /** The title of this entity. This is the name displayed in the Admin user interface. */ title?: string; /** RFC 3339 date-time when this Page was last updated. */ updated?: string; /** The URL that this Page is displayed at. */ url?: string; } interface PageList { /** Etag of the response. */ etag?: string; /** The list of Pages for a Blog. */ items?: Page[]; /** The kind of this entity. Always blogger#pageList */ kind?: string; /** Pagination token to fetch the next page, if one exists. */ nextPageToken?: string; } interface Pageviews { /** Blog Id */ blogId?: string; /** The container of posts in this blog. */ counts?: Array<{ /** Count of page views for the given time range */ count?: string; /** Time range the given count applies to */ timeRange?: string; }>; /** The kind of this entry. Always blogger#page_views */ kind?: string; } interface Post { /** The author of this Post. */ author?: { /** The display name. */ displayName?: string; /** The identifier of the Post creator. */ id?: string; /** The Post author's avatar. */ image?: { /** The Post author's avatar URL. */ url?: string; }; /** The URL of the Post creator's Profile page. */ url?: string; }; /** Data about the blog containing this Post. */ blog?: { /** The identifier of the Blog that contains this Post. */ id?: string; }; /** The content of the Post. May contain HTML markup. */ content?: string; /** The JSON meta-data for the Post. */ customMetaData?: string; /** Etag of the resource. */ etag?: string; /** The identifier of this Post. */ id?: string; /** Display image for the Post. */ images?: Array<{ url?: string; }>; /** The kind of this entity. Always blogger#post */ kind?: string; /** The list of labels this Post was tagged with. */ labels?: string[]; /** The location for geotagged posts. */ location?: { /** Location's latitude. */ lat?: number; /** Location's longitude. */ lng?: number; /** Location name. */ name?: string; /** Location's viewport span. Can be used when rendering a map preview. */ span?: string; }; /** RFC 3339 date-time when this Post was published. */ published?: string; /** Comment control and display setting for readers of this post. */ readerComments?: string; /** The container of comments on this Post. */ replies?: { /** The List of Comments for this Post. */ items?: Comment[]; /** The URL of the comments on this post. */ selfLink?: string; /** The count of comments on this post. */ totalItems?: string; }; /** The API REST URL to fetch this resource from. */ selfLink?: string; /** Status of the post. Only set for admin-level requests */ status?: string; /** The title of the Post. */ title?: string; /** The title link URL, similar to atom's related link. */ titleLink?: string; /** RFC 3339 date-time when this Post was last updated. */ updated?: string; /** The URL where this Post is displayed. */ url?: string; } interface PostList { /** Etag of the response. */ etag?: string; /** The list of Posts for this Blog. */ items?: Post[]; /** The kind of this entity. Always blogger#postList */ kind?: string; /** Pagination token to fetch the next page, if one exists. */ nextPageToken?: string; } interface PostPerUserInfo { /** ID of the Blog that the post resource belongs to. */ blogId?: string; /** True if the user has Author level access to the post. */ hasEditAccess?: boolean; /** The kind of this entity. Always blogger#postPerUserInfo */ kind?: string; /** ID of the Post resource. */ postId?: string; /** ID of the User. */ userId?: string; } interface PostUserInfo { /** The kind of this entity. Always blogger#postUserInfo */ kind?: string; /** The Post resource. */ post?: Post; /** Information about a User for the Post. */ post_user_info?: PostPerUserInfo; } interface PostUserInfosList { /** The list of Posts with User information for the post, for this Blog. */ items?: PostUserInfo[]; /** The kind of this entity. Always blogger#postList */ kind?: string; /** Pagination token to fetch the next page, if one exists. */ nextPageToken?: string; } interface User { /** Profile summary information. */ about?: string; /** The container of blogs for this user. */ blogs?: { /** The URL of the Blogs for this user. */ selfLink?: string; }; /** The timestamp of when this profile was created, in seconds since epoch. */ created?: string; /** The display name. */ displayName?: string; /** The identifier for this User. */ id?: string; /** The kind of this entity. Always blogger#user */ kind?: string; /** This user's locale */ locale?: { /** The user's country setting. */ country?: string; /** The user's language setting. */ language?: string; /** The user's language variant setting. */ variant?: string; }; /** The API REST URL to fetch this resource from. */ selfLink?: string; /** The user's profile page. */ url?: string; } interface BlogUserInfosResource { /** Gets one blog and user info pair by blogId and userId. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog to get. */ blogId: 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; /** Maximum number of posts to pull back with the blog. */ maxPosts?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<BlogUserInfo>; } interface BlogsResource { /** Gets one blog by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog to get. */ blogId: 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; /** Maximum number of posts to pull back with the blog. */ maxPosts?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the blog. Note that some fields require elevated access. */ view?: string; }): Request<Blog>; /** Retrieve a Blog by URL. */ getByUrl(request: { /** 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The URL of the blog to retrieve. */ url: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the blog. Note that some fields require elevated access. */ view?: string; }): Request<Blog>; /** Retrieves a list of blogs, possibly filtered. */ listByUser(request: { /** Data format for the response. */ alt?: string; /** Whether the response is a list of blogs with per-user information instead of just blogs. */ fetchUserInfo?: boolean; /** 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** * User access types for blogs to include in the results, e.g. AUTHOR will return blogs where the user has author level access. If no roles are specified, * defaults to ADMIN and AUTHOR roles. */ role?: string; /** Blog statuses to include in the result (default: Live blogs only). Note that ADMIN access is required to view deleted blogs. */ status?: string; /** ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the blogs. Note that some fields require elevated access. */ view?: string; }): Request<BlogList>; } interface CommentsResource { /** Marks a comment as not spam. */ approve(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** The ID of the comment to mark as not spam. */ commentId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** Delete a comment by ID. */ delete(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** The ID of the comment to delete. */ commentId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets one comment by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to containing the comment. */ blogId: string; /** The ID of the comment to get. */ commentId: 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; /** ID of the post to fetch posts from. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** * Access level for the requested comment (default: READER). Note that some comments will require elevated permissions, for example comments where the * parent posts which is in a draft state, or comments that are pending moderation. */ view?: string; }): Request<Comment>; /** Retrieves the comments for a post, possibly filtered. */ list(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch comments from. */ blogId: string; /** Latest date of comment to fetch, a date-time with RFC 3339 formatting. */ endDate?: string; /** Whether the body content of the comments is included. */ fetchBodies?: boolean; /** 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; /** Maximum number of comments to include in the result. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token if request is paged. */ pageToken?: string; /** ID of the post to fetch posts from. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Earliest date of comment to fetch, a date-time with RFC 3339 formatting. */ startDate?: string; status?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require elevated access. */ view?: string; }): Request<CommentList>; /** Retrieves the comments for a blog, across all posts, possibly filtered. */ listByBlog(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch comments from. */ blogId: string; /** Latest date of comment to fetch, a date-time with RFC 3339 formatting. */ endDate?: string; /** Whether the body content of the comments is included. */ fetchBodies?: boolean; /** 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; /** Maximum number of comments to include in the result. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token if request is paged. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Earliest date of comment to fetch, a date-time with RFC 3339 formatting. */ startDate?: string; status?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<CommentList>; /** Marks a comment as spam. */ markAsSpam(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** The ID of the comment to mark as spam. */ commentId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; /** Removes the content of a comment. */ removeContent(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** The ID of the comment to delete content from. */ commentId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Comment>; } interface PageViewsResource { /** Retrieve pageview stats for a Blog. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog to get. */ blogId: 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; range?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Pageviews>; } interface PagesResource { /** Delete a page by ID. */ delete(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Page. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Gets one blog page by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** ID of the blog containing the page. */ blogId: 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; /** The ID of the page to get. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; view?: string; }): Request<Page>; /** Add a page. */ insert(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to add the page to. */ blogId: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Whether to create the page as a draft (default: false). */ isDraft?: boolean; /** 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Page>; /** Retrieves the pages for a blog, optionally including non-LIVE statuses. */ list(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch Pages from. */ blogId: string; /** Whether to retrieve the Page bodies. */ fetchBodies?: boolean; /** 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; /** Maximum number of Pages to fetch. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Continuation token if the request is paged. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; status?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require elevated access. */ view?: string; }): Request<PageList>; /** Update a page. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Page. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Whether a publish action should be performed when the page is updated (default: false). */ publish?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether a revert action should be performed when the page is updated (default: false). */ revert?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Page>; /** Publishes a draft page. */ publish(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog. */ blogId: 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; /** The ID of the page. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Page>; /** Revert a published or scheduled page to draft state. */ revert(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog. */ blogId: 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; /** The ID of the page. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Page>; /** Update a page. */ update(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Page. */ pageId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Whether a publish action should be performed when the page is updated (default: false). */ publish?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether a revert action should be performed when the page is updated (default: false). */ revert?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Page>; } interface PostUserInfosResource { /** * Gets one post and user info pair, by post ID and user ID. The post user info contains per-user information about the post, such as access rights, * specific to the user. */ get(request: { /** Data format for the response. */ alt?: string; /** The ID of the blog. */ blogId: 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; /** Maximum number of comments to pull back on a post. */ maxComments?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the post to get. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PostUserInfo>; /** * Retrieves a list of post and post user info pairs, possibly filtered. The post user info contains per-user information about the post, such as access * rights, specific to the user. */ list(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch posts from. */ blogId: string; /** Latest post date to fetch, a date-time with RFC 3339 formatting. */ endDate?: string; /** Whether the body content of posts is included. Default is false. */ fetchBodies?: boolean; /** 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; /** Comma-separated list of labels to search for. */ labels?: string; /** Maximum number of posts to fetch. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Sort order applied to search results. Default is published. */ orderBy?: string; /** Continuation token if the request is paged. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Earliest post date to fetch, a date-time with RFC 3339 formatting. */ startDate?: string; status?: string; /** ID of the user for the per-user information to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require elevated access. */ view?: string; }): Request<PostUserInfosList>; } interface PostsResource { /** Delete a post by ID. */ delete(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<void>; /** Get a post by ID. */ get(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch the post from. */ blogId: string; /** * Whether the body content of the post is included (default: true). This should be set to false when the post bodies are not required, to help minimize * traffic. */ fetchBody?: boolean; /** Whether image URL metadata for each post is included (default: false). */ fetchImages?: boolean; /** 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; /** Maximum number of comments to pull back on a post. */ maxComments?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the post */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require elevated access. */ view?: string; }): Request<Post>; /** Retrieve a Post by Path. */ getByPath(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch the post from. */ blogId: 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; /** Maximum number of comments to pull back on a post. */ maxComments?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Path of the Post to retrieve. */ path: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require elevated access. */ view?: string; }): Request<Post>; /** Add a post. */ insert(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to add the post to. */ blogId: string; /** Whether the body content of the post is included with the result (default: true). */ fetchBody?: boolean; /** Whether image URL metadata for each post is included in the returned result (default: false). */ fetchImages?: boolean; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Whether to create the post as a draft (default: false). */ isDraft?: boolean; /** 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Post>; /** Retrieves a list of posts, possibly filtered. */ list(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch posts from. */ blogId: string; /** Latest post date to fetch, a date-time with RFC 3339 formatting. */ endDate?: string; /** * Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize * traffic. */ fetchBodies?: boolean; /** Whether image URL metadata for each post is included. */ fetchImages?: boolean; /** 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; /** Comma-separated list of labels to search for. */ labels?: string; /** Maximum number of posts to fetch. */ maxResults?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Sort search results */ orderBy?: string; /** Continuation token if the request is paged. */ pageToken?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Earliest post date to fetch, a date-time with RFC 3339 formatting. */ startDate?: string; /** Statuses to include in the results. */ status?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; /** Access level with which to view the returned result. Note that some fields require escalated access. */ view?: string; }): Request<PostList>; /** Update a post. This method supports patch semantics. */ patch(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** Whether the body content of the post is included with the result (default: true). */ fetchBody?: boolean; /** Whether image URL metadata for each post is included in the returned result (default: false). */ fetchImages?: boolean; /** 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; /** Maximum number of comments to retrieve with the returned post. */ maxComments?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Whether a publish action should be performed when the post is updated (default: false). */ publish?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether a revert action should be performed when the post is updated (default: false). */ revert?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Post>; /** Publishes a draft post, optionally at the specific time of the given publishDate parameter. */ publish(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Optional date and time to schedule the publishing of the Blog. If no publishDate parameter is given, the post is either published at the a previously * saved schedule date (if present), or the current time. If a future date is given, the post will be scheduled to be published. */ publishDate?: string; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Post>; /** Revert a published or scheduled post to draft state. */ revert(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: 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; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Post>; /** Search for a post. */ search(request: { /** Data format for the response. */ alt?: string; /** ID of the blog to fetch the post from. */ blogId: string; /** * Whether the body content of posts is included (default: true). This should be set to false when the post bodies are not required, to help minimize * traffic. */ fetchBodies?: boolean; /** 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; /** Sort search results */ orderBy?: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Query terms to search this blog for matching posts. */ q: string; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<PostList>; /** Update a post. */ update(request: { /** Data format for the response. */ alt?: string; /** The ID of the Blog. */ blogId: string; /** Whether the body content of the post is included with the result (default: true). */ fetchBody?: boolean; /** Whether image URL metadata for each post is included in the returned result (default: false). */ fetchImages?: boolean; /** 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; /** Maximum number of comments to retrieve with the returned post. */ maxComments?: number; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The ID of the Post. */ postId: string; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Whether a publish action should be performed when the post is updated (default: false). */ publish?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** Whether a revert action should be performed when the post is updated (default: false). */ revert?: boolean; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<Post>; } interface UsersResource { /** Gets one user by ID. */ get(request: { /** 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; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * Overrides userIp if both are provided. */ quotaUser?: string; /** The ID of the user to get. */ userId: string; /** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */ userIp?: string; }): Request<User>; } } }
the_stack
import NoodeState from '../types/NoodeState'; import NoodeDefinition from '../types/NoodeDefinition'; import { setActiveChild as _setActiveChild, deleteChildren, insertChildren } from '../controllers/noodel-mutate'; import { extractNoodeDefinition, parseAndApplyNoodeOptions, parseClassName, parseStyle } from '../controllers/noodel-setup'; import { getPath as _getPath } from '../controllers/getters'; import { alignBranchToIndex, updateNoodeSize, updateBranchSize, checkContentOverflow } from '../controllers/noodel-align'; import { shiftFocalNoode, doJumpNavigation } from '../controllers/noodel-navigate'; import NoodelState from '../types/NoodelState'; import { findNoodeViewModel, changeNoodeId, unregisterNoodeSubtree } from '../controllers/id-register'; import NoodeOptions from '../types/NoodeOptions'; import ComponentContent from '../types/ComponentContent'; import Vue from 'vue'; import { traverseDescendents } from '../controllers/noodel-traverse'; /** * The view model of a noode. Has 2-way binding with the view. */ export default class Noode { private _v: NoodeState; private _nv: NoodelState; /** * Custom data associated with this noode. You can freely get/set this property. */ data: any; /** * Internal use only. To get the view model for specific noodes, use methods on the Noodel class instead. */ private constructor(v: NoodeState, nv: NoodelState, data?: any) { // set to private to avoid including internal types in the declarations this._v = v; this._nv = nv; this.data = data; } private setDeleted() { this._nv = null; } private throwErrorIfDeleted() { if (!this._nv) { throw new Error("Invalid operation because this noode has been deleted from its noodel.") } } // GETTERS /** * Returns true if this noode has been deleted from its noodel. * Most operations on a deleted noode will throw an error. */ isDeleted(): boolean { return !this._nv; } /** * Gets the parent of this noode. All noodes should have a parent * except the root, which will return null. */ getParent(): Noode { this.throwErrorIfDeleted(); if (this.isRoot()) return null; return findNoodeViewModel(this._nv, this._v.parent.id); } /** * Gets the previous sibling, or null if this is already the first. */ getPrev(): Noode { if (this.isRoot()) return null; return this.getParent().getChild(this.getIndex() - 1); } /** * Gets the next sibling, or null if this is already the last. */ getNext(): Noode { if (this.isRoot()) return null; return this.getParent().getChild(this.getIndex() + 1); } /** * Gets the path (an array of zero-based indices counting from the root) of this noode. */ getPath(): number[] { this.throwErrorIfDeleted(); return _getPath(this._v); } /** * Extracts the definition tree of this noode (including its descendents). * Useful if you want to perform your own operations on the content tree. */ getDefinition(): NoodeDefinition { this.throwErrorIfDeleted(); return extractNoodeDefinition(this._nv, this._v); } /** * Gets the container element of this noode (i.e. nd-noode-box) if it is mounted, * or null otherwise. */ getEl(): HTMLDivElement { return this._v.boxEl || null; } /** * Gets the container element of the branch containing this noode's children * (i.e. nd-branch-box) if it has children and is mounted, or null otherwise. */ getChildBranchEl(): HTMLDivElement { return this._v.branchBoxEl || null; } /** * Gets the child at the given index. Returns null if does not exist. */ getChild(index: number): Noode { this.throwErrorIfDeleted(); if (typeof index !== "number" || index < 0 || index >= this._v.children.length) { return null; } return findNoodeViewModel(this._nv, this._v.children[index].id); } /** * Gets a mapped array of this noode's list of children. */ getChildren(): Noode[] { this.throwErrorIfDeleted(); return this._v.children.map(c => findNoodeViewModel(this._nv, c.id)); } /** * Gets the number of children of this noode. */ getChildCount(): number { return this._v.children.length; } /** * Gets the ID of this noode. */ getId(): string { return this._v.id; } /** * Gets the content of this noode. */ getContent(): string | ComponentContent { return this._v.content; } /** * Gets the custom class names for this noode. */ getClass(): string[] { return this._v.className; } /** * Gets the custom styles for this noode. */ getStyle(): object { return this._v.style; } /** * Gets the 0-based index (position among siblings) of this noode. */ getIndex(): number { this.throwErrorIfDeleted(); return this._v.index; } /** * Gets the level of this noode. The root has level 0, * the first branch has level 1, and so on. */ getLevel(): number { this.throwErrorIfDeleted(); return this._v.level; } /** * Gets the active child index. Returns null if there's no active child. */ getActiveChildIndex(): number { return this._v.activeChildIndex; } /** * Gets the current active child. Returns null if does not exist. */ getActiveChild(): Noode { this.throwErrorIfDeleted(); if (this._v.activeChildIndex === null) return null; return findNoodeViewModel(this._nv, this._v.children[this._v.activeChildIndex].id); } /** * Returns true if this noode is the root. */ isRoot(): boolean { this.throwErrorIfDeleted(); return this._v.parent === null; } /** * Returns true if this noode is active. */ isActive(): boolean { return this._v.isActive; } /** * Returns true if this noode is logically visible (i.e even when rendered beyond * canvas boundary). Note that visibility may be delayed due to debounce effects. */ isVisible(): boolean { this.throwErrorIfDeleted(); if (this.isRoot()) return false; return this._v.parent.isBranchVisible; } /** * Returns true if this noode's children is logically visible (i.e even when rendered beyond * canvas boundary). Note that visibility may be delayed due to debounce effects. */ isChildrenVisible(): boolean { this.throwErrorIfDeleted(); return this._v.isBranchVisible; } /** * Returns true if this noode is inside the focal branch. */ isInFocalBranch(): boolean { this.throwErrorIfDeleted(); if (this.isRoot()) return false; return this._v.parent.isFocalParent; } /** * Returns true if this noode is the parent of the focal branch. */ isFocalParent(): boolean { this.throwErrorIfDeleted(); return this._v.isFocalParent; } /** * Returns true if this noode is the focal noode. */ isFocalNoode(): boolean { this.throwErrorIfDeleted(); return this.isActive() && this.isInFocalBranch(); } /** * Returns an object that specifies whether this noode has * content overflow in each of the 4 directions. Only valid * if overflow is detected/manually checked before hand. */ hasOverflow(): {top: boolean, bottom: boolean, left: boolean, right: boolean} { return { top: this._v.hasOverflowTop, bottom: this._v.hasOverflowBottom, left: this._v.hasOverflowLeft, right: this._v.hasOverflowRight } } // MUTATERS /** * Sets the ID of this noode. */ setId(id: string) { this.throwErrorIfDeleted(); if (id === this._v.id) return; changeNoodeId(this._nv, this._v.id, id); } /** * Replaces the content of this noode. */ setContent(content: string | ComponentContent) { this.throwErrorIfDeleted(); if (this.isRoot()) return; // should not set content on root this._v.content = content; Vue.nextTick(() => { if (this._v.parent.isBranchVisible) { let noodeRect = this._v.boxEl.getBoundingClientRect(); let branchRect = this._v.parent.branchBoxEl.getBoundingClientRect(); updateNoodeSize(this._nv, this._v, noodeRect.height, noodeRect.width); updateBranchSize(this._nv, this._v.parent, branchRect.height, branchRect.width); } }); } /** * Replaces the custom class names for this noode. Can be an array or a space-delimited string. */ setClass(className: string | string[]) { this.throwErrorIfDeleted(); if (this.isRoot()) return; // should not set class on root this._v.className = parseClassName(className); } /** * Replaces the custom inline styles for this noode. Can be a string or an object of property-value * pairs. */ setStyle(style: string | object) { this.throwErrorIfDeleted(); if (this.isRoot()) return; // should not set style on root this._v.style = parseStyle(style); } /** * Changes the options for this noode. Properties of the given object * will be merged into the existing options. */ setOptions(options: NoodeOptions) { this.throwErrorIfDeleted(); if (this.isRoot()) return; // should not set options on root parseAndApplyNoodeOptions(this._nv, options, this._v); } /** * Changes the active child of this noode. If doing so will toggle * the visibility of the focal branch (i.e this noode is an ancestor * of the focal branch), a jump to the new active child will be triggered. */ setActiveChild(index: number) { this.throwErrorIfDeleted(); if (typeof index !== "number" || index < 0 || index >= this._v.children.length) { throw new Error("Cannot set active child: noode has no children or invalid index"); } if (this._v.isFocalParent) { shiftFocalNoode(this._nv, index - this._v.activeChildIndex); } else if (this._v.isBranchVisible && (this._v.level + 1) < this._nv.focalLevel) { doJumpNavigation(this._nv, this._v.children[index]); } else { _setActiveChild(this._nv, this._v, index); alignBranchToIndex(this._v, index); } } /** * Performs a navigational jump to focus on this noode. * Cannot jump to the root. */ jumpToFocus() { this.throwErrorIfDeleted(); if (this.isRoot()) { throw new Error("Cannot jump to root noode"); } doJumpNavigation(this._nv, this._v); } /** * Inserts a child noode (and its descendents) at the given index. * Will always preserve the current active child. Returns the inserted * child. * @param childDef definition tree of the child * @param index if not provided, will append to the end of the children */ addChild(childDef: NoodeDefinition, index?: number): Noode { this.throwErrorIfDeleted(); return this.addChildren([childDef], index)[0] || null; } /** * Inserts a list of child noodes (and their descendents) at the given index. * Will always preserve the current active child. Returns the inserted * children. * @param childDefs definition trees of the children * @param index if not provided, will append to the end of the children */ addChildren(childDefs: NoodeDefinition[], index?: number): Noode[] { this.throwErrorIfDeleted(); if (typeof index === "number" && (index < 0 || index > this._v.children.length)) { throw new Error("Cannot add child noode(s): invalid index"); } if (typeof index !== "number") { index = this._v.children.length; } if (childDefs.length === 0) return []; return insertChildren(this._nv, this._v, index, childDefs).map(c => findNoodeViewModel(this._nv, c.id)); } /** * Syntax sugar for adding sibling noode(s) before this noode. * @param defs noode definitions to add */ addBefore(...defs: NoodeDefinition[]): Noode[] { this.throwErrorIfDeleted(); if (this.isRoot()) { throw new Error("Cannot add sibling noodes before root"); } return this.getParent().addChildren(defs, this.getIndex()); } /** * Syntax sugar for adding sibling noode(s) after this noode. * @param defs noode definitions to add */ addAfter(...defs: NoodeDefinition[]): Noode[] { this.throwErrorIfDeleted(); if (this.isRoot()) { throw new Error("Cannot add sibling noodes after root"); } return this.getParent().addChildren(defs, this.getIndex() + 1); } /** * Removes a child noode (and its descendents) at the given index. * If the active child is removed, will set the next child active, * unless the child is the last in the list, where the previous child * will be set active. If the focal branch is deleted, will jump * to the nearest ancestor branch. Returns the definition of the deleted noode. */ removeChild(index: number): NoodeDefinition { this.throwErrorIfDeleted(); return this.removeChildren(index, 1)[0] || null; } /** * Removes children noodes (and their descendents) at the given index. * If the active child is removed, will set the next child active, * unless the child is the last in the list, where the previous child * will be set active. If the focal branch is deleted, will jump * to the nearest ancestor branch. Returns the definitions of the deleted noodes. * @param count number of children to remove, will adjust to maximum if greater than possible range */ removeChildren(index: number, count: number): NoodeDefinition[] { this.throwErrorIfDeleted(); if (typeof index !== "number" || typeof count !== "number" || index < 0 || count < 0 || index >= this._v.children.length) { throw new Error("Cannot remove child noode(s): invalid index or count"); } if (index + count > this._v.children.length) { count = this._v.children.length - index; } if (count <= 0) return []; for (let i = index; i < index + count; i++) { traverseDescendents(this._v.children[i], desc => { findNoodeViewModel(this._nv, desc.id).setDeleted(); }, true); } let deletedNoodes = deleteChildren(this._nv, this._v, index, count); // extract definitions, this must happen before unregistering let defs = deletedNoodes.map(n => extractNoodeDefinition(this._nv, n)); // unregister deletedNoodes.forEach(noode => { noode.parent = null; unregisterNoodeSubtree(this._nv, noode); }); return defs; } /** * Syntax sugar for removing sibling noode(s) before this noode. * @param count number of noodes to remove, will adjust to maximum if greater than possible range */ removeBefore(count: number): NoodeDefinition[] { this.throwErrorIfDeleted(); if (typeof count !== 'number' || count < 0) { throw new Error("Cannot remove before: invalid count"); } if (this.isRoot()) return []; let targetIndex = this.getIndex() - count; if (targetIndex < 0) targetIndex = 0; let targetCount = this.getIndex() - targetIndex; if (targetCount <= 0) return []; return this.getParent().removeChildren(targetIndex, targetCount); } /** * Syntax sugar for removing sibling noode(s) after this noode. * @param count number of noodes to remove, will adjust to maximum if greater than possible range */ removeAfter(count: number): NoodeDefinition[] { this.throwErrorIfDeleted(); if (typeof count !== 'number' || count < 0) { throw new Error("Cannot remove after: invalid count"); } if (this.isRoot()) return []; if (this.getIndex() === this.getParent().getChildCount() - 1) return []; return this.getParent().removeChildren(this.getIndex() + 1, count); } /** * Syntax sugar for removing this noode from the tree. */ removeSelf(): NoodeDefinition { this.throwErrorIfDeleted(); if (this.isRoot()) { throw new Error("Cannot remove the root"); } return this.getParent().removeChild(this.getIndex()); } // TRAVERSAL /** * Do a preorder traversal of this noode's subtree and perform the specified action * on each descendent. * @param func the action to perform * @param includeSelf whether to include this noode in the traversal */ traverseSubtree(func: (noode: Noode) => any, includeSelf: boolean) { traverseDescendents(this._v, desc => { func(findNoodeViewModel(this._nv, desc.id)); }, includeSelf); } // ALIGNMENT /** * Asynchronous method to capture the length of this noode (on the branch axis) and adjust * the branch's position if necessary. Use when resize detection is disabled to manually * trigger realignment on noode resize. Fails silently if this is root or noodel is not mounted. */ realign() { this.throwErrorIfDeleted(); if (!this._nv.isMounted) return; if (this.isRoot()) return; this._v.parent.isBranchTransparent = true; Vue.nextTick(() => { let rect = this._v.boxEl.getBoundingClientRect(); updateNoodeSize(this._nv, this._v, rect.height, rect.width); this._v.parent.isBranchTransparent = false; }); } /** * Asynchronous method to capture the length of this noode's child branch (on the trunk axis) and adjust * the trunk's position if necessary. Use when resize detection is disabled to manually * trigger realignment on branch resize. Fails silently if this has no children or noodel is not mounted. */ realignBranch() { this.throwErrorIfDeleted(); if (!this._nv.isMounted) return; if (this.getChildCount() === 0) return; this._v.isBranchTransparent = true; Vue.nextTick(() => { let rect = this._v.branchBoxEl.getBoundingClientRect(); updateBranchSize(this._nv, this._v, rect.height, rect.width); this._v.isBranchTransparent = false; }); } /** * Asynchronous method to manually check for content overflow in this noode, * and refresh overflow indicators if they are enabled. Use when * overflow detection is disabled or insufficient (e.g. when content size changed * but did not affect noode size). Fails silently if this is root or noodel is not mounted. */ checkOverflow() { this.throwErrorIfDeleted(); if (!this._nv.isMounted) return; if (this.isRoot()) return; this._v.parent.isBranchTransparent = true; Vue.nextTick(() => { checkContentOverflow(this._nv, this._v); this._v.parent.isBranchTransparent = false; }); } }
the_stack
import promisify from "../helpers/promisify"; import ServerStreaming from "./streaming"; import { Protocol, InteropSettings } from "../types"; import ServerRepository from "./repository"; import { Glue42Core } from "../../../glue"; import { WrappedCallbackFunction, ResultContext, ServerMethodInfo } from "./types"; import ServerStream from "./stream"; /* The AGM Server allows users register AGM methods. It exposes these methods to AGM clients (using presence messages) and listens for their invocation */ export default class Server { private streaming: ServerStreaming; private invocations: number = 0; private currentlyUnregistering: { [method: string]: Promise<void> } = {}; constructor(private protocol: Protocol, private serverRepository: ServerRepository) { // An array of the server's methods this.streaming = new ServerStreaming(protocol, this); this.protocol.server.onInvoked(this.onMethodInvoked.bind(this)); } // Registers a new streaming agm method public createStream(streamDef: string | Glue42Core.AGM.MethodDefinition, callbacks?: Glue42Core.AGM.StreamOptions, successCallback?: (args?: object) => void, errorCallback?: (error?: string | object) => void, existingStream?: ServerStream): Promise<Glue42Core.AGM.Stream> { // in callbacks we have subscriptionRequestHandler, subscriptionAddedHandler, subscriptionRemovedHandler const promise = new Promise((resolve, reject) => { if (!streamDef) { reject(`The stream name must be unique! Please, provide either a unique string for a stream name to “glue.interop.createStream()” or a “methodDefinition” object with a unique “name” property for the stream.`); return; } // transform to a definition let streamMethodDefinition: Glue42Core.AGM.MethodDefinition; // This is important because if you change the name for example this will change here as well and it shouldn't change by reference if (typeof streamDef === "string") { streamMethodDefinition = { name: "" + streamDef }; } else { streamMethodDefinition = { ...streamDef }; } if (!streamMethodDefinition.name) { return reject(`The “name” property is required for the “streamDefinition” object and must be unique. Stream definition: ${JSON.stringify(streamMethodDefinition)}`); } const nameAlreadyExists = this.serverRepository.getList() .some((serverMethod) => serverMethod.definition.name === streamMethodDefinition.name); if (nameAlreadyExists) { return reject(`A stream with the name "${streamMethodDefinition.name}" already exists! Please, provide a unique name for the stream.`); } streamMethodDefinition.supportsStreaming = true; // User-supplied subscription callbacks if (!callbacks) { callbacks = {}; } if (typeof callbacks.subscriptionRequestHandler !== "function") { callbacks.subscriptionRequestHandler = (request: Glue42Core.AGM.SubscriptionRequest) => { request.accept(); }; } // Add the method const repoMethod = this.serverRepository.add({ definition: streamMethodDefinition, // store un-formatted definition for checkups in un-register method streamCallbacks: callbacks, protocolState: {}, }); this.protocol.server.createStream(repoMethod) .then(() => { let streamUserObject: ServerStream; if (existingStream) { streamUserObject = existingStream; existingStream.updateRepoMethod(repoMethod); } else { streamUserObject = new ServerStream(this.protocol, repoMethod, this); } repoMethod.stream = streamUserObject; resolve(streamUserObject); }) .catch((err) => { if (repoMethod.repoId) { this.serverRepository.remove(repoMethod.repoId); } reject(err); }); }); return promisify(promise, successCallback, errorCallback); } /** * Registers a new agm method * @param {MethodDefinition} methodDefinition * @param {MethodHandler} callback Callback that will be called when the AGM server is invoked */ public register(methodDefinition: string | Glue42Core.AGM.MethodDefinition, callback: (args: object, caller: Glue42Core.AGM.Instance) => object | Promise<object>): Promise<void> { if (!methodDefinition) { return Promise.reject(`Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.`); } if (typeof callback !== "function") { return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); } const wrappedCallbackFunction: WrappedCallbackFunction = async (context: ResultContext, resultCallback: (err: string | undefined, result: object) => void) => { // get the result as direct invocation of the callback and return it using resultCallback try { const result = callback(context.args, context.instance); if (result && typeof (result as any).then === "function") { const resultValue = await result; resultCallback(undefined, resultValue); } else { resultCallback(undefined, result); } } catch (e) { if (!e) { e = ""; } resultCallback(e, e); } }; wrappedCallbackFunction.userCallback = callback; return this.registerCore(methodDefinition, wrappedCallbackFunction); } // registers a new async agm method (the result can be returned in async way) public registerAsync(methodDefinition: string | Glue42Core.AGM.MethodDefinition, callback: (args: object, caller: Glue42Core.AGM.Instance, successCallback: (args?: object) => void, errorCallback: (error?: string | object) => void) => Promise<object> | void): Promise<void> { if (!methodDefinition) { return Promise.reject(`Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.`); } if (typeof callback !== "function") { return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`); } const wrappedCallback: WrappedCallbackFunction = (context: ResultContext, resultCallback: (err: string | undefined, result: object | undefined) => void) => { // invoke the callback passing success and error callbacks try { let resultCalled = false; const success = (result?: object) => { if (!resultCalled) { resultCallback(undefined, result); } resultCalled = true; }; const error = (e: any) => { if (!resultCalled) { if (!e) { e = ""; } resultCallback(e, e); } resultCalled = true; }; const methodResult = callback(context.args, context.instance, success, error ); if (methodResult && typeof methodResult.then === "function") { methodResult .then(success) .catch(error); } } catch (e) { resultCallback(e, undefined); } }; wrappedCallback.userCallbackAsync = callback; return this.registerCore(methodDefinition, wrappedCallback); } // Unregisters a previously registered AGM method public async unregister(methodFilter: string | Glue42Core.AGM.MethodDefinition, forStream: boolean = false): Promise<void> { if (methodFilter === undefined) { return Promise.reject(`Please, provide either a unique string for a name or an object containing a “name” property.`); } // WHEN A FUNCTION IS PASSED if (typeof methodFilter === "function") { await this.unregisterWithPredicate(methodFilter, forStream); return; } // WHEN string / object is passed let methodDefinition: Glue42Core.AGM.MethodDefinition; if (typeof methodFilter === "string") { methodDefinition = { name: methodFilter }; } else { methodDefinition = methodFilter; } if (methodDefinition.name === undefined) { return Promise.reject(`Method name is required. Cannot find a method if the method name is undefined!`); } const methodToBeRemoved: ServerMethodInfo | undefined = this.serverRepository.getList().find((serverMethod) => { return serverMethod.definition.name === methodDefinition.name && (serverMethod.definition.supportsStreaming || false) === forStream; // return this.containsProps(methodFilter, method.definition); }); if (!methodToBeRemoved) { return Promise.reject(`Method with a name "${methodDefinition.name}" does not exist or is not registered by your application!`); } await this.removeMethodsOrStreams([methodToBeRemoved]); } private async unregisterWithPredicate(filterPredicate: (methodDefinition: Glue42Core.AGM.MethodDefinition) => ServerMethodInfo, forStream?: boolean) { const methodsOrStreamsToRemove = this.serverRepository.getList() .filter((sm) => filterPredicate(sm.definition)) .filter((serverMethod) => // because both can be undefined or false (serverMethod.definition.supportsStreaming || false) === forStream ); if (!methodsOrStreamsToRemove || methodsOrStreamsToRemove.length === 0) { return Promise.reject(`Could not find a ${forStream ? "stream" : "method"} matching the specified condition!`); } await this.removeMethodsOrStreams(methodsOrStreamsToRemove); } private removeMethodsOrStreams(methodsToRemove: ServerMethodInfo[]) { const methodUnregPromises: Array<Promise<void>> = []; methodsToRemove.forEach((method) => { const promise = this.protocol.server.unregister(method) .then(() => { if (method.repoId) { this.serverRepository.remove(method.repoId); } }); methodUnregPromises.push(promise); this.addAsCurrentlyUnregistering(method.definition.name, promise); }); return Promise.all(methodUnregPromises); } private async addAsCurrentlyUnregistering(methodName: string, promise: Promise<void>) { const timeout = new Promise((resolve) => setTimeout(resolve, 5000)); // will be cleared when promise resolved this.currentlyUnregistering[methodName] = Promise.race([promise, timeout]).then(() => { delete this.currentlyUnregistering[methodName]; }); } // Core method for registering agm method private async registerCore(method: string | Glue42Core.AGM.MethodDefinition, theFunction: WrappedCallbackFunction): Promise<void> { // transform to a definition let methodDefinition: Glue42Core.AGM.MethodDefinition; // This is important because if you change the name for example this will change here as well and it shouldn't change by reference if (typeof method === "string") { methodDefinition = { name: "" + method }; } else { methodDefinition = { ...method }; } if (!methodDefinition.name) { return Promise.reject(`Please, provide a (unique) string value for the “name” property in the “methodDefinition” object: ${JSON.stringify(method)}`); } const unregisterInProgress = this.currentlyUnregistering[methodDefinition.name]; if (unregisterInProgress) { await unregisterInProgress; } const nameAlreadyExists = this.serverRepository.getList() .some((serverMethod) => serverMethod.definition.name === methodDefinition.name); if (nameAlreadyExists) { return Promise.reject(`A method with the name "${methodDefinition.name}" already exists! Please, provide a unique name for the method.`); } if (methodDefinition.supportsStreaming) { return Promise.reject(`When you create methods with “glue.interop.register()” or “glue.interop.registerAsync()” the property “supportsStreaming” cannot be “true”. If you want “${methodDefinition.name}” to be a stream, please use the “glue.interop.createStream()” method.`); } // Add the method () const repoMethod = this.serverRepository.add({ definition: methodDefinition, // store un-formatted definition for checkups in un-register method theFunction, protocolState: {}, }); // make it then .catch for those error/success callbacks return this.protocol.server.register(repoMethod) .catch((err: any) => { if (repoMethod?.repoId) { this.serverRepository.remove(repoMethod.repoId); } throw err; }); } private onMethodInvoked(methodToExecute: ServerMethodInfo, invocationId: string, invocationArgs: ResultContext) { if (!methodToExecute || !methodToExecute.theFunction) { return; } // Execute it and save the result methodToExecute.theFunction(invocationArgs, (err: any, result) => { if (err !== undefined && err !== null) { // handle error case if (err.message && typeof err.message === "string") { err = err.message; } else if (typeof err !== "string") { try { err = JSON.stringify(err); } catch (unStrException) { err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`; } } } if (!result) { result = {}; } else if (typeof result !== "object" || Array.isArray(result)) { // The AGM library only transfers objects. If the result is not an object, put it in one result = { _value: result }; } this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result); }); } }
the_stack
import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core'; import '@gravitee/ui-components/wc/gv-input'; import '@gravitee/ui-components/wc/gv-list'; import '@gravitee/ui-components/wc/gv-rating-list'; import '@gravitee/ui-components/wc/gv-confirm'; import { ApiService, ApplicationService, GetSubscriptionsRequestParams, PermissionsService, Subscription, SubscriptionService, } from '../../../../../projects/portal-webclient-sdk/src/lib'; import { ActivatedRoute, Router } from '@angular/router'; import { marker as i18n } from '@biesbjerg/ngx-translate-extract-marker'; import { TranslateService } from '@ngx-translate/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { NotificationService } from '../../../services/notification.service'; import { getPictureDisplayName } from '@gravitee/ui-components/src/lib/item'; import StatusEnum = Subscription.StatusEnum; @Component({ selector: 'app-application-subscriptions', templateUrl: './application-subscriptions.component.html', styleUrls: ['./application-subscriptions.component.css'], }) export class ApplicationSubscriptionsComponent implements OnInit { subscriptions: Array<Subscription>; options: any; format: any; form: FormGroup = this.formBuilder.group({ api: '', status: [], apiKey: '', }); apisOptions: any; statusOptions: any; metadata: any; selectedSubscriptions: Array<string>; selectedSubscription: Subscription; displayExpiredApiKeys: boolean; canDelete: boolean; canUpdate: boolean; isSearching: boolean; constructor( private route: ActivatedRoute, private router: Router, private applicationService: ApplicationService, private subscriptionService: SubscriptionService, private notificationService: NotificationService, private translateService: TranslateService, private apiService: ApiService, private formBuilder: FormBuilder, private permissionsService: PermissionsService, private ref: ChangeDetectorRef, private ngZone: NgZone, ) {} ngOnInit() { const application = this.route.snapshot.data.application; const permissions = this.route.snapshot.data.permissions; if (application) { this.canDelete = permissions.SUBSCRIPTION && permissions.SUBSCRIPTION.includes('D'); this.canUpdate = permissions.SUBSCRIPTION && permissions.SUBSCRIPTION.includes('U'); this.format = (key) => this.translateService.get(key).toPromise(); this.apisOptions = []; this.options = { selectable: true, data: [ { field: 'api', type: 'image', alt: (item) => this.metadata[item.api] && getPictureDisplayName(this.metadata[item.api]), format: (item) => this.metadata[item] && this.metadata[item].pictureUrl, }, { field: 'api', label: i18n('application.subscriptions.api'), tag: (item) => this.metadata[item.api] && this.metadata[item.api].version, format: (item) => this.metadata[item] && this.metadata[item].name, }, { field: 'plan', label: i18n('application.subscriptions.plan'), format: (item) => this.metadata[item] && this.metadata[item].name, }, { field: 'created_at', type: 'date', label: i18n('application.subscriptions.created_at'), width: '160px' }, { field: 'subscribed_by', label: i18n('application.subscriptions.subscribed_by'), format: (item) => this.metadata[item] && this.metadata[item].name, width: '190px', }, { field: 'status', label: i18n('application.subscriptions.status'), width: '80px', format: (key) => { const statusKey = 'common.status.' + key.toUpperCase(); return this.translateService.get(statusKey).toPromise(); }, style: (item) => { switch (item.status.toUpperCase()) { case StatusEnum.ACCEPTED: return 'color: #009B5B'; case StatusEnum.PAUSED: case StatusEnum.PENDING: return 'color: #FA8C16'; case StatusEnum.REJECTED: return 'color: #F5222D'; } }, }, { type: 'gv-button', width: '25px', condition: (item) => this.metadata[item.api] && this.metadata[item.api].state === 'published', attributes: { link: true, href: (item) => `/catalog/api/${item.api}`, title: i18n('application.subscriptions.navigateToApi'), icon: 'communication:share', onClick: (item, e) => this.goToApi(item.api), }, }, ], }; this.applicationService .getSubscriberApisByApplicationId({ applicationId: application.id, size: -1 }) .toPromise() .then((apis) => { this.apisOptions = []; apis.data.forEach((api) => { this.apisOptions.push({ label: api.name + ' (' + api.version + ')', value: api.id }); }); }); const statusKeys = Object.keys(StatusEnum).map((s) => 'common.status.' + s); this.translateService .get(statusKeys) .toPromise() .then((translatedKeys) => { this.statusOptions = Object.keys(StatusEnum).map((s, i) => { return { label: Object.values(translatedKeys)[i], value: s }; }); this.form.patchValue({ status: [StatusEnum.ACCEPTED, StatusEnum.PAUSED, StatusEnum.PENDING] }); this.search(true); }); } } canRenew(subscription: Subscription) { return subscription && this.canUpdate && [`${StatusEnum.ACCEPTED}`, `${StatusEnum.PAUSED}`].includes(subscription.status.toUpperCase()); } canRevoke(subscription: Subscription) { return ( subscription && this.canDelete && [`${StatusEnum.ACCEPTED}`, `${StatusEnum.PAUSED}`, `${StatusEnum.PENDING}`].includes(subscription.status.toUpperCase()) ); } goToApi(apiId: string) { this.ngZone.run(() => this.router.navigate(['/catalog/api/', apiId])); } search(displaySubscription?) { const applicationId = this.route.snapshot.params.applicationId; const requestParameters: GetSubscriptionsRequestParams = { applicationId }; if (this.form.value.api) { requestParameters.apiId = this.form.value.api; } if (this.form.value.status) { requestParameters.statuses = this.form.value.status; } this.isSearching = true; this.subscriptionService .getSubscriptions(requestParameters) .toPromise() .then((response) => { this.subscriptions = response.data; this.metadata = response.metadata; if (displaySubscription && this.route.snapshot.queryParams.subscription) { const subscription = this.subscriptions.find((s) => s.id === this.route.snapshot.queryParams.subscription); this.selectedSubscriptions = [subscription.id]; this.onSelectSubscription(subscription); } else { this.selectedSubscriptions = []; this.onSelectSubscription(null); } }) .finally(() => (this.isSearching = false)); } reset() { this.form.reset({ status: [StatusEnum.ACCEPTED, StatusEnum.PAUSED, StatusEnum.PENDING], }); } closeSubscription(subscriptionId) { this.subscriptionService .closeSubscription({ subscriptionId }) .toPromise() .then(() => { this.notificationService.success(i18n('application.subscriptions.success.close')); this.search(false); }); } renewSubscription(subscriptionId) { this.subscriptionService .renewKeySubscription({ subscriptionId }) .toPromise() .then(() => { this.notificationService.success(i18n('application.subscriptions.success.renew')); this.search(true); }); } revokeApiKey(subscriptionId, apiKey) { this.subscriptionService .revokeKeySubscription({ subscriptionId, apiKey }) .toPromise() .then(() => { this.notificationService.success(i18n('application.subscriptions.apiKey.success.revoke')); this.search(true); }); } onSelectSubscription(subscription: Subscription) { this.router.navigate([], { queryParams: { subscription: subscription ? subscription.id : null }, fragment: 's' }); if (subscription) { this.selectedSubscription = subscription; if (!this.selectedSubscription.keys || !this.selectedSubscription.keys[0]) { this.subscriptionService .getSubscriptionById({ subscriptionId: subscription.id, include: ['keys'] }) .toPromise() .then((sub) => { this.subscriptions.find((s) => s.id === subscription.id).keys = sub.keys; this.ref.detectChanges(); }); } } else { delete this.selectedSubscription; } } getValidApiKeys(sub: Subscription) { if (sub && sub.keys) { const validApiKeys = sub.keys.filter((apiKey) => this.isApiKeyValid(apiKey)); if (validApiKeys && validApiKeys.length > 0) { return validApiKeys; } } } getExpiredApiKeys(sub: Subscription) { if (sub && sub.keys) { const expiredApiKeys = sub.keys.filter((apiKey) => !this.isApiKeyValid(apiKey)); if (expiredApiKeys && expiredApiKeys.length > 0) { return expiredApiKeys; } } } endAt(apiKey) { return apiKey.revoked_at || apiKey.expire_at; } apiKeyEnded(apiKey) { const endAt = this.endAt(apiKey); return endAt && new Date(endAt) < new Date(); } isApiKeyValid(apiKey) { return !this.endAt(apiKey) || !this.apiKeyEnded(apiKey); } toggleDisplayExpired() { this.displayExpiredApiKeys = !this.displayExpiredApiKeys; this.ref.detectChanges(); } }
the_stack
import 'mocha'; import 'chai'; import { newDb } from '../db'; import { expect, assert } from 'chai'; import { preventSeqScan } from './test-utils'; import { Types } from '../datatypes'; import { _IDb } from '../interfaces-private'; describe('Indices', () => { let db: _IDb; let many: (str: string) => any[]; let none: (str: string) => void; function all(table = 'test') { return many(`select * from ${table}`); } beforeEach(() => { db = newDb() as _IDb; many = db.public.many.bind(db.public); none = db.public.none.bind(db.public); }); function simpleDb() { db.public.declareTable({ name: 'data', fields: [{ name: 'id', type: Types.text(), constraints: [{ type: 'primary key' }], }, { name: 'str', type: Types.text(), }, { name: 'otherstr', type: Types.text(), }], }); return db; } function setupNulls(withIndex = true) { db = simpleDb() if (withIndex) { none('create index on data(str);') } none(`insert into data(id, str) values ('id1', null); insert into data(id, str) values ('id2', 'notnull2'); insert into data(id, str) values ('id3', null); insert into data(id, str) values ('id4', 'notnull4')`); return db; } it('uses indexes for null values', () => { const db = setupNulls(); preventSeqScan(db); const got = many('select * from data where str is null'); expect(got).to.deep.equal([{ id: 'id1', str: null, otherstr: null }, { id: 'id3', str: null, otherstr: null }]); }); it('returns something on seqscan for is null', () => { const db = setupNulls(false); const got = many('select * from data where str is null'); expect(got).to.deep.equal([{ id: 'id1', str: null, otherstr: null }, { id: 'id3', str: null, otherstr: null }]); }); it('uses indexes for not null values', () => { const db = setupNulls(); preventSeqScan(db); const got = many('select id, str from data where str is not null'); expect(got).to.deep.equal([{ id: 'id2', str: 'notnull2' }, { id: 'id4', str: 'notnull4' }]); }); it('primary index does not allow duplicates', () => { none(`create table test(id text primary key); insert into test values ('id1');`); assert.throws(() => none(`insert into test values ('id1')`)); expect(all().map(x => x.id)).to.deep.equal(['id1']); }); it('primary index does not allow null values', () => { none(`create table test(id text primary key);`); assert.throws(() => none(`insert into test values (null)`)); }); it('can unique index', () => { none(`create table test(col text); create unique index idx1 on test(col); insert into test values ('one'), ('two')`); assert.throws(() => none(`insert into test values ('one')`), /constraint/); }); it('can create partial indexes', () => { // https://github.com/oguimbal/pg-mem/issues/89 none(`create table my_table(col1 text, col2 text); CREATE UNIQUE INDEX my_idx ON my_table (col1, (col2 IS NULL)) WHERE col2 IS NULL; insert into my_table values ('a', 'a'), ('a', 'b'), ('a', null), ('b', null)`); assert.throws(() => none(`insert into my_table values ('a', null)`), /constraint/); }); describe('[bugfix #160] indexes with default values', () => { // checks issue described in https://github.com/oguimbal/pg-mem/issues/160 function begin160(condition = 'deleted_at IS NULL') { none(`create table "test_table" ( "id" character varying(36) NOT NULL, "unique_data" character varying(36), "deleted_at" timestamp without time zone, CONSTRAINT "PK_test_table_id" PRIMARY KEY ("id") ); CREATE UNIQUE INDEX "UXtest_table_unique_data" ON "public"."test_table" ("unique_data") WHERE ${condition}; insert into test_table ("id", "unique_data", "deleted_at") VALUES('1', default, default );`); } function simple160(condition = 'deleted_at IS NULL') { begin160(condition); // this was throwing: none(`insert into test_table ("id", "unique_data", "deleted_at") VALUES('2', default, default );`) } it('can insert multiple default values on partial indexes ', () => { simple160(); }); it('can update to default value on partial indexes ', () => { // checks issue described in https://github.com/oguimbal/pg-mem/issues/160 begin160(); none(`insert into test_table ("id", "unique_data", "deleted_at") VALUES('2', 'x', default );`); // this was throwing: none(`update test_table set unique_data=default where id='2'`) }); it('insert into select is OK with partial indexes', () => { // checks issue described in https://github.com/oguimbal/pg-mem/issues/160 begin160(); // was throwing n°1 none(`insert into test_table ("id", "unique_data", "deleted_at") VALUES('2', default, default );`) // was throwing n°2 none(`insert into test_table(id,unique_data,deleted_at) (select id || 'bis', unique_data, deleted_at from test_table)`); }); it('behaves the same on notnulls', () => { simple160('deleted_at NOTNULL'); }); it('behaves the same on not isnull', () => { simple160('NOT(deleted_at ISNULL)'); }); it('behaves the same on not notnull', () => { simple160('NOT(deleted_at NOTNULL)'); }); it('throws when unique is not default', () => { none(` drop table if exists test_table; create table "test_table" ( "id" character varying(36) NOT NULL, "unique_data" character varying(36), "deleted_at" timestamp without time zone, CONSTRAINT "PK_test_table_id" PRIMARY KEY ("id") ); CREATE UNIQUE INDEX "UXtest_table_unique_data" ON "public"."test_table" ("unique_data") where deleted_at isnull; insert into test_table ("id", "unique_data", "deleted_at") VALUES('1', 'x', default ); `) assert.throws(() => none(`insert into test_table ("id", "unique_data", "deleted_at") VALUES('2', 'x', default );`), /duplicate key value violates unique constraint/); }); it('accepts two default not set values on non partial', () => { none(` create table "test_table" ( "id" text not null primary key, "unique_data" text ); CREATE UNIQUE INDEX ON test_table (unique_data); insert into test_table ("id", "unique_data") VALUES('1', default); insert into test_table ("id", "unique_data") VALUES('2', default); `); }) it('accepts two default null values on non partial', () => { none(` create table "test_table" ( "id" text not null primary key, "unique_data" text default null ); CREATE UNIQUE INDEX ON test_table (unique_data); insert into test_table ("id", "unique_data") VALUES('1', default); insert into test_table ("id", "unique_data") VALUES('2', default); `); }); it('rejects two default not null values on non partial', () => { none(` create table "test_table" ( "id" text not null primary key, "unique_data" text default 'some default' ); CREATE UNIQUE INDEX ON test_table (unique_data); insert into test_table ("id", "unique_data") VALUES('1', default); `); assert.throws(() => none(`insert into test_table ("id", "unique_data") VALUES('2', default)`), /duplicate key value violates unique constraint/); }); it('allows multiple null values in unique index', () => { none(` create table "test_table" ( "id" text not null primary key, "unique_data" text default null ); CREATE UNIQUE INDEX ON test_table (unique_data); insert into test_table ("id", "unique_data") VALUES('1', default); insert into test_table ("id", "unique_data") VALUES('2', default); insert into test_table ("id", "unique_data") VALUES('3', null); insert into test_table ("id", "unique_data") VALUES('4', null); `); }); it('prevens inserting nulls on compound primary keys even when defaults', () => { none(` create table "test_table" ( "u1" text default null, "u2" text default null, primary key (u1, u2) );`); assert.throws(() => none(`insert into test_table ("u1", "u2") VALUES('1', default)`), /\s+null\s+/); assert.throws(() => none(`insert into test_table ("u1", "u2") VALUES('1', null)`), /\s+null\s+/); }); }); it('can create the same named index twice', () => { none(`create table test(col text); create index idx1 on test(col); create index idx2 on test(col);`); }); it('can create index if not exists', () => { none(`create table test(col text); create index idxname on test(col); create index if not exists idxname on test(col);`); }); it('reads .ifNotExists when creating index', () => { none(`create table test(col text); create index if not exists idxname on test(col);`); }); it('cannot create index twice', () => { none(`create table test(col text); create index idxname on test(col);`); assert.throws(() => none(`create index idxname on test(col)`), /exists/); }); it('cannot create index which has same name as a table', () => { none(`create table test(col text);`); assert.throws(() => none(`create index test on test(col)`), /exists/); }); it('can create the same anonymous index twice', () => { none(`create table test(col text); create index on test(col); create index on test(col);`); }); it('unique index does not allow duplicates', () => { none(`create table test(id text primary key, val text unique); insert into test values ('id1', 'A');`); assert.throws(() => none(`insert into test values ('id2', 'A')`)); expect(all().map(x => x.id)).to.deep.equal(['id1']); }); it('index allows duplicates', () => { none(`create table test(id text primary key, val text); create index on test(val); insert into test values ('id1', 'A'); insert into test values ('id2', 'B'); insert into test values ('id3', 'A');`); expect(all().map(x => x.id)).to.deep.equal(['id1', 'id2', 'id3']); preventSeqScan(db); // <== should use index even if index is on expression expect(many(`select id from test where val='A'`).map(x => x.id)).to.deep.equal(['id1', 'id3']); }); it('can create index on an expression', () => { none(`create table test(id text primary key, val text); create index on test(LOWER(val)); insert into test values ('id1', 'A'); insert into test values ('id2', 'B'); insert into test values ('id3', 'a');`); preventSeqScan(db); // <== should use index even if index is on expression expect(many(`select id from test where lower(val)='a'`).map(x => x.id)).to.deep.equal(['id1', 'id3']); }); it('can commutative index on an expression', () => { none(`create table test(a integer, b integer); create index on test((a+b)); insert into test values (1, 2); insert into test values (3, 4);`); preventSeqScan(db); // <== should use index even if index is on expression // notice that b+a is not the expression usedin index creation expect(many(`select a from test where (b+a)=3`).map(x => x.a)).to.deep.equal([1]); }); it('can use an index on an aliased selection not aliased var', () => { preventSeqScan(db); const got = many(`create table test(txt text, val integer); create index on test(txt); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select * from (select val from test where txt != 'A') x where x.val > 1`); const explain = db.public.explainLastSelect(); // assert.deepEqual(explain, {} as any); assert.deepEqual(explain, { _: 'ineq', entropy: 3, id: 1, on: { _: 'indexMap', of: { _: 'indexRestriction', lookup: { _: 'btree', btree: ['val'], onTable: 'test', }, for: { _: 'neq', entropy: 10 / 3, id: 2, on: { _: 'btree', btree: ['txt'], onTable: 'test', } } } } }) expect(got) .to.deep.equal([{ val: 2 }, { val: 3 }]); }); it('can use an index on an aliased selection & aliased var', () => { // preventSeqScan(db); const got = many(`create table test(txt text, val integer); create index on test(txt); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select * from (select val as xx from test where txt != 'A') x where x.xx > 1`); const explain = db.public.explainSelect(`select * from (select val as xx from test where txt != 'A') x where x.xx > 1`); assert.deepEqual(explain, { _: 'seqFilter', id: 1, filtered: { _: 'map', id: 2, select: [{ what: { on: 'test', col: 'val' }, as: 'xx', }], of: { _: 'neq', id: 3, entropy: 10 / 3, on: { _: 'btree', btree: ['txt'], onTable: 'test', } } } }); expect(got) .to.deep.equal([{ xx: 2 }, { xx: 3 }]); }); it('can use an index on an aliased "!=" selection', () => { // preventSeqScan(db); expect(many(`create table test(txt text, val integer); create index on test(txt); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select * from (select val as xx from test where txt != 'A') x where x.xx > 1`)) .to.deep.equal([{ xx: 2 }, { xx: 3 }]); }); it('can use an index on an aliased "=" selection', () => { // preventSeqScan(db); expect(many(`create table test(txt text, val integer); create index on test(txt); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select * from (select val as xx from test where txt = 'A') x where x.xx >= 1`)) .to.deep.equal([{ xx: 999 }, { xx: 1 }]); }); it('can use an index on an aliased "=" expression selection', () => { // preventSeqScan(db); expect(many(`create table test(txt text, val integer); create index on test(lower(txt)); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select * from (select val as xx from test where lower(txt) = 'a') x where x.xx >= 1`)) .to.deep.equal([{ xx: 999 }, { xx: 1 }]); }); it('can use an index expression on a transformedselection', () => { // preventSeqScan(db); expect(many(`create table test(txt text, val integer); create index on test(lower(txt)); create index on test(val); insert into test values ('A', 999); insert into test values ('A', 0); insert into test values ('A', 1); insert into test values ('B', 2); insert into test values ('C', 3); select valx from (select val as valx, txt as txtx from test where val >= 1) x where lower(x.txtx) = 'a'`)) .to.deep.equal([{ valx: 1 }, { valx: 999 }]); }); it('can use constant in index expressions', () => { none(`create table test(id text primary key, val text); create index on test(concat(val, 'X')); insert into test values ('id1', 'A'); insert into test values ('id2', 'B'); insert into test values ('id3', 'A');`); preventSeqScan(db); // <== should use index even if index is on expression expect(many(`select id from test where concat(val, 'X')='AX'`).map(x => x.id)).to.deep.equal(['id1', 'id3']); }); it('can use constant in index expressions bis', () => { none(`create table test(id text primary key, a int, b int); create index on test((a+b)); insert into test values ('id1', 40, 2); insert into test values ('id2', 1, 2); insert into test values ('id3', 30, 12);`); preventSeqScan(db); // <== should use index even if index is on expression expect(many(`select id from test where a+b=42`).map(x => x.id)).to.deep.equal(['id1', 'id3']); }); it('can use implicit cast index on index', () => { expect(many(`create table example(id int primary key); insert into example(id) values (1); select * from example where id='1';`)) .to.deep.equal([ { id: 1 } ]); expect(many(`select * from example where id>'0';`)) .to.deep.equal([ { id: 1 } ]); expect(many(`select * from example where id<'3';`)) .to.deep.equal([ { id: 1 } ]); expect(many(`select * from example where id>'1';`)) .to.deep.equal([]); }) describe('Indexes on comparisons', () => { it('uses asc index on > comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val); insert into test values (1), (2), (3), (4); select * from test where val > 2`); expect(result).to.deep.equal([{ val: 3 }, { val: 4 }]); }); it('uses desc index on > comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val desc); insert into test values (1), (2), (3), (4); select * from test where val > 2`); expect(result).to.deep.equal([{ val: 3 }, { val: 4 }]); }); it('uses asc index on < comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val); insert into test values (1), (2), (3), (4); select * from test where val < 3`); expect(result).to.deep.equal([{ val: 1 }, { val: 2 }]); }); it('uses desc index on < comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val desc); insert into test values (1), (2), (3), (4); select * from test where val < 3`); expect(result).to.deep.equal([{ val: 1 }, { val: 2 }]); }); it('uses index on <= comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val); insert into test values (1), (2), (3), (4); select * from test where val <= 2`); expect(result).to.deep.equal([{ val: 1 }, { val: 2 }]); }); it('uses index on >= comparison', () => { preventSeqScan(db); const result = many(`create table test(val integer); create index on test(val); insert into test values (1), (2), (3), (4); select * from test where val >= 2`); expect(result).to.deep.equal([{ val: 2 }, { val: 3 }, { val: 4 }]); }); }) });
the_stack
import { TestBed, fakeAsync, ComponentFixture, tick, flush } from '@angular/core/testing'; import { Component, Type } from '@angular/core'; import { MdcSwitchDirective, MdcSwitchInputDirective, MdcSwitchThumbDirective } from './mdc.switch.directive'; import { By } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; describe('MdcSwitchDirective', () => { it('should render the switch with correct styling and sub-elements', fakeAsync(() => { const { switchElement } = setup(); expect(switchElement.classList).toContain('mdc-switch'); expect(switchElement.children.length).toBe(2); expect(switchElement.children[0].classList).toContain('mdc-switch__track'); expect(switchElement.children[1].classList).toContain('mdc-switch__thumb-underlay'); const thumbUnderlay = switchElement.children[1]; expect(thumbUnderlay.children.length).toBe(2); expect(thumbUnderlay.children[0].classList).toContain('mdc-switch__thumb'); expect(thumbUnderlay.children[1].classList).toContain('mdc-switch__native-control'); })); it('checked can be set programmatically', fakeAsync(() => { const { fixture, testComponent, element } = setup(); expect(testComponent.checked).toBe(null); expect(element.checked).toBe(false); setAndCheck(fixture, 'yes', true); setAndCheck(fixture, 1, true); setAndCheck(fixture, true, true); setAndCheck(fixture, 'false', false); setAndCheck(fixture, '0', true); setAndCheck(fixture, false, false); setAndCheck(fixture, 0, true); setAndCheck(fixture, null, false); setAndCheck(fixture, '', true); })); it('checked can be set by user', fakeAsync(() => { const { fixture, element } = setup(); expect(element.checked).toBe(false); clickAndCheck(fixture, true, false); clickAndCheck(fixture, false, false); clickAndCheck(fixture, true, false); })); it('can be disabled', fakeAsync(() => { const { fixture, testComponent, element, input } = setup(); testComponent.disabled = true; fixture.detectChanges(); expect(element.disabled).toBe(true); expect(input.disabled).toBe(true); expect(testComponent.disabled).toBe(true); const sw = fixture.debugElement.query(By.directive(MdcSwitchDirective)).injector.get(MdcSwitchDirective); expect(sw['root'].nativeElement.classList).toContain('mdc-switch--disabled'); testComponent.disabled = false; fixture.detectChanges(); expect(element.disabled).toBe(false); expect(input.disabled).toBe(false); expect(testComponent.disabled).toBe(false); })); it('native input can be changed dynamically', fakeAsync(() => { const { fixture, testComponent } = setup(TestComponentDynamicInput); let elements = fixture.nativeElement.querySelectorAll('.mdc-switch__native-control'); // when no input is present the mdcSwitch renders without an initialized foundation: expect(elements.length).toBe(0); let check = false; for (let i = 0; i != 3; ++i) { // render/include one of the inputs: testComponent.input = i; fixture.detectChanges(); // the input should be recognized, the foundation is (re)initialized, // so we have a fully functional mdcSwitch now: elements = fixture.nativeElement.querySelectorAll('.mdc-switch__native-control'); expect(elements.length).toBe(1); expect(elements[0].classList).toContain('mdc-switch__native-control'); expect(elements[0].id).toBe(`i${i}`); // the value of the native input is correctly synced with the testcomponent: expect(elements[0].checked).toBe(check); // change the value for the next iteration: check = !check; testComponent.checked = check; fixture.detectChanges(); expect(elements[0].checked).toBe(check); } // removing input should also work: testComponent.input = null; fixture.detectChanges(); elements = fixture.nativeElement.querySelectorAll('.mdc-switch__native-control'); // when no input is present the mdcSwitch renders without an initialized foundation: expect(elements.length).toBe(0); expect(testComponent.checked).toBe(check); })); it('user interactions are registered in the absence of template bindings', fakeAsync(() => { const { fixture, element, input } = setup(TestComponentNoBindings); expect(element.checked).toBe(false); expect(input.checked).toBe(false); clickAndCheckNb(true); clickAndCheckNb(false); clickAndCheckNb(true); function clickAndCheckNb(expected) { element.click(); tick(); fixture.detectChanges(); flush(); expect(element.checked).toBe(expected); expect(input.checked).toBe(expected); } })); it('aria-checked should reflect state of switch', (() => { const { fixture, testComponent, element } = setup(); expect(element.getAttribute('aria-checked')).toBe('false'); element.click(); // user change expect(element.getAttribute('aria-checked')).toBe('true'); testComponent.checked = false; //programmatic change fixture.detectChanges(); expect(element.getAttribute('aria-checked')).toBe('false'); })); it('input should have role=switch attribute', (() => { const { element } = setup(); expect(element.getAttribute('role')).toBe('switch'); })); function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any, expected: boolean) { const testComponent = fixture.debugElement.injector.get(TestComponent); const element = fixture.nativeElement.querySelector('.mdc-switch__native-control'); const input = fixture.debugElement.query(By.directive(MdcSwitchInputDirective))?.injector.get(MdcSwitchInputDirective); testComponent.checked = value; fixture.detectChanges(); expect(element.checked).toBe(expected); expect(input.checked).toBe(expected); } function clickAndCheck(fixture: ComponentFixture<TestComponent>, expected: boolean, expectIndeterminate: any) { const testComponent = fixture.debugElement.injector.get(TestComponent); const element = fixture.nativeElement.querySelector('.mdc-switch__native-control'); const input = fixture.debugElement.query(By.directive(MdcSwitchInputDirective))?.injector.get(MdcSwitchInputDirective); element.click(); tick(); fixture.detectChanges(); expect(element.checked).toBe(expected); expect(input.checked).toBe(expected); expect(testComponent.checked).toBe(expected); } @Component({ template: ` <div mdcSwitch> <div mdcSwitchThumb> <input mdcSwitchInput type="checkbox" id="basic-switch" [checked]="checked" (click)="onClick()" [disabled]="disabled"> </div> </div> <label for="basic-switch">off/on</label> ` }) class TestComponent { checked: any = null; disabled: any = null; onClick() { this.checked = !this.checked; } } @Component({ template: ` <div mdcSwitch> <div mdcSwitchThumb> <input mdcSwitchInput type="checkbox" id="basic-switch"> </div> </div> ` }) class TestComponentNoBindings { } @Component({ template: ` <div mdcSwitch> <div mdcSwitchThumb> <input *ngIf="input === 0" id="i0" mdcSwitchInput type="checkbox" [checked]="checked"/> <input *ngIf="input === 1" id="i1" mdcSwitchInput type="checkbox" [checked]="checked"/> <input *ngIf="input === 2" id="i2" mdcSwitchInput type="checkbox" [checked]="checked"/> </div> </div> ` }) class TestComponentDynamicInput { input: number = null; checked: any = null; } function setup(compType: Type<any> = TestComponent) { const fixture = TestBed.configureTestingModule({ declarations: [MdcSwitchDirective, MdcSwitchInputDirective, MdcSwitchThumbDirective, compType] }).createComponent(compType); fixture.detectChanges(); const testComponent = fixture.debugElement.injector.get(compType); const input = fixture.debugElement.query(By.directive(MdcSwitchInputDirective))?.injector.get(MdcSwitchInputDirective); const element = fixture.nativeElement.querySelector('.mdc-switch__native-control'); const switchElement = fixture.nativeElement.querySelector('.mdc-switch'); return { fixture, testComponent, input, element, switchElement }; } }); describe('MdcSwitchDirective with FormsModule', () => { it('ngModel can be set programmatically', fakeAsync(() => { const { fixture, testComponent, element } = setup(); expect(testComponent.value).toBe(null); expect(element.checked).toBe(false); // Note that binding to 'ngModel' behaves slightly different from binding to 'checked' // ngModel coerces values the javascript way: it does !!bindedValue // checked coerces the string-safe way: value != null && `${value}` !== 'false' setAndCheck(fixture, 'yes', true); setAndCheck(fixture, false, false); setAndCheck(fixture, 'false', true); // the way it works for ngModel... setAndCheck(fixture, null, false); setAndCheck(fixture, 1, true); setAndCheck(fixture, 0, false); setAndCheck(fixture, '0', true); })); it('ngModel can be changed by updating checked property', fakeAsync(() => { const { fixture, testComponent, input } = setup(); input.checked = true; fixture.detectChanges(); tick(); expect(testComponent.value).toBe(true); input.checked = false; fixture.detectChanges(); tick(); expect(testComponent.value).toBe(false); })); it('ngModel can be changed by user', fakeAsync(() => { const { fixture, testComponent, element, input } = setup(); element.click(); tick(); fixture.detectChanges(); expect(element.checked).toBe(true); expect(input.checked).toBe(true); expect(testComponent.value).toBe(true); element.click(); tick(); fixture.detectChanges(); expect(element.checked).toBe(false); expect(input.checked).toBe(false); expect(testComponent.value).toBe(false); })); function setAndCheck(fixture: ComponentFixture<TestComponent>, value: any, expectedValue: boolean) { const testComponent = fixture.debugElement.injector.get(TestComponent); const element = fixture.nativeElement.querySelector('.mdc-switch__native-control'); const input = fixture.debugElement.query(By.directive(MdcSwitchInputDirective)).injector.get(MdcSwitchInputDirective); testComponent.value = value; fixture.detectChanges(); tick(); expect(input.checked).toBe(expectedValue); expect(element.checked).toBe(expectedValue); expect(testComponent.value).toBe(value); } @Component({ template: ` <div mdcSwitch> <input mdcSwitchInput type="checkbox" [(ngModel)]="value"/> </div> ` }) class TestComponent { value: any = null; } function setup() { const fixture = TestBed.configureTestingModule({ imports: [FormsModule], declarations: [MdcSwitchInputDirective, MdcSwitchDirective, TestComponent] }).createComponent(TestComponent); fixture.detectChanges(); tick(); const testComponent = fixture.debugElement.injector.get(TestComponent); const input = fixture.debugElement.query(By.directive(MdcSwitchInputDirective)).injector.get(MdcSwitchInputDirective); const element = fixture.nativeElement.querySelector('.mdc-switch__native-control'); return { fixture, testComponent, input, element }; } });
the_stack
import { ReadStream } from "fs" export interface IAPIError { errMsg: string } export interface IAPISuccessParam { errMsg: string } export type IAPICompleteParam = IAPISuccessParam | IAPIError export type IAPIFunction<T, P> = (param: P) => Promise<T> | any export interface ICloudConfig { env?: string | { database?: string functions?: string storage?: string } traceUser?: boolean database: { realtime: { // max reconnect retries maxReconnect: number // interval between reconnection attempt, does not apply to the case of network offline, unit: ms reconnectInterval: number // maximum tolerance on the duration of websocket connection lost, unit: s totalConnectionTimeout: number } } } export type ICloudInitOptions = Partial<ICloudConfig> export interface ICommonAPIConfig { env?: string } export interface IICloudAPI { init: (config?: ICloudConfig) => void [api: string]: AnyFunction | IAPIFunction<any, any> } export interface ICloudService { name: string context: IServiceContext getAPIs: () => { [name: string]: IAPIFunction<any, any> } } export interface IServiceContext { name: string identifiers: IRuntimeIdentifiers request: any debug: boolean env?: string } export interface ICloudServices { [serviceName: string]: ICloudService } export interface ICloudMetaData { session_id: string sdk_version?: string } export interface ICloudClass { apiPermissions: object config: ICloudConfig registerService(service: ICloudService): void } export interface IRuntimeIdentifiers { pluginId?: string [key: string]: any } export type AnyObject = { [x: string]: any } export type AnyArray = any[] export type AnyFunction = (...args: any[]) => any /** * cloud */ // init export function init(config?: ICloudInitOptions): void // functions export function callFunction(param: ICloud.CallFunctionParam): Promise<ICloud.CallFunctionResult> | void // storage export function uploadFile(param: ICloud.UploadFileParam): Promise<ICloud.UploadFileResult> export function downloadFile(param: ICloud.DownloadFileParam): Promise<ICloud.DownloadFileResult> export function getTempFileURL(param: ICloud.GetTempFileURLParam): Promise<ICloud.GetTempFileURLResult> | void export function deleteFile(param: ICloud.DeleteFileParam): Promise<ICloud.DeleteFileResult> | void // database export function database(config?: DB.IDatabaseConfig): DB.Database // open export const openapi: Record<string, any> export function getOpenData(param: ICloud.GetOpenDataParam): ICloud.GetOpenDataResult export function getOpenData(param: ICloud.GetOpenDataParam): ICloud.GetOpenDataResult // utils export function getWXContext(): ICloud.WXContext export function logger(): ICloud.Logger // constants export const DYNAMIC_CURRENT_ENV: symbol declare namespace ICloud { // === API: getWXContext === export interface BaseWXContext { OPENID?: string APPID?: string UNIONID?: string ENV?: string SOURCE?: string CLIENTIP?: string CLIENTIPV6?: string } // === API: logger === export class Logger { log(object: Record<string, any>): void info(object: Record<string, any>): void warn(object: Record<string, any>): void error(object: Record<string, any>): void } export type WXContext = BaseWXContext & Record<string, any> // === API: getOpenData === export interface GetOpenDataParam { list: string[] } export interface GetOpenDataResult extends IAPISuccessParam { list: Record<string, any>[] } // === API: getVoIPSign === export interface GetVoIPSignParam { groupId: string nonce: string timestamp: number } export interface GetVoIPSignResult extends IAPISuccessParam { signature: string } // === API: callFunction === export type CallFunctionData = AnyObject export interface CallFunctionResult extends IAPISuccessParam { result: AnyObject | string | undefined requestID?: string } export interface CallFunctionParam { name: string data?: CallFunctionData slow?: boolean version?: number config?: { env?: string } } // === end === // === API: uploadFile === export interface UploadFileResult extends IAPISuccessParam { fileID: string statusCode: number } export interface UploadFileParam { cloudPath: string fileContent: Buffer | ReadStream } // === end === // === API: downloadFile === export interface DownloadFileResult extends IAPISuccessParam { fileContent: Buffer statusCode: number } export interface DownloadFileParam { fileID: string } // === end === // === API: getTempFileURL === export interface GetTempFileURLResult extends IAPISuccessParam { fileList: GetTempFileURLResultItem[] } export interface GetTempFileURLResultItem { fileID: string tempFileURL: string maxAge: number status: number errMsg: string } export interface GetTempFileURLParam { fileList: (string | { fileID: string maxAge?: number })[] } // === end === // === API: deleteFile === interface DeleteFileResult extends IAPISuccessParam { fileList: DeleteFileResultItem[] } interface DeleteFileResultItem { fileID: string status: number errMsg: string } interface DeleteFileParam { fileList: string[] } // === end === // === API: CloudID === abstract class CloudID { constructor(cloudID: string) } // === end === } // === Functions === declare namespace Functions { export interface IFunctionsServiceContext extends IServiceContext { appConfig: { maxReqDataSize: number maxPollRetry: number maxStartRetryGap: number clientPollTimeout: number } } } // === Storage === declare namespace Storage { export interface IStorageServiceContext extends IServiceContext { appConfig: { uploadMaxFileSize: number getTempFileURLMaxReq: number } } } // === Utils === declare namespace Utils { export interface IUtilsServiceContext extends IServiceContext { } } // === Database === declare namespace DB { /** * The class of all exposed cloud database instances */ export class Database { public readonly identifiers: IRuntimeIdentifiers public config: IDatabaseConfig public readonly command: DatabaseCommand public readonly Geo: IGeo public readonly serverDate: () => ServerDate public readonly RegExp: IRegExpConstructor public readonly debug?: boolean private constructor(options: IDatabaseConstructorOptions) collection(collectionName: string): CollectionReference } export interface IDatabaseInstanceContext { database: Database serviceContext: IDatabaseServiceContext } export class CollectionReference extends Query { public readonly collectionName: string constructor(name: string) doc(docId: string | number): DocumentReference add(options: IAddDocumentOptions): Promise<IAddResult> | void | string aggregate(): Aggregate } export class DocumentReference { constructor(collection: CollectionReference, docId: string | number) _id: string | number collection: CollectionReference field(object: object): this get(options?: IGetDocumentOptions): Promise<IQuerySingleResult> | void | string set(options?: ISetSingleDocumentOptions): Promise<ISetResult> | void | string update(options?: IUpdateSingleDocumentOptions): Promise<IUpdateResult> | void | string remove(options?: IRemoveSingleDocumentOptions): Promise<IRemoveResult> | void | string } export class Query { constructor(name: string) public readonly collectionName: string where(condition: IQueryCondition): Query orderBy(fieldPath: string, order: string): Query limit(max: number): Query skip(offset: number): Query field(object: object): Query get(options?: IGetDocumentOptions): Promise<IQueryResult> | void | string update(options?: IUpdateDocumentOptions): Promise<IUpdateResult> | void remove(options?: IRemoveDocumentOptions): Promise<IRemoveResult> | void count(options?: ICountDocumentOptions): Promise<ICountResult> | void | string } export class PipelineBase<T> { addFields(val: any): T bucket(val: any): T bucketAuto(val: any): T collStats(val: any): T count(val: any): T facet(val: any): T geoNear(val: any): T graphLookup(val: any): T group(val: any): T indexStats(val: any): T limit(val: any): T lookup(val: any): T match(val: any): T out(val: any): T project(val: any): T redact(val: any): T replaceRoot(val: any): T sample(val: any): T skip(val: any): T sort(val: any): T sortByCount(val: any): T unwind(val: any): T end(): void } export class Pipeline extends PipelineBase<Pipeline> { } export class PipelineStage { stage: string val: any } export class Aggregate extends PipelineBase<Aggregate> { constructor(collection: CollectionReference, stages: PipelineStage[]) collection: CollectionReference end(): Promise<IAggregateResult> | void } export interface DatabaseCommand { eq(val: any): DatabaseQueryCommand neq(val: any): DatabaseQueryCommand gt(val: any): DatabaseQueryCommand gte(val: any): DatabaseQueryCommand lt(val: any): DatabaseQueryCommand lte(val: any): DatabaseQueryCommand in(val: any[]): DatabaseQueryCommand nin(val: any[]): DatabaseQueryCommand geoNear(options: IGeoNearCommandOptions): DatabaseQueryCommand geoWithin(options: IGeoWithinCommandOptions): DatabaseQueryCommand geoIntersects(options: IGeoIntersectsCommandOptions): DatabaseQueryCommand and(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand or(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand nor(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand not(expression: DatabaseLogicCommand): DatabaseLogicCommand exists(val: boolean): DatabaseQueryCommand mod(divisor: number, remainder: number): DatabaseQueryCommand all(val: any[]): DatabaseQueryCommand elemMatch(val: any): DatabaseQueryCommand size(val: number): DatabaseQueryCommand set(val: any): DatabaseUpdateCommand remove(): DatabaseUpdateCommand inc(val: number): DatabaseUpdateCommand mul(val: number): DatabaseUpdateCommand min(val: number): DatabaseUpdateCommand max(val: number): DatabaseUpdateCommand rename(val: string): DatabaseUpdateCommand bit(val: number): DatabaseUpdateCommand push(...values: any[]): DatabaseUpdateCommand pop(): DatabaseUpdateCommand shift(): DatabaseUpdateCommand unshift(...values: any[]): DatabaseUpdateCommand addToSet(val: any): DatabaseUpdateCommand pull(val: any): DatabaseUpdateCommand pullAll(val: any): DatabaseUpdateCommand project: { slice(val: number | [number, number]): DatabaseProjectionCommand } aggregate: { abs(val: any): DatabaseAggregateCommand add(val: any): DatabaseAggregateCommand addToSet(val: any): DatabaseAggregateCommand allElementsTrue(val: any): DatabaseAggregateCommand and(val: any): DatabaseAggregateCommand anyElementTrue(val: any): DatabaseAggregateCommand arrayElemAt(val: any): DatabaseAggregateCommand arrayToObject(val: any): DatabaseAggregateCommand avg(val: any): DatabaseAggregateCommand ceil(val: any): DatabaseAggregateCommand cmp(val: any): DatabaseAggregateCommand concat(val: any): DatabaseAggregateCommand concatArrays(val: any): DatabaseAggregateCommand cond(val: any): DatabaseAggregateCommand convert(val: any): DatabaseAggregateCommand dateFromParts(val: any): DatabaseAggregateCommand dateToParts(val: any): DatabaseAggregateCommand dateFromString(val: any): DatabaseAggregateCommand dateToString(val: any): DatabaseAggregateCommand dayOfMonth(val: any): DatabaseAggregateCommand dayOfWeek(val: any): DatabaseAggregateCommand dayOfYear(val: any): DatabaseAggregateCommand divide(val: any): DatabaseAggregateCommand eq(val: any): DatabaseAggregateCommand exp(val: any): DatabaseAggregateCommand filter(val: any): DatabaseAggregateCommand first(val: any): DatabaseAggregateCommand floor(val: any): DatabaseAggregateCommand gt(val: any): DatabaseAggregateCommand gte(val: any): DatabaseAggregateCommand hour(val: any): DatabaseAggregateCommand ifNull(val: any): DatabaseAggregateCommand in(val: any): DatabaseAggregateCommand indexOfArray(val: any): DatabaseAggregateCommand indexOfBytes(val: any): DatabaseAggregateCommand indexOfCP(val: any): DatabaseAggregateCommand isArray(val: any): DatabaseAggregateCommand isoDayOfWeek(val: any): DatabaseAggregateCommand isoWeek(val: any): DatabaseAggregateCommand isoWeekYear(val: any): DatabaseAggregateCommand last(val: any): DatabaseAggregateCommand let(val: any): DatabaseAggregateCommand literal(val: any): DatabaseAggregateCommand ln(val: any): DatabaseAggregateCommand log(val: any): DatabaseAggregateCommand log10(val: any): DatabaseAggregateCommand lt(val: any): DatabaseAggregateCommand lte(val: any): DatabaseAggregateCommand ltrim(val: any): DatabaseAggregateCommand map(val: any): DatabaseAggregateCommand max(val: any): DatabaseAggregateCommand mergeObjects(val: any): DatabaseAggregateCommand meta(val: any): DatabaseAggregateCommand min(val: any): DatabaseAggregateCommand millisecond(val: any): DatabaseAggregateCommand minute(val: any): DatabaseAggregateCommand mod(val: any): DatabaseAggregateCommand month(val: any): DatabaseAggregateCommand multiply(val: any): DatabaseAggregateCommand neq(val: any): DatabaseAggregateCommand not(val: any): DatabaseAggregateCommand objectToArray(val: any): DatabaseAggregateCommand or(val: any): DatabaseAggregateCommand pow(val: any): DatabaseAggregateCommand push(val: any): DatabaseAggregateCommand range(val: any): DatabaseAggregateCommand reduce(val: any): DatabaseAggregateCommand reverseArray(val: any): DatabaseAggregateCommand rtrim(val: any): DatabaseAggregateCommand second(val: any): DatabaseAggregateCommand setDifference(val: any): DatabaseAggregateCommand setEquals(val: any): DatabaseAggregateCommand setIntersection(val: any): DatabaseAggregateCommand setIsSubset(val: any): DatabaseAggregateCommand setUnion(val: any): DatabaseAggregateCommand size(val: any): DatabaseAggregateCommand slice(val: any): DatabaseAggregateCommand split(val: any): DatabaseAggregateCommand sqrt(val: any): DatabaseAggregateCommand stdDevPop(val: any): DatabaseAggregateCommand stdDevSamp(val: any): DatabaseAggregateCommand strcasecmp(val: any): DatabaseAggregateCommand strLenBytes(val: any): DatabaseAggregateCommand strLenCP(val: any): DatabaseAggregateCommand substr(val: any): DatabaseAggregateCommand substrBytes(val: any): DatabaseAggregateCommand substrCP(val: any): DatabaseAggregateCommand subtract(val: any): DatabaseAggregateCommand sum(val: any): DatabaseAggregateCommand switch(val: any): DatabaseAggregateCommand toBool(val: any): DatabaseAggregateCommand toDate(val: any): DatabaseAggregateCommand toDecimal(val: any): DatabaseAggregateCommand toDouble(val: any): DatabaseAggregateCommand toInt(val: any): DatabaseAggregateCommand toLong(val: any): DatabaseAggregateCommand toObjectId(val: any): DatabaseAggregateCommand toString(val: any): DatabaseAggregateCommand toLower(val: any): DatabaseAggregateCommand toUpper(val: any): DatabaseAggregateCommand trim(val: any): DatabaseAggregateCommand trunc(val: any): DatabaseAggregateCommand type(val: any): DatabaseAggregateCommand week(val: any): DatabaseAggregateCommand year(val: any): DatabaseAggregateCommand zip(val: any): DatabaseAggregateCommand } } export enum AGGREGATE_COMMANDS_LITERAL { AVG = 'avg', MULTIPLY = 'multiply', SUM = 'sum', } export class DatabaseAggregateCommand { } export enum LOGIC_COMMANDS_LITERAL { AND = 'and', OR = 'or', NOT = 'not', NOR = 'nor', } export class DatabaseLogicCommand { and(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand or(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand nor(...expressions: (DatabaseLogicCommand | IQueryCondition)[]): DatabaseLogicCommand not(expression: DatabaseLogicCommand): DatabaseLogicCommand } export enum QUERY_COMMANDS_LITERAL { // comparison EQ = 'eq', NEQ = 'neq', GT = 'gt', GTE = 'gte', LT = 'lt', LTE = 'lte', IN = 'in', NIN = 'nin', // geo GEO_NEAR = 'geoNear', GEO_WITHIN = 'geoWithin', GEO_INTERSECTS = 'geoIntersects', // element EXISTS = 'exists', // evaluation MOD = 'mod', // array ALL = 'all', ELEM_MATCH = 'elemMatch', SIZE = 'size', } export class DatabaseQueryCommand extends DatabaseLogicCommand { eq(val: any): DatabaseLogicCommand neq(val: any): DatabaseLogicCommand gt(val: any): DatabaseLogicCommand gte(val: any): DatabaseLogicCommand lt(val: any): DatabaseLogicCommand lte(val: any): DatabaseLogicCommand in(val: any[]): DatabaseLogicCommand nin(val: any[]): DatabaseLogicCommand exists(val: boolean): DatabaseLogicCommand mod(divisor: number, remainder: number): DatabaseLogicCommand all(val: any[]): DatabaseLogicCommand elemMatch(val: any): DatabaseLogicCommand size(val: number): DatabaseLogicCommand geoNear(options: IGeoNearCommandOptions): DatabaseLogicCommand geoWithin(options: IGeoWithinCommandOptions): DatabaseLogicCommand geoIntersects(options: IGeoIntersectsCommandOptions): DatabaseLogicCommand } export enum PROJECTION_COMMANDS_LITERAL { SLICE = 'slice', } export class DatabaseProjectionCommand { } export enum UPDATE_COMMANDS_LITERAL { // field SET = 'set', REMOVE = 'remove', INC = 'inc', MUL = 'mul', MIN = 'min', MAX = 'max', RENAME = 'rename', // bitwise BIT = 'bit', // array PUSH = 'push', POP = 'pop', SHIFT = 'shift', UNSHIFT = 'unshift', ADD_TO_SET = 'addToSet', PULL = 'pull', PULL_ALL = 'pullAll', } export class DatabaseUpdateCommand { } export enum UPDATE_COMMAND_MODIFIERS_LITERAL { EACH = 'each', POSITION = 'position', SLICE = 'slice', SORT = 'sort', } export class DatabaseUpdateCommandModifier { } export class Batch { } export interface IDatabaseConfig { env?: string } export interface IDatabaseConstructorOptions { config?: IDatabaseConfig context: IDatabaseServiceContext } export interface IAppConfig { docSizeLimit: number realtimePingInterval: number realtimePongWaitTimeout: number realtimeMaxReconnect: number realtimeReconnectInterval: number realtimeTotalConnectionTimeout: number realtimeQueryEventCacheTimeout: number } export interface IDatabaseServiceContext extends IServiceContext { appConfig: IAppConfig ws?: any } export interface IGeoPointConstructor { new (longitude: number, latitide: number): GeoPoint new (geojson: IGeoJSONPoint): GeoPoint (longitude: number, latitide: number): GeoPoint (geojson: IGeoJSONPoint): GeoPoint } export interface IGeoMultiPointConstructor { new (points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint (points: GeoPoint[] | IGeoJSONMultiPoint): GeoMultiPoint } export interface IGeoLineStringConstructor { new (points: GeoPoint[] | IGeoJSONLineString): GeoLineString (points: GeoPoint[] | IGeoJSONLineString): GeoLineString } export interface IGeoMultiLineStringConstructor { new (lineStrings: GeoLineString[] | IGeoJSONMultiLineString): GeoMultiLineString (lineStrings: GeoLineString[] | IGeoJSONMultiLineString): GeoMultiLineString } export interface IGeoPolygonConstructor { new (lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon (lineStrings: GeoLineString[] | IGeoJSONPolygon): GeoPolygon } export interface IGeoMultiPolygonConstructor { new (polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon (polygons: GeoPolygon[] | IGeoJSONMultiPolygon): GeoMultiPolygon } export interface IGeo { Point: IGeoPointConstructor MultiPoint: IGeoMultiPointConstructor LineString: IGeoLineStringConstructor MultiLineString: IGeoMultiLineStringConstructor Polygon: IGeoPolygonConstructor MultiPolygon: IGeoMultiPolygonConstructor } export interface IGeoJSONPoint { type: 'Point' coordinates: [number, number] } export interface IGeoJSONMultiPoint { type: 'MultiPoint' coordinates: [number, number][] } export interface IGeoJSONLineString { type: 'LineString' coordinates: [number, number][] } export interface IGeoJSONMultiLineString { type: 'MultiLineString' coordinates: [number, number][][] } export interface IGeoJSONPolygon { type: 'Polygon' coordinates: [number, number][][] } export interface IGeoJSONMultiPolygon { type: 'MultiPolygon' coordinates: [number, number][][][] } export type IGeoJSONObject = IGeoJSONPoint | IGeoJSONMultiPoint | IGeoJSONLineString | IGeoJSONMultiLineString | IGeoJSONPolygon | IGeoJSONMultiPolygon export abstract class GeoPoint { public longitude: number public latitude: number constructor(longitude: number, latitude: number) toJSON(): IGeoJSONPoint toString(): string } export abstract class GeoMultiPoint { public points: GeoPoint[] constructor(points: GeoPoint[]) toJSON(): IGeoJSONMultiPoint toString(): string } export abstract class GeoLineString { public points: GeoPoint[] constructor(points: GeoPoint[]) toJSON(): IGeoJSONLineString toString(): string } export abstract class GeoMultiLineString { public lines: GeoLineString[] constructor(lines: GeoLineString[]) toJSON(): IGeoJSONMultiLineString toString(): string } export abstract class GeoPolygon { public lines: GeoLineString[] constructor(lines: GeoLineString[]) toJSON(): IGeoJSONPolygon toString(): string } export abstract class GeoMultiPolygon { public polygons: GeoPolygon[] constructor(polygons: GeoPolygon[]) toJSON(): IGeoJSONMultiPolygon toString(): string } export type GeoInstance = GeoPoint | GeoMultiPoint | GeoLineString | GeoMultiLineString | GeoPolygon | GeoMultiPolygon export interface IGeoNearCommandOptions { geometry: GeoPoint maxDistance?: number minDistance?: number } export interface IGeoWithinCommandOptions { geometry: GeoPolygon | GeoMultiPolygon } export interface IGeoIntersectsCommandOptions { geometry: GeoPoint | GeoMultiPoint | GeoLineString | GeoMultiLineString | GeoPolygon | GeoMultiPolygon } export interface IServerDateOptions { offset: number } export abstract class ServerDate { public readonly options: IServerDateOptions constructor(options?: IServerDateOptions) } export interface IRegExpOptions { regexp: string options?: string } export interface IRegExpConstructor { new (options: IRegExpOptions): RegExp (options: IRegExpOptions): RegExp } export abstract class RegExp { public readonly regexp: string public readonly options: string constructor(options: IRegExpOptions) } export type DocumentId = string | number export interface IDocumentData { _id?: DocumentId [key: string]: any } export interface IDBAPIParam { } export interface IAddDocumentOptions extends IDBAPIParam { data: IDocumentData } export interface IGetDocumentOptions extends IDBAPIParam { stringifyTest?: boolean } export interface ICountDocumentOptions extends IDBAPIParam { stringifyTest?: boolean } export interface IUpdateDocumentOptions extends IDBAPIParam { data: IUpdateCondition stringifyTest?: boolean } export interface IUpdateSingleDocumentOptions extends IDBAPIParam { data: IUpdateCondition stringifyTest?: boolean } export interface ISetDocumentOptions extends IDBAPIParam { data: IUpdateCondition stringifyTest?: boolean } export interface ISetSingleDocumentOptions extends IDBAPIParam { data: IUpdateCondition stringifyTest?: boolean } export interface IRemoveDocumentOptions extends IDBAPIParam { query: IQueryCondition stringifyTest?: boolean } export interface IRemoveSingleDocumentOptions extends IDBAPIParam { stringifyTest?: boolean } export type IQueryCondition = Record<string, any> | DatabaseLogicCommand export interface ConditionRecord { [key: string]: IQueryCondition } // export interface IQueryCondition { // [key: string]: any // } export type IStringQueryCondition = string export interface IQueryResult extends IAPISuccessParam { data: IDocumentData[] } export interface IQuerySingleResult extends IAPISuccessParam { data: IDocumentData } export interface IUpdateCondition { [key: string]: any } export type IStringUpdateCondition = string export interface ISetCondition { } export interface IAddResult extends IAPISuccessParam { _id: DocumentId } export interface IUpdateResult extends IAPISuccessParam { stats: { updated: number // created: number } } export interface ISetResult extends IAPISuccessParam { _id: DocumentId stats: { updated: number created: number } } export interface IRemoveResult extends IAPISuccessParam { stats: { removed: number } } export interface ICountResult extends IAPISuccessParam { total: number } export interface IAggregateResult extends IAPISuccessParam { list: any[] } } type Optional<T> = { [K in keyof T]+?: T[K] } type OQ< T extends Optional< Record<'complete' | 'success' | 'fail', (...args: any[]) => any> > > = | (RQ<T> & Required<Pick<T, 'success'>>) | (RQ<T> & Required<Pick<T, 'fail'>>) | (RQ<T> & Required<Pick<T, 'complete'>>) | (RQ<T> & Required<Pick<T, 'success' | 'fail'>>) | (RQ<T> & Required<Pick<T, 'success' | 'complete'>>) | (RQ<T> & Required<Pick<T, 'fail' | 'complete'>>) | (RQ<T> & Required<Pick<T, 'fail' | 'complete' | 'success'>>) type RQ< T extends Optional< Record<'complete' | 'success' | 'fail', (...args: any[]) => any> > > = Pick<T, Exclude<keyof T, 'complete' | 'success' | 'fail'>>
the_stack
import { Platform } from '@phosphor/domutils'; import { getKeyboardLayout } from '@phosphor/keyboard'; import { DataGrid } from './datagrid'; import { SelectionModel } from './selectionmodel'; /** * A basic implementation of a data grid key handler. * * #### Notes * This class may be subclassed and customized as needed. */ export class BasicKeyHandler implements DataGrid.IKeyHandler { /** * Whether the key handler is disposed. */ get isDisposed(): boolean { return this._disposed; } /** * Dispose of the resources held by the key handler. */ dispose(): void { this._disposed = true; } /** * Handle the key down event for the data grid. * * @param grid - The data grid of interest. * * @param event - The keydown event of interest. * * #### Notes * This will not be called if the mouse button is pressed. */ onKeyDown(grid: DataGrid, event: KeyboardEvent): void { switch (getKeyboardLayout().keyForKeydownEvent(event)) { case 'ArrowLeft': this.onArrowLeft(grid, event); break; case 'ArrowRight': this.onArrowRight(grid, event); break; case 'ArrowUp': this.onArrowUp(grid, event); break; case 'ArrowDown': this.onArrowDown(grid, event); break; case 'PageUp': this.onPageUp(grid, event); break; case 'PageDown': this.onPageDown(grid, event); break; case 'Escape': this.onEscape(grid, event); break; case 'C': this.onKeyC(grid, event); break; } } /** * Handle the `'ArrowLeft'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onArrowLeft(grid: DataGrid, event: KeyboardEvent): void { // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Fetch the modifier flags. let shift = event.shiftKey; let accel = Platform.accelKey(event); // Handle no model with the accel modifier. if (!model && accel) { grid.scrollTo(0, grid.scrollY); return; } // Handle no model and no modifier. (ignore shift) if (!model) { grid.scrollByStep('left'); return; } // Fetch the selection mode. let mode = model.selectionMode; // Handle the row selection mode with accel key. if (mode === 'row' && accel) { grid.scrollTo(0, grid.scrollY); return; } // Handle the row selection mode with no modifier. (ignore shift) if (mode === 'row') { grid.scrollByStep('left'); return; } // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Dispatch based on the modifier keys. if (accel && shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 : 0; c1 = cs ? cs.c1 : 0; c2 = 0; cr = r; cc = c; clear = 'current'; } else if (shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 - 1 : 0; cr = r; cc = c; clear = 'current'; } else if (accel) { r1 = r; r2 = r; c1 = 0; c2 = 0; cr = r1; cc = c1; clear = 'all'; } else { r1 = r; r2 = r; c1 = c - 1; c2 = c - 1; cr = r1; cc = c1; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. if (shift || mode === 'column') { grid.scrollToColumn(cs.c2); } else { grid.scrollToCursor(); } } /** * Handle the `'ArrowRight'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onArrowRight(grid: DataGrid, event: KeyboardEvent): void { // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Fetch the modifier flags. let shift = event.shiftKey; let accel = Platform.accelKey(event); // Handle no model with the accel modifier. if (!model && accel) { grid.scrollTo(grid.maxScrollX, grid.scrollY); return; } // Handle no model and no modifier. (ignore shift) if (!model) { grid.scrollByStep('right'); return; } // Fetch the selection mode. let mode = model.selectionMode; // Handle the row selection model with accel key. if (mode === 'row' && accel) { grid.scrollTo(grid.maxScrollX, grid.scrollY); return; } // Handle the row selection mode with no modifier. (ignore shift) if (mode === 'row') { grid.scrollByStep('right'); return; } // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Dispatch based on the modifier keys. if (accel && shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 : 0; c1 = cs ? cs.c1 : 0; c2 = Infinity; cr = r; cc = c; clear = 'current'; } else if (shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 + 1 : 0; cr = r; cc = c; clear = 'current'; } else if (accel) { r1 = r; r2 = r; c1 = Infinity; c2 = Infinity; cr = r1; cc = c1; clear = 'all'; } else { r1 = r; r2 = r; c1 = c + 1; c2 = c + 1; cr = r1; cc = c1; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. if (shift || mode === 'column') { grid.scrollToColumn(cs.c2); } else { grid.scrollToCursor(); } } /** * Handle the `'ArrowUp'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onArrowUp(grid: DataGrid, event: KeyboardEvent): void { // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Fetch the modifier flags. let shift = event.shiftKey; let accel = Platform.accelKey(event); // Handle no model with the accel modifier. if (!model && accel) { grid.scrollTo(grid.scrollX, 0); return; } // Handle no model and no modifier. (ignore shift) if (!model) { grid.scrollByStep('up'); return; } // Fetch the selection mode. let mode = model.selectionMode; // Handle the column selection mode with accel key. if (mode === 'column' && accel) { grid.scrollTo(grid.scrollX, 0); return; } // Handle the column selection mode with no modifier. (ignore shift) if (mode === 'column') { grid.scrollByStep('up'); return; } // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Dispatch based on the modifier keys. if (accel && shift) { r1 = cs ? cs.r1 : 0; r2 = 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else if (shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 - 1 : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else if (accel) { r1 = 0; r2 = 0; c1 = c; c2 = c; cr = r1; cc = c1; clear = 'all'; } else { r1 = r - 1; r2 = r - 1; c1 = c; c2 = c; cr = r1; cc = c1; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. if (shift || mode === 'row') { grid.scrollToRow(cs.r2); } else { grid.scrollToCursor(); } } /** * Handle the `'ArrowDown'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onArrowDown(grid: DataGrid, event: KeyboardEvent): void { // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Fetch the modifier flags. let shift = event.shiftKey; let accel = Platform.accelKey(event); // Handle no model with the accel modifier. if (!model && accel) { grid.scrollTo(grid.scrollX, grid.maxScrollY); return; } // Handle no model and no modifier. (ignore shift) if (!model) { grid.scrollByStep('down'); return; } // Fetch the selection mode. let mode = model.selectionMode; // Handle the column selection mode with accel key. if (mode === 'column' && accel) { grid.scrollTo(grid.scrollX, grid.maxScrollY); return; } // Handle the column selection mode with no modifier. (ignore shift) if (mode === 'column') { grid.scrollByStep('down'); return; } // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Dispatch based on the modifier keys. if (accel && shift) { r1 = cs ? cs.r1 : 0; r2 = Infinity; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else if (shift) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 + 1 : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else if (accel) { r1 = Infinity; r2 = Infinity; c1 = c; c2 = c; cr = r1; cc = c1; clear = 'all'; } else { r1 = r + 1; r2 = r + 1; c1 = c; c2 = c; cr = r1; cc = c1; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. if (shift || mode === 'row') { grid.scrollToRow(cs.r2); } else { grid.scrollToCursor(); } } /** * Handle the `'PageUp'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onPageUp(grid: DataGrid, event: KeyboardEvent): void { // Ignore the event if the accel key is pressed. if (Platform.accelKey(event)) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Scroll by page if there is no selection model. if (!model || model.selectionMode === 'column') { grid.scrollByPage('up'); return; } // Get the normal number of cells in the page height. let n = Math.floor(grid.pageHeight / grid.defaultSizes.rowHeight); // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Select or resize as needed. if (event.shiftKey) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 - n : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else { r1 = cs ? cs.r1 - n : 0; r2 = r1; c1 = c; c2 = c; cr = r1; cc = c; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. grid.scrollToRow(cs.r2); } /** * Handle the `'PageDown'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onPageDown(grid: DataGrid, event: KeyboardEvent): void { // Ignore the event if the accel key is pressed. if (Platform.accelKey(event)) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Fetch the selection model. let model = grid.selectionModel; // Scroll by page if there is no selection model. if (!model || model.selectionMode === 'column') { grid.scrollByPage('down'); return; } // Get the normal number of cells in the page height. let n = Math.floor(grid.pageHeight / grid.defaultSizes.rowHeight); // Fetch the cursor and selection. let r = model.cursorRow; let c = model.cursorColumn; let cs = model.currentSelection(); // Set up the selection variables. let r1: number; let r2: number; let c1: number; let c2: number; let cr: number; let cc: number; let clear: SelectionModel.ClearMode; // Select or resize as needed. if (event.shiftKey) { r1 = cs ? cs.r1 : 0; r2 = cs ? cs.r2 + n : 0; c1 = cs ? cs.c1 : 0; c2 = cs ? cs.c2 : 0; cr = r; cc = c; clear = 'current'; } else { r1 = cs ? cs.r1 + n : 0; r2 = r1; c1 = c; c2 = c; cr = r1; cc = c; clear = 'all'; } // Create the new selection. model.select({ r1, c1, r2, c2, cursorRow: cr, cursorColumn: cc, clear }); // Re-fetch the current selection. cs = model.currentSelection(); // Bail if there is no selection. if (!cs) { return; } // Scroll the grid appropriately. grid.scrollToRow(cs.r2); } /** * Handle the `'Escape'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onEscape(grid: DataGrid, event: KeyboardEvent): void { if (grid.selectionModel) { grid.selectionModel.clear(); } } /** * Handle the `'C'` key press for the data grid. * * @param grid - The data grid of interest. * * @param event - The keyboard event of interest. */ protected onKeyC(grid: DataGrid, event: KeyboardEvent): void { // Bail early if the modifiers aren't correct for copy. if (event.shiftKey || !Platform.accelKey(event)) { return; } // Stop the event propagation. event.preventDefault(); event.stopPropagation(); // Copy the current selection to the clipboard. grid.copyToClipboard(); } private _disposed = false; }
the_stack
const Ajv = require('ajv'); import { ValidationContext } from '../types'; import { validate, getType } from '../validator'; import { pick, patch } from '../picker'; import { compile } from '../compiler'; import { generateJsonSchemaObject } from '../codegen'; import { serialize, deserialize } from '../serializer'; import * as op from '../operators'; describe("foo", function() { it("foo-1", function() { try { /* const ast1 = parse(` export type A = string; type AA = (string); type AAA = string|number; type AAAA = string | number; type AAAAA = (string|number); type AAAAAA = {a: string, b: number}; type AAAAAAA = (string|(number|'aaa')|{a: string, b: number}|[string, number]); type AAAAAAA2 = (string|(number|'aaa')|{a: string, b: number}|[string, @range(10, 20) number]); interface B { a: string; b?: number; 'b2'?: number; @range(2, 5) @max(10) @min(3) b3: number; b4: @range(2, 5) @max(10) @min(3) number; @msg({a: "1234", b: "3456"}) b5: number; c: [string]; d: [string, number]; e: [1, 2, 'aaa']; e2: [1, ...<string, 3..5>, 'aaa']; e3: [...<string|number>]; f: Array<number>; g: Array<Array<number>>; g2: Array<{a: string, b: number}>; h: Array<number[]>; i: number[]; i2: number[3]; i3: number[3..]; i4: number[..3]; i5: number[1..3]; i6: (number)[]; i7: (number|string)[]; j: number[][]; j2: (number|string)[][]; k: number | string; k2: number[] | string []; k3: number[][] | string [][]; k4: number[][] | string [][] | string[][][]; k4b: @range(2, 5) @max(10) @min(3) number[][] | @range(2, 5) @max(10) @min(3) string [][] | @range(2, 5) @max(10) @min(3) string[][][]; k5: {} | string [][] | string[][][]; k6: {a: number} | string [][] | string[][][]; k7: {a: number, b:string} | string [][] | string[][][]; k8: {a: number, b:string} | {c?: boolean} | string[][][]; k9: (number[]) | (string []); k10: (number[][]) | (string [][]); k11: (number[3..4][5..6]) | (string [3..4][5..6]); k12: (number[3..4][5..6]) | (string [3..4][5..6]) | (string[][3..4][5..6]); k13: ({}) | (string [3..4][5..6]) | (string[][3..4][5..6]); k14: ({a: number}) | (string [3..4][5..6]) | (string[][3..4][5..6]); k15: ({a: number, b:string}) | (string [3..4][5..6]) | (string[][3..4][5..6]); k16: ({a: number, b:string}) | ({c?: boolean}) | (string[][3..4][5..6]); } export interface C extends A {} export interface D extends A, B { x: string; } `); */ /* const ast2 = parse(` type A = @min(3) @range(5, 9) @msgId({a: '12345', b: [1, {c: 3}]}) string; `); */ const schema2 = compile(` import * as fs from 'fs'; external U, W; /** doc comment X - line 1 * doc comment X - line 2 */ export type X = string | number | 'foo'; type XX = number; /** doc comment S */ enum S { /** doc comment S.q */ q, w = 3, e, r, t = 10, u = 'aaa', } export enum R {} interface B1111 {} /** doc comment B - line 1 */ interface B { @range(2, 5) a: number; /** doc comment B.b - line 1 * doc comment B.b - line 2 */ b?: string; } export interface C { c?: string[10..20][]; d: string|number|boolean[1][2..3]|B|B[]|B|{/** doc comment C.d.p */p: string}; d2?: X; d3?: U; d4?: S; [propName: /^[B][0-9]$/]: U; } interface A extends B,C, D,DD { e: (string[])|(@minValue(3) number[])|(boolean[]); f: X | boolean; @match(/^[A-F]+$/) g: string; @msg('custom msg of A.h') h?: C; i: [string, number?, string?]; j: [...<number, 1..2>, string]; j2: [string, ...<number, 2..3>]; j3: string[..2]; k: Y; l: B; [propName: /^[a-z][0-9]$/ | number]?: string; /** doc comment A.propName (C) */ [propName: /^[A][0-9]$/]: C; } interface AA extends A {} type Y = boolean; interface D { d90: string; } interface DD { d91: string; } interface H { // interface H extends HH { // <- recursive extend a?: HH; b: H | number; } interface HH extends H {c?:number;} /* interface HH extends H {c?:number;} interface H { a?: HH; // a?: H; b: H | number; } */ `); // console.log(JSON.stringify(getType(schema2, 'X'), null, 2)); // console.log(JSON.stringify(getType(schema2, 'C'), null, 2)); // console.log(JSON.stringify(getType(schema2, 'A'), null, 2)); // console.log(JSON.stringify(getType(schema2, 'H'), null, 2)); /* const ctx: Partial<ValidationContext> = { checkAll: true, // noAdditionalProps: true, schema: schema2, }; expect(validate({ a: 5, c: [['', '', '', '', '', '', '', '', '', '']], d: 10, // d2: true, d3: 11, // d4: 11, d90: '', d91: '', e: [true, false], // e: [0, 1, 2], f: true, g: 'DEBCB', // h: 1, i: ['q', 12, 'a'], j: [1, 2, 'aaa'], // j: ['', 1, 2, 'aaa'], // j: [1, 2, 3, 'aaa'], // j: '', j2: ['aaa', 1, 2, 3], // j2: ['aaa', '', 1, 2, 3], j3: ['', ''], // j3: ['', 0], // j3: '', k: false, l: {a: 5}, z1: 'a', // A0: 1, // B0: 2, }, getType(schema2, 'A'), ctx)).toEqual({} as any); console.log(generateTypeScriptCode(schema2)); console.log(generateProto3Code(schema2)); // console.log(JSON.stringify(ctx)); console.log(ctx.errors); delete ctx.errors; expect(validate({ a: {a: {b: 2}, b: 1}, b: {b: {b: 3}}, }, getType(schema2, 'HH'), ctx)).toEqual({} as any); // console.log(JSON.stringify(ctx)); console.log(ctx.errors); */ } catch (e) { throw e; } expect(1).toEqual(1); }); it("foo-2", function() { /* console.log(JSON.stringify(getType(z, 'A'), null, 2)); */ const z = compile(` type Foo = string; interface A { a: Foo; @range(3, 5) b: number; @maxLength(3) c: Foo; } `); const ctx: Partial<ValidationContext> = {checkAll: true}; const r = validate({b: 6, c: '1234'}, getType(z, 'A'), ctx); // console.log(JSON.stringify(r)); // console.log(ctx.errors); expect(1).toEqual(1); }); it("foo-2b", function() { /* console.log(JSON.stringify(getType(z, 'A'), null, 2)); */ const z = compile(` type Foo = string; interface A { a: Foo; @range(3, 5) b: number; @maxLength(3) c: Foo; } `); const ctx: Partial<ValidationContext> = {checkAll: true}; const subtype = op.picked(getType(z, 'A'), 'a', 'c'); const original = {a: '', b: 3, c: '123', d: 0}; const needle = pick(original, subtype, ctx); needle.a = '1'; needle.b = 6; (needle as any).e = 5; try { const r = patch(original, needle, subtype, ctx); // console.log(r); expect(1).toEqual(1); } catch (e) { // console.log(e.message); // console.log(e.ctx?.errors); expect(1).toEqual(0); } }); it("foo-4", function() { const z = compile(` type Foo = string; interface A { a: Foo; @range(3, 5) b: number; @maxLength(3) c: Foo; } `); const zz = deserialize(serialize(z)); // console.log(zz.keys()); expect(1).toEqual(1); }); it("readme-examples-1", function() { { const mySchema = compile(` type Foo = string; interface A { @maxLength(4) a: Foo; z?: boolean; } `); type Foo = string; interface A { a: Foo; z?: boolean; } { const validated1 = validate({ a: 'x', b: 3, }, getType(mySchema, 'A')); // {value: {a: 'x', b: 3}} expect(validated1).toEqual({value: {a: 'x', b: 3}}); const validated2 = validate({ aa: 'x', b: 3, }, getType(mySchema, 'A')); // null if (validated2 === null) { expect(1).toEqual(1); } else { expect(1).toEqual(0); } const ctx3: Partial<ValidationContext> = { // To receive the error messages, define the context as a variable. checkAll: true, // (optional) Set to true to continue validation after the first error. noAdditionalProps: true, // (optional) Do not allow implicit additional properties. schema: mySchema, // (optional) Pass "schema" to check for recursive types. }; const validated3 = validate({ aa: 'x', b: 3, }, getType(mySchema, 'A'), ctx3); if (validated3 === null) { expect(1).toEqual(1); // console.log(JSON.stringify( // ctx3.errors, // error messages // null, 2)); } else { expect(1).toEqual(0); } } { const original = { a: 'x', b: 3, }; const needleType = op.picked(getType(mySchema, 'A'), 'a'); try { const needle1 = pick(original, needleType); // {a: 'x'} const unknownInput1: unknown = { // Edit the needle data ...needle1, a: 'y', q: 1234, }; const changed1 = patch(original, unknownInput1, needleType); // {a: 'y', b: 3} expect(changed1).toEqual({a: 'y', b: 3}); } catch (e) { expect(1).toEqual(0); // console.log(e.message); // console.log(e.ctx?.errors); } try { const needle2 = pick(original, needleType); // {a: 'x'} const unknownInput2: unknown = { // Edit the needle data ...needle2, a: 'yyyyy', q: 1234, }; const changed1 = patch(original, unknownInput2, needleType); // Throws an error expect(1).toEqual(0); } catch (e) { expect(1).toEqual(1); // console.log(e.message); // console.log(e.ctx?.errors); } try { const ctx3: Partial<ValidationContext> = { // To receive the error messages, define the context as a variable. checkAll: true, // (optional) Set to true to continue validation after the first error. schema: mySchema, // (optional) Pass "schema" to check for recursive types. }; const needle3 = pick({ aa: 'x', b: 3, }, needleType, ctx3); // Throws an error expect(1).toEqual(0); } catch (e) { expect(1).toEqual(1); // console.log(e.message); // console.log(e.ctx?.errors); } } { const unknownInput: unknown = {a: 'x'}; const validated = validate<A>(unknownInput, getType(mySchema, 'A')); if (validated) { const validatedInput = validated.value; expect(validatedInput).toEqual({a: 'x'}); } else { expect(1).toEqual(0); } } { interface Store { baz: A; } const store: Store = { baz: { a: 'x', z: false, } }; const needleType = op.picked(getType(mySchema, 'A'), 'a'); try { const needle = pick(store.baz, needleType); // {a: 'x'} const unknownInput: unknown = { // Edit the needle data ...needle, a: 'y', q: 1234, }; store.baz = patch(store.baz, unknownInput, needleType); // {a: 'y', z: false} expect(store.baz).toEqual({a: 'y', z: false}); } catch (e) { expect(1).toEqual(0); // console.log(e.message); // console.log(e.ctx?.errors); } } } }); });
the_stack
import { BSONDeserializer, BSONSerializer, deserializeBSONWithoutOptimiser, getBSONDeserializer, getBSONSerializer } from '@deepkit/bson'; import { arrayRemoveItem, asyncOperation, ClassType } from '@deepkit/core'; import { AsyncSubscription } from '@deepkit/core-rxjs'; import { createRpcMessage, RpcBaseClient, RpcDirectClientAdapter, RpcMessage, RpcMessageRouteType } from '@deepkit/rpc'; import { BrokerKernel } from './kernel'; import { brokerDelete, brokerEntityFields, brokerGet, brokerIncrement, brokerLock, brokerLockId, brokerPublish, brokerResponseIncrement, brokerResponseIsLock, brokerResponseSubscribeMessage, brokerSet, brokerSubscribe, BrokerType } from './model'; import { ReceiveType, ReflectionClass, ReflectionKind, resolveReceiveType, Type, TypePropertySignature } from '@deepkit/type'; export class BrokerChannel<T> { protected listener: number = 0; protected callbacks: ((next: Uint8Array) => void)[] = []; protected wrapped: boolean = false; protected decoder: (bson: Uint8Array) => any; constructor( public channel: string, protected type: Type, protected client: BrokerClient, ) { const standaloneType = type.kind === ReflectionKind.objectLiteral || (type.kind === ReflectionKind.class && type.types.length); if (!standaloneType) { this.type = { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'v', type: type, } as TypePropertySignature] }; this.wrapped = true; } this.decoder = getBSONDeserializer(undefined, this.type); } public async publish(data: T) { const serializer = getBSONSerializer(undefined, this.type); const v = this.wrapped ? serializer({ v: data }) : serializer(data); await this.client.sendMessage<brokerPublish>(BrokerType.Publish, { c: this.channel, v: v }) .ackThenClose(); return undefined; } next(data: Uint8Array) { for (const callback of this.callbacks) { callback(data); } } async subscribe(callback: (next: T) => void): Promise<AsyncSubscription> { const parsedCallback = (next: Uint8Array) => { try { const parsed = this.decoder(next); callback(this.wrapped ? parsed.v : parsed); } catch (error: any) { console.log('message', Buffer.from(next).toString('utf8'), deserializeBSONWithoutOptimiser(next)); console.error(`Could not parse channel message ${this.channel}: ${error}`); } }; this.listener++; this.callbacks.push(parsedCallback); if (this.listener === 1) { await this.client.sendMessage<brokerSubscribe>(BrokerType.Subscribe, { c: this.channel }) .ackThenClose(); } return new AsyncSubscription(async () => { this.listener--; arrayRemoveItem(this.callbacks, parsedCallback); if (this.listener === 0) { await this.client.sendMessage<brokerSubscribe>(BrokerType.Unsubscribe, { c: this.channel }) .ackThenClose(); } }); } } export class BrokerKeyValue<T> { protected serializer: BSONSerializer; protected decoder: BSONDeserializer<T>; constructor( protected key: string, protected type: Type, protected client: BrokerClient, ) { this.serializer = getBSONSerializer(undefined, type); this.decoder = getBSONDeserializer(undefined, type); } public async set(data: T): Promise<undefined> { await this.client.sendMessage<brokerSet>(BrokerType.Set, { n: this.key, v: this.serializer(data) }).ackThenClose(); return undefined; } public async get(): Promise<T> { const v = await this.getOrUndefined(); if (v !== undefined) return v; throw new Error(`No value for key ${this.key} found`); } public async delete(): Promise<boolean> { await this.client.sendMessage<brokerDelete>(BrokerType.Delete, { n: this.key }).ackThenClose(); return true; } public async getOrUndefined(): Promise<T | undefined> { const first: RpcMessage = await this.client.sendMessage<brokerGet>(BrokerType.Get, { n: this.key }).firstThenClose(BrokerType.ResponseGet); if (first.buffer && first.buffer.byteLength > first.bodyOffset) { return this.decoder(first.buffer, first.bodyOffset); } return undefined; } } export class BrokerClient extends RpcBaseClient { protected activeChannels = new Map<string, BrokerChannel<any>>(); protected knownEntityFields = new Map<string, string[]>(); protected publishedEntityFields = new Map<string, Map<string, number>>(); /** * On first getEntityFields() call we check if entityFieldsReceived is true. If not * we connect and load all available entity-fields from the server and start * streaming all changes to the entity-fields directly to our entityFields map. */ protected entityFieldsReceived = false; protected entityFieldsPromise?: Promise<void>; public async getEntityFields(classSchema: ClassType | string): Promise<string[]> { const entityName = 'string' === typeof classSchema ? classSchema : ReflectionClass.from(classSchema).getName(); if (!this.entityFieldsReceived) { this.entityFieldsReceived = true; this.entityFieldsPromise = asyncOperation(async (resolve) => { const subject = this.sendMessage(BrokerType.AllEntityFields); const answer = await subject.waitNextMessage(); subject.release(); if (answer.type === BrokerType.AllEntityFields) { for (const body of answer.getBodies()) { const fields = body.parseBody<brokerEntityFields>(); this.knownEntityFields.set(fields.name, fields.fields); } } this.entityFieldsPromise = undefined; resolve(); }); } if (this.entityFieldsPromise) { await this.entityFieldsPromise; } return this.knownEntityFields.get(entityName) || []; } protected onMessage(message: RpcMessage) { if (message.routeType === RpcMessageRouteType.server) { if (message.type === BrokerType.EntityFields) { const fields = message.parseBody<brokerEntityFields>(); this.knownEntityFields.set(fields.name, fields.fields); this.transporter.send(createRpcMessage(message.id, BrokerType.Ack, undefined, RpcMessageRouteType.server)); } else if (message.type === BrokerType.ResponseSubscribeMessage) { const body = message.parseBody<brokerResponseSubscribeMessage>(); const channel = this.activeChannels.get(body.c); if (!channel) return; channel.next(body.v); } } else { super.onMessage(message); } } public async publishEntityFields<T>(classSchema: ClassType | string, fields: string[]): Promise<AsyncSubscription> { const entityName = 'string' === typeof classSchema ? classSchema : ReflectionClass.from(classSchema).getName(); let store = this.publishedEntityFields.get(entityName); if (!store) { store = new Map; this.publishedEntityFields.set(entityName, store); } let changed = false; const newFields: string[] = []; for (const field of fields) { const v = store.get(field); if (v === undefined) { changed = true; newFields.push(field); } ; store.set(field, v === undefined ? 1 : v + 1); } if (changed) { const response = await this.sendMessage<brokerEntityFields>( BrokerType.PublishEntityFields, { name: entityName, fields: newFields } ).firstThenClose<brokerEntityFields>(BrokerType.EntityFields); this.knownEntityFields.set(response.name, response.fields); } return new AsyncSubscription(async () => { if (!store) return; const unsubscribed: string[] = []; for (const field of fields) { let v = store.get(field); if (v === undefined) throw new Error(`Someone deleted our field ${field}`); v--; if (v === 0) { store.delete(field); unsubscribed.push(field); //we can't remove it from knownEntityFields, because we don't know whether another //its still used by another client. } else { store.set(field, v); } } if (unsubscribed.length) { const response = await this.sendMessage<brokerEntityFields>( BrokerType.UnsubscribeEntityFields, { name: entityName, fields: unsubscribed } ).firstThenClose<brokerEntityFields>(BrokerType.EntityFields); this.knownEntityFields.set(response.name, response.fields); } }); } /** * Tries to lock an id on the broker. If the id is already locked, it returns immediately undefined without locking anything * * ttl (time to life) defines how long the given lock is allowed to stay active. Per default each lock is automatically unlocked * after 30 seconds. If you haven't released the lock until then, another lock acquisition is allowed to receive it anyways. * ttl of 0 disables ttl and keeps the lock alive until you manually unlock it (or the process dies). */ public async tryLock(id: string, ttl: number = 30): Promise<AsyncSubscription | undefined> { const subject = this.sendMessage<brokerLock>(BrokerType.TryLock, { id, ttl }); const message = await subject.waitNextMessage(); if (message.type === BrokerType.ResponseLockFailed) { subject.release(); return undefined; } if (message.type === BrokerType.ResponseLock) { return new AsyncSubscription(async () => { await subject.send(BrokerType.Unlock).ackThenClose(); }); } throw new Error(`Invalid message returned. Expected Lock, but got ${message.type}`); } /** * Locks an id on the broker. If the id is already locked, it waits until it is released. If timeout is specified, * the lock acquisition should take maximum `timeout` seconds. 0 means it waits without limit. * * ttl (time to life) defines how long the given lock is allowed to stay active. Per default each lock is automatically unlocked * after 30 seconds. If you haven't released the lock until then, another lock acquisition is allowed to receive it anyways. * ttl of 0 disables ttl and keeps the lock alive until you manually unlock it (or the process dies). */ public async lock(id: string, ttl: number = 30, timeout: number = 0): Promise<AsyncSubscription> { const subject = this.sendMessage<brokerLock>(BrokerType.Lock, { id, ttl, timeout }); await subject.waitNext(BrokerType.ResponseLock); //or throw error return new AsyncSubscription(async () => { await subject.send(BrokerType.Unlock).ackThenClose(); subject.release(); }); } public async isLocked(id: string): Promise<boolean> { const subject = this.sendMessage<brokerLockId>(BrokerType.IsLocked, { id }); const lock = await subject.firstThenClose<brokerResponseIsLock>(BrokerType.ResponseIsLock); return lock.v; } public channel<T>(channel: string, type?: ReceiveType<T>): BrokerChannel<T> { let brokerChannel = this.activeChannels.get(channel); if (!brokerChannel) { brokerChannel = new BrokerChannel(channel, resolveReceiveType(type), this); this.activeChannels.set(channel, brokerChannel); } return brokerChannel; } public async getRawOrUndefined<T>(id: string): Promise<Uint8Array | undefined> { const first: RpcMessage = await this.sendMessage<brokerGet>(BrokerType.Get, { n: id }).firstThenClose(BrokerType.ResponseGet); if (first.buffer && first.buffer.byteLength > first.bodyOffset) { return first.buffer.slice(first.bodyOffset); } return undefined; } public async getRaw<T>(id: string): Promise<Uint8Array> { const v = await this.getRawOrUndefined(id); if (v === undefined) throw new Error(`Key ${id} is undefined`); return v; } public async setRaw<T>(id: string, data: Uint8Array): Promise<undefined> { await this.sendMessage<brokerSet>(BrokerType.Set, { n: id, v: data }) .ackThenClose(); return undefined; } public key<T>(key: string, type?: ReceiveType<T>) { return new BrokerKeyValue(key, resolveReceiveType(type), this); } public async getIncrement<T>(id: string): Promise<number> { const v = await this.getRaw(id); const view = new DataView(v.buffer, v.byteOffset, v.byteLength); return view.getFloat64(0, true); } public async increment<T>(id: string, value?: number): Promise<number> { const response = await this.sendMessage<brokerIncrement>(BrokerType.Increment, { n: id, v: value }) .waitNext<brokerResponseIncrement>(BrokerType.ResponseIncrement); return response.v; } public async delete<T>(id: string): Promise<undefined> { await this.sendMessage<brokerDelete>(BrokerType.Delete, { n: id }) .ackThenClose(); return undefined; } } export class BrokerDirectClient extends BrokerClient { constructor(rpcKernel: BrokerKernel) { super(new RpcDirectClientAdapter(rpcKernel)); } }
the_stack
export class MuteMemberResponse { constructor(params: object); apiId: string; memberId: string; message: string; } export class StartRecordingConferenceResponse { constructor(params: object); apiId: string; message: string; recordingId: string; url: string; } export class RetrieveConferenceResponse { constructor(params: object); apiId: string; conferenceMemberCount: string; conferenceName: string; conferenceRunTime: string; members: string; } export class ListAllConferenceResponse { constructor(params: object); apiId: string; conferences: string; } export class SpeakMemberResponse { constructor(params: object); apiId: string; memberId: string; message: string; } export class PlayAudioMemberResponse { constructor(params: object); apiId: string; memberId: string; message: string; } export class DeafMemberResponse { constructor(params: string); apiId: string; memberId: string; message: string; } export class Conference extends PlivoResource { constructor(client: Function, data?: {}); id: string; /** * hangup conference * @method * @promise {Boolean} return true if call hung up * @fail {Error} return Error */ hangup(): Promise<any>; /** * hangup member from conference * @method * @param {string} memberId - id of member to be hangup * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ hangupMember(memberId: string): Promise<any>; /** * kick member from conference * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ kickMember(memberId: string): Promise<any>; /** * mute member from conference * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ muteMember(memberId: string): Promise<MuteMemberResponse>; /** * unmute member from conference * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ unmuteMember(memberId: string): Promise<any>; /** * deaf member from conference * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ deafMember(memberId: string): Promise<DeafMemberResponse>; /** * undeaf member from conference * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ undeafMember(memberId: string): Promise<any>; /** * play audio to member * @method * @param {string} memberId - id of member * @param {string} url - url for audio * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ playAudioToMember(memberId: string, url: string): Promise<PlayAudioMemberResponse>; /** * stop playing audio to member * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopPlayingAudioToMember(memberId: string): Promise<any>; /** * speak text to member * @method * @param {string} memberId - id of member * @param {string} text - text to be speak to member * @param {object} optionalParams - optionalPrams to speak text * @param {string} [optionalParams.voice] The voice to be used. Can be MAN or WOMAN. Defaults to WOMAN. * @param {string} [optionalParams.language] The language to be used. Defaults to en-US. * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ speakTextToMember(memberId: string, text: string, optionalParams: { voice: string; language: string; }): Promise<SpeakMemberResponse>; /** * stop speaking text to member * @method * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopSpeakingTextToMember(memberId: string): Promise<any>; /** * Record conference * @method * @param {object} params - optional params to record conference * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. * @param {string} [params.transcriptionUrl] The URL where the transcription is available. * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ record(params: { fileFormat: string; transcriptionType: string; transcriptionUrl: string; transcriptionMethod: string; callbackUrl: string; callbackMethod: string; }): Promise<any>; /** * Record conference * @method * @param {object} params - optional params to record conference * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. * @param {string} [params.transcriptionUrl] The URL where the transcription is available. * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ startRecording(params?: { fileFormat: string; transcriptionType: string; transcriptionUrl: string; transcriptionMethod: string; callbackUrl: string; callbackMethod: string; }): Promise<StartRecordingConferenceResponse>; /** * stop recording conference * @method * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopRecording(): Promise<any>; [clientKey]: symbol; } /** * Represents a Conference Interface * @constructor * @param {function} client - make api call * @param {object} [data] - data of call */ export class ConferenceInterface extends PlivoResourceInterface { constructor(client: Function, data?: {}); /** * get conference by id * @method * @param {string} id - id of conference * @promise {@link Conference} return {@link Conference} object if success * @fail {Error} return Error */ get(id: string): Promise<RetrieveConferenceResponse>; /** * get all conferences. returns name of all conferences * @method * @promise {@link [Conference]} returns list of {@link Conference} objects if success * @fail {Error} return Error */ list(): Promise<ListAllConferenceResponse>; /** * hangup conference * @method * @param {string} conferenceName - name of conference * @promise {@link Conference} return {@link Conference} object if success * @fail {Error} return Error */ hangup(conferenceName: string): Promise<any>; /** * hangup all * @method * @promise {@link PlivoGenericResponse} returns object of PlivoGenericResponse if success * @fail {Error} return Error */ hangupAll(): Promise<any>; /** * hangup member from conference * @method * @param {string} id - id of conference * @param {string} memberId - id of member to be hangup * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ hangupMember(id: string, memberId: string): Promise<any>; /** * kick member from conference * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ kickMember(id: string, memberId: string): Promise<any>; /** * mute member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ muteMember(id: string, memberId: string): Promise<any>; /** * unmute member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ unmuteMember(id: string, memberId: string): Promise<any>; /** * deaf member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ deafMember(id: string, memberId: string): Promise<any>; /** * undeaf member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ undeafMember(id: string, memberId: string): Promise<any>; /** * play audio to member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @param {string} url - urls for audio * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ playAudioToMember(id: string, memberId: string, url: string): Promise<any>; /** * stop playing audio to member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopPlayingAudioToMember(id: string, memberId: string): Promise<any>; /** * speak text to member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @param {string} text - text to speak * @param {object} optionalParams - optional params * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ speakTextToMember(id: string, memberId: string, text: string, optionalParams: object): Promise<any>; /** * stop speaking text to member * @method * @param {string} id - id of conference * @param {string} memberId - id of member * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopSpeakingTextToMember(id: string, memberId: string): Promise<any>; /** * record conference * @method * @param {string} id - id of conference * @param {object} params - optional params to record conference * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. * @param {string} [params.transcriptionUrl] The URL where the transcription is available. * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ record(id: string, params: { fileFormat: string; transcriptionType: string; transcriptionUrl: string; transcriptionMethod: string; callbackUrl: string; callbackMethod: string; }): Promise<any>; /** * record conference * @method * @param {string} id - id of conference * @param {object} params - optional params to record conference * @param {string} [params.fileFormat] The file format of the record can be of mp3 or wav format. Defaults to mp3 format. * @param {string} [params.transcriptionType] The type of transcription required. The following values are allowed: * - auto - This is the default value. Transcription is completely automated; turnaround time is about 5 minutes. * - hybrid - Transcription is a combination of automated and human verification processes; turnaround time is about 10-15 minutes. * @param {string} [params.transcriptionUrl] The URL where the transcription is available. * @param {string} [params.transcriptionMethod] The method used to invoke the transcription_url. Defaults to POST. * @param {string} [params.callbackUrl] The URL invoked by the API when the recording ends. * @param {string} [params.callbackMethod] The method which is used to invoke the callback_url URL. Defaults to POST. * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ startRecording(id: string, params: { fileFormat: string; transcriptionType: string; transcriptionUrl: string; transcriptionMethod: string; callbackUrl: string; callbackMethod: string; }): Promise<any>; /** * stop recording * @method * @param {string} id - id of conference * @promise {PlivoGenericResponse} return PlivoGenericResponse if success * @fail {Error} return Error */ stopRecording(id: string): Promise<any>; [clientKey]: symbol; } import { PlivoResource } from "../base"; declare const clientKey: unique symbol; import { PlivoResourceInterface } from "../base"; export {};
the_stack
import * as chai from 'chai'; import {KeycloakAdminClient} from '../src/client'; import {credentials} from './constants'; import ClientScopeRepresentation from '../src/defs/clientScopeRepresentation'; import ProtocolMapperRepresentation from '../src/defs/protocolMapperRepresentation'; import ClientRepresentation from '../src/defs/clientRepresentation'; const expect = chai.expect; describe('Client Scopes', () => { let kcAdminClient: KeycloakAdminClient; let currentClientScope: ClientScopeRepresentation; let currentClientScopeName: string; let currentClient: ClientRepresentation; before(async () => { kcAdminClient = new KeycloakAdminClient(); await kcAdminClient.auth(credentials); }); beforeEach(async () => { currentClientScopeName = 'best-of-the-bests-scope'; await kcAdminClient.clientScopes.create({ name: currentClientScopeName, }); currentClientScope = (await kcAdminClient.clientScopes.findOneByName({ name: currentClientScopeName, }))!; }); afterEach(async () => { // cleanup default client scopes try { await kcAdminClient.clientScopes.delDefaultClientScope({ id: currentClientScope.id!, }); } catch (e) { // ignore } // cleanup optional client scopes try { await kcAdminClient.clientScopes.delDefaultOptionalClientScope({ id: currentClientScope.id!, }); } catch (e) { // ignore } // cleanup client scopes try { await kcAdminClient.clientScopes.delByName({ name: currentClientScopeName, }); } catch (e) { // ignore } }); it('list client scopes', async () => { const scopes = await kcAdminClient.clientScopes.find(); expect(scopes).to.be.ok; }); it('create client scope and get by name', async () => { // ensure that the scope does not exist try { await kcAdminClient.clientScopes.delByName({ name: currentClientScopeName, }); } catch (e) { // ignore } await kcAdminClient.clientScopes.create({ name: currentClientScopeName, }); const scope = (await kcAdminClient.clientScopes.findOneByName({ name: currentClientScopeName, }))!; expect(scope).to.be.ok; expect(scope.name).to.equal(currentClientScopeName); }); it('find scope by id', async () => { const scope = await kcAdminClient.clientScopes.findOne({ id: currentClientScope.id!, }); expect(scope).to.be.ok; expect(scope).to.eql(currentClientScope); }); it('find scope by name', async () => { const scope = (await kcAdminClient.clientScopes.findOneByName({ name: currentClientScopeName, }))!; expect(scope).to.be.ok; expect(scope.name).to.eql(currentClientScopeName); }); it('return null if scope not found by id', async () => { const scope = await kcAdminClient.clientScopes.findOne({ id: 'I do not exist', }); expect(scope).to.be.null; }); it('return null if scope not found by name', async () => { const scope = await kcAdminClient.clientScopes.findOneByName({ name: 'I do not exist', }); expect(scope).to.be.undefined; }); it('update client scope', async () => { const {id, description: oldDescription} = currentClientScope; const description = 'This scope is totally awesome.'; await kcAdminClient.clientScopes.update({id: id!}, {description}); const updatedScope = (await kcAdminClient.clientScopes.findOne({ id: id!, }))!; expect(updatedScope).to.be.ok; expect(updatedScope).not.to.eql(currentClientScope); expect(updatedScope.description).to.eq(description); expect(updatedScope.description).not.to.eq(oldDescription); }); it('delete single client scope by id', async () => { await kcAdminClient.clientScopes.del({ id: currentClientScope.id!, }); const scope = await kcAdminClient.clientScopes.findOne({ id: currentClientScope.id!, }); expect(scope).not.to.be.ok; }); it('delete single client scope by name', async () => { await kcAdminClient.clientScopes.delByName({ name: currentClientScopeName, }); const scope = await kcAdminClient.clientScopes.findOneByName({ name: currentClientScopeName, }); expect(scope).not.to.be.ok; }); describe('default client scope', () => { it('list default client scopes', async () => { const defaultClientScopes = await kcAdminClient.clientScopes.listDefaultClientScopes(); expect(defaultClientScopes).to.be.ok; }); it('add default client scope', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addDefaultClientScope({id: id!}); const defaultClientScopeList = await kcAdminClient.clientScopes.listDefaultClientScopes(); const defaultClientScope = defaultClientScopeList.find( (scope) => scope.id === id, )!; expect(defaultClientScope).to.be.ok; expect(defaultClientScope.id).to.equal(currentClientScope.id); expect(defaultClientScope.name).to.equal(currentClientScope.name); }); it('delete default client scope', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addDefaultClientScope({id: id!}); await kcAdminClient.clientScopes.delDefaultClientScope({id: id!}); const defaultClientScopeList = await kcAdminClient.clientScopes.listDefaultClientScopes(); const defaultClientScope = defaultClientScopeList.find( (scope) => scope.id === id, ); expect(defaultClientScope).not.to.be.ok; }); }); describe('default optional client scopes', () => { it('list default optional client scopes', async () => { const defaultOptionalClientScopes = await kcAdminClient.clientScopes.listDefaultOptionalClientScopes(); expect(defaultOptionalClientScopes).to.be.ok; }); it('add default optional client scope', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addDefaultOptionalClientScope({id: id!}); const defaultOptionalClientScopeList = await kcAdminClient.clientScopes.listDefaultOptionalClientScopes(); const defaultOptionalClientScope = defaultOptionalClientScopeList.find( (scope) => scope.id === id, )!; expect(defaultOptionalClientScope).to.be.ok; expect(defaultOptionalClientScope.id).to.eq(currentClientScope.id); expect(defaultOptionalClientScope.name).to.eq(currentClientScope.name); }); it('delete default optional client scope', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addDefaultOptionalClientScope({id: id!}); await kcAdminClient.clientScopes.delDefaultOptionalClientScope({id: id!}); const defaultOptionalClientScopeList = await kcAdminClient.clientScopes.listDefaultOptionalClientScopes(); const defaultOptionalClientScope = defaultOptionalClientScopeList.find( (scope) => scope.id === id, ); expect(defaultOptionalClientScope).not.to.be.ok; }); }); describe('protocol mappers', () => { let dummyMapper: ProtocolMapperRepresentation; beforeEach(() => { dummyMapper = { name: 'mapping-maps-mapper', protocol: 'openid-connect', protocolMapper: 'oidc-audience-mapper', }; }); afterEach(async () => { try { const {id} = currentClientScope; const { id: mapperId, } = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; await kcAdminClient.clientScopes.delProtocolMapper({ id: id!, mapperId: mapperId!, }); } catch (e) { // ignore } }); it('list protocol mappers', async () => { const {id} = currentClientScope; const mapperList = await kcAdminClient.clientScopes.listProtocolMappers({ id: id!, }); expect(mapperList).to.be.ok; }); it('add multiple protocol mappers', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addMultipleProtocolMappers({id: id!}, [ dummyMapper, ]); const mapper = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; expect(mapper).to.be.ok; expect(mapper.protocol).to.eq(dummyMapper.protocol); expect(mapper.protocolMapper).to.eq(dummyMapper.protocolMapper); }); it('add single protocol mapper', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const mapper = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; expect(mapper).to.be.ok; expect(mapper.protocol).to.eq(dummyMapper.protocol); expect(mapper.protocolMapper).to.eq(dummyMapper.protocolMapper); }); it('find protocol mapper by id', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const { id: mapperId, } = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; const mapper = await kcAdminClient.clientScopes.findProtocolMapper({ id: id!, mapperId: mapperId!, }); expect(mapper).to.be.ok; expect(mapper?.id).to.eql(mapperId); }); it('find protocol mapper by name', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const mapper = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; expect(mapper).to.be.ok; expect(mapper.name).to.eql(dummyMapper.name); }); it('find protocol mappers by protocol', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const mapperList = await kcAdminClient.clientScopes.findProtocolMappersByProtocol( {id: id!, protocol: dummyMapper.protocol!}, ); expect(mapperList).to.be.ok; expect(mapperList.length).to.be.gte(1); const mapper = mapperList.find((item) => item.name === dummyMapper.name); expect(mapper).to.be.ok; }); it('update protocol mapper', async () => { const {id} = currentClientScope; dummyMapper.config = {'access.token.claim': 'true'}; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const mapper = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; expect(mapper.config!['access.token.claim']).to.eq('true'); mapper.config = {'access.token.claim': 'false'}; await kcAdminClient.clientScopes.updateProtocolMapper( {id: id!, mapperId: mapper.id!}, mapper, ); const updatedMapper = (await kcAdminClient.clientScopes.findProtocolMapperByName( {id: id!, name: dummyMapper.name!}, ))!; expect(updatedMapper.config!['access.token.claim']).to.eq('false'); }); it('delete protocol mapper', async () => { const {id} = currentClientScope; await kcAdminClient.clientScopes.addProtocolMapper({id: id!}, dummyMapper); const { id: mapperId, } = (await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }))!; await kcAdminClient.clientScopes.delProtocolMapper({id: id!, mapperId: mapperId!}); const mapper = await kcAdminClient.clientScopes.findProtocolMapperByName({ id: id!, name: dummyMapper.name!, }); expect(mapper).not.to.be.ok; }); }); describe('scope mappings', () => { it('list client and realm scope mappings', async () => { const {id} = currentClientScope; const scopes = await kcAdminClient.clientScopes.listScopeMappings({ id: id!, }); expect(scopes).to.be.ok; }); describe('client', () => { const dummyClientId = 'scopeMappings-dummy'; const dummyRoleName = 'scopeMappingsRole-dummy'; beforeEach(async () => { const {id} = await kcAdminClient.clients.create({ clientId: dummyClientId, }); currentClient = (await kcAdminClient.clients.findOne({ id, }))!; await kcAdminClient.clients.createRole({ id, name: dummyRoleName, }); }); afterEach(async () => { const {id} = currentClient; await kcAdminClient.clients.delRole({ id: id!, roleName: dummyRoleName, }); await kcAdminClient.clients.del({id: id!}); }); it('add scope mappings', async () => { const {id} = currentClientScope; const {id: clientUniqueId} = currentClient; const availableRoles = await kcAdminClient.clientScopes.listAvailableClientScopeMappings( { id: id!, client: clientUniqueId!, }, ); const filteredRoles = availableRoles.filter((role) => !role.composite); await kcAdminClient.clientScopes.addClientScopeMappings( { id: id!, client: clientUniqueId!, }, filteredRoles, ); const roles = await kcAdminClient.clientScopes.listClientScopeMappings({ id: id!, client: clientUniqueId!, }); expect(roles).to.be.ok; expect(roles).to.be.eql(filteredRoles); }); it('list scope mappings', async () => { const {id} = currentClientScope; const {id: clientUniqueId} = currentClient; const roles = await kcAdminClient.clientScopes.listClientScopeMappings({ id: id!, client: clientUniqueId!, }); expect(roles).to.be.ok; }); it('list available scope mappings', async () => { const {id} = currentClientScope; const {id: clientUniqueId} = currentClient; const roles = await kcAdminClient.clientScopes.listAvailableClientScopeMappings( { id: id!, client: clientUniqueId!, }, ); expect(roles).to.be.ok; }); it('list composite scope mappings', async () => { const {id} = currentClientScope; const {id: clientUniqueId} = currentClient; const roles = await kcAdminClient.clientScopes.listCompositeClientScopeMappings( { id: id!, client: clientUniqueId!, }, ); expect(roles).to.be.ok; }); it('delete scope mappings', async () => { const {id} = currentClientScope; const {id: clientUniqueId} = currentClient; const rolesBefore = await kcAdminClient.clientScopes.listClientScopeMappings( { id: id!, client: clientUniqueId!, }, ); await kcAdminClient.clientScopes.delClientScopeMappings( { id: id!, client: clientUniqueId!, }, rolesBefore, ); const rolesAfter = await kcAdminClient.clientScopes.listClientScopeMappings( { id: id!, client: clientUniqueId!, }, ); expect(rolesAfter).to.be.ok; expect(rolesAfter).to.eql([]); }); }); describe('realm', () => { const dummyRoleName = 'realmScopeMappingsRole-dummy'; beforeEach(async () => { await kcAdminClient.roles.create({ name: dummyRoleName, }); }); afterEach(async () => { try { await kcAdminClient.roles.delByName({ name: dummyRoleName, }); } catch (e) { // ignore } }); it('add scope mappings', async () => { const {id} = currentClientScope; const availableRoles = await kcAdminClient.clientScopes.listAvailableRealmScopeMappings( {id: id!}, ); const filteredRoles = availableRoles.filter((role) => !role.composite); await kcAdminClient.clientScopes.addRealmScopeMappings( {id: id!}, filteredRoles, ); const roles = await kcAdminClient.clientScopes.listRealmScopeMappings({ id: id!, }); expect(roles).to.be.ok; expect(roles).to.include.deep.members(filteredRoles); }); it('list scope mappings', async () => { const {id} = currentClientScope; const roles = await kcAdminClient.clientScopes.listRealmScopeMappings({ id: id!, }); expect(roles).to.be.ok; }); it('list available scope mappings', async () => { const {id} = currentClientScope; const roles = await kcAdminClient.clientScopes.listAvailableRealmScopeMappings( { id: id!, }, ); expect(roles).to.be.ok; }); it('list composite scope mappings', async () => { const {id} = currentClientScope; const roles = await kcAdminClient.clientScopes.listCompositeRealmScopeMappings( { id: id!, }, ); expect(roles).to.be.ok; }); it('delete scope mappings', async () => { const {id} = currentClientScope; const rolesBefore = await kcAdminClient.clientScopes.listRealmScopeMappings( { id: id!, }, ); await kcAdminClient.clientScopes.delRealmScopeMappings( { id: id!, }, rolesBefore, ); const rolesAfter = await kcAdminClient.clientScopes.listRealmScopeMappings( { id: id!, }, ); expect(rolesAfter).to.be.ok; expect(rolesAfter).to.eql([]); }); }); }); });
the_stack
import * as path from 'path'; import { ForgeClient, IAuthOptions } from 'forge-server-utils/dist/common'; const ApiHost = 'https://otg.autodesk.com' const RootPath = 'modeldata'; const ReadTokenScopes = ['bucket:read', 'data:read']; const WriteTokenScopes = ['data:write']; export interface IView { urn: string; id: string; role: string; mime: string; resolvedUrn: string; } interface IPropertyDbAsset { tag: string; type: string; resolvedUrn: string; } export class ManifestHelper { constructor(protected manifest: any) { console.assert(manifest.version === 1); console.assert(manifest.progress === 'complete'); console.assert(manifest.status === 'success'); } get sharedRoot() { return this.manifest.paths.shared_root; } listViews(): IView[] { const versionRoot = this.manifest.paths.version_root; return Object.entries(this.manifest.views).map(([id, view]: [string, any]) => { return { id, role: view.role, mime: view.mime, urn: view.urn, resolvedUrn: path.normalize(path.join(versionRoot, view.urn)) }; }); } listSharedDatabaseAssets(): IPropertyDbAsset[] { const pdbManifest = this.manifest.pdb_manifest; const sharedRoot = this.manifest.paths.shared_root; return pdbManifest.assets.filter((asset: any) => asset.isShared).map((asset: any) => { return { tag: asset.tag, type: asset.type, uri: asset.uri, resolvedUrn: path.normalize(path.join(sharedRoot, pdbManifest.pdb_shared_rel_path, asset.uri)) }; }); } } export class ViewHelper { constructor(protected view: any, protected resolvedViewUrn: string) { } listPrivateModelAssets(): ({ [key: string]: { uri: string; resolvedUrn: string; } } | undefined) { const assets = this.view.manifest && this.view.manifest.assets; if (assets) { let result: { [key: string]: { uri: string; resolvedUrn: string; } } = {}; if (assets.fragments) { result.fragments = { uri: assets.fragments, resolvedUrn: this.resolveAssetUrn(assets.fragments) }; } if (assets.fragments_extra) { result.fragments_extra = { uri: assets.fragments_extra, resolvedUrn: this.resolveAssetUrn(assets.fragments_extra) }; } if (assets.materials_ptrs) { result.materials_ptrs = { uri: assets.materials_ptrs, resolvedUrn: this.resolveAssetUrn(assets.materials_ptrs) }; } if (assets.geometry_ptrs) { result.geometry_ptrs = { uri: assets.geometry_ptrs, resolvedUrn: this.resolveAssetUrn(assets.geometry_ptrs) }; } return result; } else { return undefined; } } listSharedModelAssets(): ({ [key: string]: { uri: string; resolvedUrn: string; } } | undefined) { const assets = this.view.manifest && this.view.manifest.shared_assets; if (assets) { let result: { [key: string]: { uri: string; resolvedUrn: string; } } = {}; if (assets.geometry) { result.geometry = { uri: assets.geometry, resolvedUrn: this.resolveAssetUrn(assets.geometry) }; } if (assets.materials) { result.materials = { uri: assets.materials, resolvedUrn: this.resolveAssetUrn(assets.materials) }; } if (assets.textures) { result.textures = { uri: assets.textures, resolvedUrn: this.resolveAssetUrn(assets.textures) }; } return result; } else { return undefined; } } listPrivateDatabaseAssets(): ({ [key: string]: { uri: string; resolvedUrn: string; } } | undefined) { const pdb = this.view.manifest && this.view.manifest.assets && this.view.manifest.assets.pdb; if (pdb) { return { avs: { uri: pdb.avs, resolvedUrn: this.resolveAssetUrn(pdb.avs) }, offsets: { uri: pdb.offsets, resolvedUrn: this.resolveAssetUrn(pdb.offsets) }, dbid: { uri: pdb.dbid, resolvedUrn: this.resolveAssetUrn(pdb.dbid) } }; } else { return undefined; } } listSharedDatabaseAssets(): ({ [key: string]: { uri: string; resolvedUrn: string; } } | undefined) { const pdb = this.view.manifest && this.view.manifest.shared_assets && this.view.manifest.shared_assets.pdb; if (pdb) { return { attrs: { uri: pdb.attrs, resolvedUrn: this.resolveAssetUrn(pdb.attrs) }, values: { uri: pdb.values, resolvedUrn: this.resolveAssetUrn(pdb.values) }, ids: { uri: pdb.ids, resolvedUrn: this.resolveAssetUrn(pdb.ids) } }; } else { return undefined; } } resolveAssetUrn(assetUrn: string): string { if (assetUrn.startsWith('urn:')) { return assetUrn; } else { return path.normalize( path.join(path.dirname(this.resolvedViewUrn), assetUrn) ); } } getGeometryUrn(hash: string): string { return this.view.manifest.shared_assets.geometry + hash; } getMaterialUrn(hash: string): string { return this.view.manifest.shared_assets.materials + hash; } getTextureUrn(hash: string): string { return this.view.manifest.shared_assets.textures + hash; } } /** * Client for the OTG service (https://otg.autodesk.com). */ export class Client extends ForgeClient { /** * Initializes the client with specific authentication and host address. * @param {IAuthOptions} auth Authentication object, * containing either `client_id` and `client_secret` properties (for 2-legged authentication), * or a single `token` property (for 2-legged or 3-legged authentication with pre-generated access token). * @param {string} [host="https://otg.autodesk.com"] OTG service host. */ constructor(auth: IAuthOptions, host: string = ApiHost) { super(RootPath, auth, host); this.axios.defaults.headers = this.axios.defaults.headers || {}; this.axios.defaults.headers['Pragma'] = 'no-cache'; } /** * Triggers processing of OTG derivatives for a specific model. * Note: the model must already be processed into SVF using the Model Derivative service. * @async * @param {string} urn Model Derivative model URN. * @param {string} [account] Optional account ID. * @param {boolean} [force] Optional flag to force the translation. * @throws Error when the request fails, for example, due to insufficient rights, or incorrect scopes. */ async createDerivatives(urn: string, account?: string, force?: boolean): Promise<any> { const params: { [key: string]: any } = { urn }; if (account) { params['account_id'] = account; } if (force) { params['force_conversion'] = force; } return this.post(``, params, {}, WriteTokenScopes); } /** * Removes OTG derivatives for a specific model. * @async * @param {string} urn Model Derivative model URN. * @throws Error when the request fails, for example, due to insufficient rights, or incorrect scopes. */ async deleteDerivatives(urn: string): Promise<any> { return this.delete(urn, {}, WriteTokenScopes); } /** * Retrieves the Model Derivative manifest augmented with OTG information. * @async * @param {string} urn Model Derivative model URN. * @returns {Promise<any>} Model Derivative manifest augmented with OTG information. * @throws Error when the request fails, for example, due to insufficient rights, or incorrect scopes. */ async getManifest(urn: string): Promise<any> { return this.get(`manifest/${urn}`, {}, ReadTokenScopes); } /** * Retrieves raw data of specific OTG asset. * @async * @param {string} urn Model Derivative model URN. * @param {string} assetUrn OTG asset URN, typically composed from OTG "version root" or "shared root", * path to OTG view JSON, etc. * @returns {Promise<Buffer>} Asset data. * @throws Error when the request fails, for example, due to insufficient rights, or incorrect scopes. */ async getAsset(urn: string, assetUrn: string): Promise<Buffer> { return this.getBuffer(`file/${assetUrn}?acmsession=${urn}`, {}, ReadTokenScopes); } } export class SharedClient extends ForgeClient { protected sharding: number = 4; constructor(auth: IAuthOptions, host: string = ApiHost) { super('cdn', auth, host); this.axios.defaults.headers = this.axios.defaults.headers || {}; this.axios.defaults.headers['Pragma'] = 'no-cache'; } async getAsset(urn: string, assetUrn: string): Promise<Buffer> { const assetUrnTokens = assetUrn.split('/'); const account = assetUrnTokens[1]; const assetType = assetUrnTokens[2]; const assetHash = assetUrnTokens[3]; const cdnUrn = `${assetHash.substr(0, 4)}/${account}/${assetType}/${assetHash.substr(4)}`; return this.getBuffer(cdnUrn + `?acmsession=${urn}`, {}, ReadTokenScopes); } }
the_stack
import { PdfColorSpace, PdfDocument, PdfGraphics, PdfPage, PdfStandardFont, PdfFontFamily, PdfColor, PdfSolidBrush, PdfGraphicsState } from "../../../../src/index"; import { Utils } from '../../utils.spec'; describe('PdfColor.ts', () => { describe('Constructor initializing',()=> { let t1 : PdfColor = new PdfColor(240, 250, 250, 100); it('-Set gray >1', () => { t1.gray = 50; expect(t1.gray).toEqual(1); }) it('-Set gray <1', () => { t1.gray = -5; expect(t1.gray).toEqual(0); }) it('-Set gray == 0', () => { t1.gray = 0; expect(t1.gray).toEqual(0); }) it('-Set a >=0', () => { t1.a = 50; expect(t1.a).toEqual(50); }) it('-Set a <0', () => { t1.a = -5; expect(t1.a).toEqual(0); }) it('-ToString(PdfColorSpace.Cmyk, false) != Undefined', () => { expect(t1.toString(PdfColorSpace.Cmyk, false)).not.toBeUndefined(); }) let t2 : PdfColor = new PdfColor(t1); it('-Check empty PdfColor overload', () => { expect(t2.isEmpty).toEqual(false); }) let emptyColor : PdfColor; let t3 : PdfColor = new PdfColor(emptyColor); it('-Check empty - overload emptyColor', () => { expect(t3.isEmpty).toEqual(true); }) let t4 : PdfColor = new PdfColor(); it('-Check empty - overload', () => { expect(t4.isEmpty).toEqual(true); }) let emptyNumber : number; let t5 : PdfColor = new PdfColor(emptyNumber, 100, 100); it('-Check empty - emptyNumber overload', () => { expect(t5.isEmpty).toEqual(true); }) let t6 : PdfColor = new PdfColor(100, emptyNumber, 100); it('-Check empty - emptyNumber overload', () => { expect(t6.isEmpty).toEqual(true); }) let t7 : PdfColor = new PdfColor(100, 100, emptyNumber); it('-Check empty - emptyNumber overload', () => { expect(t7.isEmpty).toEqual(true); }) let t8 : PdfColor = new PdfColor(100, 100, 100); it('-Check number, number, number - overload', () => { expect(t8.isEmpty).toEqual(false); }) let t9 : PdfColor = new PdfColor(emptyNumber, 100, 100, 100); it('-Check undefined, number, number, number - overload', () => { expect(t9.isEmpty).toEqual(false); }) let t10 : PdfColor = new PdfColor(100, emptyNumber, 100, 100); it('-Check empty - emptyNumber overload', () => { expect(t10.isEmpty).toEqual(true); }) let t11 : PdfColor = new PdfColor(100, 100, emptyNumber, 100); it('-Check empty - emptyNumber overload', () => { expect(t11.isEmpty).toEqual(true); }) let t12 : PdfColor = new PdfColor(100, 100, 100, emptyNumber); it('-Check number, number, number, undefined - overload', () => { expect(t12.isEmpty).toEqual(false); }) let t13 : PdfColor = new PdfColor(100, 100, 100, 100); it('-Check number, number, number, number - overload', () => { expect(t13.isEmpty).toEqual(false); }) }) }) describe('Manual testing',()=>{ it('-Empty color with graphic state', (done) => { let document : PdfDocument = new PdfDocument(); let page : PdfPage = document.pages.add(); let graphics : PdfGraphics = page.graphics; let emptyColor : PdfColor = new PdfColor(); let emptyBrush : PdfSolidBrush = new PdfSolidBrush(emptyColor); graphics.drawRectangle(emptyBrush, 10, 50, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 10, null); let state : PdfGraphicsState = graphics.save(); let redColor : PdfColor = new PdfColor(255, 0, 0); let redBrush : PdfSolidBrush = new PdfSolidBrush(redColor); graphics.drawRectangle(redBrush, 10, 150, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, redBrush, 10, 100, null); graphics.drawRectangle(emptyBrush, 10, 250, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 200, null); graphics.restore(state); graphics.drawRectangle(emptyBrush, 10, 350, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 300, null); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EmptyColorWithGraphicState.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }); }); describe('Manual testing',()=>{ it('-Empty color', (done) => { let document : PdfDocument = new PdfDocument(); let page : PdfPage = document.pages.add(); let graphics : PdfGraphics = page.graphics; let emptyColor : PdfColor = new PdfColor(); let emptyBrush : PdfSolidBrush = new PdfSolidBrush(emptyColor); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 10, null); graphics.drawRectangle(emptyBrush, 10, 10, 100, 20); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EmptyColor.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }); }); describe('Manual testing',()=>{ it('-Red With Empty Color', (done) => { let document : PdfDocument = new PdfDocument(); let page : PdfPage = document.pages.add(); let graphics : PdfGraphics = page.graphics; let redColor : PdfColor = new PdfColor(255, 0, 0); let redBrush : PdfSolidBrush = new PdfSolidBrush(redColor); let emptyColor : PdfColor = new PdfColor(); let emptyBrush : PdfSolidBrush = new PdfSolidBrush(emptyColor); graphics.drawRectangle(redBrush, 10, 50, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 10, null); graphics.drawRectangle(emptyBrush, 10, 150, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 100, 10, null); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'RedWithEmptyColor.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }); }); describe('Manual testing',()=>{ it('-Empty color - multiple page', (done) => { let document : PdfDocument = new PdfDocument(); let page : PdfPage = document.pages.add(); let graphics : PdfGraphics = page.graphics; let emptyColor : PdfColor = new PdfColor(); let emptyBrush : PdfSolidBrush = new PdfSolidBrush(emptyColor); graphics.drawRectangle(emptyBrush, 10, 50, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 10, null); let state : PdfGraphicsState = graphics.save(); let redColor : PdfColor = new PdfColor(255, 0, 0); let redBrush : PdfSolidBrush = new PdfSolidBrush(redColor); graphics.drawRectangle(redBrush, 10, 150, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, redBrush, 10, 100, null); graphics.drawRectangle(emptyBrush, 10, 250, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 200, null); graphics.restore(state); graphics.drawRectangle(emptyBrush, 10, 350, 100, 20); graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 300, null); let secondPage : PdfPage = document.pages.add(); secondPage.graphics.drawRectangle(emptyBrush, 10, 50, 100, 20); secondPage.graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 10, null); let graphicsState : PdfGraphicsState = secondPage.graphics.save(); secondPage.graphics.drawRectangle(redBrush, 10, 150, 100, 20); secondPage.graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, redBrush, 10, 100, null); secondPage.graphics.drawRectangle(emptyBrush, 10, 250, 100, 20); secondPage.graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 200, null); secondPage.graphics.restore(graphicsState); secondPage.graphics.drawRectangle(emptyBrush, 10, 350, 100, 20); secondPage.graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, emptyBrush, 10, 300, null); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'EmptyColorWithMultiplePage.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }); }); describe('Manual testing',()=>{ it('-Overload test', (done) => { let document : PdfDocument = new PdfDocument(); let page : PdfPage = document.pages.add(); let graphics : PdfGraphics = page.graphics; let emptyNumber : number; let emptyPdfColor : PdfColor; let emptyColor : PdfColor = new PdfColor(200, emptyNumber, emptyNumber); let emptyBrush : PdfSolidBrush = new PdfSolidBrush(emptyColor); let redColor : PdfColor = new PdfColor(255, 0, 0); let redBrush : PdfSolidBrush = new PdfSolidBrush(redColor); //empty constructor graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor()), 10, 10, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor()), 10, 50, 100, 20); //PdfColor is undefined graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(emptyPdfColor)), 210, 10, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(emptyPdfColor)), 210, 50, 100, 20); //undefined-number-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(emptyNumber, 255, 255)), 10, 100, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(emptyNumber, 255, 255)), 10, 150, 100, 20); //number-undefined-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, emptyNumber, 255)), 10, 200, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, emptyNumber, 255)), 10, 250, 100, 20); //number-number-undefined graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, 255, emptyNumber)), 10, 300, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, 255, emptyNumber)), 10, 350, 100, 20); //number-number-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, 0, 0)), 10, 400, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, 0, 0)), 10, 450, 100, 20); //undefined-number-number-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(emptyNumber, 255, 0, 255)), 210, 100, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(emptyNumber, 255, 0, 255)), 210, 150, 100, 20); //number-undefined-number-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, emptyNumber, 255, 255)), 210, 200, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, emptyNumber, 255, 255)), 210, 250, 100, 20); //number-number-undefined-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, 255, emptyNumber, 255)), 210, 300, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, 255, emptyNumber, 255)), 210, 350, 100, 20); //number-number-number-undefined graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(255, 255, 0, emptyNumber)), 210, 400, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(255, 255, 0, emptyNumber)), 210, 450, 100, 20); //number-number-number-number graphics.drawString("Hello world", new PdfStandardFont(PdfFontFamily.Helvetica, 10), null, new PdfSolidBrush(new PdfColor(0.5, 0, 255, 255)), 210, 500, null); graphics.drawRectangle(new PdfSolidBrush(new PdfColor(0.5, 0, 255, 255)), 210, 550, 100, 20); document.save().then((xlBlob: { blobData: Blob }) => { if (Utils.isDownloadEnabled) { Utils.download(xlBlob.blobData, 'PdfColorOverloadTest.pdf'); } let reader: FileReader = new FileReader(); reader.readAsArrayBuffer(xlBlob.blobData); reader.onload = (): void => { if (reader.readyState == 2) { // DONE == 2 expect((reader.result as ArrayBuffer).byteLength).toBeGreaterThanOrEqual(0); done(); } } }); document.destroy(); }); });
the_stack
import {Mutable, Class, AnyTiming, Timing} from "@swim/util"; import {Affinity, Property} from "@swim/component"; import {ConstraintProperty} from "@swim/constraint"; import {AnyLength, Length} from "@swim/math"; import {AnyPresence, Presence, AnyExpansion, Expansion} from "@swim/style"; import { Look, Mood, ThemeAnimator, PresenceThemeAnimator, ExpansionThemeAnimator, ThemeConstraintAnimator, } from "@swim/theme"; import { ViewportInsets, ViewContextType, View, ModalOptions, ModalState, Modal, } from "@swim/view"; import {HtmlViewInit, HtmlView} from "@swim/dom"; import type {DrawerViewObserver} from "./DrawerViewObserver"; /** @public */ export type DrawerPlacement = "top" | "right" | "bottom" | "left"; /** @public */ export interface DrawerViewInit extends HtmlViewInit { placement?: DrawerPlacement; collapsedWidth?: AnyLength; expandedWidth?: AnyLength; } /** @public */ export class DrawerView extends HtmlView implements Modal { constructor(node: HTMLElement) { super(node); this.modality = true; this.initDrawer(); } override readonly observerType?: Class<DrawerViewObserver>; protected initDrawer(): void { this.addClass("drawer"); this.display.setState("flex", Affinity.Intrinsic); this.overflowX.setState("hidden", Affinity.Intrinsic); this.overflowY.setState("auto", Affinity.Intrinsic); this.overscrollBehaviorY.setState("contain", Affinity.Intrinsic); this.overflowScrolling.setState("touch", Affinity.Intrinsic); } @ThemeConstraintAnimator({type: Length, value: Length.px(60)}) readonly collapsedWidth!: ThemeConstraintAnimator<this, Length, AnyLength>; @ThemeConstraintAnimator({type: Length, value: Length.px(200)}) readonly expandedWidth!: ThemeConstraintAnimator<this, Length, AnyLength>; @ConstraintProperty<DrawerView, Length | null, AnyLength | null>({ type: Length, value: null, toNumber(value: Length | null): number { return value !== null ? value.pxValue() : 0; }, }) readonly effectiveWidth!: ConstraintProperty<this, Length | null, AnyLength | null>; @ConstraintProperty<DrawerView, Length | null, AnyLength | null>({ type: Length, value: null, toNumber(value: Length | null): number { return value !== null ? value.pxValue() : 0; }, }) readonly effectiveHeight!: ConstraintProperty<this, Length | null, AnyLength | null>; isHorizontal(): boolean { return this.placement.value === "top" || this.placement.value === "bottom"; } isVertical(): boolean { return this.placement.value === "left" || this.placement.value === "right"; } protected willSetPlacement(newPlacement: DrawerPlacement, oldPlacement: DrawerPlacement): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillSetPlacement !== void 0) { observer.viewWillSetPlacement(newPlacement, oldPlacement, this); } } } protected onSetPlacement(newPlacement: DrawerPlacement, oldPlacement: DrawerPlacement): void { // hook } protected didSetPlacement(newPlacement: DrawerPlacement, oldPlacement: DrawerPlacement): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidSetPlacement !== void 0) { observer.viewDidSetPlacement(newPlacement, oldPlacement, this); } } } @Property<DrawerView, DrawerPlacement>({ type: String, value: "left", updateFlags: View.NeedsResize | View.NeedsLayout, willSetValue(newPlacement: DrawerPlacement, oldPlacement: DrawerPlacement): void { this.owner.willSetPlacement(newPlacement, oldPlacement); }, didSetValue(newPlacement: DrawerPlacement, oldPlacement: DrawerPlacement): void { this.owner.onSetPlacement(newPlacement, oldPlacement); this.owner.didSetPlacement(newPlacement, oldPlacement); }, }) readonly placement!: Property<this, DrawerPlacement>; protected willPresent(): void { const observers = this.observers!; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillPresent !== void 0) { observer.viewWillPresent(this); } } } protected didPresent(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidPresent !== void 0) { observer.viewDidPresent(this); } } } protected willDismiss(): void { const modalService = this.modalProvider.service; if (modalService !== void 0 && modalService !== null) { modalService.dismissModal(this); } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillDismiss !== void 0) { observer.viewWillDismiss(this); } } } protected didDismiss(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidDismiss !== void 0) { observer.viewDidDismiss(this); } } } @ThemeAnimator<DrawerView, Presence, AnyPresence>({ type: Presence, value: Presence.presented(), updateFlags: View.NeedsLayout, willPresent(): void { this.owner.willPresent(); }, didPresent(): void { this.owner.didPresent(); }, willDismiss(): void { this.owner.willDismiss(); }, didDismiss(): void { this.owner.didDismiss(); }, }) readonly slide!: PresenceThemeAnimator<this, Presence, AnyPresence>; protected willExpand(): void { const modalService = this.modalProvider.service; if (modalService !== void 0 && modalService !== null) { modalService.dismissModal(this); } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillExpand !== void 0) { observer.viewWillExpand(this); } } } protected didExpand(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidExpand !== void 0) { observer.viewDidExpand(this); } } } protected willCollapse(): void { const modalService = this.modalProvider.service; if (modalService !== void 0 && modalService !== null) { modalService.dismissModal(this); } const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewWillCollapse !== void 0) { observer.viewWillCollapse(this); } } } protected didCollapse(): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; if (observer.viewDidCollapse !== void 0) { observer.viewDidCollapse(this); } } } @ThemeAnimator<DrawerView, Expansion, AnyExpansion>({ type: Expansion, value: Expansion.expanded(), updateFlags: View.NeedsResize | View.NeedsLayout, willExpand(): void { this.owner.willExpand(); }, didExpand(): void { this.owner.didExpand(); }, willCollapse(): void { this.owner.willCollapse(); }, didCollapse(): void { this.owner.didCollapse(); }, }) readonly stretch!: ExpansionThemeAnimator<this, Expansion, AnyExpansion>; @Property({type: Object, inherits: true, value: null}) readonly edgeInsets!: Property<this, ViewportInsets | null>; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.display.setState(!this.slide.dismissed ? "flex" : "none", Affinity.Intrinsic); this.layoutDrawer(viewContext); if (viewContext.viewportIdiom === "mobile") { this.boxShadow.setState(this.getLookOr(Look.shadow, Mood.floating, null), Affinity.Intrinsic); } else { this.boxShadow.setState(this.getLookOr(Look.shadow, null), Affinity.Intrinsic); } } protected layoutDrawer(viewContext: ViewContextType<this>): void { const placement = this.placement.value; if (placement === "top") { this.layoutDrawerTop(viewContext); } else if (placement === "right") { this.layoutDrawerRight(viewContext); } else if (placement === "bottom") { this.layoutDrawerBottom(viewContext); } else if (placement === "left") { this.layoutDrawerLeft(viewContext); } } protected layoutDrawerTop(viewContext: ViewContextType<this>): void { const slidePhase = this.slide.getPhase(); this.addClass("drawer-top") .removeClass("drawer-right") .removeClass("drawer-bottom") .removeClass("drawer-left"); this.position.setState("fixed", Affinity.Intrinsic); this.width.setState(null, Affinity.Intrinsic); this.height.setState(null, Affinity.Intrinsic); this.left.setState(Length.zero(), Affinity.Intrinsic); this.right.setState(Length.zero(), Affinity.Intrinsic); this.bottom.setState(null, Affinity.Intrinsic); let height: Length | null = this.height.value; if (height === null) { height = Length.px(this.node.offsetHeight); } this.top.setState(height.times(slidePhase - 1), Affinity.Intrinsic); this.effectiveWidth.setValue(this.width.value); this.effectiveHeight.setValue(height.times(slidePhase), Affinity.Intrinsic); let edgeInsets = this.edgeInsets.superValue; if (edgeInsets === void 0 || edgeInsets === null) { edgeInsets = viewContext.viewport.safeArea; } this.edgeInsets.setValue({ insetTop: 0, insetRight: edgeInsets.insetRight, insetBottom: 0, insetLeft: edgeInsets.insetLeft, }, Affinity.Intrinsic); if (this.stretch.collapsed) { this.expand(); } } protected layoutDrawerRight(viewContext: ViewContextType<this>): void { const stretchPhase = this.stretch.getPhase(); const slidePhase = this.slide.getPhase(); this.removeClass("drawer-top") .addClass("drawer-right") .removeClass("drawer-bottom") .removeClass("drawer-left"); this.position.setState("fixed", Affinity.Intrinsic); this.height.setState(null, Affinity.Intrinsic); this.top.setState(Length.zero(), Affinity.Intrinsic); this.bottom.setState(Length.zero(), Affinity.Intrinsic); this.left.setState(null, Affinity.Intrinsic); let width: Length | null; if (this.width.hasAffinity(Affinity.Intrinsic)) { const collapsedWidth = this.collapsedWidth.getValue(); const expandedWidth = this.expandedWidth.getValue(); width = collapsedWidth.times(1 - stretchPhase).plus(expandedWidth.times(stretchPhase)); } else { width = this.width.value; if (width === null) { width = Length.px(this.node.offsetWidth); } } this.width.setState(width, Affinity.Intrinsic); this.right.setState(width.times(slidePhase - 1), Affinity.Intrinsic); this.effectiveWidth.setValue(width.times(slidePhase), Affinity.Intrinsic); this.effectiveHeight.setValue(this.height.value, Affinity.Intrinsic); let edgeInsets = this.edgeInsets.superValue; if ((edgeInsets === void 0 || edgeInsets === null) || edgeInsets === null) { edgeInsets = viewContext.viewport.safeArea; } this.paddingTop.setState(Length.px(edgeInsets.insetTop), Affinity.Intrinsic); this.paddingBottom.setState(Length.px(edgeInsets.insetBottom), Affinity.Intrinsic); this.edgeInsets.setValue({ insetTop: 0, insetRight: edgeInsets.insetRight, insetBottom: 0, insetLeft: 0, }, Affinity.Intrinsic); } protected layoutDrawerBottom(viewContext: ViewContextType<this>): void { const slidePhase = this.slide.getPhase(); this.removeClass("drawer-top") .removeClass("drawer-right") .addClass("drawer-bottom") .removeClass("drawer-left"); this.position.setState("fixed", Affinity.Intrinsic); this.width.setState(null, Affinity.Intrinsic); this.height.setState(null, Affinity.Intrinsic); this.left.setState(Length.zero(), Affinity.Intrinsic); this.right.setState(Length.zero(), Affinity.Intrinsic); this.top.setState(null, Affinity.Intrinsic); let height: Length | null = this.height.value; if (height === null) { height = Length.px(this.node.offsetHeight); } this.bottom.setState(height.times(slidePhase - 1), Affinity.Intrinsic); this.effectiveWidth.setValue(this.width.value, Affinity.Intrinsic); this.effectiveHeight.setValue(height.times(slidePhase), Affinity.Intrinsic); let edgeInsets = this.edgeInsets.superValue; if ((edgeInsets === void 0 || edgeInsets === null) || edgeInsets === null) { edgeInsets = viewContext.viewport.safeArea; } this.edgeInsets.setValue({ insetTop: 0, insetRight: edgeInsets.insetRight, insetBottom: 0, insetLeft: edgeInsets.insetLeft, }, Affinity.Intrinsic); if (this.stretch.collapsed) { this.expand(); } } protected layoutDrawerLeft(viewContext: ViewContextType<this>): void { const stretchPhase = this.stretch.getPhase(); const slidePhase = this.slide.getPhase(); this.removeClass("drawer-top") .removeClass("drawer-right") .removeClass("drawer-bottom") .addClass("drawer-left"); this.position.setState("fixed", Affinity.Intrinsic); this.height.setState(null, Affinity.Intrinsic); this.top.setState(Length.zero(), Affinity.Intrinsic); this.bottom.setState(Length.zero(), Affinity.Intrinsic); this.right.setState(null, Affinity.Intrinsic); let width: Length | null; if (this.width.hasAffinity(Affinity.Intrinsic)) { const collapsedWidth = this.collapsedWidth.getValue(); const expandedWidth = this.expandedWidth.getValue(); width = collapsedWidth.times(1 - stretchPhase).plus(expandedWidth.times(stretchPhase)); } else { width = this.width.value; if (width === null) { width = Length.px(this.node.offsetWidth); } } this.width.setState(width, Affinity.Intrinsic); this.left.setState(width.times(slidePhase - 1), Affinity.Intrinsic); this.effectiveWidth.setValue(width.times(slidePhase), Affinity.Intrinsic); this.effectiveHeight.setValue(this.height.value, Affinity.Intrinsic); let edgeInsets = this.edgeInsets.superValue; if ((edgeInsets === void 0 || edgeInsets === null) || edgeInsets === null) { edgeInsets = viewContext.viewport.safeArea; } this.paddingTop.setState(Length.px(edgeInsets.insetTop), Affinity.Intrinsic); this.paddingBottom.setState(Length.px(edgeInsets.insetBottom), Affinity.Intrinsic); this.edgeInsets.setValue({ insetTop: 0, insetRight: 0, insetBottom: 0, insetLeft: edgeInsets.insetLeft, }, Affinity.Intrinsic); } get modalView(): View | null { return this; } get modalState(): ModalState { return this.slide.modalState as ModalState; } readonly modality: boolean | number; showModal(options: ModalOptions, timing?: AnyTiming | boolean): void { if (options.modal !== void 0) { (this as Mutable<this>).modality = options.modal; } this.present(timing); } hideModal(timing?: AnyTiming | boolean): void { this.dismiss(timing); } present(timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } this.slide.present(timing); } dismiss(timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } this.slide.dismiss(timing); } expand(timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } this.stretch.expand(timing); } collapse(timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } this.stretch.collapse(timing); } toggle(timing?: AnyTiming | boolean): void { if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, false); } else { timing = Timing.fromAny(timing); } if (this.viewportIdiom === "mobile" || this.isHorizontal()) { if (this.slide.presented) { this.slide.dismiss(timing); } else { this.stretch.expand(timing); this.slide.present(timing); const modalService = this.modalProvider.service; if (modalService !== void 0 && modalService !== null) { modalService.presentModal(this, {modal: true}); } } } else { this.stretch.toggle(timing); this.slide.present(timing); } } override init(init: DrawerViewInit): void { super.init(init); if (init.placement !== void 0) { this.placement(init.placement); } if (init.collapsedWidth !== void 0) { this.collapsedWidth(init.collapsedWidth); } if (init.expandedWidth !== void 0) { this.expandedWidth(init.expandedWidth); } } }
the_stack
import * as tf from '@tensorflow/tfjs'; import * as tf_init from '@tensorflow/tfjs-layers/dist/initializers'; type DName = string|number|symbol; export interface DimensionData<G extends DName, D extends G> { name: D; size: number; gtensor: GTensor<G>; index: number; } interface DotError_MustPassDimensionToDot { _DotError_MustPassDimensionToDot: ['DotError_MustPassDimensionToDot'] } interface DotError_DimensionNamesMustBeEqual<D1, D2> { _DotError_DimensionNamesMustBeEqual: ['DotError_DimensionNamesMustBeEqual', D1, D2] } interface DotError_NotAllowedNameOutsideDot<OtherNames> { _DotError_NotAllowedNameOutsideDot: ['DotError_NotAllowedNameOutsideDot', OtherNames] } type DotCompatibleDimension<M1 extends DName, D1 extends M1, M2 extends DName, D2 extends M2> = D2 extends never ? DotError_MustPassDimensionToDot : D1 extends D2 ? D2 extends D1 ? Exclude<M1 & M2, D1 & D2> extends never ? Dimension<M2, D2> : DotError_NotAllowedNameOutsideDot<Exclude<M1 & M2, D2>> : DotError_DimensionNamesMustBeEqual<D2,D1> : DotError_DimensionNamesMustBeEqual<D1,D2>; // type OnlyDsInterection<D1 extends G1, D2 extends G2, G1 extends string, G2 extends string> = // // D1 = D2, lets call this D // D2 extends D1 ? D1 extends D2 ? // // G intersects G2 only at D // (Exclude<G1 & G2, D2> extends never ? Dimension<G2, D2> : ErrorGTensorsOtherIntersectionNames<Exclude<G1 & G2, D2>>) // : ErrorFirstDimFailsToExtendSecond<D1,D2> : ErrorFirstDimFailsToExtendSecond<D2,D1>; export function dot<D1 extends G1, D2 extends G2, G1 extends DName, G2 extends DName>( d1: Dimension<G1, D1>, maybed2: DotCompatibleDimension<G1,D1,G2,D2> ): GTensor<Exclude<G1|G2, D1>> { // TODO: maybe we canmake the type system do more for us... D extends D2 ? (D2 // extends D ? GTensor<Exclude<G1|G2, D>> : never) : never // // TODO: We use `tf.einsum`, and consturct the inputs for it via // strings; this is quite a bit of indirection, and likely we could use an // underlying API directly and it save string construction and parsing. // // TODO: think about if the 'never' below is needed. let d2 = maybed2 as never as Dimension<G2, D2>; const FIRST_CHAR_CODE_FOR_d1 = 'A'.charCodeAt(0); const d1Names = d1.gtensor.dimNames; const d1CharNames = d1Names.map( (n, i) => String.fromCharCode(FIRST_CHAR_CODE_FOR_d1 + i)); const d1CharName = d1CharNames[d1.index]; const FIRST_CHAR_CODE_FOR_d2 = FIRST_CHAR_CODE_FOR_d1 + d1CharNames.length; const d2Names = d2.gtensor.dimNames; const d2CharNames = d2Names.map( (n, i) => String.fromCharCode(FIRST_CHAR_CODE_FOR_d2 + i)); // const d2CharName = d1CharNames[d2.index]; d2CharNames.splice(d2.index, 1, d1CharName); if ((d2CharNames.length + d1CharNames.length) > 52) { console.warn(''); } const resultCharNames = d1CharNames.concat(d2CharNames).filter( c => c !== d1CharName); const einsumStr = `${d1CharNames.join('')},${d2CharNames.join('')}->${ resultCharNames.join('')}`; // console.log(einsumStr); const resultTensor = tf.einsum( einsumStr, d1.gtensor.tensor, d2.gtensor.tensor); const newNames = (d1Names.slice(0, d1.index) as DName[]) .concat(d1Names.slice(d1.index + 1, d1Names.length)) .concat(d2Names.slice(0, d2.index) as DName[]) .concat(d2Names.slice(d2.index + 1, d2Names.length)); return new GTensor(resultTensor, newNames as (Exclude<G1|G2, D1>)[]); } interface LiftError_DimInInput<D> { _LiftError_DimInInput: ['LiftError_DimInInput', D] } interface LiftError_DimInOutput<D> { _LiftError_DimMustBeInFnOutput: ['LiftError_DimInOutput', D] } type DimensionFnToLift<D extends DName, G extends DName, G2 extends DName> = D extends G ? LiftError_DimInInput<D> : D extends G2 ? LiftError_DimInOutput<D> : D export function liftFnOverDim<D extends DName, G extends DName, G2 extends DName>( liftDim: DimensionFnToLift<D,G,G2>, toLiftFn: (input: Dims<G>) => Dims<G2>): (input: Dims<G|D>) => Dims<G2|D> { function liftedFn(input: Dims<G|D>): Dims<G2|D> { if (!((liftDim as DName) in input)) { throw new ValueError(`The lift dimension ${liftDim } must occur in input's dimensions: ${Object.keys(input)}`); } const unstacked_dims = input[liftDim as D].unstack() as never as Dims<G>[]; return stack(liftDim as D, unstacked_dims.map(toLiftFn)); } return liftedFn; } export function liftMapFnOverDim< D extends DName, // The new dimension being lifted over. G extends DName, // The dimensions of the input. // A mapping from the name of each output of toLiftFn to the dimensions of that output. MapDim extends { [key in keyof MapDim]: MapDim[keyof MapDim] }, >( liftDim: DimensionFnToLift<D,G,MapDim[keyof MapDim]>, toLiftFn: (input: Dims<G>) => { [key in keyof MapDim]: Dims<MapDim[key]> }, ): (input: Dims<G|D>) => { [key in keyof MapDim]: Dims<MapDim[key]|D> } { function liftedFn(input: Dims<G|D>): { [key in keyof MapDim]: Dims<MapDim[key]|D> } { if (!((liftDim as string) in input)) { throw new ValueError(`The lift dimension ${liftDim} must occur in input's dimensions: ${Object.keys(input)}`); } const unstacked_dims = input[liftDim as D].unstack() as never as Dims<G>[]; const unstackedApplications = unstacked_dims.map(toLiftFn); const stackedApplications = {} as { [key in keyof MapDim]: Dims<MapDim[key]|D> }; for(const key of Object.keys(unstackedApplications[0]) as (keyof MapDim)[]) { const toStack = unstackedApplications.map(a => a[key] as Dims<MapDim[keyof MapDim]>); stackedApplications[key] = stack(liftDim as D, toStack); } return stackedApplications; } return liftedFn; } // G is the set of all names in the tensor. D is the specific name of this dimension. export class Dimension<G extends DName, D extends G> implements DimensionData<G, D> { name: D; size: number; gtensor: GTensor<G>; index: number; constructor(e: DimensionData<G, D>) { this.name = e.name; this.size = e.size; this.gtensor = e.gtensor; this.index = e.index; } get dtype(): tf.DataType { return this.gtensor.tensor.dtype; } _dot<D2 extends G2, G2 extends DName>( d2: DotCompatibleDimension<G,D,G2,D2> ): GTensor<Exclude<G | G2, D>> { return dot(this, d2); } dot<D2 extends G2, G2 extends DName>( d2: DotCompatibleDimension<G,D,G2,D2> ): Dims<Exclude<G | G2, D>> { return this._dot(d2).dim; } // softmax<D2 extends G2, G2 extends DName>( // d2: DotCompatibleDimension<G,D,G2,D2> // ): Dims<Exclude<G | G2, D>> { // tf.softmax(this.gtensor.tensor) // } _rename<T extends DName>(newName: T): GTensor<Exclude<G, D> | T> { // TODO: shouldn't TS be able to infer that typeod(this.name) extends G? It's specified in the // contrains for the class...? return this.gtensor.rename(this.name as never, newName) as GTensor<Exclude<G, D> | T>; } rename<T extends DName>(newName: T): Dims<Exclude<G, D> | T> { return this._rename(newName).dim; } _unstack(): GTensor<Exclude<G, D>>[] { const tensors = tf.unstack(this.gtensor.tensor, this.index); const newDimNames = [...this.gtensor.dimNames] as Exclude<G, D>[]; newDimNames.splice(this.index, 1); return tensors.map(t => new GTensor<Exclude<G, D>>(t, newDimNames)); } unstack(): Dims<Exclude<G, D>>[] { return this._unstack().map(g => g.dim); } // pairwise_add(d2: Dimension): GTensor; // pairwise_mult(d2: Dimension): GTensor; } export class ValueError extends Error {} // export function gtensorOfDims<G extends DName>(dims: Dims<G>): GTensor<G> { // return dims._gtensor; // } export function gtensorOfDims<G extends DName>(dims: Dims<G>): GTensor<G> { // Technically, we don't know the dimension is G... but it doesn't matter, this makes TS happy. // In theory I think `unknown` should replace the second G. const d = Object.values(dims)[0] as Dimension<G, G>; if (!d) { throw new ValueError('gtensorOfDims: empty set of dimensions'); } return d.gtensor; } // export function stackGtensors<G extends DName, NewD extends DName>( newDimName: NewD, gtensors: GTensor<G>[], ): GTensor<G|NewD> { if(gtensors.length === 0) { throw new ValueError('stackDims was empty'); } const tensors = gtensors.map(g => g.tensor); const newTensor = tf.stack(tensors); const newDimNames = [newDimName, ...gtensors[0].dimNames] return new GTensor(newTensor, newDimNames); } export function stack<G extends DName, NewD extends DName>( newDimName: NewD, stackDims: Dims<G>[], ): Dims<G|NewD> { const gtensors = stackDims.map(gtensorOfDims); return stackGtensors(newDimName, gtensors).dim; } export type Dims<G extends DName> = { [key in G]: Dimension<G, key> }; export class GTensor<G extends DName> { // TODO: the type-system fails here because we can't force dim to always have all the keys of T, // and for the key-name to match the Dimension<T>. // // The dimensions in the GTensor. dim!: Dims<G>; tensor: tf.Tensor; dimNames: G[]; constructor(tensor: tf.Tensor, dimNames: G[]) { if(tensor.shape.length !== dimNames.length) { throw new ValueError( `tensor.shape: ${tensor.shape } should be the same length as dimNames: ${dimNames}.`); } this.tensor = tensor; this.dimNames = dimNames; this._resetDim(); } gshape(): { [key in G]: number } { const gshape = {} as { [key in G]: number }; for (let i = 0; i < this.dimNames.length; i++) { gshape[this.dimNames[i]] = this.tensor.shape[i]; } return gshape; } _resetDim() { this.dim = {} as Dims<G>; for (let i = 0; i < this.dimNames.length; i++) { const dim_i = new Dimension({ name: this.dimNames[i], index: i, size: this.tensor.shape[i], gtensor: this, }); (this.dim as {[k:string]: Dimension<G, any>})[dim_i.name as string] = dim_i; } } public transpose(): GTensor<G> { return new GTensor<G>(tf.transpose(this.tensor), this.dimNames.slice().reverse()); } // Rename a set of dimensions. public renaming<ReplacedNames extends G, NewNames extends DName>( renaming: { [Key in ReplacedNames]: NewNames } // from: { [fromKey in G extends T1 ? T1 : never]: 'from' }, // to: { [toKey in T2]: 'to' }, ): GTensor<Exclude<G, ReplacedNames>|NewNames> { const newDimNames = [...this.dimNames] as never as NewNames[]; for (const key in renaming) { const index = this.dim[key].index; newDimNames[index as any] = renaming[key]; } return new GTensor<Exclude<G, ReplacedNames>|NewNames>(this.tensor, newDimNames); } // Rename a single dimension. public rename<T1 extends DName, T2 extends DName>( // { [key in G]: T2 } fromName: G extends T1 ? T1 : never, toName: T2 // from: { [fromKey in G extends T1 ? T1 : never]: 'from' }, // to: { [toKey in T2]: 'to' }, ): GTensor<Exclude<G, T1>|T2> { // const fromName = Object.keys(from)[0] as string; // T1; // const toName = Object.keys(to)[0] as ``; const i = this.dimNames.findIndex(n => (n as DName) === fromName); if (i === undefined) { throw new ValueError(`${fromName} is missing from ${this.dimNames}`); } // console.log('this.dimNames:', this.dimNames); // console.log('i:', i); // console.log('toName:', toName); const newDimNames = [...this.dimNames] as (Exclude<G, T1>|T2)[]; newDimNames.splice(i, 1, toName); // console.log('newDimNames:', newDimNames); return new GTensor<Exclude<G, T1>|T2>(this.tensor, newDimNames); } public _permuteIndexTo(i:number, new_i:number): GTensor<G> { // hack/trick to start with the identity permutation [0,1,...n]. console.log('this.dimNames', this.dimNames); const permutation = this.dimNames.map((s, i) => i); console.log('permutation', permutation); // Now swap the last and the ith index. // // TODO(ldixon): I heard that some permutations are cheeper than others, // so is there some smart way to do an optimal permutation? const lastIndex = new_i; permutation[i] = lastIndex; permutation[lastIndex] = i; const oldLastName = this.dimNames[lastIndex]; const newLastName = this.dimNames[i]; const newDimNames = this.dimNames.slice(); newDimNames[lastIndex] = newLastName; newDimNames[i] = oldLastName; console.log('newDimNames', newDimNames); return new GTensor<G>(tf.transpose(this.tensor, permutation), newDimNames); } _permuteIndexToLast(i:number): GTensor<G> { return this._permuteIndexTo(i, this.dimNames.length - 1); } _permuteIndexToSecondLast(i:number): GTensor<G> { return this._permuteIndexTo(i, this.dimNames.length - 2); } public permuteDimNameToLast(name: G): GTensor<G> { return this._permuteIndexToLast(this.dim[name].index); } } export interface InitializerConfig { // Only one of these should be specified. tuncNormal?: tf_init.TruncatedNormalArgs; zeros?: {}; ones?: {}; constant?: tf_init.ConstantArgs; } export function makeInitializer(config: InitializerConfig) { if (config.tuncNormal) { return tf.initializers.truncatedNormal(config.tuncNormal); } else if (config.zeros) { return tf.initializers.zeros(); } else if (config.ones) { return tf.initializers.ones(); } else if (config.constant) { return tf.initializers.constant(config.constant); } throw new ValueError('need to specify an initalizer config'); } export function fromInitializer<T extends string>( dims: { [key in T]: number }, initialiser: tf_init.Initializer, dtype?: tf.DataType) { const dimNames = Object.keys(dims) as T[]; const shape = dimNames.map((n: T) => dims[n]); return new GTensor(initialiser.apply(shape, dtype), dimNames); } export function makeTruncNormal<T extends string>(dims: { [key in T]: number }, truncNormalConfig?: tf_init.TruncatedNormalArgs, dtype?: tf.DataType) { return fromInitializer( dims, tf.initializers.truncatedNormal(truncNormalConfig || {}), dtype); } export function makeZeros<T extends string>(dims: { [key in T]: number }, dtype?: tf.DataType) { return fromInitializer(dims, tf.initializers.zeros(), dtype); } export function makeOnes<T extends string>(dims: { [key in T]: number }, dtype?: tf.DataType) { return fromInitializer(dims, tf.initializers.ones(), dtype); } export function makeConstant<T extends string>(dims: { [key in T]: number }, constant: number, dtype?: tf.DataType) { return fromInitializer(dims, tf.initializers.constant({value: constant}), dtype); }
the_stack
import { Day } from './Day'; import { DaySpan } from './DaySpan'; import { Functions as fn } from './Functions'; import { Locales } from './Locale'; // tslint:disable: no-magic-numbers /** * The type for identifiers. Most of the time an identifier can be stored as a * number because the 4 digit year is first. However when the year is below * 1000 a string will be used with zero padding. Storing identifiers as numbers * enable very quick comparisons and using strings or numbers allows the * identifier to be used as a key to a map. */ export type IdentifierInput = number | string; /** * The possible properties which can be pulled from an identifier. */ export interface IdentifierObject { /** * The year pulled from an identifier (0-9999). */ year?: number; /** * The quarter of the year pulled from an identifier (1-4) */ quarter?: number; /** * The month of the year pulled from an identifier (0-11) */ month?: number; /** * The week of the year pulled from an identifier (1-52) */ week?: number; /** * The day of the month pulled from an identifier (1-31) */ day?: number; /** * The hour of the day pulled from an identifier (0-23) */ hour?: number; /** * The minute of the hour pulled from an identifier (0-59) */ minute?: number; } /** * A class for detecting, parsing, and building identifiers to and from days. * * An identifier is a simple value which represents a span of time. It may * represent an entire year, a quarter (3 months) of a year, a week of a year, * a month in a year, a specific day of a month of a year, or a specific hour, * minute, day, and month of a year. * * For example: * - `2018`: The year 2018 * - `201801`: January 2018 * - `2014023`: The 23rd week of 2014 * - `20170311`: March 11th, 2017 * - `201406151651`: June 15th 2016 at 4:51 pm * - `'0525'`: Year 525 of the first age, Elrond and Elros are born */ export abstract class Identifier { /** * Determines whether the given identifier is this type. * * @param id The identifier to test. * @returns `true` if the identifier is this type, otherwise `false`. */ public is(id: IdentifierInput): boolean { return (id + '').length === this.getLength(); } /** * Returns the identifier of this type for the given day, * * @param day The day to get the identifier of. * @returns The identifier for the day of this type. */ abstract get(day: Day): IdentifierInput; /** * Converts the given identifier which has passed [[Identifier.is]] to an * object with properties pulled from the identifier. * * @param id The identifier to parse. * @returns The object with properties parsed from the identifer. */ abstract object(id: IdentifierInput): IdentifierObject; /** * Returns the start of the time span the identifier represents. * * @param id The identifier to convert to a start day. * @returns The start of the time span the identifier represents. */ abstract start(id: IdentifierInput): Day; /** * Returns the span of time the identifier represents. * * @param id The identifier to convert to a span. * @param endInclusive When `true` the end of the span will be the very last * millisecond that represents the timespan, otherwise `false` the end * will be the start of the very next span. * @returns */ abstract span(id: IdentifierInput, endInclusive: boolean): DaySpan; /** * Determines if the day matches the given identifier. * * @param day The day to test. * @param id The identifier to compare to. * @returns `true` if the day exists in the time span represented by the * identifier, otherwise `false`. */ abstract matches(day: Day, id: IdentifierInput): boolean; /** * Describes the given identifier as a human friendly string. * * @param id The identifier to describe. * @param short If the description should use shorter language or longer. * @returns The human friendly string that describes the identifier. */ abstract describe(id: IdentifierInput, short: boolean): string; /** * The scales for all the different values stored in an identifier. */ protected abstract getScales(): number[]; /** * The length of the identifier of this type in digits. */ protected abstract getLength(): number; /** * Computes the identifier given values taken from a [[Day]]. * * @param values The values to compute. * @returns The computed identifier. */ protected compute(...values: number[]): IdentifierInput { const scales: number[] = this.getScales(); let total: number = 0; for (let i = 0; i < values.length; i++) { total += values[ i ] * scales[ i ]; } return this.is( total ) ? total : fn.padNumber(total, this.getLength()); } /** * Decomputes the given identifier and returns values which describe a span * of time. * * @param id The identifier to decompute. * @returns The original values which computed the identifier. */ protected decompute(id: IdentifierInput): number[] { const scales: number[] = this.getScales(); let total: number = fn.isNumber(id) ? id : parseInt(id); const values: number[] = []; for (let i = 0; i < scales.length - 1; i++) { const curr: number = scales[ i + 0 ]; const next: number = scales[ i + 1 ]; const mod: number = next / curr; const value: number = total % mod; values.push( value ); total = Math.floor( total / mod ); } values.push( total ); return values; } /** * The identifier type for an hour of time on a specific day. */ public static Time: Identifier = null; /** * The identifier type for a specific day. */ public static Day: Identifier = null; /** * The identifier type for a specific week of a year. */ public static Week: Identifier = null; /** * The identifier type for a specific month of a year. */ public static Month: Identifier = null; /** * The identifier type for a specific quarter of a year. */ public static Quarter: Identifier = null; /** * The identifier type for a specific year. */ public static Year: Identifier = null; /** * Finds which identifier type matches the given identifier, if any. * * @param id The identifier to find the type of. * @returns The found identifier type, otherwise `null` if none exists. */ public static find(id: IdentifierInput): Identifier { if (this.Time.is(id)) return this.Time; if (this.Day.is(id)) return this.Day; if (this.Week.is(id)) return this.Week; if (this.Month.is(id)) return this.Month; if (this.Year.is(id)) return this.Year; return null; } /** * Determines whether the given time span `outer` contains the time span * `inner`. * * @param outer The potentially larger time span `inner` must be contained in. * @param inner The time span to test is contained inside `outer`. * @returns `true` if `inner` is equal to or contained in `outer`, otherwise * `false`. */ public static contains(outer: IdentifierInput, inner: IdentifierInput): boolean { const outerString: string = outer + ''; return (inner + '').substring( 0, outerString.length ) === outerString; } } // YYYYMMddHHmm (12) class IdentifierTime extends Identifier { private static SCALES: number[] = [ 1 /* minute */, 100 /* hour */, 10000 /* day */, 1000000 /* month */, 100000000 /* year */]; private static LENGTH: number = 12; protected getScales(): number[] { return IdentifierTime.SCALES; } protected getLength(): number { return IdentifierTime.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.minute, day.hour, day.dayOfMonth, day.month + 1, day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { minute: values[0], hour: values[1], day: values[2], month: values[3] - 1, year: values[4] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, obj.month, obj.day, obj.hour, obj.minute ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.endOf( 'hour', endInclusive ); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierTime(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.timeIdentifier === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year && day.month === obj.month && day.dayOfMonth === obj.day && day.hour === obj.hour && day.minute === obj.minute ); */ } } // YYYYMMdd (8) class IdentifierDay extends Identifier { private static SCALES: number[] = [ 1 /* day */, 100 /* month */, 10000 /* year */]; private static LENGTH: number = 8; protected getScales(): number[] { return IdentifierDay.SCALES; } protected getLength(): number { return IdentifierDay.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.dayOfMonth, day.month + 1, day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { day: values[0], month: values[1] - 1, year: values[2] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, obj.month, obj.day ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.endOf( 'day', endInclusive ); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierDay(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.dayIdentifier === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year && day.month === obj.month && day.dayOfMonth === obj.day ); */ } } // YYYY0ww (7) class IdentifierWeek extends Identifier { private static SCALES: number[] = [ 1 /* week */, 1000 /* year */]; private static LENGTH: number = 7; protected getScales(): number[] { return IdentifierWeek.SCALES; } protected getLength(): number { return IdentifierWeek.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.weekOfYear, day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { week: values[0], year: values[1] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, 0 ).withWeekOfYear( obj.week ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.endOf( 'week', endInclusive ); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierWeek(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.weekIdentifier === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year && day.week === obj.week ); */ } } // YYYYMM (6) class IdentifierMonth extends Identifier { private static SCALES: number[] = [ 1 /* month */, 100 /* year */]; private static LENGTH: number = 6; protected getScales(): number[] { return IdentifierMonth.SCALES; } protected getLength(): number { return IdentifierMonth.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.month + 1, day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { month: values[0] - 1, year: values[1] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, obj.month ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.endOf( 'month', endInclusive ); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierMonth(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.monthIdentifier === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year && day.month === obj.month ); */ } } // YYYYQ (5) class IdentifierQuarter extends Identifier { private static SCALES: number[] = [ 1 /* quarter */, 10 /* year */]; private static LENGTH: number = 5; protected getScales(): number[] { return IdentifierQuarter.SCALES; } protected getLength(): number { return IdentifierQuarter.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.quarter, day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { quarter: values[0], year: values[1] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, (obj.quarter - 1) * 3 ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.add('month', 3).endOf('month', endInclusive); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierQuarter(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.quarterIdentifier === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year && day.quarter === obj.quarter ); */ } } // YYYY (4) class IdentifierYear extends Identifier { private static SCALES: number[] = [ 1 /* year */]; private static LENGTH: number = 4; protected getScales(): number[] { return IdentifierYear.SCALES; } protected getLength(): number { return IdentifierYear.LENGTH; } public get(day: Day): IdentifierInput { return this.compute(day.year); } public object(id: IdentifierInput): IdentifierObject { const values: number[] = this.decompute(id); return { year: values[0] }; } public start(id: IdentifierInput): Day { const obj: IdentifierObject = this.object(id); const start: Day = Day.build( obj.year, 0 ); return start; } public span(id: IdentifierInput, endInclusive: boolean = false): DaySpan { const start: Day = this.start( id ); const end: Day = start.endOf( 'year', endInclusive ); return new DaySpan(start, end); } public describe(id: IdentifierInput, short: boolean = false): string { const start: Day = this.start( id ); const format: string = Locales.current.identifierYear(short); return start.format( format ); } public matches(day: Day, id: IdentifierInput): boolean { return day.year === id; /* let obj: IdentifierObject = this.object(id); return ( day.year === obj.year ); */ } } // Sets the Identifier types Identifier.Time = new IdentifierTime(); Identifier.Day = new IdentifierDay(); Identifier.Week = new IdentifierWeek(); Identifier.Month = new IdentifierMonth(); Identifier.Quarter = new IdentifierQuarter(); Identifier.Year = new IdentifierYear();
the_stack
import { join } from "path"; import { Nullable, Undefinable } from "../../../shared/types"; import * as React from "react"; import { Position, ButtonGroup, Popover, Menu, MenuItem, Divider, Tag, Tooltip, Pre, AnchorButton, ProgressBar } from "@blueprintjs/core"; import { Node, TargetCamera, Vector3, Animation, Light, Mesh, Camera, InstancedMesh, IParticleSystem, ParticleSystem, AbstractMesh, Sound, Observable, } from "babylonjs"; import { Editor } from "../editor"; import { ScenePicker } from "../scene/picker"; import { SceneGizmo, GizmoType } from "../scene/gizmo"; import { SceneSettings } from "../scene/settings"; import { Tools } from "../tools/tools"; import { Icon } from "../gui/icon"; import { Alert } from "../gui/alert"; import { Omnibar, IOmnibarItem } from "../gui/omni-bar"; import { WorkSpace } from "../project/workspace"; import { ProjectExporter } from "../project/project-exporter"; import { ScenePlayer } from "../../play/inline-play"; export interface IPreviewProps { /** * The editor reference. */ editor: Editor; } export interface IPreviewState { /** * Wether or not the canvas is focused or not. */ canvasFocused: boolean; /** * The name of the node which is under the pointer. */ overNodeName: string; /** * The current type of gizmo used in the preview. */ gizmoType: GizmoType; /** * Defines the current used while using the gizmos. */ gizmoStep: number; /** * Defines the list of all available gizmo steps. */ availableGizmoSteps: number[]; /** * Defines wether or not force wireframe is enabled or not. */ forceWireframe: boolean; /** * Defines wether or not the icons should be drawn. */ showIcons: boolean; /** * Defines wether or not the preview is in isolated mode. */ isIsolatedMode: boolean; /** * Defines wether or not the user is playing the scene. */ isPlaying: boolean; /** * Defines wether or not the user is playing the scene in a dedicated iframe. */ isPlayingInIframe: boolean; /** * Defines the current play loading progress. */ playLoadingProgress: number; } export enum PreviewCanvasEventType { /** * Defines the event raised when the preview canvas is focused. */ Focused = 0, /** * Defines the vent raised when the preview canvas is blurred. */ Blurred, } export class Preview extends React.Component<IPreviewProps, IPreviewState> { /** * Defines the scene picker used to get/pick infos from the scene. */ public picker: ScenePicker; /** * Defines the scene gizmo manager. */ public gizmo: SceneGizmo; /** * Notifies observers that an event happened on the canvas. */ public onCanvasEventObservable: Observable<PreviewCanvasEventType> = new Observable<PreviewCanvasEventType>(); private _editor: Editor; private _copiedNode: Nullable<Node | IParticleSystem> = null; private _scenePlayer: ScenePlayer; private _isolatedObject: Nullable<AbstractMesh | IParticleSystem> = null; private _cameraPositionBeforeIsolation: Nullable<Vector3> = null; private _cameraTargetBeforeIsolation: Nullable<Vector3> = null; private _isolationBaseMeshesArray: Nullable<AbstractMesh[]> = null; private _searchBar: Omnibar; private _playIframe: HTMLIFrameElement; private _refHandler = { getSearchBar: (ref: Omnibar) => this._searchBar = ref, getPlayIframe: (ref: HTMLIFrameElement) => this._playIframe = ref, }; private _playMessageEventListener: Nullable<(ev: MessageEvent) => void> = null; /** * Constructor. * @param props the component's props. */ public constructor(props: IPreviewProps) { super(props); this._editor = props.editor; this._editor.preview = this; this._editor.editorInitializedObservable.addOnce(() => this._createPicker()); this._scenePlayer = new ScenePlayer(this._editor); this.state = { canvasFocused: false, overNodeName: "", gizmoType: GizmoType.None, gizmoStep: 0, availableGizmoSteps: [0, 1, 2, 5, 10], forceWireframe: false, showIcons: true, isIsolatedMode: false, isPlaying: false, isPlayingInIframe: false, playLoadingProgress: 1, }; } /** * Renders the component. */ public render(): React.ReactNode { const cameras = ( <Menu> {this._editor.scene?.cameras.map((c) => ( <MenuItem key={c.id} id={c.id} text={c.name} icon={<Icon src="camera.svg" />} onClick={() => SceneSettings.SetActiveCamera(this._editor, c)} /> ))} </Menu> ); const isNone = this.state.gizmoType === GizmoType.None; const isPosition = this.state.gizmoType === GizmoType.Position; const isRotation = this.state.gizmoType === GizmoType.Rotation; const isScaling = this.state.gizmoType === GizmoType.Scaling; const steps = ( <Menu> {this.state.availableGizmoSteps.map((s) => ( <MenuItem key={s.toString()} text={s.toString()} icon={this._getCheckedIcon(this.state.gizmoStep === s)} onClick={() => this.setGizmoStep(s)} /> ))} </Menu> ); const isolatedMode = this.state.isIsolatedMode ? ( <Pre style={{ position: "absolute", top: "30px", left: "10px" }}> Focusing On: {this._isolatedObject?.name} </Pre> ) : undefined; const displayPlayIframe = this.state.isPlaying && this.state.isPlayingInIframe; const playIframe = displayPlayIframe ? ( <iframe src="./play.html" key={Tools.RandomId()} ref={this._refHandler.getPlayIframe} onLoad={(ev) => this._handlePlay(ev.nativeEvent.target as HTMLIFrameElement)} style={{ width: "100%", height: "100%", position: "unset", top: "0", touchAction: "none", border: "none" }} ></iframe> ) : undefined; const loadingProgress = this.state.isPlaying && !this.state.isPlayingInIframe && this.state.playLoadingProgress < 1 ? ( <ProgressBar animate value={this.state.playLoadingProgress * 100} /> ) : undefined; return ( <> <div id="preview-toolbar" style={{ width: "100%", height: "25px" }}> <ButtonGroup key="preview-buttons" large={false} style={{ height: "20px", marginTop: "auto", marginBottom: "auto" }}> <Popover key="cameras-popover" content={cameras} position={Position.BOTTOM_LEFT}> <AnchorButton key="cameras-button" small={true} icon={<Icon src="camera.svg" />} rightIcon="caret-down" text="Cameras" /> </Popover> <Divider /> <Tooltip content="Hide Gizmo" position={Position.BOTTOM}> <AnchorButton key="gizmo-none" small={true} active={isNone} disabled={isNone} text="None" onClick={() => this.setGizmoType(GizmoType.None)} /> </Tooltip> <Tooltip content="Position" position={Position.BOTTOM}> <AnchorButton key="gizmo-position" small={true} active={isPosition} disabled={isPosition} icon={<Icon src="arrows-alt.svg" />} onClick={() => this.setGizmoType(GizmoType.Position)} /> </Tooltip> <Tooltip content="Rotation" position={Position.BOTTOM}> <AnchorButton key="gizmo-rotation" small={true} active={isRotation} disabled={isRotation} icon={<Icon src="crosshairs.svg" />} onClick={() => this.setGizmoType(GizmoType.Rotation)} /> </Tooltip> <Tooltip content="Scaling" position={Position.BOTTOM}> <AnchorButton key="gizmo-scaling" small={true} active={isScaling} disabled={isScaling} icon={<Icon src="arrows-alt-v.svg" />} onClick={() => this.setGizmoType(GizmoType.Scaling)} /> </Tooltip> <Popover content={steps} position={Position.BOTTOM_LEFT}> <AnchorButton key="step1" small={true} rightIcon="caret-down" text={`Steps (${this.state.gizmoStep})`} /> </Popover> <Divider /> <Tooltip content="Wireframe" position={Position.BOTTOM}> <AnchorButton key="wireframe" small={true} icon={<Icon src="grip-lines.svg" style={{ opacity: (this.state.forceWireframe ? 1 : 0.5) }} />} onClick={() => this.toggleWireframe()} /> </Tooltip> <Tooltip content="Show Icons" position={Position.BOTTOM}> <AnchorButton key="icons" small={true} icon={<Icon src="eye.svg" style={{ opacity: (this.state.showIcons ? 1 : 0.5) }} />} onClick={() => this.toggleShowIcons()} /> </Tooltip> </ButtonGroup> </div> <div style={{ height: "calc(100% - 25px)" }}> <canvas id="renderCanvas" style={{ width: "100%", height: "100%", position: "unset", top: "0", touchAction: "none", display: displayPlayIframe ? "none" : "block" }}></canvas> {playIframe} {isolatedMode} <Tag key="preview-tag" round={true} large={true} style={{ visibility: (this.state.canvasFocused && !this.state.isPlaying ? "visible" : "hidden"), position: "absolute", left: "50%", top: "calc(100% - 15px)", transform: "translate(-50%, -50%)" }} >{this.state.overNodeName}</Tag> <Omnibar ref={this._refHandler.getSearchBar} onChange={(i) => this._handleSearchBarChanged(i)} /> <div style={{ position: "absolute", top: "50%", left: "25%", width: "50%" }}> {loadingProgress} </div> </div> </> ); } /** * Called on the user wants to play or stop the scene. * @param isPlayingInIframe defines wether or not the game is played in an isolated context using an iFrame. */ public async playOrStop(isPlayingInIframe: boolean): Promise<void> { const isPlaying = !this.state.isPlaying; if (isPlaying) { await this.startPlayScene(isPlayingInIframe); } else { await this.stopPlayingScene(isPlayingInIframe); } } /** * Starts playing the scene in the editor. * @param isPlayingInIframe defines wether or not the game is played in an isolated context using an iFrame. * @throws */ public async startPlayScene(isPlayingInIframe: boolean): Promise<void> { this._editor.runRenderLoop(false); if (!isPlayingInIframe) { this.setState({ isPlaying: true, isPlayingInIframe, playLoadingProgress: 0.5 }); } await ProjectExporter.ExportFinalScene(this._editor, undefined, { geometryRootPath: this.state.isPlayingInIframe ? undefined : join("../../scenes", WorkSpace.GetProjectName(), "/"), }); if (isPlayingInIframe) { return this.setState({ isPlaying: true, isPlayingInIframe }); } this._editor.engine!.loadingScreen = { displayLoadingUI: () => { }, hideLoadingUI: () => { }, loadingUIText: "", loadingUIBackgroundColor: "", } try { await this._scenePlayer.start((p) => this.setState({ playLoadingProgress: p })); } catch (e) { await this.stopPlayingScene(isPlayingInIframe); this._editor.console.logSection("Failed to start playing scene"); this._editor.console.logError(`An error happened: ${e.message}`); throw e; } } /** * Stops the game that is runnning in the editor. * @param isPlayingInIframe defines wether or not the game is played in an isolated context using an iFrame. */ public async stopPlayingScene(isPlayingInIframe: boolean): Promise<void> { if (!this.state.isPlaying) { return; } if (this._playMessageEventListener) { window.removeEventListener("message", this._playMessageEventListener); } this._playMessageEventListener = null; if (!isPlayingInIframe) { this._scenePlayer.dispose(); } this.setState({ isPlaying: false, playLoadingProgress: 1 }); this._editor.runRenderLoop(true); } /** * In case the user is playing the test scene, it restarts the iframe. */ public async restartPlay(): Promise<void> { if (this._playIframe) { this._playIframe.src = this._playIframe.src; } else { try { this._scenePlayer.dispose(); await this._scenePlayer.start((p) => this.setState({ playLoadingProgress: p })); } catch (e) { this._editor.console.logError(`Failed to restart: ${e.message}`); } } } /** * Toggles the isolated mode. */ public toggleIsolatedMode(object: Nullable<AbstractMesh | IParticleSystem> = null): void { const scene = this._editor.scene!; const camera = scene.activeCamera; if (!camera) { return; } if (this.state.isIsolatedMode) { scene.meshes = this._isolationBaseMeshesArray!.concat(scene.meshes.filter((m) => this._isolationBaseMeshesArray?.indexOf(m) === -1)); this._isolatedObject = null; this._restoreCameraPositionBeforeIsolation(camera); this.setState({ isIsolatedMode: false }); } else { if (!object) { object = this._editor.graph.lastSelectedObject as any; } if (!object || (!(object instanceof AbstractMesh) && !(object instanceof ParticleSystem))) { return; } this._isolatedObject = object; if (object instanceof AbstractMesh) { this._isolationBaseMeshesArray = scene.meshes; scene.meshes = [object]; } this._cameraPositionBeforeIsolation = camera.position.clone(); if (camera instanceof TargetCamera) { this._cameraTargetBeforeIsolation = camera.target.clone(); } this._editor.inspector.setSelectedObject(object); this._focusNode(object, false, camera); this.setState({ isIsolatedMode: true }); } } /** * Sets the new gizmo type to be used in the preview. * If the given gizmo type is the same as the current, it just sets the current type as "None". * @param gizmoType the new type of gizmo to be used in the preview. */ public setGizmoType(gizmoType: GizmoType): void { if (this.state.gizmoType === gizmoType) { gizmoType = GizmoType.None; } this.gizmo.gizmoType = gizmoType; this.setState({ gizmoType }); } /** * Sets the current step used while using the gizmos. * @param gizmoStep the new step to use when using the current gizmo. */ public setGizmoStep(gizmoStep: number): void { this.gizmo.gizmoStep = gizmoStep; this.setState({ gizmoStep }); } /** * Toggles the force wireframe boolean for the current scene. */ public toggleWireframe(): void { this._editor.scene!.forceWireframe = !this._editor.scene!.forceWireframe; this.setState({ forceWireframe: this._editor.scene!.forceWireframe }); } /** * Togglets the scene icons for the current scene. */ public toggleShowIcons(): void { this.picker.icons.enabled = !this.picker.icons.enabled; this.setState({ showIcons: this.picker.icons.enabled }); } /** * Returns wether or not the canvas is focused. */ public get canvasFocused(): boolean { return this.state.canvasFocused; } /** * Shows the search bar. */ public showSearchBar(): void { this._searchBar.show([ { id: "__editor__separator__", name: "Scene Nodes" } ].concat(this._editor.sceneUtils.getAllNodes()).concat([ { id: "__editor__separator__", name: "Commands" }, { id: "__command__build__project__", name: "Build Project..." }, { id: "__command__generate_scene__", name: "Generate Scene..." }, ])); } /** * Focuses the currently selected node. * @param onlyCameraTarget defines wether or not only camera's target should focus (no position animation). */ public focusSelectedNode(onlyCameraTarget: boolean): void { this._focusNode(this._editor.graph.lastSelectedObject, onlyCameraTarget); } /** * Focuses the given node. * @param node defines the reference to the node to focus. * @param onlyCameraTarget defines wether or not only camera's target should focus (no position animation). */ public focusNode(node: Node | IParticleSystem | Sound, onlyCameraTarget: boolean): void { this._focusNode(node, onlyCameraTarget); } /** * Copies the currently selected node. */ public copySelectedNode(): void { const object = this._editor.graph.lastSelectedObject; if (!(object instanceof Sound)) { this._copiedNode = object; } } /** * Pastes the latest copied node. */ public pasteCopiedNode(): void { if (!this._copiedNode) { return; } let clone: Nullable<Node | IParticleSystem> = null; if (this._copiedNode instanceof Light) { clone = this._copiedNode.clone(this._copiedNode.name); } else if (this._copiedNode instanceof Camera) { clone = this._copiedNode.clone(this._copiedNode.name); } else if (this._copiedNode instanceof Mesh) { if (this._copiedNode.hasThinInstances) { Alert.Show("Can't create mesh instance", "The mesh to paste contains Thin Instances. Please use Thin Instances painting tool instead to create copies."); return; } const instance = clone = this._copiedNode.createInstance(`${this._copiedNode.name} (Mesh Instance)`); instance.position.copyFrom(this._copiedNode.position); instance.rotation.copyFrom(this._copiedNode.rotation); if (this._copiedNode.rotationQuaternion) { instance.rotationQuaternion = this._copiedNode.rotationQuaternion.clone(); } instance.scaling.copyFrom(this._copiedNode.scaling); instance.checkCollisions = this._copiedNode.checkCollisions; } else if (this._copiedNode instanceof InstancedMesh) { const instance = clone = this._copiedNode.sourceMesh.createInstance(`${this._copiedNode.sourceMesh.name} (Mesh Instance)`); instance.position.copyFrom(this._copiedNode.position); instance.rotation.copyFrom(this._copiedNode.rotation); if (this._copiedNode.rotationQuaternion) { instance.rotationQuaternion = this._copiedNode.rotationQuaternion.clone(); } instance.scaling.copyFrom(this._copiedNode.scaling); instance.checkCollisions = this._copiedNode.checkCollisions; } else if (this._copiedNode instanceof ParticleSystem) { clone = this._copiedNode.clone(this._copiedNode.name, this._copiedNode.emitter); } if (clone) { if (clone instanceof Node && this._copiedNode instanceof Node) { clone.parent = this._copiedNode.parent; } if (this._copiedNode instanceof AbstractMesh) { const collider = this._copiedNode.getChildMeshes(true).find((m) => m.metadata?.collider); if (collider) { let colliderInstance: Nullable<AbstractMesh> = null; if (collider instanceof Mesh) { colliderInstance = collider.createInstance(`${collider.name} (Mesh Instance)`); } else if (collider instanceof InstancedMesh) { colliderInstance = collider.sourceMesh.createInstance(collider.name); } if (colliderInstance && clone instanceof Node) { colliderInstance.parent = clone; colliderInstance.checkCollisions = collider.checkCollisions; colliderInstance.metadata = { collider: Tools.CloneObject(collider.metadata.collider), }; colliderInstance.id = Tools.RandomId(); } } } clone.id = Tools.RandomId(); if (clone instanceof Node) { this._editor.addedNodeObservable.notifyObservers(clone); } else { this._editor.addedParticleSystemObservable.notifyObservers(clone); } this._editor.graph.refresh(() => { if (clone instanceof Node) { this._editor.selectedNodeObservable.notifyObservers(clone); } else { this._editor.selectedParticleSystemObservable.notifyObservers(clone!); } }); } } /** * Removes the currently selected node. */ public removeSelectedNode(): void { const node = this._editor.graph.lastSelectedObject; if (!node) { return; } this._editor.graph.removeObject(node); } /** * Returns the check icon if the given "checked" property is true. */ private _getCheckedIcon(checked: Undefinable<boolean>): Undefinable<JSX.Element> { return checked ? <Icon src="check.svg" /> : undefined; } /** * Creates the scene picker. */ private _createPicker(): void { this.picker = new ScenePicker(this._editor); this.picker.onNodeOver.add((n) => { this.setState({ overNodeName: n.name }); }); this.gizmo = new SceneGizmo(this._editor); this._bindEvents(); } /** * Focuses on the given node. */ private _focusNode(node: Nullable<Node | IParticleSystem | Sound>, onlyCameraTarget: boolean, camera?: Nullable<Camera>): void { if (!node) { return; } if (node instanceof ParticleSystem) { node = node.emitter as AbstractMesh; } if (node instanceof Sound) { node = node["_connectedTransformNode"]; } if (!node) { return; } if (!camera) { camera = this._editor.scene!.activeCamera; } if (!camera || !(camera instanceof TargetCamera)) { return; } this._editor.scene!.stopAnimation(camera); let translation = Vector3.Zero(); const scaling = Vector3.Zero(); (node as Node).getWorldMatrix().decompose(scaling, undefined, translation); if (node instanceof AbstractMesh) { node.refreshBoundingInfo(true); translation = node.getBoundingInfo()?.boundingBox?.centerWorld?.clone() ?? translation; } if (camera["target"]) { const a = new Animation("FocusTargetAnimation", "target", 60, Animation.ANIMATIONTYPE_VECTOR3); a.setKeys([{ frame: 0, value: camera.getTarget() }, { frame: 60, value: translation }]); this._editor.scene!.beginDirectAnimation(camera, [a], 0, 60, false, 3); } else { camera.setTarget(translation); } if (!onlyCameraTarget && node instanceof AbstractMesh && node._boundingInfo) { const distance = Vector3.Distance( node._boundingInfo.minimum.multiply(scaling), node._boundingInfo.maximum.multiply(scaling), ); const a = new Animation("FocusPositionAnimation", "position", 60, Animation.ANIMATIONTYPE_VECTOR3); a.setKeys([{ frame: 0, value: camera.position.clone() }, { frame: 60, value: translation.add(new Vector3(distance, distance, distance)) }]); this._editor.scene!.beginDirectAnimation(camera, [a], 0, 60, false, 3); } } /** * Restores the camera's position before the isolation. */ private _restoreCameraPositionBeforeIsolation(camera: Camera): void { if (!this._cameraPositionBeforeIsolation) { return; } const positionAnimation = new Animation("RestorePositionAnimation", "position", 60, Animation.ANIMATIONTYPE_VECTOR3); positionAnimation.setKeys([{ frame: 0, value: camera.position.clone() }, { frame: 60, value: this._cameraPositionBeforeIsolation.clone() }]); this._cameraPositionBeforeIsolation = null; const animations = [positionAnimation]; if (camera instanceof TargetCamera && this._cameraTargetBeforeIsolation) { const targetAnimation = new Animation("RestoreTargetAnimation", "target", 60, Animation.ANIMATIONTYPE_VECTOR3); targetAnimation.setKeys([{ frame: 0, value: camera.getTarget() }, { frame: 60, value: this._cameraTargetBeforeIsolation.clone() }]); animations.push(targetAnimation); this._cameraTargetBeforeIsolation = null; } this._editor.scene!.beginDirectAnimation(camera, animations, 0, 60, false, 3); } /** * Called on the user selects an item in the searchbar */ private async _handleSearchBarChanged(item: Nullable<IOmnibarItem>): Promise<void> { if (!item) { return; } switch (item.id) { case "__command__build__project__": return WorkSpace.BuildProject(this._editor); case "__command__generate_scene__": return ProjectExporter.ExportFinalScene(this._editor); } const node = this._editor.scene!.getNodeByID(item.id); if (!node) { return; } // this._focusNode(node, false); this._editor.selectedNodeObservable.notifyObservers(node); } /** * Called on the play iframe has been loaded. */ private _handlePlay(ref: HTMLIFrameElement): void { ref.contentWindow?.postMessage({ id: "init", workspaceDir: WorkSpace.DirPath!, projectName: WorkSpace.GetProjectName(), physicsEngine: WorkSpace.Workspace!.physicsEngine, }, undefined!); window.addEventListener("message", this._playMessageEventListener = (ev) => { if (ev.data?.error) { this._editor.notifyMessage(ev.data.error, 5000, "notifications", "danger"); window.removeEventListener("message", this._playMessageEventListener!); this._playMessageEventListener = null; } }); } /** * Binds the events. */ private _bindEvents(): void { const canvas = this._editor.engine!.getRenderingCanvas(); if (!canvas) { return; } canvas.addEventListener("mouseenter", () => { this.setState({ canvasFocused: true }); this.onCanvasEventObservable.notifyObservers(PreviewCanvasEventType.Focused); }); canvas.addEventListener("mouseleave", () => { this.setState({ canvasFocused: false }); this.picker?.canvasBlur(); this.onCanvasEventObservable.notifyObservers(PreviewCanvasEventType.Blurred); }); } }
the_stack
import { MultipleResponsesGet200Model204NoModelDefaultError200ValidOptionalParams, MultipleResponsesGet200Model204NoModelDefaultError200ValidResponse, MultipleResponsesGet200Model204NoModelDefaultError204ValidOptionalParams, MultipleResponsesGet200Model204NoModelDefaultError204ValidResponse, MultipleResponsesGet200Model204NoModelDefaultError201InvalidOptionalParams, MultipleResponsesGet200Model204NoModelDefaultError201InvalidResponse, MultipleResponsesGet200Model204NoModelDefaultError202NoneOptionalParams, MultipleResponsesGet200Model204NoModelDefaultError202NoneResponse, MultipleResponsesGet200Model204NoModelDefaultError400ValidOptionalParams, MultipleResponsesGet200Model204NoModelDefaultError400ValidResponse, MultipleResponsesGet200Model201ModelDefaultError200ValidOptionalParams, MultipleResponsesGet200Model201ModelDefaultError200ValidResponse, MultipleResponsesGet200Model201ModelDefaultError201ValidOptionalParams, MultipleResponsesGet200Model201ModelDefaultError201ValidResponse, MultipleResponsesGet200Model201ModelDefaultError400ValidOptionalParams, MultipleResponsesGet200Model201ModelDefaultError400ValidResponse, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidOptionalParams, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidResponse, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidOptionalParams, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidResponse, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidOptionalParams, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidResponse, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidOptionalParams, MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidResponse, MultipleResponsesGet202None204NoneDefaultError202NoneOptionalParams, MultipleResponsesGet202None204NoneDefaultError204NoneOptionalParams, MultipleResponsesGet202None204NoneDefaultError400ValidOptionalParams, MultipleResponsesGet202None204NoneDefaultNone202InvalidOptionalParams, MultipleResponsesGet202None204NoneDefaultNone204NoneOptionalParams, MultipleResponsesGet202None204NoneDefaultNone400NoneOptionalParams, MultipleResponsesGet202None204NoneDefaultNone400InvalidOptionalParams, MultipleResponsesGetDefaultModelA200ValidOptionalParams, MultipleResponsesGetDefaultModelA200ValidResponse, MultipleResponsesGetDefaultModelA200NoneOptionalParams, MultipleResponsesGetDefaultModelA200NoneResponse, MultipleResponsesGetDefaultModelA400ValidOptionalParams, MultipleResponsesGetDefaultModelA400NoneOptionalParams, MultipleResponsesGetDefaultNone200InvalidOptionalParams, MultipleResponsesGetDefaultNone200NoneOptionalParams, MultipleResponsesGetDefaultNone400InvalidOptionalParams, MultipleResponsesGetDefaultNone400NoneOptionalParams, MultipleResponsesGet200ModelA200NoneOptionalParams, MultipleResponsesGet200ModelA200NoneResponse, MultipleResponsesGet200ModelA200ValidOptionalParams, MultipleResponsesGet200ModelA200ValidResponse, MultipleResponsesGet200ModelA200InvalidOptionalParams, MultipleResponsesGet200ModelA200InvalidResponse, MultipleResponsesGet200ModelA400NoneOptionalParams, MultipleResponsesGet200ModelA400NoneResponse, MultipleResponsesGet200ModelA400ValidOptionalParams, MultipleResponsesGet200ModelA400ValidResponse, MultipleResponsesGet200ModelA400InvalidOptionalParams, MultipleResponsesGet200ModelA400InvalidResponse, MultipleResponsesGet200ModelA202ValidOptionalParams, MultipleResponsesGet200ModelA202ValidResponse } from "../models"; /** Interface representing a MultipleResponses. */ export interface MultipleResponses { /** * Send a 200 response with valid payload: {'statusCode': '200'} * @param options The options parameters. */ get200Model204NoModelDefaultError200Valid( options?: MultipleResponsesGet200Model204NoModelDefaultError200ValidOptionalParams ): Promise< MultipleResponsesGet200Model204NoModelDefaultError200ValidResponse >; /** * Send a 204 response with no payload * @param options The options parameters. */ get200Model204NoModelDefaultError204Valid( options?: MultipleResponsesGet200Model204NoModelDefaultError204ValidOptionalParams ): Promise< MultipleResponsesGet200Model204NoModelDefaultError204ValidResponse >; /** * Send a 201 response with valid payload: {'statusCode': '201'} * @param options The options parameters. */ get200Model204NoModelDefaultError201Invalid( options?: MultipleResponsesGet200Model204NoModelDefaultError201InvalidOptionalParams ): Promise< MultipleResponsesGet200Model204NoModelDefaultError201InvalidResponse >; /** * Send a 202 response with no payload: * @param options The options parameters. */ get200Model204NoModelDefaultError202None( options?: MultipleResponsesGet200Model204NoModelDefaultError202NoneOptionalParams ): Promise<MultipleResponsesGet200Model204NoModelDefaultError202NoneResponse>; /** * Send a 400 response with valid error payload: {'status': 400, 'message': 'client error'} * @param options The options parameters. */ get200Model204NoModelDefaultError400Valid( options?: MultipleResponsesGet200Model204NoModelDefaultError400ValidOptionalParams ): Promise< MultipleResponsesGet200Model204NoModelDefaultError400ValidResponse >; /** * Send a 200 response with valid payload: {'statusCode': '200'} * @param options The options parameters. */ get200Model201ModelDefaultError200Valid( options?: MultipleResponsesGet200Model201ModelDefaultError200ValidOptionalParams ): Promise<MultipleResponsesGet200Model201ModelDefaultError200ValidResponse>; /** * Send a 201 response with valid payload: {'statusCode': '201', 'textStatusCode': 'Created'} * @param options The options parameters. */ get200Model201ModelDefaultError201Valid( options?: MultipleResponsesGet200Model201ModelDefaultError201ValidOptionalParams ): Promise<MultipleResponsesGet200Model201ModelDefaultError201ValidResponse>; /** * Send a 400 response with valid payload: {'code': '400', 'message': 'client error'} * @param options The options parameters. */ get200Model201ModelDefaultError400Valid( options?: MultipleResponsesGet200Model201ModelDefaultError400ValidOptionalParams ): Promise<MultipleResponsesGet200Model201ModelDefaultError400ValidResponse>; /** * Send a 200 response with valid payload: {'statusCode': '200'} * @param options The options parameters. */ get200ModelA201ModelC404ModelDDefaultError200Valid( options?: MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidOptionalParams ): Promise< MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidResponse >; /** * Send a 200 response with valid payload: {'httpCode': '201'} * @param options The options parameters. */ get200ModelA201ModelC404ModelDDefaultError201Valid( options?: MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidOptionalParams ): Promise< MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidResponse >; /** * Send a 200 response with valid payload: {'httpStatusCode': '404'} * @param options The options parameters. */ get200ModelA201ModelC404ModelDDefaultError404Valid( options?: MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidOptionalParams ): Promise< MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidResponse >; /** * Send a 400 response with valid payload: {'code': '400', 'message': 'client error'} * @param options The options parameters. */ get200ModelA201ModelC404ModelDDefaultError400Valid( options?: MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidOptionalParams ): Promise< MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidResponse >; /** * Send a 202 response with no payload * @param options The options parameters. */ get202None204NoneDefaultError202None( options?: MultipleResponsesGet202None204NoneDefaultError202NoneOptionalParams ): Promise<void>; /** * Send a 204 response with no payload * @param options The options parameters. */ get202None204NoneDefaultError204None( options?: MultipleResponsesGet202None204NoneDefaultError204NoneOptionalParams ): Promise<void>; /** * Send a 400 response with valid payload: {'code': '400', 'message': 'client error'} * @param options The options parameters. */ get202None204NoneDefaultError400Valid( options?: MultipleResponsesGet202None204NoneDefaultError400ValidOptionalParams ): Promise<void>; /** * Send a 202 response with an unexpected payload {'property': 'value'} * @param options The options parameters. */ get202None204NoneDefaultNone202Invalid( options?: MultipleResponsesGet202None204NoneDefaultNone202InvalidOptionalParams ): Promise<void>; /** * Send a 204 response with no payload * @param options The options parameters. */ get202None204NoneDefaultNone204None( options?: MultipleResponsesGet202None204NoneDefaultNone204NoneOptionalParams ): Promise<void>; /** * Send a 400 response with no payload * @param options The options parameters. */ get202None204NoneDefaultNone400None( options?: MultipleResponsesGet202None204NoneDefaultNone400NoneOptionalParams ): Promise<void>; /** * Send a 400 response with an unexpected payload {'property': 'value'} * @param options The options parameters. */ get202None204NoneDefaultNone400Invalid( options?: MultipleResponsesGet202None204NoneDefaultNone400InvalidOptionalParams ): Promise<void>; /** * Send a 200 response with valid payload: {'statusCode': '200'} * @param options The options parameters. */ getDefaultModelA200Valid( options?: MultipleResponsesGetDefaultModelA200ValidOptionalParams ): Promise<MultipleResponsesGetDefaultModelA200ValidResponse>; /** * Send a 200 response with no payload * @param options The options parameters. */ getDefaultModelA200None( options?: MultipleResponsesGetDefaultModelA200NoneOptionalParams ): Promise<MultipleResponsesGetDefaultModelA200NoneResponse>; /** * Send a 400 response with valid payload: {'statusCode': '400'} * @param options The options parameters. */ getDefaultModelA400Valid( options?: MultipleResponsesGetDefaultModelA400ValidOptionalParams ): Promise<void>; /** * Send a 400 response with no payload * @param options The options parameters. */ getDefaultModelA400None( options?: MultipleResponsesGetDefaultModelA400NoneOptionalParams ): Promise<void>; /** * Send a 200 response with invalid payload: {'statusCode': '200'} * @param options The options parameters. */ getDefaultNone200Invalid( options?: MultipleResponsesGetDefaultNone200InvalidOptionalParams ): Promise<void>; /** * Send a 200 response with no payload * @param options The options parameters. */ getDefaultNone200None( options?: MultipleResponsesGetDefaultNone200NoneOptionalParams ): Promise<void>; /** * Send a 400 response with valid payload: {'statusCode': '400'} * @param options The options parameters. */ getDefaultNone400Invalid( options?: MultipleResponsesGetDefaultNone400InvalidOptionalParams ): Promise<void>; /** * Send a 400 response with no payload * @param options The options parameters. */ getDefaultNone400None( options?: MultipleResponsesGetDefaultNone400NoneOptionalParams ): Promise<void>; /** * Send a 200 response with no payload, when a payload is expected - client should return a null object * of thde type for model A * @param options The options parameters. */ get200ModelA200None( options?: MultipleResponsesGet200ModelA200NoneOptionalParams ): Promise<MultipleResponsesGet200ModelA200NoneResponse>; /** * Send a 200 response with payload {'statusCode': '200'} * @param options The options parameters. */ get200ModelA200Valid( options?: MultipleResponsesGet200ModelA200ValidOptionalParams ): Promise<MultipleResponsesGet200ModelA200ValidResponse>; /** * Send a 200 response with invalid payload {'statusCodeInvalid': '200'} * @param options The options parameters. */ get200ModelA200Invalid( options?: MultipleResponsesGet200ModelA200InvalidOptionalParams ): Promise<MultipleResponsesGet200ModelA200InvalidResponse>; /** * Send a 400 response with no payload client should treat as an http error with no error model * @param options The options parameters. */ get200ModelA400None( options?: MultipleResponsesGet200ModelA400NoneOptionalParams ): Promise<MultipleResponsesGet200ModelA400NoneResponse>; /** * Send a 200 response with payload {'statusCode': '400'} * @param options The options parameters. */ get200ModelA400Valid( options?: MultipleResponsesGet200ModelA400ValidOptionalParams ): Promise<MultipleResponsesGet200ModelA400ValidResponse>; /** * Send a 200 response with invalid payload {'statusCodeInvalid': '400'} * @param options The options parameters. */ get200ModelA400Invalid( options?: MultipleResponsesGet200ModelA400InvalidOptionalParams ): Promise<MultipleResponsesGet200ModelA400InvalidResponse>; /** * Send a 202 response with payload {'statusCode': '202'} * @param options The options parameters. */ get200ModelA202Valid( options?: MultipleResponsesGet200ModelA202ValidOptionalParams ): Promise<MultipleResponsesGet200ModelA202ValidResponse>; }
the_stack
const workerRouter = require('express').Router() const basicAuth = require('express-basic-auth') import { mergeBlocks, filterFields, limitRange, checkAuth, aggregateShareCreditsFromPoolShares, aggregateShareCreditsFromUserStats, getLatestNetworkBlockHeight, sanitizeHeight, calculateBlockReward } from '../utils' const app = require('../index') import { cache, knex, rigCache, getAsync } from '../index' import { WorkerGpsStat, DatabaseWorkerStat, BlockAlgoValidShare, DatabasePoolUtxo, DatabasePoolPayment, DatabasePoolBlock, PoolSharesQueryResult, UserSharesQueryResult } from '../types/types' workerRouter.get('/stats/:id/:height,:range/:fields?', sanitizeHeight, limitRange, checkAuth, async (req, res, next) => { try { const { height, fields, id } = req.params const range = res.locals.range if (!height || !range) throw { statusCode: 400, message: 'No height or range field specified' } const max = parseInt(height) const rangeNumber = parseInt(range) const min = max - rangeNumber // console.log('min is: ', min, ' max is: ', max, ' and rangeNumber is: ', rangeNumber) const results: WorkerGpsStat[] = await knex.select(['*', knex.raw('UNIX_TIMESTAMP(timestamp) as timestamp')]) .from('worker_stats') .join('gps', 'gps.worker_stats_id', '=', 'worker_stats.id') .where('worker_stats.height', '>', min) .andWhere('worker_stats.height', '<=', max) .andWhere('worker_stats.user_id', '=', id) .limit(range * 2) // console.log('/stats/:id/:height,:range/:fields? results.length: ', results.length) const output = mergeBlocks(results) // console.log('merged blocks output length is: ', output.length) res.json(output) app.cache.set(res.locals.cacheKey, JSON.stringify(output), 'EX', 20) } catch (e) { next(e) } }) // get rig data for a user in a block range workerRouter.get('/rigs/:id/:height,:range', sanitizeHeight, limitRange, checkAuth, async (req, res, next) => { try { const { height, fields, id } = req.params const range = res.locals.range if (!height || !range) throw { statusCode: 400, message: 'No height or range field specified' } const max = parseInt(height) const rangeNumber = parseInt(range) const min = max - rangeNumber let rigData = [] let blockHeights = [] // console.log('min is: ', min) for (let iterator = min; iterator <= max; iterator++) { const rigCacheKey = `rigdata.${iterator}.${id}` // rigData.push(getAsync(rigCacheKey)) rigData[iterator] = getAsync(rigCacheKey) blockHeights.push(iterator) // console.log('iterator is: ', iterator) } // console.log('blockHeights is: ', blockHeights) const temp = await Promise.all(Object.values(rigData)) // console.log('rigData is: ', rigData) const finalRigData = {} let index = 0 // console.log('rigData is: ', rigData) temp.forEach((item) => { let parsedData = JSON.parse(item) if (parsedData) { // console.log('parsedData is: ', parsedData) finalRigData[blockHeights[index]] = parsedData // parsedData.height = blockHeights[index] // finalRigData.push(parsedData) // console.log('index is: ', index, ' an blockHeights[index] is: ', blockHeights[index]) } index++ }) // console.log('barely inside of for loop and rigData is: ', finalRigData) res.json(finalRigData) } catch (e) { } }) // complete workerRouter.get('/stat/:id/:fields?', checkAuth, async (req, res, next) => { try { const { id, fields } = req.params const latestWorkerStatSubquery: { id: number }[] = knex('worker_stats') .max('id'). where('user_id', '=', id) .limit(1) const latestWorkerStatResults: DatabaseWorkerStat[] = await knex.select() .from('worker_stats') .where('user_id', '=', id) .andWhere('id', '=', latestWorkerStatSubquery) .limit(1) let output = latestWorkerStatResults app.cache.set(res.locals.cacheKey, JSON.stringify(output[0]), 'EX', 20) res.json(...output) } catch (e) { next(e) } }) // new workerRouter.get('/shares/:id/:height,:range/:fields?', checkAuth, sanitizeHeight, limitRange, async (req, res, next) => { try { const { id, height } = req.params const range = res.locals.range if (!height || !range) throw { statusCode: 400, message: 'No height or range field specified' } const max = parseInt(height) const rangeNumber = parseInt(range) const min = max - rangeNumber // console.log('/shares/:id/:height,:range/:fields, rangeNumber is: ', rangeNumber, ' max is: ', max, ' and min is: ', min) const workerShareResults: BlockAlgoValidShare[] = await knex.select(['edge_bits', 'valid', 'worker_shares.height as height']) .from('shares') .join('worker_shares', 'shares.parent_id', '=', 'worker_shares.id') .where('worker_shares.height', '<=', max) .andWhere('worker_shares.height', '>', min) .andWhere('worker_shares.user_id', '=', id) // console.log('workerShareResults are: ', workerShareResults) app.cache.set(res.locals.cacheKey, JSON.stringify(workerShareResults), 'EX', 60 * 60) res.json(workerShareResults) } catch (e) { next(e) } }) // checking workerRouter.get('/utxo/:id', checkAuth, async (req, res, next) => { try { const { id } = req.params const results: DatabasePoolUtxo = await knex.select() .from('pool_utxo') .where('user_id', '=', id) .limit(1) delete results.id app.cache.set(res.locals.cacheKey, JSON.stringify(results[0]), 'EX', 60) res.json(results[0]) } catch (e) { next(e) } }) // complete workerRouter.get('/payment/:id', checkAuth, async (req, res, next) => { try { const { id } = req.params const workerLatestPaymentSubquery: { timestamp: any }[] = await knex('pool_payment') .max('timestamp') .where('user_id', '=', id) const result: DatabasePoolPayment[] = await knex('pool_payment') .where('user_id', '=', id) .andWhere('timestamp', '=', workerLatestPaymentSubquery) // console.log('/payment/:id result is: ', result) app.cache.set(res.locals.cacheKey, JSON.stringify(result), 'EX', 60) res.json(result) } catch (e) { next(e) } }) workerRouter.get('/payments/:id/:range', checkAuth, limitRange, async (req, res, next) => { try { // console.log('in /payments/:id/:range') const { id } = req.params const range = res.locals.range if (!range) throw { statusCode: 400, message: 'No block range set' } const results: DatabasePoolPayment[] = await knex.select() .from('pool_payment') .where('user_id', '=', id) .orderBy('timestamp', 'desc') .limit(range) app.cache.set(res.locals.cacheKey, JSON.stringify(results), 'EX', 60) res.json(results) } catch (e) { next(e) } }) export const getUserEstimatedRewardForBlock = (id: number, height: number, res, next) => { // console.log('inside getUserEstimatedRewardForBlock function') const getUserEstimatedRewardsForBlockCacheKey = `api_getUserEstimatedRewardForBlock_${id}_${height}` let getUserEstimatedRewardsForBlockResult return new Promise((resolve, reject) => { cache.get(getUserEstimatedRewardsForBlockCacheKey, async (error, getUserEstimatedRewardsCache: string) => { if (getUserEstimatedRewardsCache) { // console.log(getUserEstimatedRewardsForBlockCacheKey, ' already found: ', getUserEstimatedRewardsCache) resolve(parseInt(getUserEstimatedRewardsCache)) } else { try { // console.log(getUserEstimatedRewardsForBlockCacheKey, ' not found') const creditRange = 60 const escapedMinHeight = height - creditRange // get data for pool blocks in last day // const poolBlockMinedQuery = `SELECT * FROM pool_blocks WHERE state = 'new' AND height = ${height} LIMIT 1` const poolBlockMined: DatabasePoolBlock[] = await knex('pool_blocks') .where('state', '=', 'new') .andWhere('height', '=', height) .limit(1) // no blocks = no reward // console.log('poolBlocksMined are: ', poolBlockMined) if (poolBlockMined.length === 0) res.status(200).json(0) let poolSharesWeights let userSharesWeights const poolBlockShareWeightCacheKey = `api_pool_shares_weights_${height}` const userBlockShareWeightCacheKey = `api_user_shares_weights_${id}_${height}` //console.log('poolBlockShareWeightCacheKey is: ', poolBlockShareWeightCacheKey) cache.get(poolBlockShareWeightCacheKey, async (error, poolSharesCreditCache: string) => { if (error) throw {statusCode: 500, message: 'Error getting cache'} const poolSharesCredit: {c29: number, c31: number} = JSON.parse(poolSharesCreditCache) if (poolSharesCredit) { poolSharesWeights = poolSharesCredit } else { // need to get pool shares for 60-block range const poolSharesResults: PoolSharesQueryResult[] = await knex('pool_stats') .select() .join('blocks', 'pool_stats.height', 'blocks.height') .where('blocks.height', '<=', height) .andWhere('blocks.height', '>', escapedMinHeight) poolSharesWeights = aggregateShareCreditsFromPoolShares(poolSharesResults) cache.set(poolBlockShareWeightCacheKey, JSON.stringify(poolSharesWeights), 'EX', 60 * 60 * 24) cache.get(userBlockShareWeightCacheKey, async (error, userSharesCreditCache: string) => { if (error) throw { statusCode: 500, message: 'Error getting cache' } const userSharesCredit: { c29: number, c31: number } = JSON.parse(userSharesCreditCache) if (userSharesCredit) { userSharesWeights = userSharesCredit } else { const userSharesResults: UserSharesQueryResult[] = await knex('shares') .select() .join('worker_shares as ws', 'ws.id', 'shares.parent_id') .join('blocks as b', 'b.height', 'ws.height') .where('ws.user_id', '=', id) .andWhere('ws.height', '<=', height) .andWhere('ws.height', '>', escapedMinHeight) userSharesWeights = aggregateShareCreditsFromUserStats(userSharesResults) cache.set(userBlockShareWeightCacheKey, JSON.stringify(userSharesWeights), 'EX', 60 * 60 * 24) } //console.log('userSharesWeights is: ', userSharesWeights, ' and poolSharesWeights is: ', poolSharesWeights) const aggregatePoolSharesWeight = poolSharesWeights.c29 + poolSharesWeights.c31 const aggregateUserSharesWeight = userSharesWeights.c29 + userSharesWeights.c31 //console.log('aggregatePoolSharesWeight is: ', aggregatePoolSharesWeight, ' aggregateUserSharesWeight is: ', aggregateUserSharesWeight) if (aggregatePoolSharesWeight === 0 || aggregateUserSharesWeight === 0) { resolve(0) return } const blockRewardRate = aggregateUserSharesWeight / (aggregatePoolSharesWeight) // keep in mind that pool shares will include user's shares const blockReward = Math.floor(60000000000 * blockRewardRate) // sent in nanogrin // console.log('blockReward is: ', blockReward) cache.set(getUserEstimatedRewardsForBlockCacheKey, JSON.stringify(blockReward), 'EX', 60 * 60 * 24) resolve(blockReward) }) } }) } catch (e) { reject(e) } } }) }) } // complete, get payment estimate for a (immature) block workerRouter.get('/estimate/payment/:id/:height', checkAuth, sanitizeHeight, async (req, res, next) => { try { const { height, id } = req.params if (!height) throw { statusCode: 400, message: 'No height field specified' } const reward = await getUserEstimatedRewardForBlock(id, height, res, next) app.cache.set(res.locals.cacheKey, reward, 'EX', 60 * 60) res.json(reward) return } catch (e) { next(e) } }) // gets user's immature balances workerRouter.get('/estimate/payment/:id', checkAuth, async (req, res, next) => { try { const { id } = req.params const poolBlocksMinedResults: DatabasePoolBlock[] = await knex('pool_blocks') .select('height') .where('state', '=', 'new') .orderBy('height', 'desc') //console.log('poolBlocksMinedResults is: ', poolBlocksMinedResults) if (poolBlocksMinedResults.length === 0) { res.status(200).json(0) return } const maxPoolBlockHeight = poolBlocksMinedResults[0].height const minBlockHeight = maxPoolBlockHeight - 1440 - 60 const poolSharesQuery = knex('pool_stats') .select() .join('blocks', 'pool_stats.height', 'blocks.height') .where('blocks.height', '<=', maxPoolBlockHeight) .andWhere('blocks.height', '>', minBlockHeight) const userSharesQuery = knex('shares') .select('*', knex.raw('shares.edge_bits AS share_edge_bits')) .join('worker_shares as ws', 'ws.id', 'shares.parent_id') .join('blocks as b', 'b.height', 'ws.height') .where('ws.user_id', '=', id) .andWhere('ws.height', '<=', maxPoolBlockHeight) .andWhere('ws.height', '>', minBlockHeight) const [ poolSharesResults, userSharesResults ]: [PoolSharesQueryResult[], UserSharesQueryResult[]] = await Promise.all([poolSharesQuery, userSharesQuery]) // console.log('poolSharesResults[0]: ', poolSharesResults[0]) // console.log('userSharesResults[0]: ', userSharesResults[0]) let rewards = 0 poolBlocksMinedResults.forEach((result) => { const additionalReward = calculateBlockReward(result.height, userSharesResults, poolSharesResults) // console.log('additionalReward for height ', result.height, ' is: ', additionalReward / 1000000000) rewards += additionalReward }) app.cache.set(res.locals.cacheKey, rewards, 'EX', 60 * 2) // console.log('rewards is: ', rewards / 1000000000) res.status(200).json(rewards) } catch (e) { next(e) } }) module.exports = workerRouter
the_stack
import { injectable } from 'inversify'; import * as ts from 'typescript'; import { isModuleDeclaration, isNamespaceExportDeclaration, findImports, ImportKind } from 'tsutils'; import { resolveCachedResult, getOutputFileNamesOfProjectReference, iterateProjectReferences, unixifyPath } from '../utils'; import bind from 'bind-decorator'; import * as path from 'path'; export interface DependencyResolver { update(program: ts.Program, updatedFile: string): void; getDependencies(fileName: string): ReadonlyMap<string, null | readonly string[]>; getFilesAffectingGlobalScope(): readonly string[]; } export type DependencyResolverHost = Required<Pick<ts.CompilerHost, 'resolveModuleNames'>> & { useSourceOfProjectReferenceRedirect?(): boolean; }; @injectable() export class DependencyResolverFactory { public create(host: DependencyResolverHost, program: ts.Program): DependencyResolver { return new DependencyResolverImpl(host, program); } } interface DependencyResolverState { affectsGlobalScope: readonly string[]; ambientModules: ReadonlyMap<string, readonly string[]>; moduleAugmentations: ReadonlyMap<string, readonly string[]>; patternAmbientModules: ReadonlyMap<string, readonly string[]>; } class DependencyResolverImpl implements DependencyResolver { private dependencies = new Map<string, Map<string, string | null>>(); private fileToProjectReference: ReadonlyMap<string, ts.ResolvedProjectReference> | undefined = undefined; private fileMetadata = new Map<string, MetaData>(); private compilerOptions = this.program.getCompilerOptions(); private useSourceOfProjectReferenceRedirect = this.host.useSourceOfProjectReferenceRedirect?.() === true && !this.compilerOptions.disableSourceOfProjectReferenceRedirect; private state: DependencyResolverState | undefined = undefined; constructor(private host: DependencyResolverHost, private program: ts.Program) {} public update(program: ts.Program, updatedFile: string) { this.state = undefined; this.dependencies.delete(updatedFile); this.fileMetadata.delete(updatedFile); this.program = program; } private buildState(): DependencyResolverState { const affectsGlobalScope = []; const ambientModules = new Map<string, string[]>(); const patternAmbientModules = new Map<string, string[]>(); const moduleAugmentationsTemp = new Map<string, string[]>(); for (const file of this.program.getSourceFiles()) { const meta = this.getFileMetaData(file.fileName); if (meta.affectsGlobalScope) affectsGlobalScope.push(file.fileName); for (const ambientModule of meta.ambientModules) { const map = meta.isExternalModule ? moduleAugmentationsTemp : ambientModule.includes('*') ? patternAmbientModules : ambientModules; addToList(map, ambientModule, file.fileName); } } const moduleAugmentations = new Map<string, string[]>(); for (const [module, files] of moduleAugmentationsTemp) { // if an ambient module with the same identifier exists, the augmentation always applies to that const ambientModuleAffectingFiles = ambientModules.get(module); if (ambientModuleAffectingFiles !== undefined) { ambientModuleAffectingFiles.push(...files); continue; } for (const file of files) { const resolved = this.getExternalReferences(file).get(module); // if an augmentation's identifier can be resolved from the declaring file, the augmentation applies to the resolved path if (resolved != null) { // tslint:disable-line:triple-equals addToList(moduleAugmentations, resolved, file); } else { // if a pattern ambient module matches the augmented identifier, the augmentation applies to that const matchingPattern = getBestMatchingPattern(module, patternAmbientModules.keys()); if (matchingPattern !== undefined) addToList(patternAmbientModules, matchingPattern, file); } } } return { affectsGlobalScope, ambientModules, moduleAugmentations, patternAmbientModules, }; } public getFilesAffectingGlobalScope() { return (this.state ??= this.buildState()).affectsGlobalScope; } public getDependencies(file: string) { const result = new Map<string, null | readonly string[]>(); if (this.program.getSourceFile(file) === undefined) return result; this.state ??= this.buildState(); { const augmentations = this.state.moduleAugmentations.get(file); if (augmentations !== undefined) result.set('\0', augmentations); } for (const [identifier, resolved] of this.getExternalReferences(file)) { const filesAffectingAmbientModule = this.state.ambientModules.get(identifier); if (filesAffectingAmbientModule !== undefined) { result.set(identifier, filesAffectingAmbientModule); } else if (resolved !== null) { const list = [resolved]; const augmentations = this.state.moduleAugmentations.get(resolved); if (augmentations !== undefined) list.push(...augmentations); result.set(identifier, list); } else { const pattern = getBestMatchingPattern(identifier, this.state.patternAmbientModules.keys()); if (pattern !== undefined) { result.set(identifier, this.state.patternAmbientModules.get(pattern)!); } else { result.set(identifier, null); } } } const meta = this.fileMetadata.get(file)!; if (!meta.isExternalModule) for (const ambientModule of meta.ambientModules) result.set( ambientModule, this.state[ambientModule.includes('*') ? 'patternAmbientModules' : 'ambientModules'].get(ambientModule)!, ); return result; } private getFileMetaData(fileName: string) { return resolveCachedResult(this.fileMetadata, fileName, this.collectMetaDataForFile); } private getExternalReferences(fileName: string) { return resolveCachedResult(this.dependencies, fileName, this.collectExternalReferences); } @bind private collectMetaDataForFile(fileName: string) { return collectFileMetadata(this.program.getSourceFile(fileName)!); } @bind private collectExternalReferences(fileName: string): Map<string, string | null> { // TODO add tslib if importHelpers is enabled const sourceFile = this.program.getSourceFile(fileName)!; const references = new Set(findImports(sourceFile, ImportKind.All, false).map(({text}) => text)); if (ts.isExternalModule(sourceFile)) for (const augmentation of this.getFileMetaData(fileName).ambientModules) references.add(augmentation); const result = new Map<string, string | null>(); if (references.size === 0) return result; this.fileToProjectReference ??= createProjectReferenceMap(this.program.getResolvedProjectReferences()); const arr = Array.from(references); const resolved = this.host.resolveModuleNames(arr, fileName, undefined, this.fileToProjectReference.get(fileName), this.compilerOptions); for (let i = 0; i < resolved.length; ++i) { const current = resolved[i]; if (current === undefined) { result.set(arr[i], null); } else { const projectReference = this.useSourceOfProjectReferenceRedirect ? this.fileToProjectReference.get(current.resolvedFileName) : undefined; if (projectReference === undefined) { result.set(arr[i], current.resolvedFileName); } else if (projectReference.commandLine.options.outFile) { // with outFile the files must be global anyway, so we don't care about the exact file result.set(arr[i], projectReference.commandLine.fileNames[0]); } else { result.set(arr[i], getSourceOfProjectReferenceRedirect(current.resolvedFileName, projectReference)); } } } return result; } } function getBestMatchingPattern(moduleName: string, patternAmbientModules: Iterable<string>) { // TypeScript uses the pattern with the longest matching prefix let longestMatchLength = -1; let longestMatch: string | undefined; for (const pattern of patternAmbientModules) { if (moduleName.length < pattern.length - 1) continue; // compare length without the wildcard first, to avoid false positives like 'foo' matching 'foo*oo' const index = pattern.indexOf('*'); if ( index > longestMatchLength && moduleName.startsWith(pattern.substring(0, index)) && moduleName.endsWith(pattern.substring(index + 1)) ) { longestMatchLength = index; longestMatch = pattern; } } return longestMatch; } function createProjectReferenceMap(references: ts.ResolvedProjectReference['references']) { const result = new Map<string, ts.ResolvedProjectReference>(); for (const ref of iterateProjectReferences(references)) for (const file of getOutputFileNamesOfProjectReference(ref)) result.set(file, ref); return result; } function addToList<T>(map: Map<string, T[]>, key: string, value: T) { const arr = map.get(key); if (arr === undefined) { map.set(key, [value]); } else { arr.push(value); } } interface MetaData { affectsGlobalScope: boolean; ambientModules: Set<string>; isExternalModule: boolean; } function collectFileMetadata(sourceFile: ts.SourceFile): MetaData { let affectsGlobalScope: boolean | undefined; const ambientModules = new Set<string>(); const isExternalModule = ts.isExternalModule(sourceFile); for (const statement of sourceFile.statements) { if (statement.flags & ts.NodeFlags.GlobalAugmentation) { affectsGlobalScope = true; } else if (isModuleDeclaration(statement) && statement.name.kind === ts.SyntaxKind.StringLiteral) { ambientModules.add(statement.name.text); if (!isExternalModule && !affectsGlobalScope && statement.body !== undefined) { // search for global augmentations in ambient module blocks for (const s of (<ts.ModuleBlock>statement.body).statements) { if (s.flags & ts.NodeFlags.GlobalAugmentation) { affectsGlobalScope = true; break; } } } } else if (isNamespaceExportDeclaration(statement)) { affectsGlobalScope = true; } else if (affectsGlobalScope === undefined) { // files that only consist of ambient modules do not affect global scope affectsGlobalScope = !isExternalModule; } } return {ambientModules, isExternalModule, affectsGlobalScope: affectsGlobalScope === true}; } function getSourceOfProjectReferenceRedirect(outputFileName: string, ref: ts.ResolvedProjectReference): string { const options = ref.commandLine.options; const projectDirectory = path.dirname(ref.sourceFile.fileName); const origin = unixifyPath(path.resolve( options.rootDir || projectDirectory, path.relative(options.declarationDir || options.outDir || /* istanbul ignore next */ projectDirectory, outputFileName.slice(0, -5)), )); for (const extension of ['.ts', '.tsx', '.js', '.jsx']) { const name = origin + extension; if (ref.commandLine.fileNames.includes(name)) return name; } /* istanbul ignore next */ return outputFileName; // should never happen }
the_stack
declare module "quagga" { var Quagga: QuaggaJSStatic; export default Quagga; } interface QuaggaJSStatic { /** * This method initializes the library for a given * configuration config (see below) and invokes the callback when Quagga is * ready to start. The initialization process also requests for camera * access if real-time detection is configured. */ init( config: QuaggaJSConfigObject, callback?: (err: any) => void ): void; init( config: QuaggaJSConfigObject, callback: (err: any) => void, imageWrapper: any ): void; /** * When the library is initialized, the start() * method starts the video-stream and begins locating and decoding the * images. */ start(): void; /** * If the decoder is currently running, after calling * stop() the decoder does not process any more images. * Additionally, if a camera-stream was requested upon initialization, * this operation also disconnects the camera. */ stop(): void; /** * Pauses processing, but does not release any handlers */ pause(): void; /** * This method registers a callback(data) function that is * called for each frame after the processing is done. The data object * contains detailed information about the success/failure of the operation. * The output varies, depending whether the detection and/or decoding were * successful or not. */ onProcessed(callback: QuaggaJSResultCallbackFunction): void; /** * Removes a callback that was previously registered with @see onProcessed */ offProcessed(callback: QuaggaJSResultCallbackFunction): void; /** * Registers a callback(data) function which is triggered whenever a * barcode- pattern has been located and decoded successfully. The passed * data object contains information about the decoding process including the * detected code which can be obtained by calling data.codeResult.code. */ onDetected(callback: QuaggaJSResultCallbackFunction): void; /** * Removes a callback that was previously registered with @see onDetected */ offDetected(callback: QuaggaJSResultCallbackFunction): void; ResultCollector: QuaggaJSResultCollector; registerResultCollector(resultCollector: QuaggaJSResultCollector): void; setReaders(readers: (QuaggaJSReaderConfig | string)[]): void; /** * In contrast to the calls described * above, this method does not rely on getUserMedia and operates on a single * image instead. The provided callback is the same as in onDetected and * contains the result data object. */ decodeSingle( config: QuaggaJSConfigObject, resultCallback: QuaggaJSResultCallbackFunction ): void; /** * Constructs used for debugging purposes */ ImageDebug: { drawPath: QuaggaJSDebugDrawPath; drawRect: QuaggaJSDebugDrawRect; }; ImageWrapper: any; /** * an object Quagga uses for drawing and processing, useful for calling code * when debugging */ canvas: { ctx: { image: CanvasRenderingContext2D; overlay: CanvasRenderingContext2D }; dom: { image: HTMLCanvasElement; overlay: HTMLCanvasElement } }; CameraAccess: QuaggaJSCameraAccess; } /** * Used for accessing information about the active stream track and available video devices. */ interface QuaggaJSCameraAccess { request(video: HTMLVideoElement, videoConstraints: QuaggaJSConstraints): Promise<void>; release(): void; enumerateVideoDevices(): Promise<MediaDeviceInfo[]>; getActiveStreamLabel(): string; getActiveTrack(): MediaStreamTrack; } /** * Called whenever an item is detected or a process step has been completed. */ interface QuaggaJSResultCallbackFunction { ( data: QuaggaJSResultObject ): void; } /** * Called to draw debugging path. The path is an array of array of 2 numbers. * The def.x specifies element in the sub array is the x, and similary the def.y * defines the y. * typical values 0, 1, 'x', 'y' */ interface QuaggaJSDebugDrawPath { ( path: any[], def: QuaggaJSxyDef, ctx: CanvasRenderingContext2D, style: QuaggaJSStyle ): void } /** * Called to draw debugging Rectangle */ interface QuaggaJSDebugDrawRect { ( pos: any[], size: QuaggaJSRectSize, ctx: CanvasRenderingContext2D, style: QuaggaJSStyle ): void } /** * an object with an x and a y value, the x and y specify which element in * another array is the x or y value. * typical values 0, 1, 'x', 'y' */ interface QuaggaJSxyDef { x: any; y: any; } /** * an object with an x and a y value */ interface QuaggaJSxy { x: number; y: number; } /** * an object with a pair of x and a y values. * Used for giving a htiml canvas context.strokeRect function it's x, y, width * and height values. */ interface QuaggaJSRectSize { pos: QuaggaJSxy; size: QuaggaJSxy; } /** * an object with the styles, color can actually be a color, a gradient or a * pattern (see defintions for context.strokeStyle. But is most commonly a * colour. */ interface QuaggaJSStyle { color: string; /* http://www.w3schools.com/tags/canvas_linewidth.asp */ lineWidth: number; } /** * Pass when creating a ResultCollector */ interface QuaggaJSResultCollector { /** * keep track of the image producing this result */ capture?: boolean; /** * maximum number of results to store */ capacity?: number; /** * a list of codes that should not be recorded. This is effectively a list * of filters that return false. */ blacklist?: QuaggaJSCodeResult; /** * passed a QuaggaJSCodeResult, return true if you want this to be stored, * false if you don't. Note: The black list is effectively a list of filters * that return false. So if you only want to store results that are ean_13, * you would say return codeResult.format==="ean_13" */ filter?: QuaggaJSResultCollectorFilterFunction; /* * a static function that returns you a ResultCollector */ create?(param: QuaggaJSResultCollector): QuaggaJSResultCollector; getResults?(): QuaggaJSCodeResult[]; } /** * used for ResultCollector blacklists and filters */ interface QuaggaJSCodeResult { code?: string; format?: string; } /** * Called to filter which Results to collect in ResultCollector */ interface QuaggaJSResultCollectorFilterFunction { ( data: QuaggaJSCodeResult ): boolean; } /** * The callbacks passed into onProcessed, onDetected and decodeSingle receive a * data object upon execution. The data object contains the following * information. Depending on the success, some fields may be undefined or just * empty. */ interface QuaggaJSResultObject { codeResult: QuaggaJSResultObject_CodeResult; line: { x: number; y: number; }[]; angle: number; pattern: number[]; box: number[][]; boxes: number[][][]; } interface QuaggaJSResultObject_CodeResult { code: string; start: number; end: number; codeset: number; startInfo: { error: number; code: number; start: number; end: number; }; decodedCodes: { error?: number; code: number; start: number; end: number; }[]; endInfo: { error: number; code: number; start: number; end: number; }; direction: number; format: string; } interface QuaggaJSConfigObject { /** * The image path to load from, or a data url * Ex: '/test/fixtures/code_128/image-001.jpg' * or: 'data:image/jpg;base64,' + data */ src?: string; inputStream?: { /** * @default "Live" */ name?: string; /** * @default "LiveStream" */ type?: string; target?: HTMLElement, constraints?: QuaggaJSConstraints; /** * defines rectangle of the detection/localization area. Useful when you * KNOW that certain parts of the image will not contain a barcode, also * useful when you have multiple barcodes in a row and you want to make * sure that only a code in, say the middle quarter is read not codes * above or below */ area?: { /** * @default "0%", set this and bottom to 25% if you only want to * read a 'line' that is in the middle quarter */ top?: string; /** * @default "0%" */ right?: string; /** * @default "0%" */ left?: string; /** * @default "0%", set this and top to 50% if you only want to read a * 'line' that is in the middle half */ bottom?: string; }; singleChannel?: boolean; size?: number; sequence?: boolean; }; /** * @default false */ debug?: boolean; /** * @default true */ locate?: boolean; /** * @default 4 */ numOfWorkers?: number; /** * This top-level property controls the scan-frequency of the video-stream. * It’s optional and defines the maximum number of scans per second. * This renders useful for cases where the scan-session is long-running and * resources such as CPU power are of concern. */ frequency?: number; decoder?: { /** * @default [ "code_128_reader" ] */ readers?: (QuaggaJSReaderConfig | string)[]; debug?: { /** * @default false */ drawBoundingBox?: boolean; /** * @default false */ showFrequency?: boolean; /** * @default false */ drawScanline?: boolean; /** * @default false */ showPattern?: boolean; }; /** * The multiple property tells the decoder if it should continue decoding after finding a valid barcode. * If multiple is set to true, the results will be returned as an array of result objects. * Each object in the array will have a box, and may have a codeResult * depending on the success of decoding the individual box. */ multiple?: boolean; }; locator?: { /** * @default true */ halfSample?: boolean; /** * @default "medium" * Available values: x-small, small, medium, large, x-large */ patchSize?: string; debug?: { /** * @default false */ showCanvas?: boolean; /** * @default false */ showPatches?: boolean; /** * @default false */ showFoundPatches?: boolean; /** * @default false */ showSkeleton?: boolean; /** * @default false */ showLabels?: boolean; /** * @default false */ showPatchLabels?: boolean; /** * @default false */ showRemainingPatchLabels?: boolean; boxFromPatches?: { /** * @default false */ showTransformed?: boolean; /** * @default false */ showTransformedBox?: boolean; /** * @default false */ showBB?: boolean; }; } }; } interface QuaggaJSConstraints { /** * @default 640 */ width?: number; /** * @default 480 */ height?: number; /** * In cases where height/width does not suffice */ aspectRatio?: number /** * @default "environment" */ facingMode?: string; /** * Explicitly set the camera to the user's choice */ deviceId?: string } /** * Used for extending a reader with supplements (ex: EAN-2, EAN-5) */ interface QuaggaJSReaderConfig { format: string; config: { supplements: string[]; } }
the_stack
import { IFileManager, ReadArgs, SortOrder, SearchArgs, FileDragEventArgs, BeforeImageLoadEventArgs } from '../base/interface'; import * as CLS from '../base/classes'; import * as events from '../base/constant'; import { read, paste, Search, filter, Download, Delete } from '../common/operations'; import { getValue, setValue, isNullOrUndefined as isNOU, matches, select, createElement, Draggable } from '@syncfusion/ej2-base'; import { closest, DragEventArgs, detach } from '@syncfusion/ej2-base'; import { DataManager, Query } from '@syncfusion/ej2-data'; import { MenuEventArgs } from '@syncfusion/ej2-navigations'; import { createDialog } from '../pop-up/dialog'; /** * Utility file for common actions * * @param {HTMLLIElement} node - specifies the node. * @param {Object} data - specifies the data. * @param {IFileManager} instance - specifies the control instance. * @returns {void} * @private */ // eslint-disable-next-line export function updatePath(node: HTMLLIElement, data: Object, instance: IFileManager): void { const text: string = getValue('name', data); const id: string = node.getAttribute('data-id'); const newText: string = isNOU(id) ? text : id; instance.setProperties({ path: getPath(node, newText, instance.hasId) }, true); instance.pathId = getPathId(node); instance.pathNames = getPathNames(node, text); } /** * Functions for get path in FileManager * * @param {Element | Node} element - specifies the element. * @param {string} text - specifies the text. * @param {boolean} hasId - specifies the id. * @returns {string} returns the path. * @private */ export function getPath(element: Element | Node, text: string, hasId: boolean): string { const matched: string[] = getParents(<Element>element, text, false, hasId); let path: string = hasId ? '' : '/'; const len: number = matched.length - (hasId ? 1 : 2); for (let i: number = len; i >= 0; i--) { path += matched[i] + '/'; } return path; } /** * Functions for get path id in FileManager * * @param {Element} node - specifies the node element. * @returns {string[]} returns the path ids. * @private */ export function getPathId(node: Element): string[] { const matched: string[] = getParents(node, node.getAttribute('data-uid'), true); const ids: string[] = []; for (let i: number = matched.length - 1; i >= 0; i--) { ids.push(matched[i]); } return ids; } /** * Functions for get path names in FileManager * * @param {Element} element - specifies the node element. * @param {string} text - specifies the text. * @returns {string[]} returns the path names. * @private */ export function getPathNames(element: Element, text: string): string[] { const matched: string[] = getParents(element, text, false); const names: string[] = []; for (let i: number = matched.length - 1; i >= 0; i--) { names.push(matched[i]); } return names; } /** * Functions for get path id in FileManager * * @param {Element} element - specifies the node element. * @param {string} text - specifies the text. * @param {boolean} isId - specifies the id. * @param {boolean} hasId - checks the id exists. * @returns {string[]} returns parent element. * @private */ export function getParents(element: Element, text: string, isId: boolean, hasId?: boolean): string[] { const matched: string[] = [text]; let el: Element = <Element>element.parentNode; while (!isNOU(el)) { if (matches(el, '.' + CLS.LIST_ITEM)) { const parentText: string = isId ? el.getAttribute('data-uid') : (hasId ? el.getAttribute('data-id') : select('.' + CLS.LIST_TEXT, el).textContent); matched.push(parentText); } el = <Element>el.parentNode; if (el.classList.contains(CLS.TREE_VIEW)) { break; } } return matched; } /** * Functions for generate path * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function generatePath(parent: IFileManager): void { const key: string = parent.hasId ? 'id' : 'name'; let newPath: string = parent.hasId ? '' : '/'; let i: number = parent.hasId ? 0 : 1; for (i; i < parent.pathId.length; i++) { // eslint-disable-next-line const data: Object = getValue(parent.pathId[i], parent.feParent); newPath += getValue(key, data) + '/'; } parent.setProperties({ path: newPath }, true); } /** * Functions for remove active element * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function removeActive(parent: IFileManager): void { if (parent.isCut) { removeBlur(parent); parent.selectedNodes = []; parent.actionRecords = []; parent.enablePaste = false; parent.notify(events.hidePaste, {}); } } /** * Selects active element in File Manager * * @param {string} action - specifies the action. * @param {IFileManager} parent - specifies the parent element. * @returns {boolean} - returns active element. * @private */ export function activeElement(action: string, parent: IFileManager): boolean { parent.isSearchCut = false; parent.actionRecords = []; parent.activeElements = []; parent.notify(events.cutCopyInit, {}); if (parent.activeElements.length === 0) { return false; } removeBlur(parent); const blurEle: Element[] = parent.activeElements; if (parent.activeModule !== 'navigationpane') { parent.targetPath = parent.path; } else { parent.targetPath = getParentPath(parent.path); } let i: number = 0; if (blurEle) { getModule(parent, blurEle[0]); if (action === 'cut') { while (i < blurEle.length) { addBlur(blurEle[i]); i++; } } } i = 0; parent.selectedNodes = []; parent.enablePaste = true; parent.notify(events.showPaste, {}); while (i < parent.activeRecords.length) { parent.actionRecords.push(parent.activeRecords[i]); parent.selectedNodes.push(getValue('name', parent.activeRecords[i])); i++; } if ((parent.breadcrumbbarModule.searchObj.element.value !== '' || parent.isFiltered) && parent.activeModule !== 'navigationpane') { parent.selectedNodes = []; parent.isSearchCut = true; let i: number = 0; while (i < parent.selectedItems.length) { parent.selectedNodes.push(parent.selectedItems[i]); i++; } } return true; } /** * Adds blur to the elements * * @param {Element} nodes - specifies the nodes. * @returns {void} * @private */ export function addBlur(nodes: Element): void { nodes.classList.add(CLS.BLUR); } /** * Removes blur from elements * * @param {IFileManager} parent - specifies the parent element. * @param {string} hover - specifies the hover string. * @returns {void} * @private */ export function removeBlur(parent?: IFileManager, hover?: string): void { const blurEle: NodeListOf<Element> = (!hover) ? parent.element.querySelectorAll('.' + CLS.BLUR) : parent.element.querySelectorAll('.' + CLS.HOVER); let i: number = 0; while (i < blurEle.length) { blurEle[i].classList.remove((!hover) ? CLS.BLUR : CLS.HOVER); i++; } } /** * Gets module name * * @param {IFileManager} parent - specifies the parent element. * @param {Element} element - specifies the element. * @returns {void} * @private */ export function getModule(parent: IFileManager, element: Element): void { if (element) { if (element.classList.contains(CLS.ROW)) { parent.activeModule = 'detailsview'; } else if (closest(element, '.' + CLS.LARGE_ICON)) { parent.activeModule = 'largeiconsview'; } else { parent.activeModule = 'navigationpane'; } } } /** * Gets module name * * @param {IFileManager} parent - specifies the parent element. * @param {string} value - specifies the value. * @param {boolean} isLayoutChange - specifies the layout change. * @returns {void} * @private */ export function searchWordHandler(parent: IFileManager, value: string, isLayoutChange: boolean): void { let searchWord: string; if (value.length === 0 && !parent.isFiltered) { parent.notify(events.pathColumn, { args: parent }); } if (parent.searchSettings.filterType === 'startsWith') { searchWord = value + '*'; } else if (parent.searchSettings.filterType === 'endsWith') { searchWord = '*' + value; } else { searchWord = '*' + value + '*'; } parent.searchWord = searchWord; parent.itemData = [getPathObject(parent)]; if (value.length > 0) { const caseSensitive: boolean = parent.searchSettings.ignoreCase; const hiddenItems: boolean = parent.showHiddenItems; Search(parent, isLayoutChange ? events.layoutChange : events.search, parent.path, searchWord, hiddenItems, !caseSensitive); } else { if (!parent.isFiltered) { read(parent, isLayoutChange ? events.layoutChange : events.search, parent.path); } else { filter(parent, events.layoutChange); } } } /** * Gets updated layout * * @param {IFileManager} parent - specifies the parent element. * @param {string} view - specifies the view. * @returns {void} * @private */ export function updateLayout(parent: IFileManager, view: string): void { parent.setProperties({ view: view }, true); if (parent.breadcrumbbarModule.searchObj.element.value !== '' || parent.isFiltered) { parent.layoutSelectedItems = parent.selectedItems; } let searchWord: string = ''; if (parent.breadcrumbbarModule.searchObj.element.value) { searchWord = parent.breadcrumbbarModule.searchObj.element.value; } parent.isLayoutChange = true; searchWordHandler(parent, searchWord, true); } /* istanbul ignore next */ /** * Gets updated layout * * @param {IFileManager} parent - specifies the parent element. * @param {Element} element - specifies the element. * @returns {void} * @private */ export function getTargetModule(parent: IFileManager, element: Element): void { let tartgetModule: string = ''; if (element) { if (closest(element, '.e-gridcontent')) { tartgetModule = 'detailsview'; } else if (closest(element, '.' + CLS.LARGE_ICONS)) { tartgetModule = 'largeiconsview'; } else if (element.classList.contains('e-fullrow') || element.classList.contains('e-icon-expandable')) { tartgetModule = 'navigationpane'; } else if (closest(element, '.e-address-list-item')) { tartgetModule = 'breadcrumbbar'; } else { tartgetModule = ''; } } parent.targetModule = tartgetModule; } /* istanbul ignore next */ /** * refresh the layout * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function refresh(parent: IFileManager): void { parent.itemData = [getPathObject(parent)]; if (!hasReadAccess(parent.itemData[0])) { createDeniedDialog(parent, parent.itemData[0], events.permissionRead); } else { read(parent, events.refreshEnd, parent.path); } } /** * open action in the layout * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function openAction(parent: IFileManager): void { read(parent, events.openEnd, parent.path); } /** * open action in the layout * * @param {IFileManager} parent - specifies the parent element. * @returns {Object} - returns the path data. * @private */ // eslint-disable-next-line export function getPathObject(parent: IFileManager): Object { return getValue(parent.pathId[parent.pathId.length - 1], parent.feParent); } /** * Copy files * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function copyFiles(parent: IFileManager): void { if (!activeElement('copy', parent)) { return; } else { parent.fileAction = 'copy'; } } /** * Cut files * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function cutFiles(parent: IFileManager): void { if (!activeElement('cut', parent)) { return; } else { parent.isCut = true; parent.fileAction = 'move'; } } /** * To add class for fileType * * @param {Object} file - specifies the file. * @returns {string} - returns the file type. * @private */ // eslint-disable-next-line export function fileType(file: Object): string { const isFile: string = getValue('isFile', file); if (!isFile) { return CLS.FOLDER; } const imageFormat: string[] = ['bmp', 'dib', 'jpg', 'jpeg', 'jpe', 'jfif', 'gif', 'tif', 'tiff', 'png', 'ico']; const audioFormat: string[] = ['mp3', 'wav', 'aac', 'ogg', 'wma', 'aif', 'fla', 'm4a']; const videoFormat: string[] = ['webm', 'mkv', 'flv', 'vob', 'ogv', 'ogg', 'avi', 'wmv', 'mp4', '3gp']; const knownFormat: string[] = ['css', 'exe', 'html', 'js', 'msi', 'pdf', 'pptx', 'ppt', 'rar', 'zip', 'txt', 'docx', 'doc', 'xlsx', 'xls', 'xml', 'rtf', 'php']; let filetype: string = getValue('type', file); filetype = filetype.toLowerCase(); if (filetype.indexOf('.') !== -1) { filetype = filetype.split('.').join(''); } let iconType: string; if (imageFormat.indexOf(filetype) !== -1) { iconType = CLS.ICON_IMAGE; } else if (audioFormat.indexOf(filetype) !== -1) { iconType = CLS.ICON_MUSIC; } else if (videoFormat.indexOf(filetype) !== -1) { iconType = CLS.ICON_VIDEO; } else if (knownFormat.indexOf(filetype) !== -1) { iconType = 'e-fe-' + filetype; } else { iconType = 'e-fe-unknown e-fe-' + filetype; } return iconType; } /* istanbul ignore next */ /** * To get the image URL * * @param {IFileManager} parent - specifies the parent element. * @param {Object} item - specifies the item. * @returns {string} - returns the image url. * @private */ // eslint-disable-next-line export function getImageUrl(parent: IFileManager, item: Object): string { const baseUrl: string = parent.ajaxSettings.getImageUrl ? parent.ajaxSettings.getImageUrl : parent.ajaxSettings.url; let imgUrl: string; const fileName: string = getValue('name', item); const fPath: string = getValue('filterPath', item); if (parent.hasId) { const imgId: string = getValue('id', item); imgUrl = baseUrl + '?path=' + parent.path + '&id=' + imgId; } else if (!isNOU(fPath)) { imgUrl = baseUrl + '?path=' + fPath.replace(/\\/g, '/') + fileName; } else { imgUrl = baseUrl + '?path=' + parent.path + fileName; } imgUrl = imgUrl + '&time=' + (new Date().getTime()).toString(); const eventArgs: BeforeImageLoadEventArgs = { fileDetails: [item], imageUrl: imgUrl }; parent.trigger('beforeImageLoad', eventArgs); return eventArgs.imageUrl; } /* istanbul ignore next */ /** * Gets the full path * * @param {IFileManager} parent - specifies the parent element. * @param {Object} data - specifies the data. * @param {string} path - specifies the path. * @returns {string} - returns the image url. * @private */ // eslint-disable-next-line export function getFullPath(parent: IFileManager, data: Object, path: string): string { const filePath: string = getValue(parent.hasId ? 'id' : 'name', data) + '/'; const fPath: string = getValue(parent.hasId ? 'filterId' : 'filterPath', data); if (!isNOU(fPath)) { return fPath.replace(/\\/g, '/') + filePath; } else { return path + filePath; } } /** * Gets the name * * @param {IFileManager} parent - specifies the parent element. * @param {Object} data - specifies the data. * @returns {string} - returns the name. * @private */ // eslint-disable-next-line export function getName(parent: IFileManager, data: Object): string { let name: string = getValue('name', data); let fPath: string = getValue('filterPath', data); if ((parent.breadcrumbbarModule.searchObj.element.value !== '' || parent.isFiltered) && !isNOU(fPath)) { fPath = fPath.replace(/\\/g, '/'); name = fPath.replace(parent.path, '') + name; } return name; } /** * Gets the name * * @param {IFileManager} parent - specifies the parent element. * @param {Object[]} items - specifies the item elements. * @returns {Object[]} - returns the sorted data. * @private */ // eslint-disable-next-line export function getSortedData(parent: IFileManager, items: Object[]): Object[] { if (items.length === 0) { return items; } let query: Query ; if (parent.sortOrder !== 'None') { query = new Query().sortBy(parent.sortBy, parent.sortOrder.toLowerCase(), true).group('isFile'); } else { query = new Query().group('isFile'); } // eslint-disable-next-line const lists: Object[] = new DataManager(items).executeLocal(query); return getValue('records', lists); } /** * Gets the data object * * @param {IFileManager} parent - specifies the parent element. * @param {string} key - specifies the key. * @param {string} value - specifies the value. * @returns {Object} - returns the sorted data. * @private */ // eslint-disable-next-line export function getObject(parent: IFileManager, key: string, value: string): Object { // eslint-disable-next-line const currFiles: Object[] = getValue(parent.pathId[parent.pathId.length - 1], parent.feFiles); const query: Query = new Query().where(key, 'equal', value); // eslint-disable-next-line const lists: Object[] = new DataManager(currFiles).executeLocal(query); return lists[0]; } /** * Creates empty element * * @param {IFileManager} parent - specifies the parent element. * @param {HTMLElement} element - specifies the element. * @param {ReadArgs | SearchArgs} args - specifies the args. * @returns {void} * @private */ export function createEmptyElement(parent: IFileManager, element: HTMLElement, args: ReadArgs | SearchArgs): void { let top: number; const layoutElement: Element = select('#' + parent.element.id + CLS.LAYOUT_ID, parent.element); const addressBarHeight: number = (<HTMLElement>select('#' + parent.element.id + CLS.BREADCRUMBBAR_ID, layoutElement)).offsetHeight; top = (<HTMLElement>layoutElement).offsetHeight - addressBarHeight; if (parent.view === 'Details') { top = top - (<HTMLElement>select('.' + CLS.GRID_HEADER, layoutElement)).offsetHeight; } if (isNOU(element.querySelector('.' + CLS.EMPTY))) { const emptyDiv: Element = createElement('div', { className: CLS.EMPTY }); const emptyFolder: Element = createElement('div', { className: CLS.LARGE_EMPTY_FOLDER }); const emptyEle: Element = createElement('div', { className: CLS.EMPTY_CONTENT }); const dragFile: Element = createElement('div', { className: CLS.EMPTY_INNER_CONTENT }); if (parent.view === 'Details') { element.querySelector('.' + CLS.GRID_VIEW).appendChild(emptyDiv); } else { element.appendChild(emptyDiv); } emptyDiv.appendChild(emptyFolder); emptyDiv.appendChild(emptyEle); emptyDiv.appendChild(dragFile); } if (element.querySelector('.' + CLS.EMPTY)) { if (!isNOU(args.error)) { element.querySelector('.' + CLS.EMPTY_CONTENT).innerHTML = getLocaleText(parent, 'Access-Denied'); element.querySelector('.' + CLS.EMPTY_INNER_CONTENT).innerHTML = getLocaleText(parent, 'Access-Details'); } else if (parent.isFiltered) { element.querySelector('.' + CLS.EMPTY_CONTENT).innerHTML = getLocaleText(parent, 'Filter-Empty'); element.querySelector('.' + CLS.EMPTY_INNER_CONTENT).innerHTML = getLocaleText(parent, 'Filter-Key'); } else if (parent.breadcrumbbarModule.searchObj.element.value !== '') { element.querySelector('.' + CLS.EMPTY_CONTENT).innerHTML = getLocaleText(parent, 'Search-Empty'); element.querySelector('.' + CLS.EMPTY_INNER_CONTENT).innerHTML = getLocaleText(parent, 'Search-Key'); } else { element.querySelector('.' + CLS.EMPTY_CONTENT).innerHTML = getLocaleText(parent, 'Folder-Empty'); element.querySelector('.' + CLS.EMPTY_INNER_CONTENT).innerHTML = getLocaleText(parent, 'File-Upload'); } } const eDiv: HTMLElement = <HTMLElement>select('.' + CLS.EMPTY, element); top = (top - eDiv.offsetHeight) / 2; eDiv.style.marginTop = top + 'px'; } /** * Gets the directories * * @param {Object[]} files - specifies the file object. * @returns {Object[]} - returns the sorted data. * @private */ // eslint-disable-next-line export function getDirectories(files: Object[]): Object[] { return new DataManager(files).executeLocal(new Query().where(events.isFile, 'equal', false, false)); } /** * set the Node ID * * @param {ReadArgs} result - specifies the result. * @param {string} rootId - specifies the rootId. * @returns {void} * @private */ export function setNodeId(result: ReadArgs, rootId: string): void { // eslint-disable-next-line const dirs: Object[] = getDirectories(result.files); for (let i: number = 0, len: number = dirs.length; i < len; i++) { setValue('_fm_id', rootId + '_' + i, dirs[i]); } } /** * set the date object * * @param {Object[]} args - specifies the file object. * @returns {void} * @private */ // eslint-disable-next-line export function setDateObject(args: Object[]): void { for (let i: number = 0; i < args.length; i++) { setValue('_fm_created', new Date(getValue('dateCreated', args[i])), args[i]); setValue('_fm_modified', new Date(getValue('dateModified', args[i])), args[i]); } } /** * get the locale text * * @param {IFileManager} parent - specifies the parent element. * @param {string} text - specifies the text. * @returns {string} - returns the locale text. * @private */ export function getLocaleText(parent: IFileManager, text: string): string { const locale: string = parent.localeObj.getConstant(text); return (locale === '') ? text : locale; } /** * get the CSS class * * @param {IFileManager} parent - specifies the parent element. * @param {string} css - specifies the css. * @returns {string} - returns the css classes. * @private */ export function getCssClass(parent: IFileManager, css: string): string { let cssClass: string = parent.cssClass; cssClass = (isNOU(cssClass) || cssClass === '') ? css : (cssClass + ' ' + css); return cssClass; } /** * sort on click * * @param {IFileManager} parent - specifies the parent element. * @param {MenuEventArgs} args - specifies the menu event arguements. * @returns {void} * @private */ export function sortbyClickHandler(parent: IFileManager, args: MenuEventArgs): void { let tick: boolean; if (args.item.id.indexOf('ascending') !== -1 || args.item.id.indexOf('descending') !== -1 || args.item.id.indexOf('none') !== -1) { tick = true; } else { tick = false; } if (!tick) { parent.sortBy = getSortField(args.item.id); } else { parent.sortOrder = <SortOrder>getSortField(args.item.id); } parent.itemData = [getPathObject(parent)]; if (parent.view === 'Details') { if (parent.isMobile) { updateLayout(parent, 'Details'); } else { parent.notify(events.sortColumn, { module: 'detailsview' }); } } if (parent.view === 'LargeIcons') { updateLayout(parent, 'LargeIcons'); } parent.notify(events.sortByChange, {}); } /** * Gets the sorted fields * * @param {string} id - specifies the id. * @returns {string} - returns the sorted fields * @private */ export function getSortField(id: string): string { const text: string = id.substring(id.lastIndexOf('_') + 1); let field: string = text; switch (text) { case 'date': field = '_fm_modified'; break; case 'ascending': field = 'Ascending'; break; case 'descending': field = 'Descending'; break; case 'none': field = 'None'; break; } return field; } /** * Sets the next path * * @param {IFileManager} parent - specifies the parent element. * @param {string} path - specifies the path. * @returns {void} * @private */ export function setNextPath(parent: IFileManager, path: string): void { const currfolders: string[] = path.split('/'); const folders: string[] = parent.originalPath.split('/'); // eslint-disable-next-line const root: Object = getValue(parent.pathId[0], parent.feParent); const key: string = isNOU(getValue('id', root)) ? 'name' : 'id'; for (let i: number = currfolders.length - 1, len: number = folders.length - 1; i < len; i++) { const eventName: string = (folders[i + 1] === '') ? events.finalizeEnd : events.initialEnd; const newPath: string = (folders[i] === '') ? '/' : (parent.path + folders[i] + '/'); // eslint-disable-next-line const data: Object = getObject(parent, key, folders[i]); const id: string = getValue('_fm_id', data); parent.setProperties({ path: newPath }, true); parent.pathId.push(id); parent.itemData = [data]; parent.pathNames.push(getValue('name', data)); read(parent, eventName, parent.path); break; } } /** * Opens the searched folder * * @param {IFileManager} parent - specifies the parent element. * @param {Object} data - specifies the data * @returns {void} * @private */ // eslint-disable-next-line export function openSearchFolder(parent: IFileManager, data: Object): void { parent.notify(events.clearPathInit, { selectedNode: parent.pathId[parent.pathId.length - 1] }); parent.originalPath = getFullPath(parent, data, parent.path); read(parent, (parent.path !== parent.originalPath) ? events.initialEnd : events.finalizeEnd, parent.path); } /** * Paste handling function * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function pasteHandler(parent: IFileManager): void { parent.isDragDrop = false; if (parent.selectedNodes.length !== 0 && parent.enablePaste) { const path: string = (parent.folderPath === '') ? parent.path : parent.folderPath; // eslint-disable-next-line const subFolder: boolean = validateSubFolder(parent, <{ [key: string]: Object; }[]>parent.actionRecords, path, parent.path); if (!subFolder) { if ((parent.fileAction === 'move' && parent.targetPath !== path) || parent.fileAction === 'copy') { parent.notify(events.pasteInit, {}); paste( parent, parent.targetPath, parent.selectedNodes, path, parent.fileAction, [], parent.actionRecords); } else { parent.enablePaste = false; parent.notify(events.hidePaste, {}); removeBlur(parent); } } } } /** * Validates the sub folders * * @param {IFileManager} parent - specifies the parent element. * @param {'{ [key: string]: Object; }[]'} data - specifies the data. * @param {string} dropPath - specifies the drop path. * @param {string} dragPath - specifies the drag path. * @returns {boolean} - returns the validated sub folder. * @private */ // eslint-disable-next-line export function validateSubFolder(parent: IFileManager, data: { [key: string]: Object; }[], dropPath: string, dragPath: string): boolean { let subFolder: boolean = false; for (let i: number = 0; i < data.length; i++) { if (!getValue('isFile', data[i])) { const tempTarget: string = getFullPath(parent, data[i], dragPath); if (dropPath.indexOf(tempTarget) === 0) { const result: ReadArgs = { files: null, error: { code: '402', message: getLocaleText(parent, 'Sub-Folder-Error'), fileExists: null } }; createDialog(parent, 'Error', result); subFolder = true; break; } } else { const srcData: string = parent.dragNodes[i]; let len: number = 0; if (srcData) { len = srcData.lastIndexOf('/'); } let path: string = ''; if (len > 0) { path = dragPath + srcData.substring(0, len + 1); } if (path === dropPath) { const result: ReadArgs = { files: null, error: { code: '402', message: getLocaleText(parent, 'Same-Folder-Error'), fileExists: null } }; createDialog(parent, 'Error', result); subFolder = true; break; } } } return subFolder; } /** * Validates the drop handler * * @param {IFileManager} parent - specifies the parent element. * @returns {void} * @private */ export function dropHandler(parent: IFileManager): void { parent.isDragDrop = true; if (parent.dragData.length !== 0) { parent.dragPath = parent.dragPath.replace(/\\/g, '/'); parent.dropPath = parent.dropPath.replace(/\\/g, '/'); const subFolder: boolean = validateSubFolder(parent, parent.dragData, parent.dropPath, parent.dragPath); if (!subFolder && (parent.dragPath !== parent.dropPath)) { parent.itemData = [parent.dropData]; paste( parent, parent.dragPath, parent.dragNodes, parent.dropPath, 'move', [], parent.dragData); parent.notify(events.pasteInit, {}); } } } /** * Gets the parent path * * @param {string} oldPath - specifies the old path. * @returns {string} - returns the parent path. * @private */ export function getParentPath(oldPath: string): string { const path: string[] = oldPath.split('/'); let newPath: string = path[0] + '/'; for (let i: number = 1; i < path.length - 2; i++) { newPath += path[i] + '/'; } return newPath; } /** * Gets the directory path * * @param {IFileManager} parent - specifies the parent. * @param {ReadArgs} args - returns the read arguements. * @returns {string} - returns the directory path * @private */ export function getDirectoryPath(parent: IFileManager, args: ReadArgs): string { const filePath: string = getValue(parent.hasId ? 'id' : 'name', args.cwd) + '/'; const fPath: string = getValue(parent.hasId ? 'filterId' : 'filterPath', args.cwd); if (!isNOU(fPath)) { if (fPath === '') { return parent.hasId ? filePath : '/'; } return fPath.replace(/\\/g, '/') + filePath; } else { return parent.path + filePath; } } /** * Gets the do paste path * * @param {IFileManager} parent - specifies the parent. * @param {string} operation - specifies the operations. * @param {ReadArgs} result - returns the result. * @returns {void} * @private */ export function doPasteUpdate(parent: IFileManager, operation: string, result: ReadArgs): void { if (operation === 'move') { if (!parent.isDragDrop) { parent.enablePaste = false; parent.notify(events.hidePaste, {}); parent.notify(events.cutEnd, result); } else { parent.notify(events.dragEnd, result); } } if (parent.duplicateItems.length === 0) { parent.pasteNodes = []; } const flag: boolean = false; for (let count: number = 0; (count < result.files.length) && !flag; count++) { parent.pasteNodes.push(<string>result.files[count][parent.hasId ? 'id' : 'name']); if (parent.isDragDrop) { parent.droppedObjects.push(result.files[count]); } } parent.duplicateItems = []; parent.duplicateRecords = []; if (parent.isDragDrop && !parent.isPasteError) { parent.isDropEnd = true; } else { parent.isDropEnd = false; } if (!parent.isDragDrop || (parent.path === parent.dragPath) || (parent.path === parent.dropPath) || parent.isSearchDrag) { parent.isPathDrag = false; read(parent, events.pasteEnd, parent.path); } else { readDropPath(parent); } parent.trigger('success', { action: operation, result: result }); } /** * Reads the drop path * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function readDropPath(parent: IFileManager): void { const pathId: string = getValue('_fm_id', parent.dropData); parent.expandedId = pathId; parent.itemData = [parent.dropData]; if (parent.isPathDrag) { parent.notify(events.pathDrag, parent.itemData); } else { if (parent.navigationpaneModule) { const node: Element = select('[data-uid="' + pathId + '"]', parent.navigationpaneModule.treeObj.element); updatePath(<HTMLLIElement>node, parent.dropData, parent); } read(parent, events.dropPath, parent.dropPath); } } /** * Gets the duplicated path * * @param {IFileManager} parent - specifies the parent. * @param {string} name - specifies the name. * @returns {object} - returns the duplicated path. * @private */ // eslint-disable-next-line export function getDuplicateData(parent: IFileManager, name: string): object { // eslint-disable-next-line let data: object = null; // eslint-disable-next-line const records: object[] = parent.isDragDrop ? parent.dragData : parent.actionRecords; for (let i: number = 0; i < records.length; i++) { if (getValue('name', records[i]) === name) { data = records[i]; break; } } return data; } /** * Gets the create the virtual drag element * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function createVirtualDragElement(parent: IFileManager): void { parent.isSearchDrag = false; if (parent.breadcrumbbarModule.searchObj.element.value !== '') { parent.isSearchDrag = true; } if (parent.activeModule !== 'navigationpane') { parent.dragNodes = []; let i: number = 0; while (i < parent.selectedItems.length) { parent.dragNodes.push(parent.selectedItems[i]); i++; } if (parent.selectedItems.length == 0 && parent.dragData && parent.dragData.length == 1) { parent.dragNodes.push(getItemName(parent, parent.dragData[0])); } } const cloneIcon: HTMLElement = parent.createElement('div', { className: 'e-fe-icon ' + fileType(parent.dragData[0]) }); const cloneName: HTMLElement = parent.createElement('div', { className: 'e-fe-name', innerHTML: <string>parent.dragData[0].name }); const virtualEle: HTMLElement = parent.createElement('div', { className: 'e-fe-content' }); virtualEle.appendChild(cloneIcon); virtualEle.appendChild(cloneName); const ele: HTMLElement = parent.createElement('div', { className: CLS.CLONE }); ele.appendChild(virtualEle); if (parent.dragNodes.length > 1) { const badge: HTMLElement = parent.createElement('span', { className: 'e-fe-count', innerHTML: (parent.dragNodes.length).toString(10) }); ele.appendChild(badge); } parent.virtualDragElement = ele; parent.element.appendChild(parent.virtualDragElement); } /** * Drops the stop handler * * @param {IFileManager} parent - specifies the parent. * @param {DragEventArgs} args - specifies the drag event arguements. * @returns {void} * @private */ export function dragStopHandler(parent: IFileManager, args: DragEventArgs): void { const dragArgs: FileDragEventArgs = args; dragArgs.cancel = false; if (parent.treeExpandTimer != null) { window.clearTimeout(parent.treeExpandTimer); parent.treeExpandTimer = null; } removeDropTarget(parent); parent.element.classList.remove('e-fe-drop', 'e-no-drop'); removeBlur(parent); parent.uploadObj.dropArea = <HTMLElement>select('#' + parent.element.id + CLS.CONTENT_ID, parent.element); const virtualEle: Element = select('.' + CLS.CLONE, parent.element); if (virtualEle) { detach(virtualEle); } getTargetModule(parent, args.target); parent.notify(events.dropInit, args); removeBlur(parent, 'hover'); dragArgs.fileDetails = parent.dragData; parent.trigger('fileDragStop', dragArgs, (dragArgs: FileDragEventArgs) => { if (!dragArgs.cancel && !isNOU(parent.targetModule) && parent.targetModule !== '' && parent.dragCount > 2) { dropHandler(parent); } parent.dragCount = 0; }); } /** * Drag the start handler * * @param {IFileManager} parent - specifies the parent. * @param {'DragEventArgs'} args - specifies the drag event arguements. * @param {Draggable} dragObj - specifies the drag event arguements. * @returns {void} * @private */ export function dragStartHandler(parent: IFileManager, args: DragEventArgs, dragObj: Draggable): void { const dragArgs: FileDragEventArgs = args; dragArgs.cancel = false; dragArgs.fileDetails = parent.dragData; parent.dragCount = 0; parent.droppedObjects = []; if (!parent.allowDragAndDrop || ((parent.activeModule === 'navigationpane') && (closest(args.element, 'li').getAttribute('data-uid') === parent.pathId[0]))) { dragArgs.cancel = true; } if ((parent.activeModule === 'navigationpane') && (parent.pathId.indexOf(closest(args.element, 'li').getAttribute('data-uid')) !== -1)) { parent.isPathDrag = true; } else { parent.isPathDrag = false; } removeBlur(parent); if (dragArgs.cancel) { dragObj.intDestroy(args.event); dragCancel(parent); } else if (!dragArgs.cancel) { let i: number = 0; while (i < parent.activeElements.length) { addBlur(parent.activeElements[i]); i++; } parent.trigger('fileDragStart', dragArgs, (dragArgs: FileDragEventArgs) => { if (dragArgs.cancel) { dragObj.intDestroy(args.event); dragCancel(parent); } else { parent.uploadObj.dropArea = null; } }); } } /** * Drag the cancel handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function dragCancel(parent: IFileManager): void { removeBlur(parent); const virtualEle: Element = select('.' + CLS.CLONE, parent.element); if (virtualEle) { detach(virtualEle); } } /** * Remove drop target handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function removeDropTarget(parent: IFileManager): void { removeItemClass(parent, CLS.DROP_FOLDER); removeItemClass(parent, CLS.DROP_FILE); } /** * Remove item class handler * * @param {IFileManager} parent - specifies the parent. * @param {string} value - specifies the value. * @returns {void} * @private */ export function removeItemClass(parent: IFileManager, value: string): void { const ele: NodeListOf<Element> = parent.element.querySelectorAll('.' + value); for (let i: number = 0; i < ele.length; i++) { ele[i].classList.remove(value); } } /** * Dragging handler * * @param {IFileManager} parent - specifies the parent. * @param {DragEventArgs} args - specifies the arguements. * @returns {void} * @private */ export function draggingHandler(parent: IFileManager, args: DragEventArgs): void { const dragArgs: FileDragEventArgs = args; dragArgs.fileDetails = parent.dragData; let canDrop: boolean = false; getTargetModule(parent, args.target); removeDropTarget(parent); if (parent.treeExpandTimer != null) { window.clearTimeout(parent.treeExpandTimer); parent.treeExpandTimer = null; } removeBlur(parent, 'hover'); let node: Element = null; if (parent.targetModule === 'navigationpane') { node = closest(args.target, 'li'); node.classList.add(CLS.HOVER, CLS.DROP_FOLDER); canDrop = true; /* istanbul ignore next */ parent.treeExpandTimer = window.setTimeout(() => { parent.notify(events.dragging, args); }, 800); } else if (parent.targetModule === 'detailsview') { node = closest(args.target, 'tr'); if (node && node.querySelector('.' + CLS.FOLDER) && !node.classList.contains(CLS.BLUR)) { node.classList.add(CLS.DROP_FOLDER); } else if (node && !node.querySelector('.' + CLS.FOLDER) && !node.classList.contains(CLS.BLUR)) { node.classList.add(CLS.DROP_FILE); } canDrop = true; } else if (parent.targetModule === 'largeiconsview') { node = closest(args.target, 'li'); if (node && node.querySelector('.' + CLS.FOLDER) && !node.classList.contains(CLS.BLUR)) { node.classList.add(CLS.HOVER, CLS.DROP_FOLDER); } canDrop = true; /* istanbul ignore next */ } else if (parent.targetModule === 'breadcrumbbar') { canDrop = true; } parent.element.classList.remove('e-fe-drop', 'e-no-drop'); parent.element.classList.add(canDrop ? 'e-fe-drop' : 'e-no-drop'); parent.dragCount = parent.dragCount + 1; parent.trigger('fileDragging', dragArgs); } /** * Object to string handler * * @param {Object} data - specifies the data. * @returns {string} returns string converted from Object. * @private */ // Ignored the message key value in permission object // eslint-disable-next-line export function objectToString(data: Object): string { let str: string = ''; const keys: string[] = Object.keys(data); for (let i: number = 0; i < keys.length; i++) { if (keys[i] !== 'message') { str += (i === 0 ? '' : ', ') + keys[i] + ': ' + getValue(keys[i], data); } } return str; } /** * Get item name handler * * @param {IFileManager} parent - specifies the parent. * @param {Object} data - specifies the data. * @returns {string} returns the item name. * @private */ // eslint-disable-next-line export function getItemName(parent: IFileManager, data: Object): string { if (parent.hasId) { return getValue('id', data); } return getName(parent, data); } /** * Get item name handler * * @param {IFileManager} parent - specifies the parent. * @param {Object} data - specifies the data. * @returns {void} * @private */ // eslint-disable-next-line export function updateRenamingData(parent: IFileManager, data: Object): void { parent.itemData = [data]; parent.currentItemText = getValue('name', data); parent.isFile = getValue('isFile', data); parent.filterPath = getValue('filterPath', data); } /** * Get item name handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function doRename(parent: IFileManager): void { if (!hasEditAccess(parent.itemData[0])) { createDeniedDialog(parent, parent.itemData[0], events.permissionEdit); } else { createDialog(parent, 'Rename'); } } /* istanbul ignore next */ /** * Download handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function doDownload(parent: IFileManager): void { // eslint-disable-next-line const items: Object[] = parent.itemData; for (let i: number = 0; i < items.length; i++) { if (!hasDownloadAccess(items[i])) { createDeniedDialog(parent, items[i], events.permissionDownload); return; } } if (parent.selectedItems.length > 0) { Download(parent, parent.path, parent.selectedItems); } } /** * Delete Files handler * * @param {IFileManager} parent - specifies the parent. * @param {Object[]} data - specifies the data. * @param {string[]} newIds - specifies the new Ids. * @returns {void} * @private */ // eslint-disable-next-line export function doDeleteFiles(parent: IFileManager, data: Object[], newIds: string[]): void { for (let i: number = 0; i < data.length; i++) { if (!hasEditAccess(data[i])) { createDeniedDialog(parent, data[i], events.permissionEdit); return; } } parent.itemData = data; Delete(parent, newIds, parent.path, 'delete'); } /* istanbul ignore next */ /** * Download files handler * * @param {IFileManager} parent - specifies the parent. * @param {Object[]} data - specifies the data. * @param {string[]} newIds - specifies the new Ids. * @returns {void} * @private */ // eslint-disable-next-line export function doDownloadFiles(parent: IFileManager, data: Object[], newIds: string[]): void { for (let i: number = 0; i < data.length; i++) { if (!hasDownloadAccess(data[i])) { createDeniedDialog(parent, data[i], events.permissionDownload); return; } } parent.itemData = data; if (newIds.length > 0) { Download(parent, parent.path, newIds); } } /** * Download files handler * * @param {IFileManager} parent - specifies the parent. * @param {Object} data - specifies the data. * @param {string} action - specifies the actions. * @returns {void} * @private */ // eslint-disable-next-line export function createDeniedDialog(parent: IFileManager, data: Object, action: string): void { let message: string = getValue('message', getValue('permission', data)); if (message === '') { message = getLocaleText(parent, 'Access-Message').replace('{0}', getValue('name', data)).replace('{1}', action); } const response: ReadArgs = { error: { code: '401', fileExists: null, message: message } }; createDialog(parent, 'Error', response); } /** * Get Access Classes * * @param {Object} data - specifies the data. * @returns {string} - returns accesses classes. * @private */ // eslint-disable-next-line export function getAccessClass(data: Object): string { return !hasReadAccess(data) ? 'e-fe-locked e-fe-hidden' : 'e-fe-locked'; } /** * Check read access handler * * @param {Object} data - specifies the data. * @returns {boolean} - returns read access. * @private */ // eslint-disable-next-line export function hasReadAccess(data: Object): boolean { // eslint-disable-next-line const permission: Object = getValue('permission', data); return (permission && !getValue('read', permission)) ? false : true; } /** * Check edit access handler * * @param {Object} data - specifies the data. * @returns {boolean} - returns edit access. * @private */ // eslint-disable-next-line export function hasEditAccess(data: Object): boolean { // eslint-disable-next-line const permission: Object = getValue('permission', data); return permission ? ((getValue('read', permission) && getValue('write', permission))) : true; } /** * Check content access handler * * @param {Object} data - specifies the data. * @returns {boolean} - returns content access. * @private */ // eslint-disable-next-line export function hasContentAccess(data: Object): boolean { // eslint-disable-next-line const permission: Object = getValue('permission', data); return permission ? ((getValue('read', permission) && getValue('writeContents', permission))) : true; } /** * Check upload access handler * * @param {Object} data - specifies the data. * @returns {boolean} - returns upload access. * @private */ // eslint-disable-next-line export function hasUploadAccess(data: Object): boolean { // eslint-disable-next-line const permission: Object = getValue('permission', data); return permission ? ((getValue('read', permission) && getValue('upload', permission))) : true; } /** * Check download access handler * * @param {Object} data - specifies the data. * @returns {boolean} - returns download access. * @private */ // eslint-disable-next-line export function hasDownloadAccess(data: Object): boolean { // eslint-disable-next-line const permission: Object = getValue('permission', data); return permission ? ((getValue('read', permission) && getValue('download', permission))) : true; } /** * Create new folder handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function createNewFolder(parent: IFileManager): void { // eslint-disable-next-line const details: Object = parent.itemData[0]; if (!hasContentAccess(details)) { createDeniedDialog(parent, details, events.permissionEditContents); } else { createDialog(parent, 'NewFolder'); } } /** * Upload item handler * * @param {IFileManager} parent - specifies the parent. * @returns {void} * @private */ export function uploadItem(parent: IFileManager): void { // eslint-disable-next-line const details: Object = parent.itemData[0]; if (!hasUploadAccess(details)) { createDeniedDialog(parent, details, events.permissionUpload); } else { const eleId: string = '#' + parent.element.id + CLS.UPLOAD_ID; const uploadEle: HTMLElement = document.querySelector(eleId); uploadEle.click(); } }
the_stack
// import com.google.zxing.FormatException; import FormatException from '../../FormatException'; // import com.google.zxing.common.CharacterSetECI; import CharacterSetECI from '../../common/CharacterSetECI'; // import com.google.zxing.common.DecoderResult; import DecoderResult from '../../common/DecoderResult'; // import com.google.zxing.pdf417.PDF417ResultMetadata; import PDF417ResultMetadata from '../PDF417ResultMetadata'; // import java.io.ByteArrayOutputStream; // import java.math.BigInteger; // import java.nio.charset.Charset; // import java.nio.charset.StandardCharsets; // import java.util.Arrays; import Arrays from '../../util/Arrays'; import StringBuilder from '../../util/StringBuilder'; import Integer from '../../util/Integer'; import Long from '../../util/Long'; import ByteArrayOutputStream from '../../util/ByteArrayOutputStream'; import StringEncoding from '../../util/StringEncoding'; import { int } from '../../../customTypings'; /*private*/ enum Mode { ALPHA, LOWER, MIXED, PUNCT, ALPHA_SHIFT, PUNCT_SHIFT } /** * Indirectly access the global BigInt constructor, it * allows browsers that doesn't support BigInt to run * the library without breaking due to "undefined BigInt" * errors. */ function getBigIntConstructor(): BigIntConstructor { if (typeof window !== 'undefined') { return window['BigInt'] || null; } if (typeof global !== 'undefined') { return global['BigInt'] || null; } if (typeof self !== 'undefined') { return self['BigInt'] || null; } throw new Error('Can\'t search globals for BigInt!'); } /** * Used to store the BigInt constructor. */ let BigInteger: BigIntConstructor; /** * This function creates a bigint value. It allows browsers * that doesn't support BigInt to run the rest of the library * by not directly accessing the BigInt constructor. */ function createBigInt(num: number | string | bigint): bigint { if (typeof BigInteger === 'undefined') { BigInteger = getBigIntConstructor(); } if (BigInteger === null) { throw new Error('BigInt is not supported!'); } return BigInteger(num); } function getEXP900(): bigint[] { // in Java - array with length = 16 let EXP900 = []; EXP900[0] = createBigInt(1); let nineHundred = createBigInt(900); EXP900[1] = nineHundred; // in Java - array with length = 16 for (let i /*int*/ = 2; i < 16; i++) { EXP900[i] = EXP900[i - 1] * nineHundred; } return EXP900; } /** * <p>This class contains the methods for decoding the PDF417 codewords.</p> * * @author SITA Lab (kevin.osullivan@sita.aero) * @author Guenther Grau */ export default /*final*/ class DecodedBitStreamParser { private static /*final*/ TEXT_COMPACTION_MODE_LATCH: int = 900; private static /*final*/ BYTE_COMPACTION_MODE_LATCH: int = 901; private static /*final*/ NUMERIC_COMPACTION_MODE_LATCH: int = 902; private static /*final*/ BYTE_COMPACTION_MODE_LATCH_6: int = 924; private static /*final*/ ECI_USER_DEFINED: int = 925; private static /*final*/ ECI_GENERAL_PURPOSE: int = 926; private static /*final*/ ECI_CHARSET: int = 927; private static /*final*/ BEGIN_MACRO_PDF417_CONTROL_BLOCK: int = 928; private static /*final*/ BEGIN_MACRO_PDF417_OPTIONAL_FIELD: int = 923; private static /*final*/ MACRO_PDF417_TERMINATOR: int = 922; private static /*final*/ MODE_SHIFT_TO_BYTE_COMPACTION_MODE: int = 913; private static /*final*/ MAX_NUMERIC_CODEWORDS: int = 15; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME: int = 0; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT: int = 1; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP: int = 2; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_SENDER: int = 3; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE: int = 4; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE: int = 5; private static /*final*/ MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM: int = 6; private static /*final*/ PL: int = 25; private static /*final*/ LL: int = 27; private static /*final*/ AS: int = 27; private static /*final*/ ML: int = 28; private static /*final*/ AL: int = 28; private static /*final*/ PS: int = 29; private static /*final*/ PAL: int = 29; private static /*final*/ PUNCT_CHARS: string = ';<>@[\\]_`~!\r\t,:\n-.$/"|*()?{}\''; private static /*final*/ MIXED_CHARS: string = '0123456789&\r\t,:#-.$/+%*=^'; /** * Table containing values for the exponent of 900. * This is used in the numeric compaction decode algorithm. */ private static /*final*/ EXP900: bigint[] = getBigIntConstructor() ? getEXP900() : []; private static /*final*/ NUMBER_OF_SEQUENCE_CODEWORDS: int = 2; // private DecodedBitStreamParser() { // } /** * * @param codewords * @param ecLevel * * @throws FormatException */ static decode(codewords: Int32Array, ecLevel: string): DecoderResult { // pass encoding to result (will be used for decode symbols in byte mode) let result: StringBuilder = new StringBuilder(''); // let encoding: Charset = StandardCharsets.ISO_8859_1; let encoding = CharacterSetECI.ISO8859_1; /** * @note the next command is specific from this TypeScript library * because TS can't properly cast some values to char and * convert it to string later correctly due to encoding * differences from Java version. As reported here: * https://github.com/zxing-js/library/pull/264/files#r382831593 */ result.enableDecoding(encoding); // Get compaction mode let codeIndex: int = 1; let code: int = codewords[codeIndex++]; let resultMetadata: PDF417ResultMetadata = new PDF417ResultMetadata(); while (codeIndex < codewords[0]) { switch (code) { case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, result); break; case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: codeIndex = DecodedBitStreamParser.byteCompaction(code, codewords, encoding, codeIndex, result); break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.append(/*(char)*/ codewords[codeIndex++]); break; case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH: codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex, result); break; case DecodedBitStreamParser.ECI_CHARSET: let charsetECI: CharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]); // encoding = Charset.forName(charsetECI.getName()); break; case DecodedBitStreamParser.ECI_GENERAL_PURPOSE: // Can't do anything with generic ECI; skip its 2 characters codeIndex += 2; break; case DecodedBitStreamParser.ECI_USER_DEFINED: // Can't do anything with user ECI; skip its 1 character codeIndex++; break; case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK: codeIndex = DecodedBitStreamParser.decodeMacroBlock(codewords, codeIndex, resultMetadata); break; case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: // Should not see these outside a macro block throw new FormatException(); default: // Default to text compaction. During testing numerous barcodes // appeared to be missing the starting mode. In these cases defaulting // to text compaction seems to work. codeIndex--; codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, result); break; } if (codeIndex < codewords.length) { code = codewords[codeIndex++]; } else { throw FormatException.getFormatInstance(); } } if (result.length() === 0) { throw FormatException.getFormatInstance(); } let decoderResult: DecoderResult = new DecoderResult(null, result.toString(), null, ecLevel); decoderResult.setOther(resultMetadata); return decoderResult; } /** * * @param int * @param param1 * @param codewords * @param int * @param codeIndex * @param PDF417ResultMetadata * @param resultMetadata * * @throws FormatException */ // @SuppressWarnings("deprecation") static decodeMacroBlock(codewords: Int32Array, codeIndex: int, resultMetadata: PDF417ResultMetadata): int { if (codeIndex + DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) { // we must have at least two bytes left for the segment index throw FormatException.getFormatInstance(); } let segmentIndexArray: Int32Array = new Int32Array(DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS); for (let i /*int*/ = 0; i < DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) { segmentIndexArray[i] = codewords[codeIndex]; } resultMetadata.setSegmentIndex(Integer.parseInt(DecodedBitStreamParser.decodeBase900toBase10(segmentIndexArray, DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS))); let fileId: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, fileId); resultMetadata.setFileId(fileId.toString()); let optionalFieldsStart: int = -1; if (codewords[codeIndex] === DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD) { optionalFieldsStart = codeIndex + 1; } while (codeIndex < codewords[0]) { switch (codewords[codeIndex]) { case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: codeIndex++; switch (codewords[codeIndex]) { case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME: let fileName: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, fileName); resultMetadata.setFileName(fileName.toString()); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SENDER: let sender: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, sender); resultMetadata.setSender(sender.toString()); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE: let addressee: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, addressee); resultMetadata.setAddressee(addressee.toString()); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT: let segmentCount: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, segmentCount); resultMetadata.setSegmentCount(Integer.parseInt(segmentCount.toString())); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP: let timestamp: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, timestamp); resultMetadata.setTimestamp(Long.parseLong(timestamp.toString())); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM: let checksum: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, checksum); resultMetadata.setChecksum(Integer.parseInt(checksum.toString())); break; case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE: let fileSize: StringBuilder = new StringBuilder(); codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, fileSize); resultMetadata.setFileSize(Long.parseLong(fileSize.toString())); break; default: throw FormatException.getFormatInstance(); } break; case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: codeIndex++; resultMetadata.setLastSegment(true); break; default: throw FormatException.getFormatInstance(); } } // copy optional fields to additional options if (optionalFieldsStart !== -1) { let optionalFieldsLength: int = codeIndex - optionalFieldsStart; if (resultMetadata.isLastSegment()) { // do not include terminator optionalFieldsLength--; } resultMetadata.setOptionalData(Arrays.copyOfRange(codewords, optionalFieldsStart, optionalFieldsStart + optionalFieldsLength)); } return codeIndex; } /** * Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be * encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as * well as selected control characters. * * @param codewords The array of codewords (data + error) * @param codeIndex The current index into the codeword array. * @param result The decoded data is appended to the result. * @return The next index into the codeword array. */ private static textCompaction(codewords: Int32Array, codeIndex: int, result: StringBuilder): int { // 2 character per codeword let textCompactionData: Int32Array = new Int32Array((codewords[0] - codeIndex) * 2); // Used to hold the byte compaction value if there is a mode shift let byteCompactionData: Int32Array = new Int32Array((codewords[0] - codeIndex) * 2); let index: int = 0; let end: boolean = false; while ((codeIndex < codewords[0]) && !end) { let code: int = codewords[codeIndex++]; if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) { textCompactionData[index] = code / 30; textCompactionData[index + 1] = code % 30; index += 2; } else { switch (code) { case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: // reinitialize text compaction mode to alpha sub mode textCompactionData[index++] = DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH; break; case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // The Mode Shift codeword 913 shall cause a temporary // switch from Text Compaction mode to Byte Compaction mode. // This switch shall be in effect for only the next codeword, // after which the mode shall revert to the prevailing sub-mode // of the Text Compaction mode. Codeword 913 is only available // in Text Compaction mode; its use is described in 5.4.2.4. textCompactionData[index] = DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE; code = codewords[codeIndex++]; byteCompactionData[index] = code; index++; break; } } } DecodedBitStreamParser.decodeTextCompaction(textCompactionData, byteCompactionData, index, result); return codeIndex; } /** * The Text Compaction mode includes all the printable ASCII characters * (i.e. values from 32 to 126) and three ASCII control characters: HT or tab * (9: e), LF or line feed (10: e), and CR or carriage * return (13: e). The Text Compaction mode also includes various latch * and shift characters which are used exclusively within the mode. The Text * Compaction mode encodes up to 2 characters per codeword. The compaction rules * for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode * switches are defined in 5.4.2.3. * * @param textCompactionData The text compaction data. * @param byteCompactionData The byte compaction data if there * was a mode shift. * @param length The size of the text compaction and byte compaction data. * @param result The decoded data is appended to the result. */ private static decodeTextCompaction(textCompactionData: Int32Array, byteCompactionData: Int32Array, length: int, result: StringBuilder): void { // Beginning from an initial state of the Alpha sub-mode // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text // Compaction mode Alpha sub-mode (alphabetic: uppercase). A latch codeword from another mode to the Text // Compaction mode shall always switch to the Text Compaction Alpha sub-mode. let subMode: Mode = Mode.ALPHA; let priorToShiftMode: Mode = Mode.ALPHA; let i: int = 0; while (i < length) { let subModeCh: int = textCompactionData[i]; let ch: /*char*/ string = ''; switch (subMode) { case Mode.ALPHA: // Alpha (alphabetic: uppercase) if (subModeCh < 26) { // Upper case Alpha Character // Note: 65 = 'A' ASCII -> there is byte code of symbol ch = /*(char)('A' + subModeCh) */ String.fromCharCode(65 + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case DecodedBitStreamParser.LL: subMode = Mode.LOWER; break; case DecodedBitStreamParser.ML: subMode = Mode.MIXED; break; case DecodedBitStreamParser.PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.append(/*(char)*/ byteCompactionData[i]); break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.LOWER: // Lower (alphabetic: lowercase) if (subModeCh < 26) { ch = /*(char)('a' + subModeCh)*/String.fromCharCode(97 + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case DecodedBitStreamParser.AS: // Shift to alpha priorToShiftMode = subMode; subMode = Mode.ALPHA_SHIFT; break; case DecodedBitStreamParser.ML: subMode = Mode.MIXED; break; case DecodedBitStreamParser.PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // TODO Does this need to use the current character encoding? See other occurrences below result.append(/*(char)*/ byteCompactionData[i]); break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.MIXED: // Mixed (punctuation: e) if (subModeCh < DecodedBitStreamParser.PL) { ch = DecodedBitStreamParser.MIXED_CHARS[subModeCh]; } else { switch (subModeCh) { case DecodedBitStreamParser.PL: subMode = Mode.PUNCT; break; case 26: ch = ' '; break; case DecodedBitStreamParser.LL: subMode = Mode.LOWER; break; case DecodedBitStreamParser.AL: subMode = Mode.ALPHA; break; case DecodedBitStreamParser.PS: // Shift to punctuation priorToShiftMode = subMode; subMode = Mode.PUNCT_SHIFT; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.append(/*(char)*/ byteCompactionData[i]); break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.PUNCT: // Punctuation if (subModeCh < DecodedBitStreamParser.PAL) { ch = DecodedBitStreamParser.PUNCT_CHARS[subModeCh]; } else { switch (subModeCh) { case DecodedBitStreamParser.PAL: subMode = Mode.ALPHA; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: result.append(/*(char)*/ byteCompactionData[i]); break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.ALPHA_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < 26) { ch = /*(char)('A' + subModeCh)*/ String.fromCharCode(65 + subModeCh); } else { switch (subModeCh) { case 26: ch = ' '; break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; case Mode.PUNCT_SHIFT: // Restore sub-mode subMode = priorToShiftMode; if (subModeCh < DecodedBitStreamParser.PAL) { ch = DecodedBitStreamParser.PUNCT_CHARS[subModeCh]; } else { switch (subModeCh) { case DecodedBitStreamParser.PAL: subMode = Mode.ALPHA; break; case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE: // PS before Shift-to-Byte is used as a padding character, // see 5.4.2.4 of the specification result.append(/*(char)*/ byteCompactionData[i]); break; case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: subMode = Mode.ALPHA; break; } } break; } // if (ch !== 0) { if (ch !== '') { // Append decoded character to result result.append(ch); } i++; } } /** * Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded. * This includes all ASCII characters value 0 to 127 inclusive and provides for international * character set support. * * @param mode The byte compaction mode i.e. 901 or 924 * @param codewords The array of codewords (data + error) * @param encoding Currently active character encoding * @param codeIndex The current index into the codeword array. * @param result The decoded data is appended to the result. * @return The next index into the codeword array. */ private static /*int*/ byteCompaction(mode: int, codewords: Int32Array, encoding: /*Charset*/ CharacterSetECI, codeIndex: int, result: StringBuilder) { let decodedBytes: ByteArrayOutputStream = new ByteArrayOutputStream(); let count: int = 0; let value: /*long*/ number = 0; let end: boolean = false; switch (mode) { case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: // Total number of Byte Compaction characters to be encoded // is not a multiple of 6 let byteCompactedCodewords: Int32Array = new Int32Array(6); let nextCode: int = codewords[codeIndex++]; while ((codeIndex < codewords[0]) && !end) { byteCompactedCodewords[count++] = nextCode; // Base 900 value = 900 * value + nextCode; nextCode = codewords[codeIndex++]; // perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH switch (nextCode) { case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; default: if ((count % 5 === 0) && (count > 0)) { // Decode every 5 codewords // Convert to Base 256 for (let j /*int*/ = 0; j < 6; ++j) { /* @note * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. * So the next bitwise operation could not be done with simple numbers */ decodedBytes.write(/*(byte)*/Number(createBigInt(value) >> createBigInt(8 * (5 - j)))); } value = 0; count = 0; } break; } } // if the end of all codewords is reached the last codeword needs to be added if (codeIndex === codewords[0] && nextCode < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) { byteCompactedCodewords[count++] = nextCode; } // If Byte Compaction mode is invoked with codeword 901, // the last group of codewords is interpreted directly // as one byte per codeword, without compaction. for (let i /*int*/ = 0; i < count; i++) { decodedBytes.write(/*(byte)*/ byteCompactedCodewords[i]); } break; case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: // Total number of Byte Compaction characters to be encoded // is an integer multiple of 6 while (codeIndex < codewords[0] && !end) { let code: int = codewords[codeIndex++]; if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) { count++; // Base 900 value = 900 * value + code; } else { switch (code) { case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; } } if ((count % 5 === 0) && (count > 0)) { // Decode every 5 codewords // Convert to Base 256 /* @note * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. * So the next bitwise operation could not be done with simple numbers */ for (let j /*int*/ = 0; j < 6; ++j) { decodedBytes.write(/*(byte)*/Number(createBigInt(value) >> createBigInt(8 * (5 - j)))); } value = 0; count = 0; } } break; } result.append(StringEncoding.decode(decodedBytes.toByteArray(), encoding)); return codeIndex; } /** * Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings. * * @param codewords The array of codewords (data + error) * @param codeIndex The current index into the codeword array. * @param result The decoded data is appended to the result. * @return The next index into the codeword array. * * @throws FormatException */ private static numericCompaction(codewords: Int32Array, codeIndex: number /*int*/, result: StringBuilder): int { let count: int = 0; let end: boolean = false; let numericCodewords: Int32Array = new Int32Array(DecodedBitStreamParser.MAX_NUMERIC_CODEWORDS); while (codeIndex < codewords[0] && !end) { let code: int = codewords[codeIndex++]; if (codeIndex === codewords[0]) { end = true; } if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) { numericCodewords[count] = code; count++; } else { switch (code) { case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH: case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK: case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD: case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR: codeIndex--; end = true; break; } } if ((count % DecodedBitStreamParser.MAX_NUMERIC_CODEWORDS === 0 || code === DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH || end) && count > 0) { // Re-invoking Numeric Compaction mode (by using codeword 902 // while in Numeric Compaction mode) serves to terminate the // current Numeric Compaction mode grouping as described in 5.4.4.2, // and then to start a new one grouping. result.append(DecodedBitStreamParser.decodeBase900toBase10(numericCodewords, count)); count = 0; } } return codeIndex; } /** * Convert a list of Numeric Compacted codewords from Base 900 to Base 10. * * @param codewords The array of codewords * @param count The number of codewords * @return The decoded string representing the Numeric data. * * EXAMPLE * Encode the fifteen digit numeric string 000213298174000 * Prefix the numeric string with a 1 and set the initial value of * t = 1 000 213 298 174 000 * Calculate codeword 0 * d0 = 1 000 213 298 174 000 mod 900 = 200 * * t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082 * Calculate codeword 1 * d1 = 1 111 348 109 082 mod 900 = 282 * * t = 1 111 348 109 082 div 900 = 1 234 831 232 * Calculate codeword 2 * d2 = 1 234 831 232 mod 900 = 632 * * t = 1 234 831 232 div 900 = 1 372 034 * Calculate codeword 3 * d3 = 1 372 034 mod 900 = 434 * * t = 1 372 034 div 900 = 1 524 * Calculate codeword 4 * d4 = 1 524 mod 900 = 624 * * t = 1 524 div 900 = 1 * Calculate codeword 5 * d5 = 1 mod 900 = 1 * t = 1 div 900 = 0 * Codeword sequence is: 1, 624, 434, 632, 282, 200 * * Decode the above codewords involves * 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 + * 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000 * * Remove leading 1 => Result is 000213298174000 * * @throws FormatException */ private static decodeBase900toBase10(codewords: Int32Array, count: int): string { let result = createBigInt(0); for (let i /*int*/ = 0; i < count; i++) { result += DecodedBitStreamParser.EXP900[count - i - 1] * createBigInt(codewords[i]); } let resultString: String = result.toString(); if (resultString.charAt(0) !== '1') { throw new FormatException(); } return resultString.substring(1); } }
the_stack
import { Injectable } from '@angular/core'; import * as hljs from 'highlight.js'; import * as yaml from 'js-yaml'; import { EOL } from 'os'; import * as path from 'path'; import * as Remarkable from 'remarkable'; import { escapeHtml, replaceEntities, unescapeMd } from 'remarkable/lib/common/utils'; import { Note, NoteMetadata, NoteSnippetTypes } from '../../../core/note'; import { WorkspaceService } from '../../shared'; import { NoteContent, NoteSnippetContent } from '../note-editor'; import { NoteContentParseResult, NoteContentRawValueParseResult, NoteSnippetParseResult } from './note-parsing.model'; import remarkableMetaPlugin = require('remarkable-meta'); const getMdTitle = require('get-md-title') as (content: string) => { text: string } | undefined; export class NoteContentParsingOptions { readonly indent?: number = 4; readonly lineSpacing?: number = 2; readonly metadata?: NoteMetadata | null = null; } @Injectable() export class NoteParser { private readonly markdownParser: Remarkable; constructor(private workspace: WorkspaceService) { this.markdownParser = new Remarkable({ highlight: (str, lang) => { if (lang && hljs.getLanguage(lang)) { try { return hljs.highlight(lang, str).value; } catch (err) { } } try { return hljs.highlightAuto(str).value; } catch (err) { } return ''; // use external default escaping }, }); this.markdownParser.use(remarkableMetaPlugin); overrideMarkdownParseToAdaptLink(this.markdownParser, this.workspace.configs.assetsDirPath); } generateNoteContent(note: Note, contentRawValue: string): NoteContent { if (!contentRawValue) { return null; } const lines = contentRawValue.split(EOL); const snippets: NoteSnippetContent[] = []; for (const snippet of note.snippets) { const startIndex = snippet.startLineNumber - 1; const endIndex = snippet.endLineNumber - 1; const value = lines.slice(startIndex, endIndex + 1).join(EOL); let snippetContent: NoteSnippetContent = { type: snippet.type, value, }; if (snippet.type === NoteSnippetTypes.CODE) { snippetContent = { ...snippetContent, value: lines.slice(startIndex + 1, endIndex).join(EOL), // Remove first and last line. codeLanguageId: snippet.codeLanguageId, codeFileName: snippet.codeFileName, }; } snippets.push(snippetContent); } return { noteId: note.id, snippets, }; } parseNoteContentRawValue(contentRawValue: string): NoteContentRawValueParseResult { const snippets = []; const lines = contentRawValue.split('\n'); const tokens = this.markdownParser.parse(contentRawValue, { breaks: true }); for (const snippet of parseTokens(lines, tokens)) { snippets.push(snippet); } /** * When parsing the Markdown text, the Front matter data is parsed * together by the plugin named 'remarkable-meta'. * * The data is stored in the 'meta' property, but is not typed in * Typescript. * * See * https://github.com/eugeneware/remarkable-meta */ const metadata = (<any>this.markdownParser).meta as NoteMetadata; /** * 'get-md-title' fetches the first header of the Markdown content * as the first header. * * We will use note title by priority. * 1. The title stated in Front matter * 2. First header of content */ const firstHeaderTitle = getMdTitle(contentRawValue); const title = metadata.title ? metadata.title : firstHeaderTitle ? firstHeaderTitle.text : 'No Title'; const stacks = metadata.stacks ? metadata.stacks : []; const createdDatetime = !metadata.date ? null : !Number.isNaN(Date.parse(metadata.date)) ? Date.parse(metadata.date) : null; return { title, parsedSnippets: [...snippets], stackIds: stacks, createdDatetime, }; } parseNoteContent( content: NoteContent, options?: NoteContentParsingOptions, ): NoteContentParseResult { const opts = { ...(new NoteContentParsingOptions()), ...options, } as NoteContentParsingOptions; let metadataLines: string[]; if (opts.metadata) { const metadata = yaml.safeDump(opts.metadata, { indent: opts.indent, }); metadataLines = metadata.split(EOL); // If last line is empty, discard last line. if (isEmptyLine(getLastLine(metadataLines))) { metadataLines = metadataLines.slice(0, metadataLines.length - 1); } } let str = ''; let startLine: number; let endLine: number; const nl = EOL; const lineSpacing = numToArray(opts.lineSpacing) .reduce(sum => `${sum}${nl}`, nl); // Add front matter to note content raw value if exists. if (metadataLines) { str += `---${nl}` + `${metadataLines.join(nl)}${nl}` + `---${nl}` + `${nl}`; } // Parse tokens to get parsed snippet. const parsedSnippets: NoteSnippetParseResult[] = []; startLine = endLine = str.split(EOL).length; // Add each snippet value to note content raw value. for (const snippet of content.snippets) { if (snippet.type === NoteSnippetTypes.CODE) { str += '```'; if (snippet.codeLanguageId) { str += snippet.codeLanguageId; } str += '\n'; endLine += 1; // Add 1 line. } str += snippet.value; endLine += snippet.value.split(EOL).length - 1; if (snippet.type === NoteSnippetTypes.CODE) { str += '\n```'; endLine += 1; } parsedSnippets.push({ ...snippet, startLineNumber: startLine, endLineNumber: endLine, }); str += lineSpacing; startLine = endLine = endLine + opts.lineSpacing + 1; } return { parsedSnippets, contentRawValue: str, }; } convertSnippetContentToHtml(snippet: NoteSnippetContent): string { let value: string; if (snippet.type === NoteSnippetTypes.CODE) { value = (snippet.codeLanguageId ? `\`\`\`${snippet.codeLanguageId}\n` : '```\n') + snippet.value + '\n```'; } else if (snippet.type === NoteSnippetTypes.TEXT) { value = snippet.value; } return this.markdownParser.render(value); } } function* parseTokens(lines: string[], _tokens: Remarkable.Token[]): IterableIterator<NoteSnippetParseResult> { let start = 0; let end = 0; let startLine; let endLine; // We only need content token. // Occasionally, content token does not have 'lines' property. // Therefore, ensure token validation by checking 'lines' property. const tokens = _tokens.filter(token => !!token.lines && !!(<any>token).content); for (let i = 0; i < tokens.length; i++) { if (tokens[i].type === 'fence') { if (start !== i && end !== i) { startLine = tokens[start].lines[0]; endLine = tokens[end].lines[1]; yield { type: NoteSnippetTypes.TEXT, value: lines.slice(startLine, endLine).join(EOL), startLineNumber: startLine + 1, endLineNumber: endLine, }; } [startLine, endLine] = tokens[i].lines; yield { type: NoteSnippetTypes.CODE, value: lines.slice(startLine + 1, endLine - 1).join(EOL), // Remove first and last line. startLineNumber: startLine + 1, endLineNumber: endLine, codeLanguageId: (<any>tokens[i]).params, codeFileName: '', }; start = i + 1; end = i + 1; } else { end = i; if (i === tokens.length - 1) { startLine = tokens[start].lines[0]; endLine = tokens[end].lines[1]; yield { type: NoteSnippetTypes.TEXT, value: lines.slice(startLine, endLine).join(EOL), startLineNumber: startLine + 1, endLineNumber: endLine, }; } } } } function overrideMarkdownParseToAdaptLink(md: Remarkable, assetDir: string): void { md.renderer.rules.image = (tokens, idx, options /*, env */) => { const srcUrl = path.resolve(assetDir, path.basename(tokens[idx].src)); const src = ' src="' + escapeHtml(srcUrl) + '"'; const title = tokens[idx].title ? (' title="' + escapeHtml(replaceEntities(tokens[idx].title)) + '"') : ''; const alt = ' alt="' + (tokens[idx].alt ? escapeHtml(replaceEntities(unescapeMd(tokens[idx].alt))) : '') + '"'; const suffix = options.xhtmlOut ? ' /' : ''; // noinspection HtmlRequiredAltAttribute return '<img' + src + alt + title + suffix + '>'; }; } /** Check if line is empty. */ function isEmptyLine(line: string): boolean { return line.trim() === ''; } /** Get last element of lines. */ function getLastLine(lines: string[]): string { return lines[lines.length - 1]; } /** Simple convert number to array. */ function numToArray(count: number): number[] { const arr = []; for (let i = 0; i < count; i++) { arr.push(i + 1); } return arr; }
the_stack
/// <reference path="../SearchBox/SearchBox.ts"/> /// <reference path="../CommandButton/CommandButton.ts"/> /// <reference path="../ContextualHost/ContextualHost.ts"/> /** * CommandBar * * Commanding and navigational surface * */ namespace fabric { "use strict"; interface WindowSize { x: number; y: number; } interface CommandBarElements { mainArea: Element; sideCommandArea?: Element; overflowCommand?: Element; contextMenu?: HTMLElement; searchBox?: Element; searchBoxClose?: Element; } interface ItemCollection { item: Element; label: string; icon: string; isCollapsed: boolean; commandButtonRef: fabric.CommandButton; } const CONTEXTUAL_MENU = ".ms-ContextualMenu"; const CONTEXTUAL_MENU_ITEM = ".ms-ContextualMenu-item"; const CONTEXTUAL_MENU_LINK = ".ms-ContextualMenu-link"; const CB_SEARCH_BOX = ".ms-SearchBox"; const CB_MAIN_AREA = ".ms-CommandBar-mainArea"; const CB_SIDE_COMMAND_AREA = ".ms-CommandBar-sideCommands"; const CB_ITEM_OVERFLOW = ".ms-CommandBar-overflowButton"; const CB_NO_LABEL_CLASS = "ms-CommandButton--noLabel"; const SEARCH_BOX_CLOSE = ".ms-SearchBox-closeField"; const COMMAND_BUTTON = ".ms-CommandButton"; const COMMAND_BUTTON_LABEL = ".ms-CommandButton-label"; const ICON = ".ms-Icon"; const OVERFLOW_WIDTH = 40; const OVERFLOW_LEFT_RIGHT_PADDING = 30; export class CommandBar { private responsiveSizes: Object = { "sm-min": 320, "md-min": 480, "lg-min": 640, "xl-min": 1024, "xxl-min": 1366, "xxxl-min": 1920 }; private visibleCommands: Array<ItemCollection> = []; private commandWidths: Array<number> = []; private overflowCommands: Array<ItemCollection> = []; private itemCollection: Array<ItemCollection> = []; private _sideAreaCollection: Array<ItemCollection> = []; private contextualItemContainerRef: Node; private contextualItemLink: Node; private contextualItemIcon: Node; private breakpoint: string = "sm"; private _elements: CommandBarElements; private activeCommand: Element; private searchBoxInstance: SearchBox; private _container: Element; private _commandButtonInstance: CommandButton; constructor(container: Element) { this._container = container; this.responsiveSizes["sm-max"] = this.responsiveSizes["md-min"] - 1; this.responsiveSizes["md-max"] = this.responsiveSizes["lg-min"] - 1; this.responsiveSizes["lg-max"] = this.responsiveSizes["xl-min"] - 1; this.responsiveSizes["xl-max"] = this.responsiveSizes["xxl-min"] - 1; this.responsiveSizes["xxl-max"] = this.responsiveSizes["xxxl-min"] - 1; this._setElements(); this._setBreakpoint(); // If the overflow exists then run the overflow resizing if (this._elements.overflowCommand) { this._initOverflow(); } this._setUIState(); } private _runsSearchBox(state: string = "add") { this._changeSearchState("is-collapsed", state); } private _runOverflow() { if (this._elements.overflowCommand) { this._saveCommandWidths(); this._redrawMenu(); this._updateCommands(); this._drawCommands(); this._checkOverflow(); } } private _initOverflow() { this._createContextualRef(); this._createItemCollection(this.itemCollection, CB_MAIN_AREA); this._createItemCollection(this._sideAreaCollection, CB_SIDE_COMMAND_AREA); this._saveCommandWidths(); this._updateCommands(); this._drawCommands(); this._setWindowEvent(); this._checkOverflow(); } private _hasClass(element, cls): boolean { return (" " + element.className + " ").indexOf(" " + cls + " ") > -1; } private _onSearchExpand(): void { if (this.breakpoint === "lg") { this._container.classList.add("search-expanded"); this._doResize(); } } private _onSearchCollapse(): void { if (this.breakpoint === "lg") { this._container.classList.remove("search-expanded"); this._doResize(); } } private _getScreenSize(): WindowSize { // First we need to set what the screen is doing, check screen size let w = window; let wSize = { x: 0, y: 0 }; let d = document, e = d.documentElement, g = d.getElementsByTagName("body")[0]; wSize.x = w.innerWidth || e.clientWidth || g.clientWidth; wSize.y = w.innerHeight || e.clientHeight || g.clientHeight; return wSize; } private _setBreakpoint(): void { let screenSize = this._getScreenSize().x; switch (true) { case (screenSize <= this.responsiveSizes["sm-max"]): this.breakpoint = "sm"; break; case (screenSize >= this.responsiveSizes["md-min"] && screenSize <= this.responsiveSizes["md-max"]): this.breakpoint = "md"; break; case (screenSize >= this.responsiveSizes["lg-min"] && screenSize <= this.responsiveSizes["lg-max"]): this.breakpoint = "lg"; break; case (screenSize >= this.responsiveSizes["xl-min"] && screenSize <= this.responsiveSizes["xl-max"]): this.breakpoint = "xl"; break; case (screenSize >= this.responsiveSizes["xxl-min"] && screenSize <= this.responsiveSizes["xxl-max"]): this.breakpoint = "xxl"; break; case (screenSize >= this.responsiveSizes["xxxl-min"]): this.breakpoint = "xxxl"; break; } } private _createSearchInstance(): any { if (this._elements.searchBox) { return new fabric.SearchBox(<HTMLElement>this._elements.searchBox); } else { return false; } } private _changeSearchState(state: string, action: string) { if (this._elements.searchBox) { switch (action) { case "remove": this._elements.searchBox.classList.remove(state); break; case "add": this._elements.searchBox.classList.add(state); break; default: break; } } } private _setElements() { this._elements = { mainArea: this._container.querySelector(CB_MAIN_AREA) }; if (this._container.querySelector(CB_SIDE_COMMAND_AREA)) { this._elements.sideCommandArea = this._container.querySelector(CB_SIDE_COMMAND_AREA); } if (this._container.querySelector(CB_ITEM_OVERFLOW)) { this._elements.overflowCommand = this._container.querySelector(CB_ITEM_OVERFLOW); this._elements.contextMenu = <HTMLElement>this._container.querySelector(CB_ITEM_OVERFLOW).querySelector(CONTEXTUAL_MENU); } if (this._container.querySelector(CB_MAIN_AREA + " " + CB_SEARCH_BOX)) { this._elements.searchBox = this._container.querySelector(CB_MAIN_AREA + " " + CB_SEARCH_BOX); this._elements.searchBoxClose = this._container.querySelector(SEARCH_BOX_CLOSE); this.searchBoxInstance = this._createSearchInstance(); this.searchBoxInstance.getInputField().addEventListener("focus", () => { this._onSearchExpand(); }, false); this.searchBoxInstance.getInputField().addEventListener("searchCollapse", () => { this._onSearchCollapse(); }, false); } } private _createItemCollection(iCollection: Array<ItemCollection>, areaClass: string) { let item, label, iconClasses, splitClasses, items = this._container.querySelectorAll(areaClass + " > " + COMMAND_BUTTON + ":not(" + CB_ITEM_OVERFLOW + ")"); // Initiate the overflow command this._commandButtonInstance = new fabric.CommandButton(<HTMLElement>this._elements.overflowCommand); for (let i = 0; i < items.length; i++) { item = items[i]; label = item.querySelector(COMMAND_BUTTON_LABEL).textContent; let icon = item.querySelector(ICON); if (icon) { iconClasses = icon.className; splitClasses = iconClasses.split(" "); for (let o = 0; o < splitClasses.length; o++) { if (splitClasses[o].indexOf(ICON.replace(".", "") + "--") > -1) { icon = splitClasses[o]; break; } } } iCollection.push({ item: item, label: label, icon: icon, isCollapsed: (item.classList.contains(CB_NO_LABEL_CLASS)) ? true : false, commandButtonRef: new fabric.CommandButton(<HTMLElement>item) }); } return; } private _createContextualRef() { this.contextualItemContainerRef = this._elements.contextMenu.querySelector(CONTEXTUAL_MENU_ITEM).cloneNode(true); this.contextualItemLink = this._elements.contextMenu.querySelector(CONTEXTUAL_MENU_LINK).cloneNode(false); this.contextualItemIcon = this._elements.contextMenu.querySelector(".ms-Icon").cloneNode(false); this._elements.contextMenu.innerHTML = ""; } private _getElementWidth(element) { let width, styles; if (element.offsetParent === null) { element.setAttribute("style", "position: absolute; opacity: 0; display: block;"); } width = element.getBoundingClientRect().width; styles = window.getComputedStyle(element); width += parseInt(styles.marginLeft, 10) + parseInt(styles.marginRight, 10); element.setAttribute("style", ""); return width; } private _saveCommandWidths() { for (let i = 0; i < this.itemCollection.length; i++) { let item = this.itemCollection[i].item; let width = this._getElementWidth(item); this.commandWidths[i] = width; } } private _updateCommands() { let searchCommandWidth = 0; let mainAreaWidth = this._elements.mainArea.getBoundingClientRect().width; if (this._elements.searchBox) { searchCommandWidth = this._getElementWidth(this._elements.searchBox); } const offset: number = searchCommandWidth + OVERFLOW_WIDTH + OVERFLOW_LEFT_RIGHT_PADDING; const totalAreaWidth: number = mainAreaWidth - offset; // Start with searchbox width // Reset overflow and visible this.visibleCommands = []; this.overflowCommands = []; let totalWidths: number = 0; for (let i = 0; i < this.itemCollection.length; i++) { totalWidths += this.commandWidths[i]; if (totalWidths < totalAreaWidth) { this.visibleCommands.push(this.itemCollection[i]); } else { this.overflowCommands.push(this.itemCollection[i]); } } } private _drawCommands() { // Remove existing commands this._elements.contextMenu.innerHTML = ""; for (let i = 0; i < this.overflowCommands.length; i++) { this.overflowCommands[i].item.classList.add("is-hidden"); // Add all items to contextual menu. const newCItem: HTMLElement = <HTMLElement>this.contextualItemContainerRef.cloneNode(false); const newClink: HTMLElement = <HTMLElement>this.contextualItemLink.cloneNode(false); const iconClass = this.overflowCommands[i].icon; newClink.innerText = this.overflowCommands[i].label; newCItem.appendChild(newClink); if (iconClass) { let newIcon: HTMLElement = <HTMLElement>this.contextualItemIcon.cloneNode(false); newIcon.className = ICON.replace(".", "") + " " + iconClass; newCItem.appendChild(newIcon); } this._elements.contextMenu.appendChild(newCItem); } // Show visible commands for (let x = 0; x < this.visibleCommands.length; x++) { this.visibleCommands[x].item.classList.remove("is-hidden"); } } private _setWindowEvent() { window.addEventListener("resize", () => { this._doResize(); }, false); } private _processCollapsedClasses(type) { for (let i = 0; i < this.itemCollection.length; i++) { let thisItem = this.itemCollection[i]; if (!thisItem.isCollapsed) { if (type === "add") { thisItem.item.classList.add(CB_NO_LABEL_CLASS); } else { thisItem.item.classList.remove(CB_NO_LABEL_CLASS); } } } for (let i = 0; i < this._sideAreaCollection.length; i++) { let thisItem = this._sideAreaCollection[i]; if (!thisItem.isCollapsed) { if (type === "add") { thisItem.item.classList.add(CB_NO_LABEL_CLASS); } else { thisItem.item.classList.remove(CB_NO_LABEL_CLASS); } } } } private _setUIState() { switch (this.breakpoint) { case "sm": this._runsSearchBox(); this._processCollapsedClasses("add"); this._runOverflow(); break; case "md": this._runsSearchBox(); // Add collapsed classes to commands this._processCollapsedClasses("add"); this._runOverflow(); break; case "lg": this._runsSearchBox(); this._processCollapsedClasses("remove"); this._runOverflow(); break; case "xl": this._runsSearchBox( "remove"); this._processCollapsedClasses("remove"); this._runOverflow(); break; default: this._runsSearchBox("remove"); this._processCollapsedClasses("remove"); this._runOverflow(); break; } } private _checkOverflow() { if ( this.overflowCommands.length > 0) { this._elements.overflowCommand.classList.remove("is-hidden"); } else { this._elements.overflowCommand.classList.add("is-hidden"); if (this.activeCommand === this._elements.overflowCommand) { this._elements.contextMenu.classList.remove("is-open"); } } } private _redrawMenu() { let left; if (this._hasClass(this._elements.contextMenu, "is-open")) { left = this.activeCommand.getBoundingClientRect().left; this._drawOverflowMenu(left); } } private _drawOverflowMenu(left) { this._elements.contextMenu.setAttribute("style", "left: " + left + "px; transform: translateX(-50%)"); } private _doResize() { this._setBreakpoint(); this._setUIState(); } } }
the_stack
import { render, renderJSXElement, jsx, Fragment, compareRenderTree } from '../../src/jsx'; import { ELEMENT_DELETE } from '../../src/jsx/elementStatus'; import { Canvas } from '@antv/f2-graphic'; import { createContext } from '../util'; const canvasEl = document.createElement('canvas'); canvasEl.style.width = '359px'; canvasEl.style.height = '400px'; document.body.appendChild(canvasEl); const context = canvasEl.getContext('2d'); const canvas = new Canvas({ context, }); describe('render', () => { it('group', () => { const container = canvas.addGroup(); const group = render( <group> <rect attrs={{ x: 0, y: 0, width: 10, height: 10, fill: 'red', }} /> </group>, container ); canvas.draw(); expect(!!group).toBe(true); expect(group.get('children').length).toBe(1); expect(group.get('children')[0].get('type')).toBe('rect'); container.remove(true); }); it('group with background', () => { const container = canvas.addGroup(); const shape = render( <group style={{ width: 100, height: 100 }} attrs={{ fill: 'gray', }} > <rect attrs={{ x: 0, y: 0, width: 10, height: 10, fill: 'red', }} /> </group>, container ); canvas.draw(); const background = shape.get('attrs'); expect(background.fill).toBe('gray'); expect(background.width).toBe(100); expect(background.height).toBe(100); container.remove(true); }); it('group children empty', () => { const container = canvas.addGroup(); const group1 = render(<group></group>, container); const group2 = render(<group />, container); canvas.draw(); expect(group1.get('children').length).toBe(0); expect(group2.get('children').length).toBe(0); }); it('shape', () => { const container = canvas.addGroup(); const shape = render( <rect attrs={{ x: 0, y: 0, width: 10, height: 10, fill: 'red', }} />, container ); canvas.draw(); expect(shape.get('type')).toBe('rect'); container.remove(true); }); it('test shape ref', () => { const ref = { current: null }; const container = canvas.addGroup(); const shape = render( <rect attrs={{ x: 0, y: 0, width: 10, height: 10, fill: 'red', }} ref={ref} />, container ); canvas.draw(); expect(ref.current).toBe(shape); container.remove(true); }); it('test group ref', () => { const groupRef = { current: null }; const rectRef = { current: null }; const container = canvas.addGroup(); const group = render( <group ref={groupRef}> <rect ref={rectRef} attrs={{ x: 0, y: 0, width: 10, height: 10, fill: 'red', }} /> </group>, container ); canvas.draw(); expect(groupRef.current).toBe(group); expect(rectRef.current.get('type')).toBe('rect'); container.remove(true); }); it('render null', () => { const container = canvas.addGroup(); const shape = render(null, container); canvas.draw(); expect(shape).toBeUndefined(); container.remove(true); }); }); describe('render style alias', () => { it('group', () => { const container = canvas.addGroup(); const group = render( <group> <rect style={{ left: 0, top: 0, width: 10, height: 10, backgroundColor: 'red', }} /> </group>, container ); canvas.draw(); expect(!!group).toBe(true); expect(group.get('children').length).toBe(1); expect(group.get('children')[0].get('type')).toBe('rect'); container.remove(true); }); }); describe('layout', () => { it('flex direction default column', () => { const container = canvas.addGroup(); const group = render( <group style={{ width: '200px', height: '200px', }} > <rect style={{ flex: 1, }} attrs={{ fill: 'gray', }} /> <rect style={{ flex: 1, }} attrs={{ fill: 'red', }} /> </group>, container ); canvas.draw(); const children = group.get('children'); expect(children[0].get('attrs').x).toBe(0); expect(children[0].get('attrs').y).toBe(0); expect(children[0].get('attrs').width).toBe(100); expect(children[0].get('attrs').height).toBe(50); expect(children[0].get('attrs').fill).toBe('gray'); expect(children[1].get('attrs').x).toBe(0); expect(children[1].get('attrs').y).toBe(50); expect(children[1].get('attrs').width).toBe(100); expect(children[1].get('attrs').height).toBe(50); expect(children[1].get('attrs').fill).toBe('red'); container.remove(true); }); it('flex direction row', () => { const container = canvas.addGroup(); const group = render( <group style={{ flexDirection: 'row', padding: ['20px', '40px'], width: '380px', height: '200px', }} > <rect style={{ flex: 1, }} attrs={{ fill: 'gray', }} /> <rect style={{ flex: 1, }} attrs={{ fill: 'red', }} /> <group style={{ flex: 1, }} > <text attrs={{ fill: '#000', text: '123', }} /> </group> </group>, container ); canvas.draw(); const children = group.get('children'); expect(children[0].get('attrs').x).toBe(20); expect(children[0].get('attrs').y).toBe(10); expect(children[0].get('attrs').width).toBe(50); expect(children[0].get('attrs').height).toBe(80); expect(children[0].get('attrs').fill).toBe('gray'); expect(children[1].get('attrs').x).toBe(70); expect(children[1].get('attrs').y).toBe(10); expect(children[1].get('attrs').width).toBe(50); expect(children[1].get('attrs').height).toBe(80); expect(children[1].get('attrs').fill).toBe('red'); expect(children[2].get('children')[0].get('type')).toBe('text'); expect(children[2].get('children')[0].get('attrs').x).toBe(120); expect(children[2].get('children')[0].get('attrs').y).toBe(16); container.remove(true); }); it('text render', () => { const container = canvas.addGroup(); const group = render( <group style={{ flexDirection: 'row', width: '20px', height: '200px', flexWrap: 'wrap', }} > <text style={ { // flex: 1, } } attrs={{ fill: '#000', text: '111', }} /> <text style={ { // flex: 1, } } attrs={{ fill: '#000', text: '222', }} /> </group>, container ); canvas.draw(); const children = group.get('children'); expect(children[0].get('attrs').x).toBe(0); expect(children[0].get('attrs').y).toBe(6); expect(children[0].get('attrs').textBaseline).toBe('middle'); expect(children[1].get('attrs').x).toBe(0); expect(children[1].get('attrs').y).toBe(18); expect(children[1].get('attrs').textBaseline).toBe('middle'); container.remove(true); }); it('margin percent', () => { const container = canvas.addGroup(); const group = render( <group style={{ // padding: '20px', marginLeft: '-50%', // marginTop: '-50%', }} > <text style={ { // flex: 1, } } attrs={{ fill: '#000', text: '111', }} /> </group>, container ); canvas.draw(); const children = group.get('children'); const textShape = children[0]; const left = -(textShape.getBBox().width / 2); expect(textShape.get('attrs').x).toBeCloseTo(left, 3); // expect(children[0].get('attrs').x).toBe(0); // expect(children[0].get('attrs').y).toBe(6); // expect(children[0].get('attrs').textBaseline).toBe('middle'); // expect(children[1].get('attrs').x).toBe(0); // expect(children[1].get('attrs').y).toBe(18); // expect(children[1].get('attrs').textBaseline).toBe('middle'); // container.remove(true); }); describe('delete element', () => { it('删除元素不参布局计算', () => { const container = canvas.addGroup(); const groupJSXElement = ( <group style={{ flexDirection: 'row', width: 200, height: 200, flexWrap: 'wrap', }} > <rect style={{ flex: 1, }} attrs={{ fill: '#f00', }} /> <rect style={{ flex: 1, }} attrs={{ fill: '#0f0', }} /> <group style={{ flex: 1, flexDirection: 'row', }} > <rect style={{ flex: 1, }} attrs={{ fill: '#00f', }} /> <rect style={{ flex: 1, }} attrs={{ fill: '#0f0', }} /> </group> </group> ); // 新增和变化的元素不保留上次的attrs groupJSXElement.props.children[0]._cache = { attrs: { x: 100, y: 200, width: 10, height: 10 }, }; // 把中间的元素标记为删除 groupJSXElement.props.children[1].status = ELEMENT_DELETE; // 删除的元素保留attrs groupJSXElement.props.children[1]._cache = { attrs: { x: 0, y: 200, width: 10, height: 10 }, }; groupJSXElement.props.children[2].props.children[1].status = ELEMENT_DELETE; const group = render(groupJSXElement, container); canvas.draw(); const children = group.get('children'); expect(children[0].get('attrs').x).toBe(0); expect(children[0].get('attrs').y).toBe(0); expect(children[0].get('attrs').width).toBe(100); expect(children[0].get('attrs').height).toBe(200); expect(children[1].get('attrs').x).toBe(0); expect(children[1].get('attrs').y).toBe(200); expect(children[1].get('attrs').width).toBe(10); expect(children[1].get('attrs').height).toBe(10); expect(children[2].get('attrs').x).toBe(100); expect(children[2].get('attrs').y).toBe(0); expect(children[2].get('attrs').width).toBe(100); expect(children[2].get('attrs').height).toBe(200); const subChildren = children[2].get('children'); expect(subChildren[0].get('attrs').x).toBe(100); expect(subChildren[0].get('attrs').y).toBe(0); expect(subChildren[0].get('attrs').width).toBe(100); expect(subChildren[0].get('attrs').height).toBe(200); expect(subChildren[1].get('attrs').x).toBe(0); expect(subChildren[1].get('attrs').y).toBe(0); expect(subChildren[1].get('attrs').width).toBe(0); expect(subChildren[1].get('attrs').height).toBe(0); }); it('删除元素不参布局计算-根元素', () => { const container = canvas.addGroup(); const groupJSXElement = ( <group style={{ flexDirection: 'row', width: 200, height: 200, flexWrap: 'wrap', }} > <rect style={{ flex: 1, }} attrs={{ fill: '#f00', }} /> <rect style={{ flex: 1, }} attrs={{ fill: '#0f0', }} /> </group> ); // 把中间的元素标记为删除 groupJSXElement.status = ELEMENT_DELETE; const group = render(groupJSXElement, container); canvas.draw(); const children = group.get('children'); expect(children.length).toBe(2); expect(children[0].get('attrs').x).toBe(0); expect(children[0].get('attrs').y).toBe(0); expect(children[0].get('attrs').width).toBe(0); expect(children[0].get('attrs').height).toBe(0); expect(children[1].get('attrs').x).toBe(0); expect(children[1].get('attrs').y).toBe(0); expect(children[1].get('attrs').width).toBe(0); expect(children[1].get('attrs').height).toBe(0); }); }); }); describe('clip', () => { it('rect', () => { const context = createContext(); const canvas = new Canvas({ context, pixelRatio: 1, }); render( <group> <rect attrs={{ x: 0, y: 0, width: 100, height: 100, fill: 'red', clip: { type: 'circle', attrs: { x: 50, y: 50, r: 40, }, }, }} /> </group>, canvas ); canvas.draw(); expect(context).toMatchImageSnapshot(); }); it('group', () => { const context = createContext(); const canvas = new Canvas({ context, pixelRatio: 1, }); render( <group attrs={{ clip: { type: 'circle', attrs: { x: 50, y: 50, r: 40, }, }, }} > <rect attrs={{ x: 0, y: 0, width: 100, height: 100, fill: 'red', }} /> </group>, canvas ); canvas.draw(); expect(context).toMatchImageSnapshot(); }); });
the_stack
import { EngineEvent, EngineEventMap, INodeService, Result, NodeParams, NodeResponses, OptionalPublicIdentifier, Values, NodeError, GetTransfersFilterOpts, } from "@connext/vector-types"; import Ajv from "ajv"; import Axios from "axios"; import { Evt, VoidCtx } from "evt"; import { BaseLogger } from "pino"; const ajv = new Ajv(); export type EventCallbackConfig = { [event in keyof EngineEventMap]: { evt?: Evt<EngineEventMap[event]>; url?: string; }; }; // Holds all the contexts for each public identifier type ContextContainer = { [publicIdentifier: string]: VoidCtx; }; export type ServerNodeServiceErrorContext = NodeError & { requestUrl: string; publicIdentifier: string; params: any; }; export class ServerNodeServiceError extends NodeError { static readonly type = "ServerNodeServiceError"; static readonly reasons = { InternalServerError: "Failed to send request", InvalidParams: "Request has invalid parameters", MultinodeProhibitted: "Not allowed to have multiple nodes", NoEvts: "No evts for event", NoPublicIdentifier: "Public identifier not supplied, and no default identifier", Timeout: "Timeout", } as const; readonly context: ServerNodeServiceErrorContext; constructor( public readonly msg: Values<typeof ServerNodeServiceError.reasons>, publicIdentifier: string, requestUrl: string, // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types params: any, context: any = {}, ) { super(msg, { requestUrl, publicIdentifier, params, ...context }); } } export class RestServerNodeService implements INodeService { public publicIdentifier = ""; public signerAddress = ""; private readonly ctxs: ContextContainer = {}; private constructor( private readonly serverNodeUrl: string, private readonly logger: BaseLogger, private readonly evts?: EventCallbackConfig, ) {} static async connect( serverNodeUrl: string, logger: BaseLogger, evts?: EventCallbackConfig, index?: number, skipCheckIn?: boolean, ): Promise<RestServerNodeService> { const service = new RestServerNodeService(serverNodeUrl, logger, evts); // If an index is provided, the service will only host a single engine // and the publicIdentifier will be automatically included in parameters if (typeof index === "number") { // Create the public identifier and signer address const node = await service.createNode({ index, skipCheckIn }); if (node.isError) { logger.error({ error: node.getError()!.message, method: "connect" }, "Failed to create node"); throw node.getError(); } const { publicIdentifier, signerAddress } = node.getValue(); service.publicIdentifier = publicIdentifier; service.signerAddress = signerAddress; } return service; } getStatus(publicIdentifer?: string): Promise<Result<NodeResponses.GetStatus, ServerNodeServiceError>> { return this.executeHttpRequest( `${publicIdentifer ?? this.publicIdentifier}/status`, "get", {}, NodeParams.GetStatusSchema, ); } getRouterConfig( params: OptionalPublicIdentifier<NodeParams.GetRouterConfig>, ): Promise<Result<NodeResponses.GetRouterConfig, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/router/config/${params.routerIdentifier}`, "get", params, NodeParams.GetRouterConfigSchema, ); } async getConfig(): Promise<Result<NodeResponses.GetConfig, ServerNodeServiceError>> { return this.executeHttpRequest("config", "get", {}, NodeParams.GetConfigSchema); } async getWithdrawalCommitment( params: OptionalPublicIdentifier<NodeParams.GetWithdrawalCommitment>, ): Promise<Result<NodeResponses.GetWithdrawalCommitment, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/withdraw/transfer/${params.transferId}`, "get", {}, NodeParams.GetWithdrawalCommitmentSchema, ); } async getWithdrawalCommitmentByTransactionHash( params: OptionalPublicIdentifier<NodeParams.GetWithdrawalCommitmentByTransactionHash>, ): Promise<Result<NodeResponses.GetWithdrawalCommitmentByTransactionHash, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/withdraw/transaction/${params.transactionHash}`, "get", {}, NodeParams.GetWithdrawalCommitmentByTransactionHashSchema, ); } getChannelDispute( params: OptionalPublicIdentifier<NodeParams.GetChannelDispute>, ): Promise<Result<NodeResponses.GetChannelDispute, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels/channel/${params.channelAddress}/dispute`, "get", params, NodeParams.SendDefundChannelTxSchema, ); } sendDisputeChannelTx( params: OptionalPublicIdentifier<NodeParams.SendDisputeChannelTx>, ): Promise<Result<NodeResponses.SendDisputeChannelTx, ServerNodeServiceError>> { return this.executeHttpRequest(`send-dispute-channel-tx`, "post", params, NodeParams.SendDisputeChannelTxSchema); } sendDefundChannelTx( params: OptionalPublicIdentifier<NodeParams.SendDefundChannelTx>, ): Promise<Result<NodeResponses.SendDefundChannelTx, ServerNodeServiceError>> { return this.executeHttpRequest(`send-defund-channel-tx`, "post", params, NodeParams.SendDefundChannelTxSchema); } getTransferDispute( params: OptionalPublicIdentifier<NodeParams.GetTransferDispute>, ): Promise<Result<NodeResponses.GetTransferDispute, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/transfers/transfer/${params.transferId}/dispute`, "get", params, NodeParams.SendDefundChannelTxSchema, ); } sendDisputeTransferTx( params: OptionalPublicIdentifier<NodeParams.SendDisputeTransferTx>, ): Promise<Result<NodeResponses.SendDisputeTransferTx, ServerNodeServiceError>> { return this.executeHttpRequest(`send-dispute-transfer-tx`, "post", params, NodeParams.SendDisputeTransferTxSchema); } sendDefundTransferTx( params: OptionalPublicIdentifier<NodeParams.SendDefundTransferTx>, ): Promise<Result<NodeResponses.SendDefundTransferTx, ServerNodeServiceError>> { return this.executeHttpRequest(`send-defund-transfer-tx`, "post", params, NodeParams.SendDefundTransferTxSchema); } sendExitChannelTx( params: OptionalPublicIdentifier<NodeParams.SendExitChannelTx>, ): Promise<Result<NodeResponses.SendExitChannelTx, ServerNodeServiceError>> { return this.executeHttpRequest(`send-exit-channel-tx`, "post", params, NodeParams.SendExitChannelTxSchema); } syncDisputes(params: {}): Promise<Result<void, NodeError>> { return this.executeHttpRequest(`sync-disputes`, "post", params, undefined); } async createNode(params: NodeParams.CreateNode): Promise<Result<NodeResponses.CreateNode, ServerNodeServiceError>> { const res = await this.executeHttpRequest<NodeResponses.CreateNode>( `node`, "post", params, NodeParams.CreateNodeSchema, ); if (res.isError) { return res; } if (!this.evts) { return res; } // Register listener subscription const { publicIdentifier } = res.getValue(); // Check if the events have been registered (i.e. this called // twice) if (this.ctxs[publicIdentifier]) { return res; } const urls = Object.fromEntries( Object.entries(this.evts).map(([event, config]) => { return [event, config.url ?? ""]; }), ); // Create an evt context for this public identifier only // (see not in `off`) this.ctxs[publicIdentifier] = Evt.newCtx(); const subscriptionParams: NodeParams.RegisterListener = { events: urls, publicIdentifier, }; // IFF the public identifier is undefined, it should be overridden by // the pubId defined in the parameters. const subscription = await this.executeHttpRequest( `event/subscribe`, "post", subscriptionParams, NodeParams.RegisterListenerSchema, ); if (subscription.isError) { this.logger.error({ error: subscription.getError()!, publicIdentifier }, "Failed to create subscription"); return Result.fail(subscription.getError()!); } this.logger.info({ urls, method: "createNode", publicIdentifier }, "Engine event subscription created"); return res; } async getStateChannel( params: OptionalPublicIdentifier<NodeParams.GetChannelState>, ): Promise<Result<NodeResponses.GetChannelState, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels/${params.channelAddress}`, "get", params, NodeParams.GetChannelStateSchema, ); } async getStateChannels( params: OptionalPublicIdentifier<NodeParams.GetChannelStates>, ): Promise<Result<NodeResponses.GetChannelStates, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels`, "get", params, NodeParams.GetChannelStatesSchema, ); } async getTransfersByRoutingId( params: OptionalPublicIdentifier<NodeParams.GetTransferStatesByRoutingId>, ): Promise<Result<NodeResponses.GetTransferStatesByRoutingId, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/transfers/routing-id/${params.routingId}`, "get", params, NodeParams.GetTransferStatesByRoutingIdSchema, ); } async getTransferByRoutingId( params: OptionalPublicIdentifier<NodeParams.GetTransferStateByRoutingId>, ): Promise<Result<NodeResponses.GetTransferStateByRoutingId, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels/${params.channelAddress}/transfers/routing-id/${ params.routingId }`, "get", params, NodeParams.GetTransferStateByRoutingIdSchema, ); } async getTransfer( params: OptionalPublicIdentifier<NodeParams.GetTransferState>, ): Promise<Result<NodeResponses.GetTransferState, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/transfers/${params.transferId}`, "get", params, NodeParams.GetTransferStateSchema, ); } async getActiveTransfers( params: OptionalPublicIdentifier<NodeParams.GetActiveTransfersByChannelAddress>, ): Promise<Result<NodeResponses.GetActiveTransfersByChannelAddress, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels/${params.channelAddress}/active-transfers`, "get", params, NodeParams.GetActiveTransfersByChannelAddressSchema, ); } async getTransfers( params: OptionalPublicIdentifier< NodeParams.GetTransfers & Omit<GetTransfersFilterOpts, "startDate" | "endDate"> & { startDate: Date; endDate: Date } // in the client, use Date type >, ): Promise<Result<NodeResponses.GetTransfers, ServerNodeServiceError>> { const queryString = [ params.active ? `active=${params.active}` : undefined, params.channelAddress ? `channelAddress=${params.channelAddress}` : undefined, params.routingId ? `routingId=${params.routingId}` : undefined, params.startDate ? `startDate=${Date.parse(params.startDate.toString())}` : undefined, params.endDate ? `endDate=${Date.parse(params.endDate.toString())}` : undefined, ] .filter((x) => !!x) .join("&"); return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/transfers?${queryString}`, "get", params, NodeParams.GetActiveTransfersByChannelAddressSchema, ); } async getStateChannelByParticipants( params: OptionalPublicIdentifier<NodeParams.GetChannelStateByParticipants>, ): Promise<Result<NodeResponses.GetChannelStateByParticipants, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/channels/counterparty/${params.counterparty}/chain-id/${ params.chainId }`, "get", params, NodeParams.GetChannelStateByParticipantsSchema, ); } getRegisteredTransfers( params: OptionalPublicIdentifier<NodeParams.GetRegisteredTransfers>, ): Promise<Result<NodeResponses.GetRegisteredTransfers, ServerNodeServiceError>> { return this.executeHttpRequest( `${params.publicIdentifier ?? this.publicIdentifier}/registered-transfers/chain-id/${params.chainId}`, "get", params, NodeParams.GetRegisteredTransfersSchema, ); } restoreState( params: OptionalPublicIdentifier<NodeParams.RestoreState>, ): Promise<Result<NodeResponses.RestoreState, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.RestoreState>( `restore`, "post", params, NodeParams.RestoreStateSchema, ); } async setup( params: OptionalPublicIdentifier<NodeParams.RequestSetup>, ): Promise<Result<NodeResponses.RequestSetup, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.RequestSetup>("setup", "post", params, NodeParams.RequestSetupSchema); } async internalSetup( params: OptionalPublicIdentifier<NodeParams.Setup>, ): Promise<Result<NodeResponses.Setup, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.Setup>("internal-setup", "post", params, NodeParams.SetupSchema); } async sendDepositTx( params: OptionalPublicIdentifier<NodeParams.SendDepositTx>, ): Promise<Result<NodeResponses.SendDepositTx, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.SendDepositTx>( "send-deposit-tx", "post", params, NodeParams.SendDepositTxSchema, ); } async reconcileDeposit( params: OptionalPublicIdentifier<NodeParams.Deposit>, ): Promise<Result<NodeResponses.Deposit, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.Deposit>( "deposit", "post", { channelAddress: params.channelAddress, assetId: params.assetId, publicIdentifier: params.publicIdentifier, }, NodeParams.DepositSchema, ); } async requestCollateral( params: OptionalPublicIdentifier<NodeParams.RequestCollateral>, ): Promise<Result<NodeResponses.RequestCollateral, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.RequestCollateral>( "request-collateral", "post", params, NodeParams.RequestCollateralSchema, ); } getTransferQuote( params: OptionalPublicIdentifier<NodeParams.TransferQuote>, ): Promise<Result<NodeResponses.TransferQuote, NodeError>> { return this.executeHttpRequest(`transfers/quote`, "post", params, NodeParams.TransferQuoteSchema); } async conditionalTransfer( params: OptionalPublicIdentifier<NodeParams.ConditionalTransfer>, ): Promise<Result<NodeResponses.ConditionalTransfer, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.ConditionalTransfer>( `transfers/create`, "post", params, NodeParams.ConditionalTransferSchema, ); } async resolveTransfer( params: OptionalPublicIdentifier<NodeParams.ResolveTransfer>, ): Promise<Result<NodeResponses.ResolveTransfer, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.ResolveTransfer>( `transfers/resolve`, "post", params, NodeParams.ResolveTransferSchema, ); } withdraw( params: OptionalPublicIdentifier<NodeParams.Withdraw>, ): Promise<Result<NodeResponses.Withdraw, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.Withdraw>(`withdraw`, "post", params, NodeParams.WithdrawSchema); } getWithdrawalQuote( params: OptionalPublicIdentifier<NodeParams.WithdrawalQuote>, ): Promise<Result<NodeResponses.WithdrawalQuote, NodeError>> { return this.executeHttpRequest<NodeResponses.WithdrawalQuote>( `withdraw/quote`, "post", params, NodeParams.WithdrawalQuoteSchema, ); } signUtilityMessage( params: OptionalPublicIdentifier<NodeParams.SignUtilityMessage>, ): Promise<Result<NodeResponses.SignUtilityMessage, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.SignUtilityMessage>( `sign-utility-message`, "post", params, NodeParams.SignUtilityMessageSchema, ); } sendIsAliveMessage( params: OptionalPublicIdentifier<NodeParams.SendIsAlive>, ): Promise<Result<NodeResponses.SendIsAlive, ServerNodeServiceError>> { return this.executeHttpRequest<NodeResponses.SendIsAlive>(`is-alive`, "post", params, NodeParams.SendIsAliveSchema); } public once<T extends EngineEvent>( event: T, callback: (payload: EngineEventMap[T]) => void | Promise<void>, filter: (payload: EngineEventMap[T]) => boolean = () => true, publicIdentifier?: string, ): void { if (!this.evts || !this.evts[event]?.evt) { throw new ServerNodeServiceError( ServerNodeServiceError.reasons.NoEvts, publicIdentifier ?? this.publicIdentifier, "", { event, publicIdentifier }, ); } const pubId = publicIdentifier ?? this.publicIdentifier; if (!pubId) { throw new ServerNodeServiceError(ServerNodeServiceError.reasons.NoPublicIdentifier, "", "", { event, publicIdentifier, }); } const ctx = this.ctxs[publicIdentifier ?? this.publicIdentifier]; this.evts[event].evt .pipe(ctx) .pipe((data: EngineEventMap[T]) => { const filtered = filter(data); const toStrip = data as any; const pubIds = [toStrip.publicIdentifier, toStrip.bobIdentifier, toStrip.aliceIdentifier].filter((x) => !!x); return filtered && pubIds.includes(pubId); }) .attachOnce(callback); } public on<T extends EngineEvent>( event: T, callback: (payload: EngineEventMap[T]) => void | Promise<void>, filter: (payload: EngineEventMap[T]) => boolean = () => true, publicIdentifier?: string, ): void { if (!this.evts || !this.evts[event]?.evt) { throw new ServerNodeServiceError( ServerNodeServiceError.reasons.NoEvts, publicIdentifier ?? this.publicIdentifier, "", { event, publicIdentifier }, ); } const pubId = publicIdentifier ?? this.publicIdentifier; if (!pubId) { throw new ServerNodeServiceError(ServerNodeServiceError.reasons.NoPublicIdentifier, "", "", { event, publicIdentifier, }); } const ctx = this.ctxs[pubId]; this.evts[event].evt .pipe(ctx) .pipe((data: EngineEventMap[T]) => { const filtered = filter(data); const toStrip = data as any; const pubIds = [toStrip.publicIdentifier, toStrip.bobIdentifier, toStrip.aliceIdentifier].filter((x) => !!x); return filtered && pubIds.includes(pubId); }) .attach(callback); } public waitFor<T extends EngineEvent>( event: T, timeout: number, filter: (payload: EngineEventMap[T]) => boolean = () => true, publicIdentifier?: string, ): Promise<EngineEventMap[T] | undefined> { if (!this.evts || !this.evts[event]?.evt) { throw new ServerNodeServiceError( ServerNodeServiceError.reasons.NoEvts, publicIdentifier ?? this.publicIdentifier, "", { event, timeout, publicIdentifier }, ); } const pubId = publicIdentifier ?? this.publicIdentifier; if (!pubId) { throw new ServerNodeServiceError(ServerNodeServiceError.reasons.NoPublicIdentifier, "", "", { event, publicIdentifier, }); } const ctx = this.ctxs[pubId]; return this.evts[event].evt .pipe(ctx) .pipe((data: EngineEventMap[T]) => { const filtered = filter(data); const toStrip = data as any; const pubIds = [toStrip.publicIdentifier, toStrip.bobIdentifier, toStrip.aliceIdentifier].filter((x) => !!x); return filtered && pubIds.includes(pubId); }) .waitFor(timeout) as Promise<EngineEventMap[T]>; } public off<T extends EngineEvent>(event: T, publicIdentifier?: string): void { if (!this.evts || !this.evts[event]?.evt) { throw new ServerNodeServiceError( ServerNodeServiceError.reasons.NoEvts, publicIdentifier ?? this.publicIdentifier, "", { event, publicIdentifier }, ); } if (!publicIdentifier && !this.publicIdentifier) { throw new ServerNodeServiceError(ServerNodeServiceError.reasons.NoPublicIdentifier, "", "", { event, publicIdentifier, }); } const ctx = this.ctxs[publicIdentifier ?? this.publicIdentifier]; ctx.done(); } // Helper methods private async executeHttpRequest<U>( urlPath: string, method: "get" | "post", params: any, paramSchema: any, ): Promise<Result<U, ServerNodeServiceError>> { const url = `${this.serverNodeUrl}/${urlPath}`; const filled = { publicIdentifier: this.publicIdentifier, ...params }; if (paramSchema) { // Validate parameters are in line with schema const validate = ajv.compile(paramSchema); // IFF the public identifier is undefined, it should be overridden by // the pubId defined in the parameters. if (!validate(filled)) { return Result.fail( new ServerNodeServiceError( ServerNodeServiceError.reasons.InvalidParams, (filled as any).publicIdentifer, urlPath, params, { paramsError: validate.errors?.map((err) => err.message).join(","), }, ), ); } } // Attempt request try { const res = method === "get" ? await Axios.get(url) : await Axios.post(url, filled); return Result.ok(res.data); } catch (e) { const jsonErr = Object.keys(e).includes("toJSON") ? e.toJSON() : e; const msg = e.response?.data?.message ?? jsonErr.message ?? ServerNodeServiceError.reasons.InternalServerError; const toThrow = new ServerNodeServiceError( msg.includes("timed out") || msg.includes("timeout") ? ServerNodeServiceError.reasons.Timeout : msg, (filled as any).publicIdentifier, urlPath, params, { ...(e.response?.data ?? { stack: jsonErr.stack ?? "" }), }, ); return Result.fail(toThrow); } } }
the_stack
export interface DescribeRolesResponse { /** * 记录数。 */ TotalCount: number; /** * 角色数组。 */ RoleSets: Array<Role>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeBindClusters返回参数结构体 */ export interface DescribeBindClustersResponse { /** * 专享集群的数量 */ TotalCount: number; /** * 专享集群的列表 */ ClusterSet: Array<BindCluster>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * cmq DeadLetterPolicy */ export interface CmqDeadLetterPolicy { /** * 死信队列。 注意:此字段可能返回 null,表示取不到有效值。 */ DeadLetterQueue: string; /** * 死信队列策略。 注意:此字段可能返回 null,表示取不到有效值。 */ Policy: number; /** * 最大未消费过期时间。Policy为1时必选。范围300-43200,单位秒,需要小于消息最大保留时间MsgRetentionSeconds。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxTimeToLive: number; /** * 最大接收次数。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxReceiveCount: number; } /** * 运营端命名空间bundle实体 */ export declare type BundleSetOpt = null; /** * DescribeSubscriptions请求参数结构体 */ export interface DescribeSubscriptionsRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * 订阅者名称,模糊匹配。 */ SubscriptionName?: string; /** * 数据过滤条件。 */ Filters?: Array<FilterSubscription>; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * 角色实例 */ export interface Role { /** * 角色名称。 */ RoleName: string; /** * 角色token值。 */ Token: string; /** * 备注说明。 */ Remark: string; /** * 创建时间。 */ CreateTime: string; /** * 更新时间。 */ UpdateTime: string; } /** * DeleteCluster返回参数结构体 */ export interface DeleteClusterResponse { /** * 集群的ID */ ClusterId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendBatchMessages返回参数结构体 */ export interface SendBatchMessagesResponse { /** * 消息的唯一标识 注意:此字段可能返回 null,表示取不到有效值。 */ MessageId: string; /** * 错误消息,返回为 "",代表没有错误 注意:此字段可能返回 null,表示取不到有效值。 */ ErrorMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyCmqSubscriptionAttribute返回参数结构体 */ export interface ModifyCmqSubscriptionAttributeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateCmqTopic请求参数结构体 */ export interface CreateCmqTopicRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。 */ MaxMsgSize?: number; /** * 用于指定主题的消息匹配策略。1:表示标签匹配策略;2:表示路由匹配策略,默认值为标签匹配策略。 */ FilterType?: number; /** * 消息保存时间。取值范围60 - 86400 s(即1分钟 - 1天),默认值86400。 */ MsgRetentionSeconds?: number; /** * 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。 */ Trace?: boolean; } /** * ReceiveMessage请求参数结构体 */ export interface ReceiveMessageRequest { /** * 接收消息的topic的名字, 这里尽量需要使用topic的全路径,如果不指定,即:tenant/namespace/topic。默认使用的是:public/default */ Topic: string; /** * 订阅者的名字 */ SubscriptionName: string; /** * 默认值为1000,consumer接收的消息会首先存储到receiverQueueSize这个队列中,用作调优接收消息的速率 */ ReceiverQueueSize?: number; /** * 默认值为:Latest。用作判定consumer初始接收消息的位置,可选参数为:Earliest, Latest */ SubInitialPosition?: string; } /** * 用户专享集群信息 */ export interface BindCluster { /** * 物理集群的名称 */ ClusterName: string; } /** * ModifyCluster返回参数结构体 */ export interface ModifyClusterResponse { /** * Pulsar 集群的ID */ ClusterId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqQueues返回参数结构体 */ export interface DescribeCmqQueuesResponse { /** * 数量 */ TotalCount: number; /** * 队列列表 注意:此字段可能返回 null,表示取不到有效值。 */ QueueList: Array<CmqQueue>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteCmqQueue返回参数结构体 */ export interface DeleteCmqQueueResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateCmqSubscribe请求参数结构体 */ export interface CreateCmqSubscribeRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ SubscriptionName: string; /** * 订阅的协议,目前支持两种协议:http、queue。使用http协议,用户需自己搭建接受消息的web server。使用queue,消息会自动推送到CMQ queue,用户可以并发地拉取消息。 */ Protocol: string; /** * 接收通知的Endpoint,根据协议Protocol区分:对于http,Endpoint必须以“`http://`”开头,host可以是域名或IP;对于Queue,则填QueueName。 请注意,目前推送服务不能推送到私有网络中,因此Endpoint填写为私有网络域名或地址将接收不到推送的消息,目前支持推送到公网和基础网络。 */ Endpoint: string; /** * 向Endpoint推送消息出现错误时,CMQ推送服务器的重试策略。取值有:1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息;2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始1s,后面是2s,4s,8s...由于Topic消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是EXPONENTIAL_DECAY_RETRY。 */ NotifyStrategy?: string; /** * 消息正文。消息标签(用于消息过滤)。标签数量不能超过5个,每个标签不超过16个字符。与(Batch)PublishMessage的MsgTag参数配合使用,规则:1)如果FilterTag没有设置,则无论MsgTag是否有设置,订阅接收所有发布到Topic的消息;2)如果FilterTag数组有值,则只有数组中至少有一个值在MsgTag数组中也存在时(即FilterTag和MsgTag有交集),订阅才接收该发布到Topic的消息;3)如果FilterTag数组有值,但MsgTag没设置,则不接收任何发布到Topic的消息,可以认为是2)的一种特例,此时FilterTag和MsgTag没有交集。规则整体的设计思想是以订阅者的意愿为主。 */ FilterTag?: Array<string>; /** * BindingKey数量不超过5个, 每个BindingKey长度不超过64字节,该字段表示订阅接收消息的过滤策略,每个BindingKey最多含有15个“.”, 即最多16个词组。 */ BindingKey?: Array<string>; /** * 推送内容的格式。取值:1)JSON;2)SIMPLIFIED,即raw格式。如果Protocol是queue,则取值必须为SIMPLIFIED。如果Protocol是http,两个值均可以,默认值是JSON。 */ NotifyContentFormat?: string; } /** * RewindCmqQueue返回参数结构体 */ export interface RewindCmqQueueResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteCluster请求参数结构体 */ export interface DeleteClusterRequest { /** * 集群Id,传入需要删除的集群Id。 */ ClusterId: string; } /** * cmq订阅返回参数 */ export interface CmqSubscription { /** * 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 注意:此字段可能返回 null,表示取不到有效值。 */ SubscriptionName: string; /** * 订阅 ID。订阅 ID 在拉取监控数据时会用到。 注意:此字段可能返回 null,表示取不到有效值。 */ SubscriptionId: string; /** * 订阅拥有者的 APPID。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicOwner: number; /** * 该订阅待投递的消息数。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgCount: number; /** * 最后一次修改订阅属性的时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifyTime: number; /** * 订阅的创建时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: number; /** * 表示订阅接收消息的过滤策略。 注意:此字段可能返回 null,表示取不到有效值。 */ BindingKey: Array<string>; /** * 接收通知的 endpoint,根据协议 protocol 区分:对于 HTTP,endpoint 必须以http://开头,host 可以是域名或 IP;对于 queue,则填 queueName。 注意:此字段可能返回 null,表示取不到有效值。 */ Endpoint: string; /** * 描述用户创建订阅时选择的过滤策略: filterType = 1表示用户使用 filterTag 标签过滤 filterType = 2表示用户使用 bindingKey 过滤。 注意:此字段可能返回 null,表示取不到有效值。 */ FilterTags: Array<string>; /** * 订阅的协议,目前支持两种协议:HTTP、queue。使用 HTTP 协议,用户需自己搭建接受消息的 Web Server。使用 queue,消息会自动推送到 CMQ queue,用户可以并发地拉取消息。 注意:此字段可能返回 null,表示取不到有效值。 */ Protocol: string; /** * 向 endpoint 推送消息出现错误时,CMQ 推送服务器的重试策略。取值有: (1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息; (2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始 1s,后面是 2s,4s,8s...由于 Topic 消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是 EXPONENTIAL_DECAY_RETRY。 注意:此字段可能返回 null,表示取不到有效值。 */ NotifyStrategy: string; /** * 推送内容的格式。取值:(1)JSON;(2)SIMPLIFIED,即 raw 格式。如果 protocol 是 queue,则取值必须为 SIMPLIFIED。如果 protocol 是 HTTP,两个值均可以,默认值是 JSON。 注意:此字段可能返回 null,表示取不到有效值。 */ NotifyContentFormat: string; } /** * DeleteCmqTopic返回参数结构体 */ export interface DeleteCmqTopicResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateSubscription请求参数结构体 */ export interface CreateSubscriptionRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; /** * 订阅者名称,不支持中字以及除了短线和下划线外的特殊字符且不超过150个字符。 */ SubscriptionName: string; /** * 是否幂等创建,若否不允许创建同名的订阅关系。 */ IsIdempotent: boolean; /** * 备注,128个字符以内。 */ Remark?: string; /** * Pulsar 集群的ID */ ClusterId?: string; /** * 是否自动创建死信和重试主题,True 表示创建,False表示不创建,默认自动创建死信和重试主题。 */ AutoCreatePolicyTopic?: boolean; /** * 指定死信和重试主题名称规范,LEGACY表示历史命名规则,COMMUNITY表示Pulsar社区命名规范 */ PostFixPattern?: string; } /** * DescribeCmqTopicDetail返回参数结构体 */ export interface DescribeCmqTopicDetailResponse { /** * 主题详情 */ TopicDescribe: CmqTopic; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * cmq 批量queue属性信息 */ export interface CmqQueue { /** * 消息队列ID。 */ QueueId: string; /** * 消息队列名字。 */ QueueName: string; /** * 每秒钟生产消息条数的限制,消费消息的大小是该值的1.1倍。 注意:此字段可能返回 null,表示取不到有效值。 */ Qps: number; /** * 带宽限制。 注意:此字段可能返回 null,表示取不到有效值。 */ Bps: number; /** * 飞行消息最大保留时间。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxDelaySeconds: number; /** * 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。 */ MaxMsgHeapNum: number; /** * 消息接收长轮询等待时间。取值范围0 - 30秒,默认值0。 注意:此字段可能返回 null,表示取不到有效值。 */ PollingWaitSeconds: number; /** * 消息保留周期。取值范围60-1296000秒(1min-15天),默认值345600秒(4 天)。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRetentionSeconds: number; /** * 消息可见性超时。取值范围1 - 43200秒(即12小时内),默认值30。 注意:此字段可能返回 null,表示取不到有效值。 */ VisibilityTimeout: number; /** * 消息最大长度。取值范围1024 - 1048576 Byte(即1K - 1024K),默认值65536。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxMsgSize: number; /** * 回溯队列的消息回溯时间最大值,取值范围0 - 43200秒,0表示不开启消息回溯。 注意:此字段可能返回 null,表示取不到有效值。 */ RewindSeconds: number; /** * 队列的创建时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: number; /** * 最后一次修改队列属性的时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifyTime: number; /** * 在队列中处于 Active 状态(不处于被消费状态)的消息总数,为近似值。 注意:此字段可能返回 null,表示取不到有效值。 */ ActiveMsgNum: number; /** * 在队列中处于 Inactive 状态(正处于被消费状态)的消息总数,为近似值。 注意:此字段可能返回 null,表示取不到有效值。 */ InactiveMsgNum: number; /** * 延迟消息数。 注意:此字段可能返回 null,表示取不到有效值。 */ DelayMsgNum: number; /** * 已调用 DelMsg 接口删除,但还在回溯保留时间内的消息数量。 注意:此字段可能返回 null,表示取不到有效值。 */ RewindMsgNum: number; /** * 消息最小未消费时间,单位为秒。 注意:此字段可能返回 null,表示取不到有效值。 */ MinMsgTime: number; /** * 事务消息队列。true表示是事务消息,false表示不是事务消息。 注意:此字段可能返回 null,表示取不到有效值。 */ Transaction: boolean; /** * 死信队列。 注意:此字段可能返回 null,表示取不到有效值。 */ DeadLetterSource: Array<CmqDeadLetterSource>; /** * 死信队列策略。 注意:此字段可能返回 null,表示取不到有效值。 */ DeadLetterPolicy: CmqDeadLetterPolicy; /** * 事务消息策略。 注意:此字段可能返回 null,表示取不到有效值。 */ TransactionPolicy: CmqTransactionPolicy; /** * 创建者Uin。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateUin: number; /** * 关联的标签。 注意:此字段可能返回 null,表示取不到有效值。 */ Tags: Array<Tag>; /** * 消息轨迹。true表示开启,false表示不开启。 注意:此字段可能返回 null,表示取不到有效值。 */ Trace: boolean; /** * 租户id 注意:此字段可能返回 null,表示取不到有效值。 */ TenantId: string; /** * 命名空间名称 注意:此字段可能返回 null,表示取不到有效值。 */ NamespaceName: string; } /** * CreateEnvironment返回参数结构体 */ export interface CreateEnvironmentResponse { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 未消费消息过期时间,单位:秒。 */ MsgTTL: number; /** * 说明,128个字符以内。 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 命名空间ID */ NamespaceId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 生产者 */ export interface Producer { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; /** * 连接数。 注意:此字段可能返回 null,表示取不到有效值。 */ CountConnect: number; /** * 连接集合。 注意:此字段可能返回 null,表示取不到有效值。 */ ConnectionSets: Array<Connection>; } /** * CreateSubscription返回参数结构体 */ export interface CreateSubscriptionResponse { /** * 创建结果。 */ Result: boolean; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendMsg返回参数结构体 */ export interface SendMsgResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyCmqTopicAttribute返回参数结构体 */ export interface ModifyCmqTopicAttributeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqSubscriptionDetail请求参数结构体 */ export interface DescribeCmqSubscriptionDetailRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 分页时本页获取主题列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0 */ Offset?: number; /** * 分页时本页获取主题的个数,如果不传递该参数,则该参数默认为20,最大值为50。 */ Limit?: number; /** * 根据SubscriptionName进行模糊搜索 */ SubscriptionName?: string; } /** * 主题实例 */ export interface Topic { /** * 最后一次间隔内发布消息的平均byte大小。 注意:此字段可能返回 null,表示取不到有效值。 */ AverageMsgSize: string; /** * 消费者数量。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerCount: string; /** * 被记录下来的消息总数。 注意:此字段可能返回 null,表示取不到有效值。 */ LastConfirmedEntry: string; /** * 最后一个ledger创建的时间。 注意:此字段可能返回 null,表示取不到有效值。 */ LastLedgerCreatedTimestamp: string; /** * 本地和复制的发布者每秒发布消息的速率。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateIn: string; /** * 本地和复制的消费者每秒分发消息的数量之和。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateOut: string; /** * 本地和复制的发布者每秒发布消息的byte。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputIn: string; /** * 本地和复制的消费者每秒分发消息的byte。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputOut: string; /** * 被记录下来的消息总数。 注意:此字段可能返回 null,表示取不到有效值。 */ NumberOfEntries: string; /** * 分区数<=0:topic下无子分区。 注意:此字段可能返回 null,表示取不到有效值。 */ Partitions: number; /** * 生产者数量。 注意:此字段可能返回 null,表示取不到有效值。 */ ProducerCount: string; /** * 以byte计算的所有消息存储总量。 注意:此字段可能返回 null,表示取不到有效值。 */ TotalSize: string; /** * 分区topic里面的子分区。 注意:此字段可能返回 null,表示取不到有效值。 */ SubTopicSets: Array<PartitionsTopic>; /** * topic类型描述: 0:普通消息; 1:全局顺序消息; 2:局部顺序消息; 3:重试队列; 4:死信队列; 5:事务消息。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicType: number; /** * 环境(命名空间)名称。 注意:此字段可能返回 null,表示取不到有效值。 */ EnvironmentId: string; /** * 主题名称。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicName: string; /** * 说明,128个字符以内。 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 创建时间。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string; /** * 最近修改时间。 注意:此字段可能返回 null,表示取不到有效值。 */ UpdateTime: string; /** * 生产者上限。 注意:此字段可能返回 null,表示取不到有效值。 */ ProducerLimit: string; /** * 消费者上限。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerLimit: string; } /** * DescribeEnvironments请求参数结构体 */ export interface DescribeEnvironmentsRequest { /** * 命名空间名称,模糊搜索。 */ EnvironmentId?: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * Pulsar 集群的ID */ ClusterId?: string; /** * * EnvironmentId 按照名称空间进行过滤,精确查询。 类型:String 必选:否 */ Filters?: Array<Filter>; } /** * DescribeCmqQueueDetail返回参数结构体 */ export interface DescribeCmqQueueDetailResponse { /** * 队列详情列表。 */ QueueDescribe: CmqQueue; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateEnvironment请求参数结构体 */ export interface CreateEnvironmentRequest { /** * 环境(命名空间)名称,不支持中字以及除了短线和下划线外的特殊字符且不超过16个字符。 */ EnvironmentId: string; /** * 未消费消息过期时间,单位:秒,最小60,最大1296000,(15天)。 */ MsgTTL: number; /** * 说明,128个字符以内。 */ Remark?: string; /** * Pulsar 集群的ID */ ClusterId?: string; /** * 消息保留策略 */ RetentionPolicy?: RetentionPolicy; } /** * DeleteTopics返回参数结构体 */ export interface DeleteTopicsResponse { /** * 被删除的主题数组。 */ TopicSets: Array<TopicRecord>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeClusters请求参数结构体 */ export interface DescribeClustersRequest { /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * 集群ID列表过滤 */ ClusterIdList?: Array<string>; } /** * ModifyEnvironmentAttributes请求参数结构体 */ export interface ModifyEnvironmentAttributesRequest { /** * 命名空间名称。 */ EnvironmentId: string; /** * 未消费消息过期时间,单位:秒,最大1296000。 */ MsgTTL: number; /** * 备注,字符串最长不超过128。 */ Remark?: string; /** * 集群ID */ ClusterId?: string; /** * 消息保留策略 */ RetentionPolicy?: RetentionPolicy; } /** * DescribeCmqSubscriptionDetail返回参数结构体 */ export interface DescribeCmqSubscriptionDetailResponse { /** * 总数 */ TotalCount: number; /** * Subscription属性集合 注意:此字段可能返回 null,表示取不到有效值。 */ SubscriptionSet: Array<CmqSubscription>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * vcp绑定记录 */ export interface VpcBindRecord { /** * 租户Vpc Id */ UniqueVpcId: string; /** * 租户Vpc子网Id */ UniqueSubnetId: string; /** * 路由Id */ RouterId: string; /** * Vpc的Id */ Ip: string; /** * Vpc的Port */ Port: number; /** * 说明,128个字符以内 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; } /** * RewindCmqQueue请求参数结构体 */ export interface RewindCmqQueueRequest { /** * 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ QueueName: string; /** * 设定该时间,则(Batch)receiveMessage接口,会按照生产消息的先后顺序消费该时间戳以后的消息。 */ StartConsumeTime: number; } /** * ModifyCluster请求参数结构体 */ export interface ModifyClusterRequest { /** * Pulsar 集群的ID,需要更新的集群Id。 */ ClusterId: string; /** * 更新后的集群名称。 */ ClusterName?: string; /** * 说明信息。 */ Remark?: string; } /** * DescribeEnvironmentAttributes请求参数结构体 */ export interface DescribeEnvironmentAttributesRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * AcknowledgeMessage请求参数结构体 */ export interface AcknowledgeMessageRequest { /** * 用作标识消息的唯一的ID(可从 receiveMessage 的返回值中获得) */ MessageId: string; /** * Topic 名字(可从 receiveMessage 的返回值中获得)这里尽量需要使用topic的全路径,即:tenant/namespace/topic。如果不指定,默认使用的是:public/default */ AckTopic: string; /** * 订阅者的名字,可以从receiveMessage的返回值中获取到。这里尽量与receiveMessage中的订阅者保持一致,否则没办法正确ack 接收回来的消息。 */ SubName: string; } /** * DescribeTopics返回参数结构体 */ export interface DescribeTopicsResponse { /** * 主题集合数组。 */ TopicSets: Array<Topic>; /** * 主题数量。 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * PublishCmqMsg返回参数结构体 */ export interface PublishCmqMsgResponse { /** * true表示发送成功 */ Result: boolean; /** * 消息id */ MsgId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendCmqMsg请求参数结构体 */ export interface SendCmqMsgRequest { /** * 队列名 */ QueueName: string; /** * 消息内容 */ MsgContent: string; /** * 延迟时间 */ DelaySeconds: number; } /** * AcknowledgeMessage返回参数结构体 */ export interface AcknowledgeMessageResponse { /** * 如果为“”,则说明没有错误返回 注意:此字段可能返回 null,表示取不到有效值。 */ ErrorMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteEnvironmentRoles返回参数结构体 */ export interface DeleteEnvironmentRolesResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeClusterDetail请求参数结构体 */ export interface DescribeClusterDetailRequest { /** * 集群的ID */ ClusterId: string; } /** * ModifyRole返回参数结构体 */ export interface ModifyRoleResponse { /** * 角色名称 */ RoleName: string; /** * 备注说明 */ Remark: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 标签的key/value的类型 */ export interface Tag { /** * 标签的key的值 */ TagKey: string; /** * 标签的Value的值 */ TagValue: string; } /** * DescribeNamespaceBundlesOpt返回参数结构体 */ export interface DescribeNamespaceBundlesOptResponse { /** * 记录条数 */ TotalCount: number; /** * bundle列表 */ BundleSet: Array<BundleSetOpt>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendMessages请求参数结构体 */ export interface SendMessagesRequest { /** * 消息要发送的topic的名字, 这里尽量需要使用topic的全路径,即:tenant/namespace/topic。如果不指定,默认使用的是:public/default */ Topic: string; /** * 要发送的消息的内容 */ Payload: string; /** * Token 是用来做鉴权使用的,可以不填,系统会自动获取 */ StringToken?: string; /** * 设置 producer 的名字,要求全局唯一,用户不配置,系统会随机生成 */ ProducerName?: string; /** * 设置消息发送的超时时间,默认为30s */ SendTimeout?: number; /** * 内存中缓存的最大的生产消息的数量,默认为1000条 */ MaxPendingMessages?: number; } /** * ModifyCmqTopicAttribute请求参数结构体 */ export interface ModifyCmqTopicAttributeRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 消息最大长度。取值范围1024 - 65536 Byte(即1 - 64K),默认值65536。 */ MaxMsgSize?: number; /** * 消息保存时间。取值范围60 - 86400 s(即1分钟 - 1天),默认值86400。 */ MsgRetentionSeconds?: number; /** * 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。 */ Trace?: boolean; } /** * DeleteRoles请求参数结构体 */ export interface DeleteRolesRequest { /** * 角色名称数组。 */ RoleNames: Array<string>; /** * 必填字段,集群Id */ ClusterId?: string; } /** * 订阅者 */ export interface Subscription { /** * 主题名称。 */ TopicName: string; /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 消费者开始连接的时间。 注意:此字段可能返回 null,表示取不到有效值。 */ ConnectedSince: string; /** * 消费者地址。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerAddr: string; /** * 消费者数量。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerCount: string; /** * 消费者名称。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerName: string; /** * 堆积的消息数量。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgBacklog: string; /** * 于TTL,此订阅下没有被发送而是被丢弃的比例。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateExpired: string; /** * 消费者每秒分发消息的数量之和。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateOut: string; /** * 消费者每秒消息的byte。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputOut: string; /** * 订阅名称。 注意:此字段可能返回 null,表示取不到有效值。 */ SubscriptionName: string; /** * 消费者集合。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerSets: Array<Consumer>; /** * 是否在线。 注意:此字段可能返回 null,表示取不到有效值。 */ IsOnline: boolean; /** * 消费进度集合。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumersScheduleSets: Array<ConsumersSchedule>; /** * 备注。 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 创建时间。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string; /** * 最近修改时间。 注意:此字段可能返回 null,表示取不到有效值。 */ UpdateTime: string; } /** * CreateCmqSubscribe返回参数结构体 */ export interface CreateCmqSubscribeResponse { /** * 订阅id */ SubscriptionId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeSubscriptions返回参数结构体 */ export interface DescribeSubscriptionsResponse { /** * 订阅者集合数组。 */ SubscriptionSets: Array<Subscription>; /** * 数量。 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyRole请求参数结构体 */ export interface ModifyRoleRequest { /** * 角色名称,不支持中字以及除了短线和下划线外的特殊字符且长度必须大于0且小等于32。 */ RoleName: string; /** * 备注说明,长度必须大等于0且小等于128。 */ Remark?: string; /** * 必填字段,集群Id */ ClusterId?: string; } /** * SendMessages返回参数结构体 */ export interface SendMessagesResponse { /** * 消息的messageID, 是全局唯一的,用来标识消息的元数据信息 注意:此字段可能返回 null,表示取不到有效值。 */ MessageId: string; /** * 返回的错误消息,如果返回为 “”,说明没有错误 注意:此字段可能返回 null,表示取不到有效值。 */ ErrorMsg: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateTopic请求参数结构体 */ export interface CreateTopicRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名,不支持中字以及除了短线和下划线外的特殊字符且不超过64个字符。 */ TopicName: string; /** * 0:非分区topic,无分区;非0:具体分区topic的分区数,最大不允许超过128。 */ Partitions: number; /** * 0: 普通消息; 1 :全局顺序消息; 2 :局部顺序消息; 3 :重试队列; 4 :死信队列。 */ TopicType: number; /** * 备注,128字符以内。 */ Remark?: string; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * DescribeTopics请求参数结构体 */ export interface DescribeTopicsRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名模糊匹配。 */ TopicName?: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * topic类型描述: 0:普通消息; 1:全局顺序消息; 2:局部顺序消息; 3:重试队列; 4:死信队列; 5:事务消息。 */ TopicType?: number; /** * Pulsar 集群的ID */ ClusterId?: string; /** * * TopicName 按照主题名字查询,精确查询。 类型:String 必选:否 */ Filters?: Array<Filter>; } /** * DeleteEnvironments返回参数结构体 */ export interface DeleteEnvironmentsResponse { /** * 成功删除的环境(命名空间)数组。 */ EnvironmentIds: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeEnvironmentRoles返回参数结构体 */ export interface DescribeEnvironmentRolesResponse { /** * 记录数。 */ TotalCount: number; /** * 命名空间角色集合。 */ EnvironmentRoleSets: Array<EnvironmentRole>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ClearCmqQueue请求参数结构体 */ export interface ClearCmqQueueRequest { /** * 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ QueueName: string; } /** * 过滤订阅列表 */ export interface FilterSubscription { /** * 是否仅展示包含真实消费者的订阅。 */ ConsumerHasCount?: boolean; /** * 是否仅展示消息堆积的订阅。 */ ConsumerHasBacklog?: boolean; /** * 是否仅展示存在消息超期丢弃的订阅。 */ ConsumerHasExpired?: boolean; /** * 按照订阅名过滤,精确查询。 */ SubscriptionNames?: Array<string>; } /** * DescribeCmqTopics返回参数结构体 */ export interface DescribeCmqTopicsResponse { /** * 主题列表 注意:此字段可能返回 null,表示取不到有效值。 */ TopicList: Array<CmqTopic>; /** * 全量主题数量 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqTopicDetail请求参数结构体 */ export interface DescribeCmqTopicDetailRequest { /** * 精确匹配TopicName。 */ TopicName?: string; } /** * cmq topic返回信息展示字段 */ export interface CmqTopic { /** * 主题的 ID。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicId: string; /** * 主题名称。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicName: string; /** * 消息在主题中最长存活时间,从发送到该主题开始经过此参数指定的时间后,不论消息是否被成功推送给用户都将被删除,单位为秒。固定为一天(86400秒),该属性不能修改。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRetentionSeconds: number; /** * 消息最大长度。取值范围1024 - 1048576Byte(即1 - 1024K),默认值为65536。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxMsgSize: number; /** * 每秒钟发布消息的条数。 注意:此字段可能返回 null,表示取不到有效值。 */ Qps: number; /** * 描述用户创建订阅时选择的过滤策略: FilterType = 1表示用户使用 FilterTag 标签过滤; FilterType = 2表示用户使用 BindingKey 过滤。 注意:此字段可能返回 null,表示取不到有效值。 */ FilterType: number; /** * 主题的创建时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: number; /** * 最后一次修改主题属性的时间。返回 Unix 时间戳,精确到毫秒。 注意:此字段可能返回 null,表示取不到有效值。 */ LastModifyTime: number; /** * 当前该主题中消息数目(消息堆积数)。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgCount: number; /** * 创建者 Uin,CAM 鉴权 resource 由该字段组合而成。 注意:此字段可能返回 null,表示取不到有效值。 */ CreateUin: number; /** * 关联的标签。 注意:此字段可能返回 null,表示取不到有效值。 */ Tags: Array<Tag>; /** * 消息轨迹。true表示开启,false表示不开启。 注意:此字段可能返回 null,表示取不到有效值。 */ Trace: boolean; /** * 租户id 注意:此字段可能返回 null,表示取不到有效值。 */ TenantId: string; /** * 命名空间名称 注意:此字段可能返回 null,表示取不到有效值。 */ NamespaceName: string; } /** * UnbindCmqDeadLetter返回参数结构体 */ export interface UnbindCmqDeadLetterResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeNodeHealthOpt请求参数结构体 */ export interface DescribeNodeHealthOptRequest { /** * 节点实例ID */ InstanceId: string; } /** * DescribeBindVpcs请求参数结构体 */ export interface DescribeBindVpcsRequest { /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * DescribeClusters返回参数结构体 */ export interface DescribeClustersResponse { /** * 集群列表数量 */ TotalCount: number; /** * 集群信息列表 */ ClusterSet: Array<Cluster>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ClearCmqSubscriptionFilterTags请求参数结构体 */ export interface ClearCmqSubscriptionFilterTagsRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ SubscriptionName: string; } /** * 主题关键信息 */ export interface TopicRecord { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; } /** * DescribeEnvironmentRoles请求参数结构体 */ export interface DescribeEnvironmentRolesRequest { /** * 必填字段,环境(命名空间)名称。 */ EnvironmentId?: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * 必填字段,Pulsar 集群的ID */ ClusterId?: string; /** * 角色名称 */ RoleName?: string; /** * * RoleName 按照角色名进行过滤,精确查询。 类型:String 必选:否 */ Filters?: Array<Filter>; } /** * DeleteRoles返回参数结构体 */ export interface DeleteRolesResponse { /** * 成功删除的角色名称数组。 */ RoleNames: Array<string>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 命名空间信息 */ export interface Environment { /** * 命名空间名称 */ EnvironmentId: string; /** * 说明 */ Remark: string; /** * 未消费消息过期时间,单位:秒,最大1296000(15天) */ MsgTTL: number; /** * 创建时间 */ CreateTime: string; /** * 最近修改时间 */ UpdateTime: string; /** * 命名空间ID */ NamespaceId: string; /** * 命名空间名称 */ NamespaceName: string; /** * Topic数量 注意:此字段可能返回 null,表示取不到有效值。 */ TopicNum: number; /** * 消息保留策略 注意:此字段可能返回 null,表示取不到有效值。 */ RetentionPolicy: RetentionPolicy; } /** * CreateCmqQueue返回参数结构体 */ export interface CreateCmqQueueResponse { /** * 创建成功的queueId */ QueueId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 分区topic */ export interface PartitionsTopic { /** * 最后一次间隔内发布消息的平均byte大小。 注意:此字段可能返回 null,表示取不到有效值。 */ AverageMsgSize: string; /** * 消费者数量。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerCount: string; /** * 被记录下来的消息总数。 注意:此字段可能返回 null,表示取不到有效值。 */ LastConfirmedEntry: string; /** * 最后一个ledger创建的时间。 注意:此字段可能返回 null,表示取不到有效值。 */ LastLedgerCreatedTimestamp: string; /** * 本地和复制的发布者每秒发布消息的速率。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateIn: string; /** * 本地和复制的消费者每秒分发消息的数量之和。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateOut: string; /** * 本地和复制的发布者每秒发布消息的byte。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputIn: string; /** * 本地和复制的消费者每秒分发消息的byte。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputOut: string; /** * 被记录下来的消息总数。 注意:此字段可能返回 null,表示取不到有效值。 */ NumberOfEntries: string; /** * 子分区id。 注意:此字段可能返回 null,表示取不到有效值。 */ Partitions: number; /** * 生产者数量。 注意:此字段可能返回 null,表示取不到有效值。 */ ProducerCount: string; /** * 以byte计算的所有消息存储总量。 注意:此字段可能返回 null,表示取不到有效值。 */ TotalSize: string; /** * topic类型描述。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicType: number; } /** * ResetMsgSubOffsetByTimestamp返回参数结构体 */ export interface ResetMsgSubOffsetByTimestampResponse { /** * 结果。 注意:此字段可能返回 null,表示取不到有效值。 */ Result: boolean; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateCluster返回参数结构体 */ export interface CreateClusterResponse { /** * 集群ID */ ClusterId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqDeadLetterSourceQueues请求参数结构体 */ export interface DescribeCmqDeadLetterSourceQueuesRequest { /** * 死信队列名称 */ DeadLetterQueueName: string; /** * 分页时本页获取主题列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0。 */ Limit?: number; /** * 分页时本页获取主题的个数,如果不传递该参数,则该参数默认为20,最大值为50。 */ Offset?: number; /** * 根据SourceQueueName过滤 */ SourceQueueName?: string; } /** * DescribeNodeHealthOpt返回参数结构体 */ export interface DescribeNodeHealthOptResponse { /** * 0-异常;1-正常 */ NodeState: number; /** * 最近一次健康检查的时间 */ LatestHealthCheckTime: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateCluster请求参数结构体 */ export interface CreateClusterRequest { /** * 集群名称,不支持中字以及除了短线和下划线外的特殊字符且不超过16个字符。 */ ClusterName: string; /** * 用户专享物理集群ID,如果不传,则默认在公共集群上创建用户集群资源。 */ BindClusterId?: number; /** * 说明,128个字符以内。 */ Remark?: string; /** * 集群的标签列表 */ Tags?: Array<Tag>; } /** * ModifyCmqQueueAttribute返回参数结构体 */ export interface ModifyCmqQueueAttributeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateTopic返回参数结构体 */ export interface CreateTopicResponse { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名。 */ TopicName: string; /** * 0:非分区topic,无分区;非0:具体分区topic的分区数。 */ Partitions: number; /** * 备注,128字符以内。 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 0: 普通消息; 1 :全局顺序消息; 2 :局部顺序消息; 3 :重试队列; 4 :死信队列; 5 :事务消息。 注意:此字段可能返回 null,表示取不到有效值。 */ TopicType: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqQueues请求参数结构体 */ export interface DescribeCmqQueuesRequest { /** * 分页时本页获取队列列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0 */ Offset?: number; /** * 分页时本页获取队列的个数,如果不传递该参数,则该参数默认为20,最大值为50。 */ Limit?: number; /** * 根据QueueName进行过滤 */ QueueName?: string; /** * CMQ 队列名称列表过滤 */ QueueNameList?: Array<string>; /** * 标签过滤查找时,需要设置为 true */ IsTagFilter?: boolean; } /** * DescribeEnvironments返回参数结构体 */ export interface DescribeEnvironmentsResponse { /** * 命名空间记录数。 */ TotalCount: number; /** * 命名空间集合数组。 */ EnvironmentSet: Array<Environment>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ModifyCmqSubscriptionAttribute请求参数结构体 */ export interface ModifyCmqSubscriptionAttributeRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ SubscriptionName: string; /** * 向 Endpoint 推送消息出现错误时,CMQ 推送服务器的重试策略。取值如下: (1)BACKOFF_RETRY,退避重试。每隔一定时间重试一次,重试够一定次数后,就把该消息丢弃,继续推送下一条消息。 (2)EXPONENTIAL_DECAY_RETRY,指数衰退重试。每次重试的间隔是指数递增的,例如开始1s,后面是2s,4s,8s···由于 Topic 消息的周期是一天,所以最多重试一天就把消息丢弃。默认值是 EXPONENTIAL_DECAY_RETRY。 */ NotifyStrategy?: string; /** * 推送内容的格式。取值:(1)JSON;(2)SIMPLIFIED,即 raw 格式。如果 Protocol 是 queue,则取值必须为 SIMPLIFIED。如果 Protocol 是 HTTP,两个值均可以,默认值是 JSON。 */ NotifyContentFormat?: string; /** * 消息正文。消息标签(用于消息过滤)。标签数量不能超过5个,每个标签不超过16个字符。与(Batch)PublishMessage的MsgTag参数配合使用,规则:1)如果FilterTag没有设置,则无论MsgTag是否有设置,订阅接收所有发布到Topic的消息;2)如果FilterTag数组有值,则只有数组中至少有一个值在MsgTag数组中也存在时(即FilterTag和MsgTag有交集),订阅才接收该发布到Topic的消息;3)如果FilterTag数组有值,但MsgTag没设置,则不接收任何发布到Topic的消息,可以认为是2)的一种特例,此时FilterTag和MsgTag没有交集。规则整体的设计思想是以订阅者的意愿为主。 */ FilterTags?: Array<string>; /** * BindingKey数量不超过5个, 每个BindingKey长度不超过64字节,该字段表示订阅接收消息的过滤策略,每个BindingKey最多含有15个“.”, 即最多16个词组。 */ BindingKey?: Array<string>; } /** * ModifyTopic返回参数结构体 */ export interface ModifyTopicResponse { /** * 分区数 */ Partitions: number; /** * 备注,128字符以内。 */ Remark: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * ReceiveMessage返回参数结构体 */ export interface ReceiveMessageResponse { /** * 用作标识消息的唯一主键 */ MessageID: string; /** * 接收消息的内容 */ MessagePayload: string; /** * 提供给 Ack 接口,用来Ack哪一个topic中的消息 */ AckTopic: string; /** * 返回的错误信息,如果为空,说明没有错误 注意:此字段可能返回 null,表示取不到有效值。 */ ErrorMsg: string; /** * 返回订阅者的名字,用来创建 ack consumer时使用 注意:此字段可能返回 null,表示取不到有效值。 */ SubName: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateCmqTopic返回参数结构体 */ export interface CreateCmqTopicResponse { /** * 主题id */ TopicId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * Cmq DeadLetterSource */ export interface CmqDeadLetterSource { /** * 消息队列ID。 注意:此字段可能返回 null,表示取不到有效值。 */ QueueId: string; /** * 消息队列名字。 注意:此字段可能返回 null,表示取不到有效值。 */ QueueName: string; } /** * ClearCmqSubscriptionFilterTags返回参数结构体 */ export interface ClearCmqSubscriptionFilterTagsResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeCmqTopics请求参数结构体 */ export interface DescribeCmqTopicsRequest { /** * 分页时本页获取队列列表的起始位置。如果填写了该值,必须也要填写 limit 。该值缺省时,后台取默认值 0 */ Offset?: number; /** * 分页时本页获取队列的个数,如果不传递该参数,则该参数默认为20,最大值为50。 */ Limit?: number; /** * 根据TopicName进行模糊搜索 */ TopicName?: string; /** * CMQ 主题名称列表过滤 */ TopicNameList?: Array<string>; /** * 标签过滤查找时,需要设置为 true */ IsTagFilter?: boolean; } /** * 过滤参数 */ export interface Filter { /** * 过滤参数的名字 */ Name?: string; /** * 数值 */ Values?: Array<string>; } /** * 生产者连接实例 */ export interface Connection { /** * 生产者地址。 注意:此字段可能返回 null,表示取不到有效值。 */ Address: string; /** * 主题分区。 注意:此字段可能返回 null,表示取不到有效值。 */ Partitions: number; /** * 生产者版本。 注意:此字段可能返回 null,表示取不到有效值。 */ ClientVersion: string; /** * 生产者名称。 注意:此字段可能返回 null,表示取不到有效值。 */ ProducerName: string; /** * 生产者ID。 注意:此字段可能返回 null,表示取不到有效值。 */ ProducerId: string; /** * 消息平均大小(byte)。 注意:此字段可能返回 null,表示取不到有效值。 */ AverageMsgSize: string; /** * 生成速率(byte/秒)。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgThroughputIn: string; } /** * DeleteTopics请求参数结构体 */ export interface DeleteTopicsRequest { /** * 主题集合,每次最多删除20个。 */ TopicSets: Array<TopicRecord>; /** * pulsar集群Id。 */ ClusterId?: string; /** * 环境(命名空间)名称。 */ EnvironmentId?: string; /** * 是否强制删除,默认为false */ Force?: boolean; } /** * cmq TransactionPolicy */ export interface CmqTransactionPolicy { /** * 第一次回查时间。 注意:此字段可能返回 null,表示取不到有效值。 */ FirstQueryInterval: number; /** * 最大查询次数。 注意:此字段可能返回 null,表示取不到有效值。 */ MaxQueryCount: number; } /** * DescribeNamespaceBundlesOpt请求参数结构体 */ export interface DescribeNamespaceBundlesOptRequest { /** * 物理集群名 */ ClusterName: string; /** * 虚拟集群(租户)ID */ TenantId: string; /** * 命名空间名 */ NamespaceName: string; /** * 是否需要监控指标,若传false,则不需要传Limit和Offset分页参数 */ NeedMetrics: boolean; /** * 查询限制条数 */ Limit?: number; /** * 查询偏移量 */ Offset?: number; } /** * ModifyTopic请求参数结构体 */ export interface ModifyTopicRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名。 */ TopicName: string; /** * 分区数,必须大于或者等于原分区数,若想维持原分区数请输入原数目,修改分区数仅对非全局顺序消息起效果,不允许超过128个分区。 */ Partitions: number; /** * 备注,128字符以内。 */ Remark?: string; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * ResetMsgSubOffsetByTimestamp请求参数结构体 */ export interface ResetMsgSubOffsetByTimestampRequest { /** * 命名空间名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; /** * 订阅者名称。 */ Subscription: string; /** * 时间戳,精确到毫秒。 */ ToTimestamp: number; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * CreateEnvironmentRole返回参数结构体 */ export interface CreateEnvironmentRoleResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 消费者 */ export interface Consumer { /** * 消费者开始连接的时间。 注意:此字段可能返回 null,表示取不到有效值。 */ ConnectedSince: string; /** * 消费者地址。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerAddr: string; /** * 消费者名称。 注意:此字段可能返回 null,表示取不到有效值。 */ ConsumerName: string; /** * 消费者版本。 注意:此字段可能返回 null,表示取不到有效值。 */ ClientVersion: string; } /** * DescribeBindVpcs返回参数结构体 */ export interface DescribeBindVpcsResponse { /** * 记录数。 */ TotalCount?: number; /** * Vpc集合。 */ VpcSets?: Array<VpcBindRecord>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteCmqSubscribe请求参数结构体 */ export interface DeleteCmqSubscribeRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; /** * 订阅名字,在单个地域同一帐号的同一主题下唯一。订阅名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ SubscriptionName: string; } /** * DescribeCmqDeadLetterSourceQueues返回参数结构体 */ export interface DescribeCmqDeadLetterSourceQueuesResponse { /** * 满足本次条件的队列个数 */ TotalCount: number; /** * 死信队列源队列 */ QueueSet: Array<CmqDeadLetterSource>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteSubscriptions返回参数结构体 */ export interface DeleteSubscriptionsResponse { /** * 成功删除的订阅关系数组。 */ SubscriptionTopicSets: Array<SubscriptionTopic>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 消费进度详情 */ export interface ConsumersSchedule { /** * 当前分区id。 注意:此字段可能返回 null,表示取不到有效值。 */ Partitions: number; /** * 消息数量。 注意:此字段可能返回 null,表示取不到有效值。 */ NumberOfEntries: number; /** * 消息积压数量。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgBacklog: number; /** * 消费者每秒分发消息的数量之和。 */ MsgRateOut: string; /** * 消费者每秒消息的byte。 */ MsgThroughputOut: string; /** * 超时丢弃比例。 注意:此字段可能返回 null,表示取不到有效值。 */ MsgRateExpired: string; } /** * 集群信息集合 */ export interface Cluster { /** * 集群Id。 */ ClusterId: string; /** * 集群名称。 */ ClusterName: string; /** * 说明信息。 */ Remark: string; /** * 接入点数量 */ EndPointNum: number; /** * 创建时间 */ CreateTime: string; /** * 集群是否健康,1表示健康,0表示异常 */ Healthy: number; /** * 集群健康信息 注意:此字段可能返回 null,表示取不到有效值。 */ HealthyInfo: string; /** * 集群状态,0:创建中,1:正常,2:删除中,3:已删除,5:创建失败,6: 删除失败 */ Status: number; /** * 最大命名空间数量 */ MaxNamespaceNum: number; /** * 最大Topic数量 */ MaxTopicNum: number; /** * 最大QPS */ MaxQps: number; /** * 消息保留时间 */ MessageRetentionTime: number; /** * 最大存储容量 */ MaxStorageCapacity: number; /** * 集群版本 注意:此字段可能返回 null,表示取不到有效值。 */ Version: string; /** * 公网访问接入点 注意:此字段可能返回 null,表示取不到有效值。 */ PublicEndPoint: string; /** * VPC访问接入点 注意:此字段可能返回 null,表示取不到有效值。 */ VpcEndPoint: string; /** * 命名空间数量 注意:此字段可能返回 null,表示取不到有效值。 */ NamespaceNum: number; /** * 已使用存储限制,MB为单位 注意:此字段可能返回 null,表示取不到有效值。 */ UsedStorageBudget: number; } /** * 消息保留策略 */ export interface RetentionPolicy { /** * 消息保留时长 */ TimeInMinutes: number; /** * 消息保留大小 */ SizeInMB: number; } /** * SendMsg请求参数结构体 */ export interface SendMsgRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称,如果是分区topic需要指定具体分区,如果没有指定则默认发到0分区,例如:my_topic-partition-0。 */ TopicName: string; /** * 消息内容,不能为空且大小不得大于5242880个byte。 */ MsgContent: string; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * DescribeCmqQueueDetail请求参数结构体 */ export interface DescribeCmqQueueDetailRequest { /** * 精确匹配QueueName */ QueueName: string; } /** * CreateRole返回参数结构体 */ export interface CreateRoleResponse { /** * 角色名称 */ RoleName: string; /** * 角色token */ Token: string; /** * 备注说明 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteEnvironmentRoles请求参数结构体 */ export interface DeleteEnvironmentRolesRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 角色名称数组。 */ RoleNames: Array<string>; /** * 必填字段,集群的ID */ ClusterId?: string; } /** * ClearCmqQueue返回参数结构体 */ export interface ClearCmqQueueResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteEnvironments请求参数结构体 */ export interface DeleteEnvironmentsRequest { /** * 环境(命名空间)数组,每次最多删除20个。 */ EnvironmentIds: Array<string>; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * DescribeBindClusters请求参数结构体 */ export declare type DescribeBindClustersRequest = null; /** * ModifyEnvironmentAttributes返回参数结构体 */ export interface ModifyEnvironmentAttributesResponse { /** * 命名空间名称。 */ EnvironmentId: string; /** * 未消费消息过期时间,单位:秒。 */ MsgTTL: number; /** * 备注,字符串最长不超过128。 注意:此字段可能返回 null,表示取不到有效值。 */ Remark: string; /** * 命名空间ID 注意:此字段可能返回 null,表示取不到有效值。 */ NamespaceId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 环境角色集合 */ export interface EnvironmentRole { /** * 环境(命名空间)。 */ EnvironmentId: string; /** * 角色名称。 */ RoleName: string; /** * 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ Permissions: Array<string>; /** * 角色描述。 */ RoleDescribe: string; /** * 创建时间。 */ CreateTime: string; /** * 更新时间。 */ UpdateTime: string; } /** * CreateCmqQueue请求参数结构体 */ export interface CreateCmqQueueRequest { /** * 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过 64 个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ QueueName: string; /** * 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。 */ MaxMsgHeapNum?: number; /** * 消息接收长轮询等待时间。取值范围 0-30 秒,默认值 0。 */ PollingWaitSeconds?: number; /** * 消息可见性超时。取值范围 1-43200 秒(即12小时内),默认值 30。 */ VisibilityTimeout?: number; /** * 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。 */ MaxMsgSize?: number; /** * 消息保留周期。取值范围 60-1296000 秒(1min-15天),默认值 345600 (4 天)。 */ MsgRetentionSeconds?: number; /** * 队列是否开启回溯消息能力,该参数取值范围0-msgRetentionSeconds,即最大的回溯时间为消息在队列中的保留周期,0表示不开启。 */ RewindSeconds?: number; /** * 1 表示事务队列,0 表示普通队列 */ Transaction?: number; /** * 第一次回查间隔 */ FirstQueryInterval?: number; /** * 最大回查次数 */ MaxQueryCount?: number; /** * 死信队列名称 */ DeadLetterQueueName?: string; /** * 死信策略。0为消息被多次消费未删除,1为Time-To-Live过期 */ Policy?: number; /** * 最大接收次数 1-1000 */ MaxReceiveCount?: number; /** * policy为1时必选。最大未消费过期时间。范围300-43200,单位秒,需要小于消息最大保留时间msgRetentionSeconds */ MaxTimeToLive?: number; /** * 是否开启消息轨迹追踪,当不设置字段时,默认为不开启,该字段为true表示开启,为false表示不开启 */ Trace?: boolean; } /** * ModifyEnvironmentRole返回参数结构体 */ export interface ModifyEnvironmentRoleResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteCmqQueue请求参数结构体 */ export interface DeleteCmqQueueRequest { /** * 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ QueueName: string; } /** * CreateRole请求参数结构体 */ export interface CreateRoleRequest { /** * 角色名称,不支持中字以及除了短线和下划线外的特殊字符且长度必须大于0且小等于32。 */ RoleName: string; /** * 备注说明,长度必须大等于0且小等于128。 */ Remark?: string; /** * 必填字段,集群Id */ ClusterId?: string; } /** * DescribeProducers请求参数结构体 */ export interface DescribeProducersRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名。 */ TopicName: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * 生产者名称,模糊匹配。 */ ProducerName?: string; /** * Pulsar 集群的ID */ ClusterId?: string; } /** * ModifyEnvironmentRole请求参数结构体 */ export interface ModifyEnvironmentRoleRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 角色名称。 */ RoleName: string; /** * 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ Permissions: Array<string>; /** * 必填字段,集群的ID */ ClusterId?: string; } /** * DescribeEnvironmentAttributes返回参数结构体 */ export interface DescribeEnvironmentAttributesResponse { /** * 未消费消息过期时间,单位:秒,最大1296000(15天)。 */ MsgTTL: number; /** * 消费速率限制,单位:byte/秒,0:不限速。 */ RateInByte: number; /** * 消费速率限制,单位:个数/秒,0:不限速。 */ RateInSize: number; /** * 已消费消息保存策略,单位:小时,0:消费完马上删除。 */ RetentionHours: number; /** * 已消费消息保存策略,单位:G,0:消费完马上删除。 */ RetentionSize: number; /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 副本数。 */ Replicas: number; /** * 备注。 */ Remark: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 订阅关系 */ export interface SubscriptionTopic { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 主题名称。 */ TopicName: string; /** * 订阅名称。 */ SubscriptionName: string; } /** * DescribeProducers返回参数结构体 */ export interface DescribeProducersResponse { /** * 生产者集合数组。 */ ProducerSets: Array<Producer>; /** * 记录总数。 */ TotalCount: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * SendBatchMessages请求参数结构体 */ export interface SendBatchMessagesRequest { /** * 消息要发送的topic的名字, 这里尽量需要使用topic的全路径,即:tenant/namespace/topic。如果不指定,默认使用的是:public/default */ Topic: string; /** * 需要发送消息的内容 */ Payload: string; /** * String 类型的 token,可以不填,系统会自动获取 */ StringToken?: string; /** * producer 的名字,要求全局是唯一的,如果不设置,系统会自动生成 */ ProducerName?: string; /** * 单位:s。消息发送的超时时间。默认值为:30s */ SendTimeout?: number; /** * 内存中允许缓存的生产消息的最大数量,默认值:1000条 */ MaxPendingMessages?: number; /** * 每一个batch中消息的最大数量,默认值:1000条/batch */ BatchingMaxMessages?: number; /** * 每一个batch最大等待的时间,超过这个时间,不管是否达到指定的batch中消息的数量和大小,都会将该batch发送出去,默认:10ms */ BatchingMaxPublishDelay?: number; /** * 每一个batch中最大允许的消息的大小,默认:128KB */ BatchingMaxBytes?: number; } /** * DeleteCmqTopic请求参数结构体 */ export interface DeleteCmqTopicRequest { /** * 主题名字,在单个地域同一帐号下唯一。主题名称是一个不超过64个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ TopicName: string; } /** * SendCmqMsg返回参数结构体 */ export interface SendCmqMsgResponse { /** * true表示发送成功 */ Result: boolean; /** * 消息id */ MsgId: string; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * PublishCmqMsg请求参数结构体 */ export interface PublishCmqMsgRequest { /** * 主题名 */ TopicName: string; /** * 消息内容 */ MsgContent: string; /** * 消息标签 */ MsgTag?: Array<string>; } /** * UnbindCmqDeadLetter请求参数结构体 */ export interface UnbindCmqDeadLetterRequest { /** * 死信策略源队列名称,调用本接口会清空该队列的死信队列策略。 */ SourceQueueName: string; } /** * ModifyCmqQueueAttribute请求参数结构体 */ export interface ModifyCmqQueueAttributeRequest { /** * 队列名字,在单个地域同一帐号下唯一。队列名称是一个不超过 64 个字符的字符串,必须以字母为首字符,剩余部分可以包含字母、数字和横划线(-)。 */ QueueName: string; /** * 最大堆积消息数。取值范围在公测期间为 1,000,000 - 10,000,000,正式上线后范围可达到 1000,000-1000,000,000。默认取值在公测期间为 10,000,000,正式上线后为 100,000,000。 */ MaxMsgHeapNum?: number; /** * 消息接收长轮询等待时间。取值范围 0-30 秒,默认值 0。 */ PollingWaitSeconds?: number; /** * 消息可见性超时。取值范围 1-43200 秒(即12小时内),默认值 30。 */ VisibilityTimeout?: number; /** * 消息最大长度。取值范围 1024-65536 Byte(即1-64K),默认值 65536。 */ MaxMsgSize?: number; /** * 消息保留周期。取值范围 60-1296000 秒(1min-15天),默认值 345600 (4 天)。 */ MsgRetentionSeconds?: number; /** * 消息最长回溯时间,取值范围0-msgRetentionSeconds,消息的最大回溯之间为消息在队列中的保存周期,0表示不开启消息回溯。 */ RewindSeconds?: number; /** * 第一次查询时间 */ FirstQueryInterval?: number; /** * 最大查询次数 */ MaxQueryCount?: number; /** * 死信队列名称 */ DeadLetterQueueName?: string; /** * MaxTimeToLivepolicy为1时必选。最大未消费过期时间。范围300-43200,单位秒,需要小于消息最大保留时间MsgRetentionSeconds */ MaxTimeToLive?: number; /** * 最大接收次数 */ MaxReceiveCount?: number; /** * 死信队列策略 */ Policy?: number; /** * 是否开启消息轨迹标识,true表示开启,false表示不开启,不填表示不开启。 */ Trace?: boolean; /** * 是否开启事务,1开启,0不开启 */ Transaction?: number; } /** * DeleteCmqSubscribe返回参数结构体 */ export interface DeleteCmqSubscribeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeRoles请求参数结构体 */ export interface DescribeRolesRequest { /** * 角色名称,模糊查询 */ RoleName?: string; /** * 起始下标,不填默认为0。 */ Offset?: number; /** * 返回数量,不填则默认为10,最大值为20。 */ Limit?: number; /** * 必填字段,集群Id */ ClusterId?: string; /** * * RoleName 按照角色名进行过滤,精确查询。 类型:String 必选:否 */ Filters?: Array<Filter>; } /** * DeleteSubscriptions请求参数结构体 */ export interface DeleteSubscriptionsRequest { /** * 订阅关系集合,每次最多删除20个。 */ SubscriptionTopicSets: Array<SubscriptionTopic>; /** * pulsar集群Id。 */ ClusterId?: string; /** * 环境(命名空间)名称。 */ EnvironmentId?: string; /** * 是否强制删除,默认为false */ Force?: boolean; } /** * DescribeClusterDetail返回参数结构体 */ export interface DescribeClusterDetailResponse { /** * 集群的详细信息 */ ClusterSet: Cluster; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateEnvironmentRole请求参数结构体 */ export interface CreateEnvironmentRoleRequest { /** * 环境(命名空间)名称。 */ EnvironmentId: string; /** * 角色名称。 */ RoleName: string; /** * 授权项,最多只能包含produce、consume两项的非空字符串数组。 */ Permissions: Array<string>; /** * 必填字段,集群的ID */ ClusterId?: string; }
the_stack
declare module "@deck.gl/geo-layers/great-circle-layer/great-circle-vertex.glsl" { const _default: string; export default _default; } declare module "@deck.gl/geo-layers/great-circle-layer/great-circle-layer" { import { ArcLayerProps } from "@deck.gl/layers/arc-layer/arc-layer"; export interface GreatCircleLayerProps<D> extends ArcLayerProps<D> {} import { ArcLayer } from "@deck.gl/layers"; export default class GreatCircleLayer<D, P extends GreatCircleLayerProps<D> = GreatCircleLayerProps<D>> extends ArcLayer<D, P> { getShaders(): any; } } declare module "@deck.gl/geo-layers/s2-layer/s2-geometry" { export function IJToST(ij: any, order: any, offsets: any): number[]; export function STToUV(st: any): number[]; export function FaceUVToXYZ(face: any, [u, v]: [any, any]): any[]; export function XYZToLngLat([x, y, z]: [any, any, any]): number[]; export function toHilbertQuadkey(idS: any): string; export function FromHilbertQuadKey( hilbertQuadkey: any ): { face: number; ij: number[]; level: any; }; } declare module "@deck.gl/geo-layers/s2-layer/s2-utils" { export function getS2QuadKey(token: any): string; /** * Get a polygon with corner coordinates for an s2 cell * @param {*} cell - This can be an S2 key or token * @return {Array} - a simple polygon in array format: [[lng, lat], ...] * - each coordinate is an array [lng, lat] * - the polygon is closed, i.e. last coordinate is a copy of the first coordinate */ export function getS2Polygon(token: any): Float64Array; } declare module "@deck.gl/geo-layers/s2-layer/s2-layer" { import { CompositeLayer } from "@deck.gl/core"; import { CompositeLayerProps } from "@deck.gl/core/lib/composite-layer"; export interface S2LayerProps<D> extends CompositeLayerProps<D> { getS2Token: (d:D)=> any; } export default class S2Layer<D, P extends S2LayerProps<D> = S2LayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: S2LayerProps<D>[]); renderLayers(): any; } } declare module "@deck.gl/geo-layers/tile-layer/tile-2d-header" { export default class Tile2DHeader { constructor({ x, y, z, onTileLoad, onTileError, }: { x: any; y: any; z: any; onTileLoad: any; onTileError: any; }); get data(): any; get isLoaded(): any; get byteLength(): any; loadData(getTileData: any): void; } } declare module "@deck.gl/geo-layers/tile-layer/utils" { export const urlType: { type: string; value: string; validate: (value: any) => boolean; equals: (value1: any, value2: any) => boolean; }; export function getURLFromTemplate(template: any, properties: any): any; export function tileToBoundingBox( viewport: any, x: any, y: any, z: any, tileSize?: number ): | { west: number; north: number; east: number; south: number; left?: undefined; top?: undefined; right?: undefined; bottom?: undefined; } | { left: number; top: number; right: number; bottom: number; west?: undefined; north?: undefined; east?: undefined; south?: undefined; }; /** * Returns all tile indices in the current viewport. If the current zoom level is smaller * than minZoom, return an empty array. If the current zoom level is greater than maxZoom, * return tiles that are on maxZoom. */ export function getTileIndices( viewport: any, maxZoom: any, minZoom: any, zRange: any, tileSize?: number ): any[]; } declare module "@deck.gl/geo-layers/tile-layer/tileset-2d" { export const STRATEGY_NEVER = "never"; export const STRATEGY_REPLACE = "no-overlap"; export const STRATEGY_DEFAULT = "best-available"; /** * Manages loading and purging of tiles data. This class caches recently visited tiles * and only create new tiles if they are present. */ export default class Tileset2D { /** * Takes in a function that returns tile data, a cache size, and a max and a min zoom level. * Cache size defaults to 5 * number of tiles in the current viewport */ constructor(opts: any); get tiles(): any; get selectedTiles(): any; get isLoaded(): any; setOptions(opts: any): void; /** * Update the cache with the given viewport and triggers callback onUpdate. * @param {*} viewport * @param {*} onUpdate */ update( viewport: any, { zRange, }?: { zRange: any; } ): any; getTileIndices({ viewport, maxZoom, minZoom, zRange, }: { viewport: any; maxZoom: any; minZoom: any; zRange: any; }): any[]; getTileMetadata({ x, y, z, }: { x: any; y: any; z: any; }): { bbox: | { west: number; north: number; east: number; south: number; left?: undefined; top?: undefined; right?: undefined; bottom?: undefined; } | { left: number; top: number; right: number; bottom: number; west?: undefined; north?: undefined; east?: undefined; south?: undefined; }; }; getParentIndex(tileIndex: any): any; updateTileStates(): boolean; _rebuildTree(): void; _updateTileStates(selectedTiles: any): void; /** * Clear tiles that are not visible when the cache is full */ _resizeCache(): void; _getTile( { x, y, z, }: { x: any; y: any; z: any; }, create: any ): any; _getNearestAncestor(x: any, y: any, z: any): any; } } declare module "@deck.gl/geo-layers/tile-layer/tile-layer" { import { CompositeLayer, Layer } from "@deck.gl/core"; import { LayerProps } from "@deck.gl/core/lib/layer"; import { ExtentsLeftBottomRightTop } from "@deck.gl/core/utils/positions"; export interface TileLayerProps<D> extends LayerProps<D> { //Data Options getTileData?: (tile: { x: number; y: number; z: number; url: string; bbox: any; }) => D[] | Promise<D[]> | null; tileSize?: number; maxZoom?: number | null; minZoom?: number; maxCacheSize?: number; maxCacheByteSize?: number; refinementStrategy?: "best-available" | "no-overlap" | "never"; maxRequests?: number; extent?: ExtentsLeftBottomRightTop; //Render Options renderSubLayers?: (props: any) => Layer<any> | Layer<any>[]; zRange?: [number, number]; //Callbacks onViewportLoad?: (data: D[]) => void; onTileLoad?: (tile: D) => void; onTileError?: (error: Error) => void; } export default class TileLayer<D, P extends TileLayerProps<D> = TileLayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: TileLayerProps<D>[]); initializeState(params: any): void; get isLoaded(): any; _updateTileset(): void; _onTileLoad(tile: any): void; _onTileError(error: any): void; getTileData(tile: any): any; renderSubLayers(props: any): any; renderLayers(): any; } } declare module "@deck.gl/geo-layers/trips-layer/trips-layer" { import { PathLayer } from "@deck.gl/layers"; import { Position } from "@deck.gl/core/utils/positions"; import LayerPath, { PathLayerProps, TypedArray, } from "@deck.gl/layers/path-layer/path-layer"; export interface TripsLayerProps<D> extends PathLayerProps<D> { //Render Options currentTime?: number; trailLength?: number; //Data Accessors getPath?: (d: D) => Position[] | TypedArray; getTimestamps?: ( d: D, info?: { data: D[], index:number, target:number[] }) => number[]; } export default class TripsLayer<D, P extends TripsLayerProps<D> = TripsLayerProps<D>> extends PathLayer<D, P> { constructor(...props: TripsLayerProps<D>[]); getShaders(): any; initializeState(params?: any): void; draw(params: any): void; } } declare module "@deck.gl/geo-layers/h3-layers/h3-cluster-layer" { import { CompositeLayer } from "@deck.gl/core"; import { PolygonLayerProps } from "@deck.gl/layers/polygon-layer/polygon-layer"; export interface H3ClusterLayerProps<D> extends PolygonLayerProps<D> { getHexagons?: (d: D) => string[]; } export default class H3ClusterLayer<D, P extends H3ClusterLayerProps<D> = H3ClusterLayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: H3ClusterLayerProps<D>[]); renderLayers(): any; } } declare module "@deck.gl/geo-layers/h3-layers/h3-hexagon-layer" { import { CompositeLayer } from "@deck.gl/core"; import { PolygonLayerProps } from "@deck.gl/layers/polygon-layer/polygon-layer"; export function normalizeLongitudes(vertices: any, refLng: any): void; export function scalePolygon(hexId: any, vertices: any, factor: any): void; export interface H3HexagonLayerProps<D> extends PolygonLayerProps<D> { highPrecision?: boolean; coverage?: number; getHexagon?: (d: D) => string; } /** * A subclass of HexagonLayer that uses H3 hexagonIds in data objects * rather than centroid lat/longs. The shape of each hexagon is determined * based on a single "center" hexagon, which can be selected by passing in * a center lat/lon pair. If not provided, the map center will be used. * * Also sets the `hexagonId` field in the onHover/onClick callback's info * objects. Since this is calculated using math, hexagonId will be present * even when no corresponding hexagon is in the data set. You can check * index !== -1 to see if picking matches an actual object. */ export default class H3HexagonLayer<D, P extends H3HexagonLayerProps<D> = H3HexagonLayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: H3HexagonLayerProps<D>[]); _shouldUseHighPrecision(): any; _updateVertices(viewport: any): void; renderLayers(): any; _getForwardProps(): { elevationScale: any; extruded: any; coverage: any; wireframe: any; stroked: any; filled: any; lineWidthUnits: any; lineWidthScale: any; lineWidthMinPixels: any; lineWidthMaxPixels: any; material: any; getElevation: any; getFillColor: any; getLineColor: any; getLineWidth: any; updateTriggers: { getFillColor: any; getElevation: any; getLineColor: any; getLineWidth: any; }; }; _renderPolygonLayer(): any; _renderColumnLayer(): any; } } declare module "@deck.gl/geo-layers/tile-3d-layer/tile-3d-layer" { import { CompositeLayer } from "@deck.gl/core"; import { CompositeLayerProps } from "@deck.gl/core/lib/composite-layer"; import { RGBAColor } from "@deck.gl/core/utils/color"; export interface Tile3DLayerProps<D> extends CompositeLayerProps<D> { //Render Options opacity?: number; pointSize?: number; //Data Properties data?: string; loader?: any; pickable?: boolean; //Data Accessors getPointColor?: ((tileData: Object) => RGBAColor) | RGBAColor; //Callbacks onTilesetLoad?: (tileData: Object) => void; onTileLoad?: (tileHeader: Object) => void; onTileUnload?: (tileHeader: Object) => void; onTileError?: (tileHeader: Object, url: string, message: string) => void; } export default class Tile3DLayer<D, P extends Tile3DLayerProps<D> = Tile3DLayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: Tile3DLayerProps<D>[]); initializeState(params: any): void; _loadTileset(tilesetUrl: any): Promise<void>; _onTileLoad(tileHeader: any): void; _onTileUnload(tileHeader: any): void; _updateTileset(tileset3d: any): void; _create3DTileLayer(tileHeader: any): any; _createPointCloudTileLayer(tileHeader: any): any; _create3DModelTileLayer(tileHeader: any): any; _createSimpleMeshLayer(tileHeader: any): any; renderLayers(): any; } } declare module "@deck.gl/geo-layers/terrain-layer/terrain-layer" { import { CompositeLayer } from "@deck.gl/core"; import { CompositeLayerProps } from "@deck.gl/core/lib/composite-layer"; import { RGBAColor } from "@deck.gl/core/utils/color"; import { ExtentsLeftBottomRightTop } from "@deck.gl/core/utils/positions"; /** * state: { * isTiled: True renders TileLayer of many SimpleMeshLayers, false renders one SimpleMeshLayer * terrain: Mesh object. Only defined when isTiled is false. * } */ export interface TerrainLayerProps<D> extends CompositeLayerProps<D> { //Data Options elevationData: string | string[]; texture?: string | null; meshMaxError?: number; elevationDecoder?: { rScaler: number; gScaler: number; bScaler: number; offset: number; }; bounds?: ExtentsLeftBottomRightTop; workerUrl?: string; //Render Options color?: RGBAColor; wireframe?: boolean; material?: any; //Tile options maxRequests?: number; refinementStrategy?: "best-available" | "no-overlap" | "never"; minZoom?: number; maxZoom?: number | null; tileSize?: number; extent?: ExtentsLeftBottomRightTop; } export default class TerrainLayer<D, P extends TerrainLayerProps<D> = TerrainLayerProps<D>> extends CompositeLayer<D, P> { constructor(...props: TerrainLayerProps<D>[]); loadTerrain({ elevationData, bounds, elevationDecoder, meshMaxError, workerUrl, }: { elevationData: any; bounds: any; elevationDecoder: any; meshMaxError: any; workerUrl: any; }): any; getTiledTerrainData(tile: any): Promise<[any, any]>; renderSubLayers(props: any): any; onViewportLoad(data: any): void; renderLayers(): any; } } declare module "@deck.gl/geo-layers/mvt-layer/clip-extension" { import { LayerExtension } from "@deck.gl/core"; export default class ClipExtension extends LayerExtension { getShaders( opts: any ): | { modules: { name: string; vs: string; }[]; inject: { "vs:#decl": string; "vs:DECKGL_FILTER_GL_POSITION": string; "fs:#decl": string; "fs:DECKGL_FILTER_COLOR": string; }; } | { modules: { name: string; fs: string; }[]; inject: { "vs:#decl": string; "vs:DECKGL_FILTER_GL_POSITION": string; "fs:#decl": string; "fs:DECKGL_FILTER_COLOR": string; }; }; draw({ uniforms }: { uniforms: any }): void; } } declare module "@deck.gl/geo-layers/mvt-layer/mvt-layer" { import TileLayer, { TileLayerProps } from "@deck.gl/geo-layers/tile-layer/tile-layer"; export interface MVTLayerProps<D> extends TileLayerProps<D> { } export default class MVTLayer<D, P extends MVTLayerProps<D> = MVTLayerProps<D>> extends TileLayer<D, P> { getTileData(tile: any): any; renderSubLayers(props: any): any; } } declare module "@deck.gl/geo-layers" { export { default as GreatCircleLayer } from "@deck.gl/geo-layers/great-circle-layer/great-circle-layer"; export { default as S2Layer } from "@deck.gl/geo-layers/s2-layer/s2-layer"; export { default as TileLayer } from "@deck.gl/geo-layers/tile-layer/tile-layer"; export { default as TripsLayer } from "@deck.gl/geo-layers/trips-layer/trips-layer"; export { default as H3ClusterLayer } from "@deck.gl/geo-layers/h3-layers/h3-cluster-layer"; export { default as H3HexagonLayer } from "@deck.gl/geo-layers/h3-layers/h3-hexagon-layer"; export { default as Tile3DLayer } from "@deck.gl/geo-layers/tile-3d-layer/tile-3d-layer"; export { default as TerrainLayer } from "@deck.gl/geo-layers/terrain-layer/terrain-layer"; export { default as MVTLayer } from "@deck.gl/geo-layers/mvt-layer/mvt-layer"; }
the_stack
import React from 'react'; import { act, renderHook } from '@testing-library/react-hooks'; import { createBrowserHistory } from 'history'; import { Router } from 'react-router-dom'; import usePasscodeAuth, { getPasscode, verifyPasscode } from './usePasscodeAuth'; delete window.location; // @ts-ignore window.location = { search: '', }; const customHistory = { ...createBrowserHistory(), replace: jest.fn() }; const wrapper = (props: React.PropsWithChildren<unknown>) => ( <Router history={customHistory as any}>{props.children}</Router> ); describe('the usePasscodeAuth hook', () => { describe('on first render', () => { beforeEach(() => window.sessionStorage.clear()); it('should return a user when the passcode is valid', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); expect(result.current).toMatchObject({ isAuthReady: true, user: { passcode: '123123' } }); }); it('should remove the query parameter from the URL when the passcode is valid', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); // @ts-ignore window.location = { search: '?passcode=000000', origin: 'http://test-origin', pathname: '/test-pathname', }; Object.defineProperty(window.history, 'replaceState', { value: jest.fn() }); window.sessionStorage.setItem('passcode', '123123'); const { waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); expect(customHistory.replace).toHaveBeenLastCalledWith('/test-pathname'); }); it('should not return a user when the app code is invalid', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ status: 401, json: () => Promise.resolve({ type: 'errorMessage' }) }) ); window.location.search = ''; window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); expect(result.current).toMatchObject({ isAuthReady: true, user: null }); }); it('should not return a user when there is no passcode', () => { const { result } = renderHook(usePasscodeAuth, { wrapper }); expect(result.current).toMatchObject({ isAuthReady: true, user: null }); }); }); describe('signout function', () => { it('should clear session storage and user on signout', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); await act(() => result.current.signOut()); expect(window.sessionStorage.getItem('passcode')).toBe(null); expect(result.current.user).toBe(null); }); }); describe('signin function', () => { it('should set a user when a valid passcode is submitted', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); const { result } = renderHook(usePasscodeAuth, { wrapper }); await act(() => result.current.signIn('123456')); expect(result.current.user).toEqual({ passcode: '123456' }); }); it('should return an error when an invalid passcode is submitted', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ status: 401, json: () => Promise.resolve({ error: { message: 'passcode incorrect' } }) }) ); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); result.current.signIn('123456').catch(err => { expect(err.message).toBe('Passcode is incorrect'); }); }); it('should return an error when an expired passcode is submitted', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ status: 401, json: () => Promise.resolve({ error: { message: 'passcode expired' } }) }) ); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); result.current.signIn('123456').catch(err => { expect(err.message).toBe('Passcode has expired'); }); }); }); describe('the getToken function', () => { it('should call the API with the correct parameters', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); await act(async () => { result.current.getToken('test-name', 'test-room'); }); expect(window.fetch).toHaveBeenLastCalledWith('/token', { body: '{"user_identity":"test-name","room_name":"test-room","passcode":"123123","create_room":true,"create_conversation":true}', headers: { 'content-type': 'application/json' }, method: 'POST', }); }); it('should call the API with the correct parameters when REACT_APP_DISABLE_TWILIO_CONVERSATIONS is true', async () => { process.env.REACT_APP_DISABLE_TWILIO_CONVERSATIONS = 'true'; // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); await act(async () => { result.current.getToken('test-name', 'test-room'); }); expect(window.fetch).toHaveBeenLastCalledWith('/token', { body: '{"user_identity":"test-name","room_name":"test-room","passcode":"123123","create_room":true,"create_conversation":false}', headers: { 'content-type': 'application/json' }, method: 'POST', }); // reset the environment variable delete process.env.REACT_APP_DISABLE_TWILIO_CONVERSATIONS; }); it('should return a token', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); let token = ''; await act(async () => { token = await result.current.getToken('test-name', 'test-room'); }); expect(token).toEqual({ token: 'mockVideoToken' }); }); it('should return a useful error message from the serverless function', async () => { // @ts-ignore window.fetch = jest.fn(() => // Return a successful response when the passcode is initially verified Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); window.sessionStorage.setItem('passcode', '123123'); const { result, waitForNextUpdate } = renderHook(usePasscodeAuth, { wrapper }); await waitForNextUpdate(); // @ts-ignore window.fetch = jest.fn(() => // Return an error when the user tries to join a room Promise.resolve({ status: 401, json: () => Promise.resolve({ error: { message: 'passcode expired' } }) }) ); result.current.getToken('test-name', 'test-room').catch(err => { expect(err.message).toBe('Passcode has expired'); }); }); }); }); describe('the getPasscode function', () => { beforeEach(() => window.sessionStorage.clear()); it('should return the passcode from session storage', () => { window.location.search = ''; window.sessionStorage.setItem('passcode', '123123'); expect(getPasscode()).toBe('123123'); }); it('should return the passcode from the URL', () => { window.location.search = '?passcode=234234'; expect(getPasscode()).toBe('234234'); }); it('should return the passcode from the URL when the app code is also sotred in sessionstorage', () => { window.sessionStorage.setItem('passcode', '123123'); window.location.search = '?passcode=234234'; expect(getPasscode()).toBe('234234'); }); it('should return null when there is no passcode', () => { window.location.search = ''; expect(getPasscode()).toBe(null); }); }); describe('the verifyPasscode function', () => { it('should return the correct response when the passcode is valid', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ token: 'mockVideoToken' }) }) ); const result = await verifyPasscode('123456'); expect(result).toEqual({ isValid: true }); }); it('should return the correct response when the passcode is invalid', async () => { // @ts-ignore window.fetch = jest.fn(() => Promise.resolve({ status: 401, json: () => Promise.resolve({ error: { message: 'errorMessage' } }) }) ); const result = await verifyPasscode('123456'); expect(result).toEqual({ isValid: false, error: 'errorMessage' }); }); it('should call the API with the correct parameters', async () => { await verifyPasscode('123456'); expect(window.fetch).toHaveBeenLastCalledWith('/token', { body: '{"user_identity":"temp-name","room_name":"temp-room","passcode":"123456","create_room":false,"create_conversation":false}', headers: { 'content-type': 'application/json' }, method: 'POST', }); }); });
the_stack
import { GraphQLFieldExtensions } from 'graphql'; import type { InputFieldMap, InputShapeFromFields, Resolver, Subscriber } from '../builder-options'; import { SchemaTypes } from '../schema-types'; import { FieldNullability, FieldRequiredness, InputShapeFromTypeParam, InputType, ShapeFromTypeParam, TypeParam, } from '../type-params'; declare global { export namespace PothosSchemaTypes { export interface FieldOptions< Types extends SchemaTypes = SchemaTypes, ParentShape = unknown, Type extends TypeParam<Types> = TypeParam<Types>, Nullable extends FieldNullability<Type> = FieldNullability<Type>, Args extends InputFieldMap = InputFieldMap, ResolveShape = unknown, ResolveReturnShape = unknown, > { /** The type for this field */ type: Type; /** arguments for this field (created via `t.args`) */ args?: Args; /** determins if this field can return null */ nullable?: Nullable; /** text description for this field. This will be added into your schema file and visable in tools like graphql-playground */ description?: string; /** When present marks this field as deprecated */ deprecationReason?: string; /** extensions for this field for use by directives, server plugins or other tools that depend on extensions */ extensions?: GraphQLFieldExtensions< ParentShape, Types['Context'], InputShapeFromFields<Args> >; /** * Resolver function for this field * @param parent - The parent object for the current type * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve?: Resolver< ResolveShape, InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; } export interface ObjectFieldOptions< Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape, > extends FieldOptions< Types, ParentShape, Type, Nullable, Args, ParentShape, ResolveReturnShape > { /** * Resolver function for this field * @param parent - The parent object for the current type * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve: Resolver< ParentShape, InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; } export interface QueryFieldOptions< Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape, > extends FieldOptions< Types, Types['Root'], Type, Nullable, Args, Types['Root'], ResolveReturnShape > { /** * Resolver function for this field * @param root - The root object for this request * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve: Resolver< Types['Root'], InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; } export interface MutationFieldOptions< Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape, > extends FieldOptions< Types, Types['Root'], Type, Nullable, Args, Types['Root'], ResolveReturnShape > { /** * Resolver function for this field * @param root - The root object for this request * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve: Resolver< Types['Root'], InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; } export interface InterfaceFieldOptions< Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveReturnShape, > extends FieldOptions< Types, ParentShape, Type, Nullable, Args, ParentShape, ResolveReturnShape > { /** * Resolver function for this field * @param root - The root object for this request * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve?: Resolver< ParentShape, InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; } export interface SubscriptionFieldOptions< Types extends SchemaTypes, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveShape, ResolveReturnShape, > extends FieldOptions< Types, Types['Root'], Type, Nullable, Args, ResolveShape, ResolveReturnShape > { /** * Resolver function for this field * @param parent - The parent object for this subscription (yielded by subscribe) * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ resolve: Resolver< ResolveShape, InputShapeFromFields<Args>, Types['Context'], ShapeFromTypeParam<Types, Type, Nullable>, ResolveReturnShape >; /** * Resolver function for this field * @param root - The root object for this request * @param {object} args - args object based on the args defined for this field * @param {object} context - the context object for the current query, based on `Context` type provided to the SchemaBuilder * @param {GraphQLResolveInfo} info - info about how this field was queried */ subscribe: Subscriber< Types['Root'], InputShapeFromFields<Args>, Types['Context'], ResolveShape >; } export interface FieldOptionsByKind< Types extends SchemaTypes, ParentShape, Type extends TypeParam<Types>, Nullable extends FieldNullability<Type>, Args extends InputFieldMap, ResolveShape, ResolveReturnShape, > { Query: QueryFieldOptions<Types, Type, Nullable, Args, ResolveReturnShape>; Mutation: MutationFieldOptions<Types, Type, Nullable, Args, ResolveReturnShape>; Subscription: SubscriptionFieldOptions< Types, Type, Nullable, Args, ResolveShape, ResolveReturnShape >; Object: ObjectFieldOptions<Types, ParentShape, Type, Nullable, Args, ResolveReturnShape>; Interface: InterfaceFieldOptions< Types, ParentShape, Type, Nullable, Args, ResolveReturnShape >; } export interface InputFieldOptions< Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [InputType<Types>] = InputType<Types> | [InputType<Types>], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>, > { /** The type for this field */ type: Type; /** text description for this field. This will be added into your schema file and visable in tools like graphql-playground */ description?: string; /** When present marks this field as deprecated */ deprecationReason?: string; /** etermins if this field can be omitted (or set as null) */ required?: Req; /** default value if this field is not included in the query */ defaultValue?: NonNullable<InputShapeFromTypeParam<Types, Type, Req>>; /** extensions for this field for use by directives, server plugins or other tools that depend on extensions */ extensions?: Readonly<Record<string, unknown>>; } export interface ArgFieldOptions< Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [InputType<Types>] = InputType<Types> | [InputType<Types>], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>, > extends InputFieldOptions<Types, Type, Req> {} export interface InputObjectFieldOptions< Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [InputType<Types>] = InputType<Types> | [InputType<Types>], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>, > extends InputFieldOptions<Types, Type, Req> {} export interface InputFieldOptionsByKind< Types extends SchemaTypes = SchemaTypes, Type extends InputType<Types> | [InputType<Types>] = InputType<Types> | [InputType<Types>], Req extends FieldRequiredness<Type> = FieldRequiredness<Type>, > { Arg: ArgFieldOptions<Types, Type, Req>; InputObject: InputObjectFieldOptions<Types, Type, Req>; } } }
the_stack
import { Disposable } from '../utils/dispose'; import * as vscode from 'vscode'; import { ConnectionManager } from '../infoManagers/connectionManager'; import { INIT_PANEL_TITLE } from '../utils/constants'; import { NavEditCommands, PageHistory } from './pageHistoryTracker'; import { getNonce, isFileInjectable } from '../utils/utils'; import { PathUtil } from '../utils/pathUtil'; /** * @description the object responsible for communicating messages to the webview. */ export class WebviewComm extends Disposable { private readonly _pageHistory: PageHistory; public currentAddress: string; private readonly _onPanelTitleChange = this._register( new vscode.EventEmitter<{ title?: string; pathname?: string }>() ); public readonly onPanelTitleChange = this._onPanelTitleChange.event; constructor( initialFile: string, private readonly _panel: vscode.WebviewPanel, private readonly _extensionUri: vscode.Uri, private readonly _connectionManager: ConnectionManager ) { super(); this._pageHistory = this._register(new PageHistory()); this.updateForwardBackArrows(); // Set the webview's html content this.goToFile(initialFile, false); this._pageHistory?.addHistory(initialFile); this.currentAddress = initialFile; } /** * @returns {Promise<vscode.Uri>} the promise containing the HTTP URI. */ public async resolveHost(): Promise<vscode.Uri> { return this._connectionManager.resolveExternalHTTPUri(); } /** * @returns {Promise<vscode.Uri>} the promise containing the WebSocket URI. */ private async resolveWsHost(): Promise<vscode.Uri> { return this._connectionManager.resolveExternalWSUri(); } /** * @param {string} URLExt the pathname to construct the address from. * @param {string} hostURI the (optional) URI of the host; alternatively, the function will manually generate the connection manager's HTTP URI if not provided with it initially. * @returns {Promise<string>} a promise for the address for the content. */ public async constructAddress( URLExt: string, hostURI?: vscode.Uri ): Promise<string> { if (URLExt.length > 0 && URLExt[0] == '/') { URLExt = URLExt.substring(1); } URLExt = PathUtil.ConvertToUnixPath(URLExt); URLExt = URLExt.startsWith('/') ? URLExt.substr(1) : URLExt; if (!hostURI) { hostURI = await this.resolveHost(); } return `${hostURI.toString()}${URLExt}`; } /** * @description go to a file in the embeded preview * @param {string} URLExt the pathname to navigate to * @param {boolean} updateHistory whether or not to update the history from this call. */ public async goToFile(URLExt: string, updateHistory = true) { this.setHtml(this._panel.webview, URLExt, updateHistory); this.currentAddress = URLExt; } /** * @description set the webivew's HTML to show embedded preview content. * @param {vscode.Webview} webview the webview to set the HTML. * @param {string} URLExt the pathname appended to the host to navigate the preview to. * @param {boolean} updateHistory whether or not to update the history from this call. */ public async setHtml( webview: vscode.Webview, URLExt: string, updateHistory: boolean ) { const httpHost = await this.resolveHost(); const url = await this.constructAddress(URLExt, httpHost); const wsURI = await this.resolveWsHost(); this._panel.webview.html = this.getHtmlForWebview( webview, url, `ws://${wsURI.authority}${wsURI.path}`, `${httpHost.scheme}://${httpHost.authority}` ); // If we can't rely on inline script to update panel title, // then set panel title manually if (!isFileInjectable(URLExt)) { this._onPanelTitleChange.fire({ title: '', pathname: URLExt }); this._panel.webview.postMessage({ command: 'set-url', text: JSON.stringify({ fullPath: url, pathname: URLExt }), }); } if (updateHistory) { this.handleNewPageLoad(URLExt); } } /** * @description generate the HTML to load in the webview; this will contain the full-page iframe with the hosted content, * in addition to the top navigation bar. * @param {vscode.Webview} webview the webview instance (to create sufficient webview URIs)/ * @param {string} httpURL the address to navigate to in the iframe. * @param {string} wsServerAddr the address of the WebSocket server. * @param {string} httpServerAddr the address of the HTTP server. * @returns {string} the html to load in the webview. */ private getHtmlForWebview( webview: vscode.Webview, httpURL: string, wsServerAddr: string, httpServerAddr: string ): string { // Local path to main script run in the webview const scriptPathOnDisk = vscode.Uri.joinPath( this._extensionUri, 'media', 'main.js' ); // And the uri we use to load this script in the webview const scriptUri = webview.asWebviewUri(scriptPathOnDisk); // Local path to css styles const stylesPathMainPath = vscode.Uri.joinPath( this._extensionUri, 'media', 'vscode.css' ); const codiconsPathMainPath = vscode.Uri.joinPath( this._extensionUri, 'media', 'codicon.css' ); // Uri to load styles into webview const stylesMainUri = webview.asWebviewUri(stylesPathMainPath); const codiconsUri = webview.asWebviewUri(codiconsPathMainPath); // Use a nonce to only allow specific scripts to be run const nonce = getNonce(); return `<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <!-- Use a content security policy to only allow loading images from https or from our extension directory, and only allow scripts that have a specific nonce. --> <meta http-equiv="Content-Security-Policy" content=" default-src 'none'; connect-src ${wsServerAddr}; font-src ${this._panel.webview.cspSource}; style-src ${this._panel.webview.cspSource}; script-src 'nonce-${nonce}'; frame-src ${httpServerAddr}; "> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="${stylesMainUri}" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="${codiconsUri}"> <title>${INIT_PANEL_TITLE}</title> </head> <body> <div class="displayContents"> <div class="header"> <div class="headercontent"> <nav class="controls"> <button id="back" title="Back" class="back-button icon leftmost-nav"><i class="codicon codicon-arrow-left"></i></button> <button id="forward" title="Forward" class="forward-button icon leftmost-nav"><i class="codicon codicon-arrow-right"></i></button> <button id="reload" title="Reload" class="reload-button icon leftmost-nav"><i class="codicon codicon-refresh"></i></button> <input id="url-input" class="url-input" type="text"> <button id="more" title="More Browser Actions" class="more-button icon"><i class="codicon codicon-list-flat"></i></button> </nav> <div class="find-container" id="find-box" hidden=true> <nav class="find"> <input id="find-input" class="find-input" type="text"> <div id="find-result" class="find-result icon" hidden=true><i id="find-result-icon" class="codicon" ></i></div> <button id="find-prev" title="Previous" class="find-prev-button icon find-nav"><i class="codicon codicon-chevron-up"></i></button> <button id="find-next" tabIndex=-1 title="Next" class="find-next-button icon find-nav"><i class="codicon codicon-chevron-down"></i></button> <button id="find-x" tabIndex=-1 title="Close" class="find-x-button icon find-nav"><i class="codicon codicon-chrome-close"></i></button> </nav> </div> </div> <div class="extras-menu" id="extras-menu-pane" hidden=true;> <table cellspacing="0" cellpadding="0"> <tr> <td> <button tabIndex=-1 id="browser-open" class="extra-menu-nav">Open in Browser</button> </td> </tr> <tr> <td> <button tabIndex=-1 id="find" class="extra-menu-nav">Find in Page</button> </td> </tr> <tr> <td> <button tabIndex=-1 id="devtools-open" class="extra-menu-nav">Open Devtools Pane</button> </td> </tr> </table> </div> </div> <div class="content"> <iframe id="hostedContent" src="${httpURL}"></iframe> </div> </div> <div id="link-preview"></div> <script nonce="${nonce}"> const WS_URL= "${wsServerAddr}"; </script> <script nonce="${nonce}" src="${scriptUri}"></script> </body> </html>`; } /** * @description set the webview's URL bar. * @param {string} pathname the pathname of the address to set the URL bar with. */ public async setUrlBar(pathname: string) { this._panel.webview.postMessage({ command: 'set-url', text: JSON.stringify({ fullPath: await this.constructAddress(pathname), pathname: pathname, }), }); // called from main.js in the case where the target is non-injectable this.handleNewPageLoad(pathname); } /** * @param {NavEditCommands} command the enable/disable command for the webview's back/forward buttons */ public handleNavAction(command: NavEditCommands): void { let text = {}; switch (command) { case NavEditCommands.DISABLE_BACK: text = { element: 'back', disabled: true }; break; case NavEditCommands.ENABLE_BACK: text = { element: 'back', disabled: false }; break; case NavEditCommands.DISABLE_FORWARD: text = { element: 'forward', disabled: true }; break; case NavEditCommands.ENABLE_FORWARD: text = { element: 'forward', disabled: false }; break; } this._panel.webview.postMessage({ command: 'changed-history', text: JSON.stringify(text), }); } /** * @description perform the appropriate updates when a new page loads. * @param {string} pathname path to file that loaded. * @param {string} panelTitle the panel title of file (if applicable). */ public handleNewPageLoad(pathname: string, panelTitle = ''): void { // only load relative addresses if (pathname.length > 0 && pathname[0] != '/') { pathname = '/' + pathname; } this._onPanelTitleChange.fire({ title: panelTitle, pathname: pathname }); this.currentAddress = pathname; const response = this._pageHistory?.addHistory(pathname); if (response) { for (const i in response.actions) { this.handleNavAction(response.actions[i]); } } } /** * @description send a request to the webview to update the enable/disable status of the back/forward buttons. */ public updateForwardBackArrows(): void { const navigationStatus = this._pageHistory.currentCommands; for (const i in navigationStatus) { this.handleNavAction(navigationStatus[i]); } } /** * @description go forwards in page history. */ public goForwards(): void { const response = this._pageHistory.goForward(); const pagename = response.address; if (pagename != undefined) { this.goToFile(pagename, false); } for (const i in response.actions) { this.handleNavAction(response.actions[i]); } } /** * @description go backwards in page history. */ public goBack(): void { const response = this._pageHistory.goBackward(); const pagename = response.address; if (pagename != undefined) { this.goToFile(pagename, false); } for (const i in response.actions) { this.handleNavAction(response.actions[i]); } } }
the_stack
import { Aspect, Aspected, ExecutionContext, ViewBehaviorFactory, ViewTemplate, } from "@microsoft/fast-element"; import { RenderInfo } from "../render-info.js"; import { getElementRenderer } from "../element-renderer/element-renderer.js"; import { AttributeBindingOp, Op, OpType } from "../template-parser/op-codes.js"; import { parseStringToOpCodes, parseTemplateToOpCodes, } from "../template-parser/template-parser.js"; import { ViewBehaviorFactoryRenderer } from "./directives.js"; function getLast<T>(arr: T[]): T | undefined { return arr[arr.length - 1]; } /** * The mode for which a component's internals should be rendered. * @beta */ export type ComponentDOMEmissionMode = "shadow"; /** * A class designed to render HTML templates. The renderer supports * rendering {@link @microsoft/fast-element#ViewTemplate} instances as well * as arbitrary HTML strings. * * @beta */ export class TemplateRenderer { private viewBehaviorFactoryRenderers: Map< any, ViewBehaviorFactoryRenderer<any> > = new Map(); /** * Controls how the {@link TemplateRenderer} will emit component DOM internals. */ public readonly componentDOMEmissionMode: ComponentDOMEmissionMode = "shadow"; /** * Renders a {@link @microsoft/fast-element#ViewTemplate} or HTML string. * @param template - The template to render. * @param renderInfo - Information about the rendering context. * @param source - Any source data to render the template and evaluate bindings with. */ public *render( template: ViewTemplate | string, renderInfo: RenderInfo, source: unknown = undefined, context: ExecutionContext = ExecutionContext.default ): IterableIterator<string> { const codes = template instanceof ViewTemplate ? parseTemplateToOpCodes(template) : parseStringToOpCodes(template, {}); yield* this.renderOpCodes(codes, renderInfo, source, context); } /** * Render a set of op codes. * @param codes - the op codes to render. * @param renderInfo - renderInfo context. * @param source - source data. * * @internal */ public *renderOpCodes( codes: Op[], renderInfo: RenderInfo, source: unknown, context: ExecutionContext ): IterableIterator<string> { for (const code of codes) { switch (code.type) { case OpType.text: yield code.value; break; case OpType.viewBehaviorFactory: { const factory = code.factory as ViewBehaviorFactory & Aspected; const ctor = factory.constructor; const renderer = this.viewBehaviorFactoryRenderers.get(ctor); if (renderer) { yield* renderer.render( factory, renderInfo, source, this, context ); } else if (factory.aspectType && factory.binding) { const result = factory.binding(source, context); // If the result is a template, render the template if (result instanceof ViewTemplate) { yield* this.render(result, renderInfo, source, context); } else if (result === null || result === undefined) { // Don't yield anything if result is null break; } else if (factory.aspectType === Aspect.content) { yield result; } else { // debugging error - we should handle all result cases throw new Error( `Unknown AspectedHTMLDirective result found: ${result}` ); } } else { // Throw if a SSR directive implementation cannot be found. throw new Error( `Unable to process view behavior factory: ${factory}` ); } break; } case OpType.customElementOpen: { const renderer = getElementRenderer( renderInfo, code.tagName, code.ctor, code.staticAttributes ); if (renderer !== undefined) { for (const [name, value] of code.staticAttributes) { renderer.setAttribute(name, value); } renderInfo.customElementInstanceStack.push(renderer); } break; } case OpType.customElementClose: { renderInfo.customElementInstanceStack.pop(); break; } case OpType.customElementAttributes: { const currentRenderer = renderInfo.customElementInstanceStack[ renderInfo.customElementInstanceStack.length - 1 ]; if (currentRenderer) { // simulate DOM connection currentRenderer.connectedCallback(); // Allow the renderer to hoist any attribute values it needs to yield* currentRenderer.renderAttributes(); } break; } case OpType.customElementShadow: { yield '<template shadowroot="open">'; const currentRenderer = renderInfo.customElementInstanceStack[ renderInfo.customElementInstanceStack.length - 1 ]; if (currentRenderer) { const shadow = currentRenderer.renderShadow(renderInfo); if (shadow) { yield* shadow; } } yield "</template>"; break; } case OpType.attributeBinding: { const { aspect, binding } = code; // Don't emit anything for events or directives without bindings if (aspect === Aspect.event) { break; } const result = binding(source, context); const renderer = this.getAttributeBindingRenderer(code); if (renderer) { yield* renderer(code, result, renderInfo); } break; } case OpType.templateElementOpen: yield "<template"; for (const [name, value] of code.staticAttributes) { yield ` ${TemplateRenderer.formatAttribute(name, value)}`; } for (const attr of code.dynamicAttributes) { const renderer = this.getAttributeBindingRenderer(attr); if (renderer) { const result = attr.binding(source, context); yield " "; yield* renderer(attr, result, renderInfo); } } yield ">"; break; case OpType.templateElementClose: yield "</template>"; break; default: throw new Error(`Unable to interpret op code '${code}'`); } } } /** * Registers DirectiveRenderers to use when rendering templates. * @param renderers - The directive renderers to register * * @internal */ public withViewBehaviorFactoryRenderers( ...renderers: ViewBehaviorFactoryRenderer<any>[] ): void { for (const renderer of renderers) { this.viewBehaviorFactoryRenderers.set(renderer.matcher, renderer); } } private getAttributeBindingRenderer(code: AttributeBindingOp) { switch (code.aspect) { case Aspect.booleanAttribute: return TemplateRenderer.renderBooleanAttribute; case Aspect.property: case Aspect.tokenList: return TemplateRenderer.renderProperty; case Aspect.attribute: return TemplateRenderer.renderAttribute; } } /** * Format attribute key/value pair into a HTML attribute string. * @param name - the attribute name. * @param value - the attribute value. */ private static formatAttribute(name: string, value: string) { return value === "" ? name : `${name}="${value}"`; } /** * Renders an attribute binding */ private static *renderAttribute( code: AttributeBindingOp, value: any, renderInfo: RenderInfo ) { if (value !== null && value !== undefined) { const { target } = code; if (code.useCustomElementInstance) { const instance = getLast(renderInfo.customElementInstanceStack); if (instance) { instance.setAttribute(target, value); } } else { yield TemplateRenderer.formatAttribute(target, value); } } } /** * Renders a property or tokenList binding */ private static *renderProperty( code: AttributeBindingOp, value: any, renderInfo: RenderInfo ) { const { target } = code; if (code.useCustomElementInstance) { const instance = getLast(renderInfo.customElementInstanceStack); if (instance) { switch (code.aspect) { case Aspect.property: instance.setProperty(target, value); break; case Aspect.tokenList: instance.setAttribute("class", value); break; } } } else if (target === "classList" || target === "className") { yield TemplateRenderer.formatAttribute("class", value); } } /** * Renders a boolean attribute binding */ private static *renderBooleanAttribute( code: AttributeBindingOp, value: unknown, renderInfo: RenderInfo ) { if (value) { const value = ""; const { target } = code; if (code.useCustomElementInstance) { const instance = getLast(renderInfo.customElementInstanceStack); if (instance) { instance.setAttribute(target, value); } } else { yield TemplateRenderer.formatAttribute(target, value); } } } }
the_stack
import "../../../../../entry"; import { assert } from "chai"; import { IContext } from "../../../../../../src/robotlegs/bender/framework/api/IContext"; import { IInjector } from "../../../../../../src/robotlegs/bender/framework/api/IInjector"; import { Context } from "../../../../../../src/robotlegs/bender/framework/impl/Context"; import { IEventDispatcher } from "../../../../../../src/robotlegs/bender/events/api/IEventDispatcher"; import { Event } from "../../../../../../src/robotlegs/bender/events/impl/Event"; import { EventDispatcher } from "../../../../../../src/robotlegs/bender/events/impl/EventDispatcher"; import { ICommand } from "../../../../../../src/robotlegs/bender/extensions/commandCenter/api/ICommand"; import { ICommandMapping } from "../../../../../../src/robotlegs/bender/extensions/commandCenter/api/ICommandMapping"; import { ICommandMapper } from "../../../../../../src/robotlegs/bender/extensions/commandCenter/dsl/ICommandMapper"; import { CommandMapper } from "../../../../../../src/robotlegs/bender/extensions/commandCenter/impl/CommandMapper"; import { IEventCommandMap } from "../../../../../../src/robotlegs/bender/extensions/eventCommandMap/api/IEventCommandMap"; import { EventCommandMap } from "../../../../../../src/robotlegs/bender/extensions/eventCommandMap/impl/EventCommandMap"; import { HappyGuard } from "../../../framework/impl/guardSupport/HappyGuard"; import { GrumpyGuard } from "../../../framework/impl/guardSupport/GrumpyGuard"; import { CallbackCommand } from "../../commandCenter/support/CallbackCommand"; import { CallbackCommand2 } from "../../commandCenter/support/CallbackCommand2"; import { ClassReportingCallbackGuard } from "../../commandCenter/support/ClassReportingCallbackGuard"; import { ClassReportingCallbackGuard2 } from "../../commandCenter/support/ClassReportingCallbackGuard2"; import { ClassReportingCallbackCommand } from "../../commandCenter/support/ClassReportingCallbackCommand"; import { ClassReportingCallbackCommand2 } from "../../commandCenter/support/ClassReportingCallbackCommand2"; import { ClassReportingCallbackHook } from "../../commandCenter/support/ClassReportingCallbackHook"; import { NullCommand } from "../../commandCenter/support/NullCommand"; import { CascadingCommand } from "../support/CascadingCommand"; import { CommandMappingCommand } from "../support/CommandMappingCommand"; import { CommandUnmappingCommand } from "../support/CommandUnmappingCommand"; import { EventInjectedCallbackCommand } from "../support/EventInjectedCallbackCommand"; import { EventInjectedCallbackGuard } from "../support/EventInjectedCallbackGuard"; import { EventParametersCommand } from "../support/EventParametersCommand"; import { SupportEvent } from "../support/SupportEvent"; import { SupportEventTriggeredSelfReportingCallbackCommand } from "../support/SupportEventTriggeredSelfReportingCallbackCommand"; describe("EventCommandMap", () => { let reportedExecutions: any[]; let context: IContext; let injector: IInjector; let dispatcher: EventDispatcher; let subject: EventCommandMap; function reportingFunction(item: any): void { reportedExecutions.push(item); } function commandExecutionCount(totalEvents: number = 1, oneshot: boolean = false): number { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; }) .whenTargetNamed("executeCallback"); subject .map(SupportEvent.TYPE1, SupportEvent) .toCommand(CallbackCommand) .once(oneshot); while (totalEvents--) { dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); } return executeCount; } function oneshotCommandExecutionCount(totalEvents: number = 1): number { return commandExecutionCount(totalEvents, true); } function hookCallCount(...hooks: any[]): number { let executionCount: number = 0; injector.unbind("Function"); injector .bind("Function") .toFunction(() => { executionCount++; }) .whenTargetNamed("reportingFunction"); subject .map(SupportEvent.TYPE1) .toCommand(NullCommand) .withHooks(hooks); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); return executionCount; } function commandExecutionCountWithGuards(...guards: any[]): number { let executionCount: number = 0; injector .bind("Function") .toFunction(() => { executionCount++; }) .whenTargetNamed("executeCallback"); subject .map(SupportEvent.TYPE1) .toCommand(CallbackCommand) .withGuards(guards); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); return executionCount; } beforeEach(() => { reportedExecutions = []; context = new Context(); injector = context.injector; injector .bind("Function") .toConstantValue(reportingFunction) .whenTargetNamed("reportingFunction"); dispatcher = new EventDispatcher(); subject = new EventCommandMap(context, dispatcher); context.initialize(); }); afterEach(() => { reportedExecutions = null; context.destroy(); context = null; injector = null; dispatcher = null; subject = null; }); it("map_creates_mapper", () => { assert.instanceOf(subject.map(SupportEvent.TYPE1, SupportEvent), CommandMapper); }); it("map_to_identical_Type_but_different_Event_returns_different_mapper", () => { let mapper1: ICommandMapper = subject.map(SupportEvent.TYPE1, SupportEvent); let mapper2: ICommandMapper = subject.map(SupportEvent.TYPE1, Event); assert.notEqual(mapper1, mapper2); }); it("map_to_different_Type_but_identical_Event_returns_different_mapper", () => { let mapper1: ICommandMapper = subject.map(SupportEvent.TYPE1, SupportEvent); let mapper2: ICommandMapper = subject.map(SupportEvent.TYPE2, SupportEvent); assert.notEqual(mapper1, mapper2); }); it("unmap_returns_mapper", () => { subject.map(SupportEvent.TYPE1, SupportEvent); assert.instanceOf(subject.unmap(SupportEvent.TYPE1, SupportEvent), CommandMapper); }); it("robust_to_unmapping_non_existent_mappings", () => { // note: no assertion, just testing for the lack of an NPE subject.unmap(SupportEvent.TYPE1, SupportEvent).fromCommand(NullCommand); }); it("command_executes_successfully", () => { assert.equal(commandExecutionCount(1), 1); }); it("command_executes_repeatedly", () => { assert.equal(commandExecutionCount(5), 5); }); it("fireOnce_command_executes_once", () => { assert.equal(oneshotCommandExecutionCount(5), 1); }); it("event_is_injected_into_command", () => { const expectedEvent: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let injectedEvent: Event = null; injector .bind("Function") .toFunction((command: EventInjectedCallbackCommand) => { injectedEvent = command.event; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, Event).toCommand(EventInjectedCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(injectedEvent, expectedEvent); }); it("event_is_passed_to_execute_method", () => { const expectedEvent: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let actualEvent: SupportEvent = null; injector .bind("Function") .toFunction((event: SupportEvent) => { actualEvent = event; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, SupportEvent).toCommand(EventParametersCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(actualEvent, expectedEvent); }); it("concretely_specified_typed_event_is_injected_into_command_as_typed_event", () => { const expectedEvent: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let untypedEvent: Event; let typedEvent: SupportEvent; injector .bind("Function") .toFunction((command: SupportEventTriggeredSelfReportingCallbackCommand) => { untypedEvent = command.untypedEvent; typedEvent = command.typedEvent; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, SupportEvent).toCommand(SupportEventTriggeredSelfReportingCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(typedEvent, expectedEvent); assert.isUndefined(untypedEvent); }); it("abstractly_specified_typed_event_is_injected_into_command_as_untyped_event", () => { const expectedEvent: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let untypedEvent: Event; let typedEvent: SupportEvent; injector .bind("Function") .toFunction((command: SupportEventTriggeredSelfReportingCallbackCommand) => { untypedEvent = command.untypedEvent; typedEvent = command.typedEvent; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, Event).toCommand(SupportEventTriggeredSelfReportingCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(untypedEvent, expectedEvent); assert.isUndefined(typedEvent); }); it("unspecified_typed_event_is_injected_into_command_as_typed_event", () => { const expectedEvent: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let untypedEvent: Event; let typedEvent: SupportEvent; injector .bind("Function") .toFunction((command: SupportEventTriggeredSelfReportingCallbackCommand) => { untypedEvent = command.untypedEvent; typedEvent = command.typedEvent; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1).toCommand(SupportEventTriggeredSelfReportingCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(typedEvent, expectedEvent); assert.isUndefined(untypedEvent); }); it("unspecified_untyped_event_is_injected_into_command_as_untyped_event", () => { const eventType: string = "eventType"; const expectedEvent: Event = new Event(eventType); let untypedEvent: Event; let typedEvent: SupportEvent; injector .bind("Function") .toFunction((command: SupportEventTriggeredSelfReportingCallbackCommand) => { untypedEvent = command.untypedEvent; typedEvent = command.typedEvent; }) .whenTargetNamed("executeCallback"); subject.map(eventType).toCommand(SupportEventTriggeredSelfReportingCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(untypedEvent, expectedEvent); assert.isUndefined(typedEvent); }); it("specified_untyped_event_is_injected_into_command_as_untyped_event", () => { const eventType: string = "eventType"; const expectedEvent: Event = new Event(eventType); let untypedEvent: Event; let typedEvent: SupportEvent; injector .bind("Function") .toFunction((command: SupportEventTriggeredSelfReportingCallbackCommand) => { untypedEvent = command.untypedEvent; typedEvent = command.typedEvent; }) .whenTargetNamed("executeCallback"); subject.map(eventType, Event).toCommand(SupportEventTriggeredSelfReportingCallbackCommand); dispatcher.dispatchEvent(expectedEvent); assert.equal(untypedEvent, expectedEvent); assert.isUndefined(typedEvent); }); it("command_does_not_execute_when_incorrect_eventType_dispatched", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1).toCommand(CallbackCommand); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE2)); assert.equal(executeCount, 0); }); it("command_does_not_execute_when_incorrect_eventClass_dispatched", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, SupportEvent).toCommand(CallbackCommand); dispatcher.dispatchEvent(new Event(SupportEvent.TYPE1)); assert.equal(executeCount, 0); }); it("command_does_not_execute_after_event_unmapped", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1, SupportEvent).toCommand(CallbackCommand); subject.unmap(SupportEvent.TYPE1, SupportEvent).fromCommand(CallbackCommand); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.equal(executeCount, 0); }); it("oneshot_mappings_should_not_bork_stacked_mappings", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; }) .whenTargetNamed("executeCallback"); subject .map(SupportEvent.TYPE1, SupportEvent) .toCommand(CallbackCommand) .once(); subject .map(SupportEvent.TYPE1, SupportEvent) .toCommand(CallbackCommand2) .once(); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.equal(executeCount, 2); }); it("one_shot_command_should_not_cause_infinite_loop_when_dispatching_to_self", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); }) .whenTargetNamed("executeCallback"); subject .map(SupportEvent.TYPE1) .toCommand(CallbackCommand) .once(); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.equal(executeCount, 1); }); it("commands_should_not_stomp_over_event_mappings", () => { let executeCount: number = 0; injector .bind("Function") .toFunction(() => { executeCount++; dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE2)); }) .whenTargetNamed("executeCallback"); subject.map(SupportEvent.TYPE1).toCommand(CallbackCommand); subject .map(SupportEvent.TYPE2) .toCommand(CallbackCommand) .once(); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.equal(executeCount, 2); }); it("commands_are_executed_in_order", () => { subject.map(SupportEvent.TYPE1).toCommand(ClassReportingCallbackCommand); subject.map(SupportEvent.TYPE1).toCommand(ClassReportingCallbackCommand2); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.deepEqual(reportedExecutions, [ClassReportingCallbackCommand, ClassReportingCallbackCommand2]); }); it("hooks_are_called", () => { assert.equal(hookCallCount(ClassReportingCallbackHook, ClassReportingCallbackHook), 2); }); it("command_executes_when_the_guard_allows", () => { assert.equal(commandExecutionCountWithGuards(HappyGuard), 1); }); it("command_executes_when_all_guards_allow", () => { assert.equal(commandExecutionCountWithGuards(HappyGuard, HappyGuard), 1); }); it("command_does_not_execute_when_the_guard_denies", () => { assert.equal(commandExecutionCountWithGuards(GrumpyGuard), 0); }); it("command_does_not_execute_when_any_guards_denies", () => { assert.equal(commandExecutionCountWithGuards(HappyGuard, GrumpyGuard), 0); }); it("command_does_not_execute_when_all_guards_deny", () => { assert.equal(commandExecutionCountWithGuards(GrumpyGuard, GrumpyGuard), 0); }); it("event_is_injected_into_guard", () => { const event: SupportEvent = new SupportEvent(SupportEvent.TYPE1); let injectedEvent: Event = null; injector .bind("Function") .toFunction((guard: EventInjectedCallbackGuard) => { injectedEvent = guard.event; }) .whenTargetNamed("approveCallback"); subject .map(SupportEvent.TYPE1, Event) .toCommand(NullCommand) .withGuards(EventInjectedCallbackGuard); dispatcher.dispatchEvent(event); assert.equal(injectedEvent, event); }); it("cascading_events_do_not_throw_unmap_errors", () => { injector.bind(IEventDispatcher).toConstantValue(dispatcher); injector.bind(IEventCommandMap).toConstantValue(subject); subject .map(CascadingCommand.EVENT_TYPE) .toCommand(CascadingCommand) .once(); dispatcher.dispatchEvent(new Event(CascadingCommand.EVENT_TYPE)); }); it("execution_sequence_is_guard_command_guard_command_for_multiple_mappings_to_same_event", () => { subject .map(SupportEvent.TYPE1) .toCommand(ClassReportingCallbackCommand) .withGuards(ClassReportingCallbackGuard); subject .map(SupportEvent.TYPE1) .toCommand(ClassReportingCallbackCommand2) .withGuards(ClassReportingCallbackGuard2); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); const expectedOrder: any[] = [ ClassReportingCallbackGuard, ClassReportingCallbackCommand, ClassReportingCallbackGuard2, ClassReportingCallbackCommand2 ]; assert.deepEqual(reportedExecutions, expectedOrder); }); it("previously_constructed_command_does_not_slip_through_the_loop", () => { subject .map(SupportEvent.TYPE1) .toCommand(ClassReportingCallbackCommand) .withGuards(HappyGuard); subject .map(SupportEvent.TYPE1) .toCommand(ClassReportingCallbackCommand2) .withGuards(GrumpyGuard); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); const expectedOrder: any[] = [ClassReportingCallbackCommand]; assert.deepEqual(reportedExecutions, expectedOrder); }); it("commands_mapped_during_execution_are_not_executed", () => { injector.bind(IEventCommandMap).toConstantValue(subject); injector .bind(ICommand) .toConstantValue(ClassReportingCallbackCommand) .whenTargetNamed("nestedCommand"); subject .map(SupportEvent.TYPE1, Event) .toCommand(CommandMappingCommand) .once(); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.deepEqual(reportedExecutions, []); }); it("commands_unmapped_during_execution_are_still_executed", () => { injector.bind(IEventCommandMap).toConstantValue(subject); injector .bind(ICommand) .toConstantValue(ClassReportingCallbackCommand) .whenTargetNamed("nestedCommand"); subject .map(SupportEvent.TYPE1, Event) .toCommand(CommandUnmappingCommand) .once(); subject .map(SupportEvent.TYPE1, Event) .toCommand(ClassReportingCallbackCommand) .once(); dispatcher.dispatchEvent(new SupportEvent(SupportEvent.TYPE1)); assert.deepEqual(reportedExecutions, [ClassReportingCallbackCommand]); }); it("mapping_processor_is_called", () => { let callCount: number = 0; subject.addMappingProcessor((mapping: ICommandMapping) => { callCount++; }); subject.map("type").toCommand(NullCommand); assert.equal(callCount, 1); }); it("mapping_processor_are_called", () => { let callCount: number = 0; subject.addMappingProcessor((mapping: ICommandMapping) => { callCount++; }); subject.addMappingProcessor((mapping: ICommandMapping) => { callCount++; }); subject.addMappingProcessor((mapping: ICommandMapping) => { callCount++; }); subject.map("type").toCommand(NullCommand); assert.equal(callCount, 3); }); it("mapping_processor_added_twice_is_called_once", () => { let callCount: number = 0; let processor: Function = (mapping: ICommandMapping) => { callCount++; }; subject.addMappingProcessor(processor); subject.addMappingProcessor(processor); subject.map("type").toCommand(NullCommand); assert.equal(callCount, 1); }); });
the_stack
import Utils from "../Utils"; import { DataTypes, TooltipMeasureFormat } from "./../Constants/Enums"; import { GRIDCONTAINERCLASS } from "./../Constants/Constants"; import {Component} from "./Component"; import {ChartComponentData} from './../Models/ChartComponentData'; import EllipsisMenu from "../Components/EllipsisMenu"; import * as d3 from 'd3'; import Split from 'split.js'; import Legend from "../Components/Legend"; import { ShiftTypes } from "../Constants/Enums"; import Grid from "../Components/Grid"; class ChartComponent extends Component { readonly MINWIDTH = 350; protected MINHEIGHT = 150; readonly CONTROLSWIDTH = 200; readonly GUTTERWIDTH = 6; public data: any; public aggregateExpressionOptions: any; protected chartControlsPanel = null; protected ellipsisContainer = null; protected ellipsisMenu: EllipsisMenu = null; protected legendObject: Legend; protected width: number; protected chartWidth: number; protected svgSelection = null; protected legendWidth: number = this.CONTROLSWIDTH; public draw; public chartComponentData: ChartComponentData; public chartMargins: any; constructor(renderTarget: Element){ super(renderTarget); this.chartComponentData = new ChartComponentData(); } public showGrid () { Grid.showGrid(this.renderTarget, this.chartOptions, this.aggregateExpressionOptions, this.chartComponentData); } public gatedShowGrid () { if (this.isGridVisible()) { this.showGrid(); } } public hideGrid () { Grid.hideGrid(this.renderTarget); } public isGridVisible () { return !d3.select(this.renderTarget).selectAll(`.${GRIDCONTAINERCLASS}`).empty(); } protected drawEllipsisMenu (additionalEllipsisItems = []) { if (this.chartOptions.canDownload || this.chartOptions.grid || (this.chartOptions.ellipsisItems && this.chartOptions.ellipsisItems.length > 0) || additionalEllipsisItems.length > 0) { if (this.ellipsisContainer === null) { this.ellipsisContainer = this.chartControlsPanel.append("div") .attr("class", "tsi-ellipsisContainerDiv"); } if (this.ellipsisMenu === null) { this.ellipsisMenu = new EllipsisMenu(this.ellipsisContainer.node()); } var ellipsisItems = []; if (this.chartOptions.grid) { ellipsisItems.push(Grid.createGridEllipsisOption(this.renderTarget, this.chartOptions, this.aggregateExpressionOptions, this.chartComponentData, this.getString("Display Grid"))); } if (this.chartOptions.canDownload) { ellipsisItems.push(Utils.createDownloadEllipsisOption(() => this.chartComponentData.generateCSVString(this.chartOptions.offset, this.chartOptions.dateLocale), () => Utils.focusOnEllipsisButton(this.renderTarget) ,this.getString("Download as CSV"))); } if (this.chartOptions.ellipsisItems) { ellipsisItems = ellipsisItems.concat(this.chartOptions.ellipsisItems); } this.ellipsisMenu.render(ellipsisItems.concat(additionalEllipsisItems), {theme: this.chartOptions.theme}); } } public downloadAsCSV = (isScatterPlot = false) => { Utils.downloadCSV(this.chartComponentData.generateCSVString(this.chartOptions.offset, this.chartOptions.dateLocale, isScatterPlot ? this.chartOptions.spMeasures : null)); } protected removeControlPanel () { if (this.chartControlsPanel) { this.chartControlsPanel.remove(); } this.chartControlsPanel = null; this.ellipsisContainer = null; this.ellipsisMenu = null; } protected removeEllipsisMenu () { if (this.ellipsisContainer) { this.ellipsisContainer.remove(); } this.ellipsisContainer = null; this.ellipsisMenu = null; } protected getWidth () { return Math.max((<any>d3.select(this.renderTarget).node()).clientWidth, this.MINWIDTH); } public getVisibilityState () { return this.chartComponentData.getVisibilityState(); } protected ellipsisItemsExist () { return (this.chartOptions.canDownload || this.chartOptions.ellipsisItems.length > 0 || this.chartOptions.grid); } protected getDataType (aggKey) { return this.chartComponentData.getDataType(aggKey); } protected getCDOFromAggKey (aggKey) { let matches = this.aggregateExpressionOptions.filter((cDO) => { return cDO.aggKey === aggKey; }); if (matches.length === 1) { return matches[0]; } return {}; } protected getFilteredMeasures (measureList, visibleMeasure, measureFormat: TooltipMeasureFormat, xyrMeasures = null) { let justVisibleMeasure = [visibleMeasure]; switch (measureFormat) { case TooltipMeasureFormat.SingleValue: return justVisibleMeasure; case TooltipMeasureFormat.Scatter: return xyrMeasures; default: if (measureList.length !== 3) { return justVisibleMeasure; } let isAvgMinMax = true; measureList.forEach((measure) => { if (!(measure === 'avg' || measure === 'min' || measure === 'max')) { isAvgMinMax = false; } }); return isAvgMinMax ? measureList.sort(m => m === 'min' ? -1 : (m === 'avg' ? 0 : 1)) : justVisibleMeasure; } } // to get alignment for data points between other types and linechart for tooltip formatting protected convertToTimeValueFormat (d: any) { let measuresObject = {}; let measureType = d.measureType ? d.measureType : this.chartComponentData.displayState[d.aggKey].splitBys[d.splitBy].visibleType; measuresObject[measureType] = d.val; return { aggregateKey: d.aggKey, splitBy: d.splitBy, aggregateName: this.chartComponentData.displayState[d.aggKey].name, measures: measuresObject } } protected formatDate (date, shiftMillis) { return Utils.timeFormat(this.chartComponentData.usesSeconds, this.chartComponentData.usesMillis, this.chartOptions.offset, this.chartOptions.is24HourTime, shiftMillis, null, this.chartOptions.dateLocale)(date); } protected tooltipFormat (d, text, measureFormat: TooltipMeasureFormat, xyrMeasures = null) { let dataType = this.getDataType(d.aggregateKey); var title = d.aggregateName; let cDO = this.getCDOFromAggKey(d.aggregateKey); let shiftMillis = this.chartComponentData.getTemporalShiftMillis(d.aggregateKey); let formatDate = (date) => this.formatDate(date, shiftMillis); let titleGroup = text.append("div") .attr("class", "tsi-tooltipTitleGroup"); this.createTooltipSeriesInfo(d, titleGroup, cDO); if (dataType === DataTypes.Categorical) { titleGroup.append('h4') .attr('class', 'tsi-tooltipSubtitle tsi-tooltipTimeStamp') .text(formatDate(d.dateTime) + ' - ' + formatDate(d.endDate)); } if (dataType === DataTypes.Events) { titleGroup.append('h4') .attr('class', 'tsi-tooltipSubtitle tsi-tooltipTimeStamp') .text(formatDate(d.dateTime)); } let tooltipAttrs = cDO.tooltipAttributes; if (shiftMillis !== 0 && tooltipAttrs) { let shiftTuple = this.chartComponentData.getTemporalShiftStringTuple(d.aggregateKey); if (shiftTuple !== null) { let keyString = this.getString(shiftTuple[0]); let valueString = (keyString === ShiftTypes.startAt) ? this.formatDate(new Date(shiftTuple[1]), 0) : shiftTuple[1]; tooltipAttrs = [...tooltipAttrs, [keyString, valueString]]; } } if (tooltipAttrs && tooltipAttrs.length > 0) { let attrsGroup = text.append('div') .attr('class', 'tsi-tooltipAttributeContainer tsi-tooltipFlexyBox'); tooltipAttrs.forEach((attrTuple, i) => { let timeShiftRow = attrsGroup.append('div') .attr('class', 'tsi-tooltipAttribute tsi-tooltipFlexyItem'); timeShiftRow.append('div') .attr('class', 'tsi-tooltipAttrTitle') .text(attrTuple[0]); timeShiftRow.append('div') .attr('class', 'tsi-tooltipAttrValue') .text(attrTuple[1]); }) } if (d.measures && Object.keys(d.measures).length) { let formatValue = (dataType === DataTypes.Events ? (d) => d : Utils.formatYAxisNumber) if(dataType !== DataTypes.Numeric) { let valueGroup = text.append('table') .attr('class', 'tsi-tooltipValues tsi-tooltipTable'); Object.keys(d.measures).forEach((measureType, i) => { if(!(dataType === DataTypes.Categorical) || d.measures[measureType] !== 0){ valueGroup.append('tr').classed('tsi-tableSpacer', true); let tr = valueGroup.append('tr') .classed('tsi-visibleValue', (dataType === DataTypes.Numeric && (measureType === this.chartComponentData.getVisibleMeasure(d.aggregateKey, d.splitBy)))) .style('border-left-color', Utils.getColorForValue(cDO, measureType)); tr.append('td') .attr('class', 'tsi-valueLabel') .text(measureType); tr.append('td') .attr('class', 'tsi-valueCell') .text(formatValue(d.measures[measureType])) } }); } else { let valueGroup = text.append('div') .attr('class', 'tsi-tooltipFlexyBox'); let filteredMeasures = this.getFilteredMeasures(Object.keys(d.measures), this.chartComponentData.getVisibleMeasure(d.aggregateKey, d.splitBy), measureFormat, xyrMeasures); filteredMeasures.forEach((measureType, i) => { let valueItem = valueGroup.append('div') .attr('class', 'tsi-tooltipFlexyItem') .classed('tsi-visibleValue', (dataType === DataTypes.Numeric && (measureType === this.chartComponentData.getVisibleMeasure(d.aggregateKey, d.splitBy)) && (measureFormat !== TooltipMeasureFormat.Scatter))); let measureTitle = valueItem.append('div') .attr('class', 'tsi-tooltipMeasureTitle') Utils.appendFormattedElementsFromString(measureTitle, measureType); valueItem.append('div') .attr('class', 'tsi-tooltipMeasureValue') .text(formatValue(d.measures[measureType])) }); } } } protected getSVGWidth () { return this.chartWidth + this.chartMargins.left + this.chartMargins.right; } protected getChartWidth (legendWidth = this.CONTROLSWIDTH) { legendWidth = this.legendWidth;// + this.GUTTERWIDTH; return Math.max(1, this.width - this.chartMargins.left - this.chartMargins.right - (this.chartOptions.legend === "shown" ? legendWidth : 0)); } protected calcSVGWidth () { return this.svgSelection.node().getBoundingClientRect().width; } protected setControlsPanelWidth () { if (!this.chartOptions.hideChartControlPanel && this.chartControlsPanel !== null) { //either calculate expected or just use svg if it's in the DOM let controlPanelWidth = this.svgSelection && this.svgSelection.node() ? this.calcSVGWidth() : this.getWidth() - (this.chartOptions.legend === 'shown' ? (this.legendWidth + this.GUTTERWIDTH) : 0); this.chartControlsPanel.style("width", controlPanelWidth + "px"); } } protected legendPostRenderProcess (legendState: string, chartElement: any, shouldSetControlsWidth: boolean, splitLegendOnDrag: any = undefined) { if (legendState === 'shown') { this.splitLegendAndSVG(chartElement.node(), splitLegendOnDrag); if (shouldSetControlsWidth) { this.setControlsPanelWidth(); } } else { d3.select(this.renderTarget).select('.tsi-resizeGutter').remove(); } } protected splitLegendAndSVG (chartElement, onDrag = () => {}) { let svgWidth = this.getSVGWidth(); let legendWidth = this.width - svgWidth; d3.select(this.renderTarget).select('.tsi-resizeGutter').remove(); let legend = this.legendObject.legendElement; Split([this.legendObject.legendElement.node(), chartElement], { sizes: [legendWidth / this.width * 100, svgWidth / this.width * 100], gutterSize: 2, minSize: [200, 0], snapOffset: 0, cursor: 'e-resize', onDragEnd: (sizes) => { let legendWidth = this.width * (sizes[0] / 100); this.legendWidth = legendWidth; this.chartWidth = this.getChartWidth(); this.draw(true); legend.style('width', this.legendWidth + 'px'); d3.select(this.renderTarget).select('.tsi-resizeGutter') .classed('tsi-isDragging', false); }, onDragStart: () => { d3.select(this.renderTarget).select('.tsi-resizeGutter') .classed('tsi-isDragging', true); }, onDrag: () => { if (!this.chartOptions.hideChartControlPanel && this.chartControlsPanel !== null) { let svgLeftOffset = this.calcSVGWidth(); this.chartControlsPanel.style("width", Math.max(svgLeftOffset, this.chartMargins.left + 8) + "px"); //8px to account for the width of the icon } onDrag(); }, gutter: (index, direction) => { const gutter = document.createElement('div'); gutter.className = `gutter tsi-resizeGutter`; return gutter; }, direction: 'horizontal' }); // explicitly set the width of the legend to a pixel value let calcedLegendWidth = legend.node().getBoundingClientRect().width; legend.style("width", calcedLegendWidth + "px"); } } export {ChartComponent}
the_stack
import { Directive, ElementRef, Renderer2, Input, Output, OnInit, HostListener, EventEmitter, OnChanges, SimpleChanges, OnDestroy, AfterViewInit } from '@angular/core'; import { Subscription, fromEvent } from 'rxjs'; import { IPosition, Position } from './models/position'; import { HelperBlock } from './widgets/helper-block'; @Directive({ selector: '[ngDraggable]', exportAs: 'ngDraggable' }) export class AngularDraggableDirective implements OnInit, OnDestroy, OnChanges, AfterViewInit { private allowDrag = true; private moving = false; private orignal: Position = null; private oldTrans = new Position(0, 0); private tempTrans = new Position(0, 0); private currTrans = new Position(0, 0); private oldZIndex = ''; private _zIndex = ''; private needTransform = false; private draggingSub: Subscription = null; /** * Bugfix: iFrames, and context unrelated elements block all events, and are unusable * https://github.com/xieziyu/angular2-draggable/issues/84 */ private _helperBlock: HelperBlock = null; @Output() started = new EventEmitter<any>(); @Output() stopped = new EventEmitter<any>(); @Output() edge = new EventEmitter<any>(); /** Make the handle HTMLElement draggable */ @Input() handle: HTMLElement; /** Set the bounds HTMLElement */ @Input() bounds: HTMLElement; /** List of allowed out of bounds edges **/ @Input() outOfBounds = { top: false, right: false, bottom: false, left: false }; /** Round the position to nearest grid */ @Input() gridSize = 1; /** Set z-index when dragging */ @Input() zIndexMoving: string; /** Set z-index when not dragging */ @Input() set zIndex(setting: string) { this.renderer.setStyle(this.el.nativeElement, 'z-index', setting); this._zIndex = setting; } /** Whether to limit the element stay in the bounds */ @Input() inBounds = false; /** Whether the element should use it's previous drag position on a new drag event. */ @Input() trackPosition = true; /** Input css scale transform of element so translations are correct */ @Input() scale = 1; /** Whether to prevent default event */ @Input() preventDefaultEvent = false; /** Set initial position by offsets */ @Input() position: IPosition = { x: 0, y: 0 }; /** Lock axis: 'x' or 'y' */ @Input() lockAxis: string = null; /** Emit position offsets when moving */ @Output() movingOffset = new EventEmitter<IPosition>(); /** Emit position offsets when put back */ @Output() endOffset = new EventEmitter<IPosition>(); @Input() set ngDraggable(setting: any) { if (setting !== undefined && setting !== null && setting !== '') { this.allowDrag = !!setting; let element = this.getDragEl(); if (this.allowDrag) { this.renderer.addClass(element, 'ng-draggable'); } else { this.putBack(); this.renderer.removeClass(element, 'ng-draggable'); } } } constructor(private el: ElementRef, private renderer: Renderer2) { this._helperBlock = new HelperBlock(el.nativeElement, renderer); } ngOnInit() { if (this.allowDrag) { let element = this.getDragEl(); this.renderer.addClass(element, 'ng-draggable'); } this.resetPosition(); } ngOnDestroy() { this.bounds = null; this.handle = null; this.orignal = null; this.oldTrans = null; this.tempTrans = null; this.currTrans = null; this._helperBlock.dispose(); this._helperBlock = null; if (this.draggingSub) { this.draggingSub.unsubscribe(); } } ngOnChanges(changes: SimpleChanges) { if (changes['position'] && !changes['position'].isFirstChange()) { let p = changes['position'].currentValue; if (!this.moving) { if (Position.isIPosition(p)) { this.oldTrans.set(p); } else { this.oldTrans.reset(); } this.transform(); } else { this.needTransform = true; } } } ngAfterViewInit() { if (this.inBounds) { this.boundsCheck(); this.oldTrans.add(this.tempTrans); this.tempTrans.reset(); } } private getDragEl() { return this.handle ? this.handle : this.el.nativeElement; } resetPosition() { if (Position.isIPosition(this.position)) { this.oldTrans.set(this.position); } else { this.oldTrans.reset(); } this.tempTrans.reset(); this.transform(); } private moveTo(p: Position) { if (this.orignal) { p.subtract(this.orignal); this.tempTrans.set(p); this.tempTrans.divide(this.scale); this.transform(); if (this.bounds) { this.edge.emit(this.boundsCheck()); } this.movingOffset.emit(this.currTrans.value); } } private transform() { let translateX = this.tempTrans.x + this.oldTrans.x; let translateY = this.tempTrans.y + this.oldTrans.y; if (this.lockAxis === 'x') { translateX = this.oldTrans.x; this.tempTrans.x = 0; } else if (this.lockAxis === 'y') { translateY = this.oldTrans.y; this.tempTrans.y = 0; } // Snap to grid: by grid size if (this.gridSize > 1) { translateX = Math.round(translateX / this.gridSize) * this.gridSize; translateY = Math.round(translateY / this.gridSize) * this.gridSize; } let value = `translate(${ Math.round(translateX) }px, ${ Math.round(translateY) }px)`; this.renderer.setStyle(this.el.nativeElement, 'transform', value); this.renderer.setStyle(this.el.nativeElement, '-webkit-transform', value); this.renderer.setStyle(this.el.nativeElement, '-ms-transform', value); this.renderer.setStyle(this.el.nativeElement, '-moz-transform', value); this.renderer.setStyle(this.el.nativeElement, '-o-transform', value); // save current position this.currTrans.x = translateX; this.currTrans.y = translateY; } private pickUp() { // get old z-index: this.oldZIndex = this.el.nativeElement.style.zIndex ? this.el.nativeElement.style.zIndex : ''; if (window) { this.oldZIndex = window.getComputedStyle(this.el.nativeElement, null).getPropertyValue('z-index'); } if (this.zIndexMoving) { this.renderer.setStyle(this.el.nativeElement, 'z-index', this.zIndexMoving); } if (!this.moving) { this.started.emit(this.el.nativeElement); this.moving = true; const element = this.getDragEl(); this.renderer.addClass(element, 'ng-dragging'); /** * Fix performance issue: * https://github.com/xieziyu/angular2-draggable/issues/112 */ this.subscribeEvents(); } } private subscribeEvents() { this.draggingSub = fromEvent(document, 'mousemove', { passive: false }).subscribe(event => this.onMouseMove(event as MouseEvent)); this.draggingSub.add(fromEvent(document, 'touchmove', { passive: false }).subscribe(event => this.onMouseMove(event as TouchEvent))); this.draggingSub.add(fromEvent(document, 'mouseup', { passive: false }).subscribe(() => this.putBack())); // checking if browser is IE or Edge - https://github.com/xieziyu/angular2-draggable/issues/153 let isIEOrEdge = /msie\s|trident\//i.test(window.navigator.userAgent); if (!isIEOrEdge) { this.draggingSub.add(fromEvent(document, 'mouseleave', {passive: false}).subscribe(() => this.putBack())); } this.draggingSub.add(fromEvent(document, 'touchend', { passive: false }).subscribe(() => this.putBack())); this.draggingSub.add(fromEvent(document, 'touchcancel', { passive: false }).subscribe(() => this.putBack())); } private unsubscribeEvents() { this.draggingSub.unsubscribe(); this.draggingSub = null; } boundsCheck() { if (this.bounds) { let boundary = this.bounds.getBoundingClientRect(); let elem = this.el.nativeElement.getBoundingClientRect(); let result = { 'top': this.outOfBounds.top ? true : boundary.top < elem.top, 'right': this.outOfBounds.right ? true : boundary.right > elem.right, 'bottom': this.outOfBounds.bottom ? true : boundary.bottom > elem.bottom, 'left': this.outOfBounds.left ? true : boundary.left < elem.left }; if (this.inBounds) { if (!result.top) { this.tempTrans.y -= (elem.top - boundary.top) / this.scale; } if (!result.bottom) { this.tempTrans.y -= (elem.bottom - boundary.bottom) / this.scale; } if (!result.right) { this.tempTrans.x -= (elem.right - boundary.right) / this.scale; } if (!result.left) { this.tempTrans.x -= (elem.left - boundary.left) / this.scale; } this.transform(); } return result; } } /** Get current offset */ getCurrentOffset() { return this.currTrans.value; } private putBack() { if (this._zIndex) { this.renderer.setStyle(this.el.nativeElement, 'z-index', this._zIndex); } else if (this.zIndexMoving) { if (this.oldZIndex) { this.renderer.setStyle(this.el.nativeElement, 'z-index', this.oldZIndex); } else { this.el.nativeElement.style.removeProperty('z-index'); } } if (this.moving) { this.stopped.emit(this.el.nativeElement); // Remove the helper div: this._helperBlock.remove(); if (this.needTransform) { if (Position.isIPosition(this.position)) { this.oldTrans.set(this.position); } else { this.oldTrans.reset(); } this.transform(); this.needTransform = false; } if (this.bounds) { this.edge.emit(this.boundsCheck()); } this.moving = false; this.endOffset.emit(this.currTrans.value); if (this.trackPosition) { this.oldTrans.add(this.tempTrans); } this.tempTrans.reset(); if (!this.trackPosition) { this.transform(); } const element = this.getDragEl(); this.renderer.removeClass(element, 'ng-dragging'); /** * Fix performance issue: * https://github.com/xieziyu/angular2-draggable/issues/112 */ this.unsubscribeEvents(); } } checkHandleTarget(target: EventTarget, element: Element) { // Checks if the target is the element clicked, then checks each child element of element as well // Ignores button clicks // Ignore elements of type button if (element.tagName === 'BUTTON') { return false; } // If the target was found, return true (handle was found) if (element === target) { return true; } // Recursively iterate this elements children for (let child in element.children) { if (element.children.hasOwnProperty(child)) { if (this.checkHandleTarget(target, element.children[child])) { return true; } } } // Handle was not found in this lineage // Note: return false is ignore unless it is the parent element return false; } @HostListener('mousedown', ['$event']) @HostListener('touchstart', ['$event']) onMouseDown(event: MouseEvent | TouchEvent) { // 1. skip right click; if (event instanceof MouseEvent && event.button === 2) { return; } // 2. if handle is set, the element can only be moved by handle let target = event.target || event.srcElement; if (this.handle !== undefined && !this.checkHandleTarget(target, this.handle)) { return; } // 3. if allow drag is set to false, ignore the mousedown if (this.allowDrag === false) { return; } if (this.preventDefaultEvent) { event.stopPropagation(); event.preventDefault(); } this.orignal = Position.fromEvent(event, this.getDragEl()); this.pickUp(); } onMouseMove(event: MouseEvent | TouchEvent) { if (this.moving && this.allowDrag) { if (this.preventDefaultEvent) { event.stopPropagation(); event.preventDefault(); } // Add a transparent helper div: this._helperBlock.add(); this.moveTo(Position.fromEvent(event, this.getDragEl())); } } }
the_stack
import { assert, assertEquals, assertThrows, assertThrowsAsync, fail, } from "https://deno.land/std@0.95.0/testing/asserts.ts"; import { AckPolicy, AdvisoryKind, deferred, Empty, ErrorCode, headers, JSONCodec, nuid, StreamConfig, StreamInfo, StringCodec, } from "../nats-base-client/internal_mod.ts"; import { cleanup, initStream, jetstreamExportServerConf, jetstreamServerConf, setup, } from "./jstest_util.ts"; import { connect } from "../src/mod.ts"; import { assertThrowsAsyncErrorCode } from "./helpers/mod.ts"; import { validateName } from "../nats-base-client/jsutil.ts"; const StreamNameRequired = "stream name required"; const ConsumerNameRequired = "durable name required"; Deno.test("jsm - jetstream not enabled", async () => { // start a regular server - no js conf const { ns, nc } = await setup(); await assertThrowsAsyncErrorCode(async () => { await nc.jetstreamManager(); }, ErrorCode.JetStreamNotEnabled); await cleanup(ns, nc); }); Deno.test("jsm - account info", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const ai = await jsm.getAccountInfo(); assert(ai.limits.max_memory === -1 || ai.limits.max_memory > 0); await cleanup(ns, nc); }); Deno.test("jsm - account not enabled", async () => { const conf = { "no_auth_user": "b", accounts: { A: { jetstream: "enabled", users: [{ user: "a", password: "a" }], }, B: { users: [{ user: "b" }], }, }, }; const { ns, nc } = await setup(jetstreamServerConf(conf, true)); await assertThrowsAsyncErrorCode(async () => { await nc.jetstreamManager(); }, ErrorCode.JetStreamNotEnabled); const a = await connect( { port: ns.port, user: "a", pass: "a" }, ); await a.jetstreamManager(); await a.close(); await cleanup(ns, nc); }); Deno.test("jsm - empty stream config fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.streams.add({} as StreamConfig); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - empty stream config update fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const name = nuid.next(); let ci = await jsm.streams.add({ name: name, subjects: [`${name}.>`] }); assertEquals(ci!.config!.subjects!.length, 1); await assertThrowsAsync( async () => { await jsm.streams.update({} as StreamConfig); }, Error, StreamNameRequired, ); ci!.config!.subjects!.push("foo"); ci = await jsm.streams.update(ci.config); assertEquals(ci!.config!.subjects!.length, 2); await cleanup(ns, nc); }); Deno.test("jsm - delete empty stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.streams.delete(""); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - info empty stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.streams.info(""); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - info msg not found stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const name = nuid.next(); await assertThrowsAsync( async () => { await jsm.streams.info(name); }, Error, "stream not found", ); await cleanup(ns, nc); }); Deno.test("jsm - delete msg empty stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.streams.deleteMessage("", 1); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - delete msg not found stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const name = nuid.next(); await assertThrowsAsync( async () => { await jsm.streams.deleteMessage(name, 1); }, Error, "stream not found", ); await cleanup(ns, nc); }); Deno.test("jsm - no stream lister is empty", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const streams = await jsm.streams.list().next(); assertEquals(streams.length, 0); await cleanup(ns, nc); }); Deno.test("jsm - lister after empty, empty", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const lister = jsm.streams.list(); let streams = await lister.next(); assertEquals(streams.length, 0); streams = await lister.next(); assertEquals(streams.length, 0); await cleanup(ns, nc); }); Deno.test("jsm - add stream", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const name = nuid.next(); let si = await jsm.streams.add({ name }); assertEquals(si.config.name, name); const fn = (i: StreamInfo): boolean => { assertEquals(i.config, si.config); assertEquals(i.state, si.state); assertEquals(i.created, si.created); return true; }; fn(await jsm.streams.info(name)); let lister = await jsm.streams.list().next(); fn(lister[0]); // add some data nc.publish(name, Empty); si = await jsm.streams.info(name); lister = await jsm.streams.list().next(); fn(lister[0]); await cleanup(ns, nc); }); Deno.test("jsm - purge not found stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const name = nuid.next(); await assertThrowsAsync( async () => { await jsm.streams.purge(name); }, Error, "stream not found", ); await cleanup(ns, nc); }); Deno.test("jsm - purge empty stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.streams.purge(""); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - stream purge", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream, subj } = await initStream(nc); const jsm = await nc.jetstreamManager(); nc.publish(subj, Empty); let si = await jsm.streams.info(stream); assertEquals(si.state.messages, 1); await jsm.streams.purge(stream); si = await jsm.streams.info(stream); assertEquals(si.state.messages, 0); await cleanup(ns, nc); }); Deno.test("jsm - purge by sequence", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); const pi = await jsm.streams.purge(stream, { seq: 4 }); assertEquals(pi.purged, 3); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 4); await cleanup(ns, nc); }); Deno.test("jsm - purge by filtered sequence", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); const pi = await jsm.streams.purge(stream, { seq: 4, filter: `${stream}.b` }); assertEquals(pi.purged, 1); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 1); assertEquals(si.state.messages, 8); await cleanup(ns, nc); }); Deno.test("jsm - purge by subject", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); const pi = await jsm.streams.purge(stream, { filter: `${stream}.b` }); assertEquals(pi.purged, 3); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 1); assertEquals(si.state.messages, 6); await cleanup(ns, nc); }); Deno.test("jsm - purge by subject", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); const pi = await jsm.streams.purge(stream, { filter: `${stream}.b` }); assertEquals(pi.purged, 3); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 1); assertEquals(si.state.messages, 6); await cleanup(ns, nc); }); Deno.test("jsm - purge keep", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); const pi = await jsm.streams.purge(stream, { keep: 1 }); assertEquals(pi.purged, 8); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 9); assertEquals(si.state.messages, 1); await cleanup(ns, nc); }); Deno.test("jsm - purge filtered keep", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const stream = nuid.next(); await jsm.streams.add( { name: stream, subjects: [`${stream}.*`] }, ); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); nc.publish(`${stream}.a`); nc.publish(`${stream}.b`); nc.publish(`${stream}.c`); let pi = await jsm.streams.purge(stream, { keep: 1, filter: `${stream}.a` }); assertEquals(pi.purged, 2); pi = await jsm.streams.purge(stream, { keep: 1, filter: `${stream}.b` }); assertEquals(pi.purged, 2); pi = await jsm.streams.purge(stream, { keep: 1, filter: `${stream}.c` }); assertEquals(pi.purged, 2); const si = await jsm.streams.info(stream); assertEquals(si.state.first_seq, 7); assertEquals(si.state.messages, 3); await cleanup(ns, nc); }); Deno.test("jsm - purge seq and keep fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync(async () => { await jsm.streams.purge("a", { keep: 10, seq: 5 }); }); await cleanup(ns, nc); }); Deno.test("jsm - stream delete", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream, subj } = await initStream(nc); const jsm = await nc.jetstreamManager(); nc.publish(subj, Empty); await jsm.streams.delete(stream); await assertThrowsAsync( async () => { await jsm.streams.info(stream); }, Error, "stream not found", ); await cleanup(ns, nc); }); Deno.test("jsm - stream delete message", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream, subj } = await initStream(nc); const jsm = await nc.jetstreamManager(); nc.publish(subj, Empty); let si = await jsm.streams.info(stream); assertEquals(si.state.messages, 1); assertEquals(si.state.first_seq, 1); assertEquals(si.state.last_seq, 1); assert(await jsm.streams.deleteMessage(stream, 1)); si = await jsm.streams.info(stream); assertEquals(si.state.messages, 0); assertEquals(si.state.first_seq, 2); assertEquals(si.state.last_seq, 1); await cleanup(ns, nc); }); Deno.test("jsm - stream delete info", async () => { const { ns, nc } = await setup(jetstreamServerConf()); const { stream, subj } = await initStream(nc); const jsm = await nc.jetstreamManager(); const js = nc.jetstream(); await js.publish(subj); await js.publish(subj); await js.publish(subj); await jsm.streams.deleteMessage(stream, 2); const si = await jsm.streams.info(stream, { deleted_details: true }); assertEquals(si.state.num_deleted, 1); assertEquals(si.state.deleted, [2]); await cleanup(ns, nc); }); Deno.test("jsm - consumer info on empty stream name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.consumers.info("", ""); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - consumer info on empty consumer name fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.consumers.info("foo", ""); }, Error, ConsumerNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - consumer info on not found stream fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.consumers.info("foo", "dur"); }, Error, "stream not found", ); await cleanup(ns, nc); }); Deno.test("jsm - consumer info on not found consumer", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream } = await initStream(nc); const jsm = await nc.jetstreamManager(); await assertThrowsAsync( async () => { await jsm.consumers.info(stream, "dur"); }, Error, "consumer not found", ); await cleanup(ns, nc); }); Deno.test("jsm - consumer info", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream } = await initStream(nc); const jsm = await nc.jetstreamManager(); await jsm.consumers.add( stream, { durable_name: "dur", ack_policy: AckPolicy.Explicit }, ); const ci = await jsm.consumers.info(stream, "dur"); assertEquals(ci.name, "dur"); assertEquals(ci.config.durable_name, "dur"); assertEquals(ci.config.ack_policy, "explicit"); await cleanup(ns, nc); }); Deno.test("jsm - no consumer lister with empty stream fails", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); assertThrows( () => { jsm.consumers.list(""); }, Error, StreamNameRequired, ); await cleanup(ns, nc); }); Deno.test("jsm - no consumer lister with no consumers empty", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream } = await initStream(nc); const jsm = await nc.jetstreamManager(); const consumers = await jsm.consumers.list(stream).next(); assertEquals(consumers.length, 0); await cleanup(ns, nc); }); Deno.test("jsm - lister", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream } = await initStream(nc); const jsm = await nc.jetstreamManager(); await jsm.consumers.add( stream, { durable_name: "dur", ack_policy: AckPolicy.Explicit }, ); let consumers = await jsm.consumers.list(stream).next(); assertEquals(consumers.length, 1); assertEquals(consumers[0].config.durable_name, "dur"); await jsm.consumers.delete(stream, "dur"); consumers = await jsm.consumers.list(stream).next(); assertEquals(consumers.length, 0); await cleanup(ns, nc); }); Deno.test("jsm - update stream", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream } = await initStream(nc); const jsm = await nc.jetstreamManager(); let si = await jsm.streams.info(stream); assertEquals(si.config!.subjects!.length, 1); si.config!.subjects!.push("foo"); si = await jsm.streams.update(si.config); assertEquals(si.config!.subjects!.length, 2); await cleanup(ns, nc); }); Deno.test("jsm - get message", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream, subj } = await initStream(nc); const jc = JSONCodec(); const h = headers(); h.set("xxx", "a"); nc.publish(subj, jc.encode(1), { headers: h }); nc.publish(subj, jc.encode(2)); const jsm = await nc.jetstreamManager(); let sm = await jsm.streams.getMessage(stream, { seq: 1 }); assertEquals(sm.subject, subj); assertEquals(sm.seq, 1); assertEquals(jc.decode(sm.data), 1); sm = await jsm.streams.getMessage(stream, { seq: 2 }); assertEquals(sm.subject, subj); assertEquals(sm.seq, 2); assertEquals(jc.decode(sm.data), 2); const err = await assertThrowsAsync( async () => { await jsm.streams.getMessage(stream, { seq: 3 }); }, Error, ); if ( err.message !== "stream store eof" && err.message !== "no message found" ) { fail(`unexpected error message ${err.message}`); } await cleanup(ns, nc); }); Deno.test("jsm - get message payload", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const { stream, subj } = await initStream(nc); const js = nc.jetstream(); const sc = StringCodec(); await js.publish(subj, Empty, { msgID: "empty" }); await js.publish(subj, sc.encode(""), { msgID: "empty2" }); const jsm = await nc.jetstreamManager(); let sm = await jsm.streams.getMessage(stream, { seq: 1 }); assertEquals(sm.subject, subj); assertEquals(sm.seq, 1); assertEquals(sm.data, Empty); sm = await jsm.streams.getMessage(stream, { seq: 2 }); assertEquals(sm.subject, subj); assertEquals(sm.seq, 2); assertEquals(sm.data, Empty); assertEquals(sc.decode(sm.data), ""); await cleanup(ns, nc); }); Deno.test("jsm - advisories", async () => { const { ns, nc } = await setup(jetstreamServerConf({}, true)); const jsm = await nc.jetstreamManager(); const iter = jsm.advisories(); const streamAction = deferred(); (async () => { for await (const a of iter) { if (a.kind === AdvisoryKind.StreamAction) { streamAction.resolve(); } } })().then(); await initStream(nc); await streamAction; await cleanup(ns, nc); }); Deno.test("jsm - validate name", () => { type t = [string, boolean]; const tests: t[] = [ ["", false], [".", false], ["*", false], [">", false], ["hello.", false], ["hello.*", false], ["hello.>", false], ["one.two", false], ["one*two", false], ["one>two", false], ["stream", true], ]; tests.forEach((v, idx) => { try { validateName(`${idx}`, v[0]); if (!v[1]) { fail(`${v[0]} should have been rejected`); } } catch (_err) { if (v[1]) { fail(`${v[0]} should have been valid`); } } }); }); Deno.test("jsm - cross account streams", async () => { const { ns, nc } = await setup( jetstreamExportServerConf(), { user: "a", pass: "s3cret", }, ); const sawIPA = deferred(); nc.subscribe("IPA.>", { callback: () => { sawIPA.resolve(); }, max: 1, }); const jsm = await nc.jetstreamManager({ apiPrefix: "IPA" }); await sawIPA; // no streams let streams = await jsm.streams.list().next(); assertEquals(streams.length, 0); // add a stream const stream = nuid.next(); const subj = `${stream}.A`; await jsm.streams.add({ name: stream, subjects: [subj] }); // list the stream streams = await jsm.streams.list().next(); assertEquals(streams.length, 1); // cannot publish to the stream from the client account // publish from the js account const admin = await connect({ port: ns.port, user: "js", pass: "js" }); admin.publish(subj); admin.publish(subj); await admin.flush(); // info let si = await jsm.streams.info(stream); assertEquals(si.state.messages, 2); // get message const sm = await jsm.streams.getMessage(stream, { seq: 1 }); assertEquals(sm.seq, 1); // delete message let ok = await jsm.streams.deleteMessage(stream, 1); assertEquals(ok, true); si = await jsm.streams.info(stream); assertEquals(si.state.messages, 1); // purge const pr = await jsm.streams.purge(stream); assertEquals(pr.success, true); assertEquals(pr.purged, 1); si = await jsm.streams.info(stream); assertEquals(si.state.messages, 0); // update const config = streams[0].config; config.subjects!.push(`${stream}.B`); si = await jsm.streams.update(config); assertEquals(si.config.subjects!.length, 2); // find const sn = await jsm.streams.find(`${stream}.B`); assertEquals(sn, stream); // delete ok = await jsm.streams.delete(stream); assertEquals(ok, true); streams = await jsm.streams.list().next(); assertEquals(streams.length, 0); await cleanup(ns, nc, admin); }); Deno.test("jsm - cross account consumers", async () => { const { ns, nc } = await setup( jetstreamExportServerConf(), { user: "a", pass: "s3cret", }, ); const sawIPA = deferred(); nc.subscribe("IPA.>", { callback: () => { sawIPA.resolve(); }, max: 1, }); const jsm = await nc.jetstreamManager({ apiPrefix: "IPA" }); await sawIPA; // add a stream const stream = nuid.next(); const subj = `${stream}.A`; await jsm.streams.add({ name: stream, subjects: [subj] }); let consumers = await jsm.consumers.list(stream).next(); assertEquals(consumers.length, 0); await jsm.consumers.add(stream, { durable_name: "me", ack_policy: AckPolicy.Explicit, }); // cannot publish to the stream from the client account // publish from the js account const admin = await connect({ port: ns.port, user: "js", pass: "js" }); admin.publish(subj); admin.publish(subj); await admin.flush(); consumers = await jsm.consumers.list(stream).next(); assertEquals(consumers.length, 1); assertEquals(consumers[0].name, "me"); assertEquals(consumers[0].config.durable_name, "me"); assertEquals(consumers[0].num_pending, 2); const ci = await jsm.consumers.info(stream, "me"); assertEquals(ci.name, "me"); assertEquals(ci.config.durable_name, "me"); assertEquals(ci.num_pending, 2); const ok = await jsm.consumers.delete(stream, "me"); assertEquals(ok, true); await assertThrowsAsync( async () => { await jsm.consumers.info(stream, "me"); }, Error, "consumer not found", ); await cleanup(ns, nc, admin); });
the_stack
/// <reference types="node" /> import events = require('events'); import http = require('http'); import https = require('https'); import net = require('net'); import url = require('url'); export interface IStringified { toString: (...args: any[]) => string; } export interface IConfig { /** * The maximum allowed received frame size in bytes. * Single frame messages will also be limited to this maximum. * @default 1MiB */ maxReceivedFrameSize?: number | undefined; /** * The maximum allowed aggregate message size (for fragmented messages) in bytes * @default 8MiB */ maxReceivedMessageSize?: number | undefined; /** * Whether or not to fragment outgoing messages. If true, messages will be * automatically fragmented into chunks of up to `fragmentationThreshold` bytes. * @default true */ fragmentOutgoingMessages?: boolean | undefined; /** * The maximum size of a frame in bytes before it is automatically fragmented. * @default 16KiB */ fragmentationThreshold?: number | undefined; /** * If true, fragmented messages will be automatically assembled and the full * message will be emitted via a `message` event. If false, each frame will be * emitted on the `connection` object via a `frame` event and the application * will be responsible for aggregating multiple fragmented frames. Single-frame * messages will emit a `message` event in addition to the `frame` event. * @default true */ assembleFragments?: boolean | undefined; /** * The number of milliseconds to wait after sending a close frame for an * `acknowledgement` to come back before giving up and just closing the socket. * @default 5000 */ closeTimeout?: number | undefined; /** * The Nagle Algorithm makes more efficient use of network resources by introducing a * small delay before sending small packets so that multiple messages can be batched * together before going onto the wire. This however comes at the cost of latency. * @default true */ disableNagleAlgorithm?: boolean | undefined; } export interface IServerConfig extends IConfig { /** The http or https server instance(s) to attach to */ httpServer: http.Server | https.Server | Array<http.Server | https.Server>; /** * The maximum allowed received frame size in bytes. * Single frame messages will also be limited to this maximum. * @default 64KiB */ maxReceivedFrameSize?: number | undefined; /** * The maximum allowed aggregate message size (for fragmented messages) in bytes. * @default 1MiB */ maxReceivedMessageSize?: number | undefined; /** * If true, the server will automatically send a ping to all clients every * `keepaliveInterval` milliseconds. Each client has an independent `keepalive` * timer, which is reset when any data is received from that client. * @default true */ keepalive?: boolean | undefined; /** * The interval in milliseconds to send `keepalive` pings to connected clients. * @default 20000 */ keepaliveInterval?: number | undefined; /** * If true, the server will consider any connection that has not received any * data within the amount of time specified by `keepaliveGracePeriod` after a * `keepalive` ping has been sent. Ignored if `keepalive` is false. * @default true */ dropConnectionOnKeepaliveTimeout?: boolean | undefined; /** * The amount of time to wait after sending a `keepalive` ping before closing * the connection if the connected peer does not respond. Ignored if `keepalive` * or `dropConnectionOnKeepaliveTimeout` are false. The grace period timer is * reset when any data is received from the client. * @default 10000 */ keepaliveGracePeriod?: number | undefined; /** * Whether to use native TCP keep-alive instead of WebSockets ping * and pong packets. Native TCP keep-alive sends smaller packets * on the wire and so uses bandwidth more efficiently. This may * be more important when talking to mobile devices. * If this value is set to true, then these values will be ignored: * keepaliveGracePeriod * dropConnectionOnKeepaliveTimeout * @default false */ useNativeKeepalive?: boolean | undefined; /** * If this is true, websocket connections will be accepted regardless of the path * and protocol specified by the client. The protocol accepted will be the first * that was requested by the client. * @default false */ autoAcceptConnections?: boolean | undefined; /** * Whether or not the X-Forwarded-For header should be respected. * It's important to set this to 'true' when accepting connections * from untrusted clients, as a malicious client could spoof its * IP address by simply setting this header. It's meant to be added * by a trusted proxy or other intermediary within your own * infrastructure. * See: http://en.wikipedia.org/wiki/X-Forwarded-For * @default false */ ignoreXForwardedFor?: boolean | undefined; } export class server extends events.EventEmitter { config?: IServerConfig | undefined; connections: connection[]; pendingRequests: request[]; constructor(serverConfig?: IServerConfig); /** Send binary or UTF-8 message for each connection */ broadcast(data: Buffer | IStringified): void; /** Send binary message for each connection */ broadcastBytes(data: Buffer): void; /** Send UTF-8 message for each connection */ broadcastUTF(data: IStringified): void; /** Attach the `server` instance to a Node http.Server instance */ mount(serverConfig: IServerConfig): void; /** * Detach the `server` instance from the Node http.Server instance. * All existing connections are left alone and will not be affected, * but no new WebSocket connections will be accepted. */ unmount(): void; /** Close all open WebSocket connections */ closeAllConnections(): void; /** Close all open WebSocket connections and unmount the server */ shutDown(): void; handleUpgrade(request: http.IncomingMessage, socket: net.Socket): void; handleRequestAccepted(connection: connection): void; handleConnectionClose(connection: connection, closeReason: number, description: string): void; handleRequestResolved(request: request): void; // Events on(event: 'request', cb: (request: request) => void): this; on(event: 'connect', cb: (connection: connection) => void): this; on(event: 'close', cb: (connection: connection, reason: number, desc: string) => void): this; addListener(event: 'request', cb: (request: request) => void): this; addListener(event: 'connect', cb: (connection: connection) => void): this; addListener(event: 'close', cb: (connection: connection, reason: number, desc: string) => void): this; } export interface ICookie { name: string; value: string; path?: string | undefined; domain?: string | undefined; expires?: Date | undefined; maxage?: number | undefined; secure?: boolean | undefined; httponly?: boolean | undefined; } export interface IExtension { name: string; value: string; } export class request extends events.EventEmitter { /** A reference to the original Node HTTP request object */ httpRequest: http.IncomingMessage; /** This will include the port number if a non-standard port is used */ host: string; /** A string containing the path that was requested by the client */ resource: string; /** `Sec-WebSocket-Key` */ key: string; /** Parsed resource, including the query string parameters */ resourceURL: url.Url; /** * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken * from that header to facilitate WebSocket servers that live behind a reverse-proxy */ remoteAddress: string; remoteAddresses: string[]; /** * If the client is a web browser, origin will be a string containing the URL * of the page containing the script that opened the connection. * If the client is not a web browser, origin may be `null` or "*". */ origin: string; /** The version of the WebSocket protocol requested by the client */ webSocketVersion: number; /** An array containing a list of extensions requested by the client */ requestedExtensions: any[]; cookies: ICookie[]; socket: net.Socket; /** * List of strings that indicate the subprotocols the client would like to speak. * The server should select the best one that it can support from the list and * pass it to the `accept` function when accepting the connection. * Note that all the strings in the `requestedProtocols` array will have been * converted to lower case. */ requestedProtocols: string[]; protocolFullCaseMap: { [key: string]: string }; serverConfig: IServerConfig; _resolved: boolean; _socketIsClosing: boolean; constructor(socket: net.Socket, httpRequest: http.IncomingMessage, config: IServerConfig); /** * After inspecting the `request` properties, call this function on the * request object to accept the connection. If you don't have a particular subprotocol * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. * * @param [acceptedProtocol] case-insensitive value that was requested by the client */ accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: ICookie[]): connection; /** * Reject connection. * You may optionally pass in an HTTP Status code (such as 404) and a textual * description that will be sent to the client in the form of an * `X-WebSocket-Reject-Reason` header. * Optional extra http headers can be added via Object key/values on extraHeaders. */ reject(httpStatus?: number, reason?: string, extraHeaders?: object): void; // Events on(event: 'requestResolved' | 'requestRejected', cb: (request: this) => void): this; on(event: 'requestAccepted', cb: (connection: connection) => void): this; addListener(event: 'requestResolved' | 'requestRejected', cb: (request: this) => void): this; addListener(event: 'requestAccepted', cb: (connection: connection) => void): this; readHandshake(): void; parseExtensions(extensionString: string): string[]; parseCookies(str: string): ICookie[] | void; _handleSocketCloseBeforeAccept(): void; _removeSocketCloseListeners(): void; _verifyResolution(): void; } export interface IUtf8Message { type: 'utf8'; utf8Data: string; } export interface IBinaryMessage { type: 'binary'; binaryData: Buffer; } export type Message = IUtf8Message | IBinaryMessage; export interface IBufferList extends events.EventEmitter { encoding: string; length: number; write(buf: Buffer): boolean; end(buf: Buffer): void; push(): void; /** * For each buffer, perform some action. * If fn's result is a true value, cut out early. */ forEach(fn: (buf: Buffer) => boolean): void; /** Create a single buffer out of all the chunks */ join(start: number, end: number): Buffer; /** Join all the chunks to existing buffer */ joinInto(buf: Buffer, offset: number, start: number, end: number): Buffer; /** * Advance the buffer stream by `n` bytes. * If `n` the aggregate advance offset passes the end of the buffer list, * operations such as `take` will return empty strings until enough data is pushed. */ advance(n: number): IBufferList; /** * Take `n` bytes from the start of the buffers. * If there are less than `n` bytes in all the buffers or `n` is undefined, * returns the entire concatenated buffer string. */ take(n: number, encoding?: string): any; take(encoding?: string): any; toString(): string; // Events on(event: 'advance', cb: (n: number) => void): this; on(event: 'write', cb: (buf: Buffer) => void): this; addListener(event: 'advance', cb: (n: number) => void): this; addListener(event: 'write', cb: (buf: Buffer) => void): this; } export class connection extends events.EventEmitter { static CLOSE_REASON_NORMAL: number; static CLOSE_REASON_GOING_AWAY: number; static CLOSE_REASON_PROTOCOL_ERROR: number; static CLOSE_REASON_UNPROCESSABLE_INPUT: number; static CLOSE_REASON_RESERVED: number; static CLOSE_REASON_NOT_PROVIDED: number; static CLOSE_REASON_ABNORMAL: number; static CLOSE_REASON_INVALID_DATA: number; static CLOSE_REASON_POLICY_VIOLATION: number; static CLOSE_REASON_MESSAGE_TOO_BIG: number; static CLOSE_REASON_EXTENSION_REQUIRED: number; static CLOSE_DESCRIPTIONS: {[code: number]: string}; /** * After the connection is closed, contains a textual description of the reason for * the connection closure, or `null` if the connection is still open. */ closeDescription: string; /** * After the connection is closed, contains the numeric close reason status code, * or `-1` if the connection is still open. */ closeReasonCode: number; /** * The subprotocol that was chosen to be spoken on this connection. This field * will have been converted to lower case. */ protocol: string; config: IConfig; socket: net.Socket; maskOutgoingPackets: boolean; maskBytes: Buffer; frameHeader: Buffer; bufferList: IBufferList; currentFrame: frame; fragmentationSize: number; frameQueue: frame[]; state: string; waitingForCloseResponse: boolean; receivedEnd: boolean; closeTimeout: number; assembleFragments: number; maxReceivedMessageSize: number; outputBufferFull: boolean; inputPaused: boolean; bytesWaitingToFlush: number; socketHadError: boolean; /** An array of extensions that were negotiated for this connection */ extensions: IExtension[]; /** * The IP address of the remote peer as a string. In the case of a server, * the `X-Forwarded-For` header will be respected and preferred for the purposes * of populating this field. If you need to get to the actual remote IP address, * `socket.remoteAddress` will provide it. */ remoteAddress: string; /** The version of the WebSocket protocol requested by the client */ webSocketVersion: number; /** Whether or not the connection is still connected. Read-only */ connected: boolean; _pingListenerCount: number; constructor(socket: net.Socket, extensions: IExtension[], protocol: string, maskOutgoingPackets: boolean, config: IConfig); /** * Close the connection. A close frame will be sent to the remote peer indicating * that we wish to close the connection, and we will then wait for up to * `config.closeTimeout` milliseconds for an acknowledgment from the remote peer * before terminating the underlying socket connection. */ close(reasonCode?: number, description?: string): void; /** * Send a close frame to the remote peer and immediately close the socket without * waiting for a response. This should generally be used only in error conditions. */ drop(reasonCode?: number, description?: string, skipCloseFrame?: boolean): void; /** * Immediately sends the specified string as a UTF-8 WebSocket message to the remote * peer. If `config.fragmentOutgoingMessages` is true the message may be sent as * multiple fragments if it exceeds `config.fragmentationThreshold` bytes. */ sendUTF(data: IStringified, cb?: (err?: Error) => void): void; /** * Immediately sends the specified Node Buffer object as a Binary WebSocket message * to the remote peer. If config.fragmentOutgoingMessages is true the message may be * sent as multiple fragments if it exceeds config.fragmentationThreshold bytes. */ sendBytes(buffer: Buffer, cb?: (err?: Error) => void): void; /** Auto-detect the data type and send UTF-8 or Binary message */ send(data: Buffer | IStringified, cb?: (err?: Error) => void): void; /** Sends a ping frame. Ping frames must not exceed 125 bytes in length. */ ping(data: Buffer | IStringified): void; /** * Sends a pong frame. Pong frames may be sent unsolicited and such pong frames will * trigger no action on the receiving peer. Pong frames sent in response to a ping * frame must mirror the payload data of the ping frame exactly. * The `connection` object handles this internally for you, so there should * be no need to use this method to respond to pings. * Pong frames must not exceed 125 bytes in length. */ pong(buffer: Buffer): void; /** * Serializes a `frame` object into binary data and immediately sends it to * the remote peer. This is an advanced function, requiring you to manually compose * your own `frame`. You should probably use sendUTF or sendBytes instead. */ sendFrame(frame: frame, cb?: (err?: Error) => void): void; /** Set or reset the `keepalive` timer when data is received */ setKeepaliveTimer(): void; clearKeepaliveTimer(): void; handleKeepaliveTimer(): void; setGracePeriodTimer(): void; clearGracePeriodTimer(): void; handleGracePeriodTimer(): void; handleSocketData(data: Buffer): void; processReceivedData(): void; handleSocketError(error: Error): void; handleSocketEnd(): void; handleSocketClose(hadError: boolean): void; handleSocketDrain(): void; handleSocketPause(): void; handleSocketResume(): void; pause(): void; resume(): void; setCloseTimer(): void; clearCloseTimer(): void; handleCloseTimer(): void; processFrame(frame: frame): void; fragmentAndSend(frame: frame, cb?: (err: Error) => void): void; sendCloseFrame(reasonCode?: number, reasonText?: string, cb?: (err?: Error) => void): void; _addSocketEventListeners(): void; // Events on(event: 'message', cb: (data: Message) => void): this; on(event: 'frame', cb: (frame: frame) => void): this; on(event: 'close', cb: (code: number, desc: string) => void): this; on(event: 'error', cb: (err: Error) => void): this; on(event: 'drain' | 'pause' | 'resume', cb: () => void): this; on(event: 'ping', cb: (cancel: () => void, binaryPayload: Buffer) => void): this; on(event: 'pong', cb: (binaryPayload: Buffer) => void): this; addListener(event: 'message', cb: (data: Message) => void): this; addListener(event: 'frame', cb: (frame: frame) => void): this; addListener(event: 'close', cb: (code: number, desc: string) => void): this; addListener(event: 'error', cb: (err: Error) => void): this; addListener(event: 'drain' | 'pause' | 'resume', cb: () => void): this; addListener(event: 'ping', cb: (cancel: () => void, binaryPayload: Buffer) => void): this; addListener(event: 'pong', cb: (binaryPayload: Buffer) => void): this; } export class frame { /** Whether or not this is last frame in a fragmentation sequence */ fin: boolean; /** * Represents the RSV1 field in the framing. Setting this to true will result in * a Protocol Error on the receiving peer. */ rsv1: boolean; /** * Represents the RSV1 field in the framing. Setting this to true will result in * a Protocol Error on the receiving peer. */ rsv2: boolean; /** * Represents the RSV1 field in the framing. Setting this to true will result in * a Protocol Error on the receiving peer. */ rsv3: boolean; /** * Whether or not this frame is (or should be) masked. For outgoing frames, when * connected as a client, this flag is automatically forced to true by `connection`. * Outgoing frames sent from the server-side of a connection are not masked. */ mask: number; /** * Identifies which kind of frame this is. * * Hex - Dec - Description * 0x00 - 0 - Continuation * 0x01 - 1 - Text Frame * 0x02 - 2 - Binary Frame * 0x08 - 8 - Close Frame * 0x09 - 9 - Ping Frame * 0x0A - 10 - Pong Frame */ opcode: number; /** * Identifies the length of the payload data on a received frame. * When sending a frame, will be automatically calculated from `binaryPayload` object. */ length: number; /** * The binary payload data. * Even text frames are sent with a Buffer providing the binary payload data. */ binaryPayload: Buffer; maskBytes: Buffer; frameHeader: Buffer; config: IConfig; maxReceivedFrameSize: number; protocolError: boolean; dropReason: string; frameTooLarge: boolean; invalidCloseFrameLength: boolean; parseState: number; closeStatus: number; addData(bufferList: IBufferList): boolean; throwAwayPayload(bufferList: IBufferList): boolean; toBuffer(nullMask: boolean): Buffer; toString(): string; } export interface IClientConfig extends IConfig { /** * Which version of the WebSocket protocol to use when making the connection. * Currently supported values are 8 and 13. This option will be removed once the * protocol is finalized by the IETF It is only available to ease the transition * through the intermediate draft protocol versions. The only thing this affects * the name of the Origin header. * @default 13 */ webSocketVersion?: number | undefined; /** * Options to pass to `https.request` if connecting via TLS. * @see https://nodejs.org/api/https.html#https_https_request_options_callback */ tlsOptions?: https.RequestOptions | undefined; } export class client extends events.EventEmitter { constructor(ClientConfig?: IClientConfig); /** * Establish a connection. The remote server will select the best subprotocol that * it supports and send that back when establishing the connection. * * @param requestUrl should be a standard websocket url * @param [requestedProtocols] list of subprotocols supported by the client. * The remote server will select the best subprotocol that it supports and send that back when establishing the connection. * @param [origin] Used in user-agent scenarios to identify the page containing * any scripting content that caused the connection to be requested. * @param [headers] additional arbitrary HTTP request headers to send along with the request. * This may be used to pass things like access tokens, etc. so that the server can verify authentication/authorization * before deciding to accept and open the full WebSocket connection. * @param [extraRequestOptions] additional configuration options to be passed to `http.request` or `https.request`. * This can be used to pass a custom `agent` to enable `client` usage from behind an HTTP or HTTPS proxy server * using {@link https://github.com/koichik/node-tunnel|koichik/node-tunnel} or similar. * @example client.connect('ws://www.mygreatapp.com:1234/websocketapp/') */ connect(requestUrl: url.Url | string, requestedProtocols?: string | string[], origin?: string, headers?: http.OutgoingHttpHeaders, extraRequestOptions?: http.RequestOptions): void; /** * Will cancel an in-progress connection request before either the `connect` event or the `connectFailed` event has been emitted. * If the `connect` or `connectFailed` event has already been emitted, calling `abort()` will do nothing. */ abort(): void; // Events on(event: 'connect', cb: (connection: connection) => void): this; on(event: 'connectFailed', cb: (err: Error) => void): this; on(event: 'httpResponse', cb: (response: http.IncomingMessage, client: client) => void): this; addListener(event: 'connect', cb: (connection: connection) => void): this; addListener(event: 'connectFailed', cb: (err: Error) => void): this; addListener(event: 'httpResponse', cb: (response: http.IncomingMessage, client: client) => void): this; } export interface IRouterRequest extends events.EventEmitter { webSocketRequest: request; protocol: string | null; /** * If the client is a web browser, origin will be a string containing the URL * of the page containing the script that opened the connection. * If the client is not a web browser, origin may be `null` or "*". */ origin: string; /** A string containing the path that was requested by the client */ resource: string; /** Parsed resource, including the query string parameters */ resourceURL: url.Url; /** A reference to the original Node HTTP request object */ httpRequest: http.IncomingMessage; /** * Client's IP. If an `X-Forwarded-For` header is present, the value will be taken * from that header to facilitate WebSocket servers that live behind a reverse-proxy */ remoteAddress: string; /** The version of the WebSocket protocol requested by the client */ webSocketVersion: number; /** An array containing a list of extensions requested by the client */ requestedExtensions: any[]; cookies: ICookie[]; /** * After inspecting the `request` properties, call this function on the * request object to accept the connection. If you don't have a particular subprotocol * you wish to speak, you may pass `null` for the `acceptedProtocol` parameter. * * @param [acceptedProtocol] case-insensitive value that was requested by the client */ accept(acceptedProtocol?: string, allowedOrigin?: string, cookies?: ICookie[]): connection; /** * Reject connection. * You may optionally pass in an HTTP Status code (such as 404) and a textual * description that will be sent to the client in the form of an * `X-WebSocket-Reject-Reason` header. */ reject(httpStatus?: number, reason?: string): void; // Events on(event: 'requestAccepted', cb: (connection: connection) => void): this; on(event: 'requestRejected', cb: (request: this) => void): this; addListener(event: 'requestAccepted', cb: (connection: connection) => void): this; addListener(event: 'requestRejected', cb: (request: this) => void): this; } export interface IRouterConfig { /* * The WebSocketServer instance to attach to. */ server: server; } export interface IRouterHandler { path: string; pathString: string; protocol: string; callback: (request: IRouterRequest) => void; } export class router extends events.EventEmitter { handlers: IRouterHandler[]; constructor(config?: IRouterConfig); /** Attach to WebSocket server */ attachServer(server: server): void; /** Detach from WebSocket server */ detachServer(): void; mount(path: string | RegExp, protocol: string | null, callback: (request: IRouterRequest) => void): void; unmount(path: string | RegExp, protocol?: string): void; findHandlerIndex(pathString: string, protocol: string): number; pathToRegExp(path: string): RegExp; pathToRegEx(path: RegExp): RegExp; handleRequest(request: request): void; } export interface ICloseEvent { code: number; reason: string; wasClean: boolean; } export interface IMessageEvent { data: string | Buffer | ArrayBuffer; } export class w3cwebsocket { static CONNECTING: number; static OPEN: number; static CLOSING: number; static CLOSED: number; _url: string; _readyState: number; _protocol?: string | undefined; _extensions: IExtension[]; _bufferedAmount: number; _binaryType: 'arraybuffer'; _connection?: connection | undefined; _client: client; url: string; readyState: number; protocol?: string | undefined; extensions: IExtension[]; bufferedAmount: number; binaryType: 'arraybuffer'; CONNECTING: number; OPEN: number; CLOSING: number; CLOSED: number; onopen: () => void; onerror: (error: Error) => void; onclose: (event: ICloseEvent) => void; onmessage: (message: IMessageEvent) => void; constructor( url: string, protocols?: string | string[], origin?: string, headers?: http.OutgoingHttpHeaders, requestOptions?: object, IClientConfig?: IClientConfig, ); send(data: ArrayBufferView | ArrayBuffer | Buffer | IStringified): void; close(code?: number, reason?: string): void; } export const deprecation: { disableWarnings: boolean; deprecationWarningMap: {[name: string]: string}; warn(deprecationName: string): void; }; export const version: string;
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { class MailboxTrackingFolderApi { /** * DynamicsCrm.DevKit MailboxTrackingFolderApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the entry was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Folder Id for a folder in Exchange */ ExchangeFolderId: DevKit.WebApi.StringValue; /** Exchange Folder Name */ ExchangeFolderName: DevKit.WebApi.StringValue; /** Information to indicate whether the folder has been on boarded for auto tracking */ FolderOnboardingStatus: DevKit.WebApi.IntegerValue; /** Mailbox id associated with this record. */ MailboxId: DevKit.WebApi.LookupValue; MailboxTrackingFolderId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the entry was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the organization associated with the record. */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the folder mapping. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns the folder mapping. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_account: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appelement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_applicationuser: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appnotification: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_appusersetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_asyncoperation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bot: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_botcomponent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_catalog: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_catalogassignment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_connectionreference: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_connector: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contact: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_customapi: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_datalakefolder: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_devkit_bpfaccount: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_featurecontrolsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_flowmachine: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_flowsession: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_managedidentity: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_organizationsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_package: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_pdfsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_pluginpackage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_processstageparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_serviceplan: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_serviceplanmapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_settingdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_territory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_workflowbinary: DevKit.WebApi.LookupValue; /** Version number of the mailbox tracking folder. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace MailboxTrackingFolder { enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import cn from 'classnames' import PropTypes from 'prop-types' import React, { useImperativeHandle, useMemo, useRef, useState } from 'react' import { useUncontrolledProp } from 'uncontrollable' import useTimeout from '@restart/hooks/useTimeout' import AddToListOption, { CREATE_OPTION } from './AddToListOption' import DropdownListInput, { DropdownInputHandle, RenderValueProp, } from './DropdownListInput' import { caretDown } from './Icon' import List, { ListHandle } from './List' import { FocusListContext, useFocusList } from './FocusListContext' import BasePopup from './Popup' import Widget from './Widget' import WidgetPicker from './WidgetPicker' import { useMessagesWithDefaults } from './messages' import { BaseListboxInputProps, Filterable, PopupWidgetProps, Searchable, WidgetHTMLProps, WidgetProps, } from './shared' import { DataItem, WidgetHandle } from './types' import { useActiveDescendant } from './A11y' import { useFilteredData, presets } from './Filter' import * as CustomPropTypes from './PropTypes' import canShowCreate from './canShowCreate' import { useAccessors } from './Accessors' import useAutoFocus from './useAutoFocus' import useDropdownToggle from './useDropdownToggle' import useFocusManager from './useFocusManager' import { notify, useFirstFocusedRender, useInstanceId } from './WidgetHelpers' import PickerCaret from './PickerCaret' const propTypes = { value: PropTypes.any, /** * @type {function ( * dataItems: ?any, * metadata: { * lastValue: ?any, * searchTerm: ?string * originalEvent: SyntheticEvent, * } * ): void} */ onChange: PropTypes.func, open: PropTypes.bool, onToggle: PropTypes.func, data: PropTypes.array, dataKey: CustomPropTypes.accessor, textField: CustomPropTypes.accessor, allowCreate: PropTypes.oneOf([true, false, 'onFilter']), /** * A React render prop for customizing the rendering of the DropdownList * value */ renderValue: PropTypes.func, renderListItem: PropTypes.func, listComponent: CustomPropTypes.elementType, optionComponent: CustomPropTypes.elementType, renderPopup: PropTypes.func, renderListGroup: PropTypes.func, groupBy: CustomPropTypes.accessor, /** * * @type {(dataItem: ?any, metadata: { originalEvent: SyntheticEvent }) => void} */ onSelect: PropTypes.func, onCreate: PropTypes.func, /** * @type function(searchTerm: string, metadata: { action, lastSearchTerm, originalEvent? }) */ onSearch: PropTypes.func, searchTerm: PropTypes.string, busy: PropTypes.bool, /** Specify the element used to render the select (down arrow) icon. */ selectIcon: PropTypes.node, /** Specify the element used to render the busy indicator */ busySpinner: PropTypes.node, placeholder: PropTypes.string, dropUp: PropTypes.bool, popupTransition: CustomPropTypes.elementType, disabled: CustomPropTypes.disabled.acceptsArray, readOnly: CustomPropTypes.disabled, /** Adds a css class to the input container element. */ containerClassName: PropTypes.string, inputProps: PropTypes.object, listProps: PropTypes.object, messages: PropTypes.shape({ open: PropTypes.string, emptyList: CustomPropTypes.message, emptyFilter: CustomPropTypes.message, createOption: CustomPropTypes.message, }), } function useSearchWordBuilder(delay: number) { const timeout = useTimeout() const wordRef = useRef('') function search(character: string, cb: (word: string) => void) { let word = (wordRef.current + character).toLowerCase() if (!character) return wordRef.current = word timeout.set(() => { wordRef.current = '' cb(word) }, delay) } return search } export type DropdownHandle = WidgetHandle export interface DropdownProps<TDataItem> extends WidgetProps, WidgetHTMLProps, PopupWidgetProps, Searchable, Filterable<TDataItem>, BaseListboxInputProps<TDataItem> { name?: string autoFocus?: boolean autoComplete?: 'on' | 'off' onCreate?: (searchTerm: string) => void renderValue?: RenderValueProp<TDataItem> } declare interface DropdownList { <TDataItem = DataItem>( props: DropdownProps<TDataItem> & React.RefAttributes<DropdownHandle>, ): React.ReactElement | null displayName?: string propTypes?: any } /** * A `<select>` replacement for single value lists. * @public */ const DropdownListImpl: DropdownList = React.forwardRef(function DropdownList< TDataItem >( { id, autoFocus, textField, dataKey, value, defaultValue, onChange, open, defaultOpen = false, onToggle, searchTerm, defaultSearchTerm = '', onSearch, filter = true, allowCreate = false, delay = 500, focusFirstItem, className, containerClassName, placeholder, busy, disabled, readOnly, selectIcon = caretDown, busySpinner, dropUp, tabIndex, popupTransition, name, autoComplete, onSelect, onCreate, onKeyPress, onKeyDown, onClick, inputProps, listProps, renderListItem, renderListGroup, optionComponent, renderValue, groupBy, onBlur, onFocus, listComponent: ListComponent = List, popupComponent: Popup = BasePopup, data: rawData = [], messages: userMessages, ...elementProps }: DropdownProps<TDataItem>, outerRef: React.RefObject<DropdownHandle>, ) { const [currentValue, handleChange] = useUncontrolledProp( value, defaultValue, onChange as any, ) const [currentOpen, handleOpen] = useUncontrolledProp( open, defaultOpen, onToggle, ) const [currentSearch, handleSearch] = useUncontrolledProp( searchTerm, defaultSearchTerm, onSearch, ) const ref = useRef<HTMLDivElement>(null) const filterRef = useRef<DropdownInputHandle>(null) const listRef = useRef<ListHandle>(null) const inputId = useInstanceId(id, '_input') const listId = useInstanceId(id, '_listbox') const activeId = useInstanceId(id, '_listbox_active_option') const accessors = useAccessors(textField, dataKey) const messages = useMessagesWithDefaults(userMessages) useAutoFocus(!!autoFocus, ref) const toggle = useDropdownToggle(currentOpen, handleOpen!) const isDisabled = disabled === true // const disabledItems = toItemArray(disabled) const isReadOnly = !!readOnly const [focusEvents, focused] = useFocusManager( ref, { disabled: isDisabled, onBlur, onFocus }, { didHandle(focused) { if (focused) { if (filter) focus() return } toggle.close() clearSearch() }, }, ) const data = useFilteredData( rawData, currentOpen ? filter : false, currentSearch, accessors.text, ) const selectedItem = useMemo( () => data[accessors.indexOf(data, currentValue)], [data, currentValue, accessors], ) const list = useFocusList({ activeId, scope: ref, focusFirstItem, anchorItem: currentOpen ? selectedItem : undefined, }) const [autofilling, setAutofilling] = useState(false) const nextSearchChar = useSearchWordBuilder(delay) const focusedItem = list.getFocused() useActiveDescendant(ref, activeId, focusedItem && currentOpen, [focusedItem]) const showCreateOption = canShowCreate(allowCreate, { searchTerm: currentSearch, data, accessors, }) const handleCreate = (event?: React.SyntheticEvent) => { notify(onCreate, [currentSearch!]) clearSearch(event) toggle.close() focus() } const handleSelect = ( dataItem: TDataItem, originalEvent?: React.SyntheticEvent, ) => { if (readOnly || isDisabled) return if (dataItem === undefined) return originalEvent?.preventDefault() if (dataItem === CREATE_OPTION) { handleCreate(originalEvent) return } notify(onSelect, [dataItem, { originalEvent }]) change(dataItem, originalEvent, true) toggle.close() focus() } const handleClick = (e: React.MouseEvent<HTMLDivElement>) => { if (readOnly || isDisabled) return // prevents double clicks when in a <label> e.preventDefault() focus() toggle() notify(onClick, [e]) } const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => { if (readOnly || isDisabled) return let { key, altKey, ctrlKey, shiftKey } = e notify(onKeyDown, [e]) let closeWithFocus = () => { clearSearch() toggle.close() if (currentOpen) setTimeout(focus) } if (e.defaultPrevented) return if (key === 'End' && currentOpen && !shiftKey) { e.preventDefault() list.focus(list.last()) } else if (key === 'Home' && currentOpen && !shiftKey) { e.preventDefault() list.focus(list.first()) } else if (key === 'Escape' && (currentOpen || currentSearch)) { e.preventDefault() closeWithFocus() } else if (key === 'Enter' && currentOpen && ctrlKey && showCreateOption) { e.preventDefault() handleCreate(e) } else if ((key === 'Enter' || (key === ' ' && !filter)) && currentOpen) { e.preventDefault() if (list.hasFocused()) handleSelect(list.getFocused()!, e) } else if (key === 'ArrowDown') { e.preventDefault() if (!currentOpen) { toggle.open() return } list.focus(list.next()) } else if (key === 'ArrowUp') { e.preventDefault() if (altKey) return closeWithFocus() list.focus(list.prev()) } } const handleKeyPress = (e: React.KeyboardEvent<HTMLDivElement>) => { if (readOnly || isDisabled) return notify(onKeyPress, [e]) if (e.defaultPrevented || filter) return nextSearchChar(String.fromCharCode(e.which), (word) => { if (!currentOpen) return let isValid = (item: TDataItem) => presets.startsWith( accessors.text(item).toLowerCase(), word.toLowerCase(), ) const [items, focusedItem] = list.get() const len = items.length const startIdx = items.indexOf(focusedItem!) + 1 const offset = startIdx >= len ? 0 : startIdx let idx = 0 let pointer = offset while (idx < len) { pointer = (idx + offset) % len let item = items[pointer] if (isValid(list.toDataItem(item)!)) break idx++ } if (idx === len) return list.focus(items[pointer]) }) } const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => { // hitting space to open if (!currentOpen && !e.target.value.trim()) { e.preventDefault() } else { search(e.target.value, e, 'input') } toggle.open() } const handleAutofillChange = (e: React.ChangeEvent<HTMLInputElement>) => { let filledValue = e.target.value.toLowerCase() if (filledValue === '') return void change(null) for (const item of rawData) { if ( String(accessors.value(item)).toLowerCase() === filledValue || accessors.text(item).toLowerCase() === filledValue ) { change(item, e) break } } } function change( nextValue: unknown, originalEvent?: React.SyntheticEvent, selected = false, ) { if (!accessors.matches(nextValue, currentValue)) { notify(handleChange, [ nextValue, { originalEvent, source: selected ? 'listbox' : 'input', lastValue: currentValue, searchTerm: currentSearch, }, ]) clearSearch(originalEvent) toggle.close() } } function focus() { if (filter) filterRef.current!.focus() else ref.current!.focus() } function clearSearch(originalEvent?: React.SyntheticEvent) { search('', originalEvent, 'clear') } function search( nextSearchTerm: string, originalEvent?: React.SyntheticEvent, action: 'input' | 'clear' = 'input', ) { if (currentSearch !== nextSearchTerm) handleSearch(nextSearchTerm, { action, originalEvent, lastSearchTerm: currentSearch, }) } /** * Render */ useImperativeHandle(outerRef, () => ({ focus, })) let valueItem = accessors.findOrSelf(data, currentValue) let shouldRenderPopup = useFirstFocusedRender(focused, currentOpen!) const widgetProps: React.HTMLProps<HTMLDivElement> = { ...elementProps, role: 'combobox', id: inputId, //tab index when there is no filter input to take focus tabIndex: filter ? -1 : tabIndex || 0, // FIXME: only when item exists 'aria-owns': listId, 'aria-expanded': !!currentOpen, 'aria-haspopup': true, 'aria-busy': !!busy, 'aria-live': currentOpen ? 'polite' : undefined, 'aria-autocomplete': 'list', 'aria-disabled': isDisabled, 'aria-readonly': isReadOnly, } return ( <FocusListContext.Provider value={list.context}> <Widget {...widgetProps} open={!!currentOpen} dropUp={!!dropUp} focused={!!focused} disabled={isDisabled} readOnly={isReadOnly} autofilling={autofilling} {...focusEvents} onKeyDown={handleKeyDown} onKeyPress={handleKeyPress} className={cn(className, 'rw-dropdown-list')} ref={ref} > <WidgetPicker onClick={handleClick} tabIndex={filter ? -1 : 0} className={cn(containerClassName, 'rw-widget-input')} > <DropdownListInput {...inputProps} value={valueItem} dataKeyAccessor={accessors.value} textAccessor={accessors.text} name={name} readOnly={readOnly} disabled={isDisabled} allowSearch={!!filter} searchTerm={currentSearch} ref={filterRef} autoComplete={autoComplete} onSearch={handleInputChange} onAutofill={setAutofilling} onAutofillChange={handleAutofillChange} placeholder={placeholder} renderValue={renderValue} /> <PickerCaret visible busy={busy} icon={selectIcon} spinner={busySpinner} /> </WidgetPicker> {shouldRenderPopup && ( <Popup dropUp={dropUp} open={currentOpen} transition={popupTransition} onEntered={focus} onEntering={() => listRef.current!.scrollIntoView()} > <ListComponent {...listProps} id={listId} data={data} tabIndex={-1} disabled={disabled} groupBy={groupBy} searchTerm={currentSearch} accessors={accessors} renderItem={renderListItem} renderGroup={renderListGroup} optionComponent={optionComponent} value={selectedItem} onChange={(d, meta) => handleSelect(d as TDataItem, meta.originalEvent!) } aria-live={currentOpen ? 'polite' : undefined} aria-labelledby={inputId} aria-hidden={!currentOpen} ref={listRef} messages={{ emptyList: rawData.length ? messages.emptyFilter : messages.emptyList, }} /> {showCreateOption && ( <AddToListOption onSelect={handleCreate}> {messages.createOption(currentValue, currentSearch || '')} </AddToListOption> )} </Popup> )} </Widget> </FocusListContext.Provider> ) }) DropdownListImpl.displayName = 'DropdownList' DropdownListImpl.propTypes = propTypes export default DropdownListImpl
the_stack
import { resolve } from 'path'; import hashString = require('string-hash'); import { NodePath } from '@babel/core'; import * as t from '@babel/types'; import { requireResolve, regNodeModules } from '../../help'; const cwd = process.cwd(); export type ChildrenElements = ( | t.JSXElement | t.JSXFragment | t.JSXExpressionContainer | t.JSXSpreadChild | t.JSXText )[]; const check = (nodes: ChildrenElements, routes: any) => { nodes.forEach((item) => { if (t.isJSXElement(item) && t.isJSXIdentifier(item.openingElement.name)) { if (item.openingElement.name.name !== 'Route') { throw new Error('RouterSwitch内的组件必须都是Route'); } else { let component = false; let _path = false; let _redirect = false; let result = 0; const props: any = { __award__spread__: [] }; item.openingElement.attributes.forEach((attr) => { if (t.isJSXAttribute(attr)) { if (t.isJSXIdentifier(attr.name)) { if (attr.name.name === '__award__spread__') { let value: any = attr.value; if (t.isJSXExpressionContainer(attr.value)) { value = attr.value.expression; } if (attr.value === null) { value = t.booleanLiteral(true); } props.__award__spread__.push({ type: 1, value }); } else { props[attr.name.name] = attr.value; if (t.isJSXExpressionContainer(attr.value)) { props[attr.name.name] = attr.value.expression; } if (attr.value === null) { props[attr.name.name] = t.booleanLiteral(true); } if (attr.name.name === 'component' && !component) { component = true; result = result + 5; } if (attr.name.name === 'path' && !_path) { _path = true; result = result + 1; } if (attr.name.name === 'redirect' && !_redirect) { _redirect = true; result = result + 3; } } } } if (t.isJSXSpreadAttribute(attr)) { props.__award__spread__.push({ type: 2, value: attr.argument }); } }); /** * path redirect component * 1 3 5 * path、redirect 1+3 = 4 * path、component 1+5 = 6 * component 5 * redirect 3 * path、redirect、component 1+3+5 = 9 */ if ([3, 4, 5, 6, 9].indexOf(result) === -1) { throw new Error( `Route组件接收的props【"path"、"component"、"redirect"】有如下组合 且必须设置props 1. <Route path="" redirect="" /> 2. <Route path="" component={} /> 3. <Route component={} /> 4. <Route redirect="" /> 5. <Route path="" component={} redirect="">` ); } if (item.children.length) { const childrens: any = []; check(item.children, childrens); const _childrenRoutes: any = []; childrens.forEach((children: any) => { const obj = []; for (const key in children) { if (Object.prototype.hasOwnProperty.call(children, key)) { if (key === '__award__spread__') { (children[key] as Array<any>).forEach((spread) => { if (spread.type === 1) { obj.push(t.objectProperty(t.identifier(key), spread.value)); } if (spread.type === 2) { obj.push(t.spreadElement(spread.value)); } }); } else { obj.push(t.objectProperty(t.identifier(key), children[key])); } } } _childrenRoutes.push(t.objectExpression(obj)); }); props.routes = t.arrayExpression(_childrenRoutes); } routes.push(props); } } }); }; const splitting = (childrens: ChildrenElements, state: any, tpl: any) => { const reference = state?.file?.opts.filename; const isServer = state?.opts?.isServer; const ts = state?.opts?.ts; const subprocess = state?.opts?.subprocess; if (childrens.length) { childrens.forEach((item) => { if (t.isJSXElement(item) && t.isJSXIdentifier(item.openingElement.name)) { if (item.openingElement.name.name === 'Route') { const attrs = item.openingElement.attributes; let sync = false; attrs.forEach((_item) => { if (t.isJSXAttribute(_item) && t.isJSXIdentifier(_item.name)) { if (_item.name.name === 'sync') { sync = true; } } }); attrs.forEach((_item) => { if (t.isJSXAttribute(_item) && t.isJSXIdentifier(_item.name)) { if (_item.name.name === 'component' && t.isJSXExpressionContainer(_item.value)) { if (t.isIdentifier(_item.value.expression)) { // 组件引用是变量 const name = _item.value.expression.name; if (state.import[name]) { try { const _path_ = state.import[name]; const source = _path_.node.source.value; const mod = requireResolve(source, resolve(reference)); if (!mod || !mod.src) { throw new Error(`Path '${source}' could not be found for '${reference}'`); } // 服务端 if (isServer && !sync) { item.openingElement.attributes.push( t.jsxAttribute( t.jsxIdentifier('__award__file__'), t.stringLiteral(String(hashString(mod.src.replace(cwd, '')))) ) ); } if (isServer && ts && !state.hasImport[name]) { state.hasImport[name] = true; state.path.node.body.push( tpl(`/**/const NAME = require(SOURCE).default`)({ NAME: t.identifier(name), SOURCE: t.stringLiteral(source) }) ); } // 客户端代码,且非同步 if (!isServer && !sync && !state.hasImport[name]) { state.hasImport[name] = true; global.routeFileNames.push(mod.src.replace(cwd, '')); _path_.replaceWith( tpl( `const NAME = (cb)=>{ return IMPORT(SOURCE).then( async (component) => { // 提前加载当前bundle里面的异步引用 const Loadable = require('react-loadable'); await Loadable.preloadReady(); cb(component); }).catch(err=>{ throw err }) }` )({ NAME: t.identifier(name), SOURCE: t.stringLiteral(source), IMPORT: t.import() }) ); } } catch (error) {} } else { // 不是import引入,说明是当前js引用的变量 // 标记props同步 item.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier('sync'))); } } else { // 组件引用, FunctionExpression, ArrowFunctionExpression if (t.isFunctionExpression || t.isArrowFunctionExpression) { // 标记props同步 item.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier('sync'))); } } } } }); if (subprocess) { process.exit(0); } if (item.children.length) { splitting(item.children, state, tpl); } } } }); } }; // https://github.com/jamiebuilds/babel-handbook/blob/master/translations/zh-Hans/plugin-handbook.md#-%E6%8F%92%E4%BB%B6%E7%9A%84%E5%87%86%E5%A4%87%E5%92%8C%E6%94%B6%E5%B0%BE%E5%B7%A5%E4%BD%9C export default function (babel: any) { const { template: tpl } = babel; return { name: 'CodeSplitting', visitor: { Program: { enter(_path: NodePath<t.Program>, state: any) { const reference = state?.file?.opts.filename; if (regNodeModules.test(reference)) { return; } const isServer = state?.opts?.isServer; state.path = _path; let exitRoutes = false; if (!state.import) { state.import = {}; } _path.traverse({ ImportDeclaration(path) { const specifiers = path.node.specifiers; if ( specifiers && specifiers.length === 1 && t.isImportDefaultSpecifier(specifiers[0]) ) { const name = specifiers[0].local.name; state.import[name] = path; } state.hasImport = {}; }, JSXElement(path) { if (t.isJSXIdentifier(path.node.openingElement.name)) { if (path.node.openingElement.name.name === 'RouterSwitch' && !exitRoutes) { exitRoutes = true; /** * 代码拆分 */ splitting(path.node.children as any, state, tpl); /** * 收集路由表 */ const routes: any = []; const _routes: any = []; // 这里要递归查找children check(path.node.children as any, routes); routes.forEach((item: any) => { const obj = []; for (const key in item) { if (Object.prototype.hasOwnProperty.call(item, key)) { if (key === '__award__spread__') { (item[key] as Array<any>).forEach((spread) => { if (spread.type === 1) { obj.push(t.objectProperty(t.identifier(key), spread.value)); } if (spread.type === 2) { obj.push(t.spreadElement(spread.value)); } }); } else { obj.push(t.objectProperty(t.identifier(key), item[key])); } } } _routes.push(t.objectExpression(obj)); }); path.node.children = [ t.jsxElement( t.jsxOpeningElement(t.jsxIdentifier('p'), []), t.jsxClosingElement(t.jsxIdentifier('p')), [t.jsxText('路由出错了...')], false ) as any ]; if (isServer) { _path.node.body.push( tpl(`global.__AWARD__INIT__ROUTES__ = INIT`)({ INIT: t.arrayExpression(_routes), __AWARD__INIT__ROUTES__: t.identifier('__AWARD__INIT__ROUTES__') }) ); } else { _path.node.body.push( tpl(`window.__AWARD__INIT__ROUTES__ = INIT`)({ INIT: t.arrayExpression(_routes), __AWARD__INIT__ROUTES__: t.identifier('__AWARD__INIT__ROUTES__') }) ); } } } } }); } } } }; }
the_stack
import Launcher from '../src/launcher' import logger from '@wdio/logger' import { sleep } from '@wdio/utils' import fs from 'fs-extra' const caps: WebDriver.DesiredCapabilities = { maxInstances: 1, browserName: 'chrome' } jest.mock('fs-extra') jest.mock('../src/interface', () => class { emit = jest.fn() on = jest.fn() sigintTrigger = jest.fn() onMessage = jest.fn() }) describe('launcher', () => { const emitSpy = jest.spyOn(process, 'emit') let launcher: Launcher beforeEach(() => { global.console.log = jest.fn() emitSpy.mockClear() launcher = new Launcher('./') }) describe('defaults', () => { it('should have default for the argv parameter', () => { expect(launcher['_args']).toEqual({}) }) it('should run autocompile by default', () => { expect(launcher['configParser'].autoCompile).toBeCalledTimes(1) }) it('should not run auto compile if cli param was provided', () => { const otherLauncher = new Launcher('./', { autoCompileOpts: { autoCompile: false } }) expect(otherLauncher['configParser'].merge).toBeCalledWith({ autoCompileOpts: { autoCompile: false } }) expect(otherLauncher['configParser'].autoCompile).toBeCalledTimes(1) }) }) describe('capabilities', () => { it('should NOT fail when capabilities are passed', async () => { launcher.runSpecs = jest.fn().mockReturnValue(1) const exitCode = await launcher.runMode({ specs: ['./'] } as any, [caps]) expect(launcher.runSpecs).toBeCalled() expect(exitCode).toEqual(0) expect(logger('').error).not.toBeCalled() }) it('should fail if no specs were found', async () => { launcher.runSpecs = jest.fn() launcher.configParser.getSpecs = jest.fn().mockReturnValue([]) const exitCode = await launcher.runMode({ specs: ['./'] } as any, [caps]) expect(launcher.runSpecs).toBeCalledTimes(0) expect(exitCode).toBe(1) }) it('should fail when no capabilities are passed', async () => { launcher.runSpecs = jest.fn().mockReturnValue(1) // @ts-ignore test invalid parameter const exitCode = await launcher.runMode({ specs: ['./'] as any }) expect(exitCode).toEqual(1) expect(logger('').error).toBeCalledWith('Missing capabilities, exiting with failure') }) it('should fail when no capabilities are set', async () => { launcher.runSpecs = jest.fn().mockReturnValue(1) const exitCode = await launcher.runMode({ specs: ['./'] } as any, undefined) expect(exitCode).toEqual(1) expect(logger('').error).toBeCalledWith('Missing capabilities, exiting with failure') }) it('should start instance in multiremote', () => { launcher.runSpecs = jest.fn() launcher.isMultiremote = true launcher.runMode( { specs: ['./'], specFileRetries: 2 } as any, { foo: { capabilities: { browserName: 'chrome' } } } ) expect(launcher['_schedule']).toHaveLength(1) expect(launcher['_schedule'][0].specs[0].retries).toBe(2) expect(typeof launcher['_resolve']).toBe('function') expect(launcher.runSpecs).toBeCalledTimes(1) }) it('should start instance with grouped specs', () => { launcher.runSpecs = jest.fn() launcher.isMultiremote = false launcher.runMode( { specs: [['/a.js', '/b.js']], specFileRetries: 2 } as any, [caps] ) expect(launcher['_schedule']).toHaveLength(1) expect(launcher['_schedule'][0].specs[0].retries).toBe(2) expect(typeof launcher['_resolve']).toBe('function') expect(launcher.runSpecs).toBeCalledTimes(1) }) it('should start instance in multiremote with grouped specs', () => { launcher.runSpecs = jest.fn() launcher.isMultiremote = true launcher.runMode( { specs: [['/a.js', '/b.js']], specFileRetries: 2 } as any, { foo: { capabilities: { browserName: 'chrome' } } } ) expect(launcher['_schedule']).toHaveLength(1) expect(launcher['_schedule'][0].specs[0].retries).toBe(2) expect(typeof launcher['_resolve']).toBe('function') expect(launcher.runSpecs).toBeCalledTimes(1) }) it('should ignore specFileRetries in watch mode', () => { launcher.runSpecs = jest.fn() launcher['_isWatchMode'] = true launcher.runMode({ specs: ['./'], specFileRetries: 2 } as any, [caps, caps]) expect(launcher['_schedule']).toHaveLength(2) expect(launcher['_schedule'][0].specs[0].retries).toBe(0) expect(launcher['_schedule'][1].specs[0].retries).toBe(0) expect(launcher.runSpecs).toBeCalledTimes(1) }) it('should apply maxInstancesPerCapability if maxInstances is not passed', () => { launcher.runSpecs = jest.fn() launcher.runMode( { specs: ['./'], specFileRetries: 3, maxInstancesPerCapability: 4 } as any, [{ browserName: 'chrome' }] ) expect(launcher['_schedule']).toHaveLength(1) expect(launcher['_schedule'][0].specs[0].retries).toBe(3) expect(launcher['_schedule'][0].availableInstances).toBe(4) expect(launcher.runSpecs).toBeCalledTimes(1) }) }) describe('hasTriggeredExitRoutine', () => { it('should return false if there are specs left of running when hasTriggeredExitRoutine is false', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher['_hasTriggeredExitRoutine'] = false const returnValue = launcher.runSpecs() expect(returnValue).toEqual(false) }) it('should return true when hasTriggeredExitRoutine is true', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher['_hasTriggeredExitRoutine'] = true const returnValue = launcher.runSpecs() expect(returnValue).toEqual(true) }) }) describe('endHandler', () => { it('should emit and resolve failed status', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher.runSpecs = jest.fn().mockReturnValue(1) launcher['_schedule'] = [{ cid: 1 } as any, { cid: 2 }] launcher['_resolve'] = jest.fn() launcher.endHandler({ cid: '0-1', exitCode: 1 } as any) expect(launcher.interface.emit).toBeCalledWith('job:end', { cid: '0-1', passed: false }) expect(launcher['_resolve']).toBeCalledWith(1) }) it('should emit and resolve passed status', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher.runSpecs = jest.fn().mockReturnValue(1) launcher['_schedule'] = [{ cid: 1 } as any, { cid: 2 }] launcher['_resolve'] = jest.fn() launcher.endHandler({ cid: '0-1', exitCode: 0 } as any) expect(launcher.interface.emit).toBeCalledWith('job:end', { cid: '0-1', passed: true }) expect(launcher['_resolve']).toBeCalledWith(0) }) it('should do nothing if not all specs are run', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher.runSpecs = jest.fn().mockReturnValue(0) launcher['_schedule'] = [{ cid: 1 } as any, { cid: 2 }] launcher['_resolve'] = jest.fn() launcher.endHandler({ cid: '0-1', exitCode: 0 } as any) expect(launcher.interface.emit).toBeCalledWith('job:end', { cid: '0-1', passed: true }) expect(launcher['_resolve']).toBeCalledTimes(0) }) it('should do nothing if watch mode is still running', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher['_isWatchMode'] = true launcher.runSpecs = jest.fn().mockReturnValue(1) launcher['_schedule'] = [{ cid: 1 } as any, { cid: 2 }] launcher['_resolve'] = jest.fn() launcher.endHandler({ cid: '0-1', exitCode: 1 } as any) expect(launcher.interface.emit).toBeCalledWith('job:end', { cid: '0-1', passed: false }) expect(launcher['_resolve']).toBeCalledTimes(0) }) it('should resolve and not emit on watch mode stop', () => { launcher.getNumberOfRunningInstances = jest.fn().mockReturnValue(1) launcher['_isWatchMode'] = true launcher['_hasTriggeredExitRoutine'] = true launcher.runSpecs = jest.fn().mockReturnValue(1) launcher['_schedule'] = [{ cid: 1 } as any, { cid: 2 }] launcher['_resolve'] = jest.fn() launcher.endHandler({ cid: '0-1', exitCode: 1 } as any) expect(launcher.interface.emit).not.toBeCalled() expect(launcher['_resolve']).toBeCalledWith(0) }) it('should reschedule when runner failed and retries remain', () => { launcher['_schedule'] = [{ cid: 0, specs: [] }] as any launcher.endHandler({ cid: '0-5', exitCode: 1, retries: 1, specs: ['a.js'] }) expect(launcher['_schedule']).toMatchObject([{ cid: 0, specs: [{ rid: '0-5', files: ['a.js'], retries: 0 }] }]) }) it('should requeue retried specfiles at beginning of queue', () => { launcher.configParser.getConfig = jest.fn().mockReturnValue({ specFileRetriesDeferred: false }) launcher['_schedule'] = [{ cid: 0, specs: [{ files: ['b.js'] }] }] as any launcher.endHandler({ cid: '0-5', exitCode: 1, retries: 1, specs: ['a.js'] }) expect(launcher['_schedule']).toMatchObject([{ cid: 0, specs: [{ rid: '0-5', files: ['a.js'], retries: 0 }, { files: ['b.js'] }] }]) }) it('should requeue retried specfiles at end of queue', () => { launcher['_schedule'] = [{ cid: 0, specs: [{ files: ['b.js'] }] }] as any launcher.endHandler({ cid: '0-5', exitCode: 1, retries: 1, specs: ['a.js'] }) expect(launcher['_schedule']).toMatchObject([{ cid: 0, specs: [{ files: ['b.js'] }, { rid: '0-5', files: ['a.js'], retries: 0 }] }]) }) }) describe('exitHandler', () => { it('should do nothing if no callback is given', () => { launcher['_hasTriggeredExitRoutine'] = false launcher.runner = { shutdown: jest.fn() .mockReturnValue(Promise.resolve()) } as any launcher.exitHandler() expect(launcher['_hasTriggeredExitRoutine']).toBe(false) expect(launcher.interface.sigintTrigger).toBeCalledTimes(0) expect(launcher.runner.shutdown).toBeCalledTimes(0) }) it('should do nothing if shutdown was called before', () => { launcher['_hasTriggeredExitRoutine'] = true launcher.runner = { shutdown: jest.fn().mockReturnValue(Promise.resolve()) } as any expect(launcher.exitHandler(() => 'foo')).toBe('foo') expect(launcher['_hasTriggeredExitRoutine']).toBe(true) expect(launcher.interface.sigintTrigger).toBeCalledTimes(0) expect(launcher.runner.shutdown).toBeCalledTimes(0) }) it('should shutdown', () => { launcher['_hasTriggeredExitRoutine'] = false launcher.runner = { shutdown: jest.fn().mockReturnValue(Promise.resolve()) } as any launcher.exitHandler(jest.fn()) expect(launcher['_hasTriggeredExitRoutine']).toBe(true) expect(launcher.interface.sigintTrigger).toBeCalledTimes(1) expect(launcher.runner.shutdown).toBeCalledTimes(1) }) }) describe('getRunnerId', () => { it('should return increasing cid numbers', () => { expect(launcher.getRunnerId(0)).toBe('0-0') expect(launcher.getRunnerId(0)).toBe('0-1') expect(launcher.getRunnerId(0)).toBe('0-2') expect(launcher.getRunnerId(2)).toBe('2-0') expect(launcher.getRunnerId(0)).toBe('0-3') expect(launcher.getRunnerId(2)).toBe('2-1') }) }) describe('getNumberOfSpecsLeft', () => { it('should return number of spec', () => { launcher['_schedule'] = [{ specs: [1, 2, [3, 4, 5]] }, { specs: [1, 2] }] as any expect(launcher.getNumberOfSpecsLeft()).toBe(5) }) }) describe('getNumberOfRunningInstances', () => { it('should return number of spec', () => { launcher['_schedule'] = [{ runningInstances: 3 }, { runningInstances: 2 }] as any expect(launcher.getNumberOfRunningInstances()).toBe(5) }) }) describe('formatSpecs', () => { it('should return correctly formatted specs', () => { // Define a capabilities that is sent to formatSpecs // - only used in function call const capabilities = { specs: ['/a.js', ['/b.js', '/c.js', '/d.js'], '/e.js'] } const specFileRetries = 17 // Define the golden result const expected = [ { 'files': ['/a.js'], 'retries': 17 }, { 'files': ['/b.js', '/c.js', '/d.js'], 'retries': 17 }, { 'files': ['/e.js'], 'retries': 17 }, ] // Mock the return value of getSpecs so we are not doing cross // module testing launcher.configParser = { getSpecs: jest.fn().mockReturnValue( ['/a.js', ['/b.js', '/c.js', '/d.js'], '/e.js'] ) } as any expect(launcher.formatSpecs(capabilities, specFileRetries)).toStrictEqual(expected) }) }) describe('runSpecs', () => { beforeEach(() => { launcher.startInstance = jest.fn() }) it('should not start running anything if exit routine is triggered', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100 }) } as any launcher['_hasTriggeredExitRoutine'] = true expect(launcher.runSpecs()).toBe(true) expect(launcher.startInstance).toBeCalledTimes(0) }) it('should run all specs', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: ['/a.js', 'b.js', 'c.js'], availableInstances: 50, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js', 'c.js', 'd.js'], availableInstances: 60, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js'], availableInstances: 70, runningInstances: 0, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(false) expect(launcher.getNumberOfRunningInstances()).toBe(9) expect(launcher.getNumberOfSpecsLeft()).toBe(0) expect(launcher['_schedule'][0].runningInstances).toBe(3) expect(launcher['_schedule'][0].availableInstances).toBe(47) expect(launcher['_schedule'][1].runningInstances).toBe(4) expect(launcher['_schedule'][1].availableInstances).toBe(56) expect(launcher['_schedule'][2].runningInstances).toBe(2) expect(launcher['_schedule'][2].availableInstances).toBe(68) }) it('should run arrayed specs in a single instance', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: ['/a.js', ['b.js', 'c.js']], availableInstances: 50, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: [['/a.js', 'b.js', 'c.js', 'd.js']], availableInstances: 60, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: [['/a.js'], 'b.js'], availableInstances: 70, runningInstances: 0, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(false) expect(launcher.getNumberOfRunningInstances()).toBe(5) expect(launcher.getNumberOfSpecsLeft()).toBe(0) expect(launcher['_schedule'][0].runningInstances).toBe(2) expect(launcher['_schedule'][0].availableInstances).toBe(48) expect(launcher['_schedule'][1].runningInstances).toBe(1) expect(launcher['_schedule'][1].availableInstances).toBe(59) expect(launcher['_schedule'][2].runningInstances).toBe(2) expect(launcher['_schedule'][2].availableInstances).toBe(68) }) it('should not run anything if runner failed', () => { launcher['_runnerFailed'] = 2 launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100, bail: 1 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: ['/a.js', 'b.js', 'c.js'], availableInstances: 50, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js', 'c.js', 'd.js'], availableInstances: 60, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js'], availableInstances: 70, runningInstances: 0, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(true) expect(launcher.getNumberOfRunningInstances()).toBe(0) expect(launcher.getNumberOfSpecsLeft()).toBe(0) }) it('should run as much as maxInstances allows', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 5 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: ['/a.js', 'b.js', 'c.js'], availableInstances: 50, runningInstances: 0, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js', 'c.js', 'd.js'], availableInstances: 60, runningInstances: 0, seleniumServer: {} }, { cid: 2, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js'], availableInstances: 70, runningInstances: 0, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(false) expect(launcher.getNumberOfRunningInstances()).toBe(5) expect(launcher.getNumberOfSpecsLeft()).toBe(4) }) it('should not allow to schedule more runner if no instances are available', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: ['/a.js', 'b.js', 'c.js'], availableInstances: 1, runningInstances: 10, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js', 'c.js', 'd.js'], availableInstances: 2, runningInstances: 4, seleniumServer: {} }, { cid: 1, caps: { browserName: 'chrome2' }, specs: ['/a.js', 'b.js'], availableInstances: 0, runningInstances: 2, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(false) expect(launcher.getNumberOfRunningInstances()).toBe(19) expect(launcher.getNumberOfSpecsLeft()).toBe(6) expect(launcher['_schedule'][0].runningInstances).toBe(11) expect(launcher['_schedule'][0].availableInstances).toBe(0) expect(launcher['_schedule'][1].runningInstances).toBe(6) expect(launcher['_schedule'][1].availableInstances).toBe(0) expect(launcher['_schedule'][2].runningInstances).toBe(2) expect(launcher['_schedule'][2].availableInstances).toBe(0) }) it('should not run if all specs were executed', () => { launcher.configParser = { getConfig: jest.fn().mockReturnValue({ maxInstances: 100 }) } as any launcher['_schedule'] = [{ cid: 0, caps: { browserName: 'chrome' }, specs: [], availableInstances: 10, runningInstances: 0, seleniumServer: {} }] as any expect(launcher.runSpecs()).toBe(true) expect(launcher.getNumberOfRunningInstances()).toBe(0) expect(launcher.getNumberOfSpecsLeft()).toBe(0) }) }) describe('startInstance', () => { beforeEach(() => { (launcher.runner.run as jest.Mock) = jest.fn().mockReturnValue({ on: () => {} }) launcher['_launcher'] = [] }) it('should start an instance', async () => { const onWorkerStartMock = jest.fn() const caps = { browserName: 'chrome' } launcher.configParser.getConfig = () => ({ onWorkerStart: onWorkerStartMock }) as any launcher['_args'].hostname = '127.0.0.2' expect(launcher['_runnerStarted']).toBe(0) await launcher.startInstance( ['/foo.test.js'], caps, 0, '0-5', 0 ) expect(sleep).not.toHaveBeenCalled() expect(launcher['_runnerStarted']).toBe(1) expect((launcher.runner.run as jest.Mock).mock.calls[0][0]).toHaveProperty('cid', '0-5') expect(launcher.getRunnerId(0)).toBe('0-0') expect(onWorkerStartMock).toHaveBeenCalledWith( '0-5', caps, ['/foo.test.js'], { hostname: '127.0.0.2' }, ['--no-wasm-code-gc'] ) }) it('should wait before starting an instance on retry', async () => { const onWorkerStartMock = jest.fn() const caps = { browserName: 'chrome' } launcher.configParser = { getConfig: jest.fn().mockReturnValue({ onWorkerStart: onWorkerStartMock, specFileRetries: 2, specFileRetriesDelay: 0.01 }) } as any launcher['_args'].hostname = '127.0.0.3' await launcher.startInstance( ['/foo.test.js'], caps, 0, '0-6', 3 ) expect(sleep).toHaveBeenCalledTimes(1) expect(sleep).toHaveBeenCalledWith(10) expect(onWorkerStartMock).toHaveBeenCalledWith( '0-6', caps, ['/foo.test.js'], { hostname: '127.0.0.3' }, ['--no-wasm-code-gc'] ) }) it('should not wait before starting an instance on the first run', async () => { const onWorkerStartMock = jest.fn() const caps = { browserName: 'chrome' } launcher.configParser = { getConfig: jest.fn().mockReturnValue({ onWorkerStart: onWorkerStartMock, specFileRetries: 4, specFileRetriesDelay: 0.01 }) } as any launcher['_args'].hostname = '127.0.0.4' await launcher.startInstance( ['/foo.test.js'], caps, 0, '0-7', 4 ) expect(sleep).not.toHaveBeenCalled() expect(onWorkerStartMock).toHaveBeenCalledWith( '0-7', caps, ['/foo.test.js'], { hostname: '127.0.0.4' }, ['--no-wasm-code-gc'] ) }) }) describe('config options', () => { let ensureDirSyncSpy beforeEach(() => { ensureDirSyncSpy = jest.spyOn(fs, 'ensureDirSync') }) it('should create directory when the config options have a outputDir option', () => { expect(ensureDirSyncSpy).toHaveBeenCalled() expect(ensureDirSyncSpy).toHaveBeenCalledWith('tempDir') }) afterEach(() => { ensureDirSyncSpy.mockClear() }) }) describe('run', () => { let config: WebdriverIO.Config = { capabilities: {} } beforeEach(() => { global.console.error = jest.fn() config = { // ConfigParser.addFileConfig() will return onPrepare and onComplete as arrays of functions onPrepare: [jest.fn()], onComplete: [jest.fn()], capabilities: {} } launcher.configParser = { getCapabilities: jest.fn().mockReturnValue(0), getConfig: jest.fn().mockReturnValue(config), autoCompile: jest.fn() } as any launcher.runner = { initialise: jest.fn(), shutdown: jest.fn() } as any launcher.runMode = jest.fn().mockImplementation((config, caps) => caps) launcher.interface = { finalise: jest.fn() } as any }) it('exit code 0', async () => { expect(await launcher.run()).toEqual(0) expect(launcher.runner.shutdown).toBeCalled() expect(launcher.configParser.getCapabilities).toBeCalledTimes(1) expect(launcher.configParser.getConfig).toBeCalledTimes(1) expect(launcher.runner.initialise).toBeCalledTimes(1) expect(config.onPrepare[0]).toBeCalledTimes(1) expect(launcher.runMode).toBeCalledTimes(1) expect(config.onPrepare[0]).toBeCalledTimes(1) expect(launcher.interface.finalise).toBeCalledTimes(1) }) it('should not shutdown runner if was called before', async () => { launcher['_hasTriggeredExitRoutine'] = true expect(await launcher.run()).toEqual(0) expect(launcher.runner.shutdown).not.toBeCalled() }) it('onComplete error', async () => { // ConfigParser.addFileConfig() will return onComplete as an array of functions config.onComplete = [() => { throw new Error() }] expect(await launcher.run()).toEqual(1) expect(launcher.runner.shutdown).toBeCalled() }) it('should shutdown runner on error', async () => { delete logger.waitForBuffer let error try { await launcher.run() } catch (err: any) { error = err } expect(launcher.runner.shutdown).toBeCalled() expect(error).toBeInstanceOf(Error) }) afterEach(() => { (global.console.error as jest.Mock).mockRestore() }) }) afterEach(() => { (global.console.log as jest.Mock).mockRestore() ;(sleep as jest.Mock).mockClear() }) })
the_stack
import { contains, errorPrefix as errorPrefixFxn, safeGet, stringLength } from '@firebase/util'; import { RepoInfo } from '../RepoInfo'; import { Path, pathChild, pathCompare, pathContains, pathGetBack, pathGetFront, pathSlice, ValidationPath, validationPathPop, validationPathPush, validationPathToErrorString } from './Path'; import { each, isInvalidJSONNumber } from './util'; /** * True for invalid Firebase keys */ export const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/; /** * True for invalid Firebase paths. * Allows '/' in paths. */ export const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/; /** * Maximum number of characters to allow in leaf value */ export const MAX_LEAF_SIZE_ = 10 * 1024 * 1024; export const isValidKey = function (key: unknown): boolean { return ( typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key) ); }; export const isValidPathString = function (pathString: string): boolean { return ( typeof pathString === 'string' && pathString.length !== 0 && !INVALID_PATH_REGEX_.test(pathString) ); }; export const isValidRootPathString = function (pathString: string): boolean { if (pathString) { // Allow '/.info/' at the beginning. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); } return isValidPathString(pathString); }; export const isValidPriority = function (priority: unknown): boolean { return ( priority === null || typeof priority === 'string' || (typeof priority === 'number' && !isInvalidJSONNumber(priority)) || (priority && typeof priority === 'object' && // eslint-disable-next-line @typescript-eslint/no-explicit-any contains(priority as any, '.sv')) ); }; /** * Pre-validate a datum passed as an argument to Firebase function. */ export const validateFirebaseDataArg = function ( fnName: string, value: unknown, path: Path, optional: boolean ) { if (optional && value === undefined) { return; } validateFirebaseData(errorPrefixFxn(fnName, 'value'), value, path); }; /** * Validate a data object client-side before sending to server. */ export const validateFirebaseData = function ( errorPrefix: string, data: unknown, path_: Path | ValidationPath ) { const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_; if (data === undefined) { throw new Error( errorPrefix + 'contains undefined ' + validationPathToErrorString(path) ); } if (typeof data === 'function') { throw new Error( errorPrefix + 'contains a function ' + validationPathToErrorString(path) + ' with contents = ' + data.toString() ); } if (isInvalidJSONNumber(data)) { throw new Error( errorPrefix + 'contains ' + data.toString() + ' ' + validationPathToErrorString(path) ); } // Check max leaf size, but try to avoid the utf8 conversion if we can. if ( typeof data === 'string' && data.length > MAX_LEAF_SIZE_ / 3 && stringLength(data) > MAX_LEAF_SIZE_ ) { throw new Error( errorPrefix + 'contains a string greater than ' + MAX_LEAF_SIZE_ + ' utf8 bytes ' + validationPathToErrorString(path) + " ('" + data.substring(0, 50) + "...')" ); } // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON // to save extra walking of large objects. if (data && typeof data === 'object') { let hasDotValue = false; let hasActualChild = false; each(data, (key: string, value: unknown) => { if (key === '.value') { hasDotValue = true; } else if (key !== '.priority' && key !== '.sv') { hasActualChild = true; if (!isValidKey(key)) { throw new Error( errorPrefix + ' contains an invalid key (' + key + ') ' + validationPathToErrorString(path) + '. Keys must be non-empty strings ' + 'and can\'t contain ".", "#", "$", "/", "[", or "]"' ); } } validationPathPush(path, key); validateFirebaseData(errorPrefix, value, path); validationPathPop(path); }); if (hasDotValue && hasActualChild) { throw new Error( errorPrefix + ' contains ".value" child ' + validationPathToErrorString(path) + ' in addition to actual children.' ); } } }; /** * Pre-validate paths passed in the firebase function. */ export const validateFirebaseMergePaths = function ( errorPrefix: string, mergePaths: Path[] ) { let i, curPath: Path; for (i = 0; i < mergePaths.length; i++) { curPath = mergePaths[i]; const keys = pathSlice(curPath); for (let j = 0; j < keys.length; j++) { if (keys[j] === '.priority' && j === keys.length - 1) { // .priority is OK } else if (!isValidKey(keys[j])) { throw new Error( errorPrefix + 'contains an invalid key (' + keys[j] + ') in path ' + curPath.toString() + '. Keys must be non-empty strings ' + 'and can\'t contain ".", "#", "$", "/", "[", or "]"' ); } } } // Check that update keys are not descendants of each other. // We rely on the property that sorting guarantees that ancestors come // right before descendants. mergePaths.sort(pathCompare); let prevPath: Path | null = null; for (i = 0; i < mergePaths.length; i++) { curPath = mergePaths[i]; if (prevPath !== null && pathContains(prevPath, curPath)) { throw new Error( errorPrefix + 'contains a path ' + prevPath.toString() + ' that is ancestor of another path ' + curPath.toString() ); } prevPath = curPath; } }; /** * pre-validate an object passed as an argument to firebase function ( * must be an object - e.g. for firebase.update()). */ export const validateFirebaseMergeDataArg = function ( fnName: string, data: unknown, path: Path, optional: boolean ) { if (optional && data === undefined) { return; } const errorPrefix = errorPrefixFxn(fnName, 'values'); if (!(data && typeof data === 'object') || Array.isArray(data)) { throw new Error( errorPrefix + ' must be an object containing the children to replace.' ); } const mergePaths: Path[] = []; each(data, (key: string, value: unknown) => { const curPath = new Path(key); validateFirebaseData(errorPrefix, value, pathChild(path, curPath)); if (pathGetBack(curPath) === '.priority') { if (!isValidPriority(value)) { throw new Error( errorPrefix + "contains an invalid value for '" + curPath.toString() + "', which must be a valid " + 'Firebase priority (a string, finite number, server value, or null).' ); } } mergePaths.push(curPath); }); validateFirebaseMergePaths(errorPrefix, mergePaths); }; export const validatePriority = function ( fnName: string, priority: unknown, optional: boolean ) { if (optional && priority === undefined) { return; } if (isInvalidJSONNumber(priority)) { throw new Error( errorPrefixFxn(fnName, 'priority') + 'is ' + priority.toString() + ', but must be a valid Firebase priority (a string, finite number, ' + 'server value, or null).' ); } // Special case to allow importing data with a .sv. if (!isValidPriority(priority)) { throw new Error( errorPrefixFxn(fnName, 'priority') + 'must be a valid Firebase priority ' + '(a string, finite number, server value, or null).' ); } }; export const validateKey = function ( fnName: string, argumentName: string, key: string, optional: boolean ) { if (optional && key === undefined) { return; } if (!isValidKey(key)) { throw new Error( errorPrefixFxn(fnName, argumentName) + 'was an invalid key = "' + key + '". Firebase keys must be non-empty strings and ' + 'can\'t contain ".", "#", "$", "/", "[", or "]").' ); } }; /** * @internal */ export const validatePathString = function ( fnName: string, argumentName: string, pathString: string, optional: boolean ) { if (optional && pathString === undefined) { return; } if (!isValidPathString(pathString)) { throw new Error( errorPrefixFxn(fnName, argumentName) + 'was an invalid path = "' + pathString + '". Paths must be non-empty strings and ' + 'can\'t contain ".", "#", "$", "[", or "]"' ); } }; export const validateRootPathString = function ( fnName: string, argumentName: string, pathString: string, optional: boolean ) { if (pathString) { // Allow '/.info/' at the beginning. pathString = pathString.replace(/^\/*\.info(\/|$)/, '/'); } validatePathString(fnName, argumentName, pathString, optional); }; /** * @internal */ export const validateWritablePath = function (fnName: string, path: Path) { if (pathGetFront(path) === '.info') { throw new Error(fnName + " failed = Can't modify data under /.info/"); } }; export const validateUrl = function ( fnName: string, parsedUrl: { repoInfo: RepoInfo; path: Path } ) { // TODO = Validate server better. const pathString = parsedUrl.path.toString(); if ( !(typeof parsedUrl.repoInfo.host === 'string') || parsedUrl.repoInfo.host.length === 0 || (!isValidKey(parsedUrl.repoInfo.namespace) && parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') || (pathString.length !== 0 && !isValidRootPathString(pathString)) ) { throw new Error( errorPrefixFxn(fnName, 'url') + 'must be a valid firebase URL and ' + 'the path can\'t contain ".", "#", "$", "[", or "]".' ); } }; export const validateString = function ( fnName: string, argumentName: string, string: unknown, optional: boolean ) { if (optional && string === undefined) { return; } if (!(typeof string === 'string')) { throw new Error( errorPrefixFxn(fnName, argumentName) + 'must be a valid string.' ); } }; export const validateObject = function ( fnName: string, argumentName: string, obj: unknown, optional: boolean ) { if (optional && obj === undefined) { return; } if (!(obj && typeof obj === 'object') || obj === null) { throw new Error( errorPrefixFxn(fnName, argumentName) + 'must be a valid object.' ); } }; export const validateObjectContainsKey = function ( fnName: string, argumentName: string, obj: unknown, key: string, optional: boolean, optType?: string ) { const objectContainsKey = // eslint-disable-next-line @typescript-eslint/no-explicit-any obj && typeof obj === 'object' && contains(obj as any, key); if (!objectContainsKey) { if (optional) { return; } else { throw new Error( errorPrefixFxn(fnName, argumentName) + 'must contain the key "' + key + '"' ); } } if (optType) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const val = safeGet(obj as any, key); if ( (optType === 'number' && !(typeof val === 'number')) || (optType === 'string' && !(typeof val === 'string')) || (optType === 'boolean' && !(typeof val === 'boolean')) || (optType === 'function' && !(typeof val === 'function')) || (optType === 'object' && !(typeof val === 'object') && val) ) { if (optional) { throw new Error( errorPrefixFxn(fnName, argumentName) + 'contains invalid value for key "' + key + '" (must be of type "' + optType + '")' ); } else { throw new Error( errorPrefixFxn(fnName, argumentName) + 'must contain the key "' + key + '" with type "' + optType + '"' ); } } } };
the_stack
import * as util from "../util.js"; import type { Warnings } from "../util.js"; import jsesc from "jsesc"; import type { Request, Query, QueryDict } from "../util.js"; // TODO: partiallySupportedArgs const supportedArgs = new Set([ "url", "request", "compressed", "no-compressed", "digest", "no-digest", "http1.0", "http1.1", "http2", "http2-prior-knowledge", "http3", "http0.9", "no-http0.9", "user-agent", "cookie", "data", "data-raw", "data-ascii", "data-binary", "data-urlencode", "json", "referer", "cert", "cacert", "key", "capath", "form", "form-string", "get", "header", "head", "no-head", "insecure", "no-insecure", "output", "user", "upload-file", "proxy-user", "proxy", ]); // supported by other generators const supportedByOthers = ["max-time", "location"]; const unsupportedArgs = [ "dns-ipv4-addr", "dns-ipv6-addr", "random-file", "egd-file", "oauth2-bearer", "connect-timeout", "doh-url", "ciphers", "dns-interface", "disable-epsv", "no-disable-epsv", "disallow-username-in-url", "no-disallow-username-in-url", "epsv", "no-epsv", "dns-servers", "trace", "npn", "no-npn", "trace-ascii", "alpn", "no-alpn", "limit-rate", "tr-encoding", "no-tr-encoding", "negotiate", "no-negotiate", "ntlm", "no-ntlm", "ntlm-wb", "no-ntlm-wb", "basic", "no-basic", "anyauth", "no-anyauth", "wdebug", "no-wdebug", "ftp-create-dirs", "no-ftp-create-dirs", "create-dirs", "no-create-dirs", "create-file-mode", "max-redirs", "proxy-ntlm", "no-proxy-ntlm", "crlf", "no-crlf", "stderr", "aws-sigv4", "interface", "krb", "krb4", "haproxy-protocol", "no-haproxy-protocol", "max-filesize", "disable-eprt", "no-disable-eprt", "eprt", "no-eprt", "xattr", "no-xattr", "ftp-ssl", "no-ftp-ssl", "ssl", "no-ssl", "ftp-pasv", "no-ftp-pasv", "socks5", "tcp-nodelay", "no-tcp-nodelay", "proxy-digest", "no-proxy-digest", "proxy-basic", "no-proxy-basic", "retry", "retry-connrefused", "no-retry-connrefused", "retry-delay", "retry-max-time", "proxy-negotiate", "no-proxy-negotiate", "form-escape", "no-form-escape", "ftp-account", "proxy-anyauth", "no-proxy-anyauth", "trace-time", "no-trace-time", "ignore-content-length", "no-ignore-content-length", "ftp-skip-pasv-ip", "no-ftp-skip-pasv-ip", "ftp-method", "local-port", "socks4", "socks4a", "ftp-alternative-to-user", "ftp-ssl-reqd", "no-ftp-ssl-reqd", "ssl-reqd", "no-ssl-reqd", "sessionid", "no-sessionid", "ftp-ssl-control", "no-ftp-ssl-control", "ftp-ssl-ccc", "no-ftp-ssl-ccc", "ftp-ssl-ccc-mode", "libcurl", "raw", "no-raw", "post301", "no-post301", "keepalive", "no-keepalive", "socks5-hostname", "keepalive-time", "post302", "no-post302", "noproxy", "socks5-gssapi-nec", "no-socks5-gssapi-nec", "proxy1.0", "tftp-blksize", "mail-from", "mail-rcpt", "ftp-pret", "no-ftp-pret", "proto", "proto-redir", "resolve", "delegation", "mail-auth", "post303", "no-post303", "metalink", "no-metalink", "sasl-authzid", "sasl-ir", "no-sasl-ir", "test-event", "no-test-event", "unix-socket", "path-as-is", "no-path-as-is", "socks5-gssapi-service", "proxy-service-name", "service-name", "proto-default", "expect100-timeout", "tftp-no-options", "no-tftp-no-options", "connect-to", "abstract-unix-socket", "tls-max", "suppress-connect-headers", "no-suppress-connect-headers", "compressed-ssh", "no-compressed-ssh", "happy-eyeballs-timeout-ms", "retry-all-errors", "no-retry-all-errors", "tlsv1", "tlsv1.0", "tlsv1.1", "tlsv1.2", "tlsv1.3", "tls13-ciphers", "proxy-tls13-ciphers", "sslv2", "sslv3", "ipv4", "ipv6", "append", "no-append", "alt-svc", "hsts", "use-ascii", "no-use-ascii", "cookie-jar", "continue-at", "dump-header", "cert-type", "key-type", "pass", "engine", "pubkey", "hostpubmd5", "hostpubsha256", "crlfile", "tlsuser", "tlspassword", "tlsauthtype", "ssl-allow-beast", "no-ssl-allow-beast", "ssl-auto-client-cert", "no-ssl-auto-client-cert", "proxy-ssl-auto-client-cert", "no-proxy-ssl-auto-client-cert", "pinnedpubkey", "proxy-pinnedpubkey", "cert-status", "no-cert-status", "doh-cert-status", "no-doh-cert-status", "false-start", "no-false-start", "ssl-no-revoke", "no-ssl-no-revoke", "ssl-revoke-best-effort", "no-ssl-revoke-best-effort", "tcp-fastopen", "no-tcp-fastopen", "proxy-tlsuser", "proxy-tlspassword", "proxy-tlsauthtype", "proxy-cert", "proxy-cert-type", "proxy-key", "proxy-key-type", "proxy-pass", "proxy-ciphers", "proxy-crlfile", "proxy-ssl-allow-beast", "no-proxy-ssl-allow-beast", "login-options", "proxy-cacert", "proxy-capath", "proxy-insecure", "no-proxy-insecure", "proxy-tlsv1", "socks5-basic", "no-socks5-basic", "socks5-gssapi", "no-socks5-gssapi", "etag-save", "etag-compare", "curves", "fail", "no-fail", "fail-early", "no-fail-early", "styled-output", "no-styled-output", "mail-rcpt-allowfails", "no-mail-rcpt-allowfails", "fail-with-body", "no-fail-with-body", "globoff", "no-globoff", "request-target", "proxy-header", "include", "no-include", "junk-session-cookies", "no-junk-session-cookies", "remote-header-name", "no-remote-header-name", "doh-insecure", "no-doh-insecure", "config", "list-only", "no-list-only", "location", "no-location", "location-trusted", "no-location-trusted", "max-time", "manual", "no-manual", "netrc", "no-netrc", "netrc-optional", "no-netrc-optional", "netrc-file", "buffer", "no-buffer", "remote-name", "remote-name-all", "no-remote-name-all", "output-dir", "proxytunnel", "no-proxytunnel", "ftp-port", "disable", "no-disable", "quote", "range", "remote-time", "no-remote-time", "telnet-option", "write-out", "preproxy", "speed-limit", "speed-time", "time-cond", "parallel", "no-parallel", "parallel-max", "parallel-immediate", "no-parallel-immediate", "next", // TODO: this is a big one ]; function reprWithVariable(value: string, hasEnvironmentVariable: boolean) { if (!value) { return "''"; } if (!hasEnvironmentVariable) { return "'" + jsesc(value, { quotes: "single", minimal: true }) + "'"; } // TODO: escape {} in the string return 'f"' + jsesc(value, { quotes: "double", minimal: true }) + '"'; } function repr(value: string): string { // In context of url parameters, don't accept nulls and such. return reprWithVariable(value, false); } function objToPython( obj: string | number | boolean | object | null, indent = 0 ): string { let s = ""; switch (typeof obj) { case "string": s += repr(obj); break; case "number": s += obj; break; case "boolean": s += obj ? "True" : "False"; break; case "object": if (obj === null) { s += "None"; } else if (Array.isArray(obj)) { if (obj.length === 0) { s += "[]"; } else { s += "[\n"; for (const item of obj) { s += " ".repeat(indent + 4) + objToPython(item, indent + 4) + ",\n"; } s += " ".repeat(indent) + "]"; } } else { const len = Object.keys(obj).length; if (len === 0) { s += "{}"; } else { s += "{\n"; for (const [k, v] of Object.entries(obj)) { // repr() because JSON keys must be strings. s += " ".repeat(indent + 4) + repr(k) + ": " + objToPython(v, indent + 4) + ",\n"; } s += " ".repeat(indent) + "}"; } } break; default: throw new util.CCError( "unexpected object type that shouldn't appear in JSON: " + typeof obj ); } return s; } function objToDictOrListOfTuples(obj: Query | QueryDict): string { if (!Array.isArray(obj)) { return objToPython(obj); } if (obj.length === 0) { return "[]"; } let s = "[\n"; for (const vals of obj) { s += " (" + vals.map(objToPython).join(", ") + "),\n"; } s += "]"; return s; } function getDataString( request: Request ): [string | null, boolean, string | null, boolean | null] { if (!request.data) { return [null, false, null, null]; } if (!request.isDataRaw && request.data.startsWith("@")) { let filePath = request.data.slice(1); if (filePath === "-") { if (request.stdin) { filePath = request.stdin; } else if (request.input) { request.data = request.input; } else { if (request.isDataBinary) { return [ "data = sys.stdin.buffer.read().replace(b'\\n', b'')\n", true, null, null, ]; } else { return [ "data = sys.stdin.read().replace('\\n', '')\n", true, null, null, ]; } } } if (!request.input) { if (request.isDataBinary) { // TODO: I bet the way python treats file paths is not identical to curl's return [ "with open(" + repr(filePath) + ", 'rb') as f:\n data = f.read().replace(b'\\n', b'')\n", false, null, null, ]; } else { return [ "with open(" + repr(filePath) + ") as f:\n data = f.read().replace('\\n', '')\n", false, null, null, ]; } } } const dataString = "data = " + repr(request.data) + "\n"; const contentTypeHeader = util.getHeader(request, "content-type"); const isJson = contentTypeHeader && contentTypeHeader.split(";")[0].trim() === "application/json"; if (isJson) { try { const dataAsJson = JSON.parse(request.data); // TODO: we actually want to know how it's serialized by // simplejson or Python's builtin json library, // which is what Requests uses // https://github.com/psf/requests/blob/b0e025ade7ed30ed53ab61f542779af7e024932e/requests/models.py#L473 // but this is hopefully good enough. const roundtrips = JSON.stringify(dataAsJson) === request.data; const jsonDataString = "json_data = " + objToPython(dataAsJson) + "\n"; return [dataString, false, jsonDataString, roundtrips]; } catch {} } const [parsedQuery, parsedQueryAsDict] = util.parseQueryString(request.data); if ( !request.isDataBinary && parsedQuery && parsedQuery.length && !parsedQuery.some((p) => p[1] === null) ) { const dataPythonObj = "data = " + objToDictOrListOfTuples(parsedQueryAsDict || parsedQuery) + "\n"; if ( util.getHeader(request, "content-type") === "application/x-www-form-urlencoded" ) { util.deleteHeader(request, "content-type"); } return [dataPythonObj, false, null, null]; } return [dataString, false, null, null]; } function getFilesString(request: Request): [string, boolean] { let usesStdin = false; if (!request.multipartUploads) { return ["", usesStdin]; } const multipartUploads = request.multipartUploads.map((m) => { // https://github.com/psf/requests/blob/2d5517682b3b38547634d153cea43d48fbc8cdb5/requests/models.py#L117 // // Requests's multipart syntax looks like this: // (name/filename, content) // (name, open(filename/contentFile)) // (name, (filename, open(contentFile)) // (name, (filename, open(contentFile), contentType, headers)) // this isn't parsed from --form yet const name = m.name ? repr(m.name) : "None"; const sentFilename = "filename" in m && m.filename ? repr(m.filename) : "None"; if ("contentFile" in m) { if (m.contentFile === "-") { // TODO: use piped stdin if we have it usesStdin = true; return [name, "(" + sentFilename + ", sys.stdin.buffer.read())"]; } else if (m.contentFile === m.filename) { return [name, "open(" + repr(m.contentFile) + ", 'rb')"]; } return [ name, "(" + sentFilename + ", open(" + repr(m.contentFile) + ", 'rb'))", ]; } return [name, "(" + sentFilename + ", " + repr(m.content) + ")"]; }); const multipartUploadsAsDict = Object.fromEntries(multipartUploads); let filesString = "files = "; if (Object.keys(multipartUploadsAsDict).length === multipartUploads.length) { filesString += "{\n"; for (const [multipartKey, multipartValue] of multipartUploads) { filesString += " " + multipartKey + ": " + multipartValue + ",\n"; } filesString += "}\n"; } else { filesString += "[\n"; for (const [multipartKey, multipartValue] of multipartUploads) { filesString += " (" + multipartKey + ", " + multipartValue + "),\n"; } filesString += "]\n"; } return [filesString, usesStdin]; } // convertVarToStringFormat will convert if inputString to f"..." format // if inputString has possible variable as its substring function detectEnvVar(inputString: string): [Set<string>, string] { // Using state machine to detect environment variable // Each character is an edge, state machine: // IN_ENV_VAR: means that currently we are iterating inside a possible environment variable // IN_STRING: means that currently we are iterating inside a normal string // For example: // "Hi my name is $USER_NAME !" // '$' --> will move state from IN_STRING to IN_ENV_VAR // ' ' --> will move state to IN_STRING, regardless the previous state const IN_ENV_VAR = 0; const IN_STRING = 1; // We only care for the unique element const detectedVariables: Set<string> = new Set(); let currState = IN_STRING; let envVarStartIndex = -1; const whiteSpaceSet = new Set(" \n\t"); const modifiedString = []; for (let idx = 0; idx < inputString.length; idx++) { const currIdx = idx; const currChar = inputString[currIdx]; if (currState === IN_ENV_VAR && whiteSpaceSet.has(currChar)) { const newVariable = inputString.substring(envVarStartIndex, currIdx); if (newVariable !== "") { detectedVariables.add(newVariable); // Change $ -> { // Add } after the last variable name modifiedString.push("{" + newVariable + "}" + currChar); } else { modifiedString.push("$" + currChar); } currState = IN_STRING; envVarStartIndex = -1; continue; } if (currState === IN_ENV_VAR) { // Skip until we actually have the new variable continue; } // currState === IN_STRING if (currChar === "$") { currState = IN_ENV_VAR; envVarStartIndex = currIdx + 1; } else { modifiedString.push(currChar); } } if (currState === IN_ENV_VAR) { const newVariable = inputString.substring( envVarStartIndex, inputString.length ); if (newVariable !== "") { detectedVariables.add(newVariable); modifiedString.push("{" + newVariable + "}"); } else { modifiedString.push("$"); } } return [detectedVariables, modifiedString.join("")]; } export const _toPython = ( request: Request, warnings: Warnings = [] ): string => { const imports: Set<string> = new Set(); // Currently, only assuming that the env-var only used in // the value part of cookies, params, or body const osVariables = new Set(); const commentedOutHeaders: { [key: string]: string } = { // TODO: add a warning why this should be commented out? "accept-encoding": "", "content-length": "", }; // https://github.com/icing/blog/blob/main/curl_on_a_weekend.md if (util.getHeader(request, "te") === "trailers") { commentedOutHeaders.te = "Requests doesn't support trailers"; } let cookieStr; if (request.cookies) { // TODO: could have repeat cookies cookieStr = "cookies = {\n"; for (const [cookieName, cookieValue] of request.cookies) { const [detectedVars, modifiedString] = detectEnvVar(cookieValue); const hasEnvironmentVariable = detectedVars.size > 0; for (const newVar of detectedVars) { osVariables.add(newVar); } cookieStr += " " + repr(cookieName) + ": " + reprWithVariable(modifiedString, hasEnvironmentVariable) + ",\n"; } cookieStr += "}\n"; // TODO: cookieStr should too, to avoid surprises. // This will stop being the case in Python 3.11 // https://github.com/python/cpython/issues/86232 commentedOutHeaders.cookie = request.cookies.length > 1 ? "Requests sorts cookies= alphabetically" : ""; if (request.cookieFiles) { warnings.push([ "cookie-files", "passing both cookies and cookie files is not supported", ]); } } else if (request.cookieFiles && request.cookieFiles.length) { // TODO: what if user passes multiple cookie files? // TODO: what if user passes cookies and cookie files? const cookieFile = request.cookieFiles[request.cookieFiles.length - 1]; imports.add("http"); // TODO: do we need to .load()? cookieStr = "cookies = http.cookiejar.MozillaCookieJar(" + repr(cookieFile) + ")\n"; } let proxyDict; if (request.proxy) { const proxy = request.proxy.includes("://") ? request.proxy : "http://" + request.proxy; const protocol = proxy.split("://")[0].toLowerCase(); proxyDict = "proxies = {\n"; switch (protocol) { case "http": case "https": // TODO: hopefully including both is right proxyDict += " 'http': " + repr(proxy) + ",\n"; proxyDict += " 'https': " + repr(proxy) + ",\n"; break; case "socks": proxyDict += " 'socks4': " + repr(proxy) + ",\n"; break; case "socks4": case "socks5": case "socks5h": case "socks4a": default: proxyDict += " '" + protocol + "': " + repr(proxy) + ",\n"; break; // default: // throw new CCError('Unsupported proxy scheme for ' + repr(request.proxy)) } proxyDict += "}\n"; } let certStr; if (request.cert) { certStr = "cert = "; if (Array.isArray(request.cert)) { certStr += "(" + request.cert.map(repr).join(", ") + ")"; } else { certStr += repr(request.cert); } certStr += "\n"; } let queryStr; if (request.query) { queryStr = "params = " + objToDictOrListOfTuples(request.queryDict || request.query) + "\n"; } const contentType = util.getHeader(request, "content-type"); let dataString; let usesStdin = false; let jsonDataString; let jsonDataStringRoundtrips; let filesString; if (request.uploadFile) { // If you mix --data and --upload-file, it gets weird. content-length will // be from --data but the data will be from --upload-file if (request.uploadFile === "-" || request.uploadFile === ".") { dataString = "data = sys.stdin.buffer.read()\n"; usesStdin = true; } else { dataString = "with open(" + repr(request.uploadFile) + ", 'rb') as f:\n"; dataString += " data = f.read()\n"; } } else if (request.data) { [dataString, usesStdin, jsonDataString, jsonDataStringRoundtrips] = getDataString(request); // Remove "Content-Type" from the headers dict // because Requests adds it automatically when you use json= if ( jsonDataString && contentType && contentType.trim() === "application/json" ) { commentedOutHeaders["content-type"] = "Already added when you pass json="; if (!jsonDataStringRoundtrips) { commentedOutHeaders["content-type"] += " but not when you pass data="; } } } else if (request.multipartUploads) { [filesString, usesStdin] = getFilesString(request); // If you pass files= then Requests adds this header and a `boundary` // If you manually pass a Content-Type header it won't set a `boundary` // wheras curl does, so the request will fail. // https://github.com/curlconverter/curlconverter/issues/248 if ( filesString && contentType && contentType.trim() === "multipart/form-data" && !contentType.includes("boundary=") ) { // TODO: better wording commentedOutHeaders["content-type"] = "requests won't add a boundary if this header is set when you pass files="; } } if (usesStdin) { imports.add("sys"); } let headerDict; if (request.headers && request.headers.length) { // TODO: what if there are repeat headers headerDict = "headers = {\n"; for (const [headerName, headerValue] of request.headers) { if (headerValue === null) { continue; } const [detectedVars, modifiedString] = detectEnvVar(headerValue); const hasVariable = detectedVars.size > 0; for (const newVar of detectedVars) { osVariables.add(newVar); } let lineStart; if (util.has(commentedOutHeaders, headerName.toLowerCase())) { if (commentedOutHeaders[headerName.toLowerCase()]) { headerDict += " # " + commentedOutHeaders[headerName.toLowerCase()] + "\n"; } lineStart = " # "; } else { lineStart = " "; } headerDict += lineStart + repr(headerName) + ": " + reprWithVariable(modifiedString, hasVariable) + ",\n"; } headerDict += "}\n"; if ( request.headers.length > 1 && request.headers.every((h) => h[0] === h[0].toLowerCase()) && !(request.http2 || request.http3) ) { warnings.push([ "--header", "all the --header/-H names are lowercase, which means this may have been an HTTP/2 or HTTP/3 request. Requests only sends HTTP/1.1", ]); } } let requestLine; if ( ["GET", "HEAD", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"].includes( request.method ) ) { requestLine = "response = requests." + request.method.toLowerCase() + "(" + repr(request.urlWithoutQuery); } else { // If the method wasn't uppercase, Requests will uppercase it anyway, but we write it out in its original case requestLine = "response = requests.request(" + repr(request.method) + ", " + repr(request.urlWithoutQuery); } let requestLineBody = ""; if (request.query) { requestLineBody += ", params=params"; } if (cookieStr) { requestLineBody += ", cookies=cookies"; } if (request.headers && request.headers.length) { requestLineBody += ", headers=headers"; } if (request.data || request.uploadFile) { if (jsonDataString) { requestLineBody += ", json=json_data"; } else { requestLineBody += ", data=data"; } } else if (request.multipartUploads) { requestLineBody += ", files=files"; } if (request.proxy) { requestLineBody += ", proxies=proxies"; } if (request.cert) { requestLineBody += ", cert=cert"; } if (request.insecure) { requestLineBody += ", verify=False"; } else if (request.cacert || request.capath) { requestLineBody += ", verify=" + repr((request.cacert || request.capath) as string); } if (request.auth) { const [user, password] = request.auth; const authClass = request.digest ? "HTTPDigestAuth" : ""; requestLineBody += ", auth=" + authClass + "(" + repr(user) + ", " + repr(password) + ")"; } requestLineBody += ")"; requestLine += requestLineBody; let pythonCode = ""; if (osVariables.size > 0) { imports.add("os"); } if (imports.size) { for (const imp of Array.from(imports).sort()) { pythonCode += "import " + imp + "\n"; } pythonCode += "\n"; } pythonCode += "import requests\n"; if (request.auth && request.digest) { pythonCode += "from requests.auth import HTTPDigestAuth\n"; } pythonCode += "\n"; if (osVariables.size > 0) { for (const osVar of osVariables) { const line = `${osVar} = os.getenv('${osVar}')\n`; pythonCode += line; } pythonCode += "\n"; } if (proxyDict) { pythonCode += proxyDict + "\n"; } if (cookieStr) { pythonCode += cookieStr + "\n"; } if (headerDict) { pythonCode += headerDict + "\n"; } if (queryStr) { pythonCode += queryStr + "\n"; } if (certStr) { pythonCode += certStr + "\n"; } if (jsonDataString) { pythonCode += jsonDataString + "\n"; } else if (dataString) { pythonCode += dataString + "\n"; } else if (filesString) { pythonCode += filesString + "\n"; } pythonCode += requestLine; if (jsonDataString && !jsonDataStringRoundtrips) { pythonCode += "\n\n" + "# Note: json_data will not be serialized by requests\n" + "# exactly as it was in the original request.\n"; pythonCode += "#" + dataString; pythonCode += "#" + requestLine.replace(", json=json_data", ", data=data"); } if (request.output && request.output !== "/dev/null") { if (request.output === "-") { pythonCode += "\nprint(response.text)"; } else { pythonCode += "\n\nwith open(" + repr(request.output) + ", 'wb') as f:\n f.write(response.content)"; } } if (request.http2) { warnings.push([ "http2", "this was an HTTP/2 request but requests only supports HTTP/1.1", ]); } if (request.http3) { warnings.push([ "http3", "this was an HTTP/3 request but requests only supports HTTP/1.1", ]); } return pythonCode + "\n"; }; export const toPythonWarn = ( curlCommand: string | string[], warnings: Warnings = [] ): [string, Warnings] => { const request = util.parseCurlCommand(curlCommand, supportedArgs, warnings); const python = _toPython(request, warnings); return [python, warnings]; }; export const toPython = (curlCommand: string | string[]): string => { return toPythonWarn(curlCommand)[0]; };
the_stack