text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import React, { useCallback, useRef, ReactNode, HTMLProps, MutableRefObject, CSSProperties, } from 'react'; import { useTable, usePagination, useSortBy, useGlobalFilter, PluginHook, TableOptions, FilterType, IdType, Row, } from 'react-table'; import { matchSorter, rankings } from 'match-sorter'; import GlobalFilter, { GlobalFilterProps } from './components/GlobalFilter'; import SelectPageSize, { SelectPageSizeProps, SizeOption, } from './components/SelectPageSize'; import SimplePagination from './components/Pagination'; import useSticky from './hooks/useSticky'; import { PAGE_SIZE_OPTIONS } from '../consts'; import { sortAlphanumericCaseInsensitive } from './utils/sortAlphanumericCaseInsensitive'; export interface DataTableProps<D extends object> extends TableOptions<D> { tableClassName?: string; searchInput?: boolean | GlobalFilterProps<D>['searchInput']; selectPageSize?: boolean | SelectPageSizeProps['selectRenderer']; pageSizeOptions?: SizeOption[]; // available page size options maxPageItemCount?: number; hooks?: PluginHook<D>[]; // any additional hooks width?: string | number; height?: string | number; serverPagination?: boolean; onServerPaginationChange: (pageNumber: number, pageSize: number) => void; serverPaginationData: { pageSize?: number; currentPage?: number }; pageSize?: number; noResults?: string | ((filterString: string) => ReactNode); sticky?: boolean; rowCount: number; wrapperRef?: MutableRefObject<HTMLDivElement>; } export interface RenderHTMLCellProps extends HTMLProps<HTMLTableCellElement> { cellContent: ReactNode; } const sortTypes = { alphanumeric: sortAlphanumericCaseInsensitive, }; // Be sure to pass our updateMyData and the skipReset option export default function DataTable<D extends object>({ tableClassName, columns, data, serverPaginationData, width: initialWidth = '100%', height: initialHeight = 300, pageSize: initialPageSize = 0, initialState: initialState_ = {}, pageSizeOptions = PAGE_SIZE_OPTIONS, maxPageItemCount = 9, sticky: doSticky, searchInput = true, onServerPaginationChange, rowCount, selectPageSize, noResults: noResultsText = 'No data found', hooks, serverPagination, wrapperRef: userWrapperRef, ...moreUseTableOptions }: DataTableProps<D>): JSX.Element { const tableHooks: PluginHook<D>[] = [ useGlobalFilter, useSortBy, usePagination, doSticky ? useSticky : [], hooks || [], ].flat(); const resultsSize = serverPagination ? rowCount : data.length; const sortByRef = useRef([]); // cache initial `sortby` so sorting doesn't trigger page reset const pageSizeRef = useRef([initialPageSize, resultsSize]); const hasPagination = initialPageSize > 0 && resultsSize > 0; // pageSize == 0 means no pagination const hasGlobalControl = hasPagination || !!searchInput; const initialState = { ...initialState_, // zero length means all pages, the `usePagination` plugin does not // understand pageSize = 0 sortBy: sortByRef.current, pageSize: initialPageSize > 0 ? initialPageSize : resultsSize || 10, }; const defaultWrapperRef = useRef<HTMLDivElement>(null); const globalControlRef = useRef<HTMLDivElement>(null); const paginationRef = useRef<HTMLDivElement>(null); const wrapperRef = userWrapperRef || defaultWrapperRef; const paginationData = JSON.stringify(serverPaginationData); const defaultGetTableSize = useCallback(() => { if (wrapperRef.current) { // `initialWidth` and `initialHeight` could be also parameters like `100%` // `Number` reaturns `NaN` on them, then we fallback to computed size const width = Number(initialWidth) || wrapperRef.current.clientWidth; const height = (Number(initialHeight) || wrapperRef.current.clientHeight) - (globalControlRef.current?.clientHeight || 0) - (paginationRef.current?.clientHeight || 0); return { width, height }; } return undefined; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ initialHeight, initialWidth, wrapperRef, hasPagination, hasGlobalControl, paginationRef, resultsSize, paginationData, ]); const defaultGlobalFilter: FilterType<D> = useCallback( (rows: Row<D>[], columnIds: IdType<D>[], filterValue: string) => { // allow searching by "col1_value col2_value" const joinedString = (row: Row<D>) => columnIds.map(x => row.values[x]).join(' '); return matchSorter(rows, filterValue, { keys: [...columnIds, joinedString], threshold: rankings.ACRONYM, }) as typeof rows; }, [], ); const { getTableProps, getTableBodyProps, prepareRow, headerGroups, footerGroups, page, pageCount, gotoPage, preGlobalFilteredRows, setGlobalFilter, setPageSize: setPageSize_, wrapStickyTable, state: { pageIndex, pageSize, globalFilter: filterValue, sticky = {} }, } = useTable<D>( { columns, data, initialState, getTableSize: defaultGetTableSize, globalFilter: defaultGlobalFilter, sortTypes, ...moreUseTableOptions, }, ...tableHooks, ); // make setPageSize accept 0 const setPageSize = (size: number) => { if (serverPagination) { onServerPaginationChange(0, size); } // keep the original size if data is empty if (size || resultsSize !== 0) { setPageSize_(size === 0 ? resultsSize : size); } }; const noResults = typeof noResultsText === 'function' ? noResultsText(filterValue as string) : noResultsText; const getNoResults = () => <div className="dt-no-results">{noResults}</div>; if (!columns || columns.length === 0) { return ( wrapStickyTable ? wrapStickyTable(getNoResults) : getNoResults() ) as JSX.Element; } const shouldRenderFooter = columns.some(x => !!x.Footer); const renderTable = () => ( <table {...getTableProps({ className: tableClassName })}> <thead> {headerGroups.map(headerGroup => { const { key: headerGroupKey, ...headerGroupProps } = headerGroup.getHeaderGroupProps(); return ( <tr key={headerGroupKey || headerGroup.id} {...headerGroupProps}> {headerGroup.headers.map(column => column.render('Header', { key: column.id, ...column.getSortByToggleProps(), }), )} </tr> ); })} </thead> <tbody {...getTableBodyProps()}> {page && page.length > 0 ? ( page.map(row => { prepareRow(row); const { key: rowKey, ...rowProps } = row.getRowProps(); return ( <tr key={rowKey || row.id} {...rowProps}> {row.cells.map(cell => cell.render('Cell', { key: cell.column.id }), )} </tr> ); }) ) : ( <tr> <td className="dt-no-results" colSpan={columns.length}> {noResults} </td> </tr> )} </tbody> {shouldRenderFooter && ( <tfoot> {footerGroups.map(footerGroup => { const { key: footerGroupKey, ...footerGroupProps } = footerGroup.getHeaderGroupProps(); return ( <tr key={footerGroupKey || footerGroup.id} {...footerGroupProps}> {footerGroup.headers.map(column => column.render('Footer', { key: column.id }), )} </tr> ); })} </tfoot> )} </table> ); // force update the pageSize when it's been update from the initial state if ( pageSizeRef.current[0] !== initialPageSize || // when initialPageSize stays as zero, but total number of records changed, // we'd also need to update page size (initialPageSize === 0 && pageSizeRef.current[1] !== resultsSize) ) { pageSizeRef.current = [initialPageSize, resultsSize]; setPageSize(initialPageSize); } const paginationStyle: CSSProperties = sticky.height ? {} : { visibility: 'hidden' }; let resultPageCount = pageCount; let resultCurrentPageSize = pageSize; let resultCurrentPage = pageIndex; let resultOnPageChange: (page: number) => void = gotoPage; if (serverPagination) { const serverPageSize = serverPaginationData.pageSize ?? initialPageSize; resultPageCount = Math.ceil(rowCount / serverPageSize); if (!Number.isFinite(resultPageCount)) { resultPageCount = 0; } resultCurrentPageSize = serverPageSize; const foundPageSizeIndex = pageSizeOptions.findIndex( ([option]) => option >= resultCurrentPageSize, ); if (foundPageSizeIndex === -1) { resultCurrentPageSize = 0; } resultCurrentPage = serverPaginationData.currentPage ?? 0; resultOnPageChange = (pageNumber: number) => onServerPaginationChange(pageNumber, serverPageSize); } return ( <div ref={wrapperRef} style={{ width: initialWidth, height: initialHeight }} > {hasGlobalControl ? ( <div ref={globalControlRef} className="form-inline dt-controls"> <div className="row"> <div className="col-sm-6"> {hasPagination ? ( <SelectPageSize total={resultsSize} current={resultCurrentPageSize} options={pageSizeOptions} selectRenderer={ typeof selectPageSize === 'boolean' ? undefined : selectPageSize } onChange={setPageSize} /> ) : null} </div> {searchInput ? ( <div className="col-sm-6"> <GlobalFilter<D> searchInput={ typeof searchInput === 'boolean' ? undefined : searchInput } preGlobalFilteredRows={preGlobalFilteredRows} setGlobalFilter={setGlobalFilter} filterValue={filterValue} /> </div> ) : null} </div> </div> ) : null} {wrapStickyTable ? wrapStickyTable(renderTable) : renderTable()} {hasPagination && resultPageCount > 1 ? ( <SimplePagination ref={paginationRef} style={paginationStyle} maxPageItemCount={maxPageItemCount} pageCount={resultPageCount} currentPage={resultCurrentPage} onPageChange={resultOnPageChange} /> ) : null} </div> ); }
the_stack
import { expect } from 'chai'; import { $, $$ } from 'common-sk/modules/dom'; import sinon from 'sinon'; import { setUpElementUnderTest, eventPromise, noEventPromise, eventSequencePromise, expectQueryStringToEqual, setQueryString, } from './test_util'; describe('test utilities', () => { describe('setUpElementUnderTest', () => { // We'll save references to the instances of the element under test created // by setUpElementUnderTest, and make assertions against them later on. let instance1: HTMLMarqueeElement; let instance2: HTMLMarqueeElement; // We run setUpElementUnderTest inside its own nested describe block to // limit the scope of the afterEach hook it sets up. describe('test suite with setUpElementUnderTest', () => { // We'll use <marquee> as the element under test. const newInstance = setUpElementUnderTest<HTMLMarqueeElement>('marquee'); let element: HTMLMarqueeElement; // Instance of the element under test. beforeEach(() => { expect( $('marquee'), 'no other <marquee> elements should be present in the DOM ' + 'prior to instantiating the element under test', ) .to.have.length(0); // Instantiate the element under test. element = newInstance((el) => el.innerHTML = '<p>hello world</p>'); }); afterEach(() => { expect( $('marquee'), 'no instances of the element under test should be found in ' + 'the DOM after each test case', ) .to.have.length(0); expect( element.parentElement, 'element under test should be detached from its parent node ' + 'after each test case', ) .to.be.null; }); it('should correctly instantiate the element', () => { instance1 = element; // Save a reference to the current instance. expect(element.tagName).to.equal('MARQUEE'); expect($$<HTMLParagraphElement>('p', element)!.innerText).to.equal('hello world'); }); it('should attach instance of element under test to document.body', () => { instance2 = element; // Save a reference to the current instance. expect($('marquee')).to.have.length(1); expect(element.parentElement).to.equal(document.body); }); }); // This describe block makes use of the fact that sibling describe blocks // are run in the order they are defined, as explained in // https://mochajs.org/#run-cycle-overview. describe('after the "setUpElementUnderTest" test suite runs', () => { // Assert that we've correctly captured the instances of the element under // test, which the test cases below rely on. it('should have correctly saved instances of the element under test', () => { expect(instance1.tagName).to.equal('MARQUEE'); expect(instance2.tagName).to.equal('MARQUEE'); }); it('creates fresh instances before each test case', () => { expect(instance1).to.not.equal(instance2); }); it('should detach instances from the DOM after each test case', () => { expect(instance1.parentElement).to.be.null; expect(instance2.parentElement).to.be.null; }); it('no stray instances left on the test runner page after tests end', () => { expect($('marquee')).to.have.length(0); }); }); }); describe('event promise functions', () => { let el: HTMLDivElement; // Element that we'll dispatch custom events from. let clock: sinon.SinonFakeTimers; beforeEach(() => { el = document.createElement('div'); document.body.appendChild(el); clock = sinon.useFakeTimers(); }); afterEach(() => { document.body.removeChild(el); clock.restore(); }); describe('eventPromise', () => { it('resolves when event is caught', async () => { const hello = eventPromise<CustomEvent<string>>('hello'); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); const ev = await hello; expect(ev.detail).to.equal('hi'); }); it('catches document-level events', async () => { const hello = eventPromise<CustomEvent<string>>('hello'); document.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); const ev = await hello; expect(ev.detail).to.equal('hi'); }); it('one single event resolves multiple promises', async () => { const hello1 = eventPromise<CustomEvent<string>>('hello'); const hello2 = eventPromise<CustomEvent<string>>('hello'); // We'll emit two different events of the same type (see event detail). el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'goodbye' })); const ev1 = await hello1; const ev2 = await hello2; // The first event above should resolve both promises. expect(ev1.detail).to.equal('hi'); expect(ev2.detail).to.equal('hi'); }); it('times out if event is not caught', async () => { const hello = eventPromise<CustomEvent<string>>('hello', 5000); el.dispatchEvent(new CustomEvent('bye', { bubbles: true })); clock.tick(10000); try { await hello; expect.fail('promise should not have resolved'); } catch (error) { expect(error.message).to.equal( 'timed out after 5000 ms while waiting to catch event "hello"', ); } }); it('never times out if timeoutMillis=0', async () => { const hello = eventPromise<CustomEvent<string>>('hello', 0); clock.tick(Number.MAX_SAFE_INTEGER); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); const ev = await hello; expect(ev.detail).to.equal('hi'); }); }); describe('noEventPromise', () => { it('resolves when event is NOT caught', async () => { const noHello = noEventPromise('hello', 200); el.dispatchEvent(new CustomEvent('bye', { bubbles: true })); clock.tick(10000); await noHello; }); it('rejects if event is caught', async () => { const noHello = noEventPromise('hello', 200); el.dispatchEvent(new CustomEvent('hello', { bubbles: true })); try { await noHello; expect.fail('promise should not have resolved'); } catch (error) { expect(error.message).to.equal( 'event "hello" was caught when none was expected', ); } }); it('never resolves if timeoutMillis=0', async () => { const noHello = noEventPromise('hello', 0); clock.tick(Number.MAX_SAFE_INTEGER); el.dispatchEvent(new CustomEvent('hello', { bubbles: true })); try { await noHello; expect.fail('promise should not have resolved'); } catch (error) { expect(error.message).to.equal( 'event "hello" was caught when none was expected', ); } }); }); describe('eventSequencePromise', () => { it('resolves immediately if the event sequence is empty', async () => { expect(await eventSequencePromise([])).to.have.length(0); }); it('catches one event', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello']); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); const events = await sequence; expect(events).to.have.length(1); expect(events[0].detail).to.equal('hi'); }); it('catches a sequence of events', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello', 'world', 'goodbye']); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'first' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'second' })); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'third' })); const events = await sequence; expect(events).to.have.length(3); expect(events[0].detail).to.equal('first'); expect(events[1].detail).to.equal('second'); expect(events[2].detail).to.equal('third'); }); it('catches a sequence with repeated events', async () => { const sequence = eventSequencePromise<CustomEvent<string>>([ 'hey', 'hey', 'hello', 'world', 'hey', 'world', 'goodbye', ]); el.dispatchEvent(new CustomEvent('hey', { bubbles: true, detail: 'first' })); el.dispatchEvent(new CustomEvent('hey', { bubbles: true, detail: 'second' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'third' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'fourth' })); el.dispatchEvent(new CustomEvent('hey', { bubbles: true, detail: 'fifth' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'sixth' })); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'seventh' })); const events = await sequence; expect(events).to.have.length(7); expect(events[0].detail).to.equal('first'); expect(events[1].detail).to.equal('second'); expect(events[2].detail).to.equal('third'); expect(events[3].detail).to.equal('fourth'); expect(events[4].detail).to.equal('fifth'); expect(events[5].detail).to.equal('sixth'); expect(events[6].detail).to.equal('seventh'); }); it('ignores out-of-sequence events', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello', 'world', 'goodbye']); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'first' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'second' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'third' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'fourth' })); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'fifth' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'sixth' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'seventh' })); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'eigth' })); const events = await sequence; expect(events).to.have.length(3); expect(events[0].detail).to.equal('third'); expect(events[1].detail).to.equal('sixth'); expect(events[2].detail).to.equal('eigth'); }); it('does not catch incomplete sequences', async () => { const sequence = eventSequencePromise<CustomEvent<string>>([ 'i', 'am', 'a', 'very', 'long', 'event', 'sequence']); el.dispatchEvent(new CustomEvent('i', { bubbles: true, detail: 'first' })); el.dispatchEvent(new CustomEvent('am', { bubbles: true, detail: 'second' })); clock.tick(10000); try { await sequence; expect.fail('promise should not have resolved'); } catch (error) { expect(error).to.equal( 'timed out after 200 ms while waiting to catch events ' + '"a", "very", "long", "event", "sequence"', ); } }); it('does not catch permutations', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello', 'world', 'goodbye']); el.dispatchEvent(new CustomEvent('goodbye', { bubbles: true, detail: 'first' })); el.dispatchEvent(new CustomEvent('world', { bubbles: true, detail: 'second' })); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'third' })); clock.tick(10000); try { await sequence; expect.fail('promise should not have resolved'); } catch (error) { expect(error).to.equal( 'timed out after 200 ms while waiting to catch events "world", "goodbye"', ); } }); it('times out if nothing is caught', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello']); clock.tick(10000); try { await sequence; expect.fail('promise should not have resolved'); } catch (error) { expect(error).to.equal( 'timed out after 200 ms while waiting to catch events "hello"', ); } }); it('never times out if timeoutMillis=0', async () => { const sequence = eventSequencePromise<CustomEvent<string>>(['hello'], 0); clock.tick(Number.MAX_SAFE_INTEGER); el.dispatchEvent(new CustomEvent('hello', { bubbles: true, detail: 'hi' })); const events = await sequence; expect(events).to.have.length(1); expect(events[0].detail).to.equal('hi'); }); }); }); describe('expectQueryStringToEqual', () => { it('matches empty string when query is empty', () => { history.pushState(null, '', // these are empty as they do not affect the test. window.location.origin + window.location.pathname); expectQueryStringToEqual(''); }); it('matches the query params when query is not emtpy', () => { // reset to known blank state history.pushState(null, '', // these are empty as they do not affect the test. window.location.origin + window.location.pathname); // push some query params history.pushState(null, '', '?foo=bar&alpha=beta&alpha=gamma'); expectQueryStringToEqual('?foo=bar&alpha=beta&alpha=gamma'); }); }); describe('setQueryString', () => { it('can set the query to be empty', () => { setQueryString(''); expectQueryStringToEqual(''); }); it('can set the query to be not empty', () => { setQueryString('?alpha=beta'); expectQueryStringToEqual('?alpha=beta'); }); }); });
the_stack
import { expect } from "chai"; import TestUtils from "../../../../TestUtils"; import { FlatGridItemType, IMutableCategorizedPropertyItem, IMutableFlatGridItem, IMutableGridCategoryItem } from "../../../../../components-react/propertygrid/internal/flat-items/MutableFlatGridItem"; import { FlatGridTestUtils as GridUtils } from "./FlatGridTestUtils"; import sinon from "sinon"; import { PropertyRecord } from "@itwin/appui-abstract"; import { MutableGridItemFactory } from "../../../../../components-react/propertygrid/internal/flat-items/MutableGridItemFactory"; import { MutableGridCategory } from "../../../../../components-react/propertygrid/internal/flat-items/MutableGridCategory"; import { PropertyCategory } from "../../../../../components-react/propertygrid/PropertyDataProvider"; import { GridCategoryItem } from "../../../../../components-react/propertygrid/internal/flat-items/FlatGridItem"; describe("GridCategory", () => { describe("GridCategory Mocked", () => { let factoryStub: sinon.SinonStubbedInstance<MutableGridItemFactory>; beforeEach(() => { factoryStub = sinon.createStubInstance(MutableGridItemFactory); }); describe("Should correctly initialize grid category", () => { it("Should correctly initialize categorized array property", () => { const category = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); expect(() => new MutableGridCategory(category, recordsDict, factoryStub, "Cat0", -1)).to.throw(Error, "Depth cannot be negative"); }); it("Should correctly initialize grid category with no children", () => { const category = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); expect(factoryStub.createCategorizedProperty.callCount).to.be.equal(0); expect(factoryStub.createGridCategory.callCount).to.be.equal(0); expect(gridCategory.parentSelectionKey).to.be.undefined; expect(gridCategory.parentCategorySelectionKey).to.be.undefined; GridUtils.assertCategoryEquals(gridCategory, category); expect(gridCategory.depth).to.be.equal(0); }); it("Should correctly initialize grid category with no children and parent", () => { const category = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub, "Cat0", 1); expect(factoryStub.createCategorizedProperty.callCount).to.be.equal(0); expect(factoryStub.createGridCategory.callCount).to.be.equal(0); expect(gridCategory.parentSelectionKey).to.be.equal("Cat0"); expect(gridCategory.parentCategorySelectionKey).to.be.equal("Cat0"); GridUtils.assertCategoryEquals(gridCategory, category); expect(gridCategory.depth).to.be.equal(1); }); it("Should correctly initialize grid category with children categories", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories: [ { name: "Cat1_1", label: "Cat 1_1", expand: false }, { name: "Cat1_1", label: "Cat 1_1", expand: false }, ], }; const expectedRecordsDict = GridUtils.constructCategoryRecordsDict([category]); GridUtils.createGridCategoryStub(category, factoryStub); new MutableGridCategory(category, expectedRecordsDict, factoryStub); const children = category.childCategories!; expect(factoryStub.createGridCategory.callCount).to.be.equal(children.length); expect(factoryStub.createCategorizedProperty.callCount).to.be.equal(0); factoryStub.createGridCategory.args.forEach((args, index) => { const [childCategory, recordsDict, parentCategorySelectionKey, depth] = args; const expectedCategory = children[index]; expect(childCategory).to.be.equal(expectedCategory); expect(recordsDict).to.be.equal(expectedRecordsDict); expect(depth).to.be.equal(1); expect(parentCategorySelectionKey).to.be.equal("Cat1"); }); }); it("Should correctly initialize grid category with record children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const expectedRecordsDict = GridUtils.constructCategoryRecordsDict([category]); const recordChildren = [ TestUtils.createPrimitiveStringProperty("CADID1_1", "V1"), TestUtils.createStructProperty("CADID1_2"), TestUtils.createArrayProperty("CADID1_3"), ]; expectedRecordsDict[category.name] = recordChildren; GridUtils.createCategorizedPropertyStub(recordChildren, factoryStub); new MutableGridCategory(category, expectedRecordsDict, factoryStub); expect(factoryStub.createGridCategory.callCount).to.be.equal(0); expect(factoryStub.createCategorizedProperty.callCount).to.be.equal(recordChildren.length); factoryStub.createCategorizedProperty.args.forEach((args, index) => { const [record, parentSelectionKey, parentCategorySelectionKey, depth] = args; const expectedRecord = recordChildren[index]; expect(parentSelectionKey).to.be.equal("Cat1"); expect(parentCategorySelectionKey).to.be.equal("Cat1"); expect(depth).to.be.equal(0); expect(record).to.be.equal(expectedRecord); }); }); }); describe("isExpanded", () => { function testIsExpanded(expectedIsExpanded: boolean) { it(`isExpanded should return ${expectedIsExpanded} when PropertyCategory expand: ${expectedIsExpanded}`, () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: expectedIsExpanded }; const expectedRecordsDict = GridUtils.constructCategoryRecordsDict([category]); const gridCategory = new MutableGridCategory(category, expectedRecordsDict, factoryStub); expect(gridCategory.isExpanded).to.be.equal(expectedIsExpanded); }); it(`isExpanded should return ${expectedIsExpanded} when isExpanded is set to: ${expectedIsExpanded}`, () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: !expectedIsExpanded }; const expectedRecordsDict = GridUtils.constructCategoryRecordsDict([category]); const gridCategory = new MutableGridCategory(category, expectedRecordsDict, factoryStub); gridCategory.isExpanded = expectedIsExpanded; expect(gridCategory.isExpanded).to.be.equal(expectedIsExpanded); }); } testIsExpanded(false); testIsExpanded(true); }); describe("getSelf", () => { it("Should return self when getSelf called on grid category", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); const self = gridCategory.getSelf(); expect(self).to.be.equal(gridCategory); }); }); describe("Grid category parent-child tests", () => { let childRecords: PropertyRecord[]; let childCategories: PropertyCategory[]; beforeEach(() => { childCategories = [ { name: "Cat1_1", label: "Cat 1_1", expand: false }, { name: "Cat1_1", label: "Cat 1_1", expand: false }, ]; childRecords = [ TestUtils.createPrimitiveStringProperty("CADID1_1", "V1"), TestUtils.createStructProperty("CADID1_2"), TestUtils.createArrayProperty("CADID1_3"), ]; }); describe("getChildren", () => { it("Should return empty array when grid category has no children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); GridUtils.createGridCategoryStub(category, factoryStub); GridUtils.createCategorizedPropertyStub([], factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); const children = gridCategory.getChildren(); expect(children).to.deep.equal([]); }); it("Should return expected array of children when grid category has child categories", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); GridUtils.createCategorizedPropertyStub([], factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); const children = gridCategory.getChildren(); expect(children).to.deep.equal(expectedCategories); }); it("Should return expected array of children when grid category has child records", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); const children = gridCategory.getChildren(); expect(children).to.deep.equal(expectedProperties); }); it("Should return expected array of children when grid category has child records and categories", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); const children = gridCategory.getChildren(); expect(children).to.deep.equal([...expectedProperties, ...expectedCategories]); }); }); describe("getDescendantsAndSelf", () => { it("Should return empty array when grid category has no children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); GridUtils.createGridCategoryStub(category, factoryStub); GridUtils.createCategorizedPropertyStub([], factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory]); }); it("Should return descendants when getDescendantsAndSelf called on grid category with children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedDescendants } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory, ...expectedDescendants]); }); it("Should return descendants when getDescendantsAndSelf called on grid category with children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedDescendants } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = false; expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory, ...expectedDescendants]); gridCategory.isExpanded = true; expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory, ...expectedDescendants]); }); }); describe("getVisibleDescendantsAndSelf", () => { it("Should return self when called on grid category with no children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); GridUtils.createGridCategoryStub(category, factoryStub); GridUtils.createCategorizedPropertyStub([], factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = false; expect(gridCategory.getVisibleDescendantsAndSelf()).to.deep.equal([gridCategory]); gridCategory.isExpanded = true; expect(gridCategory.getVisibleDescendantsAndSelf()).to.deep.equal([gridCategory]); }); it("Should return self when grid category not expanded and has children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = false; expect(gridCategory.getVisibleDescendantsAndSelf()).to.deep.equal([gridCategory]); }); it("Should return visible descendants when grid category expanded and has children without descendants", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedVisibleDescendants } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], []); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = true; expect(gridCategory.getVisibleDescendantsAndSelf()).to.deep.equal([gridCategory, ...expectedVisibleDescendants]); }); it("Should return visible descendants when grid category expanded and has children with descendants", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedVisibleDescendants } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = true; expect(gridCategory.getVisibleDescendantsAndSelf()).to.deep.equal([gridCategory, ...expectedVisibleDescendants]); }); }); describe("getLastVisibleDescendantOrSelf", () => { it("Should return self when called on grid category with no children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); GridUtils.createGridCategoryStub(category, factoryStub); GridUtils.createCategorizedPropertyStub([], factoryStub); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = false; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.deep.equal(gridCategory); gridCategory.isExpanded = true; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.deep.equal(gridCategory); }); it("Should return self when grid category not expanded and has children", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = false; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.deep.equal(gridCategory); }); it("Should return last visible descendant when grid category expanded and has children without descendants", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedLastVisibleDescendant } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], []); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = true; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.deep.equal(expectedLastVisibleDescendant); }); it("Should return last visible descendant when grid category expanded and has children with descendants", () => { const category: PropertyCategory = { name: "Cat1", label: "Cat 1", expand: false, childCategories }; const recordsDict = GridUtils.constructCategoryRecordsDict([category]); recordsDict[category.name] = childRecords; const expectedCategories = GridUtils.createGridCategoryStub(category, factoryStub); const expectedProperties = GridUtils.createCategorizedPropertyStub(childRecords, factoryStub); const { expectedLastVisibleDescendant } = GridUtils.setupExpectedDescendants([...expectedProperties, ...expectedCategories], [ { type: FlatGridItemType.Struct, isVisible: true }, { type: FlatGridItemType.Array, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: false }, { type: FlatGridItemType.Primitive, isVisible: true }, ]); const gridCategory = new MutableGridCategory(category, recordsDict, factoryStub); gridCategory.isExpanded = true; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.deep.equal(expectedLastVisibleDescendant); }); }); }); }); describe("GridCategory Integration", () => { let gridItemFactory: MutableGridItemFactory; beforeEach(() => { gridItemFactory = new MutableGridItemFactory(); }); describe("Should correctly initialize grid category", () => { const categoriesToTest: PropertyCategory[] = [ { name: "Category1", label: "Category 1", expand: false }, { name: "C", label: "Cat 1", expand: true }, { name: "Selected", label: "$élêçtèd Ítêm(s)", expand: true }, { name: "1", label: "1", expand: false }, ]; for (const propertyCategory of categoriesToTest) { const categoryStr = `Name: ${propertyCategory.name}, Label ${propertyCategory.label}, Expand: ${propertyCategory.expand}`; it(`Should correctly initialize grid category from property category: (${categoryStr})`, () => { const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); GridUtils.assertCategoryEquals(gridCategory, propertyCategory); expect(gridCategory.depth).to.be.equal(0); expect(gridCategory.isRootCategory).to.be.equal(true); expect(gridCategory.isExpanded).to.be.equal(propertyCategory.expand); expect(gridCategory.derivedCategory.expand).to.be.equal(propertyCategory.expand); expect(gridCategory.parentSelectionKey).to.be.equal(undefined); expect(gridCategory.parentCategorySelectionKey).to.be.equal(undefined); }); it(`Should correctly initialize grid category with parent: (${categoryStr})`, () => { const parentPropertyCategory = { name: "Category0", label: "Category 0", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory, parentPropertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory, "ParentCategory", 1); GridUtils.assertCategoryEquals(gridCategory, propertyCategory); expect(gridCategory.depth).to.be.equal(1); expect(gridCategory.isRootCategory).to.be.equal(false); expect(gridCategory.isExpanded).to.be.equal(propertyCategory.expand); expect(gridCategory.derivedCategory.expand).to.be.equal(propertyCategory.expand); expect(gridCategory.parentSelectionKey).to.be.equal("ParentCategory"); expect(gridCategory.parentCategorySelectionKey).to.be.equal("ParentCategory"); }); } }); it(`Should correctly set isExpanded property`, () => { const propertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const expectedExpand = !gridCategory.isExpanded; gridCategory.isExpanded = expectedExpand; expect(gridCategory.isExpanded).to.be.equal(expectedExpand); expect(gridCategory.derivedCategory.expand).to.be.equal(expectedExpand); }); function assertParentChildCategoryRelationship(gridCategory: IMutableGridCategoryItem, propertyCategory: PropertyCategory, parentSelectionKey?: string, expectedDepth: number = 0) { // Test current gridCategory against propertyCategory GridUtils.assertCategoryEquals(gridCategory, propertyCategory); expect(gridCategory.depth).to.be.equal(expectedDepth); expect(gridCategory.isRootCategory).to.be.equal(expectedDepth === 0); expect(gridCategory.parentSelectionKey).to.be.equal(parentSelectionKey); expect(gridCategory.parentCategorySelectionKey).to.be.equal(parentSelectionKey); // Test current gridCategory descendants against flattened propertyCategory // eslint-disable-next-line deprecation/deprecation const descendants = gridCategory.getDescendantCategoriesAndSelf(); const flattenedPropertyCategories = GridUtils.flattenPropertyCategories([propertyCategory], {}); expect(descendants.length).to.be.equal(flattenedPropertyCategories.length); descendants.forEach((descendant, index) => GridUtils.assertCategoryEquals(descendant, flattenedPropertyCategories[index].item as PropertyCategory)); // Test current gridCategory children parent-child category relationship (recursive) // eslint-disable-next-line deprecation/deprecation const childCategories = gridCategory.getChildCategories(); const childPropertyCategories = propertyCategory.childCategories ?? []; expect(childCategories.length).to.be.equal(childPropertyCategories.length); childCategories.forEach((childCategory, index) => assertParentChildCategoryRelationship(childCategory, childPropertyCategories[index], gridCategory.selectionKey, expectedDepth + 1)); } describe("Should correctly handle category to category parent-child relationship", () => { it(`Should correctly handle single child category`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true, childCategories: [ { name: "Category2", label: "Category 2", expand: false }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); // eslint-disable-next-line deprecation/deprecation const childCategories = gridCategory.getChildCategories(); expect(gridCategory.getChildren()).to.deep.equal(childCategories); // eslint-disable-next-line deprecation/deprecation expect(gridCategory.getDescendantCategoriesAndSelf()).to.deep.equal([gridCategory, ...childCategories]); expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory, ...childCategories]); assertParentChildCategoryRelationship(gridCategory, propertyCategory); }); it(`Should correctly handle multiple child categories`, () => { const propertyCategory: PropertyCategory = { name: "Category0", label: "Category 0", expand: true, childCategories: [ { name: "Category0_0", label: "Category 0_0", expand: false }, { name: "Category0_1", label: "Category 0_1", expand: true }, { name: "Category0_2", label: "Category 0_2", expand: false }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); // eslint-disable-next-line deprecation/deprecation const childCategories = gridCategory.getChildCategories(); expect(gridCategory.getChildren()).to.deep.equal(childCategories); // eslint-disable-next-line deprecation/deprecation expect(gridCategory.getDescendantCategoriesAndSelf()).to.deep.equal([gridCategory, ...childCategories]); expect(gridCategory.getDescendantsAndSelf()).to.deep.equal([gridCategory, ...childCategories]); assertParentChildCategoryRelationship(gridCategory, propertyCategory); }); it(`Should correctly handle deeply nested child categories`, () => { const propertyCategory: PropertyCategory = { name: "Category0", label: "Category 0", expand: true, childCategories: [ { name: "Category0_0", label: "Category 0_0", expand: false, childCategories: [ { name: "Category0_0_0", label: "Category 0_0_0", expand: true, childCategories: [ { name: "Category0_0_0_0", label: "Category 0_0_0_0", expand: false }, { name: "Category0_0_0_1", label: "Category 0_0_0_1", expand: false }, { name: "Category0_0_0_2", label: "Category 0_0_0_2", expand: false }, { name: "Category0_0_0_3", label: "Category 0_0_0_3", expand: false }, ], }, { name: "Category0_0_1", label: "Category 0_0_1", expand: true, childCategories: [ { name: "Category0_0_1_0", label: "Category 0_0_1_0", expand: false }, { name: "Category0_0_1_1", label: "Category 0_0_1_1", expand: false }, { name: "Category0_0_1_2", label: "Category 0_0_1_2", expand: false }, { name: "Category0_0_1_3", label: "Category 0_0_1_3", expand: false }, ], }, ], }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); assertParentChildCategoryRelationship(gridCategory, propertyCategory); }); }); function assertCategorizedProperties(categorizedProperties: IMutableCategorizedPropertyItem[], expectedPropertyRecords: PropertyRecord[]) { expect(categorizedProperties.length).to.be.equal(expectedPropertyRecords.length); categorizedProperties.forEach((categorizedProperty, index) => GridUtils.assertPropertyEquals(categorizedProperty, expectedPropertyRecords[index])); } function assertCategoryCategorizedProperties(gridCategory: IMutableGridCategoryItem, records: PropertyRecord[]) { // Compare category children records const categorizedProperties = GridUtils.filterProperties(gridCategory.getChildren()); assertCategorizedProperties(categorizedProperties, records); // Compare category descendant records const descendants = GridUtils.filterProperties(gridCategory.getDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey).map((record) => record.item); assertCategorizedProperties(descendants, flatRecords); } describe("Should correctly handle single category categorized property parent-child relationship", () => { it(`Should correctly handle primitive categorized properties`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); assertCategoryCategorizedProperties(gridCategory, records); }); it(`Should correctly handle struct categorized properties`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createStructProperty("Struct1", { CADID1: TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8") }), TestUtils.createStructProperty("Struct2", { CADID2: TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8") }), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); assertCategoryCategorizedProperties(gridCategory, records); }); it(`Should correctly handle array categorized properties`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createArrayProperty("Array1", []), TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), ]), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); assertCategoryCategorizedProperties(gridCategory, records); }); it(`Should correctly handle mixed categorized properties`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array0", []), TestUtils.createArrayProperty("Array1", [ TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), ]), TestUtils.createStructProperty("Struct1", { CADID5: TestUtils.createPrimitiveStringProperty("CADID5", "0000 0005 00E0 02D8"), CADID6: TestUtils.createPrimitiveStringProperty("CADID6", "0000 0005 00E0 02D8"), CADID7: TestUtils.createPrimitiveStringProperty("CADID7", "0000 0005 00E0 02D8"), Array2: TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID8", "0000 0005 00E0 02D8"), TestUtils.createStructProperty("Struct2", {}), ]), }), TestUtils.createStructProperty("Struct3", {}), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); assertCategoryCategorizedProperties(gridCategory, records); }); }); describe("Should correctly handle getting visible descendants", () => { it(`Should return self when getVisibleDescendantsAndSelf called and category not expanded`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1", [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), ], true), TestUtils.createStructProperty("Struct1", { CADID5: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), CADID6: TestUtils.createPrimitiveStringProperty("CADID5", "0000 0005 00E0 02D8"), CADID7: TestUtils.createPrimitiveStringProperty("CADID6", "0000 0005 00E0 02D8"), }, true), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = false; expect(gridCategory.getVisibleDescendantsAndSelf()).to.be.deep.equal([gridCategory]); }); it(`Should correctly handle no children visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; expect(gridCategory.getVisibleDescendantsAndSelf()).to.be.deep.equal([gridCategory]); }); it(`Should correctly handle primitive visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); it(`Should correctly handle non-nested struct visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [TestUtils.createStructProperty("Struct1"), TestUtils.createStructProperty("Struct2")]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); it(`Should correctly handle nested struct visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createStructProperty("Struct1", { CADID3: TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), CADID4: TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), }, false), TestUtils.createStructProperty("Struct2", { CADID3: TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), CADID4: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), Struct3: TestUtils.createStructProperty("Struct3"), }, true), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); it(`Should correctly handle non-nested array visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createArrayProperty("Array1"), TestUtils.createArrayProperty("Array2"), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); it(`Should correctly handle nested array visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createArrayProperty("Array1", [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), ], false), TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array3"), ], true), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); it(`Should correctly handle mixed categorized properties visible descendants`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1", [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), ], true), TestUtils.createStructProperty("Struct1", { CADID5: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), CADID6: TestUtils.createPrimitiveStringProperty("CADID5", "0000 0005 00E0 02D8"), CADID7: TestUtils.createPrimitiveStringProperty("CADID6", "0000 0005 00E0 02D8"), }, true), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const visibleDescendants = GridUtils.filterProperties(gridCategory.getVisibleDescendantsAndSelf()); const flatRecords = GridUtils.flattenPropertyRecords(records, gridCategory.selectionKey, true).map((record) => record.item); assertCategorizedProperties(visibleDescendants, flatRecords); }); function assertPropertyAndGridItemEquality(gridItems: IMutableFlatGridItem[], records: Array<PropertyCategory | PropertyRecord>) { GridUtils.callPropertyAndGridItemAsserts(gridItems, records, GridUtils.assertCategoryEquals, GridUtils.assertPropertyEquals); } it(`Should correctly handle visible descendants with child categories`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true, childCategories: [ { name: "Category1_1", label: "Category 1_1", expand: false }, { name: "Category1_2", label: "Category 1_2", expand: false }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1"), TestUtils.createStructProperty("Struct1")]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const descendants = gridCategory.getVisibleDescendantsAndSelf(); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true).map((property) => property.item); assertPropertyAndGridItemEquality(descendants, flatProperties); }); it(`Should correctly handle last visible descendants with mix of child categories and property records`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true, childCategories: [ { name: "Category1_1", label: "Category 1_1", expand: false }, { name: "Category1_2", label: "Category 1_2", expand: true }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1"), TestUtils.createStructProperty("Struct1"), ]; categoryRecords[propertyCategory.childCategories![0].name] = [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array2"), TestUtils.createStructProperty("Struct2"), ]; categoryRecords[propertyCategory.childCategories![1].name] = [ TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array3"), TestUtils.createStructProperty("Struct3"), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = true; const descendants = gridCategory.getVisibleDescendantsAndSelf(); const flatRecords = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true).map((property) => property.item); assertPropertyAndGridItemEquality(descendants, flatRecords); }); }); function assertLastVisibleDescendant( gridCategory: IMutableGridCategoryItem, expectedLastDescendant: PropertyRecord | PropertyCategory, ) { const lastDescendant = gridCategory.getLastVisibleDescendantOrSelf(); if (expectedLastDescendant instanceof PropertyRecord) { GridUtils.assertPropertyEquals(lastDescendant as IMutableCategorizedPropertyItem, expectedLastDescendant); } else { GridUtils.assertCategoryEquals(lastDescendant as GridCategoryItem, expectedLastDescendant); } } describe("Should correctly handle getting last visible descendant", () => { it(`Should correctly handle no children last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); gridCategory.isExpanded = false; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.be.equal(gridCategory); gridCategory.isExpanded = true; expect(gridCategory.getLastVisibleDescendantOrSelf()).to.be.equal(gridCategory); }); it(`Should correctly always return self when not expanded`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: false }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), ], true), TestUtils.createStructProperty("Struct1", { CADID5: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), CADID6: TestUtils.createPrimitiveStringProperty("CADID5", "0000 0005 00E0 02D8"), CADID7: TestUtils.createPrimitiveStringProperty("CADID6", "0000 0005 00E0 02D8"), }, true), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); expect(gridCategory.getLastVisibleDescendantOrSelf()).to.be.equal(gridCategory); }); it(`Should correctly handle primitive last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should correctly handle non-nested struct last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [TestUtils.createStructProperty("Struct1"), TestUtils.createStructProperty("Struct2")]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should correctly handle nested struct last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); const records = [ TestUtils.createStructProperty("Struct1", { CADID3: TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), CADID4: TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), }, false), TestUtils.createStructProperty("Struct2", { CADID3: TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), CADID4: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), Struct3: TestUtils.createStructProperty("Struct3"), }, true), ]; categoryRecords[propertyCategory.name] = records; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should correctly handle non-nested array last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createArrayProperty("Array1"), TestUtils.createArrayProperty("Array2"), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should correctly handle nested array last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createArrayProperty("Array1"), TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array3"), ], true), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should correctly handle mixed categorized properties last visible descendant`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array2", [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createPrimitiveStringProperty("CADID3", "0000 0005 00E0 02D8"), ], true), TestUtils.createStructProperty("Struct1", { CADID5: TestUtils.createPrimitiveStringProperty("CADID4", "0000 0005 00E0 02D8"), CADID6: TestUtils.createPrimitiveStringProperty("CADID5", "0000 0005 00E0 02D8"), CADID7: TestUtils.createPrimitiveStringProperty("CADID6", "0000 0005 00E0 02D8"), }, true), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should always return last child category as last visible descendant when last category has no children`, () => { const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true, childCategories: [ { name: "Category1_1", label: "Category 1_1", expand: false }, { name: "Category1_2", label: "Category 1_2", expand: false }, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1"), TestUtils.createStructProperty("Struct1"), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); it(`Should always return child categories last visible descendant as last visible descendant when child category has children`, () => { const lastCategory = { name: "Category1_2", label: "Category 1_2", expand: true }; const propertyCategory: PropertyCategory = { name: "Category1", label: "Category 1", expand: true, childCategories: [ { name: "Category1_1", label: "Category 1_1", expand: false }, lastCategory, ], }; const categoryRecords = GridUtils.constructCategoryRecordsDict([propertyCategory]); categoryRecords[propertyCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID1", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array1"), TestUtils.createStructProperty("Struct1"), ]; categoryRecords[lastCategory.name] = [ TestUtils.createPrimitiveStringProperty("CADID2", "0000 0005 00E0 02D8"), TestUtils.createArrayProperty("Array2"), TestUtils.createStructProperty("Struct2"), ]; const gridCategory = new MutableGridCategory(propertyCategory, categoryRecords, gridItemFactory); const flatProperties = GridUtils.flattenPropertyCategories([propertyCategory], categoryRecords, true); const lastDescendantProperty = GridUtils.getLast(flatProperties)!; assertLastVisibleDescendant(gridCategory, lastDescendantProperty.item); }); }); }); });
the_stack
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Host, HostListener, Inject, Injector, Input, NgZone, OnDestroy, OnInit, Output, QueryList, Renderer2, ViewChildren, ViewEncapsulation, ViewChild } from "@angular/core"; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; import {CallbackRemoval, CommonUtils} from "../../common/core/utils/common-utils"; import {ArrayCollection} from "../../common/core/data/array-collection"; import {AbstractJigsawComponent, AbstractJigsawViewBase} from "../../common/common"; import {RequireMarkForCheck} from "../../common/decorator/mark-for-check"; import {JigsawTooltip} from "../../common/directive/tooltip/tooltip"; import {FloatPosition} from "../../common/directive/float/float"; export class SliderMark { value: number; label: string; style?: any; } /** * @internal */ @Component({ selector: 'jigsaw-slider-handle', templateUrl: './slider-handle.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawSliderHandle extends AbstractJigsawViewBase implements OnInit { private _value: number; /** * @internal */ public _$tooltipRenderHtml: string; /** * @NoMarkForCheckRequired */ @Input() public index: number; /** * @NoMarkForCheckRequired */ @Input() public get value() { return this._value; } public set value(value) { this._value = this._slider._verifyValue(value); this._valueToPos(); this._$tooltipRenderHtml = `<div style="word-break: normal;">${this._value}</div>` } /** * @NoMarkForCheckRequired */ @Input() public tooltipPosition: FloatPosition = 'top'; @Output() public change = new EventEmitter<number>(); private _valueToPos() { this._offset = this._slider._transformValueToPos(this.value); this._setHandleStyle(); } private _offset: number = 0; /** * @internal */ public _$handleStyle = {}; private _setHandleStyle() { if (isNaN(this._offset)) { return; } if (this._slider.vertical) { this._$handleStyle = { bottom: this._offset + "%" } } else { this._$handleStyle = { left: this._offset + "%" } } this._cdr.markForCheck(); } private _dragging: boolean = false; private _transformPosToValue(pos: { x: number, y: number }): number { // 更新取得的滑动条尺寸. this._slider._refresh(); const dimensions = this._slider._dimensions; // bottom 在dom中的位置. const offset = this._slider.vertical ? dimensions.bottom : dimensions.left; const size = this._slider.vertical ? dimensions.height : dimensions.width; let posValue = this._slider.vertical ? pos.y - 6 : pos.x; if (this._slider.vertical) { posValue = posValue > offset ? offset : posValue; } else { posValue = posValue < offset ? offset : posValue; } let newValue = Math.abs(posValue - offset) / size * (this._slider.max - this._slider.min) + (this._slider.min - 0); // 保留两位小数 const m = this._calFloat(this._slider.step); // 解决出现的有时小数点多了N多位. newValue = Math.round(Math.round(newValue / this._slider.step) * this._slider.step * Math.pow(10, m)) / Math.pow(10, m); return this._slider._verifyValue(newValue); } /** * 增加步长的计算,计算需要保留小数的位数 */ private _calFloat(value: number): number { try { return this._slider.step.toString().split(".")[1].length; } catch (e) { return 0; } } /** * @internal */ public _$startToDrag(): void { this._tooltip.jigsawFloatCloseTrigger = 'none'; this._dragging = true; this._registerGlobalEvent(); } private _removeGlobalEventMouseMoveListener: Function; private _removeGlobalEventMouseUpListener: Function; private _registerGlobalEvent(): void { if (this._removeGlobalEventMouseMoveListener) { this._removeGlobalEventMouseMoveListener(); } this._removeGlobalEventMouseMoveListener = this._render.listen("document", "mousemove", (e) => { this._updateValuePosition(e); }); if (this._removeGlobalEventMouseUpListener) { this._removeGlobalEventMouseUpListener(); } this._removeGlobalEventMouseUpListener = this._render.listen("document", "mouseup", () => { this._dragging = false; this._destroyGlobalEvent(); }); } private _destroyGlobalEvent() { if (this._removeGlobalEventMouseMoveListener) { this._removeGlobalEventMouseMoveListener(); } if (this._removeGlobalEventMouseUpListener) { this._removeGlobalEventMouseUpListener(); } this._tooltip.jigsawFloatCloseTrigger = 'mouseleave'; } /** * 父组件 * @private */ private _slider: JigsawSlider; constructor(private _render: Renderer2, @Host() @Inject(forwardRef(() => JigsawSlider)) slider: any, protected _zone: NgZone, private _cdr: ChangeDetectorRef) { super(); this._slider = slider; } @ViewChild(JigsawTooltip) private _tooltip: JigsawTooltip; /** * 改变value的值 */ private _updateValuePosition(event?) { if (!this._dragging || this._slider.disabled) { return; } // 防止产生选中其他文本,造成鼠标放开后还可以拖拽的奇怪现象; event.stopPropagation(); event.preventDefault(); const pos = { x: event["clientX"], y: event["clientY"] }; let newValue = this._transformPosToValue(pos); if (this.value === newValue) { return; } this.value = newValue; this._slider._updateValue(this.index, newValue); this.runAfterMicrotasks(() => { this._tooltip.reposition(); }); } ngOnInit() { this._valueToPos(); } } /** * @description 滑动条组件. * * 何时使用 * 当用户需要在数值区间/自定义区间内进行选择时 */ @Component({ selector: 'jigsaw-slider, j-slider', templateUrl: './slider.html', host: { '[class.jigsaw-slider-host]': 'true', '[class.jigsaw-slider-error]': '!valid', '[class.jigsaw-slider-vertical]': 'vertical', '[style.width]': 'width', '[style.height]': 'height' }, encapsulation: ViewEncapsulation.None, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawSlider), multi: true}, ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawSlider extends AbstractJigsawComponent implements ControlValueAccessor, OnInit, OnDestroy { constructor(private _element: ElementRef, private _render: Renderer2, protected _zone: NgZone, private _changeDetectorRef: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); } /** * @NoMarkForCheckRequired */ @Input() public valid: boolean = true; // Todo 支持滑动条点击. @ViewChildren(JigsawSliderHandle) private _sliderHandle: QueryList<JigsawSliderHandle>; /** * @internal */ public get _$trackBy() { return (index: number) => index; } /** * @internal */ public _$value: ArrayCollection<number> = new ArrayCollection<number>(); private _removeRefreshCallback: CallbackRemoval = this._getRemoveRefreshCallback(); /** * slider的当前值, 类型 number | ArrayCollection<number> 支持多触点 * * @NoMarkForCheckRequired */ @Input() public get value(): number | ArrayCollection<number> { // 兼容返回单个值, 和多触点的数组; if (this._$value.length == 1) { return this._$value[0]; } else { return this._$value; } } public set value(value: number | ArrayCollection<number>) { this.writeValue(value); } /** * 设置单个的值。内部使用 * 子级组件需要用到 * @internal */ public _updateValue(index: number, value: number) { this._$value.set(index, value); this._$value.refresh(); this._changeDetectorRef.markForCheck(); } /** * 最后重新计算一下,垂直滚动条的位置 * 子级组件需要用到 * @internal */ public _refresh() { this._dimensions = this._element.nativeElement.getBoundingClientRect(); this._changeDetectorRef.markForCheck(); } /** * 使 value 支持双向绑定 */ @Output() public valueChange = new EventEmitter<number | ArrayCollection<number>>(); // 当滑动条的组件值变化时,对外发出的事件 @Output() public change = this.valueChange; private _min: number = 0; /** * 可选范围的最小值 * * @NoMarkForCheckRequired */ @Input() public get min():number { return this._min; } public set min(min: number) { min = Number(min); if (isNaN(min)) { return; } this._min = min; } private _max: number = 100; /** * 输入范围的可选最大值. * * @NoMarkForCheckRequired */ @Input() public get max():number { return this._max; } public set max(max: number) { max = Number(max); if (isNaN(max)) { return; } this._max = Number(max); } private _step: number = 1; /** * 每次变化的最小值, 最小支持小数点后两位. * * @NoMarkForCheckRequired */ @Input() public get step() { return this._step; } public set step(value: number) { this._step = value; } /** * 子级组件需要用到 * @internal */ public _transformValueToPos(value?) { // 检验值的合法性, 不合法转换成默认可接受的合法值; value = this._verifyValue(value); return (value - this.min) / (this.max - this.min) * 100; } /** * 子级组件需要用到 * @internal */ public _dimensions: ClientRect; /** * 垂直滑动条 默认 false * * @NoMarkForCheckRequired */ @Input() public vertical: boolean = false; /** * 是否禁用. 数据类型 boolean, 默认false; */ @Input() @RequireMarkForCheck() public disabled: boolean = false; /** * @internal */ public _$trackStyle = {}; private _setTrackStyle() { let startPos: number = 0; let trackSize: number = 0; if (this._$value.length > 1) { // 多触点 let min: number = Math.min(...this._$value); let max: number = Math.max(...this._$value); startPos = this._transformValueToPos(min); trackSize = Math.abs(this._transformValueToPos(max) - this._transformValueToPos(min)); } else { // 单触点 trackSize = this._transformValueToPos(this.value); } if (this.vertical) { this._$trackStyle = { bottom: startPos + "%", height: trackSize + "%" } } else { this._$trackStyle = { left: startPos + "%", width: trackSize + "%" } } } /** * @internal */ public _$marks: any[] = []; private _marks: SliderMark[]; /** * marks 标签 使用格式为 [Object] 其中 Object 必须包含value 及label 可以有style 属性 * 例如: marks = [{value: 20, label: '20 ℃'}, */ @Input() @RequireMarkForCheck() public get marks(): SliderMark[] { return this._marks; } public set marks(value: SliderMark[]) { this._marks = value; this._calcMarks(); } /** * @internal * @param markVal */ public _$isDotActive(markVal: number): boolean { if (this._$value.length == 1) { return markVal < this.value; } else { const min = Math.min(...this._$value); const max = Math.max(...this._$value); return markVal >= min && markVal <= max; } } private _calcMarks() { if (!this._marks || !this.initialized) { return; } this._$marks.splice(0, this._$marks.length); let size = Math.round(100 / this._marks.length); let margin = -Math.floor(size / 2); let vertical = this.vertical; this._marks.forEach(mark => { const richMark: any = {}; if (vertical) { richMark.dotStyle = { bottom: this._transformValueToPos(mark.value) + "%" }; richMark.labelStyle = { bottom: this._transformValueToPos(mark.value) + "%", "margin-bottom": margin + "%" }; } else { richMark.dotStyle = { top: "-2px", left: this._transformValueToPos(mark.value) + "%" }; richMark.labelStyle = { left: this._transformValueToPos(mark.value) + "%", width: size + "%", "margin-left": margin + "%" }; } // 如果用户自定义了样式, 要进行样式的合并; CommonUtils.extendObject(richMark.labelStyle, mark.style); richMark.label = mark.label; richMark.value = mark.value; this._$marks.push(richMark); }); } ngOnInit() { super.ngOnInit(); // 计算slider 的尺寸. this._dimensions = this._element.nativeElement.getBoundingClientRect(); // 设置标记. this._calcMarks(); // 注册resize事件; this._resize(); } private _removeResizeEvent: Function; private _resize() { this._zone.runOutsideAngular(() => { this._removeResizeEvent = this._render.listen("window", "resize", () => { // 计算slider 的尺寸. this._dimensions = this._element.nativeElement.getBoundingClientRect(); }) }) } /** * 暂没有使用场景. */ public ngOnDestroy() { super.ngOnDestroy(); if (this._removeResizeEvent) { this._removeResizeEvent(); } if (this._removeRefreshCallback) { this._removeRefreshCallback() } } /** * 校验value的合法性. 大于最大值,取最大值, 小于最小值取最小值 * 子级组件需要用到 * @internal */ public _verifyValue(value: number): number { if (value - this.min < 0 && this.initialized) { return this.min; } else if (value - this.max > 0 && this.initialized) { return this.max; } else { return value; } } private _getRemoveRefreshCallback() { return this._$value.onRefresh(() => { this._zone.runOutsideAngular(() => this._setTrackStyle()); this._updateSliderHandleValue(); this.valueChange.emit(this.value); this._propagateChange(this.value); this._changeDetectorRef.markForCheck(); }); } /** * 手动更新handle的值,通过ngFor更新必须value发生变化,如max变化也需要调整位置 * @private */ private _updateSliderHandleValue() { if(!this._sliderHandle || !this._$value) { return; } this._sliderHandle.forEach((item, index) => item.value = this._$value[index]) } private _propagateChange: any = () => { }; private _onTouched: any = () => { }; // ngModel触发的writeValue方法,只会在ngOnInit,ngAfterContentInit,ngAfterViewInit这些生命周期之后才调用 public writeValue(value: any): void { if (value instanceof Array) { value = new ArrayCollection(value); } if (value instanceof ArrayCollection) { if (this._$value !== value) { this._$value = value; if (this._removeRefreshCallback) { this._removeRefreshCallback(); } this._removeRefreshCallback = this._getRemoveRefreshCallback(); } } else { this._$value.splice(0, this._$value.length); this._$value.push(this._verifyValue(+value)); } // refresh的回调是异步的 this._$value.refresh(); this._changeDetectorRef.markForCheck(); } public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { this._onTouched = fn; } @HostListener('click') onClickTrigger(): void { if (this.disabled) { return; } this._onTouched(); } public setDisabledState(disabled: boolean): void { this.disabled = disabled; } }
the_stack
import * as assert from 'assert'; import { mock } from 'vs/base/test/common/mock'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { Position } from 'vs/editor/common/core/position'; import { Selection } from 'vs/editor/common/core/selection'; import { LanguageFeaturesService } from 'vs/editor/common/services/languageFeaturesService'; import { SnippetController2 } from 'vs/editor/contrib/snippet/browser/snippetController2'; import { ITestCodeEditor, withTestCodeEditor } from 'vs/editor/test/browser/testCodeEditor'; import { TestLanguageConfigurationService } from 'vs/editor/test/common/modes/testLanguageConfigurationService'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection'; import { ILabelService } from 'vs/platform/label/common/label'; import { NullLogService } from 'vs/platform/log/common/log'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; class TestSnippetController extends SnippetController2 { constructor( editor: ICodeEditor, @IContextKeyService private readonly _contextKeyService: IContextKeyService ) { super(editor, new NullLogService(), new LanguageFeaturesService(), _contextKeyService, new TestLanguageConfigurationService()); } isInSnippetMode(): boolean { return SnippetController2.InSnippetMode.getValue(this._contextKeyService)!; } } suite('SnippetController', () => { function snippetTest(cb: (editor: ITestCodeEditor, template: string, snippetController: TestSnippetController) => void, lines?: string[]): void { if (!lines) { lines = [ 'function test() {', '\tvar x = 3;', '\tvar arr = [];', '\t', '}' ]; } const serviceCollection = new ServiceCollection( [ILabelService, new class extends mock<ILabelService>() { }], [IWorkspaceContextService, new class extends mock<IWorkspaceContextService>() { }], ); withTestCodeEditor(lines, { serviceCollection }, (editor) => { editor.getModel()!.updateOptions({ insertSpaces: false }); const snippetController = editor.registerAndInstantiateContribution(TestSnippetController.ID, TestSnippetController); const template = [ 'for (var ${1:index}; $1 < ${2:array}.length; $1++) {', '\tvar element = $2[$1];', '\t$0', '}' ].join('\n'); cb(editor, template, snippetController); snippetController.dispose(); }); } test('Simple accepted', () => { snippetTest((editor, template, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(template); assert.strictEqual(editor.getModel()!.getLineContent(4), '\tfor (var index; index < array.length; index++) {'); assert.strictEqual(editor.getModel()!.getLineContent(5), '\t\tvar element = array[index];'); assert.strictEqual(editor.getModel()!.getLineContent(6), '\t\t'); assert.strictEqual(editor.getModel()!.getLineContent(7), '\t}'); editor.trigger('test', 'type', { text: 'i' }); assert.strictEqual(editor.getModel()!.getLineContent(4), '\tfor (var i; i < array.length; i++) {'); assert.strictEqual(editor.getModel()!.getLineContent(5), '\t\tvar element = array[i];'); assert.strictEqual(editor.getModel()!.getLineContent(6), '\t\t'); assert.strictEqual(editor.getModel()!.getLineContent(7), '\t}'); snippetController.next(); editor.trigger('test', 'type', { text: 'arr' }); assert.strictEqual(editor.getModel()!.getLineContent(4), '\tfor (var i; i < arr.length; i++) {'); assert.strictEqual(editor.getModel()!.getLineContent(5), '\t\tvar element = arr[i];'); assert.strictEqual(editor.getModel()!.getLineContent(6), '\t\t'); assert.strictEqual(editor.getModel()!.getLineContent(7), '\t}'); snippetController.prev(); editor.trigger('test', 'type', { text: 'j' }); assert.strictEqual(editor.getModel()!.getLineContent(4), '\tfor (var j; j < arr.length; j++) {'); assert.strictEqual(editor.getModel()!.getLineContent(5), '\t\tvar element = arr[j];'); assert.strictEqual(editor.getModel()!.getLineContent(6), '\t\t'); assert.strictEqual(editor.getModel()!.getLineContent(7), '\t}'); snippetController.next(); snippetController.next(); assert.deepStrictEqual(editor.getPosition(), new Position(6, 3)); }); }); test('Simple canceled', () => { snippetTest((editor, template, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(template); assert.strictEqual(editor.getModel()!.getLineContent(4), '\tfor (var index; index < array.length; index++) {'); assert.strictEqual(editor.getModel()!.getLineContent(5), '\t\tvar element = array[index];'); assert.strictEqual(editor.getModel()!.getLineContent(6), '\t\t'); assert.strictEqual(editor.getModel()!.getLineContent(7), '\t}'); snippetController.cancel(); assert.deepStrictEqual(editor.getPosition(), new Position(4, 16)); }); }); // test('Stops when deleting lines above', () => { // snippetTest((editor, codeSnippet, snippetController) => { // editor.setPosition({ lineNumber: 4, column: 2 }); // snippetController.insert(codeSnippet, 0, 0); // editor.getModel()!.applyEdits([{ // forceMoveMarkers: false, // identifier: null, // isAutoWhitespaceEdit: false, // range: new Range(1, 1, 3, 1), // text: null // }]); // assert.strictEqual(snippetController.isInSnippetMode(), false); // }); // }); // test('Stops when deleting lines below', () => { // snippetTest((editor, codeSnippet, snippetController) => { // editor.setPosition({ lineNumber: 4, column: 2 }); // snippetController.run(codeSnippet, 0, 0); // editor.getModel()!.applyEdits([{ // forceMoveMarkers: false, // identifier: null, // isAutoWhitespaceEdit: false, // range: new Range(8, 1, 8, 100), // text: null // }]); // assert.strictEqual(snippetController.isInSnippetMode(), false); // }); // }); // test('Stops when inserting lines above', () => { // snippetTest((editor, codeSnippet, snippetController) => { // editor.setPosition({ lineNumber: 4, column: 2 }); // snippetController.run(codeSnippet, 0, 0); // editor.getModel()!.applyEdits([{ // forceMoveMarkers: false, // identifier: null, // isAutoWhitespaceEdit: false, // range: new Range(1, 100, 1, 100), // text: '\nHello' // }]); // assert.strictEqual(snippetController.isInSnippetMode(), false); // }); // }); // test('Stops when inserting lines below', () => { // snippetTest((editor, codeSnippet, snippetController) => { // editor.setPosition({ lineNumber: 4, column: 2 }); // snippetController.run(codeSnippet, 0, 0); // editor.getModel()!.applyEdits([{ // forceMoveMarkers: false, // identifier: null, // isAutoWhitespaceEdit: false, // range: new Range(8, 100, 8, 100), // text: '\nHello' // }]); // assert.strictEqual(snippetController.isInSnippetMode(), false); // }); // }); test('Stops when calling model.setValue()', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(codeSnippet); editor.getModel()!.setValue('goodbye'); assert.strictEqual(snippetController.isInSnippetMode(), false); }); }); test('Stops when undoing', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(codeSnippet); editor.getModel()!.undo(); assert.strictEqual(snippetController.isInSnippetMode(), false); }); }); test('Stops when moving cursor outside', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(codeSnippet); editor.setPosition({ lineNumber: 1, column: 1 }); assert.strictEqual(snippetController.isInSnippetMode(), false); }); }); test('Stops when disconnecting editor model', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(codeSnippet); editor.setModel(null); assert.strictEqual(snippetController.isInSnippetMode(), false); }); }); test('Stops when disposing editor', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setPosition({ lineNumber: 4, column: 2 }); snippetController.insert(codeSnippet); snippetController.dispose(); assert.strictEqual(snippetController.isInSnippetMode(), false); }); }); test('Final tabstop with multiple selections', () => { snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(1, 1, 1, 1), new Selection(2, 1, 2, 1), ]); codeSnippet = 'foo$0'; snippetController.insert(codeSnippet); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 1, startColumn: 4, endLineNumber: 1, endColumn: 4 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 2, startColumn: 4, endLineNumber: 2, endColumn: 4 }), second.toString()); }); snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(1, 1, 1, 1), new Selection(2, 1, 2, 1), ]); codeSnippet = 'foo$0bar'; snippetController.insert(codeSnippet); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 1, startColumn: 4, endLineNumber: 1, endColumn: 4 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 2, startColumn: 4, endLineNumber: 2, endColumn: 4 }), second.toString()); }); snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(1, 1, 1, 1), new Selection(1, 5, 1, 5), ]); codeSnippet = 'foo$0bar'; snippetController.insert(codeSnippet); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 1, startColumn: 4, endLineNumber: 1, endColumn: 4 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 1, startColumn: 14, endLineNumber: 1, endColumn: 14 }), second.toString()); }); snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(1, 1, 1, 1), new Selection(1, 5, 1, 5), ]); codeSnippet = 'foo\n$0\nbar'; snippetController.insert(codeSnippet); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 4, startColumn: 1, endLineNumber: 4, endColumn: 1 }), second.toString()); }); snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(1, 1, 1, 1), new Selection(1, 5, 1, 5), ]); codeSnippet = 'foo\n$0\nbar'; snippetController.insert(codeSnippet); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 4, startColumn: 1, endLineNumber: 4, endColumn: 1 }), second.toString()); }); snippetTest((editor, codeSnippet, snippetController) => { editor.setSelections([ new Selection(2, 7, 2, 7), ]); codeSnippet = 'xo$0r'; snippetController.insert(codeSnippet, { overwriteBefore: 1 }); assert.strictEqual(editor.getSelections()!.length, 1); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 2, startColumn: 8, endColumn: 8, endLineNumber: 2 })); }); }); test('Final tabstop, #11742 simple', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelection(new Selection(1, 19, 1, 19)); codeSnippet = '{{% url_**$1** %}}'; controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getSelections()!.length, 1); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 1, startColumn: 27, endLineNumber: 1, endColumn: 27 })); assert.strictEqual(editor.getModel()!.getValue(), 'example example {{% url_**** %}}'); }, ['example example sc']); snippetTest((editor, codeSnippet, controller) => { editor.setSelection(new Selection(1, 3, 1, 3)); codeSnippet = [ 'afterEach((done) => {', '\t${1}test', '});' ].join('\n'); controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getSelections()!.length, 1); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 2, startColumn: 2, endLineNumber: 2, endColumn: 2 }), editor.getSelection()!.toString()); assert.strictEqual(editor.getModel()!.getValue(), 'afterEach((done) => {\n\ttest\n});'); }, ['af']); snippetTest((editor, codeSnippet, controller) => { editor.setSelection(new Selection(1, 3, 1, 3)); codeSnippet = [ 'afterEach((done) => {', '${1}\ttest', '});' ].join('\n'); controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getSelections()!.length, 1); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 }), editor.getSelection()!.toString()); assert.strictEqual(editor.getModel()!.getValue(), 'afterEach((done) => {\n\ttest\n});'); }, ['af']); snippetTest((editor, codeSnippet, controller) => { editor.setSelection(new Selection(1, 9, 1, 9)); codeSnippet = [ 'aft${1}er' ].join('\n'); controller.insert(codeSnippet, { overwriteBefore: 8 }); assert.strictEqual(editor.getModel()!.getValue(), 'after'); assert.strictEqual(editor.getSelections()!.length, 1); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 1, startColumn: 4, endLineNumber: 1, endColumn: 4 }), editor.getSelection()!.toString()); }, ['afterone']); }); test('Final tabstop, #11742 different indents', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(2, 4, 2, 4), new Selection(1, 3, 1, 3) ]); codeSnippet = [ 'afterEach((done) => {', '\t${0}test', '});' ].join('\n'); controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getSelections()!.length, 2); const [first, second] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 5, startColumn: 3, endLineNumber: 5, endColumn: 3 }), first.toString()); assert.ok(second.equalsRange({ startLineNumber: 2, startColumn: 2, endLineNumber: 2, endColumn: 2 }), second.toString()); }, ['af', '\taf']); }); test('Final tabstop, #11890 stay at the beginning', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 5, 1, 5) ]); codeSnippet = [ 'afterEach((done) => {', '${1}\ttest', '});' ].join('\n'); controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getSelections()!.length, 1); const [first] = editor.getSelections()!; assert.ok(first.equalsRange({ startLineNumber: 2, startColumn: 3, endLineNumber: 2, endColumn: 3 }), first.toString()); }, [' af']); }); test('Final tabstop, no tabstop', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 3, 1, 3) ]); codeSnippet = 'afterEach'; controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.ok(editor.getSelection()!.equalsRange({ startLineNumber: 1, startColumn: 10, endLineNumber: 1, endColumn: 10 })); }, ['af', '\taf']); }); test('Multiple cursor and overwriteBefore/After, issue #11060', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 7, 1, 7), new Selection(2, 4, 2, 4) ]); codeSnippet = '_foo'; controller.insert(codeSnippet, { overwriteBefore: 1 }); assert.strictEqual(editor.getModel()!.getValue(), 'this._foo\nabc_foo'); }, ['this._', 'abc']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 7, 1, 7), new Selection(2, 4, 2, 4) ]); codeSnippet = 'XX'; controller.insert(codeSnippet, { overwriteBefore: 1 }); assert.strictEqual(editor.getModel()!.getValue(), 'this.XX\nabcXX'); }, ['this._', 'abc']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 7, 1, 7), new Selection(2, 4, 2, 4), new Selection(3, 5, 3, 5) ]); codeSnippet = '_foo'; controller.insert(codeSnippet, { overwriteBefore: 1 }); assert.strictEqual(editor.getModel()!.getValue(), 'this._foo\nabc_foo\ndef_foo'); }, ['this._', 'abc', 'def_']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 7, 1, 7), // primary at `this._` new Selection(2, 4, 2, 4), new Selection(3, 6, 3, 6) ]); codeSnippet = '._foo'; controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getModel()!.getValue(), 'this._foo\nabc._foo\ndef._foo'); }, ['this._', 'abc', 'def._']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(3, 6, 3, 6), // primary at `def._` new Selection(1, 7, 1, 7), new Selection(2, 4, 2, 4), ]); codeSnippet = '._foo'; controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getModel()!.getValue(), 'this._foo\nabc._foo\ndef._foo'); }, ['this._', 'abc', 'def._']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(2, 4, 2, 4), // primary at `abc` new Selection(3, 6, 3, 6), new Selection(1, 7, 1, 7), ]); codeSnippet = '._foo'; controller.insert(codeSnippet, { overwriteBefore: 2 }); assert.strictEqual(editor.getModel()!.getValue(), 'this._._foo\na._foo\ndef._._foo'); }, ['this._', 'abc', 'def._']); }); test('Multiple cursor and overwriteBefore/After, #16277', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 5, 1, 5), new Selection(2, 5, 2, 5), ]); codeSnippet = 'document'; controller.insert(codeSnippet, { overwriteBefore: 3 }); assert.strictEqual(editor.getModel()!.getValue(), '{document}\n{document && true}'); }, ['{foo}', '{foo && true}']); }); test('Insert snippet twice, #19449', () => { snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 1, 1, 1) ]); codeSnippet = 'for (var ${1:i}=0; ${1:i}<len; ${1:i}++) { $0 }'; controller.insert(codeSnippet); assert.strictEqual(editor.getModel()!.getValue(), 'for (var i=0; i<len; i++) { }for (var i=0; i<len; i++) { }'); }, ['for (var i=0; i<len; i++) { }']); snippetTest((editor, codeSnippet, controller) => { editor.setSelections([ new Selection(1, 1, 1, 1) ]); codeSnippet = 'for (let ${1:i}=0; ${1:i}<len; ${1:i}++) { $0 }'; controller.insert(codeSnippet); assert.strictEqual(editor.getModel()!.getValue(), 'for (let i=0; i<len; i++) { }for (var i=0; i<len; i++) { }'); }, ['for (var i=0; i<len; i++) { }']); }); });
the_stack
import chalk from 'chalk' import { Argv } from 'yargs' import yargs from 'yargs/yargs' import * as cli from './cli' import fromArguments from './config' import { Converter, ConvertedCallback, ConvertType } from './converter' import { CLIError, error, isError } from './error' import { File, FileType } from './file' import { Preview, fileToURI } from './preview' import { Server } from './server' import templates from './templates' import { isOfficialImage } from './utils/docker' import { resetExecutablePath } from './utils/puppeteer' import version from './version' import watcher, { Watcher, notifier } from './watcher' enum OptionGroup { Basic = 'Basic Options:', Converter = 'Converter Options:', Template = 'Template Options:', Meta = 'Metadata Options:', Marp = 'Marp / Marpit Options:', } export interface MarpCLIInternalOptions { baseUrl?: string stdin: boolean throwErrorAlways: boolean } export type MarpCLIAPIOptions = Pick<MarpCLIInternalOptions, 'baseUrl'> export type ObservationHelper = { stop: () => void } const resolversForObservation: Array<(helper: ObservationHelper) => void> = [] const usage = ` Usage: marp [options] <files...> marp [options] -I <dir> `.trim() export const marpCli = async ( argv: string[], { baseUrl, stdin: defaultStdin, throwErrorAlways }: MarpCLIInternalOptions ): Promise<number> => { let server: Server | undefined let watcherInstance: Watcher | undefined try { const base: Argv = yargs(argv) const program = base .usage(usage) .help(false) .version(false) .options({ version: { alias: 'v', describe: 'Show versions', group: OptionGroup.Basic, type: 'boolean', }, help: { alias: 'h', describe: 'Show help', group: OptionGroup.Basic, type: 'boolean', }, output: { alias: 'o', describe: 'Output file path (or directory when input-dir is passed)', group: OptionGroup.Basic, type: 'string', }, 'input-dir': { alias: 'I', describe: 'The base directory to find markdown and theme CSS', group: OptionGroup.Basic, type: 'string', }, 'config-file': { alias: ['config', 'c'], describe: 'Specify path to a configuration file', group: OptionGroup.Basic, type: 'string', }, 'no-config-file': { alias: ['no-config'], type: 'boolean', describe: 'Prevent looking up for a configuration file', group: OptionGroup.Basic, }, watch: { alias: 'w', describe: 'Watch input markdowns for changes', group: OptionGroup.Basic, type: 'boolean', }, server: { alias: 's', describe: 'Enable server mode', group: OptionGroup.Basic, type: 'boolean', }, preview: { alias: 'p', describe: 'Open preview window', hidden: isOfficialImage(), group: OptionGroup.Basic, type: 'boolean', }, stdin: { default: defaultStdin, describe: 'Read Markdown from stdin', hidden: true, // It is an escape-hatch for advanced user group: OptionGroup.Basic, type: 'boolean', }, pdf: { conflicts: ['image', 'images', 'pptx'], describe: 'Convert slide deck into PDF', group: OptionGroup.Converter, type: 'boolean', }, pptx: { conflicts: ['pdf', 'image', 'images'], describe: 'Convert slide deck into PowerPoint document', group: OptionGroup.Converter, type: 'boolean', }, image: { conflicts: ['pdf', 'images', 'pptx'], describe: 'Convert the first slide page into an image file', group: OptionGroup.Converter, choices: ['png', 'jpeg'], coerce: (type: string) => (type === 'jpg' ? 'jpeg' : type), type: 'string', }, images: { conflicts: ['pdf', 'image', 'pptx'], describe: 'Convert slide deck into multiple image files', group: OptionGroup.Converter, choices: ['png', 'jpeg'], coerce: (type: string) => (type === 'jpg' ? 'jpeg' : type), type: 'string', }, 'image-scale': { defaultDescription: '1 (or 2 for PPTX conversion)', describe: 'The scale factor for rendered images', group: OptionGroup.Converter, type: 'number', }, 'jpeg-quality': { defaultDescription: '85', describe: 'Set JPEG image quality', group: OptionGroup.Converter, type: 'number', }, 'allow-local-files': { describe: 'Allow to access local files from Markdown while converting PDF, PPTX, or image (NOT SECURE)', group: OptionGroup.Converter, type: 'boolean', }, template: { describe: 'Choose template', defaultDescription: 'bespoke', group: OptionGroup.Template, choices: Object.keys(templates), type: 'string', }, 'bespoke.osc': { describe: '[Bespoke] Use on-screen controller', defaultDescription: 'true', group: OptionGroup.Template, type: 'boolean', }, 'bespoke.progress': { describe: '[Bespoke] Use progress bar', defaultDescription: 'false', group: OptionGroup.Template, type: 'boolean', }, 'bespoke.transition': { describe: '[Bespoke] Enable transitions powered by Shared Element Transitions API (EXPERIMENTAL)', defaultDescription: 'false', group: OptionGroup.Template, type: 'boolean', }, title: { describe: 'Define title of the slide deck', group: OptionGroup.Meta, type: 'string', }, description: { describe: 'Define description of the slide deck', group: OptionGroup.Meta, type: 'string', }, author: { describe: 'Define author of the slide deck', group: OptionGroup.Meta, type: 'string', }, keywords: { describe: 'Define comma-separated keywords for the slide deck', group: OptionGroup.Meta, type: 'string', }, url: { describe: 'Define canonical URL', group: OptionGroup.Meta, type: 'string', }, 'og-image': { describe: 'Define Open Graph image URL', group: OptionGroup.Meta, type: 'string', }, 'pdf-notes': { describe: 'Add presenter notes to PDF as annotations', group: OptionGroup.Meta, type: 'boolean', }, engine: { describe: 'Select Marpit based engine by module name or path', group: OptionGroup.Marp, type: 'string', }, html: { describe: 'Enable or disable HTML tags', group: OptionGroup.Marp, type: 'boolean', }, theme: { describe: 'Override theme by name or CSS file', group: OptionGroup.Marp, type: 'string', }, 'theme-set': { array: true, describe: 'Path to additional theme CSS files', group: OptionGroup.Marp, type: 'string', }, }) const argvRet = await program.argv const args = { baseUrl, // It's not intended using by the consumer so can't set through CLI arguments ...argvRet, _: argvRet._.map((v) => v.toString()), } if (args.help) { program.showHelp() return 0 } const config = await fromArguments(args) if (args.version) return await version(config) // Initialize converter const converter = new Converter(await config.converterOption()) const cvtOpts = converter.options // Find target markdown files const finder = async () => { if (cvtOpts.inputDir) { if (config.files.length > 0) { cli.error('Cannot pass files together with input directory.') return [] } // Find directory to keep dir structure of input dir in output return File.findDir(cvtOpts.inputDir) } // Read from stdin // (May disable by --no-stdin option to avoid hung up while reading) // @see https://github.com/marp-team/marp-cli/issues/93 const stdin = args.stdin ? await File.stdin() : undefined // Regular file finding powered by globby return <File[]>( [stdin, ...(await File.find(...config.files))].filter((f) => f) ) } const foundFiles = await finder() const { length } = foundFiles if (length === 0) { if (config.files.length > 0) cli.warn('Not found processable Markdown file(s).\n') program.showHelp() return config.files.length > 0 ? 1 : 0 } // Convert markdown into HTML const convertedFiles: File[] = [] const onConverted: ConvertedCallback = (ret) => { const { file: i, newFile: o } = ret if (!o) return const fn = (f: File, stdio: string) => f.type === FileType.StandardIO ? stdio : f.relativePath() convertedFiles.push(o) cli.info( `${fn(i, '<stdin>')} ${ o.type === FileType.Null ? 'processed.' : `=> ${fn(o, '<stdout>')}` }`, { singleLine: true } ) } try { if (cvtOpts.server) { await converter.convertFiles(foundFiles, { onlyScanning: true }) } else { cli.info(`Converting ${length} markdown${length > 1 ? 's' : ''}...`) await converter.convertFiles(foundFiles, { onConverted }) } } catch (e: unknown) { if (isError(e)) { const errorCode = e instanceof CLIError ? e.errorCode : undefined error(`Failed converting Markdown. (${e.message})`, errorCode) } else { throw e } } // Watch mode / Server mode if (cvtOpts.watch) { return await new Promise<number>((res, rej) => (async () => { watcherInstance = watcher( [ ...(cvtOpts.inputDir ? [cvtOpts.inputDir] : config.files), ...cvtOpts.themeSet.fnForWatch, ], { converter, finder, events: { onConverted, onError: (e) => cli.error(`Failed converting Markdown. (${e.message})`), }, mode: cvtOpts.server ? Watcher.WatchMode.Notify : Watcher.WatchMode.Convert, } ) // Preview window const preview = new Preview() preview.on('exit', () => res(0)) preview.on('opening', (location: string) => { const loc = location.substr(0, 50) const msg = `[Preview] Opening ${loc}...` cli.info(chalk.cyan(msg)) }) if (cvtOpts.server) { server = new Server(converter, { directoryIndex: ['index.md', 'PITCHME.md'], // GitPitch compatible }) server.on('converted', onConverted) server.on('error', (e) => cli.error(e.toString())) await server.start() const url = `http://localhost:${server.port}` const message = `[Server mode] Start server listened at ${url}/ ...` cli.info(chalk.green(message)) if (cvtOpts.preview) await preview.open(url) } else { cli.info(chalk.green('[Watch mode] Start watching...')) if (cvtOpts.preview) { for (const file of convertedFiles) { if (cvtOpts.type === ConvertType.pptx) continue await preview.open(fileToURI(file, cvtOpts.type)) } } } let resolverForObservation: | ((helper: ObservationHelper) => void) | undefined while ((resolverForObservation = resolversForObservation.shift())) { resolverForObservation({ stop: () => res(0) }) } })().catch(rej) ) } return 0 } catch (e: unknown) { if (throwErrorAlways || !(e instanceof CLIError)) throw e cli.error(e.message) return e.errorCode } finally { await Promise.all([ notifier.stop(), Converter.closeBrowser(), server?.stop(), watcherInstance?.chokidar.close(), ]) } } export const waitForObservation = () => new Promise<ObservationHelper>((res) => { resolversForObservation.push(res) }) export const apiInterface = (argv: string[], opts: MarpCLIAPIOptions = {}) => { resetExecutablePath() return marpCli(argv, { ...opts, stdin: false, throwErrorAlways: true, }) } export const cliInterface = (argv: string[] = []) => marpCli(argv, { stdin: true, throwErrorAlways: false, }) export default cliInterface
the_stack
import BN from "bn.js" import { Buffer } from "buffer/" import AvalancheCore from "../../avalanche" import BinTools from "../../utils/bintools" import { UTXO, UTXOSet } from "./utxos" import { AVMConstants } from "./constants" import { KeyChain } from "./keychain" import { Tx, UnsignedTx } from "./tx" import { PayloadBase } from "../../utils/payload" import { SECPMintOutput } from "./outputs" import { InitialStates } from "./initialstates" import { UnixNow } from "../../utils/helperfunctions" import { JRPCAPI } from "../../common/jrpcapi" import { RequestResponseData } from "../../common/apibase" import { Defaults, PrimaryAssetAlias, ONEAVAX } from "../../utils/constants" import { MinterSet } from "./minterset" import { PersistanceOptions } from "../../utils/persistenceoptions" import { OutputOwners } from "../../common/output" import { SECPTransferOutput } from "./outputs" import { AddressError, GooseEggCheckError, ChainIdError, NoAtomicUTXOsError, SymbolError, NameError, TransactionError } from "../../utils/errors" import { Serialization, SerializedType } from "../../utils" import { BuildGenesisParams, CreateAddressParams, CreateFixedCapAssetParams, CreateVariableCapAssetParams, ExportParams, ExportKeyParams, GetAllBalancesParams, GetAssetDescriptionParams, GetAVAXAssetIDParams, GetBalanceParams, GetTxParams, GetTxStatusParams, GetUTXOsParams, ImportParams, ImportKeyParams, ListAddressesParams, MintParams, SendMultipleParams, SOutputsParams } from "./interfaces" import { IssueTxParams } from "../../common" /** * @ignore */ const bintools: BinTools = BinTools.getInstance() const serialization: Serialization = Serialization.getInstance() /** * Class for interacting with a node endpoint that is using the AVM. * * @category RPCAPIs * * @remarks This extends the [[JRPCAPI]] class. This class should not be directly called. Instead, use the [[Avalanche.addAPI]] function to register this interface with Avalanche. */ export class AVMAPI extends JRPCAPI { /** * @ignore */ protected keychain: KeyChain = new KeyChain("", "") protected blockchainID: string = "" protected blockchainAlias: string = undefined protected AVAXAssetID: Buffer = undefined protected txFee: BN = undefined protected creationTxFee: BN = undefined /** * Gets the alias for the blockchainID if it exists, otherwise returns `undefined`. * * @returns The alias for the blockchainID */ getBlockchainAlias = (): string => { if (typeof this.blockchainAlias === "undefined") { const netid: number = this.core.getNetworkID() if ( netid in Defaults.network && this.blockchainID in Defaults.network[`${netid}`] ) { this.blockchainAlias = Defaults.network[`${netid}`][this.blockchainID].alias return this.blockchainAlias } else { /* istanbul ignore next */ return undefined } } return this.blockchainAlias } /** * Sets the alias for the blockchainID. * * @param alias The alias for the blockchainID. * */ setBlockchainAlias = (alias: string): undefined => { this.blockchainAlias = alias /* istanbul ignore next */ return undefined } /** * Gets the blockchainID and returns it. * * @returns The blockchainID */ getBlockchainID = (): string => this.blockchainID /** * Refresh blockchainID, and if a blockchainID is passed in, use that. * * @param Optional. BlockchainID to assign, if none, uses the default based on networkID. * * @returns The blockchainID */ refreshBlockchainID = (blockchainID: string = undefined): boolean => { const netid: number = this.core.getNetworkID() if ( typeof blockchainID === "undefined" && typeof Defaults.network[`${netid}`] !== "undefined" ) { this.blockchainID = Defaults.network[`${netid}`].X.blockchainID //default to X-Chain return true } if (typeof blockchainID === "string") { this.blockchainID = blockchainID return true } return false } /** * Takes an address string and returns its {@link https://github.com/feross/buffer|Buffer} representation if valid. * * @returns A {@link https://github.com/feross/buffer|Buffer} for the address if valid, undefined if not valid. */ parseAddress = (addr: string): Buffer => { const alias: string = this.getBlockchainAlias() const blockchainID: string = this.getBlockchainID() return bintools.parseAddress( addr, blockchainID, alias, AVMConstants.ADDRESSLENGTH ) } addressFromBuffer = (address: Buffer): string => { const chainid: string = this.getBlockchainAlias() ? this.getBlockchainAlias() : this.getBlockchainID() const type: SerializedType = "bech32" return serialization.bufferToType( address, type, this.core.getHRP(), chainid ) } /** * Fetches the AVAX AssetID and returns it in a Promise. * * @param refresh This function caches the response. Refresh = true will bust the cache. * * @returns The the provided string representing the AVAX AssetID */ getAVAXAssetID = async (refresh: boolean = false): Promise<Buffer> => { if (typeof this.AVAXAssetID === "undefined" || refresh) { const asset: GetAVAXAssetIDParams = await this.getAssetDescription( PrimaryAssetAlias ) this.AVAXAssetID = asset.assetID } return this.AVAXAssetID } /** * Overrides the defaults and sets the cache to a specific AVAX AssetID * * @param avaxAssetID A cb58 string or Buffer representing the AVAX AssetID * * @returns The the provided string representing the AVAX AssetID */ setAVAXAssetID = (avaxAssetID: string | Buffer) => { if (typeof avaxAssetID === "string") { avaxAssetID = bintools.cb58Decode(avaxAssetID) } this.AVAXAssetID = avaxAssetID } /** * Gets the default tx fee for this chain. * * @returns The default tx fee as a {@link https://github.com/indutny/bn.js/|BN} */ getDefaultTxFee = (): BN => { return this.core.getNetworkID() in Defaults.network ? new BN(Defaults.network[this.core.getNetworkID()]["X"]["txFee"]) : new BN(0) } /** * Gets the tx fee for this chain. * * @returns The tx fee as a {@link https://github.com/indutny/bn.js/|BN} */ getTxFee = (): BN => { if (typeof this.txFee === "undefined") { this.txFee = this.getDefaultTxFee() } return this.txFee } /** * Sets the tx fee for this chain. * * @param fee The tx fee amount to set as {@link https://github.com/indutny/bn.js/|BN} */ setTxFee = (fee: BN): void => { this.txFee = fee } /** * Gets the default creation fee for this chain. * * @returns The default creation fee as a {@link https://github.com/indutny/bn.js/|BN} */ getDefaultCreationTxFee = (): BN => { return this.core.getNetworkID() in Defaults.network ? new BN(Defaults.network[this.core.getNetworkID()]["X"]["creationTxFee"]) : new BN(0) } /** * Gets the creation fee for this chain. * * @returns The creation fee as a {@link https://github.com/indutny/bn.js/|BN} */ getCreationTxFee = (): BN => { if (typeof this.creationTxFee === "undefined") { this.creationTxFee = this.getDefaultCreationTxFee() } return this.creationTxFee } /** * Sets the creation fee for this chain. * * @param fee The creation fee amount to set as {@link https://github.com/indutny/bn.js/|BN} */ setCreationTxFee = (fee: BN): void => { this.creationTxFee = fee } /** * Gets a reference to the keychain for this class. * * @returns The instance of [[KeyChain]] for this class */ keyChain = (): KeyChain => this.keychain /** * @ignore */ newKeyChain = (): KeyChain => { // warning, overwrites the old keychain const alias: string = this.getBlockchainAlias() if (alias) { this.keychain = new KeyChain(this.core.getHRP(), alias) } else { this.keychain = new KeyChain(this.core.getHRP(), this.blockchainID) } return this.keychain } /** * Helper function which determines if a tx is a goose egg transaction. * * @param utx An UnsignedTx * * @returns boolean true if passes goose egg test and false if fails. * * @remarks * A "Goose Egg Transaction" is when the fee far exceeds a reasonable amount */ checkGooseEgg = async ( utx: UnsignedTx, outTotal: BN = new BN(0) ): Promise<boolean> => { const avaxAssetID: Buffer = await this.getAVAXAssetID() const outputTotal: BN = outTotal.gt(new BN(0)) ? outTotal : utx.getOutputTotal(avaxAssetID) const fee: BN = utx.getBurn(avaxAssetID) if (fee.lte(ONEAVAX.mul(new BN(10))) || fee.lte(outputTotal)) { return true } else { return false } } /** * Gets the balance of a particular asset on a blockchain. * * @param address The address to pull the asset balance from * @param assetID The assetID to pull the balance from * @param includePartial If includePartial=false, returns only the balance held solely * * @returns Promise with the balance of the assetID as a {@link https://github.com/indutny/bn.js/|BN} on the provided address for the blockchain. */ getBalance = async ( address: string, assetID: string, includePartial: boolean = false ): Promise<object> => { if (typeof this.parseAddress(address) === "undefined") { /* istanbul ignore next */ throw new AddressError( "Error - AVMAPI.getBalance: Invalid address format" ) } const params: GetBalanceParams = { address, assetID, includePartial } const response: RequestResponseData = await this.callMethod( "avm.getBalance", params ) return response.data.result } /** * Creates an address (and associated private keys) on a user on a blockchain. * * @param username Name of the user to create the address under * @param password Password to unlock the user and encrypt the private key * * @returns Promise for a string representing the address created by the vm. */ createAddress = async ( username: string, password: string ): Promise<string> => { const params: CreateAddressParams = { username, password } const response: RequestResponseData = await this.callMethod( "avm.createAddress", params ) return response.data.result.address } /** * Create a new fixed-cap, fungible asset. A quantity of it is created at initialization and there no more is ever created. * * @param username The user paying the transaction fee (in $AVAX) for asset creation * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation * @param name The human-readable name for the asset * @param symbol Optional. The shorthand symbol for the asset. Between 0 and 4 characters * @param denomination Optional. Determines how balances of this asset are displayed by user interfaces. Default is 0 * @param initialHolders An array of objects containing the field "address" and "amount" to establish the genesis values for the new asset * * ```js * Example initialHolders: * [ * { * "address": "X-avax1kj06lhgx84h39snsljcey3tpc046ze68mek3g5", * "amount": 10000 * }, * { * "address": "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr", * "amount": 50000 * } * ] * ``` * * @returns Returns a Promise<string> containing the base 58 string representation of the ID of the newly created asset. */ createFixedCapAsset = async ( username: string, password: string, name: string, symbol: string, denomination: number, initialHolders: object[] ): Promise<string> => { const params: CreateFixedCapAssetParams = { name, symbol, denomination, username, password, initialHolders } const response: RequestResponseData = await this.callMethod( "avm.createFixedCapAsset", params ) return response.data.result.assetID } /** * Create a new variable-cap, fungible asset. No units of the asset exist at initialization. Minters can mint units of this asset using createMintTx, signMintTx and sendMintTx. * * @param username The user paying the transaction fee (in $AVAX) for asset creation * @param password The password for the user paying the transaction fee (in $AVAX) for asset creation * @param name The human-readable name for the asset * @param symbol Optional. The shorthand symbol for the asset -- between 0 and 4 characters * @param denomination Optional. Determines how balances of this asset are displayed by user interfaces. Default is 0 * @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction * * ```js * Example minterSets: * [ * { * "minters":[ * "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr" * ], * "threshold": 1 * }, * { * "minters": [ * "X-avax1am4w6hfrvmh3akduzkjthrtgtqafalce6an8cr", * "X-avax1kj06lhgx84h39snsljcey3tpc046ze68mek3g5", * "X-avax1yell3e4nln0m39cfpdhgqprsd87jkh4qnakklx" * ], * "threshold": 2 * } * ] * ``` * * @returns Returns a Promise<string> containing the base 58 string representation of the ID of the newly created asset. */ createVariableCapAsset = async ( username: string, password: string, name: string, symbol: string, denomination: number, minterSets: object[] ): Promise<string> => { const params: CreateVariableCapAssetParams = { name, symbol, denomination, username, password, minterSets } const response: RequestResponseData = await this.callMethod( "avm.createVariableCapAsset", params ) return response.data.result.assetID } /** * Create an unsigned transaction to mint more of an asset. * * @param amount The units of the asset to mint * @param assetID The ID of the asset to mint * @param to The address to assign the units of the minted asset * @param minters Addresses of the minters responsible for signing the transaction * * @returns Returns a Promise<string> containing the base 58 string representation of the unsigned transaction. */ mint = async ( username: string, password: string, amount: number | BN, assetID: Buffer | string, to: string, minters: string[] ): Promise<string> => { let asset: string let amnt: BN if (typeof assetID !== "string") { asset = bintools.cb58Encode(assetID) } else { asset = assetID } if (typeof amount === "number") { amnt = new BN(amount) } else { amnt = amount } const params: MintParams = { username: username, password: password, amount: amnt, assetID: asset, to, minters } const response: RequestResponseData = await this.callMethod( "avm.mint", params ) return response.data.result.txID } /** * Exports the private key for an address. * * @param username The name of the user with the private key * @param password The password used to decrypt the private key * @param address The address whose private key should be exported * * @returns Promise with the decrypted private key as store in the database */ exportKey = async ( username: string, password: string, address: string ): Promise<string> => { if (typeof this.parseAddress(address) === "undefined") { /* istanbul ignore next */ throw new AddressError("Error - AVMAPI.exportKey: Invalid address format") } const params: ExportKeyParams = { username, password, address } const response: RequestResponseData = await this.callMethod( "avm.exportKey", params ) return response.data.result.privateKey } /** * Imports a private key into the node's keystore under an user and for a blockchain. * * @param username The name of the user to store the private key * @param password The password that unlocks the user * @param privateKey A string representing the private key in the vm's format * * @returns The address for the imported private key. */ importKey = async ( username: string, password: string, privateKey: string ): Promise<string> => { const params: ImportKeyParams = { username, password, privateKey } const response: RequestResponseData = await this.callMethod( "avm.importKey", params ) return response.data.result.address } /** * Send ANT (Avalanche Native Token) assets including AVAX from the X-Chain to an account on the P-Chain or C-Chain. * * After calling this method, you must call the P-Chain's `import` or the C-Chain’s `import` method to complete the transfer. * * @param username The Keystore user that controls the P-Chain or C-Chain account specified in `to` * @param password The password of the Keystore user * @param to The account on the P-Chain or C-Chain to send the asset to. * @param amount Amount of asset to export as a {@link https://github.com/indutny/bn.js/|BN} * @param assetID The asset id which is being sent * * @returns String representing the transaction id */ export = async ( username: string, password: string, to: string, amount: BN, assetID: string ): Promise<string> => { const params: ExportParams = { username, password, to, amount: amount, assetID } const response: RequestResponseData = await this.callMethod( "avm.export", params ) return response.data.result.txID } /** * Send ANT (Avalanche Native Token) assets including AVAX from an account on the P-Chain or C-Chain to an address on the X-Chain. This transaction * must be signed with the key of the account that the asset is sent from and which pays * the transaction fee. * * @param username The Keystore user that controls the account specified in `to` * @param password The password of the Keystore user * @param to The address of the account the asset is sent to. * @param sourceChain The chainID where the funds are coming from. Ex: "C" * * @returns Promise for a string for the transaction, which should be sent to the network * by calling issueTx. */ import = async ( username: string, password: string, to: string, sourceChain: string ): Promise<string> => { const params: ImportParams = { username, password, to, sourceChain } const response: RequestResponseData = await this.callMethod( "avm.import", params ) return response.data.result.txID } /** * Lists all the addresses under a user. * * @param username The user to list addresses * @param password The password of the user to list the addresses * * @returns Promise of an array of address strings in the format specified by the blockchain. */ listAddresses = async ( username: string, password: string ): Promise<string[]> => { const params: ListAddressesParams = { username, password } const response: RequestResponseData = await this.callMethod( "avm.listAddresses", params ) return response.data.result.addresses } /** * Retrieves all assets for an address on a server and their associated balances. * * @param address The address to get a list of assets * * @returns Promise of an object mapping assetID strings with {@link https://github.com/indutny/bn.js/|BN} balance for the address on the blockchain. */ getAllBalances = async (address: string): Promise<object[]> => { if (typeof this.parseAddress(address) === "undefined") { /* istanbul ignore next */ throw new AddressError( "Error - AVMAPI.getAllBalances: Invalid address format" ) } const params: GetAllBalancesParams = { address } const response: RequestResponseData = await this.callMethod( "avm.getAllBalances", params ) return response.data.result.balances } /** * Retrieves an assets name and symbol. * * @param assetID Either a {@link https://github.com/feross/buffer|Buffer} or an b58 serialized string for the AssetID or its alias. * * @returns Returns a Promise<object> with keys "name" and "symbol". */ getAssetDescription = async ( assetID: Buffer | string ): Promise<{ name: string symbol: string assetID: Buffer denomination: number }> => { let asset: string if (typeof assetID !== "string") { asset = bintools.cb58Encode(assetID) } else { asset = assetID } const params: GetAssetDescriptionParams = { assetID: asset } const response: RequestResponseData = await this.callMethod( "avm.getAssetDescription", params ) return { name: response.data.result.name, symbol: response.data.result.symbol, assetID: bintools.cb58Decode(response.data.result.assetID), denomination: parseInt(response.data.result.denomination, 10) } } /** * Returns the transaction data of a provided transaction ID by calling the node's `getTx` method. * * @param txID The string representation of the transaction ID * * @returns Returns a Promise<string> containing the bytes retrieved from the node */ getTx = async (txID: string): Promise<string> => { const params: GetTxParams = { txID } const response: RequestResponseData = await this.callMethod( "avm.getTx", params ) return response.data.result.tx } /** * Returns the status of a provided transaction ID by calling the node's `getTxStatus` method. * * @param txID The string representation of the transaction ID * * @returns Returns a Promise<string> containing the status retrieved from the node */ getTxStatus = async (txID: string): Promise<string> => { const params: GetTxStatusParams = { txID } const response: RequestResponseData = await this.callMethod( "avm.getTxStatus", params ) return response.data.result.status } /** * Retrieves the UTXOs related to the addresses provided from the node's `getUTXOs` method. * * @param addresses An array of addresses as cb58 strings or addresses as {@link https://github.com/feross/buffer|Buffer}s * @param sourceChain A string for the chain to look for the UTXO's. Default is to use this chain, but if exported UTXOs exist from other chains, this can used to pull them instead. * @param limit Optional. Returns at most [limit] addresses. If [limit] == 0 or > [maxUTXOsToFetch], fetches up to [maxUTXOsToFetch]. * @param startIndex Optional. [StartIndex] defines where to start fetching UTXOs (for pagination.) * UTXOs fetched are from addresses equal to or greater than [StartIndex.Address] * For address [StartIndex.Address], only UTXOs with IDs greater than [StartIndex.Utxo] will be returned. * @param persistOpts Options available to persist these UTXOs in local storage * * @remarks * persistOpts is optional and must be of type [[PersistanceOptions]] * */ getUTXOs = async ( addresses: string[] | string, sourceChain: string = undefined, limit: number = 0, startIndex: { address: string; utxo: string } = undefined, persistOpts: PersistanceOptions = undefined ): Promise<{ numFetched: number utxos: UTXOSet endIndex: { address: string; utxo: string } }> => { if (typeof addresses === "string") { addresses = [addresses] } const params: GetUTXOsParams = { addresses: addresses, limit } if (typeof startIndex !== "undefined" && startIndex) { params.startIndex = startIndex } if (typeof sourceChain !== "undefined") { params.sourceChain = sourceChain } const response: RequestResponseData = await this.callMethod( "avm.getUTXOs", params ) const utxos: UTXOSet = new UTXOSet() let data = response.data.result.utxos if (persistOpts && typeof persistOpts === "object") { if (this.db.has(persistOpts.getName())) { const selfArray: string[] = this.db.get(persistOpts.getName()) if (Array.isArray(selfArray)) { utxos.addArray(data) const utxoSet: UTXOSet = new UTXOSet() utxoSet.addArray(selfArray) utxoSet.mergeByRule(utxos, persistOpts.getMergeRule()) data = utxoSet.getAllUTXOStrings() } } this.db.set(persistOpts.getName(), data, persistOpts.getOverwrite()) } utxos.addArray(data, false) response.data.result.utxos = utxos return response.data.result } /** * Helper function which creates an unsigned transaction. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param amount The amount of AssetID to be spent in its smallest denomination, represented as {@link https://github.com/indutny/bn.js/|BN}. * @param assetID The assetID of the value being sent * @param toAddresses The addresses to send the funds * @param fromAddresses The addresses being used to send the funds from the UTXOs provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[BaseTx]]. * * @remarks * This helper exists because the endpoint API should be the primary point of entry for most functionality. */ buildBaseTx = async ( utxoset: UTXOSet, amount: BN, assetID: Buffer | string = undefined, toAddresses: string[], fromAddresses: string[], changeAddresses: string[], memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1 ): Promise<UnsignedTx> => { const to: Buffer[] = this._cleanAddressArray( toAddresses, "buildBaseTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildBaseTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildBaseTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) if (typeof assetID === "string") { assetID = bintools.cb58Decode(assetID) } if (memo instanceof PayloadBase) { memo = memo.getPayload() } const builtUnsignedTx: UnsignedTx = utxoset.buildBaseTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), amount, assetID, to, from, change, this.getTxFee(), await this.getAVAXAssetID(), memo, asOf, locktime, threshold ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildBaseTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Helper function which creates an unsigned NFT Transfer. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param toAddresses The addresses to send the NFT * @param fromAddresses The addresses being used to send the NFT from the utxoID provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param utxoid A base58 utxoID or an array of base58 utxoIDs for the nfts this transaction is sending * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[NFTTransferTx]]. * * @remarks * This helper exists because the endpoint API should be the primary point of entry for most functionality. */ buildNFTTransferTx = async ( utxoset: UTXOSet, toAddresses: string[], fromAddresses: string[], changeAddresses: string[], utxoid: string | string[], memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1 ): Promise<UnsignedTx> => { const to: Buffer[] = this._cleanAddressArray( toAddresses, "buildNFTTransferTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildNFTTransferTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildCreateNFTAssetTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } const avaxAssetID: Buffer = await this.getAVAXAssetID() let utxoidArray: string[] = [] if (typeof utxoid === "string") { utxoidArray = [utxoid] } else if (Array.isArray(utxoid)) { utxoidArray = utxoid } const builtUnsignedTx: UnsignedTx = utxoset.buildNFTTransferTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), to, from, change, utxoidArray, this.getTxFee(), avaxAssetID, memo, asOf, locktime, threshold ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildNFTTransferTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Helper function which creates an unsigned Import Tx. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param ownerAddresses The addresses being used to import * @param sourceChain The chainid for where the import is coming from * @param toAddresses The addresses to send the funds * @param fromAddresses The addresses being used to send the funds from the UTXOs provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[ImportTx]]. * * @remarks * This helper exists because the endpoint API should be the primary point of entry for most functionality. */ buildImportTx = async ( utxoset: UTXOSet, ownerAddresses: string[], sourceChain: Buffer | string, toAddresses: string[], fromAddresses: string[], changeAddresses: string[] = undefined, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1 ): Promise<UnsignedTx> => { const to: Buffer[] = this._cleanAddressArray( toAddresses, "buildImportTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildImportTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildImportTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) let srcChain: string = undefined if (typeof sourceChain === "undefined") { throw new ChainIdError( "Error - AVMAPI.buildImportTx: Source ChainID is undefined." ) } else if (typeof sourceChain === "string") { srcChain = sourceChain sourceChain = bintools.cb58Decode(sourceChain) } else if (!(sourceChain instanceof Buffer)) { throw new ChainIdError( "Error - AVMAPI.buildImportTx: Invalid destinationChain type: " + typeof sourceChain ) } const atomicUTXOs: UTXOSet = ( await this.getUTXOs(ownerAddresses, srcChain, 0, undefined) ).utxos const avaxAssetID: Buffer = await this.getAVAXAssetID() const atomics: UTXO[] = atomicUTXOs.getAllUTXOs() if (atomics.length === 0) { throw new NoAtomicUTXOsError( "Error - AVMAPI.buildImportTx: No atomic UTXOs to import from " + srcChain + " using addresses: " + ownerAddresses.join(", ") ) } if (memo instanceof PayloadBase) { memo = memo.getPayload() } const builtUnsignedTx: UnsignedTx = utxoset.buildImportTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), to, from, change, atomics, sourceChain, this.getTxFee(), avaxAssetID, memo, asOf, locktime, threshold ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildImportTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Helper function which creates an unsigned Export Tx. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param amount The amount being exported as a {@link https://github.com/indutny/bn.js/|BN} * @param destinationChain The chainid for where the assets will be sent. * @param toAddresses The addresses to send the funds * @param fromAddresses The addresses being used to send the funds from the UTXOs provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting outputs * @param threshold Optional. The number of signatures required to spend the funds in the resultant UTXO * @param assetID Optional. The assetID of the asset to send. Defaults to AVAX assetID. * Regardless of the asset which you"re exporting, all fees are paid in AVAX. * * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[ExportTx]]. */ buildExportTx = async ( utxoset: UTXOSet, amount: BN, destinationChain: Buffer | string, toAddresses: string[], fromAddresses: string[], changeAddresses: string[] = undefined, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0), threshold: number = 1, assetID: string = undefined ): Promise<UnsignedTx> => { const prefixes: object = {} toAddresses.map((a: string): void => { prefixes[a.split("-")[0]] = true }) if (Object.keys(prefixes).length !== 1) { throw new AddressError( "Error - AVMAPI.buildExportTx: To addresses must have the same chainID prefix." ) } if (typeof destinationChain === "undefined") { throw new ChainIdError( "Error - AVMAPI.buildExportTx: Destination ChainID is undefined." ) } else if (typeof destinationChain === "string") { destinationChain = bintools.cb58Decode(destinationChain) // } else if (!(destinationChain instanceof Buffer)) { throw new ChainIdError( "Error - AVMAPI.buildExportTx: Invalid destinationChain type: " + typeof destinationChain ) } if (destinationChain.length !== 32) { throw new ChainIdError( "Error - AVMAPI.buildExportTx: Destination ChainID must be 32 bytes in length." ) } const to: Buffer[] = [] toAddresses.map((a: string): void => { to.push(bintools.stringToAddress(a)) }) const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildExportTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildExportTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } const avaxAssetID: Buffer = await this.getAVAXAssetID() if (typeof assetID === "undefined") { assetID = bintools.cb58Encode(avaxAssetID) } const builtUnsignedTx: UnsignedTx = utxoset.buildExportTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), amount, bintools.cb58Decode(assetID), to, from, change, destinationChain, this.getTxFee(), avaxAssetID, memo, asOf, locktime, threshold ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildExportTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Creates an unsigned transaction. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param initialState The [[InitialStates]] that represent the intial state of a created asset * @param name String for the descriptive name of the asset * @param symbol String for the ticker symbol of the asset * @param denomination Number for the denomination which is 10^D. D must be >= 0 and <= 32. Ex: $1 AVAX = 10^9 $nAVAX * @param mintOutputs Optional. Array of [[SECPMintOutput]]s to be included in the transaction. These outputs can be spent to mint more tokens. * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[CreateAssetTx]]. * */ buildCreateAssetTx = async ( utxoset: UTXOSet, fromAddresses: string[], changeAddresses: string[], initialStates: InitialStates, name: string, symbol: string, denomination: number, mintOutputs: SECPMintOutput[] = undefined, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow() ): Promise<UnsignedTx> => { const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildCreateAssetTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildCreateNFTAssetTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } /* istanbul ignore next */ if (symbol.length > AVMConstants.SYMBOLMAXLEN) { /* istanbul ignore next */ throw new SymbolError( "Error - AVMAPI.buildCreateAssetTx: Symbols may not exceed length of " + AVMConstants.SYMBOLMAXLEN ) } /* istanbul ignore next */ if (name.length > AVMConstants.ASSETNAMELEN) { /* istanbul ignore next */ throw new NameError( "Error - AVMAPI.buildCreateAssetTx: Names may not exceed length of " + AVMConstants.ASSETNAMELEN ) } const avaxAssetID: Buffer = await this.getAVAXAssetID() const builtUnsignedTx: UnsignedTx = utxoset.buildCreateAssetTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), from, change, initialStates, name, symbol, denomination, mintOutputs, this.getCreationTxFee(), avaxAssetID, memo, asOf ) if (!(await this.checkGooseEgg(builtUnsignedTx, this.getCreationTxFee()))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildCreateAssetTx:Failed Goose Egg Check" ) } return builtUnsignedTx } buildSECPMintTx = async ( utxoset: UTXOSet, mintOwner: SECPMintOutput, transferOwner: SECPTransferOutput, fromAddresses: string[], changeAddresses: string[], mintUTXOID: string, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow() ): Promise<any> => { const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildSECPMintTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildSECPMintTx" ).map((a: string): Buffer => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } const avaxAssetID: Buffer = await this.getAVAXAssetID() const builtUnsignedTx: UnsignedTx = utxoset.buildSECPMintTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), mintOwner, transferOwner, from, change, mintUTXOID, this.getTxFee(), avaxAssetID, memo, asOf ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildSECPMintTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Creates an unsigned transaction. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param fromAddresses The addresses being used to send the funds from the UTXOs {@link https://github.com/feross/buffer|Buffer} * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param minterSets is a list where each element specifies that threshold of the addresses in minters may together mint more of the asset by signing a minting transaction * @param name String for the descriptive name of the asset * @param symbol String for the ticker symbol of the asset * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * @param locktime Optional. The locktime field created in the resulting mint output * * ```js * Example minterSets: * [ * { * "minters":[ * "X-avax1ghstjukrtw8935lryqtnh643xe9a94u3tc75c7" * ], * "threshold": 1 * }, * { * "minters": [ * "X-avax1yell3e4nln0m39cfpdhgqprsd87jkh4qnakklx", * "X-avax1k4nr26c80jaquzm9369j5a4shmwcjn0vmemcjz", * "X-avax1ztkzsrjnkn0cek5ryvhqswdtcg23nhge3nnr5e" * ], * "threshold": 2 * } * ] * ``` * * @returns An unsigned transaction ([[UnsignedTx]]) which contains a [[CreateAssetTx]]. * */ buildCreateNFTAssetTx = async ( utxoset: UTXOSet, fromAddresses: string[], changeAddresses: string[], minterSets: MinterSet[], name: string, symbol: string, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow(), locktime: BN = new BN(0) ): Promise<UnsignedTx> => { const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildCreateNFTAssetTx" ).map((a) => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildCreateNFTAssetTx" ).map((a) => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } if (name.length > AVMConstants.ASSETNAMELEN) { /* istanbul ignore next */ throw new NameError( "Error - AVMAPI.buildCreateNFTAssetTx: Names may not exceed length of " + AVMConstants.ASSETNAMELEN ) } if (symbol.length > AVMConstants.SYMBOLMAXLEN) { /* istanbul ignore next */ throw new SymbolError( "Error - AVMAPI.buildCreateNFTAssetTx: Symbols may not exceed length of " + AVMConstants.SYMBOLMAXLEN ) } const avaxAssetID: Buffer = await this.getAVAXAssetID() const builtUnsignedTx: UnsignedTx = utxoset.buildCreateNFTAssetTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), from, change, minterSets, name, symbol, this.getCreationTxFee(), avaxAssetID, memo, asOf, locktime ) if (!(await this.checkGooseEgg(builtUnsignedTx, this.getCreationTxFee()))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildCreateNFTAssetTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Creates an unsigned transaction. For more granular control, you may create your own * [[UnsignedTx]] manually (with their corresponding [[TransferableInput]]s, [[TransferableOutput]]s, and [[TransferOperation]]s). * * @param utxoset A set of UTXOs that the transaction is built on * @param owners Either a single or an array of [[OutputOwners]] to send the nft output * @param fromAddresses The addresses being used to send the NFT from the utxoID provided * @param changeAddresses The addresses that can spend the change remaining from the spent UTXOs * @param utxoid A base58 utxoID or an array of base58 utxoIDs for the nft mint output this transaction is sending * @param groupID Optional. The group this NFT is issued to. * @param payload Optional. Data for NFT Payload as either a [[PayloadBase]] or a {@link https://github.com/feross/buffer|Buffer} * @param memo Optional CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * @param asOf Optional. The timestamp to verify the transaction against as a {@link https://github.com/indutny/bn.js/|BN} * * @returns An unsigned transaction ([[UnsignedTx]]) which contains an [[OperationTx]]. * */ buildCreateNFTMintTx = async ( utxoset: UTXOSet, owners: OutputOwners[] | OutputOwners, fromAddresses: string[], changeAddresses: string[], utxoid: string | string[], groupID: number = 0, payload: PayloadBase | Buffer = undefined, memo: PayloadBase | Buffer = undefined, asOf: BN = UnixNow() ): Promise<any> => { const from: Buffer[] = this._cleanAddressArray( fromAddresses, "buildCreateNFTMintTx" ).map((a) => bintools.stringToAddress(a)) const change: Buffer[] = this._cleanAddressArray( changeAddresses, "buildCreateNFTMintTx" ).map((a) => bintools.stringToAddress(a)) if (memo instanceof PayloadBase) { memo = memo.getPayload() } if (payload instanceof PayloadBase) { payload = payload.getPayload() } if (typeof utxoid === "string") { utxoid = [utxoid] } const avaxAssetID: Buffer = await this.getAVAXAssetID() if (owners instanceof OutputOwners) { owners = [owners] } const builtUnsignedTx: UnsignedTx = utxoset.buildCreateNFTMintTx( this.core.getNetworkID(), bintools.cb58Decode(this.blockchainID), owners, from, change, utxoid, groupID, payload, this.getTxFee(), avaxAssetID, memo, asOf ) if (!(await this.checkGooseEgg(builtUnsignedTx))) { /* istanbul ignore next */ throw new GooseEggCheckError( "Error - AVMAPI.buildCreateNFTMintTx:Failed Goose Egg Check" ) } return builtUnsignedTx } /** * Helper function which takes an unsigned transaction and signs it, returning the resulting [[Tx]]. * * @param utx The unsigned transaction of type [[UnsignedTx]] * * @returns A signed transaction of type [[Tx]] */ signTx = (utx: UnsignedTx): Tx => utx.sign(this.keychain) /** * Calls the node's issueTx method from the API and returns the resulting transaction ID as a string. * * @param tx A string, {@link https://github.com/feross/buffer|Buffer}, or [[Tx]] representing a transaction * * @returns A Promise<string> representing the transaction ID of the posted transaction. */ issueTx = async (tx: string | Buffer | Tx): Promise<string> => { let Transaction = "" if (typeof tx === "string") { Transaction = tx } else if (tx instanceof Buffer) { const txobj: Tx = new Tx() txobj.fromBuffer(tx) Transaction = txobj.toString() } else if (tx instanceof Tx) { Transaction = tx.toString() } else { /* istanbul ignore next */ throw new TransactionError( "Error - AVMAPI.issueTx: provided tx is not expected type of string, Buffer, or Tx" ) } const params: IssueTxParams = { tx: Transaction.toString() } const response: RequestResponseData = await this.callMethod( "avm.issueTx", params ) return response.data.result.txID } /** * Sends an amount of assetID to the specified address from a list of owned of addresses. * * @param username The user that owns the private keys associated with the `from` addresses * @param password The password unlocking the user * @param assetID The assetID of the asset to send * @param amount The amount of the asset to be sent * @param to The address of the recipient * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction * @param changeAddr Optional. An address to send the change * @param memo Optional. CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * * @returns Promise for the string representing the transaction's ID. */ send = async ( username: string, password: string, assetID: string | Buffer, amount: number | BN, to: string, from: string[] | Buffer[] = undefined, changeAddr: string = undefined, memo: string | Buffer = undefined ): Promise<{ txID: string; changeAddr: string }> => { let asset: string let amnt: BN if (typeof this.parseAddress(to) === "undefined") { /* istanbul ignore next */ throw new AddressError("Error - AVMAPI.send: Invalid address format") } if (typeof assetID !== "string") { asset = bintools.cb58Encode(assetID) } else { asset = assetID } if (typeof amount === "number") { amnt = new BN(amount) } else { amnt = amount } const params: any = { username: username, password: password, assetID: asset, amount: amnt.toString(10), to: to } from = this._cleanAddressArray(from, "send") if (typeof from !== "undefined") { params["from"] = from } if (typeof changeAddr !== "undefined") { if (typeof this.parseAddress(changeAddr) === "undefined") { /* istanbul ignore next */ throw new AddressError("Error - AVMAPI.send: Invalid address format") } params["changeAddr"] = changeAddr } if (typeof memo !== "undefined") { if (typeof memo !== "string") { params["memo"] = bintools.cb58Encode(memo) } else { params["memo"] = memo } } const response: RequestResponseData = await this.callMethod( "avm.send", params ) return response.data.result } /** * Sends an amount of assetID to an array of specified addresses from a list of owned of addresses. * * @param username The user that owns the private keys associated with the `from` addresses * @param password The password unlocking the user * @param sendOutputs The array of SendOutputs. A SendOutput is an object literal which contains an assetID, amount, and to. * @param from Optional. An array of addresses managed by the node's keystore for this blockchain which will fund this transaction * @param changeAddr Optional. An address to send the change * @param memo Optional. CB58 Buffer or String which contains arbitrary bytes, up to 256 bytes * * @returns Promise for the string representing the transaction"s ID. */ sendMultiple = async ( username: string, password: string, sendOutputs: { assetID: string | Buffer amount: number | BN to: string }[], from: string[] | Buffer[] = undefined, changeAddr: string = undefined, memo: string | Buffer = undefined ): Promise<{ txID: string; changeAddr: string }> => { let asset: string let amnt: BN const sOutputs: SOutputsParams[] = [] sendOutputs.forEach( (output: { assetID: string | Buffer amount: number | BN to: string }) => { if (typeof this.parseAddress(output.to) === "undefined") { /* istanbul ignore next */ throw new AddressError( "Error - AVMAPI.sendMultiple: Invalid address format" ) } if (typeof output.assetID !== "string") { asset = bintools.cb58Encode(output.assetID) } else { asset = output.assetID } if (typeof output.amount === "number") { amnt = new BN(output.amount) } else { amnt = output.amount } sOutputs.push({ to: output.to, assetID: asset, amount: amnt.toString(10) }) } ) const params: SendMultipleParams = { username: username, password: password, outputs: sOutputs } from = this._cleanAddressArray(from, "send") if (typeof from !== "undefined") { params.from = from } if (typeof changeAddr !== "undefined") { if (typeof this.parseAddress(changeAddr) === "undefined") { /* istanbul ignore next */ throw new AddressError("Error - AVMAPI.send: Invalid address format") } params.changeAddr = changeAddr } if (typeof memo !== "undefined") { if (typeof memo !== "string") { params.memo = bintools.cb58Encode(memo) } else { params.memo = memo } } const response: RequestResponseData = await this.callMethod( "avm.sendMultiple", params ) return response.data.result } /** * Given a JSON representation of this Virtual Machine’s genesis state, create the byte representation of that state. * * @param genesisData The blockchain's genesis data object * * @returns Promise of a string of bytes */ buildGenesis = async (genesisData: object): Promise<string> => { const params: BuildGenesisParams = { genesisData } const response: RequestResponseData = await this.callMethod( "avm.buildGenesis", params ) return response.data.result.bytes } /** * @ignore */ protected _cleanAddressArray( addresses: string[] | Buffer[], caller: string ): string[] { const addrs: string[] = [] const chainID: string = this.getBlockchainAlias() ? this.getBlockchainAlias() : this.getBlockchainID() if (addresses && addresses.length > 0) { for (let i: number = 0; i < addresses.length; i++) { if (typeof addresses[`${i}`] === "string") { if ( typeof this.parseAddress(addresses[`${i}`] as string) === "undefined" ) { /* istanbul ignore next */ throw new AddressError( "Error - AVMAPI.${caller}: Invalid address format" ) } addrs.push(addresses[`${i}`] as string) } else { const type: SerializedType = "bech32" addrs.push( serialization.bufferToType( addresses[`${i}`] as Buffer, type, this.core.getHRP(), chainID ) ) } } } return addrs } /** * This class should not be instantiated directly. Instead use the [[Avalanche.addAP`${I}`]] method. * * @param core A reference to the Avalanche class * @param baseURL Defaults to the string "/ext/bc/X" as the path to blockchain's baseURL * @param blockchainID The Blockchain"s ID. Defaults to an empty string: "" */ constructor( core: AvalancheCore, baseURL: string = "/ext/bc/X", blockchainID: string = "" ) { super(core, baseURL) this.blockchainID = blockchainID const netID: number = core.getNetworkID() if ( netID in Defaults.network && blockchainID in Defaults.network[`${netID}`] ) { const { alias } = Defaults.network[`${netID}`][`${blockchainID}`] this.keychain = new KeyChain(this.core.getHRP(), alias) } else { this.keychain = new KeyChain(this.core.getHRP(), blockchainID) } } }
the_stack
export interface ParserOptions { /** Silently fail on parse errors */ silent?: boolean; /** * The path to the file containing css. * Makes errors and source maps more helpful, by letting them know where code comes from. */ source?: string; } /** * Error thrown during parsing. */ export interface ParserError { /** The full error message with the source position. */ message?: string; /** The error message without position. */ reason?: string; /** The value of options.source if passed to css.parse. Otherwise undefined. */ filename?: string; line?: number; column?: number; /** The portion of code that couldn't be parsed. */ source?: string; } export interface Loc { line?: number; column?: number; } /** * Base AST Tree Node. */ export interface Node { /** The possible values are the ones listed in the Types section on https://github.com/reworkcss/css page. */ type?: string; /** A reference to the parent node, or null if the node has no parent. */ parent?: Node; /** Information about the position in the source string that corresponds to the node. */ position?: { start?: Loc; end?: Loc; /** The value of options.source if passed to css.parse. Otherwise undefined. */ source?: string; /** The full source string passed to css.parse. */ content?: string; }; } export interface Rule extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: string[]; /** Array of nodes with the types declaration and comment. */ declarations?: Array<Declaration | Comment>; } export interface Declaration extends Node { /** The property name, trimmed from whitespace and comments. May not be empty. */ property?: string; /** The value of the property, trimmed from whitespace and comments. Empty values are allowed. */ value?: string; } /** * A rule-level or declaration-level comment. Comments inside selectors, properties and values etc. are lost. */ export interface Comment extends Node { comment?: string; } /** * The @charset at-rule. */ export interface Charset extends Node { /** The part following @charset. */ charset?: string; } /** * The @custom-media at-rule */ export interface CustomMedia extends Node { /** The ---prefixed name. */ name?: string; /** The part following the name. */ media?: string; } /** * The @document at-rule. */ export interface Document extends Node { /** The part following @document. */ document?: string; /** The vendor prefix in @document, or undefined if there is none. */ vendor?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array<Rule | Comment | AtRule>; } /** * The @font-face at-rule. */ export interface FontFace extends Node { /** Array of nodes with the types declaration and comment. */ declarations?: Array<Declaration | Comment>; } /** * The @host at-rule. */ export interface Host extends Node { /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array<Rule | Comment | AtRule>; } /** * The @import at-rule. */ export interface Import extends Node { /** The part following @import. */ import?: string; } /** * The @keyframes at-rule. */ export interface KeyFrames extends Node { /** The name of the keyframes rule. */ name?: string; /** The vendor prefix in @keyframes, or undefined if there is none. */ vendor?: string; /** Array of nodes with the types keyframe and comment. */ keyframes?: Array<KeyFrame | Comment>; } export interface KeyFrame extends Node { /** The list of "selectors" of the keyframe rule, split on commas. Each “selector” is trimmed from whitespace. */ values?: string[]; /** Array of nodes with the types declaration and comment. */ declarations?: Array<Declaration | Comment>; } /** * The @media at-rule. */ export interface Media extends Node { /** The part following @media. */ media?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array<Rule | Comment | AtRule>; } /** * The @namespace at-rule. */ export interface Namespace extends Node { /** The part following @namespace. */ namespace?: string; } /** * The @page at-rule. */ export interface Page extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: string[]; /** Array of nodes with the types declaration and comment. */ declarations?: Array<Declaration | Comment>; } /** * The @supports at-rule. */ export interface Supports extends Node { /** The part following @supports. */ supports?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array<Rule | Comment | AtRule>; } /** All at-rules. */ export type AtRule = | Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; /** * A collection of rules */ export interface StyleRules { source?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules: Array<Rule | Comment | AtRule>; /** Array of Errors. Errors collected during parsing when option silent is true. */ parsingErrors?: ParserError[]; } /** * The root node returned by css.parse. */ export interface Stylesheet extends Node { stylesheet?: StyleRules; } // http://www.w3.org/TR/CSS21/grammar.html // https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027 const commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g; export function parse(css: string, options: ParserOptions = {}) { /** * Positional. */ let lineno = 1; let column = 1; /** * Update lineno and column based on `str`. */ function updatePosition(str: string) { const lines = str.match(/\n/g); if (lines) { lineno += lines.length; } let i = str.lastIndexOf('\n'); column = i === -1 ? column + str.length : str.length - i; } /** * Mark position and patch `node.position`. */ function position() { const start = { line: lineno, column }; return ( node: Rule | Declaration | Comment | AtRule | Stylesheet | KeyFrame, ) => { node.position = new Position(start); whitespace(); return node; }; } /** * Store position information for a node */ class Position { public content!: string; public start!: Loc; public end!: Loc; public source?: string; constructor(start: Loc) { this.start = start; this.end = { line: lineno, column }; this.source = options.source; } } /** * Non-enumerable source string */ Position.prototype.content = css; const errorsList: ParserError[] = []; function error(msg: string) { const err = new Error( options.source + ':' + lineno + ':' + column + ': ' + msg, ) as ParserError; err.reason = msg; err.filename = options.source; err.line = lineno; err.column = column; err.source = css; if (options.silent) { errorsList.push(err); } else { throw err; } } /** * Parse stylesheet. */ function stylesheet(): Stylesheet { const rulesList = rules(); return { type: 'stylesheet', stylesheet: { source: options.source, rules: rulesList, parsingErrors: errorsList, }, }; } /** * Opening brace. */ function open() { return match(/^{\s*/); } /** * Closing brace. */ function close() { return match(/^}/); } /** * Parse ruleset. */ function rules() { let node: Rule | void; const rules: Rule[] = []; whitespace(); comments(rules); while (css.length && css.charAt(0) !== '}' && (node = atrule() || rule())) { if (node !== false) { rules.push(node); comments(rules); } } return rules; } /** * Match `re` and return captures. */ function match(re: RegExp) { const m = re.exec(css); if (!m) { return; } const str = m[0]; updatePosition(str); css = css.slice(str.length); return m; } /** * Parse whitespace. */ function whitespace() { match(/^\s*/); } /** * Parse comments; */ function comments(rules: Rule[] = []) { let c: Comment | void; while ((c = comment())) { if (c !== false) { rules.push(c); } c = comment(); } return rules; } /** * Parse comment. */ function comment() { const pos = position(); if ('/' !== css.charAt(0) || '*' !== css.charAt(1)) { return; } let i = 2; while ( '' !== css.charAt(i) && ('*' !== css.charAt(i) || '/' !== css.charAt(i + 1)) ) { ++i; } i += 2; if ('' === css.charAt(i - 1)) { return error('End of comment missing'); } const str = css.slice(2, i - 2); column += 2; updatePosition(str); css = css.slice(i); column += 2; return pos({ type: 'comment', comment: str, }); } /** * Parse selector. */ function selector() { const m = match(/^([^{]+)/); if (!m) { return; } /* @fix Remove all comments from selectors * http://ostermiller.org/findcomment.html */ return trim(m[0]) .replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '') .replace(/"(?:\\"|[^"])*"|'(?:\\'|[^'])*'/g, (m) => { return m.replace(/,/g, '\u200C'); }) .split(/\s*(?![^(]*\)),\s*/) .map((s) => { return s.replace(/\u200C/g, ','); }); } /** * Parse declaration. */ function declaration(): Declaration | void | never { const pos = position(); // prop let propMatch = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/); if (!propMatch) { return; } const prop = trim(propMatch[0]); // : if (!match(/^:\s*/)) { return error(`property missing ':'`); } // val const val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/); const ret = pos({ type: 'declaration', property: prop.replace(commentre, ''), value: val ? trim(val[0]).replace(commentre, '') : '', }); // ; match(/^[;\s]*/); return ret; } /** * Parse declarations. */ function declarations() { const decls: Array<object> = []; if (!open()) { return error(`missing '{'`); } comments(decls); // declarations let decl; while ((decl = declaration())) { if ((decl as unknown) !== false) { decls.push(decl); comments(decls); } decl = declaration(); } if (!close()) { return error(`missing '}'`); } return decls; } /** * Parse keyframe. */ function keyframe() { let m; const vals = []; const pos = position(); while ((m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/))) { vals.push(m[1]); match(/^,\s*/); } if (!vals.length) { return; } return pos({ type: 'keyframe', values: vals, declarations: declarations() as Declaration[], }); } /** * Parse keyframes. */ function atkeyframes() { const pos = position(); let m = match(/^@([-\w]+)?keyframes\s*/); if (!m) { return; } const vendor = m[1]; // identifier m = match(/^([-\w]+)\s*/); if (!m) { return error('@keyframes missing name'); } const name = m[1]; if (!open()) { return error(`@keyframes missing '{'`); } let frame; let frames = comments(); while ((frame = keyframe())) { frames.push(frame); frames = frames.concat(comments()); } if (!close()) { return error(`@keyframes missing '}'`); } return pos({ type: 'keyframes', name, vendor, keyframes: frames, }); } /** * Parse supports. */ function atsupports() { const pos = position(); const m = match(/^@supports *([^{]+)/); if (!m) { return; } const supports = trim(m[1]); if (!open()) { return error(`@supports missing '{'`); } const style = comments().concat(rules()); if (!close()) { return error(`@supports missing '}'`); } return pos({ type: 'supports', supports, rules: style, }); } /** * Parse host. */ function athost() { const pos = position(); const m = match(/^@host\s*/); if (!m) { return; } if (!open()) { return error(`@host missing '{'`); } const style = comments().concat(rules()); if (!close()) { return error(`@host missing '}'`); } return pos({ type: 'host', rules: style, }); } /** * Parse media. */ function atmedia() { const pos = position(); const m = match(/^@media *([^{]+)/); if (!m) { return; } const media = trim(m[1]); if (!open()) { return error(`@media missing '{'`); } const style = comments().concat(rules()); if (!close()) { return error(`@media missing '}'`); } return pos({ type: 'media', media, rules: style, }); } /** * Parse custom-media. */ function atcustommedia() { const pos = position(); const m = match(/^@custom-media\s+(--[^\s]+)\s*([^{;]+);/); if (!m) { return; } return pos({ type: 'custom-media', name: trim(m[1]), media: trim(m[2]), }); } /** * Parse paged media. */ function atpage() { const pos = position(); const m = match(/^@page */); if (!m) { return; } const sel = selector() || []; if (!open()) { return error(`@page missing '{'`); } let decls = comments(); // declarations let decl; while ((decl = declaration())) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) { return error(`@page missing '}'`); } return pos({ type: 'page', selectors: sel, declarations: decls, }); } /** * Parse document. */ function atdocument() { const pos = position(); const m = match(/^@([-\w]+)?document *([^{]+)/); if (!m) { return; } const vendor = trim(m[1]); const doc = trim(m[2]); if (!open()) { return error(`@document missing '{'`); } const style = comments().concat(rules()); if (!close()) { return error(`@document missing '}'`); } return pos({ type: 'document', document: doc, vendor, rules: style, }); } /** * Parse font-face. */ function atfontface() { const pos = position(); const m = match(/^@font-face\s*/); if (!m) { return; } if (!open()) { return error(`@font-face missing '{'`); } let decls = comments(); // declarations let decl; while ((decl = declaration())) { decls.push(decl); decls = decls.concat(comments()); } if (!close()) { return error(`@font-face missing '}'`); } return pos({ type: 'font-face', declarations: decls, }); } /** * Parse import */ const atimport = _compileAtrule('import'); /** * Parse charset */ const atcharset = _compileAtrule('charset'); /** * Parse namespace */ const atnamespace = _compileAtrule('namespace'); /** * Parse non-block at-rules */ function _compileAtrule(name: string) { const re = new RegExp('^@' + name + '\\s*([^;]+);'); return () => { const pos = position(); const m = match(re); if (!m) { return; } const ret: Record<string, string> = { type: name }; ret[name] = m[1].trim(); return pos(ret); }; } /** * Parse at rule. */ function atrule() { if (css[0] !== '@') { return; } return ( atkeyframes() || atmedia() || atcustommedia() || atsupports() || atimport() || atcharset() || atnamespace() || atdocument() || atpage() || athost() || atfontface() ); } /** * Parse rule. */ function rule() { const pos = position(); const sel = selector(); if (!sel) { return error('selector missing'); } comments(); return pos({ type: 'rule', selectors: sel, declarations: declarations() as Declaration[], }); } return addParent(stylesheet()); } /** * Trim `str`. */ function trim(str: string) { return str ? str.replace(/^\s+|\s+$/g, '') : ''; } /** * Adds non-enumerable parent node reference to each node. */ function addParent(obj: Stylesheet, parent?: Stylesheet) { const isNode = obj && typeof obj.type === 'string'; const childParent = isNode ? obj : parent; for (const k of Object.keys(obj)) { const value = obj[k as keyof Stylesheet]; if (Array.isArray(value)) { value.forEach((v) => { addParent(v, childParent); }); } else if (value && typeof value === 'object') { addParent((value as unknown) as Stylesheet, childParent); } } if (isNode) { Object.defineProperty(obj, 'parent', { configurable: true, writable: true, enumerable: false, value: parent || null, }); } return obj; }
the_stack
import { bySport, PHASE } from "../../common"; import type { DiscriminateUnion, DraftPickSeason, EventBBGM, MinimalPlayerRatings, Phase, Player, PlayerContract, PlayerStats, UpdateEvents, ViewInput, } from "../../common/types"; import { player, team } from "../core"; import { idb } from "../db"; import { g, getTeamInfoBySeason, helpers } from "../util"; import { assetIsPlayer, getPlayerFromPick } from "../util/formatEventText"; const findRatingsRow = ( allRatings: MinimalPlayerRatings[], ratingsIndex: number, season: number, phase: Phase, ) => { // If no data was deleted/edited, should work with just ratingsIndex const firstTry = allRatings[ratingsIndex]; if (firstTry !== undefined && firstTry.season === season) { return firstTry; } // Something's wrong! Look for first/last ratings entry that season based on phase if (phase <= PHASE.PLAYOFFS) { const ratings = allRatings.find(ratings => ratings.season >= season); if (ratings) { return ratings; } return allRatings.at(-1); } else { for (let i = allRatings.length - 1; i >= 0; i--) { const ratings = allRatings[i]; if (ratings.season <= season) { return ratings; } } return allRatings[0]; } }; const findStatSum = ( allStats: PlayerStats[], statsIndex: number | undefined, // undefined means it was a traded draft pick, so include all stats season: number, phase: Phase, statSumsBySeason?: Record<number, number>, ) => { // >= 0 check is for rookies traded after the draft, where they have no stats entry so it is -1 let index = statsIndex !== undefined && statsIndex >= 0 ? statsIndex : 0; // If no data was deleted/edited, should work with just statsIndex const firstTry = allStats[index]; if (firstTry === undefined || firstTry.season !== season) { // Something's wrong! Look for first stats entry that is after the trade index = allStats.findIndex(row => { return ( row.season > season || (row.season === season && !row.playoffs && phase < PHASE.PLAYOFFS) || (row.season === season && row.playoffs && phase <= PHASE.PLAYOFFS) ); }); } let statSum = 0; for (let i = 0; i < allStats.length; i++) { const row = allStats[i]; const stat = bySport({ basketball: row.ows + row.dws, football: row.av, hockey: row.ops + row.dps + row.gps, }); // Only after trade - undefined means traded draft pick, -1 means traded while stats array was empty (so all is after trade) if ( i > index || (i === index && phase <= PHASE.PLAYOFFS) || statsIndex === undefined || statsIndex === -1 ) { statSum += stat; } // Including before trade if (statSumsBySeason) { if ( row.season < g.get("season") || (row.season === g.get("season") && g.get("phase") >= PHASE.REGULAR_SEASON) ) { if (!statSumsBySeason[row.season]) { statSumsBySeason[row.season] = 0; } statSumsBySeason[row.season] += stat; } } } return statSum; }; const getActualPlayerInfo = ( p: Player, ratingsIndex: number, statsIndex: number | undefined, season: number, phase: Phase, statSumsBySeason?: Record<number, number>, draftPick: boolean = false, ) => { const ratings = findRatingsRow(p.ratings, ratingsIndex, season, phase); const stat = findStatSum( p.stats, statsIndex, season, phase, statSumsBySeason, ); return { name: `${p.firstName} ${p.lastName}`, age: (draftPick ? p.draft.year : season) - p.born.year, pos: ratings.pos, ovr: player.fuzzRating(ratings.ovr, ratings.fuzz), pot: player.fuzzRating(ratings.pot, ratings.fuzz), retiredYear: p.retiredYear, skills: ratings.skills, stat, watch: !!p.watch, }; }; const getSeasonsToPlot = async ( season: number, phase: Phase, tids: [number, number], statSumsBySeason: [Record<number, number>, Record<number, number>], ) => { // Default range of the plot, relative to the season of the trade const start = season - (phase <= PHASE.PLAYOFFS ? 2 : 1); let end = season + 5; // Extend end date if we have stats const statSeasons = [ ...Object.keys(statSumsBySeason[0]), ...Object.keys(statSumsBySeason[1]), ].map(x => parseInt(x)); const maxStatSeason = Math.max(...statSeasons); if (maxStatSeason > end) { end = maxStatSeason; } const seasons = []; const teamSeasonsIndex = idb.league .transaction("teamSeasons") .store.index("tid, season"); for (let i = start; i <= end; i++) { type Team = { winp?: number; ptsPct?: number; won?: number; lost?: number; tied?: number; otl?: number; stat?: number; }; const teams: [Team, Team] = [{}, {}]; for (let j = 0; j < tids.length; j++) { const tid = tids[j]; let teamSeason; if (i === g.get("season")) { teamSeason = await idb.cache.teamSeasons.indexGet( "teamSeasonsByTidSeason", [tid, i], ); } if (!teamSeason) { teamSeason = await teamSeasonsIndex.get([tid, i]); } if ( teamSeason && (teamSeason.won > 0 || teamSeason.lost > 0 || teamSeason.tied > 0 || teamSeason.otl > 0) ) { teams[j].won = teamSeason.won; teams[j].lost = teamSeason.lost; teams[j].tied = teamSeason.tied; teams[j].otl = teamSeason.otl; teams[j].winp = helpers.calcWinp(teamSeason); teams[j].ptsPct = team.ptsPct(teamSeason); } teams[j].stat = statSumsBySeason[j][i]; } seasons.push({ season: i, teams, }); } return seasons; }; type CommonPlayer = { pid: number; name: string; contract: PlayerContract; }; type CommonActualPlayer = { pid: number; name: string; age: number; pos: string; ovr: number; pot: number; retiredYear: number; skills: string[]; watch: boolean; stat: number; }; type CommonPick = { abbrev?: string; // from originalTid tid: number; // from originalTid round: number; season: DraftPickSeason; }; type TradeEvent = DiscriminateUnion<EventBBGM, "type", "trade">; type StatSumsBySeason = [Record<number, number>, Record<number, number>]; export const processAssets = async ( event: TradeEvent, i: number, statSumsBySeason?: StatSumsBySeason, ) => { if (!event.teams || event.phase === undefined) { throw new Error("Invalid event"); } const otherTid = event.tids[i === 0 ? 1 : 0]; const assets: ( | ({ type: "player"; } & CommonPlayer & CommonActualPlayer) | ({ type: "deletedPlayer"; } & CommonPlayer) | ({ type: "realizedPick"; pick: number; } & CommonPick & CommonActualPlayer) | ({ type: "unrealizedPick"; } & CommonPick) )[] = []; for (const asset of event.teams[i].assets) { if (assetIsPlayer(asset)) { const p = await idb.getCopy.players({ pid: asset.pid }, "noCopyCache"); const common = { pid: asset.pid, contract: asset.contract, }; if (p) { const playerInfo = getActualPlayerInfo( p, asset.ratingsIndex, asset.statsIndex, event.season, event.phase, statSumsBySeason ? statSumsBySeason[i] : undefined, ); assets.push({ type: "player", ...playerInfo, ...common, }); } else { assets.push({ type: "deletedPlayer", name: asset.name, ...common, }); } } else { // Show abbrev only if it's another team's pick let abbrev; if (otherTid !== asset.originalTid) { const season = typeof asset.season === "number" ? asset.season : event.season; const teamInfo = await getTeamInfoBySeason(asset.originalTid, season); if (teamInfo) { abbrev = teamInfo.abbrev; } else { abbrev = "???"; } } const common = { abbrev, tid: asset.originalTid, round: asset.round, season: asset.season, }; // Has the draft already happened? If so, fill in the player const p = await getPlayerFromPick(asset); if (p) { const playerInfo = getActualPlayerInfo( p, 0, undefined, event.season, event.phase, statSumsBySeason ? statSumsBySeason[i] : undefined, true, ); assets.push({ type: "realizedPick", pid: p.pid, pick: p.draft.pick, ...playerInfo, ...common, }); } else { assets.push({ type: "unrealizedPick", ...common, }); } } } return assets; }; const updateTradeSummary = async ( { eid }: ViewInput<"tradeSummary">, updateEvents: UpdateEvents, state: any, ) => { if ( updateEvents.includes("firstRun") || updateEvents.includes("gameSim") || updateEvents.includes("newPhase") || updateEvents.includes("playerMovement") || eid !== state.eid ) { const event = await idb.getCopy.events({ eid }, "noCopyCache"); if ( !event || event.type !== "trade" || !event.teams || event.phase === undefined ) { // https://stackoverflow.com/a/59923262/786644 const returnValue = { errorMessage: "Trade not found.", }; return returnValue; } const teams = []; const statSumsBySeason: StatSumsBySeason = [{}, {}]; for (let i = 0; i < event.tids.length; i++) { const tid = event.tids[i]; const teamInfo = await getTeamInfoBySeason(tid, event.season); if (!teamInfo) { throw new Error("teamInfo not found"); } const assets = await processAssets(event, i, statSumsBySeason); let statSum = 0; for (const asset of assets) { // https://github.com/microsoft/TypeScript/issues/21732 const stat = (asset as any).stat; if (typeof stat === "number") { statSum += stat; } } teams.push({ abbrev: teamInfo.abbrev, region: teamInfo.region, name: teamInfo.name, tid, assets, statSum, }); } const seasonsToPlot = await getSeasonsToPlot( event.season, event.phase, event.tids as [number, number], statSumsBySeason, ); const pointsFormula = g.get("pointsFormula"); const usePts = pointsFormula !== ""; return { challengeNoRatings: g.get("challengeNoRatings"), eid, teams, season: event.season, phase: event.phase, stat: bySport({ basketball: "WS", football: "AV", hockey: "PS" }), seasonsToPlot, usePts, }; } }; export default updateTradeSummary;
the_stack
import { getVoidLogger } from '@backstage/backend-common'; import { ConfigReader } from '@backstage/config'; import { Client, errors } from '@elastic/elasticsearch'; import Mock from '@elastic/elasticsearch-mock'; import { ElasticSearchConcreteQuery, decodePageCursor, ElasticSearchSearchEngine, encodePageCursor, } from './ElasticSearchSearchEngine'; import { ElasticSearchSearchEngineIndexer } from './ElasticSearchSearchEngineIndexer'; jest.mock('uuid', () => ({ v4: () => 'tag' })); class ElasticSearchSearchEngineForTranslatorTests extends ElasticSearchSearchEngine { getTranslator() { return this.translator; } } const mock = new Mock(); const options = { node: 'http://localhost:9200', Connection: mock.getConnection(), }; const indexerMock = { on: jest.fn(), indexName: 'expected-index-name', }; jest.mock('./ElasticSearchSearchEngineIndexer', () => ({ ElasticSearchSearchEngineIndexer: jest .fn() .mockImplementation(() => indexerMock), })); describe('ElasticSearchSearchEngine', () => { let testSearchEngine: ElasticSearchSearchEngine; let inspectableSearchEngine: ElasticSearchSearchEngineForTranslatorTests; let client: Client; beforeEach(() => { testSearchEngine = new ElasticSearchSearchEngine( options, 'search', '', getVoidLogger(), ); inspectableSearchEngine = new ElasticSearchSearchEngineForTranslatorTests( options, 'search', '', getVoidLogger(), ); // eslint-disable-next-line dot-notation client = testSearchEngine['elasticSearchClient']; }); describe('queryTranslator', () => { beforeAll(() => { mock.clearAll(); mock.add( { method: 'POST', path: '/*__search/_search', }, () => ({ hits: { total: { value: 0, relation: 'eq' }, hits: [], }, }), ); }); it('should invoke the query translator', async () => { const translatorSpy = jest.fn().mockReturnValue({ elasticSearchQuery: () => ({ toJSON: () => JSON.stringify({ query: { match_all: {}, }, }), }), documentTypes: [], }); testSearchEngine.setTranslator(translatorSpy); await testSearchEngine.query({ term: 'testTerm', filters: {}, }); expect(translatorSpy).toHaveBeenCalledWith( { term: 'testTerm', filters: {}, }, { highlightOptions: { preTag: `<tag>`, postTag: `</tag>`, fragmentSize: 1000, numFragments: 1, fragmentDelimiter: ' ... ', }, }, ); }); it('should return translated query with 1 filter', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = translatorUnderTest({ types: ['indexName'], term: 'testTerm', filters: { kind: 'testKind' }, }) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toMatchObject({ documentTypes: ['indexName'], elasticSearchQuery: expect.any(Object), }); const queryBody = actualTranslatedQuery.elasticSearchQuery; expect(queryBody).toEqual({ query: { bool: { must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, filter: { match: { 'kind.keyword': 'testKind', }, }, }, }, from: 0, size: 25, }); }); it('should pass page cursor', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = translatorUnderTest({ types: ['indexName'], term: 'testTerm', pageCursor: 'MQ==', }) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toMatchObject({ documentTypes: ['indexName'], elasticSearchQuery: expect.any(Object), }); const queryBody = actualTranslatedQuery.elasticSearchQuery; expect(queryBody).toEqual({ query: { bool: { filter: [], must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, }, }, from: 25, size: 25, }); }); it('should return translated query with multiple filters', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = translatorUnderTest({ types: ['indexName'], term: 'testTerm', filters: { kind: 'testKind', namespace: 'testNameSpace', foo: 123, bar: true, }, }) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toMatchObject({ documentTypes: ['indexName'], elasticSearchQuery: expect.any(Object), }); const queryBody = actualTranslatedQuery.elasticSearchQuery; expect(queryBody).toEqual({ query: { bool: { must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, filter: [ { match: { 'kind.keyword': 'testKind', }, }, { match: { 'namespace.keyword': 'testNameSpace', }, }, { match: { foo: '123', }, }, { match: { bar: 'true', }, }, ], }, }, from: 0, size: 25, }); }); it('should return translated query with filter with multiple values', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = translatorUnderTest({ types: ['indexName'], term: 'testTerm', filters: { kind: ['testKind', 'kastTeint'] }, }) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toMatchObject({ documentTypes: ['indexName'], elasticSearchQuery: expect.any(Object), }); const queryBody = actualTranslatedQuery.elasticSearchQuery; expect(queryBody).toEqual({ query: { bool: { must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, filter: { bool: { should: [ { match: { kind: 'testKind', }, }, { match: { kind: 'kastTeint', }, }, ], }, }, }, }, from: 0, size: 25, }); }); it('should accept custom highlight options', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = translatorUnderTest( { types: ['indexName'], term: 'testTerm', pageCursor: 'MQ==', }, { highlightOptions: { preTag: `<custom-tag>`, postTag: `</custom-tag>`, fragmentSize: 100, numFragments: 3, fragmentDelimiter: ' ... ', }, }, ) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toMatchObject({ documentTypes: ['indexName'], elasticSearchQuery: expect.any(Object), }); const queryBody = actualTranslatedQuery.elasticSearchQuery; expect(queryBody).toEqual({ query: { bool: { filter: [], must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, }, }, highlight: { fields: { '*': {} }, fragment_size: 100, number_of_fragments: 3, pre_tags: ['<custom-tag>'], post_tags: ['</custom-tag>'], }, from: 25, size: 25, }); }); it('should throw if unsupported filter shapes passed in', async () => { const translatorUnderTest = inspectableSearchEngine.getTranslator(); const actualTranslatedQuery = () => translatorUnderTest({ types: ['indexName'], term: 'testTerm', filters: { kind: { a: 'b' } }, }) as ElasticSearchConcreteQuery; expect(actualTranslatedQuery).toThrow(); }); }); describe('query functionality', () => { beforeEach(() => { mock.clearAll(); mock.add( { method: 'GET', path: '/_cat/aliases/test-index__search', }, () => [ { alias: 'test-index__search', index: 'test-index-index__1626850643538', filter: '-', 'routing.index': '-', 'routing.search': '-', is_write_index: '-', }, ], ); mock.add( { method: 'POST', path: ['/_bulk'], }, () => ({ took: 30, errors: false, items: [ { index: { _index: 'test', _type: '_doc', _id: '1', _version: 1, result: 'created', _shards: { total: 2, successful: 1, failed: 0, }, status: 201, _seq_no: 0, _primary_term: 1, }, }, ], }), ); mock.add( { method: 'POST', path: '/*__search/_search', }, () => ({ hits: { total: { value: 0, relation: 'eq' }, hits: [], }, }), ); }); // Mostly useless test since we are more or less testing the mock, runs through the whole flow though // We might want to spin up ES test container to run against the real engine. // That container eats GBs of memory so opting out of that for now... it('should perform search query and return 0 results on empty index', async () => { const mockedSearchResult = await testSearchEngine.query({ term: 'testTerm', filters: {}, }); // Should return 0 results as nothing is indexed here expect(mockedSearchResult).toMatchObject({ results: [], nextPageCursor: undefined, }); }); it('should perform search query with less results than one page', async () => { mock.clear({ method: 'POST', path: '/*__search/_search', }); mock.add( { method: 'POST', path: '/*__search/_search', }, () => { return { hits: { total: { value: 20, relation: 'eq' }, hits: Array(20) .fill(null) .map((_, i) => ({ _index: 'mytype-index__', _source: { value: `${i}`, }, })), }, }; }, ); const mockedSearchResult = await testSearchEngine.query({ term: 'testTerm', filters: {}, }); expect(mockedSearchResult).toMatchObject({ results: expect.arrayContaining( Array(20) .fill(null) .map((_, i) => ({ type: 'mytype', document: { value: `${i}` }, })), ), }); }); it('should perform search query with more results than one page', async () => { mock.clear({ method: 'POST', path: '/*__search/_search', }); mock.add( { method: 'POST', path: '/*__search/_search', }, () => { return { hits: { total: { value: 30, relation: 'eq' }, hits: Array(25) .fill(null) .map((_, i) => ({ _index: 'mytype-index__', _source: { value: `${i}`, }, })), }, }; }, ); const mockedSearchResult = await testSearchEngine.query({ term: 'testTerm', filters: {}, }); expect(mockedSearchResult).toMatchObject({ results: expect.arrayContaining( Array(25) .fill(null) .map((_, i) => ({ type: 'mytype', document: { value: `${i}` }, })), ), nextPageCursor: 'MQ==', }); }); it('should perform search query for second page', async () => { mock.clear({ method: 'POST', path: '/*__search/_search', }); mock.add( { method: 'POST', path: '/*__search/_search', }, () => { return { hits: { total: { value: 30, relation: 'eq' }, hits: Array(30) .fill(null) .map((_, i) => ({ _index: 'mytype-index__', _source: { value: `${i}`, }, })) .slice(25), }, }; }, ); const mockedSearchResult = await testSearchEngine.query({ term: 'testTerm', filters: {}, pageCursor: 'MQ==', }); expect(mockedSearchResult).toMatchObject({ results: expect.arrayContaining( Array(30) .fill(null) .map((_, i) => ({ type: 'mytype', document: { value: `${i}` }, })) .slice(25), ), previousPageCursor: 'MA==', }); }); it('should handle parsing highlights in search query results', async () => { mock.clear({ method: 'POST', path: '/*__search/_search', }); mock.add( { method: 'POST', path: '/*__search/_search', }, () => { return { hits: { total: { value: 30, relation: 'eq' }, hits: Array(25) .fill(null) .map((_, i) => ({ _index: 'mytype-index__', _source: { value: `${i}`, }, highlight: { foo: [ 'highlighted <tag>test</tag> result', 'another <tag>fragment</tag> result', ], bar: ['more <tag>test</tag> results'], }, })), }, }; }, ); const mockedSearchResult = await testSearchEngine.query({ term: 'testTerm', filters: {}, }); expect(mockedSearchResult).toMatchObject({ results: expect.arrayContaining( Array(25) .fill(null) .map((_, i) => ({ type: 'mytype', document: { value: `${i}` }, highlight: { preTag: '<tag>', postTag: '</tag>', fields: { foo: 'highlighted <tag>test</tag> result ... another <tag>fragment</tag> result', bar: 'more <tag>test</tag> results', }, }, })), ), nextPageCursor: 'MQ==', }); }); it('should handle index/search type filtering correctly', async () => { const elasticSearchQuerySpy = jest.spyOn(client, 'search'); await testSearchEngine.query({ term: 'testTerm', filters: {}, }); expect(elasticSearchQuerySpy).toHaveBeenCalled(); expect(elasticSearchQuerySpy).toHaveBeenCalledWith({ body: { query: { bool: { must: { multi_match: { query: 'testTerm', fields: ['*'], fuzziness: 'auto', minimum_should_match: 1, }, }, filter: [], }, }, highlight: { fields: { '*': {} }, fragment_size: 1000, number_of_fragments: 1, pre_tags: ['<tag>'], post_tags: ['</tag>'], }, from: 0, size: 25, }, index: '*__search', }); elasticSearchQuerySpy.mockClear(); }); it('should create matchAll query if no term defined', async () => { const elasticSearchQuerySpy = jest.spyOn(client, 'search'); await testSearchEngine.query({ term: '', filters: {}, }); expect(elasticSearchQuerySpy).toHaveBeenCalled(); expect(elasticSearchQuerySpy).toHaveBeenCalledWith({ body: { query: { bool: { must: { match_all: {}, }, filter: [], }, }, highlight: { fields: { '*': {} }, fragment_size: 1000, number_of_fragments: 1, pre_tags: ['<tag>'], post_tags: ['</tag>'], }, from: 0, size: 25, }, index: '*__search', }); elasticSearchQuerySpy.mockClear(); }); it('should query only specified indices if defined', async () => { const elasticSearchQuerySpy = jest.spyOn(client, 'search'); await testSearchEngine.query({ term: '', filters: {}, types: ['test-type'], }); expect(elasticSearchQuerySpy).toHaveBeenCalled(); expect(elasticSearchQuerySpy).toHaveBeenCalledWith({ body: { query: { bool: { must: { match_all: {}, }, filter: [], }, }, highlight: { fields: { '*': {} }, fragment_size: 1000, number_of_fragments: 1, pre_tags: ['<tag>'], post_tags: ['</tag>'], }, from: 0, size: 25, }, index: ['test-type__search'], }); elasticSearchQuerySpy.mockClear(); }); }); describe('indexer', () => { it('should get indexer', async () => { const indexer = await testSearchEngine.getIndexer('test-index'); expect(indexer).toStrictEqual(indexerMock); expect(ElasticSearchSearchEngineIndexer).toHaveBeenCalledWith( expect.objectContaining({ alias: 'test-index__search', type: 'test-index', indexPrefix: '', indexSeparator: '-index__', elasticSearchClient: client, }), ); expect(indexerMock.on).toHaveBeenCalledWith( 'error', expect.any(Function), ); }); describe('onError', () => { let errorHandler: Function; const error = new Error('some error'); beforeEach(async () => { mock.clearAll(); await testSearchEngine.getIndexer('test-index'); errorHandler = indexerMock.on.mock.calls[0][1]; }); it('should check for and delete expected index', async () => { const existsSpy = jest.fn().mockReturnValue('truthy value'); const deleteSpy = jest.fn().mockReturnValue({}); mock.add({ method: 'HEAD', path: '/expected-index-name' }, existsSpy); mock.add({ method: 'DELETE', path: '/expected-index-name' }, deleteSpy); await errorHandler(error); // Check and delete HTTP requests were made. expect(existsSpy).toHaveBeenCalled(); expect(deleteSpy).toHaveBeenCalled(); }); it('should not delete index if none exists', async () => { // Exists call returns 404 on no index. const existsSpy = jest.fn().mockReturnValue( new errors.ResponseError({ statusCode: 404, body: { status: 404 }, } as unknown as any), ); const deleteSpy = jest.fn().mockReturnValue({}); mock.add({ method: 'HEAD', path: '/expected-index-name' }, existsSpy); mock.add({ method: 'DELETE', path: '/expected-index-name' }, deleteSpy); await errorHandler(error); // Check request was made, but no delete request was made. expect(existsSpy).toHaveBeenCalled(); expect(deleteSpy).not.toHaveBeenCalled(); }); }); }); describe('ElasticSearchSearchEngine.fromConfig', () => { it('accesses the clientOptions and highlightOptions config', async () => { const esOptions = { clientOptions: { ssl: { rejectUnauthorized: true, }, }, node: 'http://test-node', auth: { apiKey: 'key', }, }; const config = new ConfigReader({}); const esConfig = new ConfigReader(esOptions); jest.spyOn(config, 'getConfig').mockImplementation(() => esConfig); const getOptionalConfig = jest.spyOn(esConfig, 'getOptionalConfig'); const getOptional = jest.spyOn(config, 'getOptional'); await ElasticSearchSearchEngine.fromConfig({ logger: getVoidLogger(), config, }); expect(getOptionalConfig.mock.calls[0][0]).toEqual('clientOptions'); expect(getOptional.mock.calls[0][0]).toEqual( 'search.elasticsearch.highlightOptions', ); }); it('does not require the clientOptions or highlightOptions config', async () => { const config = new ConfigReader({ search: { elasticsearch: { node: 'http://test-node', auth: { apiKey: 'test-key', }, }, }, }); expect( async () => await ElasticSearchSearchEngine.fromConfig({ logger: getVoidLogger(), config, }), ).not.toThrowError(); }); }); }); describe('decodePageCursor', () => { test('should decode page', () => { expect(decodePageCursor('MQ==')).toEqual({ page: 1 }); }); test('should fallback to first page if empty', () => { expect(decodePageCursor()).toEqual({ page: 0 }); }); }); describe('encodePageCursor', () => { test('should encode page', () => { expect(encodePageCursor({ page: 1 })).toEqual('MQ=='); }); });
the_stack
import * as Api from './api/v2'; import * as ApiV1 from './api/v1'; import * as ActionsApi from '../actionssdk/api/v2'; import { Conversation, ConversationBaseOptions, ConversationOptionsInit, } from '../actionssdk'; import {ProtoAny, JsonObject} from '../../common'; import {Contexts, ContextValues, Parameters} from './context'; import {Incoming} from './incoming'; const CONV_DATA_CONTEXT = '_actions_on_google'; const CONV_DATA_CONTEXT_LIFESPAN = 99; const SIMULATOR_WARNING = 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.'; /** @hidden */ export interface SystemIntent { intent: string; data: ProtoAny<string, JsonObject>; } /** @hidden */ export interface GoogleAssistantResponse { expectUserResponse?: boolean; noInputPrompts?: ActionsApi.GoogleActionsV2SimpleResponse[]; isSsml?: boolean; richResponse?: ActionsApi.GoogleActionsV2RichResponse; systemIntent?: SystemIntent; userStorage?: string; speechBiasingHints?: string[]; } /** @hidden */ export interface PayloadGoogle { google: GoogleAssistantResponse; } /** @public */ export interface DialogflowConversationOptions<TConvData, TUserStorage> extends ConversationBaseOptions<TConvData, TUserStorage> { /** @public */ body?: | Api.GoogleCloudDialogflowV2WebhookRequest | ApiV1.DialogflowV1WebhookRequest; } const isV1 = ( body: | Api.GoogleCloudDialogflowV2WebhookRequest | ApiV1.DialogflowV1WebhookRequest ): body is ApiV1.DialogflowV1WebhookRequest => !!(body as ApiV1.DialogflowV1WebhookRequest).result; const isSimulator = ( body: | Api.GoogleCloudDialogflowV2WebhookRequest | ApiV1.DialogflowV1WebhookRequest ) => { if (isV1(body)) { return !body.originalRequest; } if (!body.originalDetectIntentRequest) { return false; } return ( Object.keys(body.originalDetectIntentRequest.payload!).length === 0 && !!body.responseId ); }; const getRequest = ( body: | Api.GoogleCloudDialogflowV2WebhookRequest | ApiV1.DialogflowV1WebhookRequest ): ActionsApi.GoogleActionsV2AppRequest => { if (isV1(body)) { const {originalRequest = {}} = body; const {data = {}} = originalRequest; return data; } const {originalDetectIntentRequest = {}} = body; const {payload = {}} = originalDetectIntentRequest; return payload; }; const serializeData = <TConvData>(data: TConvData) => JSON.stringify(data); const deserializeData = <TContexts extends Contexts, TConvData>( contexts: ContextValues<TContexts>, defaultData?: TConvData ): TConvData => { const context = contexts.get(CONV_DATA_CONTEXT); if (context) { const {data} = context.parameters; if (typeof data === 'string') { return JSON.parse(data); } } return Object.assign({}, defaultData) as TConvData; }; /** @public */ export class DialogflowConversation< TConvData = JsonObject, TUserStorage = JsonObject, TContexts extends Contexts = Contexts > extends Conversation<TUserStorage> { /** @public */ body: | Api.GoogleCloudDialogflowV2WebhookRequest | ApiV1.DialogflowV1WebhookRequest; /** * Get the current Dialogflow action name. * * @example * ```javascript * * app.intent('Default Welcome Intent', conv => { * const action = conv.action * }) * ``` * * @public */ action: string; /** * Get the current Dialogflow intent name. * * @example * ```javascript * * app.intent('Default Welcome Intent', conv => { * const intent = conv.intent // will be 'Default Welcome Intent' * }) * ``` * * @public */ intent: string; /** * The Dialogflow parameters from the current intent. * Values will only be a string, an Object, or undefined if not included. * * Will also be sent via intent handler 3rd argument which is the encouraged method to retrieve. * * @example * ```javascript * * // Encouraged method through intent handler * app.intent('Tell Greeting', (conv, params) => { * const color = params.color * const num = params.num * }) * * // Encouraged method through destructuring in intent handler * app.intent('Tell Greeting', (conv, { color, num }) => { * // now use color and num as variables * })) * * // Using conv.parameters * app.intent('Tell Greeting', conv => { * const parameters = conv.parameters * // or destructed * const { color, num } = conv.parameters * }) * ``` * * @public */ parameters: Parameters; /** @public */ contexts: ContextValues<TContexts>; /** @public */ incoming: Incoming; /** * The user's raw input query. * * @example * ```javascript * * app.intent('User Input', conv => { * conv.close(`You said ${conv.query}`) * }) * ``` * * @public */ query: string; /** * The session data in JSON format. * Stored using contexts. * * @example * ```javascript * * app.intent('Default Welcome Intent', conv => { * conv.data.someProperty = 'someValue' * }) * ``` * * @public */ data: TConvData; /** @public */ version: number; /** @hidden */ _followup?: | Api.GoogleCloudDialogflowV2EventInput | ApiV1.DialogflowV1FollowupEvent; /** @hidden */ _init: ConversationOptionsInit<TConvData, TUserStorage>; /** @public */ constructor( options: DialogflowConversationOptions<TConvData, TUserStorage> = {} ) { const {body = {}} = options; super({ request: getRequest(body), headers: options.headers, init: options.init, ordersv3: options.ordersv3, }); this.body = body; if (isV1(this.body)) { this.version = 1; const {result = {}} = this.body; const { action = '', parameters = {}, contexts, resolvedQuery = '', metadata = {}, fulfillment, } = result; const {intentName = ''} = metadata; this.action = action; this.intent = intentName; this.parameters = parameters; this.contexts = new ContextValues(contexts); this.incoming = new Incoming(fulfillment); this.query = resolvedQuery; } else { this.version = 2; const {queryResult = {}} = this.body; const { action = '', parameters = {}, outputContexts, intent = {}, queryText = '', fulfillmentMessages, } = queryResult; const {displayName = ''} = intent; this.action = action; this.intent = displayName; this.parameters = parameters; this.contexts = new ContextValues(outputContexts, this.body.session); this.incoming = new Incoming(fulfillmentMessages); this.query = queryText; } for (const key in this.parameters) { const value = this.parameters[key]; if (typeof value !== 'object') { // Convert all non-objects to strings for consistency this.parameters[key] = String(value); } } this.data = deserializeData(this.contexts, this._init.data); } /** * Triggers an intent of your choosing by sending a followup event from the webhook. * Final response can theoretically include responses but these will not be handled * by Dialogflow. Dialogflow will not pass anything back to Google Assistant, therefore * Google Assistant specific information, most notably conv.user.storage, is ignored. * * @example * ```javascript * * const app = dialogflow() * * // Create a Dialogflow intent with event 'apply-for-license-event' * * app.intent('Default Welcome Intent', conv => { * conv.followup('apply-for-license-event', { * date: new Date().toISOString(), * }) * // The dialogflow intent with the 'apply-for-license-event' event * // will be triggered with the given parameters `date` * }) * ``` * * @param event Name of the event * @param parameters Parameters to send with the event * @param lang The language of this query. * See {@link https://dialogflow.com/docs/languages|Language Support} * for a list of the currently supported language codes. * Note that queries in the same session do not necessarily need to specify the same language. * By default, it is the languageCode sent with Dialogflow's queryResult.languageCode * @public */ followup(event: string, parameters?: Parameters, lang?: string) { this._responded = true; if (this.version === 1) { this._followup = { name: event, data: parameters, }; return this; } const body = this.body as Api.GoogleCloudDialogflowV2WebhookRequest; this._followup = { name: event, parameters, languageCode: lang || body.queryResult!.languageCode, }; return this; } /** @public */ serialize(): | Api.GoogleCloudDialogflowV2WebhookResponse | ApiV1.DialogflowV1WebhookResponse { if (this._raw) { return this._raw; } let payload: PayloadGoogle | undefined; if (this._followup) { this.digested = true; } else { const { richResponse, expectUserResponse, userStorage, expectedIntent, noInputPrompts, speechBiasingHints, } = this.response(); const google: GoogleAssistantResponse = { expectUserResponse, systemIntent: expectedIntent && { intent: expectedIntent.intent!, data: expectedIntent.inputValueData as ProtoAny<string, JsonObject>, }, noInputPrompts, speechBiasingHints, }; if (richResponse.items!.length) { google.richResponse = richResponse; } if (userStorage) { google.userStorage = userStorage; } payload = {google}; } const convDataDefault = deserializeData<TContexts, TConvData>( this.contexts, this._init.data ); const convDataIn = serializeData(convDataDefault); const convDataOut = serializeData(this.data); if (convDataOut !== convDataIn) { // Previously was setting every webhook call // But now will only set if different so lifespan does not get reset this.contexts.set(CONV_DATA_CONTEXT, CONV_DATA_CONTEXT_LIFESPAN, { data: convDataOut, }); } const simulator = isSimulator(this.body); if (this.version === 1) { const response: ApiV1.DialogflowV1WebhookResponse = { data: payload, followupEvent: this._followup, }; const contextOut = this.contexts._serializeV1(); if (contextOut.length) { response.contextOut = contextOut; } if (simulator && payload) { const {richResponse = {}} = payload.google; const {items = []} = richResponse; // Simulator only shows speech response // Since this is only shown to the simulator as text, the speech is the displayText response.speech = SIMULATOR_WARNING; if (!payload.google.systemIntent && items.length < 2) { for (const {simpleResponse} of items) { if (simpleResponse) { response.speech = simpleResponse.displayText || simpleResponse.textToSpeech; break; } } } } return response; } const response: Api.GoogleCloudDialogflowV2WebhookResponse = { payload, followupEventInput: this._followup, }; const outputContexts = this.contexts._serialize(); if (outputContexts.length) { response.outputContexts = outputContexts; } if (simulator && payload) { const {richResponse = {}} = payload.google; const {items = []} = richResponse; response.fulfillmentText = SIMULATOR_WARNING; if (!payload.google.systemIntent && items.length < 2) { for (const {simpleResponse} of items) { if (simpleResponse) { response.fulfillmentText = simpleResponse.displayText || simpleResponse.textToSpeech; break; } } } } return response; } }
the_stack
import assert from "assert"; import * as vscode from "vscode"; import { Position, Range, Selection } from "vscode"; import { moveCommandIds } from "../../../../commands/move"; import { EmacsEmulator } from "../../../../emulator"; import { KillRing } from "../../../../kill-yank/kill-ring"; import { assertCursorsEqual, assertTextEqual, cleanUpWorkspace, clearTextEditor, setEmptyCursors, setupWorkspace, } from "../../utils"; suite("kill, yank, yank-pop", () => { let activeTextEditor: vscode.TextEditor; suite("with empty initial text", () => { setup(async () => { activeTextEditor = await setupWorkspace(); await vscode.env.clipboard.writeText(""); }); teardown(cleanUpWorkspace); test("it holds the past kills and takes them for yank", async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // kill 3 times with different texts await clearTextEditor(activeTextEditor, "Lorem ipsum"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "dolor sit amet,\nconsectetur adipiscing elit,"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "sed do eiusmod tempor\nincididunt ut labore et\ndolore magna aliqua."); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank + yankPop await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcdesed do eiusmod tempor\nincididunt ut labore et\ndolore magna aliqua.fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdedolor sit amet,\nconsectetur adipiscing elit,fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); // Repeat await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdesed do eiusmod tempor\nincididunt ut labore et\ndolore magna aliqua.fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdedolor sit amet,\nconsectetur adipiscing elit,fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); // Repeat again await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdesed do eiusmod tempor\nincididunt ut labore et\ndolore magna aliqua.fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdedolor sit amet,\nconsectetur adipiscing elit,fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); }); test("works with clipboard", async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill first await clearTextEditor(activeTextEditor, "Lorem ipsum"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Then, copy to clipboard await vscode.env.clipboard.writeText("12345"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank firstly takes the text on clipboard await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcde12345fghij ABCDEFGHIJ` ); // Then, yankPop takes from killRing await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); // Repeat await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcde12345fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); // Repeat again await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcde12345fghij ABCDEFGHIJ` ); await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeLorem ipsumfghij ABCDEFGHIJ` ); }); // Test yankPop is not executed after cursorMove or some other commands const otherInterruptingCommands = ["editor.action.selectAll"]; const interruptingCommands: string[] = [...otherInterruptingCommands]; interruptingCommands.forEach((interruptingCommand) => { test(`yankPop does not work if ${interruptingCommand} is executed after previous yank`, async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill texts await clearTextEditor(activeTextEditor, "FOO"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "BAR"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank first await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcdeBARfghij ABCDEFGHIJ` ); // Interruption command invoked await vscode.commands.executeCommand(interruptingCommand); // yankPop does not work await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeBARfghij ABCDEFGHIJ` ); }); test(`yankPop does not work if ${interruptingCommand} is executed after previous yankPop`, async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill texts await clearTextEditor(activeTextEditor, "FOO"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "BAR"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank first await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcdeBARfghij ABCDEFGHIJ` ); // Then, yankPop await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeFOOfghij ABCDEFGHIJ` ); // Interruption command invoked await vscode.commands.executeCommand(interruptingCommand); // yankPop does not work await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeFOOfghij ABCDEFGHIJ` ); }); }); suite("yankPop is not executed after editing or cursorMove commands", () => { let emulator: EmacsEmulator; const edits: Array<[string, () => Thenable<unknown>]> = [ ["edit", () => activeTextEditor.edit((editBuilder) => editBuilder.insert(new Position(0, 0), "hoge"))], [ "delete", () => activeTextEditor.edit((editBuilder) => editBuilder.delete(new Range(new Position(0, 0), new Position(0, 1))) ), ], [ "replace", () => activeTextEditor.edit((editBuilder) => editBuilder.replace(new Range(new Position(0, 0), new Position(0, 1)), "hoge") ), ], ]; const moves = moveCommandIds.map((commandName): [string, () => Thenable<unknown> | void] => [ commandName, () => emulator.runCommand(commandName), ]); setup(() => { const killRing = new KillRing(3); emulator = new EmacsEmulator(activeTextEditor, killRing); }); [...edits, ...moves].forEach(([label, interruptOp]) => { test(`yankPop does not work if ${label} is executed after previous yank`, async () => { // Kill texts await clearTextEditor(activeTextEditor, "FOO"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "BAR"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank first await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcdeBARfghij ABCDEFGHIJ` ); // Interruption command invoked await interruptOp(); // yankPop does not work await emulator.runCommand("yankPop"); assert.ok(activeTextEditor.document.getText().includes("BAR")); assert.ok(!activeTextEditor.document.getText().includes("FOO")); }); test(`yankPop does not work if ${label} is executed after previous yankPop`, async () => { // Kill texts await clearTextEditor(activeTextEditor, "FOO"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "BAR"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with non-empty text const initialText = `0123456789 abcdefghij ABCDEFGHIJ`; await clearTextEditor(activeTextEditor, initialText); // Set cursor at the middle of the text activeTextEditor.selection = new Selection(new Position(1, 5), new Position(1, 5)); // yank first await emulator.runCommand("yank"); assertTextEqual( activeTextEditor, `0123456789 abcdeBARfghij ABCDEFGHIJ` ); // Then, yankPop await emulator.runCommand("yankPop"); assertTextEqual( activeTextEditor, `0123456789 abcdeFOOfghij ABCDEFGHIJ` ); // Interruption command invoked await interruptOp(); // yankPop does not work // yankPop does not work await emulator.runCommand("yankPop"); assert.ok(activeTextEditor.document.getText().includes("FOO")); assert.ok(!activeTextEditor.document.getText().includes("BAR")); }); }); }); }); suite("yank works with empty string", () => { setup(async () => { const initialText = "aaa"; activeTextEditor = await setupWorkspace(initialText); await vscode.env.clipboard.writeText(""); }); teardown(cleanUpWorkspace); test("yank works with empty string", async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill text await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Kill empty text await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Now the text is empty assertTextEqual(activeTextEditor, ""); // Yank pastes "" (an emtpy string) await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, ""); // YankPop pastes "aaa" await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "aaa"); // YankPop pastes "" (an emtpy string) await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, ""); // YankPop pastes "aaa" await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "aaa"); }); }); suite("yank works with multi cursor and empty string", () => { setup(async () => { const initialText = "aaa\nbbb\nccc"; activeTextEditor = await setupWorkspace(initialText); await vscode.env.clipboard.writeText(""); }); teardown(cleanUpWorkspace); test("yank works with multi cursor and empty string", async () => { const killRing = new KillRing(3); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill text activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 3)), new Selection(new Position(1, 0), new Position(1, 3)), new Selection(new Position(2, 0), new Position(2, 3)), ]; await emulator.runCommand("killRegion"); // Kill empty text activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 0)), new Selection(new Position(1, 0), new Position(1, 0)), new Selection(new Position(2, 0), new Position(2, 0)), ]; await emulator.runCommand("killRegion"); // Now the text is empty assertTextEqual(activeTextEditor, "\n\n"); // Yank pastes "" (an emtpy string) await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "\n\n"); // YankPop pastes "aaa" await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "aaa\nbbb\nccc"); // YankPop pastes "" (an emtpy string) await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "\n\n"); // YankPop pastes "aaa" await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "aaa\nbbb\nccc"); }); }); }); suite("yank pop with auto-indent", () => { let activeTextEditor: vscode.TextEditor; teardown(cleanUpWorkspace); test("Yank in a language that has auto-indent support", async function () { activeTextEditor = await setupWorkspace("", { language: "typescript" }); activeTextEditor.options.tabSize = 4; const killRing = new KillRing(60); const emulator = new EmacsEmulator(activeTextEditor, killRing); // Kill texts await clearTextEditor(activeTextEditor, "foo"); // No indent await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); await clearTextEditor(activeTextEditor, "bar"); // No indent await vscode.commands.executeCommand("editor.action.selectAll"); await emulator.runCommand("killRegion"); // Initialize with parentheses, that triggers auto-indent to inner text const initialText = "{\n\n}"; await clearTextEditor(activeTextEditor, initialText); setEmptyCursors(activeTextEditor, [1, 0]); // Yank pastes "bar" with auto-indentation await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "{\n bar\n}"); // YankPop pastes "foo" with auto-indentation await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "{\n foo\n}"); // yankPop again await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "{\n bar\n}"); }); }); suite("Kill and yank with multi cursor, killing at 2 cursors in different lines", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; setup(async () => { activeTextEditor = await setupWorkspace(); const killRing = new KillRing(60); emulator = new EmacsEmulator(activeTextEditor, killRing); await clearTextEditor(activeTextEditor, "hoge\nfuga\npiyo"); // Kill texts from multiple selections activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 4)), new Selection(new Position(1, 0), new Position(1, 4)), ]; await emulator.runCommand("killRegion"); assertCursorsEqual(activeTextEditor, [0, 0], [1, 0]); await clearTextEditor(activeTextEditor, "foo\nbar\nbaz"); // Again, kill texts from multiple selections, with different contents. activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 3)), new Selection(new Position(1, 0), new Position(1, 3)), ]; await emulator.runCommand("killRegion"); assertCursorsEqual(activeTextEditor, [0, 0], [1, 0]); }); teardown(cleanUpWorkspace); test("Yank with the same number of cursors", async () => { // Yank pastes the killed texts to each cursor await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo\nbar\nbaz"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foofoo\nbarbar\nbaz"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foohoge\nbarfuga\nbaz"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foofoo\nbarbar\nbaz"); }); test("Yank at 1 cursor", async () => { await clearTextEditor(activeTextEditor, ""); setEmptyCursors(activeTextEditor, [0, 0]); // Yank pastes the killed texts with concatenation await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo\nbar"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo\nbarfoo\nbar"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foo\nbarhoge\nfuga"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foo\nbarfoo\nbar"); }); test("Yank at 3 cursors", async () => { await clearTextEditor(activeTextEditor, "\n\n"); setEmptyCursors(activeTextEditor, [0, 0], [1, 0], [2, 0]); // Yank pastes the killed texts with concatenation await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo\nbar\nfoo\nbar\nfoo\nbar"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo\nbarfoo\nbar\nfoo\nbarfoo\nbar\nfoo\nbarfoo\nbar"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foo\nbarhoge\nfuga\nfoo\nbarhoge\nfuga\nfoo\nbarhoge\nfuga"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foo\nbarfoo\nbar\nfoo\nbarfoo\nbar\nfoo\nbarfoo\nbar"); }); }); suite("Kill and yank with multi cursor, killing at 2 cursors in one line", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; setup(async () => { activeTextEditor = await setupWorkspace(); const killRing = new KillRing(60); emulator = new EmacsEmulator(activeTextEditor, killRing); await clearTextEditor(activeTextEditor, "hoge fuga piyo"); // Kill texts from multiple selections activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 4)), new Selection(new Position(0, 5), new Position(0, 9)), ]; await emulator.runCommand("killRegion"); assertCursorsEqual(activeTextEditor, [0, 0], [0, 1]); await clearTextEditor(activeTextEditor, "foo bar baz"); // Again, kill texts from multiple selections, with different contents. activeTextEditor.selections = [ new Selection(new Position(0, 0), new Position(0, 3)), new Selection(new Position(0, 4), new Position(0, 7)), ]; await emulator.runCommand("killRegion"); assertCursorsEqual(activeTextEditor, [0, 0], [0, 1]); }); teardown(cleanUpWorkspace); test("Yank with the same number of cursors", async () => { // Yank pastes the killed texts to each cursor await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foo bar baz"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foofoo barbar baz"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foohoge barfuga baz"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foofoo barbar baz"); }); test("Yank at 1 cursor", async () => { await clearTextEditor(activeTextEditor, ""); setEmptyCursors(activeTextEditor, [0, 0]); // Yank pastes the killed texts with concatenation await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foobar"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foobarfoobar"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foobarhogefuga"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foobarfoobar"); }); test("Yank at 3 cursors", async () => { await clearTextEditor(activeTextEditor, "\n\n"); setEmptyCursors(activeTextEditor, [0, 0], [1, 0], [2, 0]); // Yank pastes the killed texts with concatenation await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foobar\nfoobar\nfoobar"); await emulator.runCommand("yank"); assertTextEqual(activeTextEditor, "foobarfoobar\nfoobarfoobar\nfoobarfoobar"); // Yank pop works in the same way await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foobarhogefuga\nfoobarhogefuga\nfoobarhogefuga"); await emulator.runCommand("yankPop"); assertTextEqual(activeTextEditor, "foobarfoobar\nfoobarfoobar\nfoobarfoobar"); }); }); suite("With not only single text editor", () => { setup(async () => { await vscode.env.clipboard.writeText(""); }); test("shares killRing amoung multiple editors", async function () { const killRing = new KillRing(3); const activeTextEditor0 = await setupWorkspace(); const emulator0 = new EmacsEmulator(activeTextEditor0, killRing); // Kill texts from one text editor await clearTextEditor(activeTextEditor0, "FOO"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator0.runCommand("killRegion"); await clearTextEditor(activeTextEditor0, "BAR"); await vscode.commands.executeCommand("editor.action.selectAll"); await emulator0.runCommand("killRegion"); const activeTextEditor1 = await setupWorkspace(""); const emulator1 = new EmacsEmulator(activeTextEditor1, killRing); // The killed texts are yanked on another text editor await emulator1.runCommand("yank"); assertTextEqual(activeTextEditor1, "BAR"); await emulator1.runCommand("yankPop"); assertTextEqual(activeTextEditor1, "FOO"); // Repeat await emulator1.runCommand("yankPop"); assertTextEqual(activeTextEditor1, "BAR"); await emulator1.runCommand("yankPop"); assertTextEqual(activeTextEditor1, "FOO"); }); });
the_stack
import { Config, ConfigReader } from '@backstage/config'; import { JsonObject } from '@backstage/types'; import { Knex } from 'knex'; import { merge, omit } from 'lodash'; import { mergeDatabaseConfig } from './config'; import { createDatabaseClient, createNameOverride, createSchemaOverride, ensureDatabaseExists, ensureSchemaExists, normalizeConnection, } from './connection'; import { PluginDatabaseManager } from './types'; import path from 'path'; /** * Provides a config lookup path for a plugin's config block. */ function pluginPath(pluginId: string): string { return `plugin.${pluginId}`; } /** * Creation options for {@link DatabaseManager}. * * @public */ export type DatabaseManagerOptions = { migrations?: PluginDatabaseManager['migrations']; }; /** * Manages database connections for Backstage backend plugins. * * The database manager allows the user to set connection and client settings on * a per pluginId basis by defining a database config block under * `plugin.<pluginId>` in addition to top level defaults. Optionally, a user may * set `prefix` which is used to prefix generated database names if config is * not provided. * * @public */ export class DatabaseManager { /** * Creates a {@link DatabaseManager} from `backend.database` config. * * @param config - The loaded application configuration. * @param options - An optional configuration object. */ static fromConfig( config: Config, options?: DatabaseManagerOptions, ): DatabaseManager { const databaseConfig = config.getConfig('backend.database'); return new DatabaseManager( databaseConfig, databaseConfig.getOptionalString('prefix'), options, ); } private constructor( private readonly config: Config, private readonly prefix: string = 'backstage_plugin_', private readonly options?: DatabaseManagerOptions, ) {} /** * Generates a PluginDatabaseManager for consumption by plugins. * * @param pluginId - The plugin that the database manager should be created for. Plugin names * should be unique as they are used to look up database config overrides under * `backend.database.plugin`. */ forPlugin(pluginId: string): PluginDatabaseManager { const _this = this; return { getClient(): Promise<Knex> { return _this.getDatabase(pluginId); }, migrations: { skip: false, ..._this.options?.migrations, }, }; } /** * Provides the canonical database name for a given plugin. * * This method provides the effective database name which is determined using global * and plugin specific database config. If no explicit database name is configured * and `pluginDivisionMode` is not `schema`, this method will provide a generated name * which is the pluginId prefixed with 'backstage_plugin_'. If `pluginDivisionMode` is * `schema`, it will fallback to using the default database for the knex instance. * * @param pluginId - Lookup the database name for given plugin * @returns String representing the plugin's database name */ private getDatabaseName(pluginId: string): string | undefined { const connection = this.getConnectionConfig(pluginId); if (this.getClientType(pluginId).client.includes('sqlite3')) { const sqliteFilename: string | undefined = ( connection as Knex.Sqlite3ConnectionConfig ).filename; if (sqliteFilename === ':memory:') { return sqliteFilename; } const sqliteDirectory = (connection as { directory?: string }).directory ?? '.'; return path.join(sqliteDirectory, sqliteFilename ?? `${pluginId}.sqlite`); } const databaseName = (connection as Knex.ConnectionConfig)?.database; // `pluginDivisionMode` as `schema` should use overridden databaseName if supplied or fallback to default knex database if (this.getPluginDivisionModeConfig() === 'schema') { return databaseName; } // all other supported databases should fallback to an auto-prefixed name return databaseName ?? `${this.prefix}${pluginId}`; } /** * Provides the client type which should be used for a given plugin. * * The client type is determined by plugin specific config if present. * Otherwise the base client is used as the fallback. * * @param pluginId - Plugin to get the client type for * @returns Object with client type returned as `client` and boolean * representing whether or not the client was overridden as * `overridden` */ private getClientType(pluginId: string): { client: string; overridden: boolean; } { const pluginClient = this.config.getOptionalString( `${pluginPath(pluginId)}.client`, ); const baseClient = this.config.getString('client'); const client = pluginClient ?? baseClient; return { client, overridden: client !== baseClient, }; } /** * Provides the knexConfig which should be used for a given plugin. * * @param pluginId - Plugin to get the knexConfig for * @returns The merged knexConfig value or undefined if it isn't specified */ private getAdditionalKnexConfig(pluginId: string): JsonObject | undefined { const pluginConfig = this.config .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`) ?.get<JsonObject>(); const baseConfig = this.config .getOptionalConfig('knexConfig') ?.get<JsonObject>(); return merge(baseConfig, pluginConfig); } private getEnsureExistsConfig(pluginId: string): boolean { const baseConfig = this.config.getOptionalBoolean('ensureExists') ?? true; return ( this.config.getOptionalBoolean(`${pluginPath(pluginId)}.ensureExists`) ?? baseConfig ); } private getPluginDivisionModeConfig(): string { return this.config.getOptionalString('pluginDivisionMode') ?? 'database'; } /** * Provides a Knex connection plugin config by combining base and plugin * config. * * This method provides a baseConfig for a plugin database connector. If the * client type has not been overridden, the global connection config will be * included with plugin specific config as the base. Values from the plugin * connection take precedence over the base. Base database name is omitted for * all supported databases excluding SQLite unless `pluginDivisionMode` is set * to `schema`. */ private getConnectionConfig( pluginId: string, ): Partial<Knex.StaticConnectionConfig> { const { client, overridden } = this.getClientType(pluginId); let baseConnection = normalizeConnection( this.config.get('connection'), this.config.getString('client'), ); if ( client.includes('sqlite3') && 'filename' in baseConnection && baseConnection.filename !== ':memory:' ) { throw new Error( '`connection.filename` is not supported for the base sqlite connection. Prefer `connection.directory` or provide a filename for the plugin connection instead.', ); } // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`. The // `database` property from the base connection is omitted unless `pluginDivisionMode` // is set to `schema`. SQLite3's `filename` property is an exception as this is used as a // directory elsewhere so we preserve `filename`. if (this.getPluginDivisionModeConfig() !== 'schema') { baseConnection = omit(baseConnection, 'database'); } // get and normalize optional plugin specific database connection const connection = normalizeConnection( this.config.getOptional(`${pluginPath(pluginId)}.connection`), client, ); return { // include base connection if client type has not been overridden ...(overridden ? {} : baseConnection), ...connection, }; } /** * Provides a Knex database config for a given plugin. * * This method provides a Knex configuration object along with the plugin's * client type. * * @param pluginId - The plugin that the database config should correspond with */ private getConfigForPlugin(pluginId: string): Knex.Config { const { client } = this.getClientType(pluginId); return { ...this.getAdditionalKnexConfig(pluginId), client, connection: this.getConnectionConfig(pluginId), }; } /** * Provides a partial `Knex.Config` database schema override for a given * plugin. * * @param pluginId - Target plugin to get database schema override * @returns Partial `Knex.Config` with database schema override */ private getSchemaOverrides(pluginId: string): Knex.Config | undefined { return createSchemaOverride(this.getClientType(pluginId).client, pluginId); } /** * Provides a partial `Knex.Config`• database name override for a given plugin. * * @param pluginId - Target plugin to get database name override * @returns Partial `Knex.Config` with database name override */ private getDatabaseOverrides(pluginId: string): Knex.Config { const databaseName = this.getDatabaseName(pluginId); return databaseName ? createNameOverride(this.getClientType(pluginId).client, databaseName) : {}; } /** * Provides a scoped Knex client for a plugin as per application config. * * @param pluginId - Plugin to get a Knex client for * @returns Promise which resolves to a scoped Knex database client for a * plugin */ private async getDatabase(pluginId: string): Promise<Knex> { const pluginConfig = new ConfigReader( this.getConfigForPlugin(pluginId) as JsonObject, ); const databaseName = this.getDatabaseName(pluginId); if (databaseName && this.getEnsureExistsConfig(pluginId)) { try { await ensureDatabaseExists(pluginConfig, databaseName); } catch (error) { throw new Error( `Failed to connect to the database to make sure that '${databaseName}' exists, ${error}`, ); } } let schemaOverrides; if (this.getPluginDivisionModeConfig() === 'schema') { try { schemaOverrides = this.getSchemaOverrides(pluginId); await ensureSchemaExists(pluginConfig, pluginId); } catch (error) { throw new Error( `Failed to connect to the database to make sure that schema for plugin '${pluginId}' exists, ${error}`, ); } } const databaseClientOverrides = mergeDatabaseConfig( {}, this.getDatabaseOverrides(pluginId), schemaOverrides, ); return createDatabaseClient(pluginConfig, databaseClientOverrides); } }
the_stack
import _ = require('lodash'); import { expect } from 'chai'; import * as Docker from 'dockerode'; import { docker } from '../src/lib/docker-utils'; import * as sinon from 'sinon'; import * as config from '../src/config'; import * as firewall from '../src/lib/firewall'; import * as logger from '../src/logger'; import * as iptablesMock from './lib/mocked-iptables'; import * as targetStateCache from '../src/device-state/target-state-cache'; import constants = require('../src/lib/constants'); import { RuleAction, Rule } from '../src/lib/iptables'; import { log } from '../src/lib/supervisor-console'; describe('Host Firewall', function () { const dockerStubs: Dictionary<sinon.SinonStub> = {}; let loggerSpy: sinon.SinonSpy; let logSpy: sinon.SinonSpy; let apiEndpoint: string; let listenPort: number; before(async () => { // spy the logs... loggerSpy = sinon.spy(logger, 'logSystemMessage'); logSpy = sinon.spy(log, 'error'); // stub the docker calls... dockerStubs.listContainers = sinon .stub(docker, 'listContainers') .resolves([]); dockerStubs.listImages = sinon.stub(docker, 'listImages').resolves([]); dockerStubs.getImage = sinon.stub(docker, 'getImage').returns({ id: 'abcde', inspect: async () => { return {}; }, } as Docker.Image); await targetStateCache.initialized; await firewall.initialised; apiEndpoint = await config.get('apiEndpoint'); listenPort = await config.get('listenPort'); }); after(async () => { for (const stub of _.values(dockerStubs)) { stub.restore(); } loggerSpy.restore(); logSpy.restore(); }); describe('Basic On/Off operation', () => { it('should confirm the `changed` event is handled', async function () { await iptablesMock.whilstMocked(async ({ hasAppliedRules }) => { const changedSpy = sinon.spy(); config.on('change', changedSpy); // set the firewall to be in off mode... await config.set({ firewallMode: 'off' }); await hasAppliedRules; // check it fired the events correctly... expect(changedSpy.called).to.be.true; expect(changedSpy.calledWith({ firewallMode: 'off' })).to.be.true; }); }); it('should handle the HOST_FIREWALL_MODE configuration value: invalid', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be in off mode... await config.set({ firewallMode: 'invalid' }); await hasAppliedRules; // expect that we jump to the firewall chain... expectRule({ target: 'BALENA-FIREWALL', chain: 'INPUT', family: 4, }); // expect to return... expectRule({ chain: 'BALENA-FIREWALL', target: 'RETURN', family: 4, }); }, ); }); it('should respect the HOST_FIREWALL_MODE configuration value: off', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be in off mode... await config.set({ firewallMode: 'off' }); await hasAppliedRules; // expect that we jump to the firewall chain... expectRule({ action: RuleAction.Append, target: 'BALENA-FIREWALL', chain: 'INPUT', family: 4, }); // expect to return... const returnRuleIdx = expectRule({ table: 'filter', chain: 'BALENA-FIREWALL', target: 'RETURN', family: 4, }); // ... just before we reject everything const rejectRuleIdx = expectRule({ chain: 'BALENA-FIREWALL', target: 'REJECT', matches: iptablesMock.RuleProperty.NotSet, family: 4, }); expect(returnRuleIdx).to.be.lessThan(rejectRuleIdx); }, ); }); it('should respect the HOST_FIREWALL_MODE configuration value: on', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule, expectNoRule }) => { // set the firewall to be in auto mode... await config.set({ firewallMode: 'on' }); await hasAppliedRules; // expect that we jump to the firewall chain... expectRule({ action: RuleAction.Append, target: 'BALENA-FIREWALL', chain: 'INPUT', family: 4, }); // expect to not return for any reason... expectNoRule({ chain: 'BALENA-FIREWALL', target: 'RETURN', }); }, ); }); it('should respect the HOST_FIREWALL_MODE configuration value: auto (no services in host-network)', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { await targetStateCache.setTargetApps([ { appId: 2, commit: 'abcdef2', name: 'test-app2', source: apiEndpoint, releaseId: 1232, services: JSON.stringify([ { serviceName: 'test-service', image: 'test-image', imageId: 5, environment: { TEST_VAR: 'test-string', }, tty: true, appId: 2, releaseId: 1232, serviceId: 567, commit: 'abcdef2', }, ]), networks: '[]', volumes: '[]', }, ]); // set the firewall to be in auto mode... await config.set({ firewallMode: 'auto' }); await hasAppliedRules; // expect that we jump to the firewall chain... expectRule({ action: RuleAction.Append, target: 'BALENA-FIREWALL', chain: 'INPUT', family: 4, }); // expect to return... expectRule({ chain: 'BALENA-FIREWALL', target: 'RETURN', family: 4, }); }, ); }); it('should respect the HOST_FIREWALL_MODE configuration value: auto (service in host-network)', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule, expectNoRule }) => { await targetStateCache.setTargetApps([ { appId: 2, commit: 'abcdef2', name: 'test-app2', source: apiEndpoint, releaseId: 1232, services: JSON.stringify([ { serviceName: 'test-service', networkMode: 'host', image: 'test-image', imageId: 5, environment: { TEST_VAR: 'test-string', }, tty: true, appId: 2, releaseId: 1232, serviceId: 567, commit: 'abcdef2', }, ]), networks: '[]', volumes: '[]', }, ]); // set the firewall to be in auto mode... await config.set({ firewallMode: 'auto' }); await hasAppliedRules; // expect that we jump to the firewall chain... expectRule({ action: RuleAction.Append, target: 'BALENA-FIREWALL', chain: 'INPUT', family: 4, }); // expect to return... expectNoRule({ chain: 'BALENA-FIREWALL', target: 'RETURN', family: 4, }); }, ); }); it('should catch errors when rule changes fail', async () => { await iptablesMock.whilstMocked(async ({ hasAppliedRules }) => { // clear the spies... loggerSpy.resetHistory(); logSpy.resetHistory(); // set the firewall to be in off mode... await config.set({ firewallMode: 'off' }); await hasAppliedRules; // should have caught the error and logged it expect(logSpy.calledWith('Error applying firewall mode')).to.be.true; expect(loggerSpy.called).to.be.true; }, iptablesMock.realRuleAdaptor); }); }); describe('Service rules', () => { const rejectAllRule = { target: 'REJECT', chain: 'BALENA-FIREWALL', matches: iptablesMock.RuleProperty.NotSet, }; const checkForRules = ( rules: Array<iptablesMock.Testable<Rule>> | iptablesMock.Testable<Rule>, expectRule: (rule: iptablesMock.Testable<Rule>) => number, ) => { rules = _.castArray(rules); rules.forEach((rule) => { const ruleIdx = expectRule(rule); // make sure we reject AFTER the rule... const rejectAllRuleIdx = expectRule(rejectAllRule); expect(ruleIdx).is.lessThan(rejectAllRuleIdx); }); }; it('should have a rule to allow DNS traffic from the balena0 interface', async () => { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be on... await config.set({ firewallMode: 'on' }); await hasAppliedRules; [4, 6].forEach((family: 4 | 6) => { // expect that we have a rule to allow DNS access... checkForRules( { family, target: 'ACCEPT', chain: 'BALENA-FIREWALL', proto: 'udp', matches: ['--dport 53', '-i balena0'], }, expectRule, ); }); }, ); }); it('should have a rule to allow SSH traffic any interface', async () => { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be on... await config.set({ firewallMode: 'on' }); await hasAppliedRules; [4, 6].forEach((family: 4 | 6) => { // expect that we have a rule to allow SSH access... checkForRules( { family, target: 'ACCEPT', chain: 'BALENA-FIREWALL', proto: 'tcp', matches: ['--dport 22222'], }, expectRule, ); }); }, ); }); it('should have a rule to allow Multicast traffic any interface', async () => { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be on... await config.set({ firewallMode: 'on' }); await hasAppliedRules; [4, 6].forEach((family: 4 | 6) => { // expect that we have a rule to allow multicast... checkForRules( { family, target: 'ACCEPT', chain: 'BALENA-FIREWALL', matches: ['-m addrtype', '--dst-type MULTICAST'], }, expectRule, ); }); }, ); }); it('should have a rule to allow balenaEngine traffic any interface', async () => { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the firewall to be on... await config.set({ firewallMode: 'on' }); await hasAppliedRules; [4, 6].forEach((family: 4 | 6) => { // expect that we have a rule to allow balenaEngine access... checkForRules( { family, target: 'ACCEPT', chain: 'BALENA-FIREWALL', proto: 'tcp', matches: ['--dport 2375'], }, expectRule, ); }); }, ); }); }); describe('Supervisor API access', () => { it('should allow access in localmode', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule }) => { // set the device to be in local mode... await config.set({ localMode: true }); await hasAppliedRules; [4, 6].forEach((family: 4 | 6) => { // make sure we have a rule to allow traffic on ANY interface const allowRuleIdx = expectRule({ proto: 'tcp', matches: [`--dport ${listenPort}`], target: 'ACCEPT', chain: 'BALENA-FIREWALL', table: 'filter', family, }); // make sure we have a rule to block traffic on ANY interface also const rejectRuleIdx = expectRule({ proto: 'tcp', matches: [`--dport ${listenPort}`], target: 'REJECT', chain: 'BALENA-FIREWALL', table: 'filter', family, }); // we should always reject AFTER we allow expect(allowRuleIdx).to.be.lessThan(rejectRuleIdx); }); }, ); }); it('should allow limited access in non-localmode', async function () { await iptablesMock.whilstMocked( async ({ hasAppliedRules, expectRule, expectNoRule }) => { // set the device to be in local mode... await config.set({ localMode: false }); await hasAppliedRules; // ensure we have no unrestricted rule... expectNoRule({ chain: 'BALENA-FIREWALL', proto: 'tcp', matches: [`--dport ${listenPort}`], target: 'ACCEPT', family: 4, }); // ensure we do have a restricted rule for each interface... let allowRuleIdx = -1; constants.allowedInterfaces.forEach((intf) => { [4, 6].forEach((family: 4 | 6) => { allowRuleIdx = expectRule({ chain: 'BALENA-FIREWALL', proto: 'tcp', matches: [`--dport ${listenPort}`, `-i ${intf}`], target: 'ACCEPT', family, }); }); }); // make sure we have a rule to block traffic on ANY interface also const rejectRuleIdx = expectRule({ proto: 'tcp', matches: [`--dport ${listenPort}`], target: 'REJECT', chain: 'BALENA-FIREWALL', table: 'filter', }); // we should always reject AFTER we allow expect(allowRuleIdx).to.be.lessThan(rejectRuleIdx); }, ); }); }); });
the_stack
import { readFileSync } from 'fs'; import { buildSchema, printSchema, GraphQLObjectType, assertInputObjectType } from 'graphql'; import { GraphbackCoreMetadata, printSchemaWithDirectives, GraphbackPluginEngine, metadataMap, GraphbackCRUDGeneratorConfig } from '@graphback/core'; import { SchemaCRUDPlugin } from '../src/SchemaCRUDPlugin'; const schemaText = readFileSync(`${__dirname}/mock.graphql`, 'utf8') test('Test snapshot config gql', async () => { const defautConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, buildSchema(schemaText)) const schema = schemaGenerator.transformSchema(metadata) expect(printSchemaWithDirectives(schema)).toMatchSnapshot(); }); test('Test snapshot config ts', async () => { const defautConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, buildSchema(schemaText)) const schema = schemaGenerator.transformSchema(metadata) expect(printSchema(schema)).toMatchSnapshot(); }); test('Test snapshot config js', async () => { const defautConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, buildSchema(schemaText)) const schema = schemaGenerator.transformSchema(metadata) expect(printSchema(schema)).toMatchSnapshot(); }); test('Create subscription fields when mutations are disabled', () => { const crudMethods: GraphbackCRUDGeneratorConfig = { create: false, update: false, delete: false }; const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods }, buildSchema(` """@model""" type Note { id: ID! title: String } `)) const schema = schemaGenerator.transformSchema(metadata); expect(Object.keys(schema.getSubscriptionType().getFields())).toEqual(['newNote', 'updatedNote', 'deletedNote']); expect(schema.getMutationType()).toBeUndefined(); expect(printSchema(schema)).toMatchSnapshot(); }) test('Test one side relationship schema query type generation', async () => { const defautConfig = { "create": false, "update": false, "findOne": true, "find": true, "delete": false, "subCreate": false, "subUpdate": false, "subDelete": false } const modelText = `""" @model """ type Note { id: ID! title: String! description: String! """ @oneToMany(field: 'note', key: 'test_id') """ tests: [Test]! } """ @model """ type Test { id: ID! name: String } `; const oneSidedSchema = buildSchema(modelText); const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, oneSidedSchema) const transformedSchema = schemaGenerator.transformSchema(metadata) expect(printSchema(transformedSchema)).toMatchSnapshot() }); test('Model has missing relationship annotations', async () => { const defautConfig = { "create": false, "update": false, "findOne": true, "find": true, "delete": false, "subCreate": false, "subUpdate": false, "subDelete": false }; let modelText = ` """ @model """ type Note { id: ID! tests: [Test]! } """ @model """ type Test { id: ID! name: String } `; let schema = buildSchema(modelText); let schemaGenerator = new SchemaCRUDPlugin(); let metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, schema); try { schemaGenerator.transformSchema(metadata); expect(true).toBeFalsy(); // should not reach here } catch (error) { expect(error.message).toEqual(`Missing relationship definition on: "Note.tests". Visit https://graphback.dev/docs/model/datamodel#relationships to see how you can define relationship in your business model.`); } modelText = ` """ @model """ type Note { id: ID! test: Test } """ @model """ type Test { id: ID! name: String } `; schema = buildSchema(modelText); schemaGenerator = new SchemaCRUDPlugin(); metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, schema); try { schemaGenerator.transformSchema(metadata); expect(true).toBeFalsy(); // should not reach here } catch (error) { expect(error.message).toEqual(`Missing relationship definition on: "Note.test". Visit https://graphback.dev/docs/model/datamodel#relationships to see how you can define relationship in your business model.`); } }); test('Non-model type has model-type field', () => { const defautConfig = { "create": true, "update": true, "findOne": true, "find": true, "delete": true, "subCreate": true, "subUpdate": true, "subDelete": true } const modelText = ` type JWTAuthResult { user: User! csrfToken: String! authJWT: String! } """@model""" type User { id: ID! name: String } type Query { jwt: JWTAuthResult }` const schemaGenerator = new SchemaCRUDPlugin() const metadata = new GraphbackCoreMetadata({ crudMethods: defautConfig }, buildSchema(modelText)) const schema = schemaGenerator.transformSchema(metadata) expect(schema.getType('JWTAuthResult')).toBeDefined() }) test('Creates CRUD resolvers for models', async () => { const pluginEngine = new GraphbackPluginEngine({ schema: schemaText, plugins: [ new SchemaCRUDPlugin() ] }) const metadata = pluginEngine.createResources() expect(metadata.getResolvers()).toMatchSnapshot(); }); test('field directives on relationship fields are mapped to schema', () => { const schemaGenerator = new SchemaCRUDPlugin(); const modelAST = `directive @test on FIELD_DEFINITION """ @model """ type Note { id: ID! title: String! description: String """ @oneToMany(field: 'note') """ comments: [Comment]! @test """@oneToOne""" comment: Comment @test } """ @model """ type Comment { id: ID! text: String description: String note: Note! @test }` const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); const schema = schemaGenerator.transformSchema(metadata); const noteType = schema.getType('Note') as GraphQLObjectType const { comments, comment } = noteType.getFields() // Note.comments field expect(comments.astNode?.directives).toHaveLength(1) expect(comments.astNode?.directives[0].name.value).toBe('test') // Note.comment field expect(comment.astNode?.directives).toHaveLength(1) expect(comment.astNode?.directives[0].name.value).toBe('test') const commentType = schema.getType('Comment') as GraphQLObjectType const { note } = commentType.getFields() // Note.comments field expect(note.astNode?.directives).toHaveLength(1) expect(note.astNode?.directives[0].name.value).toBe('test') expect(printSchemaWithDirectives(schema)).toMatchSnapshot(); }) test('schema does not generate filter input for unknown custom scalar', () => { const modelAST = ` scalar MyCustomScalar """ @model """ type TypeWithCustomScalar { id: ID! customField: MyCustomScalar }` const schemaGenerator = new SchemaCRUDPlugin(); const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); const schema = schemaGenerator.transformSchema(metadata); expect(schema.getType('MyCustomScalarInput')).toBeUndefined() }) test('schema does not override custom createdAt and updatedAt fields when model has @versioned annotation', () => { const fields = Object.values(metadataMap.fieldNames); for (const field of fields) { const modelAST = ` """ @model @versioned """ type Entity { id: ID! ${field}: Int }`; const schemaGenerator = new SchemaCRUDPlugin(); const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); try { schemaGenerator.transformSchema(metadata); expect(true).toBeFalsy(); // should not reach here } catch (error) { expect(error.message).toEqual(`Type "Entity" annotated with @versioned, cannot contain custom "${field}" field since it is generated automatically. Either remove the @versioned annotation, change the type of the field to "GraphbackTimestamp" or remove the field.`) } } }) test('schema does throw an error when model annotated with @versioned contain custom createdAt or updatedAt fields having GraphbackTimestamp type', () => { const modelAST = ` scalar GraphbackTimestamp """ @model @versioned """ type Entity1 { id: ID! createdAt: GraphbackTimestamp updatedAt: GraphbackTimestamp } """ @model @versioned """ type Entity2 { id: ID! createdAt: GraphbackTimestamp } """ @model @versioned """ type Entity3 { id: ID! updatedAt: GraphbackTimestamp } `; const schemaGenerator = new SchemaCRUDPlugin(); const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); const schema = schemaGenerator.transformSchema(metadata); expect(schema).toBeDefined() }) test('Transient field is excluded from input types', () => { const modelAST = ` """ @model """ type User { id: ID! name: String! """@transient""" generatedFullName: String } `; const schemaGenerator = new SchemaCRUDPlugin(); const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); const schema = schemaGenerator.transformSchema(metadata); const createUserInput = assertInputObjectType(schema.getType('CreateUserInput')) expect(Object.keys(createUserInput.getFields()).includes('generatedFullName')).toEqual(false); const mutateUserInput = assertInputObjectType(schema.getType('MutateUserInput')) expect(Object.keys(mutateUserInput.getFields())).toEqual(['id', 'name']) const userFilterInput = assertInputObjectType(schema.getType('UserFilter')) expect(Object.keys(userFilterInput.getFields()).includes('generatedFullName')).toEqual(false); const userSubscriptionInput = assertInputObjectType(schema.getType('UserFilter')) expect(Object.keys(userSubscriptionInput.getFields()).includes('generatedFullName')).toEqual(false); }) test('Auto generated primary key fields are not included in the Create<T>Mutation', () => { const modelAST = ` """ @model """ type User { id: ID! name: String! } """ @model """ type UserTwo { _id: GraphbackObjectID! name: String! } scalar GraphbackObjectID """ @model """ type UserThree { """@id""" id: String! name: String! } """ @model """ type UserFour { """ @id """ key: String! name: String _id: GraphbackObjectID id: ID }`; const schemaGenerator = new SchemaCRUDPlugin(); const metadata = new GraphbackCoreMetadata({ crudMethods: {} }, buildSchema(modelAST)); const schema = schemaGenerator.transformSchema(metadata); const createUserInput = assertInputObjectType(schema.getType('CreateUserInput')) expect(Object.keys(createUserInput.getFields()).includes('id')).toEqual(false); const createUserTwoInput = assertInputObjectType(schema.getType('CreateUserTwoInput')) expect(Object.keys(createUserTwoInput.getFields()).includes('_id')).toEqual(false); const createUserThreeInput = assertInputObjectType(schema.getType('CreateUserThreeInput')) expect(Object.keys(createUserThreeInput.getFields()).includes('id')).toEqual(true); const createUserFourInput = assertInputObjectType(schema.getType('CreateUserFourInput')) expect(Object.keys(createUserFourInput.getFields())).toEqual(['key', 'name', '_id', 'id']); })
the_stack
import { useState, useContext, useEffect } from 'react'; import { useWeb3React } from '@web3-react/core'; import { Web3Provider } from '@ethersproject/providers'; import { TokenInfo } from 'types'; import { Contract } from '@ethersproject/contracts'; import { MaxUint256 } from '@ethersproject/constants'; import { parseUnits, formatUnits, parseEther } from '@ethersproject/units'; import { BigNumber } from '@ethersproject/bignumber'; import { hexlify, isHexString } from '@ethersproject/bytes'; import { ZenethRelayer, estimateFee } from '@scopelift/zeneth-js'; import SwapBriber from '@scopelift/zeneth-contracts/artifacts/contracts/SwapBriber.sol/SwapBriber.json'; import { config } from 'config'; import { TokenSelect } from './TokenSelect'; import { BundleContext } from './BundleContext'; import { ModalContext } from './ModalContext'; import { NotificationContext } from './NotificationContext'; import { LightningBoltIcon } from '@heroicons/react/outline'; import { ExclamationCircleIcon } from '@heroicons/react/solid'; const abi = [ // Read-Only Functions 'function balanceOf(address owner) view returns (uint256)', 'function decimals() view returns (uint8)', 'function symbol() view returns (string)', // Authenticated Functions 'function transfer(address to, uint amount) returns (boolean)', 'function approve(address spender, uint256 value) returns (boolean)', ]; const inputBaseStyle = 'bg-gray-100 p-3 w-full block focus:outline-none focus:ring-indigo-600 focus:border-indigo-600 rounded-md'; // 'block w-full pr-10 border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 sm:text-sm rounded-md'; const ERC20Form = () => { const { account, library, chainId } = useWeb3React<Web3Provider>(); const { sendBundle, bundleStatus } = useContext(BundleContext); const { setModal, clearModal } = useContext(ModalContext); const { notify } = useContext(NotificationContext); const [userTokenBalance, setUserTokenBalance] = useState<BigNumber>(BigNumber.from(3000000)); const [bribeInTokens, setBribeInTokens] = useState<BigNumber>(); const [bribeInEth, setBribeInEth] = useState<BigNumber>(); const [showAddressValidationError, setShowAddressValidationError] = useState<boolean>(false); const [showAmountValidationError, setShowAmountValidationError] = useState<boolean>(false); const [formState, setFormState] = useState<{ token: TokenInfo | undefined; recipientAddress: string; amount: string; bribeMultiplier: number; }>({ token: undefined, recipientAddress: '', amount: '', bribeMultiplier: config.flashbotsPremiumMultipliers[0], }); useEffect(() => { if (!formState.token?.address) return; const getBalance = async () => { console.log(formState.token.address); console.log(abi); console.log(account); const contract = new Contract(formState.token.address, abi, library); const balance = await contract.balanceOf(account); setUserTokenBalance(balance); }; getBalance(); }, [formState.token?.address]); useEffect(() => { const { token, bribeMultiplier } = formState; if (!token) return; const getBribe = async () => { const { bribeInTokens, bribeInEth } = await estimateFee({ tokenAddress: token.address, tokenDecimals: token.decimals, bundleGasLimit: Object.values(token.gasEstimates).reduce((x: number, y: number) => x + y), flashbotsPremiumMultiplier: bribeMultiplier, }); const addRelayerPad = (bn: BigNumber) => bn.mul((config.relayerFeePadding + 1) * 100).div(100); setBribeInTokens(addRelayerPad(bribeInTokens)); setBribeInEth(bribeInEth); }; getBribe(); }, [formState.token?.address, formState.bribeMultiplier]); if (!library || !chainId) return null; if (!account) return <div>Please connect your wallet.</div>; const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => { const value = e.target.value; setFormState({ ...formState, [e.target.name]: value, }); }; const validateAddress = (e) => { if (!isHexString(formState.recipientAddress) || formState.recipientAddress.length !== 42) { setShowAddressValidationError(true); } else { setShowAddressValidationError(false); } }; const validateAmount = (e) => { if ( +formState.amount + +formatUnits(bribeInTokens, formState.token.decimals) > +formatUnits(userTokenBalance, formState.token.decimals) ) { setShowAmountValidationError(true); } else { setShowAmountValidationError(false); } }; const doSubmit = async (e: React.FormEvent) => { e.preventDefault(); const { token, recipientAddress, amount } = formState; const erc20 = new Contract(token.address, abi); const { swapBriber, weth, uniswapRouter } = config.networks[chainId].addresses; const swapBriberContract = new Contract(swapBriber, SwapBriber.abi); const zenethRelayer = await ZenethRelayer.create(library, process.env.AUTH_PRIVATE_KEY); const transferAmount = parseUnits(amount, token.decimals).toString(); console.log('bribe in tokens ', bribeInTokens.toString(), '\nbribe in eth, ', bribeInEth.toString()); const fragments = [ { data: erc20.interface.encodeFunctionData('transfer', [recipientAddress, transferAmount]), gasLimit: hexlify(token.gasEstimates.transfer), to: erc20.address, value: '0x0', }, { data: erc20.interface.encodeFunctionData('approve', [swapBriber, MaxUint256.toString()]), gasLimit: hexlify(token.gasEstimates.approve), to: erc20.address, value: '0x0', }, { data: swapBriberContract.interface.encodeFunctionData('swapAndBribe', [ erc20.address, // token to swap bribeInTokens, // fee in tokens chainId === 5 ? bribeInEth.div(6).mul(5) : bribeInEth, // bribe amount in ETH. less than or equal to DAI from above uniswapRouter, // uniswap router address [erc20.address, weth], // path of swap '2000000000', // really big deadline ]), gasLimit: hexlify(token.gasEstimates.swapAndBribe), to: swapBriber, value: '0x0', }, ]; console.log(fragments); console.log(account); setModal({ content: ( <div> Please use MetaMask to sign all {fragments.length} of the transactions that will be included in your bundle! </div> ), }); try { const signatures = await zenethRelayer.signBundle(account, fragments, library); console.log(signatures); sendBundle(signatures); } catch (e) { notify({ type: 'error', heading: 'Error signing bundle', body: e.message }); } clearModal(); }; const formGroup = 'my-2 flex flex-row items-center rounded'; const label = 'w-24 text-sm block self-center flex-shrink-0'; const submitDisabled = showAddressValidationError || showAmountValidationError || bundleStatus === 'pending'; return ( <div className="shadow-lg p-12 bg-gradient-to-br from-purple-100 via-red-100 to-transparent rounded-lg"> <form className="flex flex-col" spellCheck="false"> <h1 className="text-2xl mb-7 text-gray-700 font-bold">Gasless Token Transfer</h1> <div className={formGroup}> <label className={label}>Token</label> <TokenSelect selectedToken={formState.token} setToken={(token) => setFormState({ ...formState, token })} inputStyle={inputBaseStyle} /> </div> <div className={formGroup}> <label className={label}>Recipient</label> <div className="mt-1 relative rounded-md shadow-sm w-full"> <input name="recipientAddress" placeholder="0x123...def" value={formState.recipientAddress} className={`${inputBaseStyle} ${showAddressValidationError ? 'border-red-300 text-red-900' : ''}`} onChange={handleChange} onBlur={validateAddress} />{' '} {showAddressValidationError && ( <p className="mt-1 mb-2 text-sm text-red-600" id="email-error"> Please enter a valid Ethereum address. </p> )} </div> </div> <div className={formGroup}> <label className={label}>Amount</label> <div className="mt-1 relative rounded-md shadow-sm w-full"> <div className="flex"> <input placeholder="100" name="amount" value={formState.amount} className={`${inputBaseStyle} ${showAmountValidationError ? 'border-red-300 text-red-900' : ''}`} onChange={handleChange} onBlur={validateAmount} /> <div className="p-3 bg-gray-200">{formState.token?.symbol || ''}</div> </div> {showAmountValidationError && ( <p className="mt-1 mb-2 text-sm text-red-600" id="email-error"> Your balance of {formatUnits(userTokenBalance, formState.token.decimals)} {formState.token.symbol} is lower than total. </p> )} </div> </div> <div className={formGroup}> <label className={label}>Miner Incentive Multiplier</label> <span className="relative z-0 inline-flex shadow-sm rounded-md"> {config.flashbotsPremiumMultipliers.map((multiplier) => { const active = multiplier === formState.bribeMultiplier; return ( <button key={multiplier} type="button" onClick={() => setFormState({ ...formState, bribeMultiplier: multiplier })} className={`relative mr-2 rounded-md inline-flex items-center px-4 py-2 border border-gray-300 bg-white ${ active ? 'border-indigo-600 text-indigo-600' : 'border-gray-300' } font-medium text-gray-700 hover:bg-gray-50 focus:z-10 focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500`} > {`${multiplier}x`} </button> ); })} </span> </div> <div className={formGroup}> <label className={label}>Fee</label> <div className="border border-gray-200 bg-white bg-opacity-40 rounded-md py-2 px-4"> {bribeInTokens ? formatUnits(bribeInTokens, formState.token.decimals) : undefined}{' '} {formState.token?.symbol || ''} </div> </div> <div className={formGroup}> <label className={label + ' font-semibold'}>Total</label> <div className="border border-gray-200 font-semibold bg-white bg-opacity-40 rounded-md py-2 px-4"> {bribeInTokens ? +formatUnits(bribeInTokens, formState.token.decimals) + +formState.amount : undefined}{' '} {formState.token?.symbol || ''} </div> </div> <button type="button" className={`group mx-auto mt-5 inline-flex justify-center items-center px-6 py-3 border border-transparent shadow-sm text-base font-medium rounded-md text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${ submitDisabled ? 'bg-gray-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700 ' }`} disabled={submitDisabled} onClick={doSubmit} > {bundleStatus === 'pending' ? ( <> Processing <svg className="animate-spin ml-3 -mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" > <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle> <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" ></path> </svg> </> ) : ( <> Submit <LightningBoltIcon className={`ml-3 -mr-1 h-5 w-5 ${submitDisabled ? '' : 'group-hover:text-yellow-400'}`} aria-hidden="true" /> </> )} </button> </form> </div> ); }; export default ERC20Form;
the_stack
import { $$log } from "./debug"; let WINDOW_START = 0x3BE; let WINDOW_SIZE = 1024; let MIN_MATCH_LEN = 3; // var MAX_MATCH_LEN = 0x42; /* Mario Party N64 compression type 01 * * This type of compression was used in all three titles, though was the * exclusive type available in the original title. It is similar to LZSS, and * uses a 1KB circular buffer when referencing offsets. Like yaz0 compression, * there are code bytes for every 8 "chunks," though they are read from right * to left (0x01 to 0x80). * * When a '0' code bit is encountered, the next two bytes in the input are * read as offset and length pairs into the sliding window. * * Byte 1 Byte 2 * [oooooooo][oollllll] * * The two offset bits within Byte 2 are masked and shifted such that they * become the most significant bits. The length is found by adding the value * of MIN_MATCH_LEN, in this case, 3. * * Notably, the circular buffer begins filling not at zero, but at a position * roughly 90% of the way through, WINDOW_START. */ function decompress01(src: DataView, dst: DataView, decompressedSize: number) { // Current positions in src/dst buffers and sliding window. var srcPlace = 0; var dstPlace = 0; var winPlace = WINDOW_START; // Create the sliding window buffer. Must be initialized to zero as some // files look into the window right away for starting zeros. var winBuffer = new ArrayBuffer(WINDOW_SIZE); var windowArray = new DataView(winBuffer); // The code byte's bits are interpreted to mean straight copy (1) or read // from sliding window (0). var curCodeByte = 0; while (dstPlace < decompressedSize) { // Read a new "code" byte if the current one has expired. By placing an // 0xFF prior to the code bits, we can tell when we have consumed the // code byte by observing that the value will be become 0 only when we // have shifted away all of the code bits. if ((curCodeByte & 0x100) === 0) { curCodeByte = src.getUint8(srcPlace); curCodeByte |= 0xFF00; ++srcPlace; } if ((curCodeByte & 0x01) === 1) { // Copy the next byte from the source to the destination. dst.setUint8(dstPlace, src.getUint8(srcPlace)); windowArray.setUint8(winPlace, src.getUint8(srcPlace)); ++dstPlace; ++srcPlace; winPlace = (winPlace + 1) % WINDOW_SIZE; } else { // Interpret the next two bytes as an offset into the sliding window and // a length to read. var byte1 = src.getUint8(srcPlace); var byte2 = src.getUint8(srcPlace + 1); srcPlace += 2; var offset = ((byte2 & 0xC0) << 2) | byte1; var count = (byte2 & 0x3F) + MIN_MATCH_LEN; // Within the sliding window, locate the offset and copy count bytes. var val; for (var i = 0; i < count; ++i) { val = windowArray.getUint8(offset % WINDOW_SIZE); windowArray.setUint8(winPlace, val); winPlace = (winPlace + 1) % WINDOW_SIZE; dst.setUint8(dstPlace, val); ++dstPlace; ++offset; } } // Consider the code bit consumed. curCodeByte >>= 1; } return srcPlace; // Return the size of the compressed data. } /* This is a hack for MP3 Strings3 at the moment. Just "wraps" with dummy code * words, so file size will just grow. */ function compress01(src: DataView) { let codeWordCount = Math.ceil(src.byteLength / 8); let compressedSize = src.byteLength + codeWordCount; let compressedBuffer = new ArrayBuffer(compressedSize); let dst = new DataView(compressedBuffer); let dstPlace = 0; let srcPlace = 0; while (dstPlace < compressedSize) { if (!dstPlace || !(dstPlace % 9)) { dst.setUint8(dstPlace, 0xFF); } else { dst.setUint8(dstPlace, src.getUint8(srcPlace)); srcPlace++; } dstPlace++; } return compressedBuffer; } /* Mario Party N64 compression type 02 * * This compression algorithm was introduced in Mario Party 2, and is very * similar to yaz0. It uses word sized groups of code bits rather than a * single byte, and reads them in the same left to right order as yaz0. The * interpretation of the bytes when a code bit is 0 is also the same as yaz0. * * Byte 1 Byte 2 [Byte 3 when l = 0] * [lllldddd][dddddddd] [llllllll] * * The values of length and lookback distance are simply split apart and used. * The special case when length == 0 in yaz0 also applies, where a third byte * is read as the value of length and 0x12 is added. When the lookback * distance is farther than the start (out of bounds), 0s are inserted. * * This is also the implementation used for decompression types 03 and 04. * 03 and 04 are considered the same by the game engine. * 02 differs from 03/04 in that it is the only implementation that checks * whether lookback goes out of bounds, and handles it. As far as I know, * it is OK to use that handling for 03/04 as well, since the behavior would * otherwise be undefined. */ function decompress02(src: DataView, dst: DataView, decompressedSize: number) { // Current positions in src/dst buffers. var srcPlace = 0; var dstPlace = 0; // The code word's bits are interpreted to mean straight copy (1) // or lookback and read (0). var curCodeWord = 0; var codeWordBitsRemaining = 0; while (dstPlace < decompressedSize) { // Read a new code word if the current one has expired. if (codeWordBitsRemaining === 0) { curCodeWord = src.getUint32(srcPlace); codeWordBitsRemaining = 32; srcPlace += 4; } if ((curCodeWord & 0x80000000) !== 0) { // Copy the next byte from the source to the destination. dst.setUint8(dstPlace, src.getUint8(srcPlace)); ++dstPlace; ++srcPlace; } else { // Interpret the next two bytes as a distance to travel backwards and a // a length to read. var byte1 = src.getUint8(srcPlace); var byte2 = src.getUint8(srcPlace + 1); srcPlace += 2; var back = (((byte1 & 0x0F) << 8) | byte2) + 1; var count = ((byte1 & 0xF0) >> 4) + 2; if (count === 2) { // Special case where 0xF0 masked byte 1 is zero. count = src.getUint8(srcPlace) + 0x12; ++srcPlace; } // Step back and copy count bytes into the dst. var i, val; for (i = 0; i < count && dstPlace < decompressedSize; ++i) { if (back > dstPlace) val = 0; else val = dst.getUint8(dstPlace - back); dst.setUint8(dstPlace, val); ++dstPlace; } } // Consider the code bit consumed. curCodeWord <<= 1; --codeWordBitsRemaining; } return srcPlace; // Return the size of the compressed data. } /* This is a hack for MP2 HVQ at the moment. Just "wraps" with dummy code * words, so file size just grows. */ function compress02(src: DataView) { let codeWordCount = src.byteLength / 32; let compressedSize = src.byteLength + (codeWordCount * 4); let compressedBuffer = new ArrayBuffer(compressedSize); let dst = new DataView(compressedBuffer); let srcPlace = 0; for (let i = 0; i < compressedSize; i += 36, srcPlace += 32) { dst.setUint32(i, 0xFFFFFFFF); dst.setUint32(i + 4, src.getUint32(srcPlace)); dst.setUint32(i + 8, src.getUint32(srcPlace + 4)); dst.setUint32(i + 12, src.getUint32(srcPlace + 8)); dst.setUint32(i + 16, src.getUint32(srcPlace + 12)); dst.setUint32(i + 20, src.getUint32(srcPlace + 16)); dst.setUint32(i + 24, src.getUint32(srcPlace + 20)); dst.setUint32(i + 28, src.getUint32(srcPlace + 24)); dst.setUint32(i + 32, src.getUint32(srcPlace + 28)); } return compressedBuffer; } /* Mario Party N64 compression type 05 * * This is mostly a run-length encoding. The algorithm can be pretty simply * described: * 1. Read a byte * 2. If the byte has the sign bit (byte & 0x80), then get rid of the sign * bit and use that to count and copy in that many bytes. * 3. If there is no sign bit, use the byte to count and repeat the next byte * for that many times. * 4. Repeat until decompressed size reached. * * Typically this is used when there are a lot of zeroes or repeated single * values, like in some images. */ function decompress05(src: DataView, dst: DataView, decompressedSize: number) { // Current positions in src/dst buffers. let srcPlace = 0; let dstPlace = 0; while (dstPlace < decompressedSize) { let curCodeByte = src.getUint8(srcPlace); srcPlace++; let count = curCodeByte & 0x7F; if (curCodeByte & 0x80) { // Having the sign bit means we read the next n bytes from the input. for (let i = 0; i < count; i++) { let nextByte = src.getUint8(srcPlace); srcPlace++; dst.setUint8(dstPlace, nextByte); dstPlace++; } } else { // No sign bit means we repeat the next byte n times. let repeatedByte = src.getUint8(srcPlace); srcPlace++; for (let i = 0; i < count; i++) { dst.setUint8(dstPlace, repeatedByte); dstPlace++; } } } return srcPlace; // Return the size of the compressed data. } /** * Run length encoding compression. * Implementation provided by @gamemasterplc */ function compress05(src: DataView) { const output = new ArrayBuffer(src.byteLength * 3); // Rough upper bound. const outView = new DataView(output); let output_pos: number = 0; let input_pos = 0; let copy_len = 0; let curr_byte: number; let next_byte: number; while (input_pos < src.byteLength) { curr_byte = src.getUint8(input_pos); next_byte = src.getUint8(input_pos + 1); if (curr_byte === next_byte) { copy_len = 0; for (let i = 0; i < 127; i++) { curr_byte = src.getUint8(input_pos + i); next_byte = src.getUint8(input_pos + i + 1); if (curr_byte !== next_byte || (input_pos + i) >= src.byteLength) { copy_len++; break; } copy_len++; } outView.setUint8(output_pos, copy_len); outView.setUint8(output_pos + 1, src.getUint8(input_pos)); output_pos += 2; input_pos += copy_len; } else { copy_len = 0; for (let i = 0; i < 127; i++) { curr_byte = src.getUint8(input_pos + i); next_byte = src.getUint8(input_pos + i + 1); if (curr_byte === next_byte|| (input_pos + i) >= src.byteLength) { break; } copy_len++; } outView.setUint8(output_pos, 0x80|copy_len); output_pos += 1; for (let i = 0; i < copy_len; i++) { outView.setUint8(output_pos, src.getUint8(input_pos + i)); output_pos += 1; input_pos += 1; } } } return output.slice(0, output_pos); } // Returns a new buffer with the decompressed data. // The compressed size is attached as a property to the buffer object. export function decompress(type: number, srcDataView: DataView, decompressedSize: number): ArrayBuffer { let dstBuffer = new ArrayBuffer(decompressedSize); let dstView = new DataView(dstBuffer); let compressedSize; switch (type) { case 1: compressedSize = decompress01(srcDataView, dstView, decompressedSize); break; case 2: case 3: case 4: compressedSize = decompress02(srcDataView, dstView, decompressedSize); break; case 5: compressedSize = decompress05(srcDataView, dstView, decompressedSize); break; case 0: // Just directly copy uncompressed data. compressedSize = decompressedSize; for (let i = 0; i < decompressedSize; i++) dstView.setUint8(i, srcDataView.getUint8(i)); break; default: $$log(`decompression ${type} not implemented.`); break; } (dstBuffer as any).compressedSize = compressedSize; return dstBuffer; } export function compress(type: number, srcDataView: DataView): ArrayBuffer { switch (type) { case 1: return compress01(srcDataView); // TODO: Are all these really the same, particularly 4? case 2: case 3: case 4: return compress02(srcDataView); case 5: return compress05(srcDataView); case 0: default: // Just directly copy uncompressed data. return srcDataView.buffer.slice(0); } } export function getCompressedSize(type: number, srcDataView: DataView, decompressedSize: number) { let dstBuffer = new ArrayBuffer(decompressedSize); let dstView = new DataView(dstBuffer); switch (type) { case 1: return decompress01(srcDataView, dstView, decompressedSize); case 2: case 3: case 4: return decompress02(srcDataView, dstView, decompressedSize); case 5: return decompress05(srcDataView, dstView, decompressedSize); case 0: return decompressedSize; default: $$log(`getCompressedSize ${type} not implemented.`); } }
the_stack
const jsonldRdfaParser = require("jsonld-rdfa-parser"); const jsonldLib = require("jsonld"); // tslint:enable:no-var-requires jsonldLib.registerRDFParser("text/html", jsonldRdfaParser); import * as assert from "assert"; import * as fs from "fs"; import { ClientRequestArgs } from "http"; import * as http from "http"; import * as https from "https"; import * as path from "path"; import * as url from "url"; import { Url, UrlObject } from "url"; import * as util from "util"; import { ASLink, HttpRequestResponder } from "./types"; import { createLogger } from "../src/logger"; const logger = createLogger("util"); /** * Return the 'first' item of the provided itemOrList. * i.e. if itemOrList is an array, return the zero-indexed item. * if itemOrList is not a collection, return itself */ export const first = (itemOrList: any) => { if (Array.isArray(itemOrList)) { return itemOrList[0]; } return itemOrList; }; export const request = (urlOrOptions: string | UrlObject) => { const options = typeof urlOrOptions === "string" ? url.parse(urlOrOptions) : urlOrOptions; switch (options.protocol) { case "https:": return https.request(urlOrOptions); case "http:": return http.request(urlOrOptions); default: throw new Error(`cannot create request for protocol ${options.protocol}`); } }; export const debuglog = util.debuglog("distbin"); export const readableToString = ( readable: NodeJS.ReadableStream, ): Promise<string> => { let body: string = ""; return new Promise((resolve, reject) => { readable.on("error", reject); readable.on("data", (chunk: string) => { body += chunk; return body; }); readable.on("end", () => resolve(body)); }); }; export const requestUrl = (req: http.ServerRequest) => `http://${req.headers.host}${req.url}`; // given a map of strings/regexes to listener factories, // return a matching route (or undefined if no match) export type RoutePattern = string | RegExp; export type RouteResponderFactory = ( ...matches: string[] ) => HttpRequestResponder; export const route = ( routes: Map<RoutePattern, RouteResponderFactory>, req: http.ServerRequest, ) => { const pathname = url.parse(req.url).pathname; for (const [routePathname, createHandler] of routes.entries()) { if (typeof routePathname === "string") { // exact match if (pathname !== routePathname) { continue; } return createHandler(); } if (routePathname instanceof RegExp) { const match = pathname.match(routePathname); if (!match) { continue; } return createHandler(...match.slice(1)); } } }; export const sendRequest = ( r: http.ClientRequest, ): Promise<http.IncomingMessage> => { return new Promise((resolve, reject) => { r.once("response", resolve); r.once("error", reject); r.end(); }); }; export async function followRedirects( requestOpts: ClientRequestArgs, maxRedirects = 5, ) { let redirectsLeft = maxRedirects; const initialUrl = url.format(requestOpts); const latestUrl = initialUrl; assert(latestUrl); logger.silly("followRedirects", latestUrl); let latestResponse = await sendRequest(request(requestOpts)); /* eslint-disable no-labels */ followRedirects: while (redirectsLeft > 0) { logger.debug("followRedirects got response", { statusCode: latestResponse.statusCode, }); switch (latestResponse.statusCode) { case 301: case 302: const nextUrl = url.resolve( latestUrl, ensureArray(latestResponse.headers.location)[0], ); logger.debug("followRedirects is following to", nextUrl); latestResponse = await sendRequest( request( Object.assign(url.parse(nextUrl), { headers: requestOpts.headers, }), ), ); redirectsLeft--; continue followRedirects; default: return latestResponse; } } throw Object.assign( new Error(`Max redirects reached when requesting ${initialUrl}`), { redirects: maxRedirects - redirectsLeft, response: latestResponse, }, ); } const SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // Match everything outside of normal chars and " (quote character) const NON_ALPHANUMERIC_REGEXP = /([^#-~| |!])/g; /** * Escapes all potentially dangerous characters, so that the * resulting string can be safely inserted into attribute or * element text. * @param value * @returns {string} escaped text */ export const encodeHtmlEntities = function encodeEntities(value: string) { return value .replace(/&/g, "&amp;") .replace(SURROGATE_PAIR_REGEXP, match => { const hi = match.charCodeAt(0); const low = match.charCodeAt(1); return "&#" + ((hi - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000) + ";"; }) .replace(NON_ALPHANUMERIC_REGEXP, match => { return "&#" + match.charCodeAt(0) + ";"; }) .replace(/</g, "&lt;") .replace(/>/g, "&gt;"); }; // given a function that accepts a "node-style" errback as its last argument, return // a function that returns a promise instead export const denodeify = util.promisify; export const rdfaToJsonLd = async (html: string) => { return denodeify(jsonldLib.fromRDF)(html, { format: "text/html" }); // // use it // jsonldLib.fromRDF(html, {format: 'text/html'}, function(err, data) { }; export const isProbablyAbsoluteUrl = (someUrl: string): boolean => { const absoluteUrlPattern = new RegExp("^(?:[a-z]+:)?//", "i"); return absoluteUrlPattern.test(someUrl); }; export const ensureArray = <T>(itemOrItems: T | T[]): T[] => itemOrItems instanceof Array ? itemOrItems : [itemOrItems]; export const flatten = <T>(listOfLists: T[][]): T[] => listOfLists.reduce((flattened, list: T[]) => flattened.concat(list), []); // given an http request, return a number that is the maximum number of results this client wants in this response export const requestMaxMemberCount = (req: http.ServerRequest) => { const headerMatch = ensureArray(req.headers.prefer) .filter(Boolean) .map(header => header.match(/max-member-count="(\d+)"/)) .filter(Boolean)[0]; if (headerMatch) { return parseInt(headerMatch[1], 10); } // check querystring return parseInt( first(url.parse(req.url, true).query["max-member-count"]), 10, ); }; export const createHttpOrHttpsRequest = (urlOrObj: string | UrlObject) => { const parsedUrl: UrlObject = typeof urlOrObj === "string" ? url.parse(urlOrObj) : urlOrObj; let createRequest; switch (parsedUrl.protocol) { case "https:": createRequest = https.request.bind(https); break; case "http:": createRequest = http.request.bind(http); break; default: const activityUrl = url.format(parsedUrl); throw new Error( "Can't fetch activity with unsupported protocol in URL (only http, https supported): " + activityUrl, ); } return createRequest(urlOrObj); }; // given a Link object or url string, return an href string that can be used to refer to it export const linkToHref = (hrefOrLinkObj: ASLink | string) => { if (typeof hrefOrLinkObj === "string") { return hrefOrLinkObj; } if (typeof hrefOrLinkObj === "object") { return hrefOrLinkObj.href; } throw new Error("Unexpected link type: " + typeof hrefOrLinkObj); }; jsonldLib.documentLoader = createCustomDocumentLoader(); export const jsonld = jsonldLib.promises; type Errback = (err: Error, ...args: any[]) => void; function createCustomDocumentLoader() { // define a mapping of context URL => context doc const CONTEXTS: { [key: string]: string } = { "https://www.w3.org/ns/activitystreams": fs.readFileSync( path.join(__dirname, "/as2context.json"), "utf8", ), }; // grab the built-in node.js doc loader const nodeDocumentLoader = jsonldLib.documentLoaders.node(); // or grab the XHR one: jsonldLib.documentLoaders.xhr() // or grab the jquery one: jsonldLib.documentLoaders.jquery() // change the default document loader using the callback API // (you can also do this using the promise-based API, return a promise instead // of using a callback) const customLoader = (someUrl: string, callback: Errback) => { if (someUrl in CONTEXTS) { return callback(null, { contextUrl: null, // this is for a context via a link header document: CONTEXTS[someUrl], // this is the actual document that was loaded documentUrl: someUrl, // this is the actual context URL after redirects }); } // call the underlining documentLoader using the callback API. nodeDocumentLoader(someUrl, callback); /* Note: By default, the node.js document loader uses a callback, but browser-based document loaders (xhr or jquery) return promises if they are supported (or polyfilled) in the browser. This behavior can be controlled with the 'usePromise' option when constructing the document loader. For example: jsonldLib.documentLoaders.xhr({usePromise: false}); */ }; return customLoader; } export function assertNever(x: never): never { throw new Error("Unexpected object: " + x); } // Return new value for a JSON-LD object's value, appending to any existing one export function jsonldAppend(oldVal: any, valToAppend: any[] | any) { valToAppend = Array.isArray(valToAppend) ? valToAppend : [valToAppend]; let newVal; switch (typeof oldVal) { case "object": if (Array.isArray(oldVal)) { newVal = oldVal.concat(valToAppend); } else { newVal = [oldVal, ...valToAppend]; } break; case "undefined": newVal = valToAppend; break; default: newVal = [oldVal, ...valToAppend]; break; } return newVal; } export const makeErrorClass = ( name: string, setUp?: (...args: any[]) => void, ) => class extends Error { constructor(msg: string, ...args: any[]) { super(msg); this.message = msg; this.name = name; if (typeof setUp === "function") { setUp.apply(this, arguments); } } };
the_stack
import { IncomingMessage, ServerResponse } from 'http' import httpProxy from 'http-proxy' import PacProxyAgent from 'pac-proxy-agent' import consola from 'consola' import chalk from 'chalk' import path from 'path' import { renderTemplate } from '@portless/template' import { PortlessConfig } from '@portless/config' import { escapeReg, ThenType, getParentLevelDomain } from '@portless/util' export interface ReverseProxyOptions { publicKeyId?: string } export type IncomingDomainType = 'public' | 'local' export interface ReverseProxy { publicKeyId?: string targetDomain: string incomingDomains: { domain: string, type: IncomingDomainType }[] webMiddleware: (req: IncomingMessage, res: ServerResponse) => Promise<void> | void wsMiddleware: (req: IncomingMessage, socker: any, head: any) => Promise<void> | void } const proxies: ReverseProxy[] = [] const domainMap: { [key: string]: ReverseProxy } = {} const noReplaceReg = /\.(png|jpe?g|gif|webp|svg|mp4|webm|ogg|mp3|wav|flac|aac|woff2?|eot|ttf|otf)/ const forceHttpsMap: { [key: string]: boolean } = {} type UrlMap = { [key: string]: string[] } class Replacer { regValues: string[] = [] reg: RegExp map: UrlMap = {} add (fromUrl: string, toUrl: string) { this.regValues.push(escapeReg(fromUrl)) const mapUrls = this.map[fromUrl] = this.map[fromUrl] || [] mapUrls.push(toUrl) } build () { const dedupedValues = Array.from(new Set(this.regValues)) this.reg = new RegExp(`((http|ws)s?://)?(${dedupedValues.join('|')})`, 'g') } getReplace (req: IncomingMessage) { if (!this.reg) this.build() const secure = isSecure(req) // Put req host first (it has priority) const map: UrlMap = {} for (const key in this.map) { const list = this.map[key].slice() if (req.headers.host) { const index = list.indexOf(req.headers.host) if (index !== -1) { list.splice(index, 1) list.unshift(req.headers.host) } } map[key] = list } const replaceFn = (matched: string, g1: string, g2: string, g3: string) => { const proto = g1 ? `${g2}${secure ? 's' : ''}://` : '' return `${proto}${map[g3][0]}` } return (text: string) => text.replace(this.reg, replaceFn) } } export async function useReverseProxy (config: PortlessConfig, options: ReverseProxyOptions = {}) { if (!config.domains) return null const pacProxyAgent = config.targetProxy ? new PacProxyAgent(config.targetProxy) : undefined const currentProxies: ReverseProxy[] = [] async function proxyTarget (targetDomain: string) { if (proxies.some(p => p.targetDomain === targetDomain)) { consola.error(`A proxy targetting ${targetDomain} is already defined`) return } const proxy = httpProxy.createProxyServer({ target: `http://${targetDomain}`, agent: pacProxyAgent, changeOrigin: true, secure: false, ws: true, xfwd: true, }) proxy.on('error', (err, req, res) => { try { res.writeHead(500, { ContentType: 'text/html; charset=utf-8', }) let errorMessage = err.message if (errorMessage.startsWith('getaddrinfo ENOTFOUND')) { errorMessage = `Can't find host <b>${errorMessage.substr('getaddrinfo ENOTFOUND'.length + 1)}</b>` } res.end(renderTemplate(path.resolve(__dirname, '../templates/error.ejs'), { errorMessage, errorStack: err.stack, })) } catch (e) { consola.error(e) } consola.error(`Error proxying ${req.url}:`) consola.log(err.stack) }) // Rewrite URL in responses const targetToPublic: Replacer = new Replacer() const cookieTargetToPublic: Replacer = new Replacer() const publicToTarget: Replacer = new Replacer() const targetToLocal: Replacer = new Replacer() const cookieTargetToLocal: Replacer = new Replacer() const localToTarget: Replacer = new Replacer() if (config.domains) { for (const domainConfig of config.domains) { // Replace urls if (domainConfig.public) { targetToPublic.add(domainConfig.target, domainConfig.public) publicToTarget.add(domainConfig.public, domainConfig.target) // Cookie domains cookieTargetToPublic.add( `.${getParentLevelDomain(domainConfig.target)}`, `.${getParentLevelDomain(domainConfig.public)}`, ) // Spacial syntax targetToPublic.add(`${domainConfig.id}.portless`, domainConfig.public) } if (domainConfig.local) { targetToLocal.add(domainConfig.target, domainConfig.local) localToTarget.add(domainConfig.local, domainConfig.target) // Cookie domains cookieTargetToLocal.add( `.${getParentLevelDomain(domainConfig.target)}`, `.${getParentLevelDomain(domainConfig.local)}`, ) // Spacial syntax targetToLocal.add(`${domainConfig.id}.portless`, domainConfig.local) } } } function getIncomingDomain (req: IncomingMessage) { const host = req.headers.host if (host) { const incomingDomain = proxyInfo.incomingDomains.find(d => d.domain === host) if (incomingDomain) { return incomingDomain } } } function getReplacer (req: IncomingMessage, publicReplacer: Replacer, localReplacer: Replacer) { const url = req.url if (url && url.match(noReplaceReg)) { return } const domain = getIncomingDomain(req) if (domain) { if (domain.type === 'public') { return publicReplacer } else if (domain.type === 'local') { return localReplacer } } } const webMiddleware = (req: IncomingMessage, res: ServerResponse) => { // Replace links const replacer = getReplacer(req, targetToPublic, targetToLocal) const cookieReplacer = getReplacer(req, cookieTargetToPublic, cookieTargetToLocal) if (replacer && cookieReplacer) { // @TODO shouldRewrite was removed because `writeHead` is called after writting for some reason const replace = replacer.getReplace(req) const replaceCookie = cookieReplacer.getReplace(req) const _writeHead = res.writeHead.bind(res) res.writeHead = (...args: any) => { const headers = (args.length > 2) ? args[2] : args[1] // R<emove content-length heander since it will change res.removeHeader('content-length') if (headers) { delete headers['content-length'] } // Replace CORS header const corsHeader = res.getHeader('access-control-allow-origin') if (corsHeader && typeof corsHeader === 'string') { res.setHeader('access-control-allow-origin', replace(corsHeader)) } if (headers && headers['access-control-allow-origin']) { headers['access-control-allow-origin'] = replace(headers['access-control-allow-origin']) } // Rewrite cookies let setCookie: string[] = res.getHeader('set-cookie') as string[] if (setCookie) { res.setHeader('set-cookie', setCookie.map(cookie => replaceCookie(cookie))) } setCookie = headers && headers['set-cookie'] if (setCookie) { headers['set-cookie'] = setCookie.map(cookie => replaceCookie(cookie)) } return _writeHead(...args) } let rawBody = '' const _write = res.write.bind(res) res.write = (data: string | Buffer) => { let text: string if (data instanceof Buffer) { text = data.toString() } else { text = data } rawBody += text return true } const _end = res.end.bind(res) res.end = () => { _write(replace(rawBody)) _end() } } // Proxy HTTP proxy.web(req, res) } const wsMiddleware = (req: IncomingMessage, socket: any, head: any) => { const replacer = getReplacer(req, publicToTarget, localToTarget) if (replacer) { const replace = replacer.getReplace(req) if (req.headers.host) { req.headers.host = replace(req.headers.host) } if (Array.isArray(req.headers.origin)) { // @ts-ignore req.headers.origin = req.headers.origin.map(value => replace(value)) } else if (req.headers.origin) { req.headers.origin = replace(req.headers.origin) } } // Proxy websockets proxy.ws(req, socket, head) } const proxyInfo: ReverseProxy = { publicKeyId: options.publicKeyId, targetDomain, incomingDomains: [], webMiddleware, wsMiddleware, } currentProxies.push(proxyInfo) proxies.push(proxyInfo) } // Dedupe target urls const targetDomains = Array.from(new Set(config.domains.map(d => d.target))) // Create proxies for (const domain of targetDomains) { await proxyTarget(domain) } // Map Urls for (const domainConfig of config.domains) { const proxy = proxies.find(p => p.targetDomain === domainConfig.target) if (!proxy) { consola.error(`Proxy with target ${domainConfig.target} not found`) continue } const incoming = { public: domainConfig.public, local: domainConfig.local } for (const key in incoming) { const type: IncomingDomainType = key as keyof typeof incoming const domain = incoming[type] if (domain) { if (domainMap[domain]) { consola.error(`Domain ${domain} is already mapped to a Proxy`) } else { domainMap[domain] = proxy proxy.incomingDomains.push({ domain, type }) consola.log(chalk.cyan('PROXY'), chalk.bold(domain), '⇒', chalk.blue.bold(domainConfig.target)) } } } } function destroy () { // Remove current app proxies for (const proxy of currentProxies) { const index = proxies.indexOf(proxy) if (index !== -1) { proxies.splice(index, 1) } for (const incomingDomain of proxy.incomingDomains) { delete domainMap[incomingDomain.domain] } } } return { destroy, } } export type UseReverseProxy = ThenType<typeof useReverseProxy> export function getProxy (incoming: string): ReverseProxy | null { return domainMap[incoming] } function isSecure (req: IncomingMessage) { if (forceHttpsMap[req.headers.host || '']) { return true } const proto = req.headers['x-forwarded-proto'] return proto === 'https' || proto === 'wss' } export function forceHttps (domain: string, https: boolean) { forceHttpsMap[domain] = https }
the_stack
import 'hammerjs'; import 'mousetrap'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import Spy = jasmine.Spy; import { DebugElement } from '@angular/core'; import { AccessibilityConfig } from '../../model/accessibility.interface'; import { KS_DEFAULT_ACCESSIBILITY_CONFIG } from '../../components/accessibility-default'; import { InternalLibImage } from '../../model/image-internal.class'; import { ModalGalleryComponent } from './modal-gallery.component'; import { Size } from '../../model/size.interface'; import { SizeDirective } from '../../directives/size.directive'; import { WrapDirective } from '../../directives/wrap.directive'; import { DirectionDirective } from '../../directives/direction.directive'; import { ATagBgImageDirective } from '../../directives/a-tag-bg-image.directive'; import { ConfigService } from '../../services/config.service'; import { ModalGalleryService } from './modal-gallery.service'; import { IdValidatorService } from '../../services/id-validator.service'; import { KeyboardService } from '../../services/keyboard.service'; import { ModalGalleryConfig } from '../../model/modal-gallery-config.interface'; import { DIALOG_DATA } from './modal-gallery.tokens'; import { OverlayModule } from '@angular/cdk/overlay'; import { LibConfig } from '../../model/lib-config.interface'; import { UpperButtonsComponent } from '../upper-buttons/upper-buttons.component'; import { CurrentImageComponent, ImageLoadEvent } from '../current-image/current-image.component'; import { DotsComponent } from '../dots/dots.component'; import { PreviewsComponent } from '../previews/previews.component'; import { FallbackImageDirective } from '../../directives/fallback-image.directive'; import { ClickOutsideDirective } from '../../directives/click-outside.directive'; import { LoadingSpinnerComponent } from '../current-image/loading-spinner/loading-spinner.component'; import { DescriptionDirective } from '../../directives/description.directive'; import { KeyboardNavigationDirective } from '../../directives/keyboard-navigation.directive'; import { By, DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { ButtonConfig, ButtonEvent, ButtonType } from '../../model/buttons-config.interface'; import { Action } from '../../model/action.enum'; import { ImageModalEvent } from '../../model/image.class'; import { CurrentImageConfig } from '../../model/current-image-config.interface'; let comp: ModalGalleryComponent; let fixture: ComponentFixture<ModalGalleryComponent>; const CUSTOM_ACCESSIBILITY: AccessibilityConfig = Object.assign({}, KS_DEFAULT_ACCESSIBILITY_CONFIG); CUSTOM_ACCESSIBILITY.plainGalleryContentAriaLabel = 'custom plainGalleryContentAriaLabel'; CUSTOM_ACCESSIBILITY.plainGalleryContentTitle = 'custom plainGalleryContentTitle'; const DEFAULT_PLAIN_SIZE: Size = { width: 'auto', height: '50px' }; const CUSTOM_SIZE: Size = { height: '40px', width: '40px' }; const CUSTOM_SIZE_AUTO_HEIGHT: Size = { height: 'auto', width: '40px' }; const CUSTOM_SIZE_AUTO_WIDTH: Size = { height: '40px', width: 'auto' }; const CUSTOM_SIZES: Size[] = [CUSTOM_SIZE, CUSTOM_SIZE_AUTO_HEIGHT, CUSTOM_SIZE_AUTO_WIDTH]; const GALLERY_ID = 0; const IMAGES: InternalLibImage[] = [ new InternalLibImage(0, { // modal img: '../assets/images/gallery/img1.jpg', extUrl: 'http://www.google.com' }), new InternalLibImage(1, { // modal img: '../assets/images/gallery/img2.png', description: 'Description 2' }), new InternalLibImage( 2, { // modal img: '../assets/images/gallery/img3.jpg', description: 'Description 3', extUrl: 'http://www.google.com' }, { // plain img: '../assets/images/gallery/thumbs/img3.png', title: 'custom title 2', alt: 'custom alt 2', ariaLabel: 'arial label 2' } ), new InternalLibImage(3, { // modal img: '../assets/images/gallery/img4.jpg', description: 'Description 4', extUrl: 'http://www.google.com' }), new InternalLibImage( 4, { // modal img: '../assets/images/gallery/img5.jpg' }, { // plain img: '../assets/images/gallery/thumbs/img5.jpg' } ) ]; const IMAGES_CUSTOM_DOWNLOAD_FILENAME: InternalLibImage[] = [ new InternalLibImage(0, { // modal img: '../assets/images/gallery/img1.jpg', extUrl: 'http://www.google.com', downloadFileName: 'a.png' }), new InternalLibImage(1, { // modal img: '../assets/images/gallery/img2.png', description: 'Description 2', downloadFileName: 'b.png' }) ]; // example of a png converted into base64 using https://www.base64-image.de/ or other similar websites const base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABN0lEQV' + 'R4nO3SQQ2AQBDAwAVlaMEhCkAV' + 'b2RcQmcU9NEZAAAAAOD/tvN675k5VoewxLOvLmAtA8QZIM4AcQaIM0CcAeIMEGeAOAPEGSDOAHEGiDNAnAHiDBBngDgDxBkgzgBxBogzQJwB4gwQZ4A4A8QZIM4AcQaIM0C' + 'cAeIMEGeAOAPEGSDOAHEGiDNAnAHiDBBngDgDxBkgzgBxBogzQJwB4gwQZ4A4A8QZIM4AcQaIM0CcAeIMEGeAOAPEGSDOAHEGiDNAnAHiDBBngDgDxBkgzgBxBogzQJwB4g' + 'wQZ4A4A8QZIM4AcQaIM0CcAeIMEGeAOAPEGSDOAHEGiDNAnAHiDBBngDgDxBkgzgBxBogzQJwB4gwQZ4A4A8QZIM4AcQaIM0CcAeIMEGeAOAPEGQAAAAAA4Pc+8asEoPPGq' + 'xUAAAAASUVORK5CYII'; const base64RedString = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAY1BMVEX/AAD/////WVn/+vr/qan/Nzf/ERH/2tr/s7P/KSn/' + '7+//vr7/0ND/W1v/6+v/m5v/4+P/U1P/HR3/o6P/rq7/g4P/k5P/t7f/dXX/SEj/zMz/ZWX/h4f/bm7/amr/np7/yMhDG/2oAAAC8ElEQVR4nO3dC3KqQBCF4WkHERHFRyKIL/' + 'a/ymDuVYMMFipTbbfnW8H5S4lQVGUMaWe4B3iHQvlQKB8K5UOhfCiUD4XyoVA+FJ7Myijd5dvBO9nmuzQqZ68X2mI9NO9suC7s84VxNuAO6GSQxU8VJvuQe3pn4T55uLDYcK9+' + '0KZ4qDB574vPbej+HF2Fcc499km563p0FAbcQ18QdCi0B+6VLzk0fjtuC0dj7o0vGo/uF064B/agvFcYca/rRdReeOTe1pNjW6HkP6J1gbtQwzV4NnEVJtyrepU0C2M599ldhH' + 'GjcMq9qWfT28KUe1Hv0nrhnHuPB/Na4YJ7jgeLv4UZ9xovsmuhXXKP8WJpL4Ur7i2erC6Fun4Kr8Jz4Rf3Em++/hdKf+htN/5XqOuGtC75LfzmnuHR96nQ6v2SVl9TWxVq/pKevq' + 'aG1twjvFpXhTLeLz1rQMZyb/DMmhH3BM9GRudjxVVmtN51n62M1DdpXeVG2rveR22MxLe9jxgazfdsJ2Oj9en3THsfAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAgHba/+98+AFnI+g/30L/GSX6z5nRf1aQ/vOe9J/Zpf/cNf1n533A+Yf6z7DUfw6p/rNkVX9Nkw850/kDzuXWf7Y6ab37Xl0K7ZJ7ixdLeykknQ8YGV0LacG9xo' + 'MF/S2cc8/xYF4rpJR7T+9SqhfSlHtRz6Z0Wxjr+lEM40ahstvThJqFNOFe1aMJuQop4N7Vm4DchXTkXtaTI7UVUsS9rRcRtRequBZLuldII+mPw+MR3S8ke+De+JKDvQ1qFMr+kx' + 'o0cxyFFEt945bHjhpXYXV/I/HN8DBxtrgLiQpp74Y3RUtJW2H1Oe7l3IuHe/fnd7+wuh4zGe+lBpnr+utSWLHF+r0vyeG6aPw+PFT4a1ZG6S7fDt7JNt+lUTnrsL5LoWwolA+F8q' + 'FQPhTKh0L5UCgfCuVDoXw/lnQz7dm7GjoAAAAASUVORK5CYII='; const base64GreenString = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADIAgMAAADQNkYNAAAADFBMVEUAAAAy/ysy/ysy/ysyTcibAAAAA3RSTlMA2r/af0d' + 'WAAAAQUlEQVRo3u3YMREAMAzEsJAMyZJsMXy3XORdBFySJK3qxFXH1Y1DEARBEARBEARBEARBEARBkNmk436mvSRJ0o4eOKL2P81eyn8AAAAASUVORK5CYII='; class KeyboardServiceMock { init(config: LibConfig): Promise<void> { return new Promise(resolve => resolve()); } // tslint:disable-next-line:no-any add(onBind: (e: KeyboardEvent, combo: string) => any, config: LibConfig): void { } reset(config: LibConfig): void { } } function initTestBed(): void { TestBed.configureTestingModule({ imports: [OverlayModule], declarations: [ModalGalleryComponent, UpperButtonsComponent, CurrentImageComponent, DotsComponent, PreviewsComponent, LoadingSpinnerComponent, FallbackImageDirective, ClickOutsideDirective, DescriptionDirective, KeyboardNavigationDirective, SizeDirective, WrapDirective, DirectionDirective, ATagBgImageDirective] }).overrideComponent(ModalGalleryComponent, { set: { providers: [ { provide: ConfigService, useClass: ConfigService }, { provide: ModalGalleryService, useClass: ModalGalleryService }, { provide: KeyboardService, useClass: KeyboardServiceMock }, { provide: IdValidatorService, useClass: IdValidatorService }, { provide: DIALOG_DATA, useValue: { id: GALLERY_ID, images: IMAGES, currentImage: IMAGES[0], libConfig: { accessibilityConfig: CUSTOM_ACCESSIBILITY } as LibConfig } as ModalGalleryConfig } ] } }); } describe('ModalGalleryComponent', () => { beforeEach(() => { initTestBed(); fixture = TestBed.createComponent(ModalGalleryComponent); comp = fixture.componentInstance; }); it('should instantiate it', () => expect(comp).not.toBeNull()); describe('---YES---', () => { it(`should display modal gallery`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); const hasDataSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitHasData'); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); expect(hasDataSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onCustomEmit`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.CUSTOM } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onCustomEmit(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onFullScreen`, () => { const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, {accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG}); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const EVENT: ButtonEvent = { button: { type: ButtonType.FULLSCREEN } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onFullScreen(EVENT); }); it(`should display modal gallery and call onDelete`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.DELETE } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDelete(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onDelete with only 1 image`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = [IMAGES[0]]; // only 1 image comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const emitCloseSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitClose'); const EVENT: ButtonEvent = { button: { type: ButtonType.DELETE } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDelete(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); expect(emitCloseSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onNavigate`, () => { const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, {accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG}); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); // replace updateLocationHref() method in component with an empty function // to bypass window.location.href that causes test failures spyOn(comp, 'updateLocationHref').and.callFake(() => {}); const EVENT: ButtonEvent = { button: { type: ButtonType.EXTURL } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onNavigate(EVENT); }); it(`should display modal gallery and call onDownload with downloadable = true`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG, currentImageConfig: { downloadable: true } as CurrentImageConfig }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.DOWNLOAD } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDownload(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onDownload with downloadable = true and SafeResourceUrl img url as base64`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); const sanitizer = fixture.debugElement.injector.get(DomSanitizer); const base64Image: SafeResourceUrl = sanitizer.bypassSecurityTrustResourceUrl(base64String); const base64RedImage: SafeResourceUrl = sanitizer.bypassSecurityTrustResourceUrl(base64RedString); const base64GreenImage: SafeResourceUrl = sanitizer.bypassSecurityTrustResourceUrl(base64GreenString); const imagesBase64: InternalLibImage[] = [ new InternalLibImage(0, { img: base64Image, extUrl: 'http://www.google.com' }), new InternalLibImage(1, { img: base64GreenImage, description: 'Description 2' }), new InternalLibImage( 2, { img: base64RedImage, description: 'Description 3', extUrl: 'http://www.google.com' }, { img: base64RedImage, title: 'custom title 2', alt: 'custom alt 2', ariaLabel: 'arial label 2' } ) ]; configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG, currentImageConfig: { downloadable: true } as CurrentImageConfig }); comp.id = GALLERY_ID; comp.images = imagesBase64; comp.currentImage = imagesBase64[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.DOWNLOAD } as ButtonConfig, image: imagesBase64[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDownload(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onDownload with downloadable = true and custom downloadFileName`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG, currentImageConfig: { downloadable: true } as CurrentImageConfig }); comp.id = GALLERY_ID; comp.images = IMAGES_CUSTOM_DOWNLOAD_FILENAME; comp.currentImage = IMAGES_CUSTOM_DOWNLOAD_FILENAME[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.DOWNLOAD } as ButtonConfig, image: IMAGES_CUSTOM_DOWNLOAD_FILENAME[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDownload(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onCloseGalleryButton`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.CLOSE } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onCloseGalleryButton(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onCloseGallery`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ImageModalEvent = { action: Action.NORMAL, galleryId: GALLERY_ID, result: true }; comp.onCloseGallery(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); [true, false].forEach(isCalledByService => { it(`should display modal gallery and call closeGallery. Test with isCalledByService = ${isCalledByService}`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const emitCloseSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitClose'); const closeSpy: Spy<any> = spyOn<any>(modalGalleryService, 'close'); comp.closeGallery(Action.NORMAL, true, isCalledByService); expect(emitCloseSpy).toHaveBeenCalled(); expect(closeSpy).toHaveBeenCalled(); }); }); [0, 1, IMAGES.length - 1].forEach(index => { it(`should display modal gallery and call onChangeCurrentImage with Image at index = ${index}`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const emitShowSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitShow'); const EVENT: ImageModalEvent = { action: Action.NORMAL, galleryId: GALLERY_ID, result: index }; comp.onChangeCurrentImage(EVENT); expect(emitShowSpy).toHaveBeenCalled(); }); }); it(`should display modal gallery and call onClickOutside`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const emitCloseSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitClose'); const closeSpy: Spy<any> = spyOn<any>(modalGalleryService, 'close'); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); comp.onClickOutside(true); expect(emitCloseSpy).toHaveBeenCalled(); expect(closeSpy).toHaveBeenCalled(); }); it(`should display modal gallery and call onImageLoad`, () => { const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const EVENT: ImageLoadEvent = { status: true, index: 0, id: GALLERY_ID }; comp.onImageLoad(EVENT); }); it(`should display modal gallery and call onClickDot`, () => { const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); comp.onClickDot(1); }); it(`should display modal gallery and call onClickPreview`, () => { const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const EVENT: ImageModalEvent = { action: Action.NORMAL, galleryId: GALLERY_ID, result: 1 }; comp.onClickPreview(EVENT); }); it(`should display modal gallery and updateImages via modalGalleryService`, () => { const modalGalleryService: ModalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService: ConfigService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); // change IMAGES array pushing a new Image (equals to the first one) modalGalleryService.updateModalImages([...IMAGES, IMAGES[0]]); }); }); describe('---NO---', () => { [-1, IMAGES.length + 1].forEach(index => { it(`should display modal gallery and call onChangeCurrentImage without changing image, because index ${index} is out of bound.`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const emitShowSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitShow'); const EVENT: ImageModalEvent = { action: Action.NORMAL, galleryId: GALLERY_ID, result: index }; comp.onChangeCurrentImage(EVENT); expect(emitShowSpy).not.toHaveBeenCalled(); }); }); it(`should display modal gallery and call onClickOutside, but enableCloseOutside is false`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; comp.enableCloseOutside = false; fixture.detectChanges(); const emitCloseSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitClose'); const closeSpy: Spy<any> = spyOn<any>(modalGalleryService, 'close'); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); comp.onClickOutside(true); expect(emitCloseSpy).not.toHaveBeenCalled(); expect(closeSpy).not.toHaveBeenCalled(); }); it(`should display modal gallery and call onDownload with downloadable = false`, () => { const modalGalleryService = fixture.debugElement.injector.get(ModalGalleryService); const configService = fixture.debugElement.injector.get(ConfigService); configService.setConfig(GALLERY_ID, { accessibilityConfig: KS_DEFAULT_ACCESSIBILITY_CONFIG, currentImageConfig: { downloadable: false } as CurrentImageConfig }); comp.id = GALLERY_ID; comp.images = IMAGES; comp.currentImage = IMAGES[0]; fixture.detectChanges(); const element: DebugElement = fixture.debugElement; const modalGallery: DebugElement = element.query(By.css('div#modal-gallery-wrapper')); expect(modalGallery).not.toBeNull(); const beforeHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonBeforeHook'); const afterHookSpy: Spy<any> = spyOn<any>(modalGalleryService, 'emitButtonAfterHook'); const EVENT: ButtonEvent = { button: { type: ButtonType.DOWNLOAD } as ButtonConfig, image: IMAGES[0] as InternalLibImage, action: Action.NORMAL, galleryId: GALLERY_ID }; comp.onDownload(EVENT); expect(beforeHookSpy).toHaveBeenCalled(); expect(afterHookSpy).toHaveBeenCalled(); }); }); });
the_stack
import {scalar, Tensor, tensor1d, tensor2d, test_util} from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter'; import {ExecutionContext} from '../../executor/execution_context'; import {GraphExecutor} from '../../executor/graph_executor'; import {TensorArray} from '../../executor/tensor_array'; import {TensorList} from '../../executor/tensor_list'; import * as control from '../op_list/control'; import {Graph, Node} from '../types'; import {executeOp} from './control_executor'; import {createBoolAttr, createDtypeAttr, createNumberAttrFromIndex, createNumericArrayAttrFromIndex, createStrAttr, createTensorAttr, createTensorsAttr, createTensorShapeAttr, validateParam} from './test_helper'; import {createShapeAttrFromIndex} from './test_helper'; describe('control', () => { let node: Node; let input1: Tensor[]; let input2: Tensor[]; const context = new ExecutionContext({}, {}, {}); beforeEach(() => { node = { name: 'test', op: '', category: 'control', inputNames: ['input1', 'pred'], inputs: [], inputParams: {}, attrParams: {}, children: [] }; input1 = [tfOps.scalar(1, 'int32')]; input2 = [tfOps.scalar(0, 'bool')]; }); afterEach(() => { input1[0].dispose(); input2[0].dispose(); }); describe('executeOp', () => { describe('Switch', () => { it('should set the output condition is true', async () => { node.op = 'Switch'; node.inputParams['pred'] = createTensorAttr(1); node.inputParams['data'] = createTensorAttr(0); const pred = [tfOps.scalar(true)]; const result = await executeOp(node, {pred, input1}, context); expect(result[0]).toBeUndefined(); test_util.expectArraysEqual( await result[1].array(), await input1[0].array()); }); it('should set the output condition is false', async () => { node.op = 'Switch'; node.inputParams['pred'] = createTensorAttr(1); node.inputParams['data'] = createTensorAttr(0); const pred = [tfOps.scalar(false)]; const result = await executeOp(node, {pred, input1}, context); test_util.expectArraysEqual( await result[0].array(), await input1[0].array()); expect(result[1]).toBeUndefined(); }); it('should match json def', () => { node.op = 'Switch'; node.inputParams['pred'] = createTensorAttr(1); node.inputParams['data'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('Merge', () => { it('should return the first available input', async () => { node.op = 'Merge'; const pred = [tfOps.scalar(true)]; test_util.expectArraysEqual( await (await executeOp(node, {pred: undefined, input1}, context))[0] .array(), await input1[0].array()); test_util.expectArraysEqual( await (await executeOp(node, {pred, input1: undefined}, context))[0] .array(), await pred[0].array()); }); it('should return undefined if no inputs are available', async () => { node.op = 'Merge'; expect(await executeOp( node, {pred: undefined, input1: undefined}, context)) .toEqual(undefined); }); it('should match json def', () => { node.op = 'Merge'; expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('Enter', () => { it('should call enterFrame on context', async () => { spyOn(context, 'enterFrame'); node.op = 'Enter'; node.inputParams['tensor'] = createTensorAttr(0); node.attrParams['frameName'] = createStrAttr('test'); node.inputNames = ['input1']; test_util.expectArraysEqual( await (await executeOp(node, {input1}, context))[0].array(), await input1[0].array()); expect(context.enterFrame).toHaveBeenCalled(); }); it('should match json def', () => { node.op = 'Enter'; node.inputParams['tensor'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('Exit', () => { it('should call existFrame on context', async () => { spyOn(context, 'exitFrame'); node.op = 'Exit'; node.inputParams['tensor'] = createTensorAttr(0); node.inputNames = ['input1']; test_util.expectArraysEqual( await (await executeOp(node, {input1}, context))[0].array(), await input1[0].array()); expect(context.exitFrame).toHaveBeenCalled(); }); it('should match json def', () => { node.op = 'Exit'; node.inputParams['tensor'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('NextIteration', () => { it('should call nextIteration on context', async () => { spyOn(context, 'nextIteration'); node.op = 'NextIteration'; node.inputParams['tensor'] = createTensorAttr(0); node.inputNames = ['input1']; test_util.expectArraysEqual( await (await executeOp(node, {input1}, context))[0].array(), await input1[0].array()); expect(context.nextIteration).toHaveBeenCalled(); }); it('should match json def', () => { node.op = 'NextIteration'; node.inputParams['tensor'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayV3', () => { it('should create new tensor on the context', async () => { node.op = 'TensorArrayV3'; node.inputParams['size'] = createNumberAttrFromIndex(0); node.attrParams['name'] = createStrAttr(''); node.attrParams['dtype'] = createDtypeAttr('int32'); node.attrParams['elementShape'] = createTensorShapeAttr([10, 10]); node.attrParams['dynamicSize'] = createBoolAttr(false); node.attrParams['clearAfterRead'] = createBoolAttr(true); node.attrParams['identicalElementShapes'] = createBoolAttr(true); node.inputNames = ['input1']; const tensorId = (await executeOp(node, {input1}, context))[0]; expect(context.getTensorArray(tensorId.id)).toBeDefined(); }); it('should match json def', () => { node.op = 'TensorArrayV3'; node.inputParams['size'] = createNumberAttrFromIndex(0); node.attrParams['name'] = createStrAttr(''); node.attrParams['dtype'] = createDtypeAttr('int32'); node.attrParams['elementShape'] = createTensorShapeAttr([10, 10]); node.attrParams['dynamicSize'] = createBoolAttr(false); node.attrParams['clearAfterRead'] = createBoolAttr(true); node.attrParams['identicalElementShapes'] = createBoolAttr(true); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayWriteV3', () => { it('should write the tensor to tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [], true, false, true); context.addTensorArray(tensorArray); node.op = 'TensorArrayWriteV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); node.inputNames = ['input2', 'input3', 'input1']; const input2 = [tensorArray.idTensor]; const input3 = [scalar(0)]; await executeOp(node, {input1, input2, input3}, context); expect(tensorArray.size()).toEqual(1); }); it('should match json def', () => { node.op = 'TensorArrayWriteV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayReadV3', () => { it('should read the tensor from tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = tensor1d([0, 0, 0], 'int32'); tensorArray.write(0, input4); context.addTensorArray(tensorArray); node.op = 'TensorArrayReadV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputNames = ['input2', 'input3']; const input2 = [tensorArray.idTensor]; const input3 = [scalar(0)]; const read = await executeOp(node, {input1, input2, input3}, context); test_util.expectArraysClose( await read[0].array(), await input4.array()); }); it('should match json def', () => { node.op = 'TensorArrayReadV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayGatherV3', () => { it('should gather the tensors from tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = tensor1d([0, 0, 0], 'int32'); const input5 = tensor1d([1, 1, 1], 'int32'); tensorArray.writeMany([0, 1], [input4, input5]); context.addTensorArray(tensorArray); node.op = 'TensorArrayGatherV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.attrParams['dtype'] = createDtypeAttr('int32'); node.inputNames = ['input2', 'input3']; const input2 = [tensorArray.idTensor]; const input3 = [tensor1d([0, 1])]; const gather = await executeOp(node, {input2, input3}, context); expect(gather.length).toEqual(1); expect(gather[0].shape).toEqual([2, 3]); test_util.expectArraysClose( gather[0].dataSync(), new Int32Array([0, 0, 0, 1, 1, 1])); }); it('should match json def', () => { node.op = 'TensorArrayGatherV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.attrParams['dtype'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayScatterV3', () => { it('should scatter the tensor to tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = [tensor2d([0, 0, 0, 1, 1, 1], [2, 3], 'int32')]; context.addTensorArray(tensorArray); node.op = 'TensorArrayScatterV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); node.inputNames = ['input2', 'input3', 'input4']; const input2 = [tensorArray.idTensor]; const input3 = [tensor1d([0, 1], 'int32')]; await executeOp(node, {input2, input3, input4}, context); expect(tensorArray.size()).toEqual(2); }); it('should match json def', () => { node.op = 'TensorArrayScatterV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArraySplitV3', () => { it('should split the tensor to tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 2, [3], true, false, true); const input4 = [tensor2d([0, 0, 0, 1, 1, 1], [2, 3], 'int32')]; context.addTensorArray(tensorArray); node.op = 'TensorArraySplitV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['tensor'] = createTensorAttr(1); node.inputParams['lengths'] = createNumericArrayAttrFromIndex(2); node.inputNames = ['input2', 'input4', 'input3']; const input2 = [tensorArray.idTensor]; const input3 = [tensor1d([1, 1], 'int32')]; await executeOp(node, {input2, input3, input4}, context); expect(tensorArray.size()).toEqual(2); }); it('should match json def', () => { node.op = 'TensorArraySplitV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputParams['tensor'] = createTensorAttr(1); node.inputParams['lengths'] = createNumericArrayAttrFromIndex(2); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayConcatV3', () => { it('should concat the tensors from tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = tensor1d([0, 0, 0], 'int32'); const input5 = tensor1d([1, 1, 1], 'int32'); tensorArray.writeMany([0, 1], [input4, input5]); context.addTensorArray(tensorArray); node.op = 'TensorArrayConcatV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.attrParams['dtype'] = createDtypeAttr('int32'); node.inputNames = ['input2']; const input2 = [tensorArray.idTensor]; const concat = await executeOp(node, {input2}, context); expect(concat.length).toEqual(1); expect(concat[0].shape).toEqual([6]); test_util.expectArraysClose( concat[0].dataSync(), new Int32Array([0, 0, 0, 1, 1, 1])); }); it('should match json def', () => { node.op = 'TensorArrayConcatV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.attrParams['dtype'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArraySizeV3', () => { it('should get the size of tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = tensor1d([0, 0, 0], 'int32'); const input5 = tensor1d([1, 1, 1], 'int32'); tensorArray.writeMany([0, 1], [input4, input5]); context.addTensorArray(tensorArray); node.op = 'TensorArraySizeV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputNames = ['input2']; const input2 = [tensorArray.idTensor]; const size = await executeOp(node, {input2}, context); expect(size.length).toEqual(1); expect(size[0].shape).toEqual([]); test_util.expectArraysClose(size[0].dataSync(), new Int32Array([2])); }); it('should match json def', () => { node.op = 'TensorArraySizeV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorArrayCloseV3', () => { it('should close the tensorArray', async () => { const tensorArray = new TensorArray('', 'int32', 5, [3], true, false, true); const input4 = tensor1d([0, 0, 0], 'int32'); const input5 = tensor1d([1, 1, 1], 'int32'); tensorArray.writeMany([0, 1], [input4, input5]); context.addTensorArray(tensorArray); node.op = 'TensorArrayCloseV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); node.inputNames = ['input2']; const input2 = [tensorArray.idTensor]; await executeOp(node, {input2}, context); expect(tensorArray.closed).toBeTruthy(); }); it('should match json def', () => { node.op = 'TensorArrayCloseV3'; node.inputParams['tensorArrayId'] = createTensorAttr(0); expect(validateParam(node, control.json)).toBeTruthy(); }); }); }); describe('StatelessWhile', () => { it('should set the output', async () => { node.op = 'StatelessWhile'; node.inputNames = ['input1', 'input2']; node.inputParams['args'] = createTensorsAttr(0, 0); node.attrParams['cond'] = {'value': 'condFunc', 'type': 'func'}; node.attrParams['body'] = {'value': 'bodyFunc', 'type': 'func'}; const cond = [tfOps.scalar(false)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const condExecutor = new GraphExecutor(graph); let firstTime = true; spyOn(condExecutor, 'executeFunctionAsync').and.callFake(() => { if (firstTime) { firstTime = false; return input1; } return input2; }); const bodyExecutor = new GraphExecutor(graph); const input3 = [tfOps.scalar(3, 'int32')]; spyOn(bodyExecutor, 'executeFunctionAsync').and.returnValue(input3); context.functionMap['bodyFunc'] = bodyExecutor; context.functionMap['condFunc'] = condExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input3[0].array()); }); it('should match json def', () => { node.op = 'StatelessWhile'; node.inputNames = ['input1', 'input2']; node.inputParams['args'] = createTensorsAttr(0, 0); node.attrParams['cond'] = {'value': 'condFunc', 'type': 'func'}; node.attrParams['body'] = {'value': 'bodyFunc', 'type': 'func'}; expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('While', () => { it('should set the output', async () => { node.op = 'While'; node.inputNames = ['input1', 'input2']; node.inputParams['args'] = createTensorsAttr(0, 0); node.attrParams['cond'] = {'value': 'condFunc', 'type': 'func'}; node.attrParams['body'] = {'value': 'bodyFunc', 'type': 'func'}; const cond = [tfOps.scalar(false)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const condExecutor = new GraphExecutor(graph); let firstTime = true; spyOn(condExecutor, 'executeFunctionAsync').and.callFake(() => { if (firstTime) { firstTime = false; return input1; } return input2; }); const bodyExecutor = new GraphExecutor(graph); const input3 = [tfOps.scalar(3, 'int32')]; spyOn(bodyExecutor, 'executeFunctionAsync').and.returnValue(input3); context.functionMap['bodyFunc'] = bodyExecutor; context.functionMap['condFunc'] = condExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input3[0].array()); }); it('should match json def', () => { node.op = 'While'; node.inputNames = ['input1', 'input2']; node.inputParams['args'] = createTensorsAttr(0, 0); node.attrParams['cond'] = {'value': 'condFunc', 'type': 'func'}; node.attrParams['body'] = {'value': 'bodyFunc', 'type': 'func'}; expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('StatelessIf', () => { it('should set the output condition is true', async () => { node.op = 'StatelessIf'; node.inputNames = ['cond', 'input1', 'input2']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; const cond = [tfOps.scalar(true)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const thenExecutor = new GraphExecutor(graph); spyOn(thenExecutor, 'executeFunctionAsync').and.returnValue(input1); const elseExecutor = new GraphExecutor(graph); spyOn(elseExecutor, 'executeFunctionAsync').and.returnValue(input2); context.functionMap['thenFunc'] = thenExecutor; context.functionMap['elseFunc'] = elseExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input1[0].array()); }); it('should set the output condition is false', async () => { node.op = 'StatelessIf'; node.inputNames = ['cond', 'input1']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; const cond = [tfOps.scalar(false)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const thenExecutor = new GraphExecutor(graph); spyOn(thenExecutor, 'executeFunctionAsync').and.returnValue(input1); const elseExecutor = new GraphExecutor(graph); spyOn(elseExecutor, 'executeFunctionAsync').and.returnValue(input2); context.functionMap['thenFunc'] = thenExecutor; context.functionMap['elseFunc'] = elseExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input2[0].array()); }); it('should match json def', () => { node.op = 'StatelessIf'; node.inputNames = ['cond', 'input1']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('If', () => { it('should set the output condition is true', async () => { node.op = 'If'; node.inputNames = ['cond', 'input1', 'input2']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; const cond = [tfOps.scalar(true)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const thenExecutor = new GraphExecutor(graph); spyOn(thenExecutor, 'executeFunctionAsync').and.returnValue(input1); const elseExecutor = new GraphExecutor(graph); spyOn(elseExecutor, 'executeFunctionAsync').and.returnValue(input2); context.functionMap['thenFunc'] = thenExecutor; context.functionMap['elseFunc'] = elseExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input1[0].array()); }); it('should set the output condition is false', async () => { node.op = 'If'; node.inputNames = ['cond', 'input1']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; const cond = [tfOps.scalar(false)]; const graph: Graph = { inputs: [], nodes: { }, outputs: [], weights: [], placeholders: [], functions: {}, signature: {} }; const thenExecutor = new GraphExecutor(graph); spyOn(thenExecutor, 'executeFunctionAsync').and.returnValue(input1); const elseExecutor = new GraphExecutor(graph); spyOn(elseExecutor, 'executeFunctionAsync').and.returnValue(input2); context.functionMap['thenFunc'] = thenExecutor; context.functionMap['elseFunc'] = elseExecutor; const result = await executeOp(node, {cond, input1, input2}, context); test_util.expectArraysEqual( await result[0].array(), await input2[0].array()); }); it('should match json def', () => { node.op = 'If'; node.inputNames = ['cond', 'input1']; node.inputParams['args'] = createTensorsAttr(1, 0); node.inputParams['cond'] = createTensorAttr(0); node.attrParams['thenBranch'] = {'value': 'thenFunc', 'type': 'func'}; node.attrParams['elseBranch'] = {'value': 'elseFunc', 'type': 'func'}; expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListReserve', () => { it('should create new tensor on the context', async () => { node.op = 'TensorListReserve'; node.inputParams['elementShape'] = createNumericArrayAttrFromIndex(0); node.inputParams['numElements'] = createNumberAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.inputNames = ['input4', 'input1']; const input4 = [tensor1d([10, 10], 'int32')]; const tensorListId = (await executeOp(node, {input1, input4}, context))[0]; const tensorList = context.getTensorList(tensorListId.id); expect(tensorList.elementDtype).toEqual('int32'); expect(tensorList.elementShape).toEqual([10, 10]); expect(tensorList.maxNumElements).toEqual(1); }); it('should match json def', () => { node.op = 'TensorListReserve'; node.inputParams['elementShape'] = createShapeAttrFromIndex(0); node.inputParams['numElements'] = createNumberAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('EmptyTensorList', () => { it('should create new tensor on the context', async () => { node.op = 'EmptyTensorList'; node.inputParams['elementShape'] = createNumericArrayAttrFromIndex(0); node.inputParams['maxNumElements'] = createNumberAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.inputNames = ['input4', 'input1']; const input4 = [tensor1d([10, 10], 'int32')]; const tensorListId = (await executeOp(node, {input1, input4}, context))[0]; const tensorList = context.getTensorList(tensorListId.id); expect(tensorList.elementDtype).toEqual('int32'); expect(tensorList.elementShape).toEqual([10, 10]); expect(tensorList.maxNumElements).toEqual(1); }); it('should match json def', () => { node.op = 'EmptyTensorList'; node.inputParams['elementShape'] = createShapeAttrFromIndex(0); node.inputParams['maxNumElements'] = createNumberAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListConcat', () => { it('should concat the tensors from tensorList', async () => { const input4 = tensor1d([0, 0, 0], 'int32'); const input5 = tensor1d([1, 1, 1], 'int32'); const tensorList = new TensorList([input4, input5], [3], 'int32', 5); context.addTensorList(tensorList); node.op = 'TensorListConcat'; node.inputParams['tensorListId'] = createTensorAttr(0); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.attrParams['elementShape'] = createTensorShapeAttr([3]); node.inputNames = ['input2']; const input2 = [tensorList.idTensor]; const concat = await executeOp(node, {input2}, context); expect(concat.length).toEqual(1); expect(concat[0].shape).toEqual([6]); test_util.expectArraysClose( concat[0].dataSync(), new Int32Array([0, 0, 0, 1, 1, 1])); }); it('should match json def', () => { node.op = 'TensorListConcat'; node.inputParams['tensorListId'] = createTensorAttr(0); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.attrParams['elementShape'] = createTensorShapeAttr([3]); expect(validateParam(node, control.json)).toBeTruthy(); }); describe('TensorListScatter', () => { it('should scatter the tensor to tensorList', async () => { const input4 = [tensor2d([0, 0, 0, 1, 1, 1], [2, 3], 'int32')]; node.op = 'TensorListScatter'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.inputNames = ['input4', 'input2', 'input3']; const input2 = [tensor1d([0, 1], 'int32')]; const input3 = [tensor1d([3], 'int32')]; const tensorListId = (await executeOp(node, {input2, input3, input4}, context))[0]; const tensorList = context.getTensorList(tensorListId.id); expect(tensorList.size()).toEqual(2); }); it('should match json def', () => { node.op = 'TensorListScatter'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListScatterV2', () => { it('should scatter the tensor to tensorList', async () => { const input4 = [tensor2d([0, 0, 0, 1, 1, 1], [2, 3], 'int32')]; node.op = 'TensorListScatterV2'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.inputParams['numElements'] = createNumberAttrFromIndex(3); node.inputNames = ['input4', 'input2', 'input3', 'input5']; const input2 = [tensor1d([0, 1], 'int32')]; const input3 = [tensor1d([3], 'int32')]; const input5 = [tensor1d([2], 'int32')]; const tensorListId = (await executeOp( node, {input2, input3, input4, input5}, context))[0]; const tensorList = context.getTensorList(tensorListId.id); expect(tensorList.size()).toEqual(2); }); it('should match json def', () => { node.op = 'TensorListScatterV2'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.inputParams['numElements'] = createNumberAttrFromIndex(3); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListSetItem', () => { it('should write the tensor to tensorArray', async () => { const tensorList = new TensorList([], [], 'int32', 5); context.addTensorList(tensorList); node.op = 'TensorListSetItem'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.inputNames = ['input2', 'input3', 'input1']; const input2 = [tensorList.idTensor]; const input3 = [scalar(0)]; await executeOp(node, {input1, input2, input3}, context); expect(tensorList.size()).toEqual(1); }); it('should match json def', () => { node.op = 'TensorListSetItem'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['tensor'] = createTensorAttr(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListGetItem', () => { it('should read the tensor from tensorList', async () => { const tensorList = new TensorList([], [3], 'int32', 5); const input4 = tensor1d([0, 0, 0], 'int32'); tensorList.setItem(0, input4); context.addTensorList(tensorList); node.op = 'TensorListGetItem'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.inputNames = ['input2', 'input3', 'input5']; node.attrParams['elementDType'] = createDtypeAttr('int32'); const input2 = [tensorList.idTensor]; const input3 = [scalar(0)]; const input5 = [tensor1d([3], 'int32')]; const read = await executeOp(node, {input5, input2, input3}, context); test_util.expectArraysClose( await read[0].array(), await input4.array()); }); it('should match json def', () => { node.op = 'TensorListGetItem'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['index'] = createNumberAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListPushBack', () => { it('should write the tensor to tensorArray', async () => { const tensorList = new TensorList([], [], 'int32', 5); context.addTensorList(tensorList); node.op = 'TensorListPushBack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['tensor'] = createTensorAttr(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.inputNames = ['input2', 'input1']; const input2 = [tensorList.idTensor]; await executeOp(node, {input1, input2}, context); expect(tensorList.size()).toEqual(1); }); it('should match json def', () => { node.op = 'TensorListPushBack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['tensor'] = createTensorAttr(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListPopBack', () => { it('should read the tensor from tensorList', async () => { const tensorList = new TensorList([], [3], 'int32', 5); const input4 = tensor1d([0, 0, 0], 'int32'); tensorList.setItem(0, input4); context.addTensorList(tensorList); node.op = 'TensorListPopBack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.inputNames = ['input2', 'input5']; node.attrParams['elementDType'] = createDtypeAttr('int32'); const input2 = [tensorList.idTensor]; const input5 = [tensor1d([3], 'int32')]; const read = await executeOp(node, {input5, input2}, context); test_util.expectArraysClose( await read[0].array(), await input4.array()); }); it('should match json def', () => { node.op = 'TensorListPopBack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); describe('TensorListStack', () => { it('should read the tensor from tensorList', async () => { const tensorList = new TensorList([], [3], 'int32', 5); const input4 = tensor1d([0, 0, 0], 'int32'); tensorList.setItem(0, input4); context.addTensorList(tensorList); node.op = 'TensorListStack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.inputNames = ['input2', 'input5']; node.attrParams['elementDType'] = createDtypeAttr('int32'); const input2 = [tensorList.idTensor]; const input5 = [tensor1d([3], 'int32')]; const read = await executeOp(node, {input5, input2}, context); test_util.expectArraysClose( await read[0].array(), [await input4.array()]); }); it('should match json def', () => { node.op = 'TensorListStack'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); describe('TensorListGather', () => { it('should read the tensor from tensorList', async () => { const tensorList = new TensorList([], [3], 'int32', 5); const input4 = tensor1d([0, 0, 0], 'int32'); tensorList.setItem(0, input4); const input6 = tensor1d([1, 1, 1], 'int32'); tensorList.setItem(1, input6); context.addTensorList(tensorList); node.op = 'TensorListGather'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.inputNames = ['input2', 'input3', 'input5']; node.attrParams['elementDType'] = createDtypeAttr('int32'); const input2 = [tensorList.idTensor]; const input3 = [tensor1d([0, 1], 'int32')]; const input5 = [tensor1d([3], 'int32')]; const read = await executeOp(node, {input5, input2, input3}, context); test_util.expectArraysClose( await read[0].array(), [await input4.array(), await input6.array()]); }); it('should match json def', () => { node.op = 'TensorListGather'; node.inputParams['tensorListId'] = createTensorAttr(0); node.inputParams['indices'] = createNumericArrayAttrFromIndex(1); node.inputParams['elementShape'] = createShapeAttrFromIndex(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); }); describe('TensorListSplit', () => { it('should scatter the tensor to tensorList', async () => { const input4 = [tensor2d([0, 0, 0, 1, 1, 1], [2, 3], 'int32')]; node.op = 'TensorListSplit'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.inputParams['lengths'] = createNumericArrayAttrFromIndex(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); node.inputNames = ['input4', 'input2', 'input3']; const input2 = [tensor1d([3], 'int32')]; const input3 = [tensor1d([1, 1], 'int32')]; const idTensor = (await executeOp(node, {input2, input3, input4}, context))[0]; const tensorList = context.getTensorList(idTensor.id); expect(tensorList.size()).toEqual(2); }); it('should match json def', () => { node.op = 'TensorListSplit'; node.inputParams['tensor'] = createTensorAttr(0); node.inputParams['elementShape'] = createShapeAttrFromIndex(1); node.inputParams['lengths'] = createNumericArrayAttrFromIndex(2); node.attrParams['elementDType'] = createDtypeAttr('int32'); expect(validateParam(node, control.json)).toBeTruthy(); }); }); }); });
the_stack
import loadData from "../../assets/mock-data/curation/ingestion.data"; import curateData from "../../assets/mock-data/curation/flows.data"; import stepsData from "../../assets/mock-data/curation/steps.data"; import commonData from "../../assets/mock-data/curation/common.data"; import systemInfoData from "../../assets/mock-data/system-info.data"; const loadAPI = (axiosMock) => { axiosMock.delete["mockImplementation"]((url) => { switch (url) { case "/api/steps/ingestion/" + loadData.loads.data[0].name: return Promise.resolve(loadData.genericSuccess); default: return Promise.reject(new Error("not found")); } }); axiosMock.post["mockImplementation"]((url) => { switch (url) { case "/api/steps/ingestion/" + loadData.loads.data[0].name: return Promise.resolve({ "data": {}, "status": 200 }); default: return Promise.reject(new Error("not found")); } }); return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(loadData.flows); case "/api/steps/ingestion": return Promise.resolve(loadData.loads); case "/api/steps/ingestion/" + loadData.loads.data[0].name: return Promise.resolve(loadData.loadSettings); default: return Promise.reject(new Error("not found")); } }); }; const curateAPI = (axiosMock) => { axiosMock.delete["mockImplementation"]((url) => { switch (url) { case "/api/steps/ingestion/" + loadData.loads.data[0].name: return Promise.resolve(loadData.genericSuccess); case "/api/steps/mapping/" + curateData.mappings.data[0].artifacts[0].name: return Promise.resolve(loadData.genericSuccess); default: console.error("no DELETE defined: " + url); return Promise.reject(new Error("not found")); } }); axiosMock.post["mockImplementation"]((url) => { switch (url) { case "/api/steps/mapping/" + curateData.mappings.data[0].artifacts[0].name: return Promise.resolve({ "data": {}, "status": 200 }); default: console.error("no POST defined: " + url); return Promise.reject(new Error("not found")); } }); return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(curateData.flows); case "/api/steps": return Promise.resolve(curateData.steps); case "/api/models/primaryEntityTypes": return Promise.resolve(curateData.primaryEntityTypes); case "/api/steps/ingestion": return Promise.resolve(loadData.loads); case "/api/steps/ingestion/" + loadData.loads.data[0].name: return Promise.resolve(loadData.loadSettings); case "/api/steps/mapping": return Promise.resolve(curateData.mappings); case "/api/steps/mapping/" + curateData.mappings.data[0].artifacts[0].name: return Promise.resolve(curateData.mappingSettings); case "/api/artifacts/mapping/functions": return Promise.resolve({status: 200, data: {}}); case "/api/artifacts/matching": return Promise.resolve(curateData.matchings); case "/api/steps/custom": return Promise.resolve(curateData.customSteps); case "/api/steps/custom/customJSON": return Promise.resolve({status: 200, data: commonData.customData[0]}); case "/api/artifacts/mapping/entity/Customer": return Promise.resolve({status: 200, data: {}}); case "/api/steps/mapping/" + curateData.mappings.data[0].artifacts[0].name + "/uris?limit=20": return Promise.resolve({ "data": ["/testdoc.xml"], "status": 200 }); case `/api/steps/mapping/${curateData.mappings.data[0].artifacts[0].name}/doc?docUri=${encodeURIComponent("/testdoc.xml")}`: return Promise.resolve({status: 200, data: `<Order xmlns="https://www.w3schools.com/OrderNS"> <RequiredDate>1996-09-23T13:27:06</RequiredDate> <ShipName>B's Beverages</ShipName> <OrderDetails xmlns:y="https://www.w3schools.com/OD"> <OrderDetail xmlns:r="https://www.w3schools.com/Washington"> <r:UnitPrice>26.6000</r:UnitPrice> <r:Discount>0</r:Discount> <r:Quantity>9</r:Quantity> <r:ProductID>64</r:ProductID> </OrderDetail> <OrderDetail xmlns:n="https://www.w3schools.com/California"> <n:UnitPrice>27.2000</n:UnitPrice> <n:Discount>0</n:Discount> <n:Quantity>40</n:Quantity> <n:ProductID xmlns:k="https://www.w3schools.com/ProductNS">60</n:ProductID> </OrderDetail> </OrderDetails> <ShippedDate xmlns:l="https://www.w3schools.com/SD1">1996-08-28T19:15:26</ShippedDate> <ShippedDate xmlns:l="https://www.w3schools.com/SD2">1997-02-13T120:15:26</ShippedDate> <ShipCity>London</ShipCity> <CustomerID>BSBEV</CustomerID> <ShipVia xmlns="https://www.w3schools.com/SV">3</ShipVia> <ShipPostalCode>EC2 5NT</ShipPostalCode> <OrderID>10289</OrderID> <OrderDate>1996-08-26T07:24:10</OrderDate> <ShipRegion>null</ShipRegion> <ShipAddress>Fauntleroy Circus</ShipAddress> <ShipCountry>UK</ShipCountry> <EmployeeID>7</EmployeeID> <Freight>22.7700</Freight> </Order>`}); default: console.error("no GET defined: " + url); return Promise.reject(new Error("not found")); } }); }; const runAPI = (axiosMock) => { return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(curateData.flows); case "/api/steps": return Promise.resolve(curateData.steps); case "/api/flows/testFlow/latestJobInfo": return Promise.resolve({}); case "/api/steps/ingestion": return Promise.resolve(curateData.loads); case "/api/steps/mapping": return Promise.resolve(curateData.mappings); case "/api/jobs/e4590649-8c4b-419c-b6a1-473069186592": return Promise.resolve(curateData.jobRespSuccess); default: return Promise.reject(new Error("not found")); } }); }; const runCrudAPI = (axiosMock) => { // call Run API for the GET operations runAPI(axiosMock); axiosMock.post["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve({status: 201, data: {}}); case `/api/flows/${curateData.flows.data[0].name}/steps`: return Promise.resolve({status: 200, data: {}}); case `/api/flows/${curateData.flows.data[0].name}/steps/2`: return Promise.resolve({status: 200, data: {}}); default: return Promise.reject(new Error("not found")); } }); const updateURL = `/api/flows/${curateData.flows.data[0].name}`; axiosMock.put["mockImplementation"]((url) => { switch (url) { case updateURL: return Promise.resolve({status: 200, data: {}}); default: return Promise.reject(new Error("not found")); } }); return axiosMock.delete["mockImplementation"]((url) => { switch (url) { case updateURL: return Promise.resolve({status: 200, data: {}}); default: return Promise.reject(new Error("not found")); } }); }; const runAddStepAPI = (axiosMock) => { // call Run API for the GET operations runAPI(axiosMock); axiosMock.post["mockImplementation"]((url) => { switch (url) { case `/api/flows/${curateData.flows.data[0].name}/steps`: return Promise.resolve({status: 200, data: {}}); default: return Promise.reject(new Error("not found")); } }); }; // For testing display of a flow missing a step (DHFPROD-6369) const runMissingStep = (axiosMock) => { axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.reject({ "response": { "data": { "code": 400, "message": "Error message" } } }); case "/api/steps": return Promise.resolve(curateData.steps); default: return Promise.reject(new Error("not found")); } }); }; const runErrorsAPI = (axiosMock) => { return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(curateData.flows); case "/api/steps": return Promise.resolve(curateData.steps); case "/api/steps/ingestion": return Promise.resolve(curateData.loads); case "/api/steps/mapping": return Promise.resolve(curateData.mappings); case "/api/jobs/350da405-c1e9-4fa7-8269-d9aefe3b4b9a": return Promise.resolve(curateData.jobRespFailedWithError); default: return Promise.reject(new Error("not found")); } }); }; const runFailedAPI = (axiosMock) => { return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(curateData.flows); case "/api/steps": return Promise.resolve(curateData.steps); case "/api/steps/ingestion": return Promise.resolve(curateData.loads); case "/api/steps/mapping": return Promise.resolve(curateData.mappings); case "/api/jobs/350da405-c1e9-4fa7-8269-d9aefe3b4b9a": return Promise.resolve(curateData.jobRespFailed); default: return Promise.reject(new Error("not found")); } }); }; const runXMLAPI = (axiosMock) => { return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/flows": return Promise.resolve(curateData.flowsXML); case "/api/flows/testFlow/latestJobInfo": return Promise.resolve(curateData.flowsXMLLatestJob); case "/api/steps": return Promise.resolve(curateData.steps); case "/api/steps/ingestion": return Promise.resolve(curateData.loadsXML); case "/api/steps/mapping": return Promise.resolve(curateData.mappings); case "/api/jobs/350da405-c1e9-4fa7-8269-d9aefe3b4b9a": return Promise.resolve(curateData.jobRespFailedWithError); default: return Promise.reject(new Error("not found")); } }); }; const advancedAPI = (axiosMock) => { axiosMock.post["mockImplementationOnce"](jest.fn(() => Promise.resolve({status: 200, data: {}}))); return axiosMock.get["mockImplementation"]((url) => { const targetEntityType = String(stepsData.stepMerging.targetEntityType); const targetEntityTitle = targetEntityType.substring(targetEntityType.lastIndexOf("/") + 1); const defaultCollectionsURL = `/api/steps/merging/defaultCollections/${encodeURIComponent(targetEntityTitle)}`; switch (url) { case "/api/steps/ingestion/AdvancedLoad": return Promise.resolve({status: 200, data: stepsData.stepLoad}); //Settings for a custom ingestion step case "/api/steps/ingestion/CustomLoad": return Promise.resolve({data: {...stepsData.stepLoad, stepDefinitionName: "custom-ingestion", name: "CustomLoad"}, status: 200}); case "/api/steps/mapping/AdvancedMapping": return Promise.resolve(stepsData.stepMapping); case "/api/steps/matching/AdvancedMatching": return Promise.resolve(stepsData.stepMatching); case "/api/steps/merging/AdvancedMerging": return Promise.resolve(stepsData.stepMerging); case defaultCollectionsURL: return Promise.resolve(stepsData.defaultTargetCollections); default: return Promise.reject(new Error("not found")); } }); }; const systemInfoAPI = (axiosMock) => { return axiosMock["mockImplementation"]((url) => { switch (url) { case "/api/environment/systemInfo": return Promise.resolve({status: 200, data: systemInfoData.environment}); default: return Promise.reject(new Error("not found")); } }); }; const noResponseAPI = (axiosMock) => { return axiosMock.get["mockImplementation"]((url) => { switch (url) { case "/api/environment/systemInfo": return Promise.reject(new Error()); default: return Promise.reject(new Error("not found")); } }); }; const clearUserDataAPI = (axiosMock) => { return axiosMock.post["mockImplementation"]((url) => { switch (url) { case "/api/environment/clearUserData": return Promise.resolve({ "data": {}, "status": 200 }); default: return Promise.reject(new Error("not found")); } }); }; const mocks = { loadAPI: loadAPI, curateAPI: curateAPI, runAPI: runAPI, runAddStepAPI: runAddStepAPI, runMissingStep: runMissingStep, runCrudAPI: runCrudAPI, runErrorsAPI: runErrorsAPI, runFailedAPI: runFailedAPI, runXMLAPI: runXMLAPI, advancedAPI: advancedAPI, systemInfoAPI: systemInfoAPI, noResponseAPI: noResponseAPI, clearUserDataAPI: clearUserDataAPI }; export default mocks;
the_stack
import * as React from 'react'; import { Tree } from 'antd'; import { AntTreeNodeDropEvent } from 'antd/lib/tree/Tree'; import { ReactElement } from 'react'; import { TreeProps, AntTreeNodeCheckedEvent } from 'antd/lib/tree'; import { EventDataNode } from 'rc-tree/lib/interface'; import OlMap from 'ol/Map'; import OlLayerBase from 'ol/layer/Base'; import OlLayerGroup from 'ol/layer/Group'; import OlCollection from 'ol/Collection'; import OlMapEvent from 'ol/MapEvent'; import { unByKey } from 'ol/Observable'; import { getUid } from 'ol'; import _isBoolean from 'lodash/isBoolean'; import _isFunction from 'lodash/isFunction'; import _isEqual from 'lodash/isEqual'; import Logger from '@terrestris/base-util/dist/Logger'; import MapUtil from '@terrestris/ol-util/dist/MapUtil/MapUtil'; import LayerTreeNode, { LayerTreeNodeProps } from './LayerTreeNode/LayerTreeNode'; import { CSS_PREFIX } from '../constants'; interface DefaultProps extends TreeProps { /** * An optional array-filter function that is applied to every layer and * subLayer. Return false to exclude this layer from the layerTree or true * to include it. * * Compare MDN Docs for Array.prototype.filter: https://mdn.io/array/filter */ filterFunction: (value: any, index: number, array: any[]) => boolean; } export interface BaseProps { /** * An optional CSS class which should be added. */ className?: string; /** * A LayerGroup the Tree should handle. */ layerGroup?: OlLayerGroup; /** * The OpenLayers map the tree interacts with. */ map: OlMap; /** * A function that can be used to pass a custom node title. It can return * any renderable element (String, Number, Element etc.) and receives * the layer instance of the current tree node. */ nodeTitleRenderer?: (layer: OlLayerBase) => React.ReactNode; } interface LayerTreeState { layerGroup: OlLayerGroup; layerGroupRevision?: number; treeNodes: ReactElement<LayerTreeNodeProps>[]; checkedKeys: React.ReactText[]; mapResolution: number; } export type LayerTreeProps = BaseProps & Partial<DefaultProps> & TreeProps; /** * The LayerTree. * * Note. This component expects that all layerGroups are permanently visible. * * @class LayerTree * @extends React.Component */ class LayerTree extends React.Component<LayerTreeProps, LayerTreeState> { /** * The default properties. */ static defaultProps: DefaultProps = { draggable: true, checkable: true, filterFunction: () => true }; /** * The className added to this component. * @private */ className = `${CSS_PREFIX}layertree`; /** * An array of ol.EventsKey as returned by on() or once(). * @private */ olListenerKeys = []; /** * Create the LayerTree. * * @constructs LayerTree */ constructor(props: LayerTreeProps) { super(props); this.state = { layerGroup: null, layerGroupRevision: null, treeNodes: [], checkedKeys: [], mapResolution: -1 }; } /** * Invoked after the component is instantiated as well as when it * receives new props. It should return an object to update state, or null * to indicate that the new props do not require any state updates. * * @param nextProps The next properties. * @param prevState The previous state. */ static getDerivedStateFromProps(nextProps: LayerTreeProps, prevState: LayerTreeState) { if (prevState.layerGroup && nextProps.layerGroup) { if (!_isEqual(getUid(prevState.layerGroup), getUid(nextProps.layerGroup)) || !_isEqual(prevState.layerGroupRevision, nextProps.layerGroup.getRevision())) { return { layerGroup: nextProps.layerGroup, layerGroupRevision: nextProps.layerGroup.getRevision() }; } } return null; } /** * Determines what to do on the initial mount. */ componentDidMount() { const layerGroup = this.props.layerGroup ? this.props.layerGroup : this.props.map.getLayerGroup(); const revision = this.props.layerGroup ? this.props.layerGroup.getRevision() : 0; this.setState({ layerGroup: layerGroup, layerGroupRevision: revision }, () => { this.registerAddRemoveListeners(this.state.layerGroup); this.registerResolutionChangeHandler(); this.rebuildTreeNodes(); }); } /** * Invoked immediately after updating occurs. This method is not called for * the initial render. * * @param prevProps The previous props. * @param prevState The previous state. */ componentDidUpdate(prevProps: LayerTreeProps, prevState: LayerTreeState) { const { layerGroup, nodeTitleRenderer } = this.props; if (layerGroup && prevState.layerGroup) { if (!_isEqual(getUid(prevState.layerGroup), getUid(layerGroup))) { unByKey(this.olListenerKeys); this.olListenerKeys = []; this.registerAddRemoveListeners(layerGroup); this.rebuildTreeNodes(); } } if (nodeTitleRenderer !== prevProps.nodeTitleRenderer) { this.rebuildTreeNodes(); } } /** * Determines what to do when the component is unmounted. */ componentWillUnmount() { unByKey(this.olListenerKeys); } /** * Creates TreeNodes from a given layergroup and sets the treeNodes in the state. * * @param groupLayer A grouplayer. */ treeNodesFromLayerGroup(groupLayer: OlLayerGroup) { const layerArray = groupLayer.getLayers().getArray() .filter(this.props.filterFunction); const treeNodes = layerArray.map((layer) => { return this.treeNodeFromLayer(layer); }); treeNodes.reverse(); this.setState({ treeNodes }); } /** * Registers the add/remove listeners recursively for all ol.layer.Group. * * @param groupLayer A ol.layer.Group */ registerAddRemoveListeners(groupLayer: OlLayerGroup) { const collection = groupLayer.getLayers(); const addEvtKey = collection.on('add', this.onCollectionAdd); const removeEvtKey = collection.on('remove', this.onCollectionRemove); // @ts-ignore const changeEvtKey = groupLayer.on('change:layers', this.onChangeLayers); this.olListenerKeys.push(addEvtKey, removeEvtKey, changeEvtKey); collection.forEach((layer) => { if (layer instanceof OlLayerGroup) { this.registerAddRemoveListeners(layer); } }); } /** * Registers an eventhandler on the `ol.View`, which will rebuild the tree * nodes whenever the view's resolution changes. */ registerResolutionChangeHandler() { const { map } = this.props; const evtKey = map.on('moveend', this.rebuildTreeNodes.bind(this)); this.olListenerKeys.push(evtKey); // TODO when and how to we unbind? } /** * Listens to the collections add event of a collection. * Registers add/remove listeners if element is a collection and rebuilds the * treeNodes. * * @param evt The add event. */ onCollectionAdd = (evt: any) => { if (evt.element instanceof OlLayerGroup) { this.registerAddRemoveListeners(evt.element); } this.rebuildTreeNodes(); }; /** * Listens to the collections remove event of a collection. * Unregisters the events of deleted layers and rebuilds the treeNodes. * * @param evt The remove event. */ onCollectionRemove = (evt: any) => { this.unregisterEventsByLayer(evt.element); if (evt.element instanceof OlLayerGroup) { evt.element.getLayers().forEach((layer) => { this.unregisterEventsByLayer(layer); }); } this.rebuildTreeNodes(); }; /** * Listens to the LayerGroups change:layers event. * Unregisters the old and reregisters new listeners. * * @param evt The change event. */ onChangeLayers = (evt: any) => { this.unregisterEventsByLayer(evt.oldValue); if (evt.oldValue instanceof OlCollection) { evt.oldValue.forEach((layer) => this.unregisterEventsByLayer(layer)); } if (evt.target instanceof OlLayerGroup) { this.registerAddRemoveListeners(evt.target); } this.rebuildTreeNodes(); }; /** * Unregisters the Events of a given layer. * * @param layer An ol.layer.Base. */ unregisterEventsByLayer = (layer: OlLayerBase) => { this.olListenerKeys = this.olListenerKeys.filter((key) => { if (layer instanceof OlLayerGroup) { const layers = layer.getLayers(); if (key.target === layers) { if ((key.type === 'add' && key.listener === this.onCollectionAdd) || (key.type === 'remove' && key.listener === this.onCollectionRemove) || (key.type === 'change:layers' && key.listener === this.onChangeLayers)) { unByKey(key); return false; } } } else if (key.target === layer) { if (key.type === 'change:visible' && key.listener === this.onLayerChangeVisible) { unByKey(key); return false; } } return true; }); }; /** * Rebuilds the treeNodes and its checked states. * @param evt The OpenLayers MapEvent (passed by moveend) * */ rebuildTreeNodes = (evt?: OlMapEvent) => { const { mapResolution } = this.state; let newMapResolution: number = -1; if (evt?.target instanceof OlMap) { newMapResolution = evt.target.getView().getResolution(); if (mapResolution === newMapResolution) { // If map resolution didn't change => no redraw of tree nodes needed. return; } } this.treeNodesFromLayerGroup(this.state.layerGroup); const checkedKeys = this.getVisibleOlUids(); this.setState({ checkedKeys, mapResolution: newMapResolution }); }; /** * Returns the title to render in the LayerTreeNode. If a nodeTitleRenderer * has been passed as prop, it will be called and the (custom) return value * will be rendered. Note: This can be any renderable element collection! If * no function is given (the default) the layer name will be passed. * * @param layer The layer attached to the tree node. * @return The title composition to render. */ getTreeNodeTitle(layer: OlLayerBase) { if (_isFunction(this.props.nodeTitleRenderer)) { return this.props.nodeTitleRenderer.call(this, layer); } else { return layer.get('name'); } } /** * Creates a treeNode from a given layer. * * @param layer The given layer. * @return The corresponding LayerTreeNode Element. */ treeNodeFromLayer(layer: OlLayerBase): ReactElement<LayerTreeNodeProps> { let childNodes: ReactElement<LayerTreeNodeProps>[]; if (layer instanceof OlLayerGroup) { const childLayers = layer.getLayers().getArray() .filter(this.props.filterFunction); childNodes = childLayers.map((childLayer: OlLayerBase) => { return this.treeNodeFromLayer(childLayer); }); childNodes.reverse(); } else { if (!this.hasListener(layer, 'change:visible', this.onLayerChangeVisible)) { const eventKey = layer.on('change:visible', this.onLayerChangeVisible); this.olListenerKeys.push(eventKey); } } return ( <LayerTreeNode title={this.getTreeNodeTitle(layer)} key={getUid(layer)} inResolutionRange={MapUtil.layerInResolutionRange(layer, this.props.map)} > {childNodes} </LayerTreeNode> ); } /** * Determines if the target has already registered the given listener for the * given eventtype. * * @param target The event target. * @param type The events type (name). * @param listener The function. * @return True if the listener is already contained in this.olListenerKeys. */ hasListener = (target, type, listener) => { return this.olListenerKeys.some((listenerKey) => { return listenerKey.target === target && listenerKey.type === type && listenerKey.listener === listener; }); }; /** * Reacts to the layer change:visible event and calls setCheckedState. * * @param evt The change:visible event */ onLayerChangeVisible = () => { const checkedKeys = this.getVisibleOlUids(); this.setState({ checkedKeys }, () => { this.rebuildTreeNodes(); }); }; /** * Get the flat array of ol_uids from visible non groupLayers. * * @return The visible ol_uids. */ getVisibleOlUids = () => { const layers = MapUtil.getAllLayers(this.state.layerGroup, (layer) => { return !(layer instanceof OlLayerGroup) && layer.getVisible(); }).filter(this.props.filterFunction); return layers.map(getUid); }; /** * Sets the visibility of a layer due to its checked state. * * @param checkedKeys Contains all checkedKeys. * @param checked The ant-tree event object for this event. See ant docs. */ onCheck(checkedKeys: string[], e: AntTreeNodeCheckedEvent) { const { checked } = e; const eventKey = e.node.props.eventKey; const layer = MapUtil.getLayerByOlUid(this.props.map, eventKey); this.setLayerVisibility(layer, checked); } /** * Sets the layer visibility. Calls itself recursively for groupLayers. * * @param layer The layer. * @param visibility The visibility. */ setLayerVisibility(layer: OlLayerBase, visibility: boolean) { if (!(layer instanceof OlLayerBase) || !_isBoolean(visibility)) { Logger.error('setLayerVisibility called without layer or visiblity.'); return; } if (layer instanceof OlLayerGroup) { layer.setVisible(visibility); layer.getLayers().forEach((subLayer) => { this.setLayerVisibility(subLayer, visibility); }); } else { layer.setVisible(visibility); // if layer has a parent folder, make it visible too if (visibility) { const group = this.props.layerGroup ? this.props.layerGroup : this.props.map.getLayerGroup(); this.setParentFoldersVisible(group, getUid(layer), group); } } } /** * Find the parent OlLayerGroup for the given layers ol_uid and make it * visible. Traverse the tree to also set the parenting layer groups visible * * @param currentGroup The current group to search in * @param olUid The ol_uid of the layer or folder that has been set visible * @param masterGroup The main group to search in. Needed when searching for * parents as we always have to start search from top */ setParentFoldersVisible(currentGroup: OlLayerGroup, olUid: string, masterGroup: OlLayerGroup) { const items = currentGroup.getLayers().getArray(); const groups = items.filter(l => l instanceof OlLayerGroup) as OlLayerGroup[]; const match = items.find(i => getUid(i) === olUid); if (match) { currentGroup.setVisible(true); this.setParentFoldersVisible(masterGroup, getUid(currentGroup), masterGroup); return; } groups.forEach(g => { this.setParentFoldersVisible(g, olUid, masterGroup); }); } /** * The callback method for the drop event. Layers will get reordered in the map * and the tree. * * @param e The ant-tree event object for this event. See ant docs. */ onDrop(e: AntTreeNodeDropEvent) { const dragLayer = MapUtil.getLayerByOlUid(this.props.map, e.dragNode.props.eventKey); const dragInfo = MapUtil.getLayerPositionInfo(dragLayer, this.props.map); const dragCollection = dragInfo.groupLayer.getLayers(); const dropLayer = MapUtil.getLayerByOlUid(this.props.map, e.node.props.eventKey); const dropPos = e.node.props.pos.split('-'); const location = e.dropPosition - Number(dropPos[dropPos.length - 1]); dragCollection.remove(dragLayer); const dropInfo = MapUtil.getLayerPositionInfo(dropLayer, this.props.map); const dropPosition = dropInfo.position; const dropCollection = dropInfo.groupLayer.getLayers(); // drop before node if (location === -1) { if (dropPosition === dropCollection.getLength() - 1) { dropCollection.push(dragLayer); } else { dropCollection.insertAt(dropPosition + 1, dragLayer); } // drop on node } else if (location === 0) { if (dropLayer instanceof OlLayerGroup) { dropLayer.getLayers().push(dragLayer); } else { dropCollection.insertAt(dropPosition + 1, dragLayer); } // drop after node } else if (location === 1) { dropCollection.insertAt(dropPosition, dragLayer); } this.rebuildTreeNodes(); } /** * Call rebuildTreeNodes onExpand to avoid sync issues. * */ onExpand = (expandedKeys: string[], info: { node: EventDataNode; expanded: boolean; nativeEvent: MouseEvent; }) => { const { onExpand } = this.props; this.rebuildTreeNodes(); if (onExpand) { onExpand(expandedKeys, info); } }; /** * The render function. */ render() { const { className, layerGroup, map, nodeTitleRenderer, ...passThroughProps } = this.props; let ddListeners: any; if (passThroughProps.draggable) { ddListeners = { onDrop: this.onDrop.bind(this) }; } const finalClassName = className ? `${className} ${this.className}` : this.className; return ( <Tree className={finalClassName} checkedKeys={this.state.checkedKeys} onCheck={this.onCheck.bind(this)} onExpand={this.onExpand} {...ddListeners} {...passThroughProps} > {this.state.treeNodes} </Tree> ); } } export default LayerTree;
the_stack
import { safeLoad } from 'js-yaml'; import { resolve, join } from 'path'; import * as Client from 'fabric-client'; import { ensureDir, ensureFile, readdir, readFile } from 'fs-extra'; import { ClientConfig, TxResult, TxListenerResult } from './models'; export class ClientHelper { public client: Client; public user: Client.User; public config: ClientConfig; public channel: Client.Channel; private _organizations: string[]; public get organizations() { // If this was already initialized return the result if (this._organizations) { return this._organizations; } return this.channel ? this.channel.getOrganizations() .map((org: any) => org.id as string) : this.networkConfig.getOrganizations() .map(org => org.getMspid()); } private _channels: (Client.Channel & { name: string })[]; public get channels() { if (this._channels) { return this._channels; } const channels = Object.keys(this.networkConfig._network_config.channels); this._channels = channels.map(name => { const ch: any = this.client.getChannel(name); ch.name = ch._name; return ch; }); return this._channels; } public get networkConfig(): any { return (this.client as any)._network_config as Client; } private $initializing: Promise<void>; private hubsInUse: Client.ChannelEventHub[] = []; constructor(config: ClientConfig) { this.config = { txTimeout: 300000, skipInit: false, ...config }; if (!this.config.skipInit) { this.$initializing = this.init(); } } public async init(initKeyStore = false) { if (this.$initializing) { return await this.$initializing; } this.client = new Client(); // The client needs to create the user credentials based on the CA key/cert if (initKeyStore) { const stateStore = await Client.newDefaultKeyValueStore({ path: this.renderVariables(this.config.keyStore) }); this.client.setStateStore(stateStore); const cryptoSuite = Client.newCryptoSuite(); const cryptoStore = Client.newCryptoKeyStore({ path: this.renderVariables(this.config.keyStore) }); cryptoSuite.setCryptoKeyStore(cryptoStore); this.client.setCryptoSuite(cryptoSuite); const mspPath = resolve(process.cwd(), this.renderVariables(this.config.userMspPath)); try { await ensureDir(mspPath); } catch (e) { throw new Error(`The userMspPath ${mspPath} is not reachable or not a directory`); } await this.client.createUser({ skipPersistence: false, mspid: this.config.userMsp, username: this.config.user, cryptoContent: { privateKeyPEM: await this.readSingleFileInDir(join(mspPath, 'keystore')), signedCertPEM: await this.readSingleFileInDir(join(mspPath, 'signcerts')) } }); } if (typeof this.config.networkProfile === 'string') { const networkProfilePath = this.renderVariables(this.config.networkProfile); try { const profileStr = await readFile(resolve(process.cwd(), networkProfilePath), 'utf8'); if (/\.json$/.test(networkProfilePath)) { this.config.networkProfile = JSON.parse(profileStr); } else { this.config.networkProfile = safeLoad(profileStr); } } catch (e) { throw new Error( `Failed to read or parse the network profile at '${networkProfilePath}', ${e.toString()}` ); } } const { organizations } = this.config.networkProfile as any; await Promise .all(Object.keys(organizations) .map(async name => { const org = organizations[name]; if (org.adminPrivateKey && org.signedCert) { org.adminPrivateKey.path = await this.getLonelyFile(org.adminPrivateKey.path); org.signedCert.path = await this.getLonelyFile(org.signedCert.path); } })); // add here this.client.setTlsClientCertAndKey this.client.loadFromConfig(this.config.networkProfile); await this.client.initCredentialStores(); if (this.config.user) { await this.useUser(this.config.user); } if (this.config.channel) { await this.useChannel(this.config.channel); } } public close() { console.log('Cleaning up event hubs'); this.hubsInUse .filter(hub => hub.isconnected()) .map(hub => hub.disconnect()); this.hubsInUse = []; } public async useUser(name: string) { this.user = await this.client.getUserContext(name, true); await this.client.setUserContext(this.user); } public async useChannel(name: string) { this.channel = this.channels.find(ch => ch.name === name); await this.channel.initialize(); return this.channel; } public async invoke( fcn: string, chaincodeId: string, config: any = {}, ...args: any[] ) { const user = config.user || this.config.user; const useAdmin = user === true; if (!useAdmin) { await this.useUser(user); } const extra: Partial<Client.ChaincodeInvokeRequest> = config.invokeArgs || {}; if (config.transient) { extra.transientMap = Object.keys(config.transient).reduce((map, k) => ({ ...map, [k]: Buffer.from(typeof config.transient[k] === 'string' ? config.transient[k] : JSON.stringify(config.transient[k])) }), {}); } const { proposalResponse } = await this.sendTransactionProposal({ fcn, chaincodeId, args, ...extra }, useAdmin); return await this.processProposal(proposalResponse); } public async query( fcn: string, chaincodeId: string, config: any = {}, ...args: any[] ) { const user = config.user || this.config.user; const useAdmin = user === true; if (!useAdmin) { await this.useUser(user as string); } const txResult = await this.sendQueryTx({ fcn, chaincodeId, args }, useAdmin); const result = JSON.parse(txResult.result.response.payload.toString('utf8')); return { ...txResult, result }; } public async processProposal( proposalResponse: { proposal: Client.Proposal, proposalResponses: Client.ProposalResponse[], txId: Client.TransactionId } ): Promise<TxResult> { const txRequest = this.channel.sendTransaction(proposalResponse); const txListener = this.listenTx(proposalResponse.txId.getTransactionID()); const txResult = await this.processTx(txRequest, txListener); let result: any = proposalResponse.proposalResponses[0].response.payload; try { result = JSON.parse(result); } catch (err) { // This error is expected and harmless } return { ...txResult, result }; } public async listenTx(txId: string): Promise<TxListenerResult> { let hub = this.channel.getChannelEventHubsForOrg()[0]; hub.checkConnection(true); this.hubsInUse.push(hub); return await new Promise<{ txId: string, code: string }>((res, rej) => { const timeout = setTimeout(() => { hub.unregisterTxEvent(txId); hub = undefined; const seconds = this.config.txTimeout / 1000; rej(new Error(`We could not hear back from orderer within ${seconds} seconds, `+ `closing connection. Increase the txTimeout if more time is needed`)); }, this.config.txTimeout); hub.registerTxEvent(txId, (tx, code) => { clearTimeout(timeout); hub.unregisterTxEvent(txId); hub = undefined; if (code !== 'VALID') { return rej(new Error(`Problem with the transaction. Event status ${code}`)); } res({ txId, code }); }); }); } public async sendInstantiateProposal(request: Partial<Client.ChaincodeInstantiateUpgradeRequest>) { const txId = this.client.newTransactionID(true); request.args = request.args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg.toString()); const [proposalResponses, proposal] = await this.channel.sendInstantiateProposal( { ...request, txId } as Client.ChaincodeInstantiateUpgradeRequest, this.config.txTimeout ); if (!proposalResponses.every((pr: Client.ProposalResponse) => pr.response && pr.response.status === 200)) { const err = new Error('Transaction proposal was bad'); err['responses'] = proposalResponses; throw err; } return { result: proposalResponses[0] as Client.ProposalResponse, proposalResponse: { txId, proposal, proposalResponses: proposalResponses as Client.ProposalResponse[] } }; } public async sendUpgradeProposal(request: Partial<Client.ChaincodeInstantiateUpgradeRequest>) { const txId = this.client.newTransactionID(true); request.args = request.args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg.toString()); const [proposalResponses, proposal] = await await this.channel.sendUpgradeProposal( { ...request, txId } as Client.ChaincodeInstantiateUpgradeRequest, this.config.txTimeout ); if (!proposalResponses.every((pr: Client.ProposalResponse) => pr.response && pr.response.status === 200)) { const err = new Error('Transaction proposal was bad'); err['responses'] = proposalResponses; throw err; } return { result: proposalResponses[0] as Client.ProposalResponse, proposalResponse: { txId, proposal, proposalResponses: proposalResponses as Client.ProposalResponse[] } }; } public async sendTransactionProposal(request: Partial<Client.ChaincodeInvokeRequest>, useAdmin = false) { const txId = this.client.newTransactionID(useAdmin); request.args = (request.args || []).map(arg => { if (!arg) { // tslint:disable-next-line:max-line-length throw new Error('Undefined parameters received as part of the transaction, check how the function is being called'); } return typeof arg === 'object' ? JSON.stringify(arg) : arg.toString(); }); const [proposalResponses, proposal] = await this.channel.sendTransactionProposal( { ...request, txId } as Client.ChaincodeInvokeRequest, this.config.txTimeout ); if (!proposalResponses.every((pr: Client.ProposalResponse) => pr.response && pr.response.status === 200)) { const err = new Error('Transaction proposal was bad'); err['responses'] = proposalResponses; throw err; } return { result: proposalResponses[0] as Client.ProposalResponse, proposalResponse: { txId, proposal, proposalResponses: proposalResponses as Client.ProposalResponse[] } }; } public async sendQueryTx(request: Partial<Client.ChaincodeInvokeRequest>, useAdmin = false) { const txId = this.client.newTransactionID(useAdmin); request.args = (request.args || []).map(arg => { if (!arg) { // tslint:disable-next-line:max-line-length throw new Error('Undefined parameters received as part of the transaction, check how the function is being called'); } return typeof arg === 'object' ? JSON.stringify(arg) : arg.toString(); }); const queryPeers = this.channel.getPeers() .filter(peer => peer.isInRole('chaincodeQuery')) .map(peer => peer.getPeer()); // let proposalResponses: Client.ProposalResponse; // let proposal: Client.Proposal; const [proposalResponses, proposal] = await this.channel.sendTransactionProposal( { ...request, txId, targets: queryPeers } as Client.ChaincodeInvokeRequest, this.config.txTimeout ); const successResponse = proposalResponses .find((pr: Client.ProposalResponse) => pr.response && pr.response.status === 200); if (!successResponse) { const err = new Error('All query responses were bad'); err['responses'] = proposalResponses; throw err; } return { result: successResponse as Client.ProposalResponse, proposalResponse: { txId, proposal, proposalResponses: proposalResponses as Client.ProposalResponse[] } }; } public async processTx( txRequest: Promise<Client.BroadcastResponse>, txListener: Promise<TxListenerResult> ): Promise<TxResult> { const [tx, response] = await Promise.all([txRequest, txListener]); if (!tx || tx.status !== 'SUCCESS' || !response || response.code !== 'VALID') { const err = new Error(`Transaction failed. Status ${tx.status}. Response ${response.code}`); Object.assign(err, { tx, response }); throw err; } return { ...tx, ...response } as TxResult; } private async readSingleFileInDir(dirPath: string) { try { await ensureDir(dirPath); } catch (e) { throw new Error(`The directory ${dirPath} is not reachable or not a directory`); } const content = await readdir(dirPath); if (content.length !== 1) { throw new Error( `The directory ${dirPath} is supposed to only have one file, but found ${content.length}` ); } return await readFile(join(dirPath, content[0]), 'utf8'); } private async getLonelyFile(folderPath: string): Promise<string> { folderPath = resolve(folderPath); const isFile = await ensureFile(folderPath) .then(() => Promise.resolve(true)) .catch(() => Promise.resolve(false)); const isDir = await ensureDir(folderPath) .then(() => Promise.resolve(true)) .catch(() => Promise.resolve(false)); if (isFile) { return folderPath; } if (!isDir) { throw new Error(`Path '${folderPath}' neither a file or a directory`); } const content = await readdir(folderPath); if (content.length !== 1) { throw new Error(`Directory '${folderPath}' must contain only one file, but contains ${content.length}`); } return join(folderPath, content[0]); } private renderVariables(data: string = '') { return data.replace(/(\$[a-z_0-9]+)/ig, variable => process.env[variable.slice(1)] || variable); } }
the_stack
"use strict"; // uuid: 9beb242e-6cc6-4be9-8728-7bd56787152d // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ /** @module internal | This module is to be read only by developers */ /** * ## Description * * This module isolates all the property interpolations, * allowing to break down the complexity and perform unit tests. */ namespace ABeamer { /** Var used only for internal testing via exact framework */ export let _TEST_DIGIT_LIMIT: int = 1000; // ------------------------------------------------------------------------ // Tools // ------------------------------------------------------------------------ function _bypassModeToBool(isFirst: boolean, isLast: boolean, mode: BypassMode): boolean { switch (mode || BP_FIRST_INSIDE) { case BP_FIRST_INSIDE: return !isLast; case BP_ALL: return true; case BP_INSIDE: return !isLast && !isFirst; } } // ------------------------------------------------------------------------ // Property Types // ------------------------------------------------------------------------ export const PT_BOOLEAN = 0; export const PT_NUMBER = 1; export const PT_PIXEL = 2; export const PT_STR = 3; export const PT_VALUE_TEXT_LIST = 4; export const PT_VALUE_TEXT_FUNC = 5; export const PT_VALUE_TEXT_EXPR = 6; /** Pre-compiled RegEx to determine if the string is a pixel. */ const pxRegExp = /^-?[\d\.]+(?:px)?$/; // ------------------------------------------------------------------------ // _parseRelativeValue // ------------------------------------------------------------------------ /** * Parses user defined `value`. * The `value` is similar to the `startValue` except also * supports relative values to the `startValue`. */ function _parseParseValueHandler( value: PropValueHandler, curValue: number, args: ABeamerArgs): AnimPropValue { value = _parseStartValueHandler(value, args); if (typeof value === 'string') { if (value[0] === '+') { return curValue + parseFloat(value.substr(1)); } else if (value[0] === '-') { return curValue - parseFloat(value.substr(1)); } else { const resValue = parseFloat(value); if (isNaN(resValue)) { throwI8n(Msgs.ValueTypeError, { p: value }); } return value; } } else { return value as AnimPropValue; } } // ------------------------------------------------------------------------ // _parseStartPropValue // ------------------------------------------------------------------------ /** * Parses user defined `value` and `startValue`. * If it's a expression, it computes this expression, * and if it's a function it computes the function. */ function _parseStartValueHandler(value: PropValueStartHandler, args: ABeamerArgs): PropValueHandler { return parseHandler<PropValueStartHandler, PropValueHandler>(value, undefined, undefined, args); } // ------------------------------------------------------------------------ // PropInterpolator // ------------------------------------------------------------------------ export class _PropInterpolator extends _WorkAnimationProp { protected numStartValue?: ActionNumValue; protected numEndValue?: ActionNumValue; protected curNumValue?: number; protected curStrValue?: string; protected actRg?: _ActionRg; attachSelector(elementAdpt: _ElementAdapter, elActRg: _ElActionRg, _isVerbose: boolean, args: ABeamerArgs): void { const self = this; const realPropName = this.realPropName; const actRg = elActRg.actionRg; function getStartValue(): PropValue { // user valueStart has priority const valueStart = self.animProp.valueStart; if (valueStart !== undefined) { return _parseStartValueHandler(valueStart, args) as ActionValue; } // then comes linking with previous actRg if (elActRg.linkIndex !== -1) { return elActRg.actionRgList[elActRg.linkIndex].endValue; } else { return elementAdpt.getProp(realPropName, args); } } let startValue = getStartValue(); if (startValue === 'auto') { startValue = ''; } const strStartValue = startValue as string; let numStartValue = 0; let propType = PT_NUMBER; // computes PROP_TYPE based on startValue const valueText = this.animProp.valueText; if (valueText) { switch (typeof valueText) { case 'string': if (!isExpr(valueText as string)) { throwErr('Invalid valueText'); } propType = PT_VALUE_TEXT_EXPR; break; case 'function': propType = PT_VALUE_TEXT_FUNC; break; case 'object': propType = PT_VALUE_TEXT_LIST; if (!valueText.length) { throwErr('Invalid valueText'); } break; default: throwErr('Invalid valueText'); } numStartValue = isDigit(strStartValue) ? parseFloat(strStartValue) : 0; } else { switch (typeof startValue) { case 'undefined': break; case 'boolean': propType = PT_BOOLEAN; numStartValue = startValue === true ? 1 : 0; break; case 'number': numStartValue = startValue as number; // if this property was animated previously and is pixel, // the start value will be numerical not `%dpx`. if (actRg.propType === PT_PIXEL) { propType = PT_PIXEL; } break; case 'string': if (strStartValue === 'true' || strStartValue === 'false') { propType = PT_BOOLEAN; numStartValue = strStartValue === 'true' ? 1 : 0; } else if (strStartValue.search(pxRegExp) === 0) { // string value is a pure value or a pixel if (strStartValue.endsWith('px')) { propType = PT_PIXEL; numStartValue = parseFloat(strStartValue.substr(0, strStartValue.length - 2)); } else { propType = PT_NUMBER; numStartValue = parseFloat(strStartValue); } } else { propType = PT_STR; numStartValue = isDigit(strStartValue) ? parseFloat(strStartValue) : 0; } } } const endValue = this.animProp.value; let numEndValue: number; // computes EndValue based on value switch (propType) { case PT_BOOLEAN: numEndValue = endValue as int > 0.5 ? 1 : 0; break; default: numEndValue = endValue !== undefined ? _parseParseValueHandler(endValue, numStartValue, args) as number : 1; } this.propType = propType; this.numStartValue = numStartValue; this.numEndValue = numEndValue; this.variation = this.numEndValue - this.numStartValue; this.actRg = actRg; actRg.initialValue = numStartValue; actRg.waitFor = this.waitFor; actRg.propType = this.propType; } interpolate(t: int, story: _StoryImpl, isVerbose: boolean): ActionValue { const args = story._args; _vars.v0 = this.numStartValue; _vars.v1 = this.numEndValue; _vars.vd = this.variation; // processes easing const tAfterEasing: ActionValue = this.easing ? this.easing.func(t, this.easing.params, args) : t; _vars.vot = tAfterEasing; // processes oscillator const tAfterOscillator: ActionValue = this.oscillator ? this.oscillator.func(tAfterEasing, this.oscillator.params, args) : tAfterEasing; // #debug-start if (isVerbose && this.oscillator) { story.logFrmt('oscillator', [ ['selector', typeof this.oscillator.handler === 'string' ? this.oscillator.handler : ''], ['input', tAfterEasing], ['output', tAfterOscillator as number], ]); } // #debug-end // processes `variation` and `startValue` let v = tAfterOscillator * this.variation + this.numStartValue; this.curNumValue = v; // processes `path` let values: number[]; let dimCount = 1; if (this.path) { _vars.vpt = v; values = this.path.func(v, this.path.params, FS_RUN, args); dimCount = values.length; // #debug-start if (isVerbose) { story.logFrmt('path', [ ['selector', typeof this.path.handler === 'string' ? this.path.handler : ''], ['input', v], ['output', values.toString()], ]); } // #debug-end if (dimCount === 1) { v = values[0]; } } let value: string | number = v; const valueFormat = this.animProp.valueFormat; const propType = this.propType; if (dimCount === 1) { value = this.roundFunc ? this.roundFunc(value) : value; switch (propType) { case PT_BOOLEAN: value = value > 0.5 ? 1 : 0; break; case PT_PIXEL: value = (this.roundFunc ? v : Math.round(v)).toString() + 'px'; break; case PT_VALUE_TEXT_EXPR: _vars.t = value; value = calcExpr(this.animProp.valueText as string, args).toString(); break; case PT_VALUE_TEXT_LIST: const list = this.animProp.valueText as string[]; const len = list.length; const listIndex = Math.floor(len * Math.min(Math.max(0, value), 0.999)); value = list[listIndex]; break; case PT_VALUE_TEXT_FUNC: value = this.roundFunc ? this.roundFunc(value) : value; value = (this.animProp.valueText as ValueTextFunc)(v, args); break; } // #debug-start if (isVerbose && typeof value === 'number') { value = Math.round(value as number * _TEST_DIGIT_LIMIT) / _TEST_DIGIT_LIMIT; } // #debug-end value = valueFormat ? sprintf(valueFormat, value) : value; } else { // multi-dimension paths values = _applyRoundFunc(values, this.roundFunc); value = valueFormat ? sprintf(valueFormat, ...values) : values.toString(); } // console.log(t, v, this.variation, value); return value; } toAction(v: ActionValue, isFirst: boolean, isLast: boolean): _Action { return { realPropName: this.realPropName, value: v, actRg: this.actRg, numValue: this.curNumValue, toBypassForward: _bypassModeToBool(isFirst, isLast, this.bypassForwardMode), toBypassBackward: _bypassModeToBool(isLast, isFirst, this.bypassBackwardMode), } as _Action; } } export function _applyAction(action: _Action, elAdapter: _ElementAdapter, isVerbose: boolean, args: ABeamerArgs, simulateOnly: boolean = false): ActionNumValue { const actRg = action.actRg; const value = action.value; const propName = action.realPropName; // #debug-start function log(name, aValue): void { args.story.logFrmt('action', [ ['id', elAdapter.getId(args)], ['prop', name], ['value', aValue], ]); } // #debug-end function setValue(newValue: PropValue): void { if (simulateOnly) { return; } // let prevValue: PropValue; // // #debug-start // if (isVerbose) { prevValue = elAdapter.getProp(propName, args); } // // #debug-end elAdapter.setProp(propName, newValue, args); // #debug-start if (isVerbose) { const actualNewValue = elAdapter.getProp(propName, args); let isDifferent = newValue !== actualNewValue; if (isDifferent) { // compares numerical values taking into account the numeric precision errors if (isDifferent && actRg.propType === PT_NUMBER) { const actualFloat = Math.round(parseFloat(actualNewValue as string) * _TEST_DIGIT_LIMIT); const newFloat = Math.round((newValue as number) * _TEST_DIGIT_LIMIT); isDifferent = newFloat !== actualFloat; } } if (isDifferent) { args.story.logFrmt('action-update-warn', [ ['id', elAdapter.getId(args)], ['prop', propName], ['expected', newValue + ''], ['actual', actualNewValue + ''], ], LT_WARN); } log(propName, newValue); } // #debug-end } setValue(value); if (actRg.waitFor && actRg.waitFor.length) { for (const waitFor of actRg.waitFor) { args.waitMan.addWaitFunc(_handleWaitFor, { waitFor, elAdapter } as _WorkWaitForParams); } } return action.numValue; } }
the_stack
import * as coreClient from "@azure/core-client"; export type DeliveryRuleConditionUnion = | DeliveryRuleCondition | DeliveryRuleRemoteAddressCondition | DeliveryRuleRequestMethodCondition | DeliveryRuleQueryStringCondition | DeliveryRulePostArgsCondition | DeliveryRuleRequestUriCondition | DeliveryRuleRequestHeaderCondition | DeliveryRuleRequestBodyCondition | DeliveryRuleRequestSchemeCondition | DeliveryRuleUrlPathCondition | DeliveryRuleUrlFileExtensionCondition | DeliveryRuleUrlFileNameCondition | DeliveryRuleHttpVersionCondition | DeliveryRuleCookiesCondition | DeliveryRuleIsDeviceCondition; export type DeliveryRuleActionAutoGeneratedUnion = | DeliveryRuleActionAutoGenerated | UrlRedirectAction | UrlSigningAction | OriginGroupOverrideAction | UrlRewriteAction | DeliveryRuleRequestHeaderAction | DeliveryRuleResponseHeaderAction | DeliveryRuleCacheExpirationAction | DeliveryRuleCacheKeyQueryStringAction; export type CustomDomainHttpsParametersUnion = | CustomDomainHttpsParameters | CdnManagedHttpsParameters | UserManagedHttpsParameters; export type SecurityPolicyParametersUnion = | SecurityPolicyParameters | SecurityPolicyWebApplicationFirewallParameters; export type SecretParametersUnion = | SecretParameters | UrlSigningKeyParameters | ManagedCertificateParameters | CustomerCertificateParameters; /** Result of the request to list profiles. It contains a list of profile objects and a URL link to get the next set of results. */ export interface ProfileListResult { /** * List of CDN profiles within a resource group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Profile[]; /** URL to get the next set of profile objects if there are any. */ nextLink?: string; } /** The pricing tier (defines a CDN provider, feature list and rate) of the CDN profile. */ export interface Sku { /** Name of the pricing tier. */ name?: SkuName; } /** The core properties of ARM resources */ export interface Resource { /** * Resource ID. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Resource name. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * Read only system data * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; } /** Read only system data */ export interface SystemData { /** An identifier for the identity that created the resource */ createdBy?: string; /** The type of identity that created the resource */ createdByType?: IdentityType; /** The timestamp of resource creation (UTC) */ createdAt?: Date; /** An identifier for the identity that last modified the resource */ lastModifiedBy?: string; /** The type of identity that last modified the resource */ lastModifiedByType?: IdentityType; /** The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** Error response indicates CDN service is not able to process the incoming request. The reason is provided in the error message. */ export interface ErrorResponse { /** * Error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * Error message indicating why the operation failed. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Properties required to update a profile. */ export interface ProfileUpdateParameters { /** Profile tags */ tags?: { [propertyName: string]: string }; } /** The URI required to login to the supplemental portal from the Azure portal. */ export interface SsoUri { /** * The URI used to login to the supplemental portal. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ssoUriValue?: string; } /** The result of the GetSupportedOptimizationTypes API */ export interface SupportedOptimizationTypesListResult { /** * Supported optimization types for a profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly supportedOptimizationTypes?: OptimizationType[]; } /** Output of check resource usage API. */ export interface ResourceUsageListResult { /** * List of resource usages. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: ResourceUsage[]; /** URL to get the next set of custom domain objects if there are any. */ nextLink?: string; } /** Output of check resource usage API. */ export interface ResourceUsage { /** * Resource type for which the usage is provided. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceType?: string; /** * Unit of the usage. e.g. Count. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly unit?: string; /** * Actual value of usage on the specified resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly currentValue?: number; /** * Quota of the specified resource type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly limit?: number; } /** Result of the request to list endpoints. It contains a list of endpoint objects and a URL link to get the next set of results. */ export interface EndpointListResult { /** * List of CDN endpoints within a profile * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Endpoint[]; /** URL to get the next set of endpoint objects if there is any. */ nextLink?: string; } /** The main origin of CDN content which is added when creating a CDN endpoint. */ export interface DeepCreatedOrigin { /** Origin name which must be unique within the endpoint. */ name: string; /** The address of the origin. It can be a domain name, IPv4 address, or IPv6 address. This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5. */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** Origin is enabled for load balancing or not. By default, origin is always enabled. */ enabled?: boolean; /** The Alias of the Private Link resource. Populating this optional field indicates that this origin is 'Private' */ privateLinkAlias?: string; /** The Resource Id of the Private Link resource. Populating this optional field indicates that this backend is 'Private' */ privateLinkResourceId?: string; /** The location of the Private Link resource. Required only if 'privateLinkResourceId' is populated */ privateLinkLocation?: string; /** A custom message to be included in the approval request to connect to the Private Link. */ privateLinkApprovalMessage?: string; } /** The origin group for CDN content which is added when creating a CDN endpoint. Traffic is sent to the origins within the origin group based on origin health. */ export interface DeepCreatedOriginGroup { /** Origin group name which must be unique within the endpoint. */ name: string; /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** The source of the content being delivered via CDN within given origin group. */ origins?: ResourceReference[]; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses.This property is currently not supported. */ responseBasedOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; } /** The JSON object that contains the properties to send health probes to origin. */ export interface HealthProbeParameters { /** The path relative to the origin that is used to determine the health of the origin. */ probePath?: string; /** The type of health probe request that is made. */ probeRequestType?: HealthProbeRequestType; /** Protocol to use for health probe. */ probeProtocol?: ProbeProtocol; /** The number of seconds between health probes.Default is 240sec. */ probeIntervalInSeconds?: number; } /** Reference to another resource. */ export interface ResourceReference { /** Resource ID. */ id?: string; } /** The JSON object that contains the properties to determine origin health using real requests/responses. */ export interface ResponseBasedOriginErrorDetectionParameters { /** Type of response errors for real user requests for which origin will be deemed unhealthy */ responseBasedDetectedErrorTypes?: ResponseBasedDetectedErrorTypes; /** The percentage of failed requests in the sample where failover should trigger. */ responseBasedFailoverThresholdPercentage?: number; /** The list of Http status code ranges that are considered as server errors for origin and it is marked as unhealthy. */ httpErrorRanges?: HttpErrorRangeParameters[]; } /** The JSON object that represents the range for http status codes */ export interface HttpErrorRangeParameters { /** The inclusive start of the http status code range. */ begin?: number; /** The inclusive end of the http status code range. */ end?: number; } /** The JSON object containing endpoint update parameters. */ export interface EndpointPropertiesUpdateParameters { /** A directory path on the origin that CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** List of content types on which compression applies. The value should be a valid MIME type. */ contentTypesToCompress?: string[]; /** The host header value sent to the origin with each request. This property at Endpoint is only allowed when endpoint uses single origin and can be overridden by the same property specified at origin.If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. */ originHostHeader?: string; /** Indicates whether content compression is enabled on CDN. Default value is false. If compression is enabled, content will be served as compressed if user requests for a compressed version. Content won't be compressed on CDN when requested content is smaller than 1 byte or larger than 1 MB. */ isCompressionEnabled?: boolean; /** Indicates whether HTTP traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpAllowed?: boolean; /** Indicates whether HTTPS traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpsAllowed?: boolean; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: QueryStringCachingBehavior; /** Specifies what scenario the customer wants this CDN endpoint to optimize for, e.g. Download, Media services. With this information, CDN can apply scenario driven optimization. */ optimizationType?: OptimizationType; /** Path to a file hosted on the origin which helps accelerate delivery of the dynamic content and calculate the most optimal routes for the CDN. This is relative to the origin path. This property is only relevant when using a single origin. */ probePath?: string; /** List of rules defining the user's geo access within a CDN endpoint. Each geo filter defines an access rule to a specified path or content, e.g. block APAC for path /pictures/ */ geoFilters?: GeoFilter[]; /** A reference to the origin group. */ defaultOriginGroup?: ResourceReference; /** List of keys used to validate the signed URL hashes. */ urlSigningKeys?: UrlSigningKey[]; /** A policy that specifies the delivery rules to be used for an endpoint. */ deliveryPolicy?: EndpointPropertiesUpdateParametersDeliveryPolicy; /** Defines the Web Application Firewall policy for the endpoint (if applicable) */ webApplicationFirewallPolicyLink?: EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink; } /** Rules defining user's geo access within a CDN endpoint. */ export interface GeoFilter { /** Relative path applicable to geo filter. (e.g. '/mypictures', '/mypicture/kitty.jpg', and etc.) */ relativePath: string; /** Action of the geo filter, i.e. allow or block access. */ action: GeoFilterActions; /** Two letter country codes defining user country access in a geo filter, e.g. AU, MX, US. */ countryCodes: string[]; } /** Url signing key */ export interface UrlSigningKey { /** Defines the customer defined key Id. This id will exist in the incoming request to indicate the key used to form the hash. */ keyId: string; /** Defines the parameters for using customer key vault for Url Signing Key. */ keySourceParameters: KeyVaultSigningKeyParameters; } /** Describes the parameters for using a user's KeyVault for URL Signing Key. */ export interface KeyVaultSigningKeyParameters { odataType: "#Microsoft.Azure.Cdn.Models.KeyVaultSigningKeyParameters"; /** Subscription Id of the user's Key Vault containing the secret */ subscriptionId: string; /** Resource group of the user's Key Vault containing the secret */ resourceGroupName: string; /** The name of the user's Key Vault containing the secret */ vaultName: string; /** The name of secret in Key Vault. */ secretName: string; /** The version(GUID) of secret in Key Vault. */ secretVersion: string; } /** A policy that specifies the delivery rules to be used for an endpoint. */ export interface EndpointPropertiesUpdateParametersDeliveryPolicy { /** User-friendly description of the policy. */ description?: string; /** A list of the delivery rules. */ rules: DeliveryRule[]; } /** A rule that specifies a set of actions and conditions */ export interface DeliveryRule { /** Name of the rule */ name?: string; /** The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule. It does not require any condition and actions listed in it will always be applied. */ order: number; /** A list of conditions that must be matched for the actions to be executed */ conditions?: DeliveryRuleConditionUnion[]; /** A list of actions that are executed when all the conditions of a rule are satisfied. */ actions: DeliveryRuleActionAutoGeneratedUnion[]; } /** A condition for the delivery rule. */ export interface DeliveryRuleCondition { /** Polymorphic discriminator, which specifies the different types this object can be */ name: | "RemoteAddress" | "RequestMethod" | "QueryString" | "PostArgs" | "RequestUri" | "RequestHeader" | "RequestBody" | "RequestScheme" | "UrlPath" | "UrlFileExtension" | "UrlFileName" | "HttpVersion" | "Cookies" | "IsDevice"; } /** An action for the delivery rule. */ export interface DeliveryRuleActionAutoGenerated { /** Polymorphic discriminator, which specifies the different types this object can be */ name: | "UrlRedirect" | "UrlSigning" | "OriginGroupOverride" | "UrlRewrite" | "ModifyRequestHeader" | "ModifyResponseHeader" | "CacheExpiration" | "CacheKeyQueryString"; } /** Defines the Web Application Firewall policy for the endpoint (if applicable) */ export interface EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink { /** Resource ID. */ id?: string; } /** Properties required to create or update an endpoint. */ export interface EndpointUpdateParameters { /** Endpoint tags. */ tags?: { [propertyName: string]: string }; /** A directory path on the origin that CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** List of content types on which compression applies. The value should be a valid MIME type. */ contentTypesToCompress?: string[]; /** The host header value sent to the origin with each request. This property at Endpoint is only allowed when endpoint uses single origin and can be overridden by the same property specified at origin.If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. */ originHostHeader?: string; /** Indicates whether content compression is enabled on CDN. Default value is false. If compression is enabled, content will be served as compressed if user requests for a compressed version. Content won't be compressed on CDN when requested content is smaller than 1 byte or larger than 1 MB. */ isCompressionEnabled?: boolean; /** Indicates whether HTTP traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpAllowed?: boolean; /** Indicates whether HTTPS traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpsAllowed?: boolean; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: QueryStringCachingBehavior; /** Specifies what scenario the customer wants this CDN endpoint to optimize for, e.g. Download, Media services. With this information, CDN can apply scenario driven optimization. */ optimizationType?: OptimizationType; /** Path to a file hosted on the origin which helps accelerate delivery of the dynamic content and calculate the most optimal routes for the CDN. This is relative to the origin path. This property is only relevant when using a single origin. */ probePath?: string; /** List of rules defining the user's geo access within a CDN endpoint. Each geo filter defines an access rule to a specified path or content, e.g. block APAC for path /pictures/ */ geoFilters?: GeoFilter[]; /** A reference to the origin group. */ defaultOriginGroup?: ResourceReference; /** List of keys used to validate the signed URL hashes. */ urlSigningKeys?: UrlSigningKey[]; /** A policy that specifies the delivery rules to be used for an endpoint. */ deliveryPolicy?: EndpointPropertiesUpdateParametersDeliveryPolicy; /** Defines the Web Application Firewall policy for the endpoint (if applicable) */ webApplicationFirewallPolicyLink?: EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink; } /** Parameters required for content purge. */ export interface PurgeParameters { /** The path to the content to be purged. Can describe a file path or a wild card directory. */ contentPaths: string[]; } /** Parameters required for content load. */ export interface LoadParameters { /** The path to the content to be loaded. Path should be a relative file URL of the origin. */ contentPaths: string[]; } /** Input of the custom domain to be validated for DNS mapping. */ export interface ValidateCustomDomainInput { /** The host name of the custom domain. Must be a domain name. */ hostName: string; } /** Output of custom domain validation. */ export interface ValidateCustomDomainOutput { /** * Indicates whether the custom domain is valid or not. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly customDomainValidated?: boolean; /** * The reason why the custom domain is not valid. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly reason?: string; /** * Error message describing why the custom domain is not valid. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Result of the request to list origins. It contains a list of origin objects and a URL link to get the next set of results. */ export interface OriginListResult { /** * List of CDN origins within an endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Origin[]; /** URL to get the next set of origin objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the origin. */ export interface OriginUpdatePropertiesParameters { /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** Origin is enabled for load balancing or not */ enabled?: boolean; /** The Alias of the Private Link resource. Populating this optional field indicates that this origin is 'Private' */ privateLinkAlias?: string; /** The Resource Id of the Private Link resource. Populating this optional field indicates that this backend is 'Private' */ privateLinkResourceId?: string; /** The location of the Private Link resource. Required only if 'privateLinkResourceId' is populated */ privateLinkLocation?: string; /** A custom message to be included in the approval request to connect to the Private Link. */ privateLinkApprovalMessage?: string; } /** Origin properties needed for origin update. */ export interface OriginUpdateParameters { /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** Origin is enabled for load balancing or not */ enabled?: boolean; /** The Alias of the Private Link resource. Populating this optional field indicates that this origin is 'Private' */ privateLinkAlias?: string; /** The Resource Id of the Private Link resource. Populating this optional field indicates that this backend is 'Private' */ privateLinkResourceId?: string; /** The location of the Private Link resource. Required only if 'privateLinkResourceId' is populated */ privateLinkLocation?: string; /** A custom message to be included in the approval request to connect to the Private Link. */ privateLinkApprovalMessage?: string; } /** Result of the request to list origin groups. It contains a list of origin groups objects and a URL link to get the next set of results. */ export interface OriginGroupListResult { /** * List of CDN origin groups within an endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: OriginGroup[]; /** URL to get the next set of origin objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the origin group. */ export interface OriginGroupUpdatePropertiesParameters { /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** The source of the content being delivered via CDN within given origin group. */ origins?: ResourceReference[]; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; } /** Origin group properties needed for origin group creation or update. */ export interface OriginGroupUpdateParameters { /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** The source of the content being delivered via CDN within given origin group. */ origins?: ResourceReference[]; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; } /** Result of the request to list custom domains. It contains a list of custom domain objects and a URL link to get the next set of results. */ export interface CustomDomainListResult { /** * List of CDN CustomDomains within an endpoint. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: CustomDomain[]; /** URL to get the next set of custom domain objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties to secure a custom domain. */ export interface CustomDomainHttpsParameters { /** Polymorphic discriminator, which specifies the different types this object can be */ certificateSource: "Cdn" | "AzureKeyVault"; /** Defines the TLS extension protocol that is used for secure delivery. */ protocolType: ProtocolType; /** TLS protocol version that will be used for Https */ minimumTlsVersion?: MinimumTlsVersion; } /** The customDomain JSON object required for custom domain creation or update. */ export interface CustomDomainParameters { /** The host name of the custom domain. Must be a domain name. */ hostName?: string; } /** Input of CheckNameAvailability API. */ export interface CheckNameAvailabilityInput { /** The resource name to validate. */ name: string; /** The type of the resource whose name is to be validated. */ type: "Microsoft.Cdn/Profiles/Endpoints"; } /** Output of check name availability API. */ export interface CheckNameAvailabilityOutput { /** * Indicates whether the name is available. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nameAvailable?: boolean; /** * The reason why the name is not available. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly reason?: string; /** * The detailed error message describing why the name is not available. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Input of the validate probe API. */ export interface ValidateProbeInput { /** The probe URL to validate. */ probeURL: string; } /** Output of the validate probe API. */ export interface ValidateProbeOutput { /** * Indicates whether the probe URL is accepted or not. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly isValid?: boolean; /** * Specifies the error code when the probe url is not accepted. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly errorCode?: string; /** * The detailed error message describing why the probe URL is not accepted. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; } /** Result of the request to list CDN operations. It contains a list of operations and a URL link to get the next set of results. */ export interface OperationsListResult { /** * List of CDN operations supported by the CDN resource provider. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Operation[]; /** URL to get the next set of operation list results if there are any. */ nextLink?: string; } /** CDN REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** The object that represents the operation. */ display?: OperationDisplay; } /** The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.Cdn * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provider?: string; /** * Resource on which the operation is performed: Profile, endpoint, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resource?: string; /** * Operation type: Read, write, delete, etc. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly operation?: string; } /** Result of the request to list CDN edgenodes. It contains a list of ip address group and a URL link to get the next set of results. */ export interface EdgenodeResult { /** * Edge node of CDN service. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: EdgeNode[]; /** URL to get the next set of edgenode list results if there are any. */ nextLink?: string; } /** CDN Ip address group */ export interface IpAddressGroup { /** The delivery region of the ip address group */ deliveryRegion?: string; /** The list of ip v4 addresses. */ ipv4Addresses?: CidrIpAddress[]; /** The list of ip v6 addresses. */ ipv6Addresses?: CidrIpAddress[]; } /** CIDR Ip address */ export interface CidrIpAddress { /** Ip address itself. */ baseIpAddress?: string; /** The length of the prefix of the ip address. */ prefixLength?: number; } /** The list usages operation response. */ export interface UsagesListResult { /** The list of resource usages. */ value?: Usage[]; /** URL to get the next set of results. */ nextLink?: string; } /** Describes resource usage. */ export interface Usage { /** * Resource identifier. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** An enum describing the unit of measurement. */ unit: UsageUnit; /** The current value of the usage. */ currentValue: number; /** The limit of usage. */ limit: number; /** The name of the type of usage. */ name: UsageName; } /** The usage names. */ export interface UsageName { /** A string describing the resource name. */ value?: string; /** A localized string describing the resource name. */ localizedValue?: string; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */ export interface AfdErrorResponse { /** The error object. */ error?: ErrorResponse; } /** Result of the request to list domains. It contains a list of domain objects and a URL link to get the next set of results. */ export interface AFDDomainListResult { /** * List of AzureFrontDoor domains within a profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: AFDDomain[]; /** URL to get the next set of domain objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties to validate a domain. */ export interface DomainValidationProperties { /** * Challenge used for DNS TXT record or file based validation * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly validationToken?: string; /** * The date time that the token expires * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly expirationDate?: string; } /** The JSON object that contains the properties of the domain to create. */ export interface AFDDomainUpdatePropertiesParameters { /** The configuration specifying how to enable HTTPS for the domain - using AzureFrontDoor managed certificate or user's own certificate. If not specified, enabling ssl uses AzureFrontDoor managed certificate by default. */ tlsSettings?: AFDDomainHttpsParameters; /** Resource reference to the Azure DNS zone */ azureDnsZone?: ResourceReference; } /** The JSON object that contains the properties to secure a domain. */ export interface AFDDomainHttpsParameters { /** Defines the source of the SSL certificate. */ certificateType: AfdCertificateType; /** TLS protocol version that will be used for Https */ minimumTlsVersion?: AfdMinimumTlsVersion; /** Resource reference to the secret. ie. subs/rg/profile/secret */ secret?: ResourceReference; } /** The tracking states for afd resources. */ export interface AFDStateProperties { /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; } /** The domain JSON object required for domain creation or update. */ export interface AFDDomainUpdateParameters { /** The configuration specifying how to enable HTTPS for the domain - using AzureFrontDoor managed certificate or user's own certificate. If not specified, enabling ssl uses AzureFrontDoor managed certificate by default. */ tlsSettings?: AFDDomainHttpsParameters; /** Resource reference to the Azure DNS zone */ azureDnsZone?: ResourceReference; } /** The validation token. */ export interface ValidationToken { /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly token?: string; } /** Result of the request to list endpoints. It contains a list of endpoint objects and a URL link to get the next set of results. */ export interface AFDEndpointListResult { /** * List of AzureFrontDoor endpoints within a profile * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: AFDEndpoint[]; /** URL to get the next set of endpoint objects if there is any. */ nextLink?: string; } /** The JSON object containing endpoint update parameters. */ export interface AFDEndpointPropertiesUpdateParameters { /** Send and receive timeout on forwarding request to the origin. When timeout is reached, the request fails and returns. */ originResponseTimeoutSeconds?: number; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; } /** Properties required to create or update an endpoint. */ export interface AFDEndpointUpdateParameters { /** Endpoint tags. */ tags?: { [propertyName: string]: string }; /** Send and receive timeout on forwarding request to the origin. When timeout is reached, the request fails and returns. */ originResponseTimeoutSeconds?: number; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; } /** Parameters required for content purge. */ export interface AfdPurgeParameters { /** The path to the content to be purged. Can describe a file path or a wild card directory. */ contentPaths: string[]; /** List of domains. */ domains?: string[]; } /** Result of the request to list origin groups. It contains a list of origin groups objects and a URL link to get the next set of results. */ export interface AFDOriginGroupListResult { /** * List of CDN origin groups within an endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: AFDOriginGroup[]; /** URL to get the next set of origin objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the origin group. */ export interface AFDOriginGroupUpdatePropertiesParameters { /** Load balancing settings for a backend pool */ loadBalancingSettings?: LoadBalancingSettingsParameters; /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedAfdOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; /** Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled' */ sessionAffinityState?: EnabledState; } /** Round-Robin load balancing settings for a backend pool */ export interface LoadBalancingSettingsParameters { /** The number of samples to consider for load balancing decisions */ sampleSize?: number; /** The number of samples within the sample period that must succeed */ successfulSamplesRequired?: number; /** The additional latency in milliseconds for probes to fall into the lowest latency bucket */ additionalLatencyInMilliseconds?: number; } /** AFDOrigin group properties needed for origin group creation or update. */ export interface AFDOriginGroupUpdateParameters { /** Load balancing settings for a backend pool */ loadBalancingSettings?: LoadBalancingSettingsParameters; /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedAfdOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; /** Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled' */ sessionAffinityState?: EnabledState; } /** Result of the request to list origins. It contains a list of origin objects and a URL link to get the next set of results. */ export interface AFDOriginListResult { /** * List of CDN origins within an endpoint * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: AFDOrigin[]; /** URL to get the next set of origin objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the origin. */ export interface AFDOriginUpdatePropertiesParameters { /** Resource reference to the Azure origin resource. */ azureOrigin?: ResourceReference; /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** The properties of the private link resource for private origin. */ sharedPrivateLinkResource?: Record<string, unknown>; /** Whether to enable health probes to be made against backends defined under backendPools. Health probes can only be disabled if there is a single enabled backend in single enabled backend pool. */ enabledState?: EnabledState; } /** AFDOrigin properties needed for origin update. */ export interface AFDOriginUpdateParameters { /** Resource reference to the Azure origin resource. */ azureOrigin?: ResourceReference; /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** The properties of the private link resource for private origin. */ sharedPrivateLinkResource?: Record<string, unknown>; /** Whether to enable health probes to be made against backends defined under backendPools. Health probes can only be disabled if there is a single enabled backend in single enabled backend pool. */ enabledState?: EnabledState; } /** Result of the request to list routes. It contains a list of route objects and a URL link to get the next set of results. */ export interface RouteListResult { /** * List of AzureFrontDoor routes within a profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Route[]; /** URL to get the next set of route objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the domain to create. */ export interface RouteUpdatePropertiesParameters { /** Domains referenced by this endpoint. */ customDomains?: ResourceReference[]; /** A reference to the origin group. */ originGroup?: ResourceReference; /** A directory path on the origin that AzureFrontDoor can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** rule sets referenced by this endpoint. */ ruleSets?: ResourceReference[]; /** List of supported protocols for this route. */ supportedProtocols?: AFDEndpointProtocols[]; /** The route patterns of the rule. */ patternsToMatch?: string[]; /** compression settings. */ compressionSettings?: Record<string, unknown>; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: AfdQueryStringCachingBehavior; /** Protocol this rule will use when forwarding traffic to backends. */ forwardingProtocol?: ForwardingProtocol; /** whether this route will be linked to the default endpoint domain. */ linkToDefaultDomain?: LinkToDefaultDomain; /** Whether to automatically redirect HTTP traffic to HTTPS traffic. Note that this is a easy way to set up this rule and it will be the first rule that gets executed. */ httpsRedirect?: HttpsRedirect; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; } /** The domain JSON object required for domain creation or update. */ export interface RouteUpdateParameters { /** Domains referenced by this endpoint. */ customDomains?: ResourceReference[]; /** A reference to the origin group. */ originGroup?: ResourceReference; /** A directory path on the origin that AzureFrontDoor can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** rule sets referenced by this endpoint. */ ruleSets?: ResourceReference[]; /** List of supported protocols for this route. */ supportedProtocols?: AFDEndpointProtocols[]; /** The route patterns of the rule. */ patternsToMatch?: string[]; /** compression settings. */ compressionSettings?: Record<string, unknown>; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: AfdQueryStringCachingBehavior; /** Protocol this rule will use when forwarding traffic to backends. */ forwardingProtocol?: ForwardingProtocol; /** whether this route will be linked to the default endpoint domain. */ linkToDefaultDomain?: LinkToDefaultDomain; /** Whether to automatically redirect HTTP traffic to HTTPS traffic. Note that this is a easy way to set up this rule and it will be the first rule that gets executed. */ httpsRedirect?: HttpsRedirect; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; } /** Result of the request to list rule sets. It contains a list of rule set objects and a URL link to get the next set of results. */ export interface RuleSetListResult { /** * List of AzureFrontDoor rule sets within a profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: RuleSet[]; /** URL to get the next set of rule set objects if there are any. */ nextLink?: string; } /** Result of the request to list rules. It contains a list of rule objects and a URL link to get the next set of results. */ export interface RuleListResult { /** * List of AzureFrontDoor rules within a rule set. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Rule[]; /** URL to get the next set of rule objects if there are any. */ nextLink?: string; } /** The JSON object that contains the properties of the domain to create. */ export interface RuleUpdatePropertiesParameters { /** The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule. It does not require any condition and actions listed in it will always be applied. */ order?: number; /** A list of conditions that must be matched for the actions to be executed */ conditions?: DeliveryRuleConditionUnion[]; /** A list of actions that are executed when all the conditions of a rule are satisfied. */ actions?: DeliveryRuleActionAutoGeneratedUnion[]; /** If this rule is a match should the rules engine continue running the remaining rules or stop. If not present, defaults to Continue. */ matchProcessingBehavior?: MatchProcessingBehavior; } /** The domain JSON object required for domain creation or update. */ export interface RuleUpdateParameters { /** The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule. It does not require any condition and actions listed in it will always be applied. */ order?: number; /** A list of conditions that must be matched for the actions to be executed */ conditions?: DeliveryRuleConditionUnion[]; /** A list of actions that are executed when all the conditions of a rule are satisfied. */ actions?: DeliveryRuleActionAutoGeneratedUnion[]; /** If this rule is a match should the rules engine continue running the remaining rules or stop. If not present, defaults to Continue. */ matchProcessingBehavior?: MatchProcessingBehavior; } /** Result of the request to list security policies. It contains a list of security policy objects and a URL link to get the next set of results. */ export interface SecurityPolicyListResult { /** * List of Security policies within a profile * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: SecurityPolicy[]; /** URL to get the next set of security policy objects if there is any. */ nextLink?: string; } /** The json object containing security policy parameters */ export interface SecurityPolicyParameters { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "WebApplicationFirewall"; } /** Result of the request to list secrets. It contains a list of Secret objects and a URL link to get the next set of results. */ export interface SecretListResult { /** * List of AzureFrontDoor secrets within a profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: Secret[]; /** URL to get the next set of Secret objects if there are any. */ nextLink?: string; } /** The json object containing secret parameters */ export interface SecretParameters { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "UrlSigningKey" | "ManagedCertificate" | "CustomerCertificate"; } /** Input of the secret to be validated. */ export interface ValidateSecretInput { /** The secret source. */ secretSource: ResourceReference; /** The secret type. */ secretType: ValidateSecretType; } /** Output of the validated secret. */ export interface ValidateSecretOutput { /** The validation status. */ status?: Status; /** Detailed error message */ message?: string; } /** Metrics Response */ export interface MetricsResponse { dateTimeBegin?: Date; dateTimeEnd?: Date; granularity?: MetricsResponseGranularity; series?: MetricsResponseSeriesItem[]; } export interface MetricsResponseSeriesItem { metric?: string; unit?: MetricsResponseSeriesItemUnit; groups?: MetricsResponseSeriesPropertiesItemsItem[]; data?: Components1Gs0LlpSchemasMetricsresponsePropertiesSeriesItemsPropertiesDataItems[]; } export interface MetricsResponseSeriesPropertiesItemsItem { name?: string; value?: string; } export interface Components1Gs0LlpSchemasMetricsresponsePropertiesSeriesItemsPropertiesDataItems { dateTime?: Date; value?: number; } /** Rankings Response */ export interface RankingsResponse { dateTimeBegin?: Date; dateTimeEnd?: Date; tables?: RankingsResponseTablesItem[]; } export interface RankingsResponseTablesItem { ranking?: string; data?: RankingsResponseTablesPropertiesItemsItem[]; } export interface RankingsResponseTablesPropertiesItemsItem { name?: string; metrics?: RankingsResponseTablesPropertiesItemsMetricsItem[]; } export interface RankingsResponseTablesPropertiesItemsMetricsItem { metric?: string; value?: number; percentage?: number; } /** Continents Response */ export interface ContinentsResponse { continents?: ContinentsResponseContinentsItem[]; countryOrRegions?: ContinentsResponseCountryOrRegionsItem[]; } export interface ContinentsResponseContinentsItem { id?: string; } export interface ContinentsResponseCountryOrRegionsItem { id?: string; continentId?: string; } /** Resources Response */ export interface ResourcesResponse { endpoints?: ResourcesResponseEndpointsItem[]; customDomains?: ResourcesResponseCustomDomainsItem[]; } export interface ResourcesResponseEndpointsItem { id?: string; name?: string; history?: boolean; customDomains?: ResourcesResponseEndpointsPropertiesItemsItem[]; } export interface ResourcesResponseEndpointsPropertiesItemsItem { id?: string; name?: string; endpointId?: string; history?: boolean; } export interface ResourcesResponseCustomDomainsItem { id?: string; name?: string; endpointId?: string; history?: boolean; } /** Waf Metrics Response */ export interface WafMetricsResponse { dateTimeBegin?: Date; dateTimeEnd?: Date; granularity?: WafMetricsResponseGranularity; series?: WafMetricsResponseSeriesItem[]; } export interface WafMetricsResponseSeriesItem { metric?: string; unit?: "count"; groups?: WafMetricsResponseSeriesPropertiesItemsItem[]; data?: Components18OrqelSchemasWafmetricsresponsePropertiesSeriesItemsPropertiesDataItems[]; } export interface WafMetricsResponseSeriesPropertiesItemsItem { name?: string; value?: string; } export interface Components18OrqelSchemasWafmetricsresponsePropertiesSeriesItemsPropertiesDataItems { dateTime?: Date; value?: number; } /** Waf Rankings Response */ export interface WafRankingsResponse { dateTimeBegin?: Date; dateTimeEnd?: Date; groups?: string[]; data?: WafRankingsResponseDataItem[]; } export interface WafRankingsResponseDataItem { groupValues?: string[]; metrics?: ComponentsKpo1PjSchemasWafrankingsresponsePropertiesDataItemsPropertiesMetricsItems[]; } export interface ComponentsKpo1PjSchemasWafrankingsresponsePropertiesDataItemsPropertiesMetricsItems { metric?: string; value?: number; percentage?: number; } /** Defines a list of WebApplicationFirewallPolicies for Azure CDN. It contains a list of WebApplicationFirewallPolicy objects and a URL link to get the next set of results. */ export interface CdnWebApplicationFirewallPolicyList { /** * List of Azure CDN WebApplicationFirewallPolicies within a resource group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: CdnWebApplicationFirewallPolicy[]; /** URL to get the next set of WebApplicationFirewallPolicy objects if there are any. */ nextLink?: string; } /** Defines contents of a web application firewall global configuration */ export interface PolicySettings { /** describes if the policy is in enabled state or disabled state */ enabledState?: PolicyEnabledState; /** Describes if it is in detection mode or prevention mode at policy level. */ mode?: PolicyMode; /** If action type is redirect, this field represents the default redirect URL for the client. */ defaultRedirectUrl?: string; /** If the action type is block, this field defines the default customer overridable http response status code. */ defaultCustomBlockResponseStatusCode?: Enum46; /** If the action type is block, customer can override the response body. The body must be specified in base64 encoding. */ defaultCustomBlockResponseBody?: string; } /** Defines contents of rate limit rules */ export interface RateLimitRuleList { /** List of rules */ rules?: RateLimitRule[]; } /** Defines the common attributes for a custom rule that can be included in a waf policy */ export interface CustomRule { /** Defines the name of the custom rule */ name: string; /** Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not specified. */ enabledState?: CustomRuleEnabledState; /** Defines in what order this rule be evaluated in the overall list of custom rules */ priority: number; /** List of match conditions. */ matchConditions: MatchCondition[]; /** Describes what action to be applied when rule matches */ action: ActionType; } /** Define match conditions */ export interface MatchCondition { /** Match variable to compare against. */ matchVariable: MatchVariable; /** Selector can used to match a specific key for QueryString, Cookies, RequestHeader or PostArgs. */ selector?: string; /** Describes operator to be matched */ operator: Operator; /** Describes if the result of this condition should be negated. */ negateCondition?: boolean; /** List of possible match values. */ matchValue: string[]; /** List of transforms. */ transforms?: TransformType[]; } /** Defines contents of custom rules */ export interface CustomRuleList { /** List of rules */ rules?: CustomRule[]; } /** Defines the list of managed rule sets for the policy. */ export interface ManagedRuleSetList { /** List of rule sets. */ managedRuleSets?: ManagedRuleSet[]; } /** Defines a managed rule set. */ export interface ManagedRuleSet { /** Defines the rule set type to use. */ ruleSetType: string; /** Defines the version of the rule set to use. */ ruleSetVersion: string; /** Verizon only : If the rule set supports anomaly detection mode, this describes the threshold for blocking requests. */ anomalyScore?: number; /** Defines the rule overrides to apply to the rule set. */ ruleGroupOverrides?: ManagedRuleGroupOverride[]; } /** Defines a managed rule group override setting. */ export interface ManagedRuleGroupOverride { /** Describes the managed rule group within the rule set to override */ ruleGroupName: string; /** List of rules that will be disabled. If none specified, all rules in the group will be disabled. */ rules?: ManagedRuleOverride[]; } /** Defines a managed rule group override setting. */ export interface ManagedRuleOverride { /** Identifier for the managed rule. */ ruleId: string; /** Describes if the managed rule is in enabled or disabled state. Defaults to Disabled if not specified. */ enabledState?: ManagedRuleEnabledState; /** Describes the override action to be applied when rule matches. */ action?: ActionType; } /** Defines the ARM Resource ID for the linked endpoints */ export interface CdnEndpoint { /** ARM Resource ID string. */ id?: string; } /** Properties required to update a CdnWebApplicationFirewallPolicy. */ export interface CdnWebApplicationFirewallPolicyPatchParameters { /** CdnWebApplicationFirewallPolicy tags */ tags?: { [propertyName: string]: string }; } /** List of managed rule set definitions available for use in a policy. */ export interface ManagedRuleSetDefinitionList { /** * List of managed rule set definitions. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly value?: ManagedRuleSetDefinition[]; /** URL to retrieve next set of managed rule set definitions. */ nextLink?: string; } /** Describes a managed rule group. */ export interface ManagedRuleGroupDefinition { /** * Name of the managed rule group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ruleGroupName?: string; /** * Description of the managed rule group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; /** * List of rules within the managed rule group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly rules?: ManagedRuleDefinition[]; } /** Describes a managed rule definition. */ export interface ManagedRuleDefinition { /** * Identifier for the managed rule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ruleId?: string; /** * Describes the functionality of the managed rule. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; } /** Defines the parameters for RemoteAddress match conditions */ export interface RemoteAddressMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRemoteAddressConditionParameters"; /** Describes operator to be matched */ operator: RemoteAddressOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** Match values to match against. The operator will apply to each value in here with OR semantics. If any of them match the variable with the given operator this match condition is considered a match. */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for RequestMethod match conditions */ export interface RequestMethodMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestMethodConditionParameters"; /** Describes operator to be matched */ operator: RequestMethodOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: RequestMethodMatchConditionParametersMatchValuesItem[]; } /** Defines the parameters for QueryString match conditions */ export interface QueryStringMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleQueryStringConditionParameters"; /** Describes operator to be matched */ operator: QueryStringOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for PostArgs match conditions */ export interface PostArgsMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRulePostArgsConditionParameters"; /** Name of PostArg to be matched */ selector?: string; /** Describes operator to be matched */ operator: PostArgsOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for RequestUri match conditions */ export interface RequestUriMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestUriConditionParameters"; /** Describes operator to be matched */ operator: RequestUriOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for RequestHeader match conditions */ export interface RequestHeaderMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestHeaderConditionParameters"; /** Name of Header to be matched */ selector?: string; /** Describes operator to be matched */ operator: RequestHeaderOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for RequestBody match conditions */ export interface RequestBodyMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestBodyConditionParameters"; /** Describes operator to be matched */ operator: RequestBodyOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for RequestScheme match conditions */ export interface RequestSchemeMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleRequestSchemeConditionParameters"; /** Describes operator to be matched */ operator: "Equal"; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: RequestSchemeMatchConditionParametersMatchValuesItem[]; } /** Defines the parameters for UrlPath match conditions */ export interface UrlPathMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlPathMatchConditionParameters"; /** Describes operator to be matched */ operator: UrlPathOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for UrlFileExtension match conditions */ export interface UrlFileExtensionMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlFileExtensionMatchConditionParameters"; /** Describes operator to be matched */ operator: UrlFileExtensionOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for UrlFilename match conditions */ export interface UrlFileNameMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlFilenameConditionParameters"; /** Describes operator to be matched */ operator: UrlFileNameOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for HttpVersion match conditions */ export interface HttpVersionMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleHttpVersionConditionParameters"; /** Describes operator to be matched */ operator: HttpVersionOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; } /** Defines the parameters for Cookies match conditions */ export interface CookiesMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleCookiesConditionParameters"; /** Name of Cookies to be matched */ selector?: string; /** Describes operator to be matched */ operator: CookiesOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: string[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for IsDevice match conditions */ export interface IsDeviceMatchConditionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleIsDeviceConditionParameters"; /** Describes operator to be matched */ operator: IsDeviceOperator; /** Describes if this is negate condition or not */ negateCondition?: boolean; /** The match value for the condition of the delivery rule */ matchValues?: IsDeviceMatchConditionParametersMatchValuesItem[]; /** List of transforms */ transforms?: Transform[]; } /** Defines the parameters for the url redirect action. */ export interface UrlRedirectActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlRedirectActionParameters"; /** The redirect type the rule will use when redirecting traffic. */ redirectType: RedirectType; /** Protocol to use for the redirect. The default value is MatchRequest */ destinationProtocol?: DestinationProtocol; /** The full path to redirect. Path cannot be empty and must start with /. Leave empty to use the incoming path as destination path. */ customPath?: string; /** Host to redirect. Leave empty to use the incoming host as the destination host. */ customHostname?: string; /** The set of query strings to be placed in the redirect URL. Setting this value would replace any existing query string; leave empty to preserve the incoming query string. Query string must be in <key>=<value> format. ? and & will be added automatically so do not include them. */ customQueryString?: string; /** Fragment to add to the redirect URL. Fragment is the part of the URL that comes after #. Do not include the #. */ customFragment?: string; } /** Defines the parameters for the Url Signing action. */ export interface UrlSigningActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlSigningActionParameters"; /** Algorithm to use for URL signing */ algorithm?: Algorithm; /** Defines which query string parameters in the url to be considered for expires, key id etc. */ parameterNameOverride?: UrlSigningParamIdentifier[]; } /** Defines how to identify a parameter for a specific purpose e.g. expires */ export interface UrlSigningParamIdentifier { /** Indicates the purpose of the parameter */ paramIndicator: ParamIndicator; /** Parameter name */ paramName: string; } /** Defines the parameters for the origin group override action. */ export interface OriginGroupOverrideActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleOriginGroupOverrideActionParameters"; /** defines the OriginGroup that would override the DefaultOriginGroup. */ originGroup: ResourceReference; } /** Defines the parameters for the url rewrite action. */ export interface UrlRewriteActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleUrlRewriteActionParameters"; /** define a request URI pattern that identifies the type of requests that may be rewritten. If value is blank, all strings are matched. */ sourcePattern: string; /** Define the relative URL to which the above requests will be rewritten by. */ destination: string; /** Whether to preserve unmatched path. Default value is true. */ preserveUnmatchedPath?: boolean; } /** Defines the parameters for the request header action. */ export interface HeaderActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleHeaderActionParameters"; /** Action to perform */ headerAction: HeaderAction; /** Name of the header to modify */ headerName: string; /** Value for the specified action */ value?: string; } /** Defines the parameters for the cache expiration action. */ export interface CacheExpirationActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleCacheExpirationActionParameters"; /** Caching behavior for the requests */ cacheBehavior: CacheBehavior; /** The level at which the content needs to be cached. */ cacheType: CacheType; /** The duration for which the content needs to be cached. Allowed format is [d.]hh:mm:ss */ cacheDuration?: string; } /** Defines the parameters for the cache-key query string action. */ export interface CacheKeyQueryStringActionParameters { odataType: "#Microsoft.Azure.Cdn.Models.DeliveryRuleCacheKeyQueryStringBehaviorActionParameters"; /** Caching behavior for the requests */ queryStringBehavior: QueryStringBehavior; /** query parameters to include or exclude (comma separated). */ queryParameters?: string; } /** Defines the parameters for using CDN managed certificate for securing custom domain. */ export interface CdnCertificateSourceParameters { odataType: "#Microsoft.Azure.Cdn.Models.CdnCertificateSourceParameters"; /** Type of certificate used */ certificateType: CertificateType; } /** Describes the parameters for using a user's KeyVault certificate for securing custom domain. */ export interface KeyVaultCertificateSourceParameters { odataType: "#Microsoft.Azure.Cdn.Models.KeyVaultCertificateSourceParameters"; /** Subscription Id of the user's Key Vault containing the SSL certificate */ subscriptionId: string; /** Resource group of the user's Key Vault containing the SSL certificate */ resourceGroupName: string; /** The name of the user's Key Vault containing the SSL certificate */ vaultName: string; /** The name of Key Vault Secret (representing the full certificate PFX) in Key Vault. */ secretName: string; /** The version(GUID) of Key Vault Secret in Key Vault. */ secretVersion?: string; /** Describes the action that shall be taken when the certificate is updated in Key Vault. */ updateRule: UpdateRule; /** Describes the action that shall be taken when the certificate is removed from Key Vault. */ deleteRule: DeleteRule; } /** Certificate used for https */ export interface Certificate { /** Subject name in the certificate. */ subject?: string; /** Certificate expiration date. */ expirationDate?: string; /** Certificate thumbprint. */ thumbprint?: string; } /** settings for security policy patterns to match */ export interface SecurityPolicyWebApplicationFirewallAssociation { /** List of domains. */ domains?: ResourceReference[]; /** List of paths */ patternsToMatch?: string[]; } /** settings for compression. */ export interface CompressionSettings { /** List of content types on which compression applies. The value should be a valid MIME type. */ contentTypesToCompress?: string[]; /** Indicates whether content compression is enabled on AzureFrontDoor. Default value is false. If compression is enabled, content will be served as compressed if user requests for a compressed version. Content won't be compressed on AzureFrontDoor when requested content is smaller than 1 byte or larger than 1 MB. */ isCompressionEnabled?: boolean; } /** Describes the properties of an existing Shared Private Link Resource to use when connecting to a private origin. */ export interface SharedPrivateLinkResourceProperties { /** The resource id of the resource the shared private link resource is for. */ privateLink?: ResourceReference; /** The location of the shared private link resource */ privateLinkLocation?: string; /** The group id from the provider of resource the shared private link resource is for. */ groupId?: string; /** The request message for requesting approval of the shared private link resource. */ requestMessage?: string; /** Status of the shared private link resource. Can be Pending, Approved, Rejected, Disconnected, or Timeout. */ status?: SharedPrivateLinkResourceStatus; } /** The resource model definition for a ARM tracked top level resource. */ export type TrackedResource = Resource & { /** Resource location. */ location: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** The resource model definition for a ARM proxy resource. It will have everything other than required location and tags */ export type ProxyResource = Resource & {}; /** Describes a managed rule set definition. */ export type ManagedRuleSetDefinition = Resource & { /** The pricing tier (defines a CDN provider, feature list and rate) of the CdnWebApplicationFirewallPolicy. */ sku?: Sku; /** * Provisioning state of the managed rule set. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * Type of the managed rule set. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ruleSetType?: string; /** * Version of the managed rule set type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ruleSetVersion?: string; /** * Rule groups of the managed rule set. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly ruleGroups?: ManagedRuleGroupDefinition[]; }; /** The JSON object that contains the properties required to create an endpoint. */ export type EndpointProperties = EndpointPropertiesUpdateParameters & { /** * The host name of the endpoint structured as {endpointName}.{DNSZone}, e.g. contoso.azureedge.net * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; /** The source of the content being delivered via CDN. */ origins: DeepCreatedOrigin[]; /** The origin groups comprising of origins that are used for load balancing the traffic based on availability. */ originGroups?: DeepCreatedOriginGroup[]; /** * Resource status of the endpoint. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: EndpointResourceState; /** * Provisioning status of the endpoint. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Defines the RemoteAddress condition for the delivery rule. */ export type DeliveryRuleRemoteAddressCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RemoteAddress"; /** Defines the parameters for the condition. */ parameters: RemoteAddressMatchConditionParameters; }; /** Defines the RequestMethod condition for the delivery rule. */ export type DeliveryRuleRequestMethodCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RequestMethod"; /** Defines the parameters for the condition. */ parameters: RequestMethodMatchConditionParameters; }; /** Defines the QueryString condition for the delivery rule. */ export type DeliveryRuleQueryStringCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "QueryString"; /** Defines the parameters for the condition. */ parameters: QueryStringMatchConditionParameters; }; /** Defines the PostArgs condition for the delivery rule. */ export type DeliveryRulePostArgsCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "PostArgs"; /** Defines the parameters for the condition. */ parameters: PostArgsMatchConditionParameters; }; /** Defines the RequestUri condition for the delivery rule. */ export type DeliveryRuleRequestUriCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RequestUri"; /** Defines the parameters for the condition. */ parameters: RequestUriMatchConditionParameters; }; /** Defines the RequestHeader condition for the delivery rule. */ export type DeliveryRuleRequestHeaderCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RequestHeader"; /** Defines the parameters for the condition. */ parameters: RequestHeaderMatchConditionParameters; }; /** Defines the RequestBody condition for the delivery rule. */ export type DeliveryRuleRequestBodyCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RequestBody"; /** Defines the parameters for the condition. */ parameters: RequestBodyMatchConditionParameters; }; /** Defines the RequestScheme condition for the delivery rule. */ export type DeliveryRuleRequestSchemeCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "RequestScheme"; /** Defines the parameters for the condition. */ parameters: RequestSchemeMatchConditionParameters; }; /** Defines the UrlPath condition for the delivery rule. */ export type DeliveryRuleUrlPathCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlPath"; /** Defines the parameters for the condition. */ parameters: UrlPathMatchConditionParameters; }; /** Defines the UrlFileExtension condition for the delivery rule. */ export type DeliveryRuleUrlFileExtensionCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlFileExtension"; /** Defines the parameters for the condition. */ parameters: UrlFileExtensionMatchConditionParameters; }; /** Defines the UrlFileName condition for the delivery rule. */ export type DeliveryRuleUrlFileNameCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlFileName"; /** Defines the parameters for the condition. */ parameters: UrlFileNameMatchConditionParameters; }; /** Defines the HttpVersion condition for the delivery rule. */ export type DeliveryRuleHttpVersionCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "HttpVersion"; /** Defines the parameters for the condition. */ parameters: HttpVersionMatchConditionParameters; }; /** Defines the Cookies condition for the delivery rule. */ export type DeliveryRuleCookiesCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "Cookies"; /** Defines the parameters for the condition. */ parameters: CookiesMatchConditionParameters; }; /** Defines the IsDevice condition for the delivery rule. */ export type DeliveryRuleIsDeviceCondition = DeliveryRuleCondition & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "IsDevice"; /** Defines the parameters for the condition. */ parameters: IsDeviceMatchConditionParameters; }; /** Defines the url redirect action for the delivery rule. */ export type UrlRedirectAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlRedirect"; /** Defines the parameters for the action. */ parameters: UrlRedirectActionParameters; }; /** Defines the url signing action for the delivery rule. */ export type UrlSigningAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlSigning"; /** Defines the parameters for the action. */ parameters: UrlSigningActionParameters; }; /** Defines the origin group override action for the delivery rule. */ export type OriginGroupOverrideAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "OriginGroupOverride"; /** Defines the parameters for the action. */ parameters: OriginGroupOverrideActionParameters; }; /** Defines the url rewrite action for the delivery rule. */ export type UrlRewriteAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "UrlRewrite"; /** Defines the parameters for the action. */ parameters: UrlRewriteActionParameters; }; /** Defines the request header action for the delivery rule. */ export type DeliveryRuleRequestHeaderAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "ModifyRequestHeader"; /** Defines the parameters for the action. */ parameters: HeaderActionParameters; }; /** Defines the response header action for the delivery rule. */ export type DeliveryRuleResponseHeaderAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "ModifyResponseHeader"; /** Defines the parameters for the action. */ parameters: HeaderActionParameters; }; /** Defines the cache expiration action for the delivery rule. */ export type DeliveryRuleCacheExpirationAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "CacheExpiration"; /** Defines the parameters for the action. */ parameters: CacheExpirationActionParameters; }; /** Defines the cache-key query string action for the delivery rule. */ export type DeliveryRuleCacheKeyQueryStringAction = DeliveryRuleActionAutoGenerated & { /** Polymorphic discriminator, which specifies the different types this object can be */ name: "CacheKeyQueryString"; /** Defines the parameters for the action. */ parameters: CacheKeyQueryStringActionParameters; }; /** The JSON object that contains the properties of the origin. */ export type OriginProperties = OriginUpdatePropertiesParameters & { /** * Resource status of the origin. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: OriginResourceState; /** * Provisioning status of the origin. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * The approval status for the connection to the Private Link * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateEndpointStatus?: PrivateEndpointStatus; }; /** The JSON object that contains the properties of the origin group. */ export type OriginGroupProperties = OriginGroupUpdatePropertiesParameters & { /** * Resource status of the origin group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: OriginGroupResourceState; /** * Provisioning status of the origin group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Defines the certificate source parameters using CDN managed certificate for enabling SSL. */ export type CdnManagedHttpsParameters = CustomDomainHttpsParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ certificateSource: "Cdn"; /** Defines the certificate source parameters using CDN managed certificate for enabling SSL. */ certificateSourceParameters: CdnCertificateSourceParameters; }; /** Defines the certificate source parameters using user's keyvault certificate for enabling SSL. */ export type UserManagedHttpsParameters = CustomDomainHttpsParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ certificateSource: "AzureKeyVault"; /** Defines the certificate source parameters using user's keyvault certificate for enabling SSL. */ certificateSourceParameters: KeyVaultCertificateSourceParameters; }; /** The JSON object that contains the properties of the domain to create. */ export type AFDDomainProperties = AFDDomainUpdatePropertiesParameters & AFDStateProperties & { /** * Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by step. DCV stands for DomainControlValidation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly domainValidationState?: DomainValidationState; /** The host name of the domain. Must be a domain name. */ hostName: string; /** * Values the customer needs to validate domain ownership * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly validationProperties?: DomainValidationProperties; }; /** The JSON object that contains the properties required to create an endpoint. */ export type AFDEndpointProperties = AFDEndpointPropertiesUpdateParameters & AFDStateProperties & { /** * The host name of the endpoint structured as {endpointName}.{DNSZone}, e.g. contoso.azureedge.net * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; }; /** The JSON object that contains the properties of the origin group. */ export type AFDOriginGroupProperties = AFDOriginGroupUpdatePropertiesParameters & AFDStateProperties & {}; /** The JSON object that contains the properties of the origin. */ export type AFDOriginProperties = AFDOriginUpdatePropertiesParameters & AFDStateProperties & {}; /** The JSON object that contains the properties of the Routes to create. */ export type RouteProperties = RouteUpdatePropertiesParameters & AFDStateProperties & {}; /** The JSON object that contains the properties of the Rule Set to create. */ export type RuleSetProperties = AFDStateProperties & {}; /** The JSON object that contains the properties of the Rules to create. */ export type RuleProperties = RuleUpdatePropertiesParameters & AFDStateProperties & {}; /** The json object that contains properties required to create a security policy */ export type SecurityPolicyProperties = AFDStateProperties & { /** object which contains security policy parameters */ parameters?: SecurityPolicyParametersUnion; }; /** The JSON object that contains the properties of the Secret to create. */ export type SecretProperties = AFDStateProperties & { /** object which contains secret parameters */ parameters?: SecretParametersUnion; }; /** The json object containing security policy waf parameters */ export type SecurityPolicyWebApplicationFirewallParameters = SecurityPolicyParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "WebApplicationFirewall"; /** Resource ID. */ wafPolicy?: ResourceReference; /** Waf associations */ associations?: SecurityPolicyWebApplicationFirewallAssociation[]; }; /** Url signing key parameters */ export type UrlSigningKeyParameters = SecretParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "UrlSigningKey"; /** Defines the customer defined key Id. This id will exist in the incoming request to indicate the key used to form the hash. */ keyId: string; /** Resource reference to the KV secret */ secretSource: ResourceReference; /** Version of the secret to be used */ secretVersion?: string; }; /** Managed Certificate used for https */ export type ManagedCertificateParameters = SecretParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "ManagedCertificate"; }; /** Customer Certificate used for https */ export type CustomerCertificateParameters = SecretParameters & { /** Polymorphic discriminator, which specifies the different types this object can be */ type: "CustomerCertificate"; /** Resource reference to the KV secret */ secretSource: ResourceReference; /** Version of the secret to be used */ secretVersion?: string; /** Certificate issuing authority. */ certificateAuthority?: string; /** Whether to use the latest version for the certificate */ useLatestVersion?: boolean; /** The list of SANs. */ subjectAlternativeNames?: string[]; }; /** Defines a rate limiting rule that can be included in a waf policy */ export type RateLimitRule = CustomRule & { /** Defines rate limit threshold. */ rateLimitThreshold: number; /** Defines rate limit duration. Default is 1 minute. */ rateLimitDurationInMinutes: number; }; /** Managed Certificate used for https */ export type ManagedCertificate = Certificate & {}; /** Customer Certificate used for https */ export type CustomerCertificate = Certificate & { /** Certificate version. */ version?: string; /** Certificate issuing authority. */ certificateAuthority?: string; /** Complete Url to the certificate */ certificateUrl: string; /** Whether to use the latest version for the certificate */ useLatestVersion?: boolean; /** The list of SANs. */ subjectAlternativeNames?: string[]; }; /** CDN profile is a logical grouping of endpoints that share the same settings, such as CDN provider and pricing tier. */ export type Profile = TrackedResource & { /** The pricing tier (defines a CDN provider, feature list and rate) of the CDN profile. */ sku: Sku; /** * Resource status of the profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: ProfileResourceState; /** * Provisioning status of the profile. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * The Id of the frontdoor. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly frontdoorId?: string; }; /** CDN endpoint is the entity within a CDN profile containing configuration information such as origin, protocol, content caching and delivery behavior. The CDN endpoint uses the URL format <endpointname>.azureedge.net. */ export type Endpoint = TrackedResource & { /** A directory path on the origin that CDN can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** List of content types on which compression applies. The value should be a valid MIME type. */ contentTypesToCompress?: string[]; /** The host header value sent to the origin with each request. This property at Endpoint is only allowed when endpoint uses single origin and can be overridden by the same property specified at origin.If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. */ originHostHeader?: string; /** Indicates whether content compression is enabled on CDN. Default value is false. If compression is enabled, content will be served as compressed if user requests for a compressed version. Content won't be compressed on CDN when requested content is smaller than 1 byte or larger than 1 MB. */ isCompressionEnabled?: boolean; /** Indicates whether HTTP traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpAllowed?: boolean; /** Indicates whether HTTPS traffic is allowed on the endpoint. Default value is true. At least one protocol (HTTP or HTTPS) must be allowed. */ isHttpsAllowed?: boolean; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: QueryStringCachingBehavior; /** Specifies what scenario the customer wants this CDN endpoint to optimize for, e.g. Download, Media services. With this information, CDN can apply scenario driven optimization. */ optimizationType?: OptimizationType; /** Path to a file hosted on the origin which helps accelerate delivery of the dynamic content and calculate the most optimal routes for the CDN. This is relative to the origin path. This property is only relevant when using a single origin. */ probePath?: string; /** List of rules defining the user's geo access within a CDN endpoint. Each geo filter defines an access rule to a specified path or content, e.g. block APAC for path /pictures/ */ geoFilters?: GeoFilter[]; /** A reference to the origin group. */ defaultOriginGroup?: ResourceReference; /** List of keys used to validate the signed URL hashes. */ urlSigningKeys?: UrlSigningKey[]; /** A policy that specifies the delivery rules to be used for an endpoint. */ deliveryPolicy?: EndpointPropertiesUpdateParametersDeliveryPolicy; /** Defines the Web Application Firewall policy for the endpoint (if applicable) */ webApplicationFirewallPolicyLink?: EndpointPropertiesUpdateParametersWebApplicationFirewallPolicyLink; /** * The host name of the endpoint structured as {endpointName}.{DNSZone}, e.g. contoso.azureedge.net * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; /** The source of the content being delivered via CDN. */ origins?: DeepCreatedOrigin[]; /** The origin groups comprising of origins that are used for load balancing the traffic based on availability. */ originGroups?: DeepCreatedOriginGroup[]; /** * Resource status of the endpoint. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: EndpointResourceState; /** * Provisioning status of the endpoint. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** CDN endpoint is the entity within a CDN profile containing configuration information such as origin, protocol, content caching and delivery behavior. The AzureFrontDoor endpoint uses the URL format <endpointname>.azureedge.net. */ export type AFDEndpoint = TrackedResource & { /** Send and receive timeout on forwarding request to the origin. When timeout is reached, the request fails and returns. */ originResponseTimeoutSeconds?: number; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; /** * The host name of the endpoint structured as {endpointName}.{DNSZone}, e.g. contoso.azureedge.net * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly hostName?: string; }; /** Defines web application firewall policy for Azure CDN. */ export type CdnWebApplicationFirewallPolicy = TrackedResource & { /** Gets a unique read-only string that changes whenever the resource is updated. */ etag?: string; /** The pricing tier (defines a CDN provider, feature list and rate) of the CdnWebApplicationFirewallPolicy. */ sku: Sku; /** Describes policySettings for policy */ policySettings?: PolicySettings; /** Describes rate limit rules inside the policy. */ rateLimitRules?: RateLimitRuleList; /** Describes custom rules inside the policy. */ customRules?: CustomRuleList; /** Describes managed rules inside the policy. */ managedRules?: ManagedRuleSetList; /** * Describes Azure CDN endpoints associated with this Web Application Firewall policy. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly endpointLinks?: CdnEndpoint[]; /** * Provisioning state of the WebApplicationFirewallPolicy. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: ProvisioningState; /** * Resource status of the policy. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: PolicyResourceState; }; /** CDN origin is the source of the content being delivered via CDN. When the edge nodes represented by an endpoint do not have the requested content cached, they attempt to fetch it from one or more of the configured origins. */ export type Origin = ProxyResource & { /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** Origin is enabled for load balancing or not */ enabled?: boolean; /** The Alias of the Private Link resource. Populating this optional field indicates that this origin is 'Private' */ privateLinkAlias?: string; /** The Resource Id of the Private Link resource. Populating this optional field indicates that this backend is 'Private' */ privateLinkResourceId?: string; /** The location of the Private Link resource. Required only if 'privateLinkResourceId' is populated */ privateLinkLocation?: string; /** A custom message to be included in the approval request to connect to the Private Link. */ privateLinkApprovalMessage?: string; /** * Resource status of the origin. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: OriginResourceState; /** * Provisioning status of the origin. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; /** * The approval status for the connection to the Private Link * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly privateEndpointStatus?: PrivateEndpointStatus; }; /** Origin group comprising of origins is used for load balancing to origins when the content cannot be served from CDN. */ export type OriginGroup = ProxyResource & { /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** The source of the content being delivered via CDN within given origin group. */ origins?: ResourceReference[]; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; /** * Resource status of the origin group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: OriginGroupResourceState; /** * Provisioning status of the origin group. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Friendly domain name mapping to the endpoint hostname that the customer provides for branding purposes, e.g. www.contoso.com. */ export type CustomDomain = ProxyResource & { /** The host name of the custom domain. Must be a domain name. */ hostName?: string; /** * Resource status of the custom domain. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly resourceState?: CustomDomainResourceState; /** * Provisioning status of Custom Https of the custom domain. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly customHttpsProvisioningState?: CustomHttpsProvisioningState; /** * Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by step. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly customHttpsProvisioningSubstate?: CustomHttpsProvisioningSubstate; /** Certificate parameters for securing custom HTTPS */ customHttpsParameters?: CustomDomainHttpsParametersUnion; /** Special validation or data may be required when delivering CDN to some regions due to local compliance reasons. E.g. ICP license number of a custom domain is required to deliver content in China. */ validationData?: string; /** * Provisioning status of the custom domain. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: string; }; /** Edgenode is a global Point of Presence (POP) location used to deliver CDN content to end users. */ export type EdgeNode = ProxyResource & { /** List of ip address groups. */ ipAddressGroups?: IpAddressGroup[]; }; /** Friendly domain name mapping to the endpoint hostname that the customer provides for branding purposes, e.g. www.contoso.com. */ export type AFDDomain = ProxyResource & { /** The configuration specifying how to enable HTTPS for the domain - using AzureFrontDoor managed certificate or user's own certificate. If not specified, enabling ssl uses AzureFrontDoor managed certificate by default. */ tlsSettings?: AFDDomainHttpsParameters; /** Resource reference to the Azure DNS zone */ azureDnsZone?: ResourceReference; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; /** * Provisioning substate shows the progress of custom HTTPS enabling/disabling process step by step. DCV stands for DomainControlValidation. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly domainValidationState?: DomainValidationState; /** The host name of the domain. Must be a domain name. */ hostName?: string; /** * Values the customer needs to validate domain ownership * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly validationProperties?: DomainValidationProperties; }; /** AFDOrigin group comprising of origins is used for load balancing to origins when the content cannot be served from CDN. */ export type AFDOriginGroup = ProxyResource & { /** Load balancing settings for a backend pool */ loadBalancingSettings?: LoadBalancingSettingsParameters; /** Health probe settings to the origin that is used to determine the health of the origin. */ healthProbeSettings?: HealthProbeParameters; /** Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported. */ trafficRestorationTimeToHealedOrNewEndpointsInMinutes?: number; /** The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported. */ responseBasedAfdOriginErrorDetectionSettings?: ResponseBasedOriginErrorDetectionParameters; /** Whether to allow session affinity on this host. Valid options are 'Enabled' or 'Disabled' */ sessionAffinityState?: EnabledState; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; }; /** CDN origin is the source of the content being delivered via CDN. When the edge nodes represented by an endpoint do not have the requested content cached, they attempt to fetch it from one or more of the configured origins. */ export type AFDOrigin = ProxyResource & { /** Resource reference to the Azure origin resource. */ azureOrigin?: ResourceReference; /** The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint. */ hostName?: string; /** The value of the HTTP port. Must be between 1 and 65535. */ httpPort?: number; /** The value of the HTTPS port. Must be between 1 and 65535. */ httpsPort?: number; /** The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint */ originHostHeader?: string; /** Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5 */ priority?: number; /** Weight of the origin in given origin group for load balancing. Must be between 1 and 1000 */ weight?: number; /** The properties of the private link resource for private origin. */ sharedPrivateLinkResource?: Record<string, unknown>; /** Whether to enable health probes to be made against backends defined under backendPools. Health probes can only be disabled if there is a single enabled backend in single enabled backend pool. */ enabledState?: EnabledState; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; }; /** Friendly Routes name mapping to the any Routes or secret related information. */ export type Route = ProxyResource & { /** Domains referenced by this endpoint. */ customDomains?: ResourceReference[]; /** A reference to the origin group. */ originGroup?: ResourceReference; /** A directory path on the origin that AzureFrontDoor can use to retrieve content from, e.g. contoso.cloudapp.net/originpath. */ originPath?: string; /** rule sets referenced by this endpoint. */ ruleSets?: ResourceReference[]; /** List of supported protocols for this route. */ supportedProtocols?: AFDEndpointProtocols[]; /** The route patterns of the rule. */ patternsToMatch?: string[]; /** compression settings. */ compressionSettings?: Record<string, unknown>; /** Defines how CDN caches requests that include query strings. You can ignore any query strings when caching, bypass caching to prevent requests that contain query strings from being cached, or cache every request with a unique URL. */ queryStringCachingBehavior?: AfdQueryStringCachingBehavior; /** Protocol this rule will use when forwarding traffic to backends. */ forwardingProtocol?: ForwardingProtocol; /** whether this route will be linked to the default endpoint domain. */ linkToDefaultDomain?: LinkToDefaultDomain; /** Whether to automatically redirect HTTP traffic to HTTPS traffic. Note that this is a easy way to set up this rule and it will be the first rule that gets executed. */ httpsRedirect?: HttpsRedirect; /** Whether to enable use of this rule. Permitted values are 'Enabled' or 'Disabled' */ enabledState?: EnabledState; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; }; /** Friendly RuleSet name mapping to the any RuleSet or secret related information. */ export type RuleSet = ProxyResource & { /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; }; /** Friendly Rules name mapping to the any Rules or secret related information. */ export type Rule = ProxyResource & { /** The order in which the rules are applied for the endpoint. Possible values {0,1,2,3,………}. A rule with a lesser order will be applied before a rule with a greater order. Rule with order 0 is a special rule. It does not require any condition and actions listed in it will always be applied. */ order?: number; /** A list of conditions that must be matched for the actions to be executed */ conditions?: DeliveryRuleConditionUnion[]; /** A list of actions that are executed when all the conditions of a rule are satisfied. */ actions?: DeliveryRuleActionAutoGeneratedUnion[]; /** If this rule is a match should the rules engine continue running the remaining rules or stop. If not present, defaults to Continue. */ matchProcessingBehavior?: MatchProcessingBehavior; /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; }; /** SecurityPolicy association for AzureFrontDoor profile */ export type SecurityPolicy = ProxyResource & { /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; /** object which contains security policy parameters */ parameters?: SecurityPolicyParametersUnion; }; /** Friendly Secret name mapping to the any Secret or secret related information. */ export type Secret = ProxyResource & { /** * Provisioning status * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly provisioningState?: AfdProvisioningState; /** NOTE: This property will not be serialized. It can only be populated by the server. */ readonly deploymentStatus?: DeploymentStatus; /** object which contains secret parameters */ parameters?: SecretParametersUnion; }; /** Known values of {@link SkuName} that the service accepts. */ export enum KnownSkuName { StandardVerizon = "Standard_Verizon", PremiumVerizon = "Premium_Verizon", CustomVerizon = "Custom_Verizon", StandardAkamai = "Standard_Akamai", StandardChinaCdn = "Standard_ChinaCdn", StandardMicrosoft = "Standard_Microsoft", PremiumChinaCdn = "Premium_ChinaCdn", StandardAzureFrontDoor = "Standard_AzureFrontDoor", PremiumAzureFrontDoor = "Premium_AzureFrontDoor", Standard955BandWidthChinaCdn = "Standard_955BandWidth_ChinaCdn", StandardAvgBandWidthChinaCdn = "Standard_AvgBandWidth_ChinaCdn", StandardPlusChinaCdn = "StandardPlus_ChinaCdn", StandardPlus955BandWidthChinaCdn = "StandardPlus_955BandWidth_ChinaCdn", StandardPlusAvgBandWidthChinaCdn = "StandardPlus_AvgBandWidth_ChinaCdn" } /** * Defines values for SkuName. \ * {@link KnownSkuName} can be used interchangeably with SkuName, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Standard_Verizon** \ * **Premium_Verizon** \ * **Custom_Verizon** \ * **Standard_Akamai** \ * **Standard_ChinaCdn** \ * **Standard_Microsoft** \ * **Premium_ChinaCdn** \ * **Standard_AzureFrontDoor** \ * **Premium_AzureFrontDoor** \ * **Standard_955BandWidth_ChinaCdn** \ * **Standard_AvgBandWidth_ChinaCdn** \ * **StandardPlus_ChinaCdn** \ * **StandardPlus_955BandWidth_ChinaCdn** \ * **StandardPlus_AvgBandWidth_ChinaCdn** */ export type SkuName = string; /** Known values of {@link ProfileResourceState} that the service accepts. */ export enum KnownProfileResourceState { Creating = "Creating", Active = "Active", Deleting = "Deleting", Disabled = "Disabled" } /** * Defines values for ProfileResourceState. \ * {@link KnownProfileResourceState} can be used interchangeably with ProfileResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Active** \ * **Deleting** \ * **Disabled** */ export type ProfileResourceState = string; /** Known values of {@link IdentityType} that the service accepts. */ export enum KnownIdentityType { User = "user", Application = "application", ManagedIdentity = "managedIdentity", Key = "key" } /** * Defines values for IdentityType. \ * {@link KnownIdentityType} can be used interchangeably with IdentityType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **user** \ * **application** \ * **managedIdentity** \ * **key** */ export type IdentityType = string; /** Known values of {@link OptimizationType} that the service accepts. */ export enum KnownOptimizationType { GeneralWebDelivery = "GeneralWebDelivery", GeneralMediaStreaming = "GeneralMediaStreaming", VideoOnDemandMediaStreaming = "VideoOnDemandMediaStreaming", LargeFileDownload = "LargeFileDownload", DynamicSiteAcceleration = "DynamicSiteAcceleration" } /** * Defines values for OptimizationType. \ * {@link KnownOptimizationType} can be used interchangeably with OptimizationType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **GeneralWebDelivery** \ * **GeneralMediaStreaming** \ * **VideoOnDemandMediaStreaming** \ * **LargeFileDownload** \ * **DynamicSiteAcceleration** */ export type OptimizationType = string; /** Known values of {@link EndpointResourceState} that the service accepts. */ export enum KnownEndpointResourceState { Creating = "Creating", Deleting = "Deleting", Running = "Running", Starting = "Starting", Stopped = "Stopped", Stopping = "Stopping" } /** * Defines values for EndpointResourceState. \ * {@link KnownEndpointResourceState} can be used interchangeably with EndpointResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Deleting** \ * **Running** \ * **Starting** \ * **Stopped** \ * **Stopping** */ export type EndpointResourceState = string; /** Known values of {@link MatchVariable} that the service accepts. */ export enum KnownMatchVariable { RemoteAddress = "RemoteAddress", RequestMethod = "RequestMethod", QueryString = "QueryString", PostArgs = "PostArgs", RequestUri = "RequestUri", RequestHeader = "RequestHeader", RequestBody = "RequestBody", RequestScheme = "RequestScheme", UrlPath = "UrlPath", UrlFileExtension = "UrlFileExtension", UrlFileName = "UrlFileName", HttpVersion = "HttpVersion", Cookies = "Cookies", IsDevice = "IsDevice", RemoteAddr = "RemoteAddr", SocketAddr = "SocketAddr" } /** * Defines values for MatchVariable. \ * {@link KnownMatchVariable} can be used interchangeably with MatchVariable, * this enum contains the known values that the service supports. * ### Known values supported by the service * **RemoteAddress** \ * **RequestMethod** \ * **QueryString** \ * **PostArgs** \ * **RequestUri** \ * **RequestHeader** \ * **RequestBody** \ * **RequestScheme** \ * **UrlPath** \ * **UrlFileExtension** \ * **UrlFileName** \ * **HttpVersion** \ * **Cookies** \ * **IsDevice** \ * **RemoteAddr** \ * **SocketAddr** */ export type MatchVariable = string; /** Known values of {@link DeliveryRuleAction} that the service accepts. */ export enum KnownDeliveryRuleAction { CacheExpiration = "CacheExpiration", CacheKeyQueryString = "CacheKeyQueryString", ModifyRequestHeader = "ModifyRequestHeader", ModifyResponseHeader = "ModifyResponseHeader", UrlRedirect = "UrlRedirect", UrlRewrite = "UrlRewrite", UrlSigning = "UrlSigning", OriginGroupOverride = "OriginGroupOverride" } /** * Defines values for DeliveryRuleAction. \ * {@link KnownDeliveryRuleAction} can be used interchangeably with DeliveryRuleAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **CacheExpiration** \ * **CacheKeyQueryString** \ * **ModifyRequestHeader** \ * **ModifyResponseHeader** \ * **UrlRedirect** \ * **UrlRewrite** \ * **UrlSigning** \ * **OriginGroupOverride** */ export type DeliveryRuleAction = string; /** Known values of {@link OriginResourceState} that the service accepts. */ export enum KnownOriginResourceState { Creating = "Creating", Active = "Active", Deleting = "Deleting" } /** * Defines values for OriginResourceState. \ * {@link KnownOriginResourceState} can be used interchangeably with OriginResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Active** \ * **Deleting** */ export type OriginResourceState = string; /** Known values of {@link PrivateEndpointStatus} that the service accepts. */ export enum KnownPrivateEndpointStatus { Pending = "Pending", Approved = "Approved", Rejected = "Rejected", Disconnected = "Disconnected", Timeout = "Timeout" } /** * Defines values for PrivateEndpointStatus. \ * {@link KnownPrivateEndpointStatus} can be used interchangeably with PrivateEndpointStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Pending** \ * **Approved** \ * **Rejected** \ * **Disconnected** \ * **Timeout** */ export type PrivateEndpointStatus = string; /** Known values of {@link OriginGroupResourceState} that the service accepts. */ export enum KnownOriginGroupResourceState { Creating = "Creating", Active = "Active", Deleting = "Deleting" } /** * Defines values for OriginGroupResourceState. \ * {@link KnownOriginGroupResourceState} can be used interchangeably with OriginGroupResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Active** \ * **Deleting** */ export type OriginGroupResourceState = string; /** Known values of {@link CustomDomainResourceState} that the service accepts. */ export enum KnownCustomDomainResourceState { Creating = "Creating", Active = "Active", Deleting = "Deleting" } /** * Defines values for CustomDomainResourceState. \ * {@link KnownCustomDomainResourceState} can be used interchangeably with CustomDomainResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Active** \ * **Deleting** */ export type CustomDomainResourceState = string; /** Known values of {@link CustomHttpsProvisioningState} that the service accepts. */ export enum KnownCustomHttpsProvisioningState { Enabling = "Enabling", Enabled = "Enabled", Disabling = "Disabling", Disabled = "Disabled", Failed = "Failed" } /** * Defines values for CustomHttpsProvisioningState. \ * {@link KnownCustomHttpsProvisioningState} can be used interchangeably with CustomHttpsProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabling** \ * **Enabled** \ * **Disabling** \ * **Disabled** \ * **Failed** */ export type CustomHttpsProvisioningState = string; /** Known values of {@link CustomHttpsProvisioningSubstate} that the service accepts. */ export enum KnownCustomHttpsProvisioningSubstate { SubmittingDomainControlValidationRequest = "SubmittingDomainControlValidationRequest", PendingDomainControlValidationREquestApproval = "PendingDomainControlValidationREquestApproval", DomainControlValidationRequestApproved = "DomainControlValidationRequestApproved", DomainControlValidationRequestRejected = "DomainControlValidationRequestRejected", DomainControlValidationRequestTimedOut = "DomainControlValidationRequestTimedOut", IssuingCertificate = "IssuingCertificate", DeployingCertificate = "DeployingCertificate", CertificateDeployed = "CertificateDeployed", DeletingCertificate = "DeletingCertificate", CertificateDeleted = "CertificateDeleted" } /** * Defines values for CustomHttpsProvisioningSubstate. \ * {@link KnownCustomHttpsProvisioningSubstate} can be used interchangeably with CustomHttpsProvisioningSubstate, * this enum contains the known values that the service supports. * ### Known values supported by the service * **SubmittingDomainControlValidationRequest** \ * **PendingDomainControlValidationREquestApproval** \ * **DomainControlValidationRequestApproved** \ * **DomainControlValidationRequestRejected** \ * **DomainControlValidationRequestTimedOut** \ * **IssuingCertificate** \ * **DeployingCertificate** \ * **CertificateDeployed** \ * **DeletingCertificate** \ * **CertificateDeleted** */ export type CustomHttpsProvisioningSubstate = string; /** Known values of {@link CertificateSource} that the service accepts. */ export enum KnownCertificateSource { AzureKeyVault = "AzureKeyVault", Cdn = "Cdn" } /** * Defines values for CertificateSource. \ * {@link KnownCertificateSource} can be used interchangeably with CertificateSource, * this enum contains the known values that the service supports. * ### Known values supported by the service * **AzureKeyVault** \ * **Cdn** */ export type CertificateSource = string; /** Known values of {@link ProtocolType} that the service accepts. */ export enum KnownProtocolType { ServerNameIndication = "ServerNameIndication", IPBased = "IPBased" } /** * Defines values for ProtocolType. \ * {@link KnownProtocolType} can be used interchangeably with ProtocolType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **ServerNameIndication** \ * **IPBased** */ export type ProtocolType = string; /** Known values of {@link UsageUnit} that the service accepts. */ export enum KnownUsageUnit { Count = "Count" } /** * Defines values for UsageUnit. \ * {@link KnownUsageUnit} can be used interchangeably with UsageUnit, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Count** */ export type UsageUnit = string; /** Known values of {@link DomainValidationState} that the service accepts. */ export enum KnownDomainValidationState { Unknown = "Unknown", Submitting = "Submitting", Pending = "Pending", TimedOut = "TimedOut", PendingRevalidation = "PendingRevalidation", Approved = "Approved" } /** * Defines values for DomainValidationState. \ * {@link KnownDomainValidationState} can be used interchangeably with DomainValidationState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Unknown** \ * **Submitting** \ * **Pending** \ * **TimedOut** \ * **PendingRevalidation** \ * **Approved** */ export type DomainValidationState = string; /** Known values of {@link AfdCertificateType} that the service accepts. */ export enum KnownAfdCertificateType { CustomerCertificate = "CustomerCertificate", ManagedCertificate = "ManagedCertificate" } /** * Defines values for AfdCertificateType. \ * {@link KnownAfdCertificateType} can be used interchangeably with AfdCertificateType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **CustomerCertificate** \ * **ManagedCertificate** */ export type AfdCertificateType = string; /** Known values of {@link AfdProvisioningState} that the service accepts. */ export enum KnownAfdProvisioningState { Succeeded = "Succeeded", Failed = "Failed", Updating = "Updating", Deleting = "Deleting", Creating = "Creating" } /** * Defines values for AfdProvisioningState. \ * {@link KnownAfdProvisioningState} can be used interchangeably with AfdProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Succeeded** \ * **Failed** \ * **Updating** \ * **Deleting** \ * **Creating** */ export type AfdProvisioningState = string; /** Known values of {@link DeploymentStatus} that the service accepts. */ export enum KnownDeploymentStatus { NotStarted = "NotStarted", InProgress = "InProgress", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for DeploymentStatus. \ * {@link KnownDeploymentStatus} can be used interchangeably with DeploymentStatus, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NotStarted** \ * **InProgress** \ * **Succeeded** \ * **Failed** */ export type DeploymentStatus = string; /** Known values of {@link EnabledState} that the service accepts. */ export enum KnownEnabledState { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for EnabledState. \ * {@link KnownEnabledState} can be used interchangeably with EnabledState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type EnabledState = string; /** Known values of {@link AFDEndpointProtocols} that the service accepts. */ export enum KnownAFDEndpointProtocols { Http = "Http", Https = "Https" } /** * Defines values for AFDEndpointProtocols. \ * {@link KnownAFDEndpointProtocols} can be used interchangeably with AFDEndpointProtocols, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Http** \ * **Https** */ export type AFDEndpointProtocols = string; /** Known values of {@link ForwardingProtocol} that the service accepts. */ export enum KnownForwardingProtocol { HttpOnly = "HttpOnly", HttpsOnly = "HttpsOnly", MatchRequest = "MatchRequest" } /** * Defines values for ForwardingProtocol. \ * {@link KnownForwardingProtocol} can be used interchangeably with ForwardingProtocol, * this enum contains the known values that the service supports. * ### Known values supported by the service * **HttpOnly** \ * **HttpsOnly** \ * **MatchRequest** */ export type ForwardingProtocol = string; /** Known values of {@link LinkToDefaultDomain} that the service accepts. */ export enum KnownLinkToDefaultDomain { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for LinkToDefaultDomain. \ * {@link KnownLinkToDefaultDomain} can be used interchangeably with LinkToDefaultDomain, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type LinkToDefaultDomain = string; /** Known values of {@link HttpsRedirect} that the service accepts. */ export enum KnownHttpsRedirect { Enabled = "Enabled", Disabled = "Disabled" } /** * Defines values for HttpsRedirect. \ * {@link KnownHttpsRedirect} can be used interchangeably with HttpsRedirect, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Enabled** \ * **Disabled** */ export type HttpsRedirect = string; /** Known values of {@link MatchProcessingBehavior} that the service accepts. */ export enum KnownMatchProcessingBehavior { Continue = "Continue", Stop = "Stop" } /** * Defines values for MatchProcessingBehavior. \ * {@link KnownMatchProcessingBehavior} can be used interchangeably with MatchProcessingBehavior, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Continue** \ * **Stop** */ export type MatchProcessingBehavior = string; /** Known values of {@link SecurityPolicyType} that the service accepts. */ export enum KnownSecurityPolicyType { WebApplicationFirewall = "WebApplicationFirewall" } /** * Defines values for SecurityPolicyType. \ * {@link KnownSecurityPolicyType} can be used interchangeably with SecurityPolicyType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **WebApplicationFirewall** */ export type SecurityPolicyType = string; /** Known values of {@link SecretType} that the service accepts. */ export enum KnownSecretType { UrlSigningKey = "UrlSigningKey", CustomerCertificate = "CustomerCertificate", ManagedCertificate = "ManagedCertificate" } /** * Defines values for SecretType. \ * {@link KnownSecretType} can be used interchangeably with SecretType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **UrlSigningKey** \ * **CustomerCertificate** \ * **ManagedCertificate** */ export type SecretType = string; /** Known values of {@link ValidateSecretType} that the service accepts. */ export enum KnownValidateSecretType { UrlSigningKey = "UrlSigningKey", ManagedCertificate = "ManagedCertificate", CustomerCertificate = "CustomerCertificate" } /** * Defines values for ValidateSecretType. \ * {@link KnownValidateSecretType} can be used interchangeably with ValidateSecretType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **UrlSigningKey** \ * **ManagedCertificate** \ * **CustomerCertificate** */ export type ValidateSecretType = string; /** Known values of {@link Status} that the service accepts. */ export enum KnownStatus { Valid = "Valid", Invalid = "Invalid", AccessDenied = "AccessDenied", CertificateExpired = "CertificateExpired" } /** * Defines values for Status. \ * {@link KnownStatus} can be used interchangeably with Status, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Valid** \ * **Invalid** \ * **AccessDenied** \ * **CertificateExpired** */ export type Status = string; /** Known values of {@link LogMetric} that the service accepts. */ export enum KnownLogMetric { ClientRequestCount = "clientRequestCount", ClientRequestTraffic = "clientRequestTraffic", ClientRequestBandwidth = "clientRequestBandwidth", OriginRequestTraffic = "originRequestTraffic", OriginRequestBandwidth = "originRequestBandwidth", TotalLatency = "totalLatency" } /** * Defines values for LogMetric. \ * {@link KnownLogMetric} can be used interchangeably with LogMetric, * this enum contains the known values that the service supports. * ### Known values supported by the service * **clientRequestCount** \ * **clientRequestTraffic** \ * **clientRequestBandwidth** \ * **originRequestTraffic** \ * **originRequestBandwidth** \ * **totalLatency** */ export type LogMetric = string; /** Known values of {@link LogMetricsGranularity} that the service accepts. */ export enum KnownLogMetricsGranularity { PT5M = "PT5M", PT1H = "PT1H", P1D = "P1D" } /** * Defines values for LogMetricsGranularity. \ * {@link KnownLogMetricsGranularity} can be used interchangeably with LogMetricsGranularity, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PT5M** \ * **PT1H** \ * **P1D** */ export type LogMetricsGranularity = string; /** Known values of {@link LogMetricsGroupBy} that the service accepts. */ export enum KnownLogMetricsGroupBy { HttpStatusCode = "httpStatusCode", Protocol = "protocol", CacheStatus = "cacheStatus", Country = "country", CustomDomain = "customDomain" } /** * Defines values for LogMetricsGroupBy. \ * {@link KnownLogMetricsGroupBy} can be used interchangeably with LogMetricsGroupBy, * this enum contains the known values that the service supports. * ### Known values supported by the service * **httpStatusCode** \ * **protocol** \ * **cacheStatus** \ * **country** \ * **customDomain** */ export type LogMetricsGroupBy = string; /** Known values of {@link MetricsResponseGranularity} that the service accepts. */ export enum KnownMetricsResponseGranularity { PT5M = "PT5M", PT1H = "PT1H", P1D = "P1D" } /** * Defines values for MetricsResponseGranularity. \ * {@link KnownMetricsResponseGranularity} can be used interchangeably with MetricsResponseGranularity, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PT5M** \ * **PT1H** \ * **P1D** */ export type MetricsResponseGranularity = string; /** Known values of {@link MetricsResponseSeriesItemUnit} that the service accepts. */ export enum KnownMetricsResponseSeriesItemUnit { Count = "count", Bytes = "bytes", BitsPerSecond = "bitsPerSecond" } /** * Defines values for MetricsResponseSeriesItemUnit. \ * {@link KnownMetricsResponseSeriesItemUnit} can be used interchangeably with MetricsResponseSeriesItemUnit, * this enum contains the known values that the service supports. * ### Known values supported by the service * **count** \ * **bytes** \ * **bitsPerSecond** */ export type MetricsResponseSeriesItemUnit = string; /** Known values of {@link LogRanking} that the service accepts. */ export enum KnownLogRanking { Url = "url", Referrer = "referrer", Browser = "browser", UserAgent = "userAgent", CountryOrRegion = "countryOrRegion" } /** * Defines values for LogRanking. \ * {@link KnownLogRanking} can be used interchangeably with LogRanking, * this enum contains the known values that the service supports. * ### Known values supported by the service * **url** \ * **referrer** \ * **browser** \ * **userAgent** \ * **countryOrRegion** */ export type LogRanking = string; /** Known values of {@link LogRankingMetric} that the service accepts. */ export enum KnownLogRankingMetric { ClientRequestCount = "clientRequestCount", ClientRequestTraffic = "clientRequestTraffic", HitCount = "hitCount", MissCount = "missCount", UserErrorCount = "userErrorCount", ErrorCount = "errorCount" } /** * Defines values for LogRankingMetric. \ * {@link KnownLogRankingMetric} can be used interchangeably with LogRankingMetric, * this enum contains the known values that the service supports. * ### Known values supported by the service * **clientRequestCount** \ * **clientRequestTraffic** \ * **hitCount** \ * **missCount** \ * **userErrorCount** \ * **errorCount** */ export type LogRankingMetric = string; /** Known values of {@link WafMetric} that the service accepts. */ export enum KnownWafMetric { ClientRequestCount = "clientRequestCount" } /** * Defines values for WafMetric. \ * {@link KnownWafMetric} can be used interchangeably with WafMetric, * this enum contains the known values that the service supports. * ### Known values supported by the service * **clientRequestCount** */ export type WafMetric = string; /** Known values of {@link WafGranularity} that the service accepts. */ export enum KnownWafGranularity { PT5M = "PT5M", PT1H = "PT1H", P1D = "P1D" } /** * Defines values for WafGranularity. \ * {@link KnownWafGranularity} can be used interchangeably with WafGranularity, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PT5M** \ * **PT1H** \ * **P1D** */ export type WafGranularity = string; /** Known values of {@link WafAction} that the service accepts. */ export enum KnownWafAction { Allow = "allow", Block = "block", Log = "log", Redirect = "redirect" } /** * Defines values for WafAction. \ * {@link KnownWafAction} can be used interchangeably with WafAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **allow** \ * **block** \ * **log** \ * **redirect** */ export type WafAction = string; /** Known values of {@link WafRankingGroupBy} that the service accepts. */ export enum KnownWafRankingGroupBy { HttpStatusCode = "httpStatusCode", CustomDomain = "customDomain" } /** * Defines values for WafRankingGroupBy. \ * {@link KnownWafRankingGroupBy} can be used interchangeably with WafRankingGroupBy, * this enum contains the known values that the service supports. * ### Known values supported by the service * **httpStatusCode** \ * **customDomain** */ export type WafRankingGroupBy = string; /** Known values of {@link WafRuleType} that the service accepts. */ export enum KnownWafRuleType { Managed = "managed", Custom = "custom", Bot = "bot" } /** * Defines values for WafRuleType. \ * {@link KnownWafRuleType} can be used interchangeably with WafRuleType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **managed** \ * **custom** \ * **bot** */ export type WafRuleType = string; /** Known values of {@link WafMetricsResponseGranularity} that the service accepts. */ export enum KnownWafMetricsResponseGranularity { PT5M = "PT5M", PT1H = "PT1H", P1D = "P1D" } /** * Defines values for WafMetricsResponseGranularity. \ * {@link KnownWafMetricsResponseGranularity} can be used interchangeably with WafMetricsResponseGranularity, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PT5M** \ * **PT1H** \ * **P1D** */ export type WafMetricsResponseGranularity = string; /** Known values of {@link WafRankingType} that the service accepts. */ export enum KnownWafRankingType { Action = "action", RuleGroup = "ruleGroup", RuleId = "ruleId", UserAgent = "userAgent", ClientIp = "clientIp", Url = "url", Country = "country", RuleType = "ruleType" } /** * Defines values for WafRankingType. \ * {@link KnownWafRankingType} can be used interchangeably with WafRankingType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **action** \ * **ruleGroup** \ * **ruleId** \ * **userAgent** \ * **clientIp** \ * **url** \ * **country** \ * **ruleType** */ export type WafRankingType = string; /** Known values of {@link PolicyEnabledState} that the service accepts. */ export enum KnownPolicyEnabledState { Disabled = "Disabled", Enabled = "Enabled" } /** * Defines values for PolicyEnabledState. \ * {@link KnownPolicyEnabledState} can be used interchangeably with PolicyEnabledState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Disabled** \ * **Enabled** */ export type PolicyEnabledState = string; /** Known values of {@link PolicyMode} that the service accepts. */ export enum KnownPolicyMode { Prevention = "Prevention", Detection = "Detection" } /** * Defines values for PolicyMode. \ * {@link KnownPolicyMode} can be used interchangeably with PolicyMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Prevention** \ * **Detection** */ export type PolicyMode = string; /** Known values of {@link Enum46} that the service accepts. */ export enum KnownEnum46 { TwoHundred = 200, FourHundredThree = 403, FourHundredFive = 405, FourHundredSix = 406, FourHundredTwentyNine = 429 } /** * Defines values for Enum46. \ * {@link KnownEnum46} can be used interchangeably with Enum46, * this enum contains the known values that the service supports. * ### Known values supported by the service * **200** \ * **403** \ * **405** \ * **406** \ * **429** */ export type Enum46 = number; /** Known values of {@link CustomRuleEnabledState} that the service accepts. */ export enum KnownCustomRuleEnabledState { Disabled = "Disabled", Enabled = "Enabled" } /** * Defines values for CustomRuleEnabledState. \ * {@link KnownCustomRuleEnabledState} can be used interchangeably with CustomRuleEnabledState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Disabled** \ * **Enabled** */ export type CustomRuleEnabledState = string; /** Known values of {@link Operator} that the service accepts. */ export enum KnownOperator { Any = "Any", IPMatch = "IPMatch", GeoMatch = "GeoMatch", Equal = "Equal", Contains = "Contains", LessThan = "LessThan", GreaterThan = "GreaterThan", LessThanOrEqual = "LessThanOrEqual", GreaterThanOrEqual = "GreaterThanOrEqual", BeginsWith = "BeginsWith", EndsWith = "EndsWith", RegEx = "RegEx" } /** * Defines values for Operator. \ * {@link KnownOperator} can be used interchangeably with Operator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **IPMatch** \ * **GeoMatch** \ * **Equal** \ * **Contains** \ * **LessThan** \ * **GreaterThan** \ * **LessThanOrEqual** \ * **GreaterThanOrEqual** \ * **BeginsWith** \ * **EndsWith** \ * **RegEx** */ export type Operator = string; /** Known values of {@link TransformType} that the service accepts. */ export enum KnownTransformType { Lowercase = "Lowercase", Uppercase = "Uppercase", Trim = "Trim", UrlDecode = "UrlDecode", UrlEncode = "UrlEncode", RemoveNulls = "RemoveNulls" } /** * Defines values for TransformType. \ * {@link KnownTransformType} can be used interchangeably with TransformType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Lowercase** \ * **Uppercase** \ * **Trim** \ * **UrlDecode** \ * **UrlEncode** \ * **RemoveNulls** */ export type TransformType = string; /** Known values of {@link ActionType} that the service accepts. */ export enum KnownActionType { Allow = "Allow", Block = "Block", Log = "Log", Redirect = "Redirect" } /** * Defines values for ActionType. \ * {@link KnownActionType} can be used interchangeably with ActionType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Allow** \ * **Block** \ * **Log** \ * **Redirect** */ export type ActionType = string; /** Known values of {@link ManagedRuleEnabledState} that the service accepts. */ export enum KnownManagedRuleEnabledState { Disabled = "Disabled", Enabled = "Enabled" } /** * Defines values for ManagedRuleEnabledState. \ * {@link KnownManagedRuleEnabledState} can be used interchangeably with ManagedRuleEnabledState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Disabled** \ * **Enabled** */ export type ManagedRuleEnabledState = string; /** Known values of {@link ProvisioningState} that the service accepts. */ export enum KnownProvisioningState { Creating = "Creating", Succeeded = "Succeeded", Failed = "Failed" } /** * Defines values for ProvisioningState. \ * {@link KnownProvisioningState} can be used interchangeably with ProvisioningState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Succeeded** \ * **Failed** */ export type ProvisioningState = string; /** Known values of {@link PolicyResourceState} that the service accepts. */ export enum KnownPolicyResourceState { Creating = "Creating", Enabling = "Enabling", Enabled = "Enabled", Disabling = "Disabling", Disabled = "Disabled", Deleting = "Deleting" } /** * Defines values for PolicyResourceState. \ * {@link KnownPolicyResourceState} can be used interchangeably with PolicyResourceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Creating** \ * **Enabling** \ * **Enabled** \ * **Disabling** \ * **Disabled** \ * **Deleting** */ export type PolicyResourceState = string; /** Known values of {@link RemoteAddressOperator} that the service accepts. */ export enum KnownRemoteAddressOperator { Any = "Any", IPMatch = "IPMatch", GeoMatch = "GeoMatch" } /** * Defines values for RemoteAddressOperator. \ * {@link KnownRemoteAddressOperator} can be used interchangeably with RemoteAddressOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **IPMatch** \ * **GeoMatch** */ export type RemoteAddressOperator = string; /** Known values of {@link Transform} that the service accepts. */ export enum KnownTransform { Lowercase = "Lowercase", Uppercase = "Uppercase" } /** * Defines values for Transform. \ * {@link KnownTransform} can be used interchangeably with Transform, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Lowercase** \ * **Uppercase** */ export type Transform = string; /** Known values of {@link RequestMethodOperator} that the service accepts. */ export enum KnownRequestMethodOperator { Equal = "Equal" } /** * Defines values for RequestMethodOperator. \ * {@link KnownRequestMethodOperator} can be used interchangeably with RequestMethodOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Equal** */ export type RequestMethodOperator = string; /** Known values of {@link RequestMethodMatchConditionParametersMatchValuesItem} that the service accepts. */ export enum KnownRequestMethodMatchConditionParametersMatchValuesItem { GET = "GET", Head = "HEAD", Post = "POST", PUT = "PUT", Delete = "DELETE", Options = "OPTIONS", Trace = "TRACE" } /** * Defines values for RequestMethodMatchConditionParametersMatchValuesItem. \ * {@link KnownRequestMethodMatchConditionParametersMatchValuesItem} can be used interchangeably with RequestMethodMatchConditionParametersMatchValuesItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **GET** \ * **HEAD** \ * **POST** \ * **PUT** \ * **DELETE** \ * **OPTIONS** \ * **TRACE** */ export type RequestMethodMatchConditionParametersMatchValuesItem = string; /** Known values of {@link QueryStringOperator} that the service accepts. */ export enum KnownQueryStringOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for QueryStringOperator. \ * {@link KnownQueryStringOperator} can be used interchangeably with QueryStringOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type QueryStringOperator = string; /** Known values of {@link PostArgsOperator} that the service accepts. */ export enum KnownPostArgsOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for PostArgsOperator. \ * {@link KnownPostArgsOperator} can be used interchangeably with PostArgsOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type PostArgsOperator = string; /** Known values of {@link RequestUriOperator} that the service accepts. */ export enum KnownRequestUriOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for RequestUriOperator. \ * {@link KnownRequestUriOperator} can be used interchangeably with RequestUriOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type RequestUriOperator = string; /** Known values of {@link RequestHeaderOperator} that the service accepts. */ export enum KnownRequestHeaderOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for RequestHeaderOperator. \ * {@link KnownRequestHeaderOperator} can be used interchangeably with RequestHeaderOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type RequestHeaderOperator = string; /** Known values of {@link RequestBodyOperator} that the service accepts. */ export enum KnownRequestBodyOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for RequestBodyOperator. \ * {@link KnownRequestBodyOperator} can be used interchangeably with RequestBodyOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type RequestBodyOperator = string; /** Known values of {@link RequestSchemeMatchConditionParametersMatchValuesItem} that the service accepts. */ export enum KnownRequestSchemeMatchConditionParametersMatchValuesItem { Http = "HTTP", Https = "HTTPS" } /** * Defines values for RequestSchemeMatchConditionParametersMatchValuesItem. \ * {@link KnownRequestSchemeMatchConditionParametersMatchValuesItem} can be used interchangeably with RequestSchemeMatchConditionParametersMatchValuesItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **HTTP** \ * **HTTPS** */ export type RequestSchemeMatchConditionParametersMatchValuesItem = string; /** Known values of {@link UrlPathOperator} that the service accepts. */ export enum KnownUrlPathOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", Wildcard = "Wildcard", RegEx = "RegEx" } /** * Defines values for UrlPathOperator. \ * {@link KnownUrlPathOperator} can be used interchangeably with UrlPathOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **Wildcard** \ * **RegEx** */ export type UrlPathOperator = string; /** Known values of {@link UrlFileExtensionOperator} that the service accepts. */ export enum KnownUrlFileExtensionOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for UrlFileExtensionOperator. \ * {@link KnownUrlFileExtensionOperator} can be used interchangeably with UrlFileExtensionOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type UrlFileExtensionOperator = string; /** Known values of {@link UrlFileNameOperator} that the service accepts. */ export enum KnownUrlFileNameOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for UrlFileNameOperator. \ * {@link KnownUrlFileNameOperator} can be used interchangeably with UrlFileNameOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type UrlFileNameOperator = string; /** Known values of {@link HttpVersionOperator} that the service accepts. */ export enum KnownHttpVersionOperator { Equal = "Equal" } /** * Defines values for HttpVersionOperator. \ * {@link KnownHttpVersionOperator} can be used interchangeably with HttpVersionOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Equal** */ export type HttpVersionOperator = string; /** Known values of {@link CookiesOperator} that the service accepts. */ export enum KnownCookiesOperator { Any = "Any", Equal = "Equal", Contains = "Contains", BeginsWith = "BeginsWith", EndsWith = "EndsWith", LessThan = "LessThan", LessThanOrEqual = "LessThanOrEqual", GreaterThan = "GreaterThan", GreaterThanOrEqual = "GreaterThanOrEqual", RegEx = "RegEx" } /** * Defines values for CookiesOperator. \ * {@link KnownCookiesOperator} can be used interchangeably with CookiesOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Any** \ * **Equal** \ * **Contains** \ * **BeginsWith** \ * **EndsWith** \ * **LessThan** \ * **LessThanOrEqual** \ * **GreaterThan** \ * **GreaterThanOrEqual** \ * **RegEx** */ export type CookiesOperator = string; /** Known values of {@link IsDeviceOperator} that the service accepts. */ export enum KnownIsDeviceOperator { Equal = "Equal" } /** * Defines values for IsDeviceOperator. \ * {@link KnownIsDeviceOperator} can be used interchangeably with IsDeviceOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Equal** */ export type IsDeviceOperator = string; /** Known values of {@link IsDeviceMatchConditionParametersMatchValuesItem} that the service accepts. */ export enum KnownIsDeviceMatchConditionParametersMatchValuesItem { Mobile = "Mobile", Desktop = "Desktop" } /** * Defines values for IsDeviceMatchConditionParametersMatchValuesItem. \ * {@link KnownIsDeviceMatchConditionParametersMatchValuesItem} can be used interchangeably with IsDeviceMatchConditionParametersMatchValuesItem, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Mobile** \ * **Desktop** */ export type IsDeviceMatchConditionParametersMatchValuesItem = string; /** Known values of {@link RedirectType} that the service accepts. */ export enum KnownRedirectType { Moved = "Moved", Found = "Found", TemporaryRedirect = "TemporaryRedirect", PermanentRedirect = "PermanentRedirect" } /** * Defines values for RedirectType. \ * {@link KnownRedirectType} can be used interchangeably with RedirectType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Moved** \ * **Found** \ * **TemporaryRedirect** \ * **PermanentRedirect** */ export type RedirectType = string; /** Known values of {@link DestinationProtocol} that the service accepts. */ export enum KnownDestinationProtocol { MatchRequest = "MatchRequest", Http = "Http", Https = "Https" } /** * Defines values for DestinationProtocol. \ * {@link KnownDestinationProtocol} can be used interchangeably with DestinationProtocol, * this enum contains the known values that the service supports. * ### Known values supported by the service * **MatchRequest** \ * **Http** \ * **Https** */ export type DestinationProtocol = string; /** Known values of {@link Algorithm} that the service accepts. */ export enum KnownAlgorithm { SHA256 = "SHA256" } /** * Defines values for Algorithm. \ * {@link KnownAlgorithm} can be used interchangeably with Algorithm, * this enum contains the known values that the service supports. * ### Known values supported by the service * **SHA256** */ export type Algorithm = string; /** Known values of {@link ParamIndicator} that the service accepts. */ export enum KnownParamIndicator { Expires = "Expires", KeyId = "KeyId", Signature = "Signature" } /** * Defines values for ParamIndicator. \ * {@link KnownParamIndicator} can be used interchangeably with ParamIndicator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Expires** \ * **KeyId** \ * **Signature** */ export type ParamIndicator = string; /** Known values of {@link HeaderAction} that the service accepts. */ export enum KnownHeaderAction { Append = "Append", Overwrite = "Overwrite", Delete = "Delete" } /** * Defines values for HeaderAction. \ * {@link KnownHeaderAction} can be used interchangeably with HeaderAction, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Append** \ * **Overwrite** \ * **Delete** */ export type HeaderAction = string; /** Known values of {@link CacheBehavior} that the service accepts. */ export enum KnownCacheBehavior { BypassCache = "BypassCache", Override = "Override", SetIfMissing = "SetIfMissing" } /** * Defines values for CacheBehavior. \ * {@link KnownCacheBehavior} can be used interchangeably with CacheBehavior, * this enum contains the known values that the service supports. * ### Known values supported by the service * **BypassCache** \ * **Override** \ * **SetIfMissing** */ export type CacheBehavior = string; /** Known values of {@link CacheType} that the service accepts. */ export enum KnownCacheType { All = "All" } /** * Defines values for CacheType. \ * {@link KnownCacheType} can be used interchangeably with CacheType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **All** */ export type CacheType = string; /** Known values of {@link QueryStringBehavior} that the service accepts. */ export enum KnownQueryStringBehavior { Include = "Include", IncludeAll = "IncludeAll", Exclude = "Exclude", ExcludeAll = "ExcludeAll" } /** * Defines values for QueryStringBehavior. \ * {@link KnownQueryStringBehavior} can be used interchangeably with QueryStringBehavior, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Include** \ * **IncludeAll** \ * **Exclude** \ * **ExcludeAll** */ export type QueryStringBehavior = string; /** Known values of {@link CertificateType} that the service accepts. */ export enum KnownCertificateType { Shared = "Shared", Dedicated = "Dedicated" } /** * Defines values for CertificateType. \ * {@link KnownCertificateType} can be used interchangeably with CertificateType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Shared** \ * **Dedicated** */ export type CertificateType = string; /** Known values of {@link UpdateRule} that the service accepts. */ export enum KnownUpdateRule { NoAction = "NoAction" } /** * Defines values for UpdateRule. \ * {@link KnownUpdateRule} can be used interchangeably with UpdateRule, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NoAction** */ export type UpdateRule = string; /** Known values of {@link DeleteRule} that the service accepts. */ export enum KnownDeleteRule { NoAction = "NoAction" } /** * Defines values for DeleteRule. \ * {@link KnownDeleteRule} can be used interchangeably with DeleteRule, * this enum contains the known values that the service supports. * ### Known values supported by the service * **NoAction** */ export type DeleteRule = string; /** Defines values for HealthProbeRequestType. */ export type HealthProbeRequestType = "NotSet" | "GET" | "HEAD"; /** Defines values for ProbeProtocol. */ export type ProbeProtocol = "NotSet" | "Http" | "Https"; /** Defines values for ResponseBasedDetectedErrorTypes. */ export type ResponseBasedDetectedErrorTypes = | "None" | "TcpErrorsOnly" | "TcpAndHttpErrors"; /** Defines values for QueryStringCachingBehavior. */ export type QueryStringCachingBehavior = | "IgnoreQueryString" | "BypassCaching" | "UseQueryString" | "NotSet"; /** Defines values for GeoFilterActions. */ export type GeoFilterActions = "Block" | "Allow"; /** Defines values for MinimumTlsVersion. */ export type MinimumTlsVersion = "None" | "TLS10" | "TLS12"; /** Defines values for AfdMinimumTlsVersion. */ export type AfdMinimumTlsVersion = "TLS10" | "TLS12"; /** Defines values for AfdQueryStringCachingBehavior. */ export type AfdQueryStringCachingBehavior = | "IgnoreQueryString" | "UseQueryString" | "NotSet"; /** Defines values for SharedPrivateLinkResourceStatus. */ export type SharedPrivateLinkResourceStatus = | "Pending" | "Approved" | "Rejected" | "Disconnected" | "Timeout"; /** Optional parameters. */ export interface ProfilesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ProfilesListResponse = ProfileListResult; /** Optional parameters. */ export interface ProfilesListByResourceGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroup operation. */ export type ProfilesListByResourceGroupResponse = ProfileListResult; /** Optional parameters. */ export interface ProfilesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type ProfilesGetResponse = Profile; /** Optional parameters. */ export interface ProfilesCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type ProfilesCreateResponse = Profile; /** Optional parameters. */ export interface ProfilesUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type ProfilesUpdateResponse = Profile; /** Optional parameters. */ export interface ProfilesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface ProfilesGenerateSsoUriOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the generateSsoUri operation. */ export type ProfilesGenerateSsoUriResponse = SsoUri; /** Optional parameters. */ export interface ProfilesListSupportedOptimizationTypesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listSupportedOptimizationTypes operation. */ export type ProfilesListSupportedOptimizationTypesResponse = SupportedOptimizationTypesListResult; /** Optional parameters. */ export interface ProfilesListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type ProfilesListResourceUsageResponse = ResourceUsageListResult; /** Optional parameters. */ export interface ProfilesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ProfilesListNextResponse = ProfileListResult; /** Optional parameters. */ export interface ProfilesListByResourceGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByResourceGroupNext operation. */ export type ProfilesListByResourceGroupNextResponse = ProfileListResult; /** Optional parameters. */ export interface ProfilesListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type ProfilesListResourceUsageNextResponse = ResourceUsageListResult; /** Optional parameters. */ export interface EndpointsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type EndpointsListByProfileResponse = EndpointListResult; /** Optional parameters. */ export interface EndpointsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type EndpointsGetResponse = Endpoint; /** Optional parameters. */ export interface EndpointsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type EndpointsCreateResponse = Endpoint; /** Optional parameters. */ export interface EndpointsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type EndpointsUpdateResponse = Endpoint; /** Optional parameters. */ export interface EndpointsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface EndpointsStartOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the start operation. */ export type EndpointsStartResponse = Endpoint; /** Optional parameters. */ export interface EndpointsStopOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the stop operation. */ export type EndpointsStopResponse = Endpoint; /** Optional parameters. */ export interface EndpointsPurgeContentOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface EndpointsLoadContentOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface EndpointsValidateCustomDomainOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the validateCustomDomain operation. */ export type EndpointsValidateCustomDomainResponse = ValidateCustomDomainOutput; /** Optional parameters. */ export interface EndpointsListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type EndpointsListResourceUsageResponse = ResourceUsageListResult; /** Optional parameters. */ export interface EndpointsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type EndpointsListByProfileNextResponse = EndpointListResult; /** Optional parameters. */ export interface EndpointsListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type EndpointsListResourceUsageNextResponse = ResourceUsageListResult; /** Optional parameters. */ export interface OriginsListByEndpointOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpoint operation. */ export type OriginsListByEndpointResponse = OriginListResult; /** Optional parameters. */ export interface OriginsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type OriginsGetResponse = Origin; /** Optional parameters. */ export interface OriginsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type OriginsCreateResponse = Origin; /** Optional parameters. */ export interface OriginsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type OriginsUpdateResponse = Origin; /** Optional parameters. */ export interface OriginsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface OriginsListByEndpointNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpointNext operation. */ export type OriginsListByEndpointNextResponse = OriginListResult; /** Optional parameters. */ export interface OriginGroupsListByEndpointOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpoint operation. */ export type OriginGroupsListByEndpointResponse = OriginGroupListResult; /** Optional parameters. */ export interface OriginGroupsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type OriginGroupsGetResponse = OriginGroup; /** Optional parameters. */ export interface OriginGroupsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type OriginGroupsCreateResponse = OriginGroup; /** Optional parameters. */ export interface OriginGroupsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type OriginGroupsUpdateResponse = OriginGroup; /** Optional parameters. */ export interface OriginGroupsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface OriginGroupsListByEndpointNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpointNext operation. */ export type OriginGroupsListByEndpointNextResponse = OriginGroupListResult; /** Optional parameters. */ export interface CustomDomainsListByEndpointOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpoint operation. */ export type CustomDomainsListByEndpointResponse = CustomDomainListResult; /** Optional parameters. */ export interface CustomDomainsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type CustomDomainsGetResponse = CustomDomain; /** Optional parameters. */ export interface CustomDomainsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type CustomDomainsCreateResponse = CustomDomain; /** Optional parameters. */ export interface CustomDomainsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface CustomDomainsDisableCustomHttpsOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface CustomDomainsEnableCustomHttpsOptionalParams extends coreClient.OperationOptions { /** The configuration specifying how to enable HTTPS for the custom domain - using CDN managed certificate or user's own certificate. If not specified, enabling ssl uses CDN managed certificate by default. */ customDomainHttpsParameters?: CustomDomainHttpsParametersUnion; /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface CustomDomainsListByEndpointNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpointNext operation. */ export type CustomDomainsListByEndpointNextResponse = CustomDomainListResult; /** Optional parameters. */ export interface CheckNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailability operation. */ export type CheckNameAvailabilityResponse = CheckNameAvailabilityOutput; /** Optional parameters. */ export interface CheckNameAvailabilityWithSubscriptionOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkNameAvailabilityWithSubscription operation. */ export type CheckNameAvailabilityWithSubscriptionResponse = CheckNameAvailabilityOutput; /** Optional parameters. */ export interface ValidateProbeOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the validateProbe operation. */ export type ValidateProbeResponse = ValidateProbeOutput; /** Optional parameters. */ export interface ResourceUsageListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ResourceUsageListResponse = ResourceUsageListResult; /** Optional parameters. */ export interface ResourceUsageListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ResourceUsageListNextResponse = ResourceUsageListResult; /** Optional parameters. */ export interface OperationsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type OperationsListResponse = OperationsListResult; /** Optional parameters. */ export interface OperationsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationsListResult; /** Optional parameters. */ export interface EdgeNodesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type EdgeNodesListResponse = EdgenodeResult; /** Optional parameters. */ export interface EdgeNodesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type EdgeNodesListNextResponse = EdgenodeResult; /** Optional parameters. */ export interface AFDProfilesListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type AFDProfilesListResourceUsageResponse = UsagesListResult; /** Optional parameters. */ export interface AFDProfilesCheckHostNameAvailabilityOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the checkHostNameAvailability operation. */ export type AFDProfilesCheckHostNameAvailabilityResponse = ValidateCustomDomainOutput; /** Optional parameters. */ export interface AFDProfilesListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type AFDProfilesListResourceUsageNextResponse = UsagesListResult; /** Optional parameters. */ export interface AFDCustomDomainsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type AFDCustomDomainsListByProfileResponse = AFDDomainListResult; /** Optional parameters. */ export interface AFDCustomDomainsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AFDCustomDomainsGetResponse = AFDDomain; /** Optional parameters. */ export interface AFDCustomDomainsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type AFDCustomDomainsCreateResponse = AFDDomain; /** Optional parameters. */ export interface AFDCustomDomainsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type AFDCustomDomainsUpdateResponse = AFDDomain; /** Optional parameters. */ export interface AFDCustomDomainsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AFDCustomDomainsRefreshValidationTokenOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the refreshValidationToken operation. */ export type AFDCustomDomainsRefreshValidationTokenResponse = ValidationToken; /** Optional parameters. */ export interface AFDCustomDomainsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type AFDCustomDomainsListByProfileNextResponse = AFDDomainListResult; /** Optional parameters. */ export interface AFDEndpointsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type AFDEndpointsListByProfileResponse = AFDEndpointListResult; /** Optional parameters. */ export interface AFDEndpointsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AFDEndpointsGetResponse = AFDEndpoint; /** Optional parameters. */ export interface AFDEndpointsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type AFDEndpointsCreateResponse = AFDEndpoint; /** Optional parameters. */ export interface AFDEndpointsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type AFDEndpointsUpdateResponse = AFDEndpoint; /** Optional parameters. */ export interface AFDEndpointsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AFDEndpointsPurgeContentOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AFDEndpointsListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type AFDEndpointsListResourceUsageResponse = UsagesListResult; /** Optional parameters. */ export interface AFDEndpointsValidateCustomDomainOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the validateCustomDomain operation. */ export type AFDEndpointsValidateCustomDomainResponse = ValidateCustomDomainOutput; /** Optional parameters. */ export interface AFDEndpointsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type AFDEndpointsListByProfileNextResponse = AFDEndpointListResult; /** Optional parameters. */ export interface AFDEndpointsListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type AFDEndpointsListResourceUsageNextResponse = UsagesListResult; /** Optional parameters. */ export interface AFDOriginGroupsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type AFDOriginGroupsListByProfileResponse = AFDOriginGroupListResult; /** Optional parameters. */ export interface AFDOriginGroupsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AFDOriginGroupsGetResponse = AFDOriginGroup; /** Optional parameters. */ export interface AFDOriginGroupsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type AFDOriginGroupsCreateResponse = AFDOriginGroup; /** Optional parameters. */ export interface AFDOriginGroupsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type AFDOriginGroupsUpdateResponse = AFDOriginGroup; /** Optional parameters. */ export interface AFDOriginGroupsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AFDOriginGroupsListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type AFDOriginGroupsListResourceUsageResponse = UsagesListResult; /** Optional parameters. */ export interface AFDOriginGroupsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type AFDOriginGroupsListByProfileNextResponse = AFDOriginGroupListResult; /** Optional parameters. */ export interface AFDOriginGroupsListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type AFDOriginGroupsListResourceUsageNextResponse = UsagesListResult; /** Optional parameters. */ export interface AFDOriginsListByOriginGroupOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByOriginGroup operation. */ export type AFDOriginsListByOriginGroupResponse = AFDOriginListResult; /** Optional parameters. */ export interface AFDOriginsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type AFDOriginsGetResponse = AFDOrigin; /** Optional parameters. */ export interface AFDOriginsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type AFDOriginsCreateResponse = AFDOrigin; /** Optional parameters. */ export interface AFDOriginsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type AFDOriginsUpdateResponse = AFDOrigin; /** Optional parameters. */ export interface AFDOriginsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface AFDOriginsListByOriginGroupNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByOriginGroupNext operation. */ export type AFDOriginsListByOriginGroupNextResponse = AFDOriginListResult; /** Optional parameters. */ export interface RoutesListByEndpointOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpoint operation. */ export type RoutesListByEndpointResponse = RouteListResult; /** Optional parameters. */ export interface RoutesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RoutesGetResponse = Route; /** Optional parameters. */ export interface RoutesCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type RoutesCreateResponse = Route; /** Optional parameters. */ export interface RoutesUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type RoutesUpdateResponse = Route; /** Optional parameters. */ export interface RoutesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RoutesListByEndpointNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByEndpointNext operation. */ export type RoutesListByEndpointNextResponse = RouteListResult; /** Optional parameters. */ export interface RuleSetsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type RuleSetsListByProfileResponse = RuleSetListResult; /** Optional parameters. */ export interface RuleSetsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RuleSetsGetResponse = RuleSet; /** Optional parameters. */ export interface RuleSetsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type RuleSetsCreateResponse = RuleSet; /** Optional parameters. */ export interface RuleSetsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RuleSetsListResourceUsageOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsage operation. */ export type RuleSetsListResourceUsageResponse = UsagesListResult; /** Optional parameters. */ export interface RuleSetsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type RuleSetsListByProfileNextResponse = RuleSetListResult; /** Optional parameters. */ export interface RuleSetsListResourceUsageNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listResourceUsageNext operation. */ export type RuleSetsListResourceUsageNextResponse = UsagesListResult; /** Optional parameters. */ export interface RulesListByRuleSetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByRuleSet operation. */ export type RulesListByRuleSetResponse = RuleListResult; /** Optional parameters. */ export interface RulesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type RulesGetResponse = Rule; /** Optional parameters. */ export interface RulesCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type RulesCreateResponse = Rule; /** Optional parameters. */ export interface RulesUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type RulesUpdateResponse = Rule; /** Optional parameters. */ export interface RulesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface RulesListByRuleSetNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByRuleSetNext operation. */ export type RulesListByRuleSetNextResponse = RuleListResult; /** Optional parameters. */ export interface SecurityPoliciesListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type SecurityPoliciesListByProfileResponse = SecurityPolicyListResult; /** Optional parameters. */ export interface SecurityPoliciesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SecurityPoliciesGetResponse = SecurityPolicy; /** Optional parameters. */ export interface SecurityPoliciesCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type SecurityPoliciesCreateResponse = SecurityPolicy; /** Optional parameters. */ export interface SecurityPoliciesPatchOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the patch operation. */ export type SecurityPoliciesPatchResponse = SecurityPolicy; /** Optional parameters. */ export interface SecurityPoliciesDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface SecurityPoliciesListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type SecurityPoliciesListByProfileNextResponse = SecurityPolicyListResult; /** Optional parameters. */ export interface SecretsListByProfileOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfile operation. */ export type SecretsListByProfileResponse = SecretListResult; /** Optional parameters. */ export interface SecretsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type SecretsGetResponse = Secret; /** Optional parameters. */ export interface SecretsCreateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the create operation. */ export type SecretsCreateResponse = Secret; /** Optional parameters. */ export interface SecretsUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type SecretsUpdateResponse = Secret; /** Optional parameters. */ export interface SecretsDeleteOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Optional parameters. */ export interface SecretsListByProfileNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listByProfileNext operation. */ export type SecretsListByProfileNextResponse = SecretListResult; /** Optional parameters. */ export interface ValidateSecretOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the secret operation. */ export type ValidateSecretResponse = ValidateSecretOutput; /** Optional parameters. */ export interface LogAnalyticsGetLogAnalyticsMetricsOptionalParams extends coreClient.OperationOptions { /** Array of LogMetricsGroupBy */ groupBy?: LogMetricsGroupBy[]; /** Array of Get9ItemsItem */ continents?: string[]; /** Array of Get10ItemsItem */ countryOrRegions?: string[]; } /** Contains response data for the getLogAnalyticsMetrics operation. */ export type LogAnalyticsGetLogAnalyticsMetricsResponse = MetricsResponse; /** Optional parameters. */ export interface LogAnalyticsGetLogAnalyticsRankingsOptionalParams extends coreClient.OperationOptions { /** Array of String */ customDomains?: string[]; } /** Contains response data for the getLogAnalyticsRankings operation. */ export type LogAnalyticsGetLogAnalyticsRankingsResponse = RankingsResponse; /** Optional parameters. */ export interface LogAnalyticsGetLogAnalyticsLocationsOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getLogAnalyticsLocations operation. */ export type LogAnalyticsGetLogAnalyticsLocationsResponse = ContinentsResponse; /** Optional parameters. */ export interface LogAnalyticsGetLogAnalyticsResourcesOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getLogAnalyticsResources operation. */ export type LogAnalyticsGetLogAnalyticsResourcesResponse = ResourcesResponse; /** Optional parameters. */ export interface LogAnalyticsGetWafLogAnalyticsMetricsOptionalParams extends coreClient.OperationOptions { /** Array of WafAction */ actions?: WafAction[]; /** Array of WafRankingGroupBy */ groupBy?: WafRankingGroupBy[]; /** Array of WafRuleType */ ruleTypes?: WafRuleType[]; } /** Contains response data for the getWafLogAnalyticsMetrics operation. */ export type LogAnalyticsGetWafLogAnalyticsMetricsResponse = WafMetricsResponse; /** Optional parameters. */ export interface LogAnalyticsGetWafLogAnalyticsRankingsOptionalParams extends coreClient.OperationOptions { /** Array of WafAction */ actions?: WafAction[]; /** Array of WafRuleType */ ruleTypes?: WafRuleType[]; } /** Contains response data for the getWafLogAnalyticsRankings operation. */ export type LogAnalyticsGetWafLogAnalyticsRankingsResponse = WafRankingsResponse; /** Optional parameters. */ export interface PoliciesListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type PoliciesListResponse = CdnWebApplicationFirewallPolicyList; /** Optional parameters. */ export interface PoliciesGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type PoliciesGetResponse = CdnWebApplicationFirewallPolicy; /** Optional parameters. */ export interface PoliciesCreateOrUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the createOrUpdate operation. */ export type PoliciesCreateOrUpdateResponse = CdnWebApplicationFirewallPolicy; /** Optional parameters. */ export interface PoliciesUpdateOptionalParams extends coreClient.OperationOptions { /** Delay to wait until next poll, in milliseconds. */ updateIntervalInMs?: number; /** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */ resumeFrom?: string; } /** Contains response data for the update operation. */ export type PoliciesUpdateResponse = CdnWebApplicationFirewallPolicy; /** Optional parameters. */ export interface PoliciesDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface PoliciesListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type PoliciesListNextResponse = CdnWebApplicationFirewallPolicyList; /** Optional parameters. */ export interface ManagedRuleSetsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type ManagedRuleSetsListResponse = ManagedRuleSetDefinitionList; /** Optional parameters. */ export interface ManagedRuleSetsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type ManagedRuleSetsListNextResponse = ManagedRuleSetDefinitionList; /** Optional parameters. */ export interface CdnManagementClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { computed, onMounted, Ref, ref, UnwrapRef, watch } from 'vue'; import { addDays, addMonths, getDay, getHours, getISOWeek, getMinutes, getMonth, getSeconds, getYear } from 'date-fns'; import { ICalendarDay, IMarker, InternalModuleValue, UseCalendar, VueEmit } from '../../interfaces'; import { getNextMonthYear, getNextYearMonth, getPreviousMonthYear, isDateAfter, isDateBefore, isDateEqual, sanitizeDate, setDateMonthOrYear, setDateTime, } from '../../utils/date-utils'; import { isModelValueRange, isNumberArray, isRange, isTimeArr, modelValueIsRange } from '../../utils/type-guard'; interface IUseCalendar { isDisabled: (date: Date) => boolean; isActiveDate: (day: ICalendarDay) => boolean; rangeActive: (day: ICalendarDay) => boolean; selectDate: (day: UnwrapRef<ICalendarDay>, isNext?: boolean) => void; getWeekNum: (days: UnwrapRef<ICalendarDay[]>) => string | number; setHoverDate: (day: UnwrapRef<ICalendarDay>) => void; updateTime: (value: number | number[], isHours?: boolean, isSeconds?: boolean) => void; updateMonthYear: (value: number, isMonth?: boolean, isNext?: boolean) => void; isHoverRangeEnd: (day: UnwrapRef<ICalendarDay>) => boolean; isAutoRangeInBetween: (day: UnwrapRef<ICalendarDay>) => boolean; isAutoRangeStart: (day: UnwrapRef<ICalendarDay>) => boolean; rangeActiveStartEnd: (day: UnwrapRef<ICalendarDay>, isStart?: boolean) => boolean; isHoverDate: (disabled: boolean, day: UnwrapRef<ICalendarDay>) => boolean; isHoverDateStartEnd: (isHovered: boolean, calendarDay: UnwrapRef<ICalendarDay>, start: boolean) => boolean; monthYearSelect: (isYear?: boolean) => void; clearHoverDate: () => void; handleScroll: (event: WheelEvent, isNext?: boolean) => void; handleArrow: (arrow: 'left' | 'right', isNext?: boolean) => void; getMarker: (day: UnwrapRef<ICalendarDay>) => IMarker | undefined; selectCurrentDate: () => void; today: Ref<Date>; month: Ref<number>; year: Ref<number>; monthNext: Ref<number>; yearNext: Ref<number>; hours: Ref<number | number[]>; minutes: Ref<number | number[]>; seconds: Ref<number | number[]>; } export const useCalendar = (props: UseCalendar, emit: VueEmit): IUseCalendar => { const today = ref<Date>(new Date()); const hoveredDate = ref<Date | null>(); const month = ref<number>(getMonth(new Date())); const year = ref<number>(getYear(new Date())); const monthNext = ref<number>(getNextMonthYear(new Date()).month); const yearNext = ref<number>(getNextMonthYear(new Date()).year); const hours = ref<number | number[]>( props.range ? [getHours(new Date()), getHours(new Date())] : getHours(new Date()), ); const minutes = ref<number | number[]>( props.range ? [getMinutes(new Date()), getMinutes(new Date())] : getMinutes(new Date()), ); const seconds = ref<number | number[]>(props.range ? [0, 0] : 0); onMounted(() => { mapInternalModuleValues(); if (!modelValue.value) { if (props.startDate) { month.value = getMonth(new Date(props.startDate)); year.value = getYear(new Date(props.startDate)); if (props.twoCalendars) { monthNext.value = getNextMonthYear(new Date(props.startDate)).month; yearNext.value = getNextMonthYear(new Date(props.startDate)).year; } } if (props.startTime) { assignStartTime(); } } }); const getSecondsValue = (getFirst = true): number | null => { if (props.enableSeconds) { if (Array.isArray(seconds.value)) { return getFirst ? seconds.value[0] : seconds.value[1]; } return seconds.value; } return 0; }; /** * If start time is provided, assign data. * Note: data is sanitized from the parent component with all parameters since props * can be provided partially */ const assignStartTime = (): void => { if (props.startTime) { if (isTimeArr(props.startTime)) { hours.value = [+props.startTime[0].hours, +props.startTime[1].hours]; minutes.value = [+props.startTime[0].minutes, +props.startTime[1].minutes]; if (props.enableSeconds) { seconds.value = [+props.startTime[0].seconds, +props.startTime[1].seconds]; } } else { hours.value = +props.startTime.hours; minutes.value = +props.startTime.minutes; if (props.enableSeconds) { seconds.value = +props.startTime.seconds; } } } }; /** * Model binding, removes the need for watches, sync data between components */ const modelValue = computed({ get: (): InternalModuleValue => { return props.internalModelValue; }, set: (value: InternalModuleValue): void => { if (!props.readonly && !props.disabled) { emit('update:internalModelValue', value); } }, }); watch(modelValue, () => mapInternalModuleValues()); /** * Check if date is between max and min date, or if it is included in filters */ const isDisabled = (date: Date): boolean => { const aboveMax = props.maxDate ? isDateAfter(sanitizeDate(date), sanitizeDate(new Date(props.maxDate))) : false; const bellowMin = props.minDate ? isDateBefore(sanitizeDate(date), sanitizeDate(new Date(props.minDate))) : false; const inDisableArr = typeof props.disabledDates === 'function' ? props.disabledDates(date) : props.disabledDates.some((disabledDate: Date | string) => isDateEqual(sanitizeDate(new Date(disabledDate)), sanitizeDate(date)), ); const disabledMonths = props.filters.months.length ? props.filters.months.map((month) => +month) : []; const inDisabledMonths = disabledMonths.includes(getMonth(date)); const weekDayDisabled = props.disabledWeekDays.length ? props.disabledWeekDays.some((day) => +day === getDay(date)) : false; const notInSpecific = props.allowedDates.length ? !props.allowedDates.some((dateVal) => isDateEqual(sanitizeDate(new Date(dateVal)), sanitizeDate(date))) : false; const dateYear = getYear(date); const outOfYearRange = dateYear < +props.yearRange[0] || dateYear > +props.yearRange[1]; return ( aboveMax || bellowMin || inDisableArr || inDisabledMonths || outOfYearRange || weekDayDisabled || notInSpecific ); }; /** * Check if some date is active, in case of range, it will have two dates */ const isActiveDate = (calendarDay: ICalendarDay): boolean => { if (!modelValue.value) return false; if (props.hideOffsetDates && !calendarDay.current) return false; if (!props.range) { return isDateEqual(calendarDay.value, modelValue.value ? (modelValue.value as Date) : today.value); } return false; }; /** * If range mode used, this will check if the calendar day is between 2 active dates */ const rangeActive = (calendarDay: ICalendarDay): boolean => { if (isModelValueRange(modelValue.value) && modelValue.value[0] && modelValue.value[1]) { return ( isDateAfter(calendarDay.value, modelValue.value[0]) && isDateBefore(calendarDay.value, modelValue.value[1]) ); } if (isModelValueRange(modelValue.value) && modelValue.value[0] && hoveredDate.value) { return ( (isDateAfter(calendarDay.value, modelValue.value[0]) && isDateBefore(calendarDay.value, hoveredDate.value)) || (isDateBefore(calendarDay.value, modelValue.value[0]) && isDateAfter(calendarDay.value, hoveredDate.value)) ); } return false; }; /** * Extracted method to map month and year */ const assignMonthAndYear = (date: Date): void => { month.value = getMonth(date); year.value = getYear(date); }; /** * Values for times, month and year are managed separately, here we map those values from passed v-model */ const mapInternalModuleValues = (): void => { if (modelValue.value) { if (isModelValueRange(modelValue.value)) { if (modelValue.value.length === 2) { assignMonthAndYear(modelValue.value[0]); hours.value = [ getHours(modelValue.value[0]), modelValue.value[1] ? getHours(modelValue.value[1]) : getHours(new Date()), ]; minutes.value = [ getMinutes(modelValue.value[0]), modelValue.value[1] ? getMinutes(modelValue.value[1]) : getMinutes(new Date()), ]; seconds.value = [ getSeconds(modelValue.value[0]), modelValue.value[1] ? getSeconds(modelValue.value[1]) : getSeconds(new Date()), ]; } if (props.twoCalendars) { handleNextMonthYear(); } } else { assignMonthAndYear(modelValue.value); hours.value = getHours(modelValue.value); minutes.value = getMinutes(modelValue.value); seconds.value = getSeconds(modelValue.value); } } else { if (props.timePicker) { assignStartTime(); if (!props.range) { modelValue.value = setDateTime( new Date(), hours.value as number, minutes.value as number, getSecondsValue(), ); } else if (isNumberArray(hours.value) && isNumberArray(minutes.value)) { modelValue.value = [ setDateTime(new Date(), hours.value[0], minutes.value[0], getSecondsValue()), setDateTime(new Date(), hours.value[1], minutes.value[1], getSecondsValue(false)), ]; } } else if (props.monthPicker) { modelValue.value = setDateMonthOrYear(new Date(), month.value, year.value); } } }; /** * When using next calendar on auto range mode, adjust month and year for both calendars */ const handleNextCalendarAutoRange = (date: string | Date) => { const monthValue = getMonth(new Date(date)); const yearValue = getYear(new Date(date)); const next = getNextMonthYear(new Date(date)); month.value = monthValue; year.value = yearValue; monthNext.value = next.month; yearNext.value = next.year; }; /** * Called when the date in the calendar is clicked * Do a necessary formatting and assign value to internal */ const selectDate = (day: UnwrapRef<ICalendarDay>, isNext = false): void => { if (isDisabled(day.value)) { return; } if (!day.current && props.hideOffsetDates) { return; } if (!props.range && !isNumberArray(hours.value) && !isNumberArray(minutes.value)) { modelValue.value = setDateTime(new Date(day.value), hours.value, minutes.value, getSecondsValue()); if (props.autoApply) { emit('autoApply'); } } else if (isNumberArray(hours.value) && isNumberArray(minutes.value)) { let rangeDate = modelValue.value ? (modelValue.value as Date[]).slice() : []; if (rangeDate.length === 2) { rangeDate = []; } if (props.autoRange) { if (isNext) { handleNextCalendarAutoRange(day.value); } rangeDate = [new Date(day.value), addDays(new Date(day.value), +props.autoRange)]; } else { if (!rangeDate[0]) { rangeDate[0] = new Date(day.value); } else { if (isDateBefore(new Date(day.value), new Date(rangeDate[0]))) { rangeDate.unshift(new Date(day.value)); } else { rangeDate[1] = new Date(day.value); } } } if (rangeDate[0] && !rangeDate[1]) { rangeDate[0] = setDateTime(rangeDate[0], hours.value[0], minutes.value[0], getSecondsValue()); } else { rangeDate[0] = setDateTime(rangeDate[0], hours.value[0], minutes.value[0], getSecondsValue()); rangeDate[1] = setDateTime(rangeDate[1], hours.value[1], minutes.value[1], getSecondsValue(false)); } modelValue.value = rangeDate; if (rangeDate[0] && rangeDate[1] && props.autoApply) { emit('autoApply'); } } }; /** * Get week number if enabled */ const getWeekNum = (days: UnwrapRef<ICalendarDay[]>): string | number => { const firstCurrentData = days.find((day) => day.current); if (firstCurrentData) { return getISOWeek(firstCurrentData.value); } return ''; }; /** * When using range picker keep track of hovered value in the calendar */ const setHoverDate = (day: UnwrapRef<ICalendarDay>): void => { if (!day.current && props.hideOffsetDates) { return; } hoveredDate.value = day.value; }; /** * Check if range ends on the given day */ const isHoverRangeEnd = (day: UnwrapRef<ICalendarDay>): boolean => { if (props.autoRange) { if (hoveredDate.value) { if (props.hideOffsetDates && !day.current) return false; const rangeEnd = addDays(hoveredDate.value, +props.autoRange); return isDateEqual(rangeEnd, new Date(day.value)); } return false; } return false; }; /** * Check if date in auto range preview is in between */ const isAutoRangeInBetween = (day: UnwrapRef<ICalendarDay>): boolean => { if (props.autoRange) { if (hoveredDate.value) { const rangeEnd = addDays(hoveredDate.value, +props.autoRange); if (props.hideOffsetDates && !day.current) return false; return isDateAfter(day.value, hoveredDate.value) && isDateBefore(day.value, rangeEnd); } return false; } return false; }; const isAutoRangeStart = (day: UnwrapRef<ICalendarDay>): boolean => { if (props.autoRange) { if (hoveredDate.value) { if (props.hideOffsetDates && !day.current) return false; return isDateEqual(hoveredDate.value, day.value); } return false; } return false; }; const handleNextMonthYear = (): void => { if (Array.isArray(modelValue.value) && modelValue.value.length === 2) { const date = new Date(modelValue.value[1] ? modelValue.value[1] : addMonths(modelValue.value[0], 1)); if ((monthNext.value === month.value && yearNext.value === year.value) || !props.twoCalendarsSolo) { const date = getNextYearMonth(month.value, year.value); monthNext.value = date.month; yearNext.value = date.year; } else { if (getMonth(modelValue.value[0]) !== getMonth(modelValue.value[1])) { monthNext.value = getMonth(date); yearNext.value = getYear(date); } } } }; const handlePreviousCalendarChange = (monthVal: number, yearVal: number): void => { if (!props.twoCalendarsSolo) { const date = getPreviousMonthYear(monthVal, yearVal); month.value = date.month; year.value = date.year; } }; const handleNextCalendarChange = (monthVal: number, yearVal: number): void => { if (!props.twoCalendarsSolo) { const date = getNextYearMonth(monthVal, yearVal); monthNext.value = date.month; yearNext.value = date.year; } }; const updateMonthYear = (value: number, isMonth = true, isNext = false): void => { if (isMonth) { if (isNext) { handlePreviousCalendarChange(value, yearNext.value); monthNext.value = value; } else { handleNextCalendarChange(value, year.value); month.value = value; } } else { if (isNext) { handlePreviousCalendarChange(monthNext.value, value); yearNext.value = value; } else { handleNextCalendarChange(month.value, value); year.value = value; } } if (props.monthPicker) { if (modelValue.value) { modelValue.value = setDateMonthOrYear(modelValue.value as Date, month.value, year.value); } else { modelValue.value = setDateMonthOrYear(new Date(), month.value, year.value); } } }; /** * Same logic done twice with the time update, however some checks before applying are done */ const handleTimeUpdate = (dateValue: Date | Date[]): void => { if ( isModelValueRange(dateValue) && isModelValueRange(modelValue.value) && isNumberArray(hours.value) && isNumberArray(minutes.value) ) { if (dateValue[0] && modelValue.value[0]) { modelValue.value[0] = setDateTime(dateValue[0], hours.value[0], minutes.value[0], getSecondsValue()); } if (dateValue[1] && modelValue.value[1]) { modelValue.value[1] = setDateTime( dateValue[1], hours.value[1], minutes.value[1], getSecondsValue(false), ); } } else if (!props.range && !isRange(dateValue)) { modelValue.value = setDateTime( dateValue as Date, hours.value as number, minutes.value as number, getSecondsValue(), ); } emit('timeUpdate'); }; /** * Called on event when time value is changed */ const updateTime = (value: number | number[], isHours = true, isSeconds = false) => { if (isHours) { hours.value = value; } else if (!isHours && !isSeconds) { minutes.value = value; } else if (isSeconds) { seconds.value = value; } if (modelValue.value) { handleTimeUpdate(modelValue.value); } else if (props.timePicker) { handleTimeUpdate(props.range ? [new Date(), new Date()] : new Date()); } }; // When mouse leaves the menu clear the hover date data const clearHoverDate = (): void => { hoveredDate.value = null; }; const checkRangeDirection = (isStart: boolean): boolean => { if (modelValueIsRange(modelValue.value, props.range) && modelValue.value[0] && hoveredDate.value) { return isStart ? isDateAfter(hoveredDate.value, modelValue.value[0]) : isDateBefore(hoveredDate.value, modelValue.value[0]); } return true; }; /** * Check when to add a proper active start/end date class on range picker */ const rangeActiveStartEnd = (day: UnwrapRef<ICalendarDay>, isStart = true): boolean => { if (props.range && isRange(modelValue.value)) { if (props.hideOffsetDates && !day.current) return false; return isDateEqual(new Date(day.value), modelValue.value[isStart ? 0 : 1]); } else if (props.range) { return ( (isDateEqual( new Date(day.value), modelValue.value && Array.isArray(modelValue.value) ? isStart ? modelValue.value[0] || null : modelValue.value[1] : null, ) && // this part will rotate start/end depending on the hover date (isStart ? !isDateBefore( hoveredDate.value || null, Array.isArray(modelValue.value) ? modelValue.value[0] : null, ) : true)) || (isDateEqual(day.value, Array.isArray(modelValue.value) ? modelValue.value[0] : null) && checkRangeDirection(isStart)) ); } return false; }; const isHoverDate = (disabled: boolean, calendarDay: ICalendarDay) => { return Array.isArray(props.internalModelValue) && props.internalModelValue.length ? false : !disabled && !isActiveDate(calendarDay) && !(!calendarDay.current && props.hideOffsetDates) && (props.range ? !rangeActiveStartEnd(calendarDay) && !rangeActiveStartEnd(calendarDay, false) : true); }; const isHoverDateStartEnd = (dateIsHovered: boolean, calendarDay: ICalendarDay, start?: boolean): boolean => { if ( Array.isArray(props.internalModelValue) && props.internalModelValue[0] && props.internalModelValue.length === 1 ) { if (dateIsHovered) { return false; } return start ? isDateAfter(props.internalModelValue[0], calendarDay.value) : isDateBefore(props.internalModelValue[0], calendarDay.value); } return false; }; const monthYearSelect = (isYear = false) => { if (props.autoApply && props.monthPicker) { emit('autoApply', isYear); } }; const autoChangeMonth = (increment: number, isNext: boolean) => { const yearMonth: [number, number] = isNext ? [monthNext.value, yearNext.value] : [month.value, year.value]; const dates = increment < 0 ? getNextYearMonth(...yearMonth) : getPreviousMonthYear(...yearMonth); updateMonthYear(dates.month, true, isNext); updateMonthYear(dates.year, false, isNext); }; const handleScroll = (event: WheelEvent, isNext = false): void => { if (props.monthChangeOnScroll) { autoChangeMonth(props.monthChangeOnScroll === 'inverse' ? -event.deltaY : event.deltaY, isNext); } }; const handleArrow = (arrow: 'left' | 'right', isNext = false): void => { if (props.monthChangeOnArrows) { autoChangeMonth(arrow === 'right' ? -1 : 1, isNext); } }; const getMarker = (date: UnwrapRef<ICalendarDay>): IMarker | undefined => props.markers.find((marker) => isDateEqual(sanitizeDate(new Date(date.value)), sanitizeDate(new Date(marker.date))), ); const selectCurrentDate = (): void => { if (!props.range) { emit('update:internalModelValue', new Date()); } else if (modelValueIsRange(modelValue.value, props.range)) { if (modelValue.value && modelValue.value[0]) { modelValue.value = isDateBefore(new Date(), modelValue.value[0]) ? [new Date(), modelValue.value[0]] : [modelValue.value[0], new Date()]; } else { modelValue.value = [new Date()]; } } if (props.autoApply) { emit('selectDate'); } }; return { today, hours, month, year, monthNext, yearNext, minutes, seconds, monthYearSelect, isDisabled, updateTime, setHoverDate, getWeekNum, selectDate, rangeActive, isActiveDate, updateMonthYear, isHoverRangeEnd, isAutoRangeInBetween, isAutoRangeStart, clearHoverDate, rangeActiveStartEnd, handleScroll, getMarker, handleArrow, selectCurrentDate, isHoverDate, isHoverDateStartEnd, }; };
the_stack
export * from 'libsodium-wrappers'; import { KeyPair, StateAddress, StringKeyPair, StringOutputFormat, Uint8ArrayOutputFormat, } from 'libsodium-wrappers'; export const crypto_auth_hmacsha256_BYTES: number; export const crypto_auth_hmacsha256_KEYBYTES: number; export const crypto_auth_hmacsha512_BYTES: number; export const crypto_auth_hmacsha512_KEYBYTES: number; export const crypto_box_curve25519xchacha20poly1305_NONCEBYTES: number; export const crypto_box_curve25519xchacha20poly1305_PUBLICKEYBYTES: number; export const crypto_box_curve25519xchacha20poly1305_SECRETKEYBYTES: number; export const crypto_core_hchacha20_CONSTBYTES: number; export const crypto_core_hchacha20_INPUTBYTES: number; export const crypto_core_hchacha20_KEYBYTES: number; export const crypto_core_hchacha20_OUTPUTBYTES: number; export const crypto_core_ristretto255_BYTES: number; export const crypto_core_ristretto255_HASHBYTES: number; export const crypto_core_ristretto255_NONREDUCEDSCALARBYTES: number; export const crypto_core_ristretto255_SCALARBYTES: number; export const crypto_generichash_blake2b_BYTES_MAX: number; export const crypto_generichash_blake2b_BYTES_MIN: number; export const crypto_generichash_blake2b_BYTES: number; export const crypto_generichash_blake2b_KEYBYTES_MAX: number; export const crypto_generichash_blake2b_KEYBYTES_MIN: number; export const crypto_generichash_blake2b_KEYBYTES: number; export const crypto_generichash_blake2b_PERSONALBYTES: number; export const crypto_generichash_blake2b_SALTBYTES: number; export const crypto_hash_sha256_BYTES: number; export const crypto_hash_sha512_BYTES: number; export const crypto_onetimeauth_BYTES: number; export const crypto_onetimeauth_KEYBYTES: number; export const crypto_pwhash_scryptsalsa208sha256_BYTES_MAX: number; export const crypto_pwhash_scryptsalsa208sha256_BYTES_MIN: number; export const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE: number; export const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MAX: number; export const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_MIN: number; export const crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_SENSITIVE: number; export const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE: number; export const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MAX: number; export const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_MIN: number; export const crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_SENSITIVE: number; export const crypto_pwhash_scryptsalsa208sha256_SALTBYTES: number; export const crypto_pwhash_scryptsalsa208sha256_STR_VERIFY: number; export const crypto_pwhash_scryptsalsa208sha256_STRBYTES: number; export const crypto_pwhash_scryptsalsa208sha256_STRPREFIX: string; export const crypto_scalarmult_ristretto255_BYTES: number; export const crypto_scalarmult_ristretto255_SCALARBYTES: number; export const crypto_shorthash_siphashx24_BYTES: number; export const crypto_shorthash_siphashx24_KEYBYTES: number; export const crypto_stream_chacha20_ietf_KEYBYTES: number; export const crypto_stream_chacha20_ietf_MESSAGEBYTES_MAX: number; export const crypto_stream_chacha20_ietf_NONCEBYTES: number; export const crypto_stream_chacha20_KEYBYTES: number; export const crypto_stream_chacha20_NONCEBYTES: number; export const crypto_stream_KEYBYTES: number; export const crypto_stream_MESSAGEBYTES_MAX: number; export const crypto_stream_NONCEBYTES: number; export const crypto_stream_xchacha20_KEYBYTES: number; export const crypto_stream_xchacha20_MESSAGEBYTES_MAX: number; export const crypto_stream_xchacha20_NONCEBYTES: number; export function crypto_auth_hmacsha256(message: string | Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_auth_hmacsha256(message: string | Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_auth_hmacsha256_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_auth_hmacsha256_keygen(outputFormat: StringOutputFormat): string; export function crypto_auth_hmacsha256_verify(tag: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean; export function crypto_auth_hmacsha512(message: string | Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_auth_hmacsha512(message: string | Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_auth_hmacsha512_keygen(outputFormat: StringOutputFormat): string; export function crypto_auth_hmacsha512_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_auth_hmacsha512_verify(tag: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean; export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat: StringOutputFormat): StringKeyPair; export function crypto_box_curve25519xchacha20poly1305_keypair(publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): KeyPair; export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_box_curve25519xchacha20poly1305_seal(message: Uint8Array, publicKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_box_curve25519xchacha20poly1305_seal_open(ciphertext: Uint8Array, publicKey: Uint8Array, secretKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_add(p: Uint8Array, q: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_add(p: Uint8Array, q: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_from_hash(r: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_from_hash(r: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_is_valid_point(point: string | Uint8Array): boolean; export function crypto_core_ristretto255_random(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_random(outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_add(x: Uint8Array, y: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_add(x: Uint8Array, y: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_complement(scalar: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_complement(scalar: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_invert(scalar: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_invert(scalar: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_mul(x: Uint8Array, y: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_mul(x: Uint8Array, y: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_negate(scalar: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_negate(scalar: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_random(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_random(outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_reduce(secret: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_reduce(secret: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_scalar_sub(x: Uint8Array, y: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_scalar_sub(x: Uint8Array, y: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_core_ristretto255_sub(p: Uint8Array, q: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_core_ristretto255_sub(p: Uint8Array, q: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_generichash_blake2b_salt_personal(subkey_len: number, key: string | Uint8Array | null, id: Uint8Array, ctx: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_generichash_blake2b_salt_personal(subkey_len: number, key: string | Uint8Array | null, id: Uint8Array, ctx: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_hash_sha256(message: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_hash_sha256(message: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_hash_sha512(message: string | Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_hash_sha512(message: string | Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_onetimeauth(message: string | Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_onetimeauth(message: string | Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_onetimeauth_final(state_address: StateAddress, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_onetimeauth_final(state_address: StateAddress, outputFormat: StringOutputFormat): string; export function crypto_onetimeauth_init(key?: string | Uint8Array | null): StateAddress; export function crypto_onetimeauth_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_onetimeauth_keygen(outputFormat: StringOutputFormat): string; export function crypto_onetimeauth_update(state_address: StateAddress, message_chunk: string | Uint8Array): void; export function crypto_onetimeauth_verify(hash: Uint8Array, message: string | Uint8Array, key: Uint8Array): boolean; export function crypto_pwhash_scryptsalsa208sha256(keyLength: number, password: string | Uint8Array, salt: Uint8Array, opsLimit: number, memLimit: number, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_pwhash_scryptsalsa208sha256(keyLength: number, password: string | Uint8Array, salt: Uint8Array, opsLimit: number, memLimit: number, outputFormat: StringOutputFormat): string; export function crypto_pwhash_scryptsalsa208sha256_ll(password: string | Uint8Array, salt: string | Uint8Array, opsLimit: number, r: number, p: number, keyLength: number, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_pwhash_scryptsalsa208sha256_ll(password: string | Uint8Array, salt: string | Uint8Array, opsLimit: number, r: number, p: number, keyLength: number, outputFormat: StringOutputFormat, ): string; export function crypto_pwhash_scryptsalsa208sha256_str(password: string | Uint8Array, opsLimit: number, memLimit: number): string; export function crypto_pwhash_scryptsalsa208sha256_str_verify(hashed_password: string, password: string | Uint8Array): boolean; export function crypto_scalarmult_ristretto255(scalar: Uint8Array, point: Uint8Array): Uint8Array; export function crypto_scalarmult_ristretto255_base(scalar: Uint8Array): Uint8Array; export function crypto_shorthash_siphashx24(message: string | Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_shorthash_siphashx24(message: string | Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_sign_ed25519_sk_to_pk(privateKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_sign_ed25519_sk_to_pk(privateKey: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_sign_ed25519_sk_to_seed(privateKey: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_sign_ed25519_sk_to_seed(privateKey: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20(outLength: number, key: Uint8Array, nonce: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_chacha20_ietf_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_chacha20_ietf_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20_ietf_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_stream_chacha20_ietf_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_chacha20_keygen(outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_chacha20_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_chacha20_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_stream_chacha20_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_keygen(outputFormat: StringOutputFormat): string; export function crypto_stream_xchacha20_keygen(outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_xchacha20_keygen(outputFormat: StringOutputFormat): string; export function crypto_stream_xchacha20_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null): Uint8Array; export function crypto_stream_xchacha20_xor(input_message: string | Uint8Array, nonce: Uint8Array, key: Uint8Array, outputFormat: StringOutputFormat): string; export function crypto_stream_xchacha20_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat?: Uint8ArrayOutputFormat | null, ): Uint8Array; export function crypto_stream_xchacha20_xor_ic(input_message: string | Uint8Array, nonce: Uint8Array, nonce_increment: number, key: Uint8Array, outputFormat: StringOutputFormat): string;
the_stack
import CLASS from './class' import { ChartInternal } from './core' import { isDefined, isEmpty, getOption } from './util' ChartInternal.prototype.initLegend = function() { var $$ = this $$.legendItemTextBox = {} $$.legendHasRendered = false $$.legend = $$.svg.append('g').attr('transform', $$.getTranslate('legend')) if (!$$.config.legend_show) { $$.legend.style('visibility', 'hidden') $$.hiddenLegendIds = $$.mapToIds($$.data.targets) return } // MEMO: call here to update legend box and tranlate for all // MEMO: translate will be updated by this, so transform not needed in updateLegend() $$.updateLegendWithDefaults() } ChartInternal.prototype.updateLegendWithDefaults = function() { var $$ = this $$.updateLegend($$.mapToIds($$.data.targets), { withTransform: false, withTransitionForTransform: false, withTransition: false }) } ChartInternal.prototype.updateSizeForLegend = function( legendHeight, legendWidth ) { var $$ = this, config = $$.config, insetLegendPosition = { top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y, left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5 } $$.margin3 = { top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight, right: NaN, bottom: 0, left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0 } } ChartInternal.prototype.transformLegend = function(withTransition) { var $$ = this ;(withTransition ? $$.legend.transition() : $$.legend).attr( 'transform', $$.getTranslate('legend') ) } ChartInternal.prototype.updateLegendStep = function(step) { this.legendStep = step } ChartInternal.prototype.updateLegendItemWidth = function(w) { this.legendItemWidth = w } ChartInternal.prototype.updateLegendItemHeight = function(h) { this.legendItemHeight = h } ChartInternal.prototype.getLegendWidth = function() { var $$ = this return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0 } ChartInternal.prototype.getLegendHeight = function() { var $$ = this, h = 0 if ($$.config.legend_show) { if ($$.isLegendRight) { h = $$.currentHeight } else { h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1) } } return h } ChartInternal.prototype.opacityForLegend = function(legendItem) { return legendItem.classed(CLASS.legendItemHidden) ? null : 1 } ChartInternal.prototype.opacityForUnfocusedLegend = function(legendItem) { return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3 } ChartInternal.prototype.toggleFocusLegend = function(targetIds, focus) { var $$ = this targetIds = $$.mapToTargetIds(targetIds) $$.legend .selectAll('.' + CLASS.legendItem) .filter(function(id) { return targetIds.indexOf(id) >= 0 }) .classed(CLASS.legendItemFocused, focus) .transition() .duration(100) .style('opacity', function() { var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend return opacity.call($$, $$.d3.select(this)) }) } ChartInternal.prototype.revertLegend = function() { var $$ = this, d3 = $$.d3 $$.legend .selectAll('.' + CLASS.legendItem) .classed(CLASS.legendItemFocused, false) .transition() .duration(100) .style('opacity', function() { return $$.opacityForLegend(d3.select(this)) }) } ChartInternal.prototype.showLegend = function(targetIds) { var $$ = this, config = $$.config if (!config.legend_show) { config.legend_show = true $$.legend.style('visibility', 'visible') if (!$$.legendHasRendered) { $$.updateLegendWithDefaults() } } $$.removeHiddenLegendIds(targetIds) $$.legend .selectAll($$.selectorLegends(targetIds)) .style('visibility', 'visible') .transition() .style('opacity', function() { return $$.opacityForLegend($$.d3.select(this)) }) } ChartInternal.prototype.hideLegend = function(targetIds) { var $$ = this, config = $$.config if (config.legend_show && isEmpty(targetIds)) { config.legend_show = false $$.legend.style('visibility', 'hidden') } $$.addHiddenLegendIds(targetIds) $$.legend .selectAll($$.selectorLegends(targetIds)) .style('opacity', 0) .style('visibility', 'hidden') } ChartInternal.prototype.clearLegendItemTextBoxCache = function() { this.legendItemTextBox = {} } ChartInternal.prototype.updateLegend = function( targetIds, options, transitions ) { var $$ = this, config = $$.config var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect, x1ForLegendTile, x2ForLegendTile, yForLegendTile var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = config.legend_item_tile_width + 5 var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0 var withTransition, withTransitionForTransform var texts, rects, tiles, background // Skip elements when their name is set to null targetIds = targetIds.filter(function(id) { return !isDefined(config.data_names[id]) || config.data_names[id] !== null }) options = options || {} withTransition = getOption(options, 'withTransition', true) withTransitionForTransform = getOption( options, 'withTransitionForTransform', true ) function getTextBox(textElement, id) { if (!$$.legendItemTextBox[id]) { $$.legendItemTextBox[id] = $$.getTextRect( textElement.textContent, CLASS.legendItem, textElement ) } return $$.legendItemTextBox[id] } function updatePositions(textElement, id, index) { var reset = index === 0, isLast = index === targetIds.length - 1, box = getTextBox(textElement, id), itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight) + config.legend_padding, itemHeight = box.height + paddingTop, itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth, areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(), margin, maxLength // MEMO: care about condifion of step, totalLength function updateValues(id, withoutStep?: boolean) { if (!withoutStep) { margin = (areaLength - totalLength - itemLength) / 2 if (margin < posMin) { margin = (areaLength - itemLength) / 2 totalLength = 0 step++ } } steps[id] = step margins[step] = $$.isLegendInset ? 10 : margin offsets[id] = totalLength totalLength += itemLength } if (reset) { totalLength = 0 step = 0 maxWidth = 0 maxHeight = 0 } if (config.legend_show && !$$.isLegendToShow(id)) { widths[id] = heights[id] = steps[id] = offsets[id] = 0 return } widths[id] = itemWidth heights[id] = itemHeight if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth } if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight } maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth if (config.legend_equally) { Object.keys(widths).forEach(function(id) { widths[id] = maxWidth }) Object.keys(heights).forEach(function(id) { heights[id] = maxHeight }) margin = (areaLength - maxLength * targetIds.length) / 2 if (margin < posMin) { totalLength = 0 step = 0 targetIds.forEach(function(id) { updateValues(id) }) } else { updateValues(id, true) } } else { updateValues(id) } } if ($$.isLegendInset) { step = config.legend_inset_step ? config.legend_inset_step : targetIds.length $$.updateLegendStep(step) } if ($$.isLegendRight) { xForLegend = function(id) { return maxWidth * steps[id] } yForLegend = function(id) { return margins[steps[id]] + offsets[id] } } else if ($$.isLegendInset) { xForLegend = function(id) { return maxWidth * steps[id] + 10 } yForLegend = function(id) { return margins[steps[id]] + offsets[id] } } else { xForLegend = function(id) { return margins[steps[id]] + offsets[id] } yForLegend = function(id) { return maxHeight * steps[id] } } xForLegendText = function(id, i) { return xForLegend(id, i) + 4 + config.legend_item_tile_width } yForLegendText = function(id, i) { return yForLegend(id, i) + 9 } xForLegendRect = function(id, i) { return xForLegend(id, i) } yForLegendRect = function(id, i) { return yForLegend(id, i) - 5 } x1ForLegendTile = function(id, i) { return xForLegend(id, i) - 2 } x2ForLegendTile = function(id, i) { return xForLegend(id, i) - 2 + config.legend_item_tile_width } yForLegendTile = function(id, i) { return yForLegend(id, i) + 4 } // Define g for legend area l = $$.legend .selectAll('.' + CLASS.legendItem) .data(targetIds) .enter() .append('g') .attr('class', function(id) { return $$.generateClass(CLASS.legendItem, id) }) .style('visibility', function(id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden' }) .style('cursor', function() { return config.interaction_enabled ? 'pointer' : 'auto' }) .on( 'click', config.interaction_enabled ? function(id) { if (config.legend_item_onclick) { config.legend_item_onclick.call($$, id) } else { if ($$.d3.event.altKey) { $$.api.hide() $$.api.show(id) } else { $$.api.toggle(id) $$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert() } } } : null ) .on( 'mouseover', config.interaction_enabled ? function(id) { if (config.legend_item_onmouseover) { config.legend_item_onmouseover.call($$, id) } else { $$.d3.select(this).classed(CLASS.legendItemFocused, true) if (!$$.transiting && $$.isTargetToShow(id)) { $$.api.focus(id) } } } : null ) .on( 'mouseout', config.interaction_enabled ? function(id) { if (config.legend_item_onmouseout) { config.legend_item_onmouseout.call($$, id) } else { $$.d3.select(this).classed(CLASS.legendItemFocused, false) $$.api.revert() } } : null ) l.append('text') .text(function(id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id }) .each(function(id, i) { updatePositions(this, id, i) }) .style('pointer-events', 'none') .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200) .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText) l.append('rect') .attr('class', CLASS.legendItemEvent) .style('fill-opacity', 0) .attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200) .attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect) l.append('line') .attr('class', CLASS.legendItemTile) .style('stroke', $$.color) .style('pointer-events', 'none') .attr('x1', $$.isLegendRight || $$.isLegendInset ? x1ForLegendTile : -200) .attr('y1', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile) .attr('x2', $$.isLegendRight || $$.isLegendInset ? x2ForLegendTile : -200) .attr('y2', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendTile) .attr('stroke-width', config.legend_item_tile_height) // Set background for inset legend background = $$.legend.select('.' + CLASS.legendBackground + ' rect') if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) { background = $$.legend .insert('g', '.' + CLASS.legendItem) .attr('class', CLASS.legendBackground) .append('rect') } texts = $$.legend .selectAll('text') .data(targetIds) .text(function(id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id }) // MEMO: needed for update .each(function(id, i) { updatePositions(this, id, i) }) ;(withTransition ? texts.transition() : texts) .attr('x', xForLegendText) .attr('y', yForLegendText) rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent).data(targetIds) ;(withTransition ? rects.transition() : rects) .attr('width', function(id) { return widths[id] }) .attr('height', function(id) { return heights[id] }) .attr('x', xForLegendRect) .attr('y', yForLegendRect) tiles = $$.legend.selectAll('line.' + CLASS.legendItemTile).data(targetIds) ;(withTransition ? tiles.transition() : tiles) .style( 'stroke', $$.levelColor ? function(id) { return $$.levelColor( $$.cache[id].values.reduce(function(total, item) { return total + item.value }, 0) ) } : $$.color ) .attr('x1', x1ForLegendTile) .attr('y1', yForLegendTile) .attr('x2', x2ForLegendTile) .attr('y2', yForLegendTile) if (background) { ;(withTransition ? background.transition() : background) .attr('height', $$.getLegendHeight() - 12) .attr('width', maxWidth * (step + 1) + 10) } // toggle legend state $$.legend .selectAll('.' + CLASS.legendItem) .classed(CLASS.legendItemHidden, function(id) { return !$$.isTargetToShow(id) }) // Update all to reflect change of legend $$.updateLegendItemWidth(maxWidth) $$.updateLegendItemHeight(maxHeight) $$.updateLegendStep(step) // Update size and scale $$.updateSizes() $$.updateScales() $$.updateSvgSize() // Update g positions $$.transformAll(withTransitionForTransform, transitions) $$.legendHasRendered = true }
the_stack
import { expect } from "chai"; import { Observable } from "rxjs/internal/Observable"; import * as sinon from "sinon"; import * as moq from "typemoq"; import { IModelConnection } from "@itwin/core-frontend"; import { PropertyRecord, PropertyValueFormat } from "@itwin/appui-abstract"; import { DelayLoadedTreeNodeItem, MutableTreeModel, TreeModelNodeInput, TreeModelSource } from "@itwin/components-react"; import { reloadTree } from "../../../presentation-components/tree/controlled/TreeReloader"; import { IPresentationTreeDataProvider } from "../../../presentation-components/tree/IPresentationTreeDataProvider"; describe("reloadTree", () => { let dataProvider: IPresentationTreeDataProvider; beforeEach(() => { dataProvider = { imodel: moq.Mock.ofType<IModelConnection>().object, rulesetId: "", getNodeKey: () => ({ type: "", version: 0, pathFromRoot: [] }), getFilteredNodePaths: async () => [], getNodesCount: async () => 3, getNodes: async (parent, page) => [createDelayLoadedTreeNodeItem(`${parent?.id ?? "root"}-${page?.start}`)], dispose: () => { }, }; }); it("loads first root node page", async () => { const initialTreeModel = new MutableTreeModel(); const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.undefined; expect(rootNodes.get(2)).to.be.undefined; }); it("loads first page in expanded nodes", async () => { const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren( undefined, [createTreeModelNodeInput("root-0"), createTreeModelNodeInput("root-1"), createTreeModelNodeInput("root-2")], 0, ); initialTreeModel.setChildren( "root-0", [createTreeModelNodeInput("root-0-0"), createTreeModelNodeInput("root-0-1")], 0, ); initialTreeModel.getNode("root-0")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.undefined; expect(rootNodes.get(2)).to.be.undefined; expect(treeModel.getNode("root-0")!.isExpanded).to.be.true; const childNodes = treeModel.getChildren("root-0")!; expect(childNodes.getLength()).to.be.equal(3); expect(childNodes.get(0)).to.be.equal("root-0-0"); expect(childNodes.get(1)).to.be.undefined; expect(childNodes.get(2)).to.be.undefined; }); it("looks for an expanded node at its original place", async () => { const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren( undefined, [createTreeModelNodeInput("root-0"), createTreeModelNodeInput("root-1"), createTreeModelNodeInput("root-2")], 0, ); initialTreeModel.setChildren( "root-1", [createTreeModelNodeInput("root-1-0"), createTreeModelNodeInput("root-1-1")], 0, ); initialTreeModel.getNode("root-1")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.equal("root-1"); expect(rootNodes.get(2)).to.be.undefined; expect(treeModel.getNode("root-1")!.isExpanded).to.be.true; const childNodes = treeModel.getChildren("root-1")!; expect(childNodes.getLength()).to.be.equal(3); expect(childNodes.get(0)).to.be.equal("root-1-0"); expect(childNodes.get(1)).to.be.undefined; expect(childNodes.get(2)).to.be.undefined; }); it("looks for an expanded node a page before its original position", async () => { // Simulating root-1 node moving from second to first index after the update const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren(undefined, [createTreeModelNodeInput("root-0")], 0); initialTreeModel.setChildren(undefined, [createTreeModelNodeInput("root-1")], 2); initialTreeModel.setChildren( "root-1", [createTreeModelNodeInput("root-1-0"), createTreeModelNodeInput("root-1-1")], 0, ); initialTreeModel.getNode("root-1")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.equal("root-1"); expect(rootNodes.get(2)).to.be.equal("root-2"); expect(treeModel.getNode("root-1")!.isExpanded).to.be.true; const childNodes = treeModel.getChildren("root-1")!; expect(childNodes.getLength()).to.be.equal(3); expect(childNodes.get(0)).to.be.equal("root-1-0"); expect(childNodes.get(1)).to.be.undefined; expect(childNodes.get(2)).to.be.undefined; }); it("looks for an expanded node a page after its original position", async () => { // Simulating root-2 node moving from frist to second index after the update const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren( undefined, [createTreeModelNodeInput("root-0"), createTreeModelNodeInput("root-2")], 0, ); initialTreeModel.getNode("root-2")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.equal("root-1"); expect(rootNodes.get(2)).to.be.equal("root-2"); expect(treeModel.getNode("root-2")!.isExpanded).to.be.true; const childNodes = treeModel.getChildren("root-2")!; expect(childNodes.getLength()).to.be.equal(3); expect(childNodes.get(0)).to.be.equal("root-2-0"); expect(childNodes.get(1)).to.be.undefined; expect(childNodes.get(2)).to.be.undefined; }); it("handles not being able to find the expanded node", async () => { // Simulating root-3 node being replaced with root-1 node const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren( undefined, [createTreeModelNodeInput("root-0"), createTreeModelNodeInput("root-3"), createTreeModelNodeInput("root-2")], 0, ); initialTreeModel.setChildren( "root-3", [createTreeModelNodeInput("root-3-0"), createTreeModelNodeInput("root-3-1")], 0, ); initialTreeModel.getNode("root-3")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.equal("root-1"); expect(rootNodes.get(2)).to.be.equal("root-2"); expect(treeModel.getNode("root-1")!.isExpanded).to.be.false; expect(treeModel.getChildren("root-1")).to.be.undefined; }); it("handles failure to retrieve parent node's child count", async () => { // Simulate receiving `undefined` child count on root-0 dataProvider.getNodesCount = async (parent) => parent === undefined ? 3 : undefined as any; const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren( undefined, [createTreeModelNodeInput("root-0"), createTreeModelNodeInput("root-1"), createTreeModelNodeInput("root-2")], 0, ); initialTreeModel.setChildren("root-0", [createTreeModelNodeInput("root-0-0")], 0); initialTreeModel.setChildren("root-0-0", [createTreeModelNodeInput("root-0-0-0")], 0); initialTreeModel.getNode("root-0")!.isExpanded = true; initialTreeModel.getNode("root-0-0")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(3); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(rootNodes.get(1)).to.be.undefined; expect(rootNodes.get(2)).to.be.undefined; expect(treeModel.getNode("root-0")!.numChildren).to.be.undefined; expect(treeModel.getNode("root-0")!.isExpanded).to.be.false; }); it("does not search for expanded nodes if parent no longer has any children", async () => { const getNodesFake = sinon.fake(async () => [{ ...createTreeModelNodeInput("root-0"), item: { ...createDelayLoadedTreeNodeItem("root-0"), hasChildren: false }, }]); dataProvider.getNodes = getNodesFake; dataProvider.getNodesCount = async () => 1; const initialTreeModel = new MutableTreeModel(); initialTreeModel.setChildren(undefined, [createTreeModelNodeInput("root-0")], 0); initialTreeModel.getNode("root-0")!.isExpanded = true; initialTreeModel.setChildren("root-0", [createTreeModelNodeInput("root-0-0")], 0); initialTreeModel.getNode("root-0-0")!.isExpanded = true; const modelSource = await waitForReload(reloadTree(initialTreeModel, dataProvider, 1)); const treeModel = modelSource.getModel(); expect(getNodesFake).to.have.been.calledOnce; const rootNodes = treeModel.getChildren(undefined)!; expect(rootNodes.getLength()).to.be.equal(1); expect(rootNodes.get(0)).to.be.equal("root-0"); expect(treeModel.getNode("root-0")!.isExpanded).to.be.false; }); function createTreeModelNodeInput(id: string): TreeModelNodeInput { return { id, isExpanded: false, isLoading: false, isSelected: false, item: createDelayLoadedTreeNodeItem(id), label: createPropertyRecord(id), }; } function createDelayLoadedTreeNodeItem(id: string): DelayLoadedTreeNodeItem { return { id, label: createPropertyRecord(id), hasChildren: true }; } function createPropertyRecord(value: string): PropertyRecord { return new PropertyRecord( { valueFormat: PropertyValueFormat.Primitive, value }, { name: value, typename: value, displayLabel: value }, ); } async function waitForReload(observable: Observable<TreeModelSource>): Promise<TreeModelSource> { return new Promise((resolve, reject) => { let numEmissions = 0; let lastEmission: TreeModelSource | undefined; observable.subscribe({ next: (modelSource) => { ++numEmissions; lastEmission = modelSource; }, error: reject, complete: () => { expect(numEmissions).to.be.equal(1); resolve(lastEmission!); }, }); }); } });
the_stack
import { Analyzer, StandardAnalyzer, analyze } from "./analyzer/analyzer"; /** * Converts a string into an array of code points. * @param str - the string * @returns {number[]} to code points * @hidden */ export function toCodePoints(str: string): number[] { const r = []; for (let i = 0; i < str.length;) { const chr = str.charCodeAt(i++); if (chr >= 0xD800 && chr <= 0xDBFF) { // surrogate pair const low = str.charCodeAt(i++); r.push(0x10000 + ((chr - 0xD800) << 10) | (low - 0xDC00)); } else { // ordinary character r.push(chr); } } return r; } /** * Inverted index class handles featured text search for specific document fields. * @hidden */ export class InvertedIndex { public analyzer: Analyzer; public docCount: number = 0; public docStore: Map<InvertedIndex.DocumentIndex, InvertedIndex.DocStore> = new Map(); public totalFieldLength: number = 0; public root: InvertedIndex.Index = new Map(); private _store: boolean; private _optimizeChanges: boolean; /** * @param {boolean} [options.store=true] - inverted index will be stored at serialization rather than rebuilt on load * @param {boolean} [options.optimizeChanges=true] - flag to store additional metadata inside the index for better * performance if an existing field is updated or removed * @param {Analyzer} [options.analyzer=] - the analyzer of this inverted index */ constructor(options: InvertedIndex.FieldOptions = {}) { ( { store: this._store = true, optimizeChanges: this._optimizeChanges = true, analyzer: this.analyzer = new StandardAnalyzer() } = options ); } /** * Adds defined fields of a document to the inverted index. * @param {string} field - the field to add * @param {number} docId - the doc id of the field */ public insert(field: string, docId: InvertedIndex.DocumentIndex): void { if (this.docStore.has(docId)) { throw Error("Field already added."); } // Tokenize document field. const fieldTokens = analyze(this.analyzer, field); if (fieldTokens.length == 0) { // Add empty field at least to document store for query 'exists'. this.docStore.set(docId, {fieldLength: 0}); return; } this.totalFieldLength += fieldTokens.length; this.docCount += 1; this.docStore.set(docId, {fieldLength: fieldTokens.length}); // Holds references to each index of a document. const indexRef: InvertedIndex.Index[] = []; if (this._optimizeChanges) { Object.defineProperties(this.docStore.get(docId), { indexRef: {enumerable: false, configurable: true, writable: true, value: indexRef} }); } // Iterate over all unique field terms. for (const token of new Set(fieldTokens)) { // Calculate term frequency. let tf = 0; for (let j = 0; j < fieldTokens.length; j++) { if (fieldTokens[j] === token) { ++tf; } } // Add term to index tree. let branch = this.root; for (const c of toCodePoints(token)) { let child = branch.get(c); if (child === undefined) { child = new Map(); if (this._optimizeChanges) { child.pa = branch; } branch.set(c, child); } branch = child; } // Add term info to index leaf. if (branch.dc === undefined) { branch.dc = new Map(); branch.df = 0; } branch.dc.set(docId, tf); branch.df += 1; // Store index leaf for deletion. indexRef.push(branch); } } /** * Removes all relevant terms of a document from the inverted index. * @param {number} docId - the document. */ public remove(docId: InvertedIndex.DocumentIndex): void { if (!this.docStore.has(docId)) { return; } const docStore = this.docStore.get(docId); // Remove document. this.docStore.delete(docId); if (docStore.fieldLength === 0) { return; } this.docCount -= 1; // Reduce total field length. this.totalFieldLength -= docStore.fieldLength; if (this._optimizeChanges) { // Iterate over all term references. // Remove docId from docs and decrement document frequency. const indexRef = docStore.indexRef; for (let j = 0; j < indexRef.length; j++) { let index = indexRef[j]; index.df -= 1; index.dc.delete(docId); // Check if no document is left for current tree. if (index.df === 0) { // Delete unused meta data of branch. delete index.df; delete index.dc; // Check for sub branches. if (index.size !== 0) { continue; } // Delete term branch if not used anymore. do { // Go tree upwards. const parent = index.pa; // Delete parent reference for preventing memory leak (cycle reference). delete index.pa; // Iterate over all children. for (const key of parent.keys()) { // Remove previous child form parent. if (parent.get(key) === index) { parent.delete(key); break; } } index = parent; } while (index.pa !== undefined && index.size === 0 && index.df === undefined); } } } else { this._remove(this.root, docId); } } /** * Gets the term index of a term. * @param {string} term - the term * @param {object} root - the term index to start from * @param {number} start - the position of the term string to start from * @return {object} - The term index or null if the term is not in the term tree. */ public static getTermIndex(term: number[], root: InvertedIndex.Index, start: number = 0): InvertedIndex.Index { if (start >= term.length) { return null; } for (let i = start; i < term.length; i++) { let child = root.get(term[i]); if (child === undefined) { return null; } root = child; } return root; } /** * Extends a term index to all available term leafs. * @param {object} idx - the term index to start from * @param {number[]} [term=[]] - the current term * @param {Array} termIndices - all extended indices with their term * @returns {Array} - Array with term indices and extension */ public static extendTermIndex(idx: InvertedIndex.Index, term: number[] = [], termIndices: InvertedIndex.IndexTerm[] = []): InvertedIndex.IndexTerm[] { if (idx.df !== undefined) { termIndices.push({index: idx, term: term.slice()}); } term.push(0); for (const child of idx) { term[term.length - 1] = child[0]; InvertedIndex.extendTermIndex(child[1], term, termIndices); } term.pop(); return termIndices; } /** * Serialize the inverted index. * @returns {{docStore: *, _fields: *, index: *}} */ public toJSON(): InvertedIndex.Serialization { if (this._store) { return { _store: true, _optimizeChanges: this._optimizeChanges, docCount: this.docCount, docStore: [...this.docStore], totalFieldLength: this.totalFieldLength, root: InvertedIndex._serializeIndex(this.root) }; } return { _store: false, _optimizeChanges: this._optimizeChanges, }; } /** * Deserialize the inverted index. * @param {{docStore: *, _fields: *, index: *}} serialized - The serialized inverted index. * @param {Analyzer} analyzer[undefined] - an analyzer */ public static fromJSONObject(serialized: InvertedIndex.Serialization, analyzer?: Analyzer): InvertedIndex { const invIdx = new InvertedIndex({ store: serialized._store, optimizeChanges: serialized._optimizeChanges, analyzer: analyzer }); if (serialized._store) { invIdx.docCount = serialized.docCount; invIdx.docStore = new Map(serialized.docStore); invIdx.totalFieldLength = serialized.totalFieldLength; invIdx.root = InvertedIndex._deserializeIndex(serialized.root); } if (invIdx._optimizeChanges) { invIdx._regenerate(invIdx.root, null); } return invIdx; } private static _serializeIndex(idx: InvertedIndex.Index): InvertedIndex.SerializedIndex { const serialized: InvertedIndex.SerializedIndex = {}; if (idx.dc !== undefined) { serialized.d = {df: idx.df, dc: [...idx.dc]}; } if (idx.size === 0) { return serialized; } const keys = []; const values = []; for (const child of idx) { keys.push(child[0]); values.push(InvertedIndex._serializeIndex(child[1])); } serialized.k = keys; serialized.v = values; return serialized; } private static _deserializeIndex(serialized: InvertedIndex.SerializedIndex): InvertedIndex.Index { const idx: InvertedIndex.Index = new Map(); if (serialized.k !== undefined) { for (let i = 0; i < serialized.k.length; i++) { idx.set(serialized.k[i], InvertedIndex._deserializeIndex(serialized.v[i])); } } if (serialized.d !== undefined) { idx.df = serialized.d.df; idx.dc = new Map(serialized.d.dc); } return idx; } /** * Set parent of to each index and regenerate the indexRef. * @param {Index} index - the index * @param {Index} parent - the parent */ private _regenerate(index: InvertedIndex.Index, parent: InvertedIndex.Index): void { // Set parent. if (parent !== null) { index.pa = parent; } // Iterate over subtree. for (const child of index.values()) { this._regenerate(child, index); } if (index.dc !== undefined) { // Get documents of term. for (const docId of index.dc.keys()) { // Get document store at specific document/field. const ref = this.docStore.get(docId); if (ref.indexRef === undefined) { Object.defineProperties(ref, { indexRef: {enumerable: false, configurable: true, writable: true, value: []} }); } // Set reference to term index. ref.indexRef.push(index); } } } /** * Iterate over the whole inverted index and remove the document. * Delete branch if not needed anymore. * Function is needed if index is used without optimization. * @param {Index} idx - the index * @param {number} docId - the doc id * @returns {boolean} true if index is empty */ private _remove(idx: InvertedIndex.Index, docId: InvertedIndex.DocumentIndex): boolean { for (const child of idx) { // Checkout branch. if (this._remove(child[1], docId)) { idx.delete(child[0]); } } // Remove docId from docs and decrement document frequency. if (idx.df !== undefined) { if (idx.dc.has(docId)) { idx.df -= 1; idx.dc.delete(docId); // Delete unused meta data of branch. if (idx.df === 0) { delete idx.df; delete idx.dc; } } } return idx.size === 0 && idx.dc === undefined; } } export namespace InvertedIndex { export interface FieldOptions { store?: boolean; optimizeChanges?: boolean; analyzer?: Analyzer; } export type Index = Map<number, any> & { dc?: Map<DocumentIndex, number>, df?: number, pa?: Index }; export type IndexTerm = { index: Index, term: number[] }; export interface SerializedIndex { d?: { df: number; dc: [DocumentIndex, number][] }; k?: number[]; v?: SerializedIndex[]; } export type Serialization = SpareSerialization | FullSerialization; export type SpareSerialization = { _store: false; _optimizeChanges: boolean; }; export type FullSerialization = { _store: true; _optimizeChanges: boolean; docCount: number; docStore: [DocumentIndex, DocStore][]; totalFieldLength: number; root: SerializedIndex; }; export interface DocStore { fieldLength?: number; indexRef?: Index[]; } export type DocumentIndex = number | string; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreSitePublicConfigResponse } from '@classes/site'; import { CoreApp } from '@services/app'; import { CoreSites } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { Md5 } from 'ts-md5'; import { CoreLogger } from '../../../singletons/logger'; /** * Interface that all style handlers must implement. */ export interface CoreStyleHandler { /** * Source name. */ name: string; /** * Priority of application. */ priority: number; /** * Wether the handler should be enabled for the site. * * @param siteId Site Id. * @param config Site public config for temp sites. * @return Wether the handler should be enabled for the site. */ isEnabled(siteId: string, config?: CoreSitePublicConfigResponse): boolean | Promise<boolean>; /** * Get the style for the site. * * @param siteId Site Id. * @param config Site public config for temp sites. * @return CSS to apply. */ getStyle(siteId?: string, config?: CoreSitePublicConfigResponse): string | Promise<string>; } /** * Singleton with helper functions to style the app. */ @Injectable({ providedIn: 'root' }) export class CoreStylesService { protected logger: CoreLogger; protected stylesEls: { [siteId: string]: { [sourceName: string]: string; // Hashes }; } = {}; protected styleHandlers: CoreStyleHandler[] = []; static readonly TMP_SITE_ID = 'tmpsite'; constructor() { this.logger = CoreLogger.getInstance('CoreStyles'); } /** * Initialize styles. */ async initialize(): Promise<void> { this.listenEvents(); // Preload the current site styles first, we want this to be fast. await this.preloadCurrentSite(); // Preload the styles of the rest of sites. await this.preloadSites(); } /** * Register a new style handler. * * @param styleHandler Style handler to be registered. */ registerStyleHandler(styleHandler: CoreStyleHandler): void { this.styleHandlers.push(styleHandler); // Sort them by priority, greatest go last because style loaded last it's more important. this.styleHandlers = this.styleHandlers.sort((a, b) => a.priority! >= b.priority! ? 1 : -1); } /** * Listen events. */ protected listenEvents(): void { let addingSite: string | undefined; // When a new site is added to the app, add its styles. CoreEvents.on(CoreEvents.SITE_ADDED, async (data) => { addingSite = data.siteId; try { await this.addSite(data.siteId); if (addingSite == data.siteId) { addingSite = undefined; } // User has logged in, remove tmp styles and enable loaded styles. if (data.siteId == CoreSites.getCurrentSiteId()) { this.unloadTmpStyles(); this.enableSiteStyles(data.siteId); } } catch (error) { this.logger.error('Error adding styles for new site', error); } }); // Update styles when current site is updated. CoreEvents.on(CoreEvents.SITE_UPDATED, (data) => { if (data.siteId === CoreSites.getCurrentSiteId()) { this.load(data.siteId).catch((error) => { this.logger.error('Error loading site after site update', error); }); } }); // Enable styles of current site on login. CoreEvents.on(CoreEvents.LOGIN, (data) => { this.unloadTmpStyles(); this.enableSiteStyles(data.siteId); }); // Disable added styles on logout. CoreEvents.on(CoreEvents.LOGOUT, () => { this.clear(); }); // Remove site styles when a site is deleted. CoreEvents.on(CoreEvents.SITE_DELETED, (site) => { this.removeSite(site.getId()); }); // Load temporary styles when site config is checked in login. CoreEvents.on(CoreEvents.LOGIN_SITE_CHECKED, (data) => { this.loadTmpStyles(data.config).catch((error) => { this.logger.error('Error loading tmp styles', error); }); }); // Unload temporary styles when site config is "unchecked" in login. CoreEvents.on(CoreEvents.LOGIN_SITE_UNCHECKED, (data) => { if (data.siteId && data.siteId === addingSite) { // The tmp styles are from a site that is being added permanently. // Wait for the final site styles to be loaded before removing the tmp styles so there is no blink effect. return; } // The tmp styles are from a site that wasn't added in the end. Just remove them. this.unloadTmpStyles(); }); } /** * Create a style element for a site. * * @param siteId Site Id. * @param disabled Whether the element should be disabled. */ protected createStyleElements(siteId: string, disabled: boolean): void { this.stylesEls[siteId] = {}; this.styleHandlers.forEach((handler) => { const styleElementId = this.getStyleId(siteId, handler.name); let styleEl: HTMLStyleElement | null = document.head.querySelector(`style#${styleElementId}`); if (!styleEl) { // Create the style and add it to the header. styleEl = document.createElement('style'); styleEl.setAttribute('id', styleElementId); this.disableStyleElement(styleEl, disabled); this.stylesEls[siteId][handler.name] = ''; document.head.appendChild(styleEl); } }); } /** * Set the content of an style element. * * @param siteId Site Id. * @param handler Style handler. * @param disabled Whether the element should be disabled. * @param config Site public config. * @return New element. */ protected async setStyle( siteId: string, handler: CoreStyleHandler, disabled: boolean, config?: CoreSitePublicConfigResponse, ): Promise<void> { let contents = ''; const enabled = await handler.isEnabled(siteId, config); if (enabled) { contents = (await handler.getStyle(siteId, config)).trim(); } const hash = <string>Md5.hashAsciiStr(contents); // Update the styles only if they have changed. if (this.stylesEls[siteId!][handler.name] === hash) { return; } const styleElementId = this.getStyleId(siteId, handler.name); const styleEl: HTMLStyleElement | null = document.head.querySelector(`style#${styleElementId}`); if (!styleEl) { this.stylesEls[siteId][handler.name] = ''; return; } styleEl.innerHTML = contents; this.stylesEls[siteId][handler.name] = hash; // Adding styles to a style element automatically enables it. Disable it again if needed. this.disableStyleElement(styleEl, disabled); } /** * Add a style element for a site and load the styles for that element. The style will be disabled. * * @param siteId Site ID. * @return Promise resolved when added and loaded. */ protected async addSite(siteId?: string): Promise<void> { if (!siteId || this.stylesEls[siteId]) { // Invalid site ID or style already added. return; } // Create the style and add it to the header. this.createStyleElements(siteId, true); try { await this.load(siteId, true); } catch (error) { this.logger.error('Error loading site after site init', error); } } /** * Clear styles added to the DOM, disabling them all. */ protected clear(): void { let styles: HTMLStyleElement[] = []; // Disable all the styles. this.styleHandlers.forEach((handler) => { styles = styles.concat(Array.from(document.querySelectorAll(`style[id*=${handler.name}]`))); }); styles.forEach((style) => { this.disableStyleElement(style, true); }); // Set StatusBar properties. CoreApp.setStatusBarColor(); } /** * Returns style element Id based on site and source. * * @param siteId Site Id. * @param sourceName Source or handler name. * @return Element Id. */ protected getStyleId(siteId: string, sourceName: string): string { return `${sourceName}-${siteId}`; } /** * Disabled an element based on site and source name. * * @param siteId Site Id. * @param sourceName Source or handler name. * @param disable Whether to disable or enable the element. */ protected disableStyleElementByName(siteId: string, sourceName: string, disable: boolean): void { const styleElementId = this.getStyleId(siteId, sourceName); const styleEl: HTMLStyleElement | null = document.head.querySelector(`style#${styleElementId}`); if (styleEl) { this.disableStyleElement(styleEl, disable); } } /** * Enabled or disable a certain style element. * * @param element The element to enable or disable. * @param disable Whether to disable or enable the element. */ protected disableStyleElement(element: HTMLStyleElement, disable: boolean): void { // Setting disabled should be enough, but we also set the attribute so it can be seen in the DOM which ones are disabled. // Cast to any because the HTMLStyleElement type doesn't define the disabled attribute. (<any> element).disabled = !!disable; // eslint-disable-line @typescript-eslint/no-explicit-any if (disable) { element.setAttribute('disabled', 'true'); } else { element.removeAttribute('disabled'); } } /** * Enable the styles of a certain site. * * @param siteId Site ID. If not defined, current site. */ protected enableSiteStyles(siteId?: string): void { siteId = siteId || CoreSites.getCurrentSiteId(); if (this.stylesEls[siteId]) { for (const sourceName in this.stylesEls[siteId]) { this.disableStyleElementByName(siteId, sourceName, false); } CoreApp.setStatusBarColor(); } } /** * Load styles for a certain site. * * @param siteId Site ID. If not defined, current site. * @param disabled Whether loaded styles should be disabled. * @return Promise resolved when styles are loaded. */ protected async load(siteId?: string, disabled = false): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); if (!siteId || !this.stylesEls[siteId]) { throw new CoreError('Cannot load styles, site not found: ${siteId}'); } this.logger.debug('Load site', siteId, disabled); // Enable or disable the styles. for (const sourceName in this.stylesEls[siteId]) { this.disableStyleElementByName(siteId, sourceName, disabled); } await CoreUtils.allPromises(this.styleHandlers.map(async (handler) => { await this.setStyle(siteId!, handler, !!disabled); })); if (!disabled) { // Set StatusBar properties. CoreApp.setStatusBarColor(); } } /** * Load styles for a temporary site, given its public config. These styles aren't prefetched. * * @param config Site public config. * @return Promise resolved when loaded. */ protected async loadTmpStyles(config: CoreSitePublicConfigResponse): Promise<void> { // Create the style and add it to the header. this.createStyleElements(CoreStylesService.TMP_SITE_ID, true); await CoreUtils.allPromises(this.styleHandlers.map(async (handler) => { await this.setStyle(CoreStylesService.TMP_SITE_ID, handler, false, config); })); CoreApp.setStatusBarColor(); } /** * Preload the styles of the current site (stored in DB). * * @return Promise resolved when loaded. */ protected async preloadCurrentSite(): Promise<void> { const siteId = await CoreUtils.ignoreErrors(CoreSites.getStoredCurrentSiteId()); if (!siteId) { // No current site stored. return; } return this.addSite(siteId); } /** * Preload the styles of all the stored sites. * * @return Promise resolved when loaded. */ protected async preloadSites(): Promise<void> { const ids = await CoreSites.getSitesIds(); await CoreUtils.allPromises(ids.map((siteId) => this.addSite(siteId))); } /** * Remove the styles of a certain site. * * @param siteId Site ID. */ protected removeSite(siteId: string): void { if (siteId && this.stylesEls[siteId]) { for (const sourceName in this.stylesEls[siteId]) { const styleElementId = this.getStyleId(siteId, sourceName); const styleEl: HTMLStyleElement | null = document.head.querySelector(`style#${styleElementId}`); if (styleEl) { document.head.removeChild(styleEl); } } delete this.stylesEls[siteId]; CoreApp.setStatusBarColor(); } } /** * Unload styles for a temporary site. */ protected unloadTmpStyles(): void { return this.removeSite(CoreStylesService.TMP_SITE_ID); } } export const CoreStyles = makeSingleton(CoreStylesService);
the_stack
import { ParseError } from ".."; import { ArrayUtils, Assert, Result, ResultUtils, TypeScriptUtils } from "../../common"; import { Ast, AstUtils, Constant, Token } from "../../language"; import { NodeIdMapUtils } from "../nodeIdMap"; import { Parser, ParseStateCheckpoint } from "../parser"; import { ParseState, ParseStateUtils } from "../parseState"; import { AmbiguousParse, BracketDisambiguation, DismabiguationBehavior, ParenthesisDisambiguation, TAmbiguousBracketNode, TAmbiguousParenthesisNode, } from "./disambiguation"; // For each given parse function it'll create a deep copy of the state then parse with the function. // Mutates the given state to whatever parse state which matched the most amount of tokens. // Ties are resolved in the order of the given parse functions. export function readAmbiguous<T extends Ast.TNode>( state: ParseState, parser: Parser, parseFns: ReadonlyArray<(state: ParseState, parser: Parser) => T>, ): AmbiguousParse<T> { ArrayUtils.assertNonZeroLength(parseFns, "requires at least one parse function"); let maybeBestMatch: AmbiguousParse<T> | undefined = undefined; for (const parseFn of parseFns) { const variantState: ParseState = parser.copyState(state); let maybeNode: T | undefined; let variantResult: Result<T, ParseError.ParseError>; try { maybeNode = parseFn(variantState, parser); variantResult = ResultUtils.boxOk(maybeNode); } catch (err) { if (!ParseError.isTInnerParseError(err)) { throw err; } variantResult = ResultUtils.boxError(new ParseError.ParseError(err, variantState)); } const candiate: AmbiguousParse<T> = { parseState: variantState, result: variantResult, }; maybeBestMatch = bestAmbiguousParseMatch<T>(maybeBestMatch, candiate); } Assert.isDefined(maybeBestMatch); return maybeBestMatch; } // Peeks at the token stream and either performs an explicit read or an ambiguous read. export function readAmbiguousBracket( state: ParseState, parser: Parser, allowedVariants: ReadonlyArray<BracketDisambiguation>, ): TAmbiguousBracketNode { // We might be able to peek at tokens to disambiguate what bracketed expression is next. const maybeDisambiguation: BracketDisambiguation | undefined = maybeDisambiguateBracket(state, allowedVariants); // Peeking gave us a concrete answer as to what's next. if (maybeDisambiguation !== undefined) { const disambiguation: BracketDisambiguation = maybeDisambiguation; switch (disambiguation) { case BracketDisambiguation.FieldProjection: return parser.readFieldProjection(state, parser); case BracketDisambiguation.FieldSelection: return parser.readFieldSelection(state, parser); case BracketDisambiguation.RecordExpression: return parser.readRecordExpression(state, parser); default: throw Assert.isNever(disambiguation); } } // Else we branch on `IParseState.disambiguousBehavior`. else { switch (state.disambiguationBehavior) { case DismabiguationBehavior.Strict: throw ParseStateUtils.unterminatedBracketError(state); case DismabiguationBehavior.Thorough: return thoroughReadAmbiguousBracket(state, parser, allowedVariants); default: throw Assert.isNever(state.disambiguationBehavior); } } } // Peeks at the token stream and either performs an explicit read or an ambiguous read. export function readAmbiguousParenthesis(state: ParseState, parser: Parser): TAmbiguousParenthesisNode { // We might be able to peek at tokens to disambiguate what parenthesized expression is next. const maybeDisambiguation: ParenthesisDisambiguation | undefined = maybeDisambiguateParenthesis(state, parser); // Peeking gave us a concrete answer as to what's next. if (maybeDisambiguation !== undefined) { const disambiguation: ParenthesisDisambiguation = maybeDisambiguation; switch (disambiguation) { case ParenthesisDisambiguation.FunctionExpression: return parser.readFunctionExpression(state, parser); case ParenthesisDisambiguation.ParenthesizedExpression: return readParenthesizedExpressionOrBinOpExpression(state, parser); default: throw Assert.isNever(disambiguation); } } // Else we branch on `IParseState.disambiguousBehavior`. else { switch (state.disambiguationBehavior) { case DismabiguationBehavior.Strict: throw ParseStateUtils.unterminatedParenthesesError(state); case DismabiguationBehavior.Thorough: return thoroughReadAmbiguousParenthesis(state, parser); default: throw Assert.isNever(state.disambiguationBehavior); } } } // Peeks at tokens which might give a concrete disambiguation. export function maybeDisambiguateParenthesis(state: ParseState, parser: Parser): ParenthesisDisambiguation | undefined { const initialTokenIndex: number = state.tokenIndex; const tokens: ReadonlyArray<Token.Token> = state.lexerSnapshot.tokens; const totalTokens: number = tokens.length; let nestedDepth: number = 1; let offsetTokenIndex: number = initialTokenIndex + 1; while (offsetTokenIndex < totalTokens) { const offsetTokenKind: Token.TokenKind = tokens[offsetTokenIndex].kind; if (offsetTokenKind === Token.TokenKind.LeftParenthesis) { nestedDepth += 1; } else if (offsetTokenKind === Token.TokenKind.RightParenthesis) { nestedDepth -= 1; } if (nestedDepth === 0) { // '(x as number) as number' could either be either case, // so we need to consume test if the trailing 'as number' is followed by a FatArrow. if (ParseStateUtils.isTokenKind(state, Token.TokenKind.KeywordAs, offsetTokenIndex + 1)) { const checkpoint: ParseStateCheckpoint = parser.createCheckpoint(state); unsafeMoveTo(state, offsetTokenIndex + 2); try { parser.readNullablePrimitiveType(state, parser); } catch { parser.restoreCheckpoint(state, checkpoint); if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.FatArrow)) { return ParenthesisDisambiguation.FunctionExpression; } else { return ParenthesisDisambiguation.ParenthesizedExpression; } } let disambiguation: ParenthesisDisambiguation; if (ParseStateUtils.isOnTokenKind(state, Token.TokenKind.FatArrow)) { disambiguation = ParenthesisDisambiguation.FunctionExpression; } else { disambiguation = ParenthesisDisambiguation.ParenthesizedExpression; } parser.restoreCheckpoint(state, checkpoint); return disambiguation; } else { if (ParseStateUtils.isTokenKind(state, Token.TokenKind.FatArrow, offsetTokenIndex + 1)) { return ParenthesisDisambiguation.FunctionExpression; } else { return ParenthesisDisambiguation.ParenthesizedExpression; } } } offsetTokenIndex += 1; } return undefined; } export function maybeDisambiguateBracket( state: ParseState, allowedVariants: ReadonlyArray<BracketDisambiguation>, ): BracketDisambiguation | undefined { let offsetTokenIndex: number = state.tokenIndex + 1; const tokens: ReadonlyArray<Token.Token> = state.lexerSnapshot.tokens; const maybeOffsetToken: Token.Token | undefined = tokens[offsetTokenIndex]; if (maybeOffsetToken === undefined) { return undefined; } const offsetToken: Token.Token = maybeOffsetToken; let offsetTokenKind: Token.TokenKind = offsetToken.kind; let result: BracketDisambiguation | undefined; if (offsetTokenKind === Token.TokenKind.LeftBracket) { result = BracketDisambiguation.FieldProjection; } else if (offsetTokenKind === Token.TokenKind.RightBracket) { result = BracketDisambiguation.RecordExpression; } else { const totalTokens: number = tokens.length; offsetTokenIndex += 1; while (offsetTokenIndex < totalTokens) { offsetTokenKind = tokens[offsetTokenIndex].kind; if (offsetTokenKind === Token.TokenKind.Equal) { result = BracketDisambiguation.RecordExpression; break; } else if (offsetTokenKind === Token.TokenKind.RightBracket) { result = BracketDisambiguation.FieldSelection; break; } offsetTokenIndex += 1; } } return result !== undefined && allowedVariants.includes(result) ? result : undefined; } // Copy the current state and attempt to read for each of the following: // FieldProjection, FieldSelection, and RecordExpression. // Mutates the given state with the read attempt which matched the most tokens. function thoroughReadAmbiguousBracket( state: ParseState, parser: Parser, allowedVariants: ReadonlyArray<BracketDisambiguation>, ): TAmbiguousBracketNode { return thoroughReadAmbiguous(state, parser, bracketDisambiguationParseFunctions(parser, allowedVariants)); } // Copy the current state and attempt to read for each of the following: // FunctionExpression, ParenthesisExpression. // Mutates the given state with the read attempt which matched the most tokens. function thoroughReadAmbiguousParenthesis(state: ParseState, parser: Parser): TAmbiguousParenthesisNode { return thoroughReadAmbiguous<TAmbiguousParenthesisNode>(state, parser, [ parser.readFunctionExpression, readParenthesizedExpressionOrBinOpExpression, ]); } function thoroughReadAmbiguous<T extends TAmbiguousBracketNode | TAmbiguousParenthesisNode>( state: ParseState, parser: Parser, parseFns: ReadonlyArray<(state: ParseState, parser: Parser) => T>, ): T { const ambiguousParse: AmbiguousParse<T> = readAmbiguous(state, parser, parseFns); parser.applyState(state, ambiguousParse.parseState); if (ResultUtils.isOk(ambiguousParse.result)) { return ambiguousParse.result.value; } else { // ParseError.state references the cloned state generated in readAmbiguous, not the current state parameter. // For correctness sake we need to update the existing state with the AmbiguousParse error, // then update the reference. const mutableParseError: TypeScriptUtils.StripReadonly<ParseError.ParseError> = ambiguousParse.result.error; mutableParseError.state = state; throw ambiguousParse.result.error; } } // Converts BracketDisambiguation into its corrosponding read function. function bracketDisambiguationParseFunctions( parser: Parser, allowedVariants: ReadonlyArray<BracketDisambiguation>, ): ReadonlyArray<(state: ParseState, parser: Parser) => TAmbiguousBracketNode> { return allowedVariants.map((bracketDisambiguation: BracketDisambiguation) => { switch (bracketDisambiguation) { case BracketDisambiguation.FieldProjection: return parser.readFieldProjection; case BracketDisambiguation.FieldSelection: return parser.readFieldSelection; case BracketDisambiguation.RecordExpression: return parser.readRecordExpression; default: throw Assert.isNever(bracketDisambiguation); } }); } // When the next token is an open parenthesis we can't directly read // a ParenthesisExpression as it may leave trailing tokens behind. // `(1) + 2` function readParenthesizedExpressionOrBinOpExpression( state: ParseState, parser: Parser, ): Ast.ParenthesizedExpression | Ast.TLogicalExpression { const node: Ast.TNode = parser.readLogicalExpression(state, parser); const leftMostNode: Ast.TNode = NodeIdMapUtils.assertUnboxLeftMostLeaf( state.contextState.nodeIdMapCollection, node.id, ); AstUtils.assertAsTConstant(leftMostNode); Assert.isTrue( leftMostNode.kind === Ast.NodeKind.Constant && leftMostNode.constantKind === Constant.WrapperConstant.LeftParenthesis, `leftMostNode should be a ${Ast.NodeKind.Constant} with a constantKind of ${Constant.WrapperConstant.LeftParenthesis}`, ); return node; } // WARNING: Only updates tokenIndex and currentTokenKind, // Manual cleanup of other state fields such as TokenRangeStack is assumed by the caller. function unsafeMoveTo(state: ParseState, tokenIndex: number): void { const tokens: ReadonlyArray<Token.Token> = state.lexerSnapshot.tokens; state.tokenIndex = tokenIndex; if (tokenIndex < tokens.length) { state.maybeCurrentToken = tokens[tokenIndex]; state.maybeCurrentTokenKind = state.maybeCurrentToken.kind; } else { state.maybeCurrentToken = undefined; state.maybeCurrentTokenKind = undefined; } } function bestAmbiguousParseMatch<T extends Ast.TNode>( maybeBest: AmbiguousParse<T> | undefined, candidate: AmbiguousParse<T>, ): AmbiguousParse<T> { if (maybeBest === undefined || maybeBest.parseState.tokenIndex < candidate.parseState.tokenIndex) { return candidate; } else if ( maybeBest.parseState.tokenIndex === candidate.parseState.tokenIndex && ResultUtils.isError(maybeBest.result) && ResultUtils.isOk(candidate.result) ) { return candidate; } else { return maybeBest; } }
the_stack
namespace justEat { /** * A class representing the handler for Apple Pay JS. */ export class ApplePay { public merchantIdentifier: string; public storeName: string; private applePayVersion: number; private countryCode: string; private currencyCode: string; private session: ApplePaySession; private validationResource: string; /** * Initializes a new instance of the justEat.ApplePay class. */ public constructor() { // Get the merchant identifier and store display name from the page meta tags. this.merchantIdentifier = $("meta[name='apple-pay-merchant-id']").attr("content"); this.storeName = $("meta[name='apple-pay-store-name']").attr("content"); // Get the URL to POST to for Apple Pay merchant validation this.validationResource = $("link[rel='merchant-validation']").attr("href"); // Set the Apple Pay JS version to use this.applePayVersion = 10; // Set the appropriate ISO country and currency codes this.countryCode = $("meta[name='payment-country-code']").attr("content") || "GB"; this.currencyCode = $("meta[name='payment-currency-code']").attr("content") || "GBP"; } /** * Initializes the handler for the current page. */ public initialize(): void { if (!this.merchantIdentifier) { this.showError("No Apple Pay merchant certificate is configured."); } // Is ApplePaySession available in the browser? else if (this.supportedByDevice() === true) { // Determine whether to display the Apple Pay button. See this link for details // on the two different approaches: https://developer.apple.com/documentation/applepayjs/checking_if_apple_pay_is_available if (this.canMakePayments() === true) { this.showButton(); } else { this.canMakePaymentsWithActiveCard().then((canMakePayments) => { if (canMakePayments === true) { this.showButton(); } else { if (this.supportsSetup()) { this.showSetupButton(); } else { this.showError("Apple Pay cannot be used at this time. If using macOS you need to be paired with a device that supports at least TouchID."); } } }); } } else { this.showError("This device and/or browser does not support Apple Pay."); } } /** * Handles the Apple Pay button being pressed. * @param e - The event object. */ private beginPayment = (e: JQueryEventObject): void => { e.preventDefault(); // Get the amount to request from the form and set up // the totals and line items for collection and delivery. const subtotal = $("#amount").val().toString(); const delivery = "0.01"; const deliveryTotal = (parseFloat(subtotal) + parseFloat(delivery)).toString(10); const totalForCollection = { label: this.storeName, amount: subtotal }; const lineItemsForCollection: ApplePayJS.ApplePayLineItem[] = [ { label: "Subtotal", amount: subtotal, type: "final" } ]; const totalForDelivery = { label: this.storeName, amount: deliveryTotal }; const lineItemsForDelivery: ApplePayJS.ApplePayLineItem[] = [ { label: "Subtotal", amount: subtotal, type: "final" }, { label: "Delivery", amount: delivery, type: "final" } ]; // Create the Apple Pay payment request as appropriate. const paymentRequest = this.createPaymentRequest(delivery, lineItemsForDelivery, totalForDelivery); // Create the Apple Pay session. this.session = new ApplePaySession(this.applePayVersion, paymentRequest); // Setup handler for validation the merchant session. this.session.onvalidatemerchant = this.onValidateMerchant; // Setup handler for shipping method selection. this.session.onshippingmethodselected = (event) => { let newTotal; let newLineItems; // Swap the total and line items based on the selected shipping method if (event.shippingMethod.identifier === "collection") { newTotal = totalForCollection; newLineItems = lineItemsForCollection; } else { newTotal = totalForDelivery; newLineItems = lineItemsForDelivery; } const update = { newTotal: newTotal, newLineItems: newLineItems }; this.session.completeShippingMethodSelection(update); }; // Setup handler to receive the token when payment is authorized. this.session.onpaymentauthorized = this.onPaymentAuthorized; // Begin the session to display the Apple Pay sheet. this.session.begin(); } /** * Captures funds from the specified payment token. * @param token - The authorized Apple Pay payment token. * @returns The authorization result to return to complete the payment. */ private captureFunds(token: ApplePayJS.ApplePayPaymentToken): ApplePayJS.ApplePayPaymentAuthorizationResult { // Do something with the payment to capture funds and // then dismiss the Apple Pay sheet for the session with // the relevant status code for the payment's authorization. // If any errors occurred, add them to the errors array for display. return { status: ApplePaySession.STATUS_SUCCESS, errors: [] }; } /** * Indicates whether or not the device supports Apple Pay. * @returns true if the device supports making payments with Apple Pay; otherwise, false. */ private canMakePayments(): boolean { return ApplePaySession.canMakePayments(); } /** * Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet. * @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false. */ private canMakePaymentsWithActiveCard(): Promise<boolean> { return ApplePaySession.canMakePaymentsWithActiveCard(this.merchantIdentifier); } /** * Creates an Apple Pay payment request for the specified total and line items. * @param deliveryAmount - The amount to charge for delivery. * @param lineItems - The line items for the payment. * @param total - The total for the payment. * @returns The Apple Pay payment request that was created. */ private createPaymentRequest = (deliveryAmount: string, lineItems: ApplePayJS.ApplePayLineItem[], total: ApplePayJS.ApplePayLineItem): ApplePayJS.ApplePayPaymentRequest => { let paymentRequest: ApplePayJS.ApplePayPaymentRequest = { applicationData: btoa("Custom application-specific data"), countryCode: this.countryCode, currencyCode: this.currencyCode, merchantCapabilities: ["supports3DS", "supportsCredit", "supportsDebit"], supportedNetworks: ["amex", "discover", "jcb", "masterCard", "privateLabel", "visa"], lineItems: lineItems, total: total, requiredBillingContactFields: ["email", "name", "phone", "postalAddress"], requiredShippingContactFields: ["email", "name", "phone", "postalAddress"], shippingType: "delivery", shippingMethods: [ { label: "Delivery", amount: deliveryAmount, identifier: "delivery", detail: "Delivery to you" }, { label: "Collection", amount: "0.00", identifier: "collection", detail: "Collect from the store" } ], supportedCountries: [this.countryCode] }; // You can optionally pre-populate the billing and shipping contact // with information about the current user, if available to you. // paymentRequest.billingContact = { // givenName: "", // familyName: "" // }; // paymentRequest.shippingContact = { // givenName: "", // familyName: "" // }; return paymentRequest; } /** * Gets the current page's language. * @returns The current page language. */ private getPageLanguage(): string { return $("html").attr("lang") || "en"; } /** * Hides the setup button. */ private hideSetupButton(): void { const button = $("#set-up-apple-pay-button"); button.addClass("d-none"); button.off("click"); } /** * Handles the Apple Pay payment being authorized by the user. * @param event - The event object. */ private onPaymentAuthorized = (event: ApplePayJS.ApplePayPaymentAuthorizedEvent): void => { // Get the payment data for use to capture funds from // the encrypted Apple Pay token in your server. const token = event.payment.token; // Process the payment const authorizationResult = this.captureFunds(token); if (authorizationResult.status === ApplePaySession.STATUS_SUCCESS) { // Get the contact details for use, for example to // use to create an account for the user. const billingContact = event.payment.billingContact; const shippingContact = event.payment.shippingContact; // Apply the details captured from the Apple Pay sheet to the page. $(".card-name").text(event.payment.token.paymentMethod.displayName); this.updatePanel($("#billing-contact"), billingContact); this.updatePanel($("#shipping-contact"), shippingContact); this.showSuccess(); } else { const errors = authorizationResult.errors.map((error) => { return error.message; }); this.showError(`Your payment could not be processed. ${errors.join(" ")}`); authorizationResult.errors.forEach((error) => { console.error(`${error.message} (${error.contactField}: ${error.code}).`); }); } this.session.completePayment(authorizationResult); } /** * Handles merchant validation for the Apple Pay session. * @param event - The event object. */ private onValidateMerchant = (event: ApplePayJS.ApplePayValidateMerchantEvent): void => { // Create the payload. const data = { validationUrl: event.validationURL }; const headers = this.createValidationHeaders(); const request = this.createValidationRequest(data, headers); // Post the payload to the server to validate the // merchant session using the merchant certificate. $.ajax(request).then((merchantSession) => { // Complete validation by passing the merchant session to the Apple Pay session. this.session.completeMerchantValidation(merchantSession); }); } /** * Creates the HTTP headers to use for the validation request. * @returns An object representing the HTTP headers for the request. */ private createValidationHeaders(): any { // Set any custom HTTP request headers here. let headers: any = { }; // Setup antiforgery HTTP header. const antiforgeryHeader = $("meta[name='x-antiforgery-name']").attr("content"); const antiforgeryToken = $("meta[name='x-antiforgery-token']").attr("content"); headers[antiforgeryHeader] = antiforgeryToken; return headers; } /** * Creates the validation request to use for the HTTP POST to the server. * @param data - The request data. * @param headers - The request headers. */ private createValidationRequest = (data: any, headers: any): JQueryAjaxSettings => { return { url: this.validationResource, method: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(data), headers: headers }; } /** * Event handler for setting up Apple Pay. */ private setupApplePay = (): Promise<boolean> => { return ApplePaySession.openPaymentSetup(this.merchantIdentifier) .then((success) => { if (success) { this.hideSetupButton(); this.showButton(); } else { this.showError("Failed to set up Apple Pay."); } return success; }).catch((err: any) => { this.showError(`Failed to set up Apple Pay. ${JSON.stringify(err)}`); return false; }); } /** * Shows the Apple Pay button. */ private showButton = (): void => { const button = $("#apple-pay-button"); button.attr("lang", this.getPageLanguage()); button.on("click", this.beginPayment); if (this.supportsSetup()) { button.addClass("apple-pay-button-with-text"); button.addClass("apple-pay-button-black-with-text"); } else { button.addClass("apple-pay-button"); button.addClass("apple-pay-button-black"); } button.removeClass("d-none"); } /** * Shows the error banner. * @param text - The text to show in the banner. */ private showError(text: string): void { const error = $(".apple-pay-error"); error.text(text); error.removeClass("d-none"); } /** * Shows the button to set up Apple Pay. */ private showSetupButton = (): void => { const button = $("#set-up-apple-pay-button"); button.attr("lang", this.getPageLanguage()); button.on("click", this.setupApplePay); button.removeClass("d-none"); } /** * Shows the successful payment button. */ private showSuccess() { $(".apple-pay-intro").hide(); const success = $(".apple-pay-success"); success.removeClass("d-none"); } /** * Returns whether Apple Pay is supported on the current device. * @returns Whether Apple Pay is supported. */ private supportedByDevice(): boolean { return "ApplePaySession" in window && ApplePaySession !== undefined; } /** * Returns whether setting up Apple Pay is supported on the current device. * @returns Whether setting up Apple Pay is supported. */ private supportsSetup(): boolean { return "openPaymentSetup" in ApplePaySession; } /** * Updates the specified panel with the specified Apple Pay contact. * @param panel - The panel to update. * @param contact - The contact to update the panel with the details for. */ private updatePanel = (panel: JQuery, contact: ApplePayJS.ApplePayPaymentContact) => { if (contact.emailAddress) { panel.find(".contact-email") .text(contact.emailAddress) .attr("href", "mailto:" + contact.emailAddress) .append("<br/>") .removeClass("d-none"); } if (contact.phoneNumber) { panel.find(".contact-telephone") .text(contact.phoneNumber) .attr("href", "tel:" + contact.phoneNumber) .append("<br/>") .removeClass("d-none"); } if (contact.givenName) { panel.find(".contact-name") .text(contact.givenName + " " + contact.familyName) .append("<br/>") .removeClass("d-none"); } if (contact.addressLines) { panel.find(".contact-address-lines").text(contact.addressLines.join(", ")); panel.find(".contact-sub-locality").text(contact.subLocality); panel.find(".contact-locality").text(contact.locality); panel.find(".contact-sub-administrative-area").text(contact.subAdministrativeArea); panel.find(".contact-administrative-area").text(contact.administrativeArea); panel.find(".contact-postal-code").text(contact.postalCode); panel.find(".contact-country").text(contact.country); panel.find(".contact-address").removeClass("d-none"); } } } } (() => { const handler = new justEat.ApplePay(); handler.initialize(); })();
the_stack
import {createStore, createEvent, sample, Store, Event} from 'effector' const typecheck = '{global}' describe('sample(config)', () => { describe('sample({source, filter: store})', () => { it('return new event (should pass)', () => { const trigger = createEvent<number>() const allow = createStore<boolean>(false) const result: Event<number> = sample({ source: trigger, filter: allow, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) it('support any unit (should pass)', () => { const trigger = createStore<number[]>([1]) const allow = createStore<boolean>(false) const result: Event<number[]> = sample({ source: trigger, filter: allow, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('store is not boolean (should fail)', () => { const trigger = createEvent<number>() const allow = createStore<string>('no') sample({ //@ts-expect-error source: trigger, filter: allow, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; filter: Store<string>; }' is not assignable to parameter of type '{ error: \\"filter unit should has boolean type\\"; got: string; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"filter unit should has boolean type\\"; got: string; }'. " `) }) test('result type mismatch (should fail)', () => { const trigger = createEvent<number>() const allow = createStore<string>('no') sample({ //@ts-expect-error source: trigger, filter: allow, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; filter: Store<string>; }' is not assignable to parameter of type '{ error: \\"filter unit should has boolean type\\"; got: string; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"filter unit should has boolean type\\"; got: string; }'. " `) }) describe('support target field', () => { it('allow to pass target field (should pass)', () => { const trigger: Event<number> = createEvent() const allow = createStore<boolean>(false) const target: Store<number> = createStore(0) sample({ source: trigger, filter: allow, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type mismatch (should fail)', () => { const trigger: Event<number> = createEvent() const allow = createStore<boolean>(false) const target = createStore<string>('no') sample({ //@ts-expect-error source: trigger, filter: allow, target, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; filter: Store<boolean>; target: Store<string>; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. " `) }) }) }) describe('sample({source, filter: fn})', () => { it('returns new event (should pass)', () => { const trigger = createEvent<number>() const result: Event<number> = sample({ source: trigger, filter: n => n > 0, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('result type mismatch (should fail)', () => { const trigger = createEvent<number>() //@ts-expect-error const result: Event<string> = sample({ source: trigger, filter: n => n > 0, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<number>' is not assignable to type 'Event<string>'. " `) }) describe('support target field', () => { it('allow to pass target field (should pass)', () => { const trigger = createEvent<number>() const target = createStore<number>(0) sample({ source: trigger, filter: x => x > 0, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type mismatch (should fail)', () => { const trigger = createEvent<number>() const target = createStore<string>('no') sample({ //@ts-expect-error source: trigger, filter: x => x > 0, target, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<number>; filter: (x: number) => boolean; target: Store<string>; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. " `) }) describe('any to void', () => { test('with store (should pass)', () => { const filter = createStore(true) const source = createEvent<string>() const target = createEvent<void>() sample({ source, filter, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('with function (should pass)', () => { const source = createEvent<{pass: boolean}>() const target = createEvent<void>() sample({ source, filter: ({pass}) => pass, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) }) describe('sample({source, clock, filter: fn})', () => { it('returns new event (should pass)', () => { const clock = createEvent<string>() const source = createEvent<number>() const result: Event<number> = sample({ clock, source, filter: (src, clk) => src + clk.length > 0, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('result type mismatch (should fail)', () => { const clock = createEvent<string>() const source = createEvent<number>() //@ts-expect-error const result: Event<string> = sample({ clock, source, filter: (src, clk) => src + clk.length > 0, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<number>' is not assignable to type 'Event<string>'. " `) }) describe('support target field', () => { it('allow to pass target field (should pass)', () => { const clock = createEvent<string>() const source = createEvent<number>() const target = createStore<number>(0) sample({ clock, source, filter: (src, clk) => src + clk.length > 0, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('filter + fn edge case (should pass)', () => { const $source = createStore({a: null as number | null, b: ''}) const aNum = createEvent<number>() sample({ source: $source, target: aNum, filter: (val): val is {a: number; b: string} => typeof val.a === 'number' && val.a > 0, fn: val => 1, }) sample({ source: $source, target: aNum, filter: (val): val is {a: number; b: string} => typeof val.a === 'number' && val.a > 0, fn: (val: {a: number; b: string}) => val.a + 1, }) sample({ clock: $source, target: aNum, filter: (val): val is {a: number; b: string} => typeof val.a === 'number' && val.a > 0, fn: val => 1, }) sample({ clock: $source, target: aNum, filter: (val): val is {a: number; b: string} => typeof val.a === 'number' && val.a > 0, fn: (val: {a: number; b: string}) => val.a + 1, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type mismatch (should fail)', () => { const clock = createEvent<string>() const source = createEvent<number>() const target = createStore<string>('no') sample({ //@ts-expect-error clock, source, filter: (src, clk) => src + clk.length > 0, target, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ clock: Event<string>; source: Event<number>; filter: (src: number, clk: string) => boolean; target: Store<string>; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. Object literal may only specify known properties, and 'clock' does not exist in type '{ error: \\"source should extend target type\\"; targets: { sourceType: number; targetType: string; }; }'. " `) }) describe('any to void', () => { test('with store (should pass)', () => { const clock = createEvent<string>() const filter = createStore(true) const source = createEvent<string>() const target = createEvent<void>() sample({ clock, source, filter, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('with function (should pass)', () => { const clock = createEvent<string>() const source = createEvent<{pass: boolean}>() const target = createEvent<void>() sample({ clock, source, filter: ({pass}, clk) => pass && clk.length > 0, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) }) describe('sample({source, filter: Boolean})', () => { it('returns new event (should pass)', () => { type User = {name: string} const trigger = createEvent<User | null>() const result: Event<User> = sample({ source: trigger, filter: Boolean, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('result type mismatch (should fail)', () => { type User = {name: string} const trigger = createEvent<User>() //@ts-expect-error const result: Event<string> = sample({ source: trigger, filter: Boolean, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<User>' is not assignable to type 'Event<string>'. Types of property 'watch' are incompatible. Type '(watcher: (payload: User) => any) => Subscription' is not assignable to type '(watcher: (payload: string) => any) => Subscription'. Types of parameters 'watcher' and 'watcher' are incompatible. Types of parameters 'payload' and 'payload' are incompatible. Type 'User' is not assignable to type 'string'. " `) }) it('filters falsy values (should pass)', () => { type User = {name: string} type FalsyValues = null | undefined | false | 0 | 0n | '' const trigger = createEvent<User | FalsyValues>() const result: Event<User> = sample({ source: trigger, filter: Boolean, }) const resultFn: Event<User> = sample({ source: trigger, filter: Boolean, fn: (arg: User) => arg, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('support target field', () => { it('allow to pass target field (should pass)', () => { type User = {name: string} const trigger = createEvent<User | null>() const target = createStore<User>({name: 'alice'}) sample({ source: trigger, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type mismatch (should fail)', () => { type User = {name: string} const trigger = createEvent<User>() const target = createStore<string>('no') sample({ //@ts-expect-error source: trigger, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ source: Event<User>; filter: BooleanConstructor; target: Store<string>; }' is not assignable to parameter of type '{ error: \\"source should extend target type\\"; targets: { sourceType: User; targetType: string; }; }'. Object literal may only specify known properties, and 'source' does not exist in type '{ error: \\"source should extend target type\\"; targets: { sourceType: User; targetType: string; }; }'. " `) }) test('any to void (should pass)', () => { const source = createEvent<{pass: boolean}>() const target = createEvent<void>() sample({ source, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) describe('sample({clock, filter: Boolean})', () => { it('returns new event (should pass)', () => { type User = {name: string} const trigger = createEvent<User | null>() const result: Event<User> = sample({ clock: trigger, filter: Boolean, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('result type mismatch (should fail)', () => { type User = {name: string} const trigger = createEvent<User>() //@ts-expect-error const result: Event<string> = sample({ clock: trigger, filter: Boolean, }) expect(typecheck).toMatchInlineSnapshot(` " Type 'Event<User>' is not assignable to type 'Event<string>'. Types of property 'watch' are incompatible. Type '(watcher: (payload: User) => any) => Subscription' is not assignable to type '(watcher: (payload: string) => any) => Subscription'. Types of parameters 'watcher' and 'watcher' are incompatible. Types of parameters 'payload' and 'payload' are incompatible. Type 'User' is not assignable to type 'string'. " `) }) describe('support target field', () => { it('allow to pass target field (should pass)', () => { type User = {name: string} const trigger = createEvent<User | null>() const target = createStore<User>({name: 'alice'}) sample({ clock: trigger, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('type mismatch (should fail)', () => { type User = {name: string} const trigger = createEvent<User>() const target = createStore<string>('no') sample({ //@ts-expect-error clock: trigger, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '{ clock: Event<User>; filter: BooleanConstructor; target: Store<string>; }' is not assignable to parameter of type '{ error: \\"clock should extend target type\\"; targets: { clockType: User; targetType: string; }; }'. Object literal may only specify known properties, and 'clock' does not exist in type '{ error: \\"clock should extend target type\\"; targets: { clockType: User; targetType: string; }; }'. " `) }) test('any to void (should pass)', () => { const clock = createEvent<{pass: boolean}>() const target = createEvent<void>() sample({ clock, filter: Boolean, target, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) }) describe('filter return validation', () => { const anyt = createEvent<any>() describe('wrong return', () => { test('sample({source, filter}) (should fail)', () => { //@ts-expect-error sample({source: anyt, filter: () => 0}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '[{ source: Event<any>; filter: () => number; }]' is not assignable to parameter of type '[config: { source: Event<any>; clock?: undefined; filter: (src: any) => src is any; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<any>; filter: () => number; }] | [config: ...]'. Type '[{ source: Event<any>; filter: () => number; }]' is not assignable to type '[config: { source: Event<any>; clock?: undefined; filter: (src: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<any>; filter: () => number; }]'. Type '{ source: Event<any>; filter: () => number; }' is not assignable to type '{ source: Event<any>; clock?: undefined; filter: (src: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<any>; filter: () => number; }'. Type '{ source: Event<any>; filter: () => number; }' is not assignable to type '{ source: Event<any>; clock?: undefined; filter: (src: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; }'. The types returned by 'filter(...)' are incompatible between these types. Type 'number' is not assignable to type 'boolean'. " `) }) test('sample({clock, filter}) (should fail)', () => { //@ts-expect-error sample({clock: anyt, filter: () => 0}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '[{ clock: Event<any>; filter: () => number; }]' is not assignable to parameter of type '[config: { clock: Event<any>; source?: undefined; filter: (clk: any) => clk is any; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { clock: Event<any>; filter: () => number; }] | [config: ...]'. Type '[{ clock: Event<any>; filter: () => number; }]' is not assignable to type '[config: { clock: Event<any>; source?: undefined; filter: (clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { clock: Event<any>; filter: () => number; }]'. Type '{ clock: Event<any>; filter: () => number; }' is not assignable to type '{ clock: Event<any>; source?: undefined; filter: (clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { clock: Event<any>; filter: () => number; }'. Type '{ clock: Event<any>; filter: () => number; }' is not assignable to type '{ clock: Event<any>; source?: undefined; filter: (clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; }'. The types returned by 'filter(...)' are incompatible between these types. Type 'number' is not assignable to type 'boolean'. " `) }) test('sample({source, clock, filter}) (should fail)', () => { //@ts-expect-error sample({source: anyt, clock: anyt, filter: () => 0}) expect(typecheck).toMatchInlineSnapshot(` " Argument of type '[{ source: Event<any>; clock: Event<any>; filter: () => number; }]' is not assignable to parameter of type '[config: { clock: Event<any>; source: Event<any>; filter: (src: any, clk: any) => src is any; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<...>; clock: Event<...>; filter: () => number; }] | [config: ...]'. Type '[{ source: Event<any>; clock: Event<any>; filter: () => number; }]' is not assignable to type '[config: { clock: Event<any>; source: Event<any>; filter: (src: any, clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<...>; clock: Event<...>; filter: () => number; }]'. Type '{ source: Event<any>; clock: Event<any>; filter: () => number; }' is not assignable to type '{ clock: Event<any>; source: Event<any>; filter: (src: any, clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; } & { source: Event<...>; clock: Event<...>; filter: () => number; }'. Type '{ source: Event<any>; clock: Event<any>; filter: () => number; }' is not assignable to type '{ clock: Event<any>; source: Event<any>; filter: (src: any, clk: any) => boolean; target?: undefined; greedy?: boolean | undefined; name?: string | undefined; }'. The types returned by 'filter(...)' are incompatible between these types. Type 'number' is not assignable to type 'boolean'. " `) }) }) describe('boolean return', () => { test('sample({source, filter}) (should pass)', () => { sample({source: anyt, filter: () => true as boolean}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({clock, filter}) (should pass)', () => { sample({clock: anyt, filter: () => true as boolean}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({source, clock, filter}) (should pass)', () => { sample({source: anyt, clock: anyt, filter: () => true as boolean}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) describe('boolean subtype return', () => { test('sample({source, filter}) (should pass)', () => { sample({source: anyt, filter: () => true as true}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({clock, filter}) (should pass)', () => { sample({clock: anyt, filter: () => true as true}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({source, clock, filter}) (should pass)', () => { sample({source: anyt, clock: anyt, filter: () => true as true}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) }) describe('any support in arguments inference', () => { function assertNonNever<T>(val: T): [T] extends [never] ? 'never' : 'ok' { return val as any } const anyt = createEvent<any>() test('sample({source, filter}) (should pass)', () => { sample({ source: anyt, filter(src) { const x: 'ok' = assertNonNever(src) return false }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({clock, filter}) (should pass)', () => { sample({ clock: anyt, filter(clk) { const x: 'ok' = assertNonNever(clk) return false }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({clock: [clock], filter}) (should pass)', () => { sample({ clock: [anyt], filter(clk) { const x: 'ok' = assertNonNever(clk) return false }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({source, clock, filter}) (should pass)', () => { sample({ source: anyt, clock: anyt, filter(src, clk) { const x1: 'ok' = assertNonNever(src) const x2: 'ok' = assertNonNever(clk) return false }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('sample({source, clock: [clock], filter}) (should pass)', () => { sample({ source: anyt, clock: [anyt], filter(src, clk) { const x1: 'ok' = assertNonNever(src) const x2: 'ok' = assertNonNever(clk) return false }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) }) test('sample return type supports union types (should pass)', () => { const trigger = createEvent<{a: 1} | {a: 2}>() const allow = createStore<boolean>(false) const result: Event<{a: 1} | {a: 2}> = sample({ source: trigger, filter: allow, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('incorrect filter (should fail)', () => { const trigger = createEvent() const target = createEvent() function factory() { //@ts-expect-error sample({ source: trigger, filter: null, target, }) } expect(typecheck).toMatchInlineSnapshot(` " Argument of type '[{ source: Event<void>; filter: null; target: Event<void>; }]' is not assignable to parameter of type '[config: never] | [config: never]'. Type '[{ source: Event<void>; filter: null; target: Event<void>; }]' is not assignable to type '[config: never]'. Type '{ source: Event<void>; filter: null; target: Event<void>; }' is not assignable to type 'never'. The intersection '{ source: Event<void>; clock?: undefined; filter: (src: void) => boolean; target: Event<void>; greedy?: boolean | undefined; } & { source: Event<void>; filter: null; target: Event<...>; }' was reduced to 'never' because property 'filter' has conflicting types in some constituents. " `) })
the_stack
import { h, ref, toRef, computed, watch, nextTick, defineComponent, Transition, PropType, CSSProperties, ComponentPublicInstance } from 'vue' import { VBinder, VTarget, VFollower, FollowerPlacement, FollowerInst as _FollowerInst } from 'vueuc' import { useIsMounted, useMergedState } from 'vooks' import { on, off } from 'evtd' import { useTheme, useFormItem, useConfig, ThemeProps } from '../../_mixins' import { call, useAdjustedTo, MaybeArray, ExtractPublicPropTypes } from '../../_utils' import { sliderLight, SliderTheme } from '../styles' import { OnUpdateValueImpl } from './interface' import { isTouchEvent, useRefs } from './utils' import style from './styles/index.cssr' interface FollowerInst extends _FollowerInst, ComponentPublicInstance {} export interface ClosestMark { value: number distance: number index: number } // ref: https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/button const eventButtonLeft = 0 const sliderProps = { ...(useTheme.props as ThemeProps<SliderTheme>), to: useAdjustedTo.propTo, defaultValue: { type: [Number, Array] as PropType<number | number[]>, default: 0 }, marks: Object as PropType<Record<string, string>>, disabled: { type: Boolean as PropType<boolean | undefined>, default: undefined }, formatTooltip: Function as PropType<(value: number) => string | number>, min: { type: Number, default: 0 }, max: { type: Number, default: 100 }, step: { type: [Number, String] as PropType<number | 'mark'>, default: 1 }, range: Boolean, value: [Number, Array] as PropType<number | number[]>, placement: String as PropType<FollowerPlacement>, showTooltip: { type: Boolean as PropType<boolean | undefined>, default: undefined }, tooltip: { type: Boolean, default: true }, vertical: Boolean, reverse: Boolean, 'onUpdate:value': [Function, Array] as PropType< MaybeArray<(value: number & number[]) => void> >, onUpdateValue: [Function, Array] as PropType< MaybeArray<(value: number & number[]) => void> > } as const export type SliderProps = ExtractPublicPropTypes<typeof sliderProps> export default defineComponent({ name: 'Slider', props: sliderProps, setup (props) { const { mergedClsPrefixRef, namespaceRef } = useConfig(props) const themeRef = useTheme( 'Slider', 'Slider', style, sliderLight, props, mergedClsPrefixRef ) // dom ref const handleRailRef = ref<HTMLElement | null>(null) const [handleRefs, setHandleRefs] = useRefs<HTMLElement>() const [followerRefs, setFollowerRefs] = useRefs<FollowerInst>() const followerEnabledIndexSetRef = ref<Set<number>>(new Set()) // data ref const formItem = useFormItem(props) const { mergedDisabledRef } = formItem const precisionRef = computed(() => { const { step } = props if (step <= 0 || step === 'mark') return 0 const stepString = step.toString() let precision = 0 if (stepString.includes('.')) { precision = stepString.length - stepString.indexOf('.') - 1 } return precision }) const uncontrolledValueRef = ref(props.defaultValue) const controlledValueRef = toRef(props, 'value') const mergedValueRef = useMergedState( controlledValueRef, uncontrolledValueRef ) const arrifiedValueRef = computed(() => { const { value: mergedValue } = mergedValueRef return ((props.range ? mergedValue : [mergedValue]) as number[]).map( clampValue ) }) const handleCountExceeds2Ref = computed( () => arrifiedValueRef.value.length > 2 ) const mergedPlacementRef = computed(() => { return props.placement === undefined ? props.vertical ? 'right' : 'top' : props.placement }) const markValuesRef = computed(() => { const { marks } = props return marks ? Object.keys(marks).map(parseFloat) : null }) // status ref const activeIndexRef = ref(-1) const previousIndexRef = ref(-1) const hoverIndexRef = ref(-1) const draggingRef = ref(false) // style ref const dotTransitionDisabledRef = ref(false) const styleDirectionRef = computed(() => { const { vertical, reverse } = props const left = reverse ? 'right' : 'left' const bottom = reverse ? 'top' : 'bottom' return vertical ? bottom : left }) const fillStyleRef = computed(() => { if (handleCountExceeds2Ref.value) return const values = arrifiedValueRef.value const start = valueToPercentage( props.range ? Math.min(...values) : props.min ) const end = valueToPercentage( props.range ? Math.max(...values) : values[0] ) const { value: styleDirection } = styleDirectionRef return props.vertical ? { [styleDirection]: `${start}%`, height: `${end - start}%` } : { [styleDirection]: `${start}%`, width: `${end - start}%` } }) const markInfosRef = computed(() => { const mergedMarks: Array<{ active: boolean label: string style: CSSProperties }> = [] const { marks } = props if (marks) { const orderValues = arrifiedValueRef.value.slice() orderValues.sort((a, b) => a - b) const { value: styleDirection } = styleDirectionRef const { value: handleCountExceeds2 } = handleCountExceeds2Ref const { range } = props const isActive = handleCountExceeds2 ? () => false : (num: number): boolean => range ? num >= orderValues[0] && num <= orderValues[orderValues.length - 1] : num <= orderValues[0] for (const key of Object.keys(marks)) { const num = Number(key) mergedMarks.push({ active: isActive(num), label: marks[key], style: { [styleDirection]: `${valueToPercentage(num)}%` } }) } } return mergedMarks }) function getHandleStyle (value: number, index: number): Record<string, any> { const percentage = valueToPercentage(value) const { value: styleDirection } = styleDirectionRef return { [styleDirection]: `${percentage}%`, zIndex: index === activeIndexRef.value ? 1 : 0 } } function isShowTooltip (index: number): boolean { return ( props.showTooltip || hoverIndexRef.value === index || (activeIndexRef.value === index && draggingRef.value) ) } function isSkipCSSDetection (index: number): boolean { return !( activeIndexRef.value === index && previousIndexRef.value === index ) } function focusActiveHandle (index: number): void { if (~index) { activeIndexRef.value = index handleRefs.value.get(index)?.focus() } } function syncPosition (): void { followerRefs.value.forEach((inst, index) => { if (isShowTooltip(index)) inst.syncPosition() }) } function doUpdateValue (value: number | number[]): void { const { 'onUpdate:value': _onUpdateValue, onUpdateValue } = props const { nTriggerFormInput, nTriggerFormChange } = formItem if (onUpdateValue) call(onUpdateValue as OnUpdateValueImpl, value) if (_onUpdateValue) call(_onUpdateValue as OnUpdateValueImpl, value) uncontrolledValueRef.value = value nTriggerFormInput() nTriggerFormChange() } function dispatchValueUpdate (value: number | number[]): void { const { range } = props if (range) { if (Array.isArray(value)) { const { value: oldValues } = arrifiedValueRef if (value.join() !== oldValues.join()) { doUpdateValue(value) } } } else if (!Array.isArray(value)) { const oldValue = arrifiedValueRef.value[0] if (oldValue !== value) { doUpdateValue(value) } } } function doDispatchValue (value: number, index: number): void { if (props.range) { const values = arrifiedValueRef.value.slice() values.splice(index, 1, value) dispatchValueUpdate(values) } else { dispatchValueUpdate(value) } } // value conversion function sanitizeValue ( value: number, currentValue: number, stepBuffer?: number ): number { const stepping = stepBuffer !== undefined if (!stepBuffer) { stepBuffer = value - currentValue > 0 ? 1 : -1 } const markValues = markValuesRef.value || [] const { step } = props if (step === 'mark') { const closestMark = getClosestMark( value, markValues.concat(currentValue), stepping ? stepBuffer : undefined ) return closestMark ? closestMark.value : currentValue } if (step <= 0) return currentValue const { value: precision } = precisionRef let closestMark // if it is a stepping, priority will be given to the marks // on the rail, otherwise take the nearest one if (stepping) { const currentStep = Number((currentValue / step).toFixed(precision)) const actualStep = Math.floor(currentStep) const leftStep = currentStep > actualStep ? actualStep : actualStep - 1 const rightStep = currentStep < actualStep ? actualStep : actualStep + 1 closestMark = getClosestMark( currentValue, [ Number((leftStep * step).toFixed(precision)), Number((rightStep * step).toFixed(precision)), ...markValues ], stepBuffer ) } else { const roundValue = getRoundValue(value) closestMark = getClosestMark(value, [...markValues, roundValue]) } return closestMark ? clampValue(closestMark.value) : currentValue } function clampValue (value: number): number { return Math.min(props.max, Math.max(props.min, value)) } function valueToPercentage (value: number): number { const { max, min } = props return ((value - min) / (max - min)) * 100 } function percentageToValue (percentage: number): number { const { max, min } = props return min + (max - min) * percentage } function getRoundValue (value: number): number { const { step, min } = props if (step <= 0 || step === 'mark') return value const newValue = Math.round((value - min) / step) * step + min return Number(newValue.toFixed(precisionRef.value)) } function getClosestMark ( currentValue: number, markValues = markValuesRef.value, buffer?: number ): ClosestMark | null { if (!markValues || !markValues.length) return null let closestMark: ClosestMark | null = null let index = -1 while (++index < markValues.length) { const diff = markValues[index] - currentValue const distance = Math.abs(diff) if ( // find marks in the same direction (buffer === undefined || diff * buffer > 0) && (closestMark === null || distance < closestMark.distance) ) { closestMark = { index, distance, value: markValues[index] } } } return closestMark } function getPointValue (event: MouseEvent | TouchEvent): number | undefined { const railEl = handleRailRef.value if (!railEl) return const touchEvent = isTouchEvent(event) ? event.touches[0] : event const railRect = railEl.getBoundingClientRect() let percentage: number if (props.vertical) { percentage = (railRect.bottom - touchEvent.clientY) / railRect.height } else { percentage = (touchEvent.clientX - railRect.left) / railRect.width } if (props.reverse) { percentage = 1 - percentage } return percentageToValue(percentage) } // dom event handle function handleRailKeyDown (e: KeyboardEvent): void { if (mergedDisabledRef.value) return const { vertical, reverse } = props switch (e.code) { case 'ArrowUp': e.preventDefault() handleStepValue(vertical && reverse ? -1 : 1) break case 'ArrowRight': e.preventDefault() handleStepValue(!vertical && reverse ? -1 : 1) break case 'ArrowDown': e.preventDefault() handleStepValue(vertical && reverse ? 1 : -1) break case 'ArrowLeft': e.preventDefault() handleStepValue(!vertical && reverse ? 1 : -1) break } } function handleStepValue (ratio: number): void { const activeIndex = activeIndexRef.value if (activeIndex === -1) return const { step } = props const currentValue = arrifiedValueRef.value[activeIndex] const nextValue = step <= 0 || step === 'mark' ? currentValue : currentValue + step * ratio doDispatchValue( // Avoid the number of value does not change when `step` is null sanitizeValue(nextValue, currentValue, ratio > 0 ? 1 : -1), activeIndex ) } function handleRailMouseDown (event: MouseEvent | TouchEvent): void { if (mergedDisabledRef.value) return if (!isTouchEvent(event) && event.button !== eventButtonLeft) { return } const pointValue = getPointValue(event) if (pointValue === undefined) return const values = arrifiedValueRef.value.slice() const activeIndex = props.range ? getClosestMark(pointValue, values)?.index ?? -1 : 0 if (activeIndex !== -1) { // avoid triggering scrolling on touch event.preventDefault() focusActiveHandle(activeIndex) startDragging() doDispatchValue( sanitizeValue(pointValue, arrifiedValueRef.value[activeIndex]), activeIndex ) } } function startDragging (): void { if (!draggingRef.value) { draggingRef.value = true on('touchend', document, handleMouseUp) on('mouseup', document, handleMouseUp) on('touchmove', document, handleMouseMove) on('mousemove', document, handleMouseMove) } } function stopDragging (): void { if (draggingRef.value) { draggingRef.value = false off('touchend', document, handleMouseUp) off('mouseup', document, handleMouseUp) off('touchmove', document, handleMouseMove) off('mousemove', document, handleMouseMove) } } function handleMouseMove (event: MouseEvent | TouchEvent): void { const { value: activeIndex } = activeIndexRef if (!draggingRef.value || activeIndex === -1) { stopDragging() return } const pointValue = getPointValue(event) as number doDispatchValue( sanitizeValue(pointValue, arrifiedValueRef.value[activeIndex]), activeIndex ) } function handleMouseUp (): void { stopDragging() } function handleHandleFocus (index: number): void { activeIndexRef.value = index // Wake focus style if (!mergedDisabledRef.value) { hoverIndexRef.value = index } } function handleHandleBlur (index: number): void { if (activeIndexRef.value === index) { activeIndexRef.value = -1 stopDragging() } if (hoverIndexRef.value === index) { hoverIndexRef.value = -1 } } function handleHandleMouseEnter (index: number): void { hoverIndexRef.value = index } function handleHandleMouseLeave (index: number): void { if (hoverIndexRef.value === index) { hoverIndexRef.value = -1 } } watch( activeIndexRef, (_, previous) => void nextTick(() => (previousIndexRef.value = previous)) ) watch(mergedValueRef, () => { if (props.marks) { if (dotTransitionDisabledRef.value) return dotTransitionDisabledRef.value = true void nextTick(() => { dotTransitionDisabledRef.value = false }) } void nextTick(syncPosition) }) return { mergedClsPrefix: mergedClsPrefixRef, namespace: namespaceRef, uncontrolledValue: uncontrolledValueRef, mergedValue: mergedValueRef, mergedDisabled: mergedDisabledRef, mergedPlacement: mergedPlacementRef, isMounted: useIsMounted(), adjustedTo: useAdjustedTo(props), dotTransitionDisabled: dotTransitionDisabledRef, markInfos: markInfosRef, isShowTooltip, isSkipCSSDetection, handleRailRef, setHandleRefs, setFollowerRefs, fillStyle: fillStyleRef, getHandleStyle, activeIndex: activeIndexRef, arrifiedValues: arrifiedValueRef, followerEnabledIndexSet: followerEnabledIndexSetRef, handleRailMouseDown, handleHandleFocus, handleHandleBlur, handleHandleMouseEnter, handleHandleMouseLeave, handleRailKeyDown, indicatorCssVars: computed(() => { const { self: { fontSize, indicatorColor, indicatorBoxShadow, indicatorTextColor, indicatorBorderRadius } } = themeRef.value return { '--n-font-size': fontSize, '--n-indicator-border-radius': indicatorBorderRadius, '--n-indicator-box-shadow': indicatorBoxShadow, '--n-indicator-color': indicatorColor, '--n-indicator-text-color': indicatorTextColor } }), cssVars: computed(() => { const { self: { railColor, railColorHover, fillColor, fillColorHover, handleColor, opacityDisabled, dotColor, dotColorModal, handleBoxShadow, handleBoxShadowHover, handleBoxShadowActive, handleBoxShadowFocus, dotBorder, dotBoxShadow, railHeight, railWidthVertical, handleSize, dotHeight, dotWidth, dotBorderRadius, fontSize, dotBorderActive, dotColorPopover }, common: { cubicBezierEaseInOut } } = themeRef.value return { '--n-bezier': cubicBezierEaseInOut, '--n-dot-border': dotBorder, '--n-dot-border-active': dotBorderActive, '--n-dot-border-radius': dotBorderRadius, '--n-dot-box-shadow': dotBoxShadow, '--n-dot-color': dotColor, '--n-dot-color-modal': dotColorModal, '--n-dot-color-popover': dotColorPopover, '--n-dot-height': dotHeight, '--n-dot-width': dotWidth, '--n-fill-color': fillColor, '--n-fill-color-hover': fillColorHover, '--n-font-size': fontSize, '--n-handle-box-shadow': handleBoxShadow, '--n-handle-box-shadow-active': handleBoxShadowActive, '--n-handle-box-shadow-focus': handleBoxShadowFocus, '--n-handle-box-shadow-hover': handleBoxShadowHover, '--n-handle-color': handleColor, '--n-handle-size': handleSize, '--n-opacity-disabled': opacityDisabled, '--n-rail-color': railColor, '--n-rail-color-hover': railColorHover, '--n-rail-height': railHeight, '--n-rail-width-vertical': railWidthVertical } }) } }, render () { const { mergedClsPrefix, formatTooltip } = this return ( <div class={[ `${mergedClsPrefix}-slider`, { [`${mergedClsPrefix}-slider--disabled`]: this.mergedDisabled, [`${mergedClsPrefix}-slider--active`]: this.activeIndex !== -1, [`${mergedClsPrefix}-slider--with-mark`]: this.marks, [`${mergedClsPrefix}-slider--vertical`]: this.vertical, [`${mergedClsPrefix}-slider--reverse`]: this.reverse } ]} style={this.cssVars as CSSProperties} onKeydown={this.handleRailKeyDown} onMousedown={this.handleRailMouseDown} onTouchstart={this.handleRailMouseDown} > <div class={`${mergedClsPrefix}-slider-rail`}> <div class={`${mergedClsPrefix}-slider-rail__fill`} style={this.fillStyle} /> {this.marks ? ( <div class={[ `${mergedClsPrefix}-slider-dots`, { [`${mergedClsPrefix}-slider-dots--transition-disabled`]: this.dotTransitionDisabled } ]} > {this.markInfos.map((mark) => ( <div key={mark.label} class={[ `${mergedClsPrefix}-slider-dot`, { [`${mergedClsPrefix}-slider-dot--active`]: mark.active } ]} style={mark.style} /> ))} </div> ) : null} <div ref="handleRailRef" class={`${mergedClsPrefix}-slider-handles`}> {this.arrifiedValues.map((value, index) => { const showTooltip = this.isShowTooltip(index) return ( <VBinder> {{ default: () => [ <VTarget> {{ default: () => ( <div ref={this.setHandleRefs(index)} class={`${mergedClsPrefix}-slider-handle`} tabindex={this.mergedDisabled ? -1 : 0} style={this.getHandleStyle(value, index)} onFocus={() => this.handleHandleFocus(index)} onBlur={() => this.handleHandleBlur(index)} onMouseenter={() => this.handleHandleMouseEnter(index) } onMouseleave={() => this.handleHandleMouseLeave(index) } /> ) }} </VTarget>, this.tooltip && ( <VFollower ref={this.setFollowerRefs(index)} show={showTooltip} to={this.adjustedTo} enabled={this.followerEnabledIndexSet.has(index)} teleportDisabled={ this.adjustedTo === useAdjustedTo.tdkey } placement={this.mergedPlacement} containerClass={this.namespace} > {{ default: () => ( <Transition name="fade-in-scale-up-transition" appear={this.isMounted} css={this.isSkipCSSDetection(index)} onEnter={() => this.followerEnabledIndexSet.add(index) } onAfterLeave={() => this.followerEnabledIndexSet.delete(index) } > {{ default: () => showTooltip ? ( <div class={[ `${mergedClsPrefix}-slider-handle-indicator`, `${mergedClsPrefix}-slider-handle-indicator--${this.mergedPlacement}` ]} style={ this.indicatorCssVars as CSSProperties } > {typeof formatTooltip === 'function' ? formatTooltip(value) : value} </div> ) : null }} </Transition> ) }} </VFollower> ) ] }} </VBinder> ) })} </div> {this.marks ? ( <div class={`${mergedClsPrefix}-slider-marks`}> {this.markInfos.map((mark) => ( <div key={mark.label} class={`${mergedClsPrefix}-slider-mark`} style={mark.style} > {mark.label} </div> ))} </div> ) : null} </div> </div> ) } })
the_stack
'use strict'; import * as fs from 'fs'; import * as path from 'path'; import { alignedLength, guessFileExtension, getBuffer } from './exportProvider'; function readSourceFile(sourceFilename: string): Buffer { if (typeof sourceFilename == 'undefined') { throw new Error('Input file undefined.'); } if (!fs.existsSync(sourceFilename)) { throw new Error('File not found.'); } // Read the GLB data const Binary = { Magic: 0x46546C67 }; const sourceBuf = fs.readFileSync(sourceFilename); const readMagic = sourceBuf.readUInt32LE(0); if (readMagic !== Binary.Magic) { throw new Error('Source file does not appear to be a GLB (glTF Binary) model.'); } const readVersion = sourceBuf.readUInt32LE(4); if (readVersion !== 2) { throw new Error('Only GLB version 2 is supported for import. Detected version: ' + readVersion); } return sourceBuf; } /** * Convert GLB -> glTF; overwrites any existing files. * * @param sourceFilename input glb filename * @param targetFilename output glTF filename */ export function ConvertGLBtoGltf(sourceFilename: string, targetFilename: string) { const sourceBuf = readSourceFile(sourceFilename); doConversion(sourceBuf, path.dirname(sourceFilename), targetFilename); } /** * This form of GLB -> glTF convert function will open and validate the input filename * before calling the parameter function to get a filename for output. This is allows * a UI to query a customer for a filename when its expected that the conversion will * succeed. * * @param sourceFilename input glb filename * @param getTargetFilename async function that will return the output gltf filename * @returns the output filename */ export async function ConvertGLBtoGltfLoadFirst(sourceFilename: string, getTargetFilename: () => Promise<string>): Promise<string> { const sourceBuf = readSourceFile(sourceFilename); const targetFilename = await getTargetFilename(); if (targetFilename != null) { doConversion(sourceBuf, path.dirname(sourceFilename), targetFilename); } return targetFilename; } function doConversion(sourceBuf: Buffer, pathBase: string, targetFilename: string) { // Strip off the '.glb' or other file extension, for use as a base name for external assets. let targetBasename = targetFilename; if (path.extname(targetFilename).length > 1) { const components = targetFilename.split('.'); components.pop(); targetBasename = components.join('.'); } const jsonBufSize = sourceBuf.readUInt32LE(12); const jsonString = sourceBuf.toString('utf8', 20, jsonBufSize + 20); const gltf = JSON.parse(jsonString); const binBuffer = sourceBuf.slice(jsonBufSize + 28); // returns any image objects for the given bufferView index if the buffer view is an image function findImagesForBufferView(bufferViewIndex: number): Array<any> { if (gltf.images !== undefined && gltf.images instanceof Array) { return gltf.images.filter((i: any) => i.bufferView === bufferViewIndex); } return []; } // writes to the filesystem image data from the parameters function writeImageBuf(images: Array<any>, bufferViewIndex: number, binBuffer: Buffer) { const view = gltf.bufferViews[bufferViewIndex]; const offset: number = view.byteOffset === undefined ? 0 : view.byteOffset; const length: number = view.byteLength; const firstReference = images[0]; const extension = guessFileExtension(firstReference.mimeType); const imageIndex = gltf.images.indexOf(firstReference); const filename = targetBasename + '_img' + imageIndex.toString() + extension; const buf = getBuffer(gltf, view.buffer, pathBase, binBuffer); if (buf === null) { throw new Error('Content of bufferId ' + view.bufferId + ' not found.'); } fs.writeFileSync(filename, buf.slice(offset, offset + length), 'binary'); images.forEach(image => { delete image.bufferView; delete image.mimeType; image.uri = path.basename(filename); }); } // returns any shaders for the given bufferView index if the buffer view is a shader function findShadersForBufferView(bufferViewIndex: number): Array<any> { if (gltf.shaders && gltf.shaders instanceof Array) { return gltf.shaders.filter((s: any) => s.bufferView === bufferViewIndex); } return []; } // writes to the filesystem shader data from the parameters function writeShaderBuf(shaders: Array<any>, bufferViewIndex: number, binBuffer: Buffer) { const view = gltf.bufferViews[bufferViewIndex]; const offset: number = view.byteOffset === undefined ? 0 : view.byteOffset; const length: number = view.byteLength; let extension = '.glsl'; const GL_VERTEX_SHADER_ARB = 0x8B31; const GL_FRAGMENT_SHADER_ARB = 0x8B30; const firstReference = shaders[0]; if (firstReference.type == GL_VERTEX_SHADER_ARB) { extension = '.vert'; } else if (firstReference.type == GL_FRAGMENT_SHADER_ARB) { extension = '.frag'; } const shaderIndex = gltf.shaders.indexOf(firstReference); const filename = targetBasename + '_shader' + shaderIndex.toString() + extension; const buf = getBuffer(gltf, view.buffer, pathBase, binBuffer); if (buf === null) { throw new Error('Content of bufferId ' + view.bufferId + ' not found.'); } fs.writeFileSync(filename, buf.slice(offset, offset + length), 'binary'); shaders.forEach(shader => { delete shader.bufferView; delete shader.mimeType; shader.uri = path.basename(filename); }); } function writeExtensionBuffer(buffers: { 'buffer': any, 'name': string }[], bufferViewIndex: number, binBuffer: Buffer) { const view = gltf.bufferViews[bufferViewIndex]; const offset: number = view.byteOffset === undefined ? 0 : view.byteOffset; const length: number = view.byteLength; const firstReference = buffers[0]; const extension = guessFileExtension(firstReference.buffer.mimeType); const filename = targetBasename + '_' + firstReference.name + '_' + bufferViewIndex.toString() + extension; const buf = getBuffer(gltf, view.buffer, pathBase, binBuffer); if (buf === null) { throw new Error('Content of bufferId ' + view.bufferId + ' not found.'); } fs.writeFileSync(filename, buf.slice(offset, offset + length), 'binary'); buffers.forEach(buffer => { delete buffer.buffer.bufferView; delete buffer.buffer.mimeType; buffer.buffer.uri = path.basename(filename); }); } function findExtensionBuffers(gltf: any, bufferViewIndex: number): { 'buffer': any, 'name': string }[] { const buffers = []; if (gltf.extensions) { for (const extensionName in gltf.extensions) { const extension = gltf.extensions[extensionName]; for (const extensionPropertyName in extension) { const extensionProperty = extension[extensionPropertyName]; if (extensionProperty instanceof Array) { const bufferName = extensionName + '_' + extensionPropertyName; const curBuffers = extensionProperty.filter((b: any) => b.bufferView === bufferViewIndex); for (const buffer in curBuffers) { buffers.push({'buffer': curBuffers[buffer], 'name': bufferName}); } } } } } return buffers; } // data the represents the buffers that are neither images or shaders const bufferViewList: number[] = []; const bufferDataList: Buffer[] = []; function addToBinaryBuf(bufferViewIndex: number, binBuffer: Buffer) { const view = gltf.bufferViews[bufferViewIndex]; const offset: number = view.byteOffset === undefined ? 0 : view.byteOffset; const length: number = view.byteLength; const aLength = alignedLength(length); let bufPart: Buffer; const buf = getBuffer(gltf, view.buffer, pathBase, binBuffer); if (buf === null) { throw new Error('Content of bufferId ' + view.bufferId + ' not found.'); } if (length == aLength) { bufPart = buf.slice(offset, offset + length); } else { bufPart = Buffer.alloc(aLength, buf.slice(offset, offset + length)); } bufferViewList.push(bufferViewIndex); bufferDataList.push(bufPart); } // go through all the buffer views and break out buffers as separate files if (gltf.bufferViews) { for (let bufferViewIndex = 0; bufferViewIndex < gltf.bufferViews.length; bufferViewIndex++) { const images = findImagesForBufferView(bufferViewIndex); if (images.length > 0) { writeImageBuf(images, bufferViewIndex, binBuffer); continue; } const shaders = findShadersForBufferView(bufferViewIndex); if (shaders.length > 0) { writeShaderBuf(shaders, bufferViewIndex, binBuffer); continue; } const buffers = findExtensionBuffers(gltf, bufferViewIndex); if (buffers.length > 0) { writeExtensionBuffer(buffers, bufferViewIndex, binBuffer); continue; } addToBinaryBuf(bufferViewIndex, binBuffer); } } // create a file for the rest of the buffer data const newBufferView = []; let currentOffset = 0; for (let i = 0; i < bufferViewList.length; i++) { const view = gltf.bufferViews[bufferViewList[i]]; const length: number = bufferDataList[i].length; view.buffer = 0; view.byteOffset = currentOffset; view.byteLength = length; newBufferView.push(view); currentOffset += length; } gltf.bufferViews = newBufferView; function getNewBufferViewIndex(oldIndex: number) { const newIndex = bufferViewList.indexOf(oldIndex); if (newIndex < 0) { throw new Error('Problem mapping bufferView indices.'); } return newIndex; } // Renumber existing bufferView references. // No need to check gltf.images*.bufferView since images were broken out above. if (gltf.accessors) { for (const accessor of gltf.accessors) { if (accessor.bufferView !== undefined) { accessor.bufferView = getNewBufferViewIndex(accessor.bufferView); } if (accessor.sparse) { if (accessor.sparse.indices && accessor.sparse.indices.bufferView !== undefined) { accessor.sparse.indices.bufferView = getNewBufferViewIndex(accessor.sparse.indices.bufferView); } if (accessor.sparse.values && accessor.sparse.values.bufferView !== undefined) { accessor.sparse.values.bufferView = getNewBufferViewIndex(accessor.sparse.values.bufferView); } } } } if (gltf.meshes) { for (const mesh of gltf.meshes) { for (const primitive of mesh.primitives) { if (primitive.extensions && primitive.extensions.KHR_draco_mesh_compression) { primitive.extensions.KHR_draco_mesh_compression.bufferView = getNewBufferViewIndex(primitive.extensions.KHR_draco_mesh_compression.bufferView); } } } } const binFilename = targetBasename + '_data.bin'; const finalBuffer = Buffer.concat(bufferDataList); fs.writeFileSync(binFilename, finalBuffer, 'binary'); gltf.buffers = [{ uri: path.basename(binFilename), byteLength: finalBuffer.length }]; // write out the final GLTF json and open. const gltfString = JSON.stringify(gltf, null, ' '); fs.writeFileSync(targetFilename, gltfString, 'utf8'); }
the_stack
import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, ElementRef, EventEmitter, Input, NgZone, OnDestroy, Output, QueryList, ViewEncapsulation } from '@angular/core'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {Platform} from '@angular/cdk/platform'; import {fromEvent, Subject, Subscription} from 'rxjs'; import {takeUntil, startWith} from 'rxjs/operators'; import {MDCComponent} from '@angular-mdc/web/base'; import { MdcTopAppBarActionItem, MdcTopAppBarNavigationIcon, } from './top-app-bar.directives'; import { cssClasses, MDCTopAppBarAdapter, MDCTopAppBarBaseFoundation, MDCTopAppBarFoundation, MDCShortTopAppBarFoundation, MDCFixedTopAppBarFoundation } from '@material/top-app-bar'; /** Event object emitted by MdcTopAppBar navigation icon selected. */ export class MdcTopAppBarNavSelected { constructor( public source: MdcTopAppBar) { } } @Component({ selector: 'mdc-top-app-bar, [mdc-top-app-bar]', exportAs: 'mdcTopAppBar', host: { 'class': 'mdc-top-app-bar', '[class.mdc-top-app-bar--prominent]': 'prominent', '[class.mdc-top-app-bar--dense]': 'dense', '[class.mdc-top-app-bar--short]': 'short', '[class.mdc-top-app-bar--fixed]': 'fixed' }, template: '<ng-content></ng-content>', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None }) export class MdcTopAppBar extends MDCComponent<MDCTopAppBarBaseFoundation | MDCShortTopAppBarFoundation | MDCFixedTopAppBarFoundation | any> implements AfterContentInit, AfterViewInit, OnDestroy { /** Emits whenever the component is destroyed. */ private _destroyed = new Subject<void>(); @Input() get fixed(): boolean { return this._fixed; } set fixed(value: boolean) { if (value !== this._fixed) { this.setFixed(value); } } private _fixed: boolean = false; @Input() get prominent(): boolean { return this._prominent; } set prominent(value: boolean) { if (value !== this._prominent) { this.setProminent(value); } } private _prominent: boolean = false; @Input() get short(): boolean { return this._short; } set short(value: boolean) { if (value !== this._short) { this.setShort(value); } } private _short: boolean = false; @Input() get shortCollapsed(): boolean { return this._shortCollapsed; } set shortCollapsed(value: boolean) { if (value !== this._shortCollapsed) { this.setShortCollapsed(value); } } private _shortCollapsed: boolean = false; @Input() get dense(): boolean { return this._dense; } set dense(value: boolean) { if (value !== this._dense) { this.setDense(value); } } private _dense: boolean = false; @Input() get fixedAdjustElement(): HTMLElement | null { return this._fixedAdjustElement; } set fixedAdjustElement(element: HTMLElement | null) { if (this._fixedAdjustElement !== element) { this._fixedAdjustElement = element; this._initTopAppBar(); } } private _fixedAdjustElement: HTMLElement | null = null; @Input() get scrollTarget(): any { return this._scrollTarget; } set scrollTarget(target: any) { if (target !== this._scrollTarget) { this._scrollTarget = target ? target : this._platform.isBrowser ? window : undefined; this._initScrollHandler(); } } private _scrollTarget: any = this._platform.isBrowser ? this.scrollTarget || window : undefined; /** Event emitted when the navigation icon is selected. */ @Output() readonly navigationSelected: EventEmitter<MdcTopAppBarNavSelected> = new EventEmitter<MdcTopAppBarNavSelected>(); @ContentChild(MdcTopAppBarNavigationIcon, {static: false}) navigationIcon?: MdcTopAppBarNavigationIcon; @ContentChildren(MdcTopAppBarActionItem, { descendants: true }) actions!: QueryList<MdcTopAppBarActionItem>; private _scrollTargetSubscription: Subscription | null = null; getDefaultFoundation(): any { const adapter: MDCTopAppBarAdapter = { hasClass: (className: string) => this._getHostElement().classList.contains(className), addClass: (className: string) => this._getHostElement().classList.add(className), removeClass: (className: string) => { if (className === cssClasses.SHORT_COLLAPSED_CLASS && this.shortCollapsed) { return; } this._getHostElement().classList.remove(className); }, setStyle: (property: string, value: string) => this._getHostElement().style.setProperty(property, value), getTopAppBarHeight: () => this._getHostElement().clientHeight, notifyNavigationIconClicked: () => this.navigationSelected.emit({ source: this }), getViewportScrollY: () => { if (!this._platform.isBrowser) { return 0; } return this._scrollTarget[this._scrollTarget === window ? 'pageYOffset' : 'scrollTop']; }, getTotalActionItems: () => this.actions ? this.actions.length : 0 }; let foundation: MDCTopAppBarBaseFoundation; if (!this.elementRef) { return new MDCTopAppBarBaseFoundation(adapter); } if (this.short) { foundation = new MDCShortTopAppBarFoundation(adapter); } else if (this.fixed) { foundation = new MDCFixedTopAppBarFoundation(adapter); } else { foundation = new MDCTopAppBarFoundation(adapter); } return foundation; } constructor( private _ngZone: NgZone, private _platform: Platform, private _changeDetectorRef: ChangeDetectorRef, public elementRef: ElementRef) { super(elementRef); } ngAfterContentInit(): void { this.actions.changes.pipe(startWith(null), takeUntil(this._destroyed)) .subscribe(() => { if (this.short && this.actions.length) { this._getHostElement().classList.toggle(cssClasses.SHORT_HAS_ACTION_ITEM_CLASS); } }); } ngAfterViewInit(): void { this._initFoundation(); } ngOnDestroy(): void { this._destroyed.next(); this._destroyed.complete(); if (this._scrollTargetSubscription) { this._scrollTargetSubscription.unsubscribe(); } this._destroyFoundation(); } /** Sets the top app bar to fixed or not. */ setFixed(fixed: boolean, isUserInput: boolean = false): void { this._fixed = coerceBooleanProperty(fixed); if (this.fixed && this.short) { this.setShort(false); } if (isUserInput) { this._initFoundation(); } } /** Sets the top app bar to prominent or not. */ setProminent(prominent: boolean, isUserInput: boolean = false): void { this._prominent = coerceBooleanProperty(prominent); if (this.prominent && this.short) { this.setShort(false); } if (isUserInput) { this._initFoundation(); } } /** Sets the top app bar to dense variant. */ setDense(dense: boolean, isUserInput: boolean = false): void { this._dense = coerceBooleanProperty(dense); if (this.dense && this.short) { this.setShort(false); } if (isUserInput) { this._initFoundation(); } } /** Sets the top app bar to short or not. */ setShort(short: boolean, isUserInput: boolean = false): void { this._short = coerceBooleanProperty(short); if (this.short) { this.setProminent(false); this.setDense(false); this.setFixed(false); } else { this.setShortCollapsed(false); } if (isUserInput) { this._initFoundation(); } } /** Sets the top app bar to short-collapsed or not. */ setShortCollapsed(shortCollapsed: boolean, isUserInput: boolean = false): void { this._shortCollapsed = coerceBooleanProperty(shortCollapsed); if (this.shortCollapsed && !this.short) { this.setShort(true); } if (isUserInput) { this._initFoundation(); } } isCollapsed(): boolean { return this._getHostElement().classList.contains(cssClasses.SHORT_COLLAPSED_CLASS); } private _initFoundation(): void { this._destroyFoundation(); this._getHostElement().style.top = '0px'; this._resetFixedShort(); this._foundation = this.getDefaultFoundation(); this._foundation.init(); this._initTopAppBar(); this._initScrollHandler(); this._changeDetectorRef.markForCheck(); } private _resetFixedShort(): void { this._getHostElement().classList.remove(cssClasses.SHORT_HAS_ACTION_ITEM_CLASS); this._getHostElement().classList.remove(cssClasses.SHORT_COLLAPSED_CLASS); this._getHostElement().classList.remove(cssClasses.FIXED_SCROLLED_CLASS); } private _initTopAppBar(): void { if (!this.fixed) { this._getHostElement().classList.remove(cssClasses.FIXED_SCROLLED_CLASS); } if (this.fixed && this._getScrollOffset() > 0) { this._getHostElement().classList.add(cssClasses.FIXED_SCROLLED_CLASS); } if (!this.short) { this._getHostElement().classList.remove(cssClasses.SHORT_HAS_ACTION_ITEM_CLASS); this._getHostElement().classList.remove(cssClasses.SHORT_COLLAPSED_CLASS); } if (this.short && this._getScrollOffset() > 0) { this._getHostElement().classList.add(cssClasses.SHORT_COLLAPSED_CLASS); } if (this.shortCollapsed) { this._getHostElement().classList.add(cssClasses.SHORT_COLLAPSED_CLASS); } if (this.fixedAdjustElement) { this._removeFixedAdjustClasses(); this._addFixedAdjustClass(); } } private _removeFixedAdjustClasses(): void { this.fixedAdjustElement!.classList.remove('mdc-top-app-bar--short-fixed-adjust'); this.fixedAdjustElement!.classList.remove('mdc-top-app-bar--fixed-adjust'); this.fixedAdjustElement!.classList.remove('mdc-top-app-bar--dense-fixed-adjust'); this.fixedAdjustElement!.classList.remove('mdc-top-app-bar--prominent-fixed-adjust'); this.fixedAdjustElement!.classList.remove('mdc-top-app-bar--dense-prominent-fixed-adjust'); } private _addFixedAdjustClass(): void { if (this._short) { this.fixedAdjustElement!.classList.add('mdc-top-app-bar--short-fixed-adjust'); } else if (this._dense && this._prominent) { this.fixedAdjustElement!.classList.add('mdc-top-app-bar--dense-prominent-fixed-adjust'); } else if (this._dense) { this.fixedAdjustElement!.classList.add('mdc-top-app-bar--dense-fixed-adjust'); } else if (this._prominent) { this.fixedAdjustElement!.classList.add('mdc-top-app-bar--prominent-fixed-adjust'); } else { this.fixedAdjustElement!.classList.add('mdc-top-app-bar--fixed-adjust'); } } private _destroyFoundation(): void { this._foundation?.destroy(); } private _initScrollHandler(): void { if (this._scrollTargetSubscription) { this._scrollTargetSubscription.unsubscribe(); } if (!this._platform.isBrowser) { return; } this._scrollTargetSubscription = this._ngZone.runOutsideAngular(() => fromEvent<Event>(this.scrollTarget || window, 'scroll') .subscribe(() => this._ngZone.run(() => this._foundation.handleTargetScroll()))); } private _getScrollOffset(): number { if (!this._platform.isBrowser) { return 0; } return this.scrollTarget ? this.scrollTarget.scrollTop : window.pageYOffset; } /** Retrieves the DOM element of the component host. */ private _getHostElement(): HTMLElement { return this.elementRef.nativeElement; } }
the_stack
import { CompilerContext, isArray, isIterable, isObject, toFastProperties } from '@deepkit/core'; import { binaryBigIntAnnotation, BinaryBigIntType, buildFunction, callExtractedFunctionIfAvailable, collapsePath, ContainerAccessor, copyAndSetParent, createReference, excludedAnnotation, executeTemplates, extractStateToFunctionAndCallIt, getIndexCheck, getNameExpression, getTypeJitContainer, handleUnion, hasCircularReference, isBackReferenceType, isBinaryBigIntType, isMongoIdType, isNullable, isOptional, isReferenceHydrated, isReferenceInstance, isReferenceType, isUUIDType, JitStack, memberNameToString, mongoIdAnnotation, NamingStrategy, ReceiveType, referenceAnnotation, ReflectionClass, ReflectionKind, resolveReceiveType, resolveTypeMembers, RuntimeCode, Serializer, sortSignatures, TemplateRegistry, TemplateState, Type, TypeBigInt, TypeClass, TypeGuardRegistry, TypeIndexSignature, TypeLiteral, TypeObjectLiteral, typeSettings, TypeTuple, UnpopulatedCheck, unpopulatedSymbol, uuidAnnotation } from '@deepkit/type'; import { bsonTypeGuardArray, bsonTypeGuardForBsonTypes, bsonTypeGuardLiteral, bsonTypeGuardObjectLiteral, bsonTypeGuardTemplateLiteral, bsonTypeGuardTuple, bsonTypeGuardUnion, deserializeAny, deserializeArray, deserializeBigInt, deserializeBinary, deserializeBoolean, deserializeDate, deserializeLiteral, deserializeNull, deserializeNumber, deserializeObjectLiteral, deserializeRegExp, deserializeString, deserializeTemplateLiteral, deserializeTuple, deserializeUndefined, deserializeUnion } from './bson-deserializer-templates'; import { seekElementSize } from './continuation'; import { BSONError } from './model'; import { BSON_BINARY_SUBTYPE_DEFAULT, BSON_BINARY_SUBTYPE_UUID, BSONType, digitByteSize, isSerializable, TWO_PWR_32_DBL_N } from './utils'; export function createBuffer(size: number): Uint8Array { return 'undefined' !== typeof Buffer && 'function' === typeof Buffer.allocUnsafe ? Buffer.allocUnsafe(size) : new Uint8Array(size); } // BSON MAX VALUES const BSON_INT32_MAX = 0x7fffffff; const BSON_INT32_MIN = -0x80000000; // JS MAX PRECISE VALUES export const JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. export const JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. const LONG_MAX = 'undefined' !== typeof BigInt ? BigInt('9223372036854775807') : 9223372036854775807; const LONG_MIN = 'undefined' !== typeof BigInt ? BigInt('-9223372036854775807') : -9223372036854775807; export function hexToByte(hex: string, index: number = 0, offset: number = 0): number { let code1 = hex.charCodeAt(index * 2 + offset) - 48; if (code1 > 9) code1 -= 39; let code2 = hex.charCodeAt((index * 2) + offset + 1) - 48; if (code2 > 9) code2 -= 39; return code1 * 16 + code2; } export function uuidStringToByte(hex: string, index: number = 0): number { let offset = 0; //e.g. bef8de96-41fe-442f-b70c-c3a150f8c96c if (index > 3) offset += 1; if (index > 5) offset += 1; if (index > 7) offset += 1; if (index > 9) offset += 1; return hexToByte(hex, index, offset); } export function stringByteLength(str: string): number { if (!str) return 0; let size = 0; for (let i = 0; i < str.length; i++) { const c = str.charCodeAt(i); if (c < 128) size += 1; else if (c > 127 && c < 2048) size += 2; else size += 3; } return size; } function getBinaryBigIntSize(value: bigint): number { let hex = value.toString(16); if (hex[0] === '-') hex = hex.slice(1); if (hex === '0') return 4 + 1; if (hex.length % 2) hex = '0' + hex; return 4 + 1 + Math.ceil(hex.length / 2); } function getSignedBinaryBigIntSize(value: bigint): number { let hex = value.toString(16); if (hex[0] === '-') hex = hex.slice(1); if (hex === '0') return 4 + 1; if (hex.length % 2) hex = '0' + hex; return 4 + 1 + 1 + Math.ceil(hex.length / 2); } export function getValueSize(value: any): number { if (value instanceof ValueWithBSONSerializer) { if (isUUIDType(value.type)) { return 4 + 1 + 16; } else if (isMongoIdType(value.type)) { return 12; } else if (isBinaryBigIntType(value.type)) { const binaryBigInt = binaryBigIntAnnotation.getFirst(value.type)!; return binaryBigInt === BinaryBigIntType.unsigned ? getBinaryBigIntSize(value.value) : getSignedBinaryBigIntSize(value.value); } else { return getValueSize(value.value); } } else if ('boolean' === typeof value) { return 1; } else if ('string' === typeof value) { //size + content + null return 4 + stringByteLength(value) + 1; } else if ('bigint' === typeof value) { //per default bigint will be serialized as long, to be compatible with default mongo driver and mongo database. return 8; } else if ('number' === typeof value) { if (Math.floor(value) === value) { //it's an int if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { //32bit return 4; } else if (value >= JS_INT_MIN && value <= JS_INT_MAX) { //double, 64bit return 8; } else { //long return 8; } } else { //double return 8; } } else if (value instanceof Date) { return 8; } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) { let size = 4; //size size += 1; //sub type size += value.byteLength; return size; } else if (isArray(value)) { let size = 4; //object size for (let i = 0; i < value.length; i++) { size += 1; //element type size += digitByteSize(i); //element name size += getValueSize(value[i]); } size += 1; //null return size; } else if (value && value['_bsontype'] === 'Binary') { let size = 4; //size size += 1; //sub type size += value.buffer.byteLength; return size; } else if (value instanceof RegExp) { return stringByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1; } else if (isObject(value)) { let size = 4; //object size for (let i in value) { if (!value.hasOwnProperty(i)) continue; size += 1; //element type size += stringByteLength(i) + 1; //element name + null size += getValueSize(value[i]); } size += 1; //null return size; } //isObject() should be last return 0; } export class ValueWithBSONSerializer { constructor(public value: any, public type: Type) { } } export class Writer { public dataView: DataView; constructor(public buffer: Uint8Array, public offset: number = 0) { this.dataView = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); } writeUint32(v: number) { this.dataView.setUint32(this.offset, v, true); this.offset += 4; } writeInt32(v: number) { this.dataView.setInt32(this.offset, v, true); this.offset += 4; } writeDouble(v: number) { this.dataView.setFloat64(this.offset, v, true); this.offset += 8; } writeDelayedSize(v: number, position: number) { this.dataView.setUint32(position, v, true); } writeByte(v: number) { this.buffer[this.offset++] = v; } writeBuffer(buffer: Uint8Array, offset: number = 0) { // buffer.copy(this.buffer, this.buffer.byteOffset + this.offset); for (let i = offset; i < buffer.byteLength; i++) { this.buffer[this.offset++] = buffer[i]; } // this.offset += buffer.byteLength; } writeNull() { this.writeByte(0); } writeAsciiString(str: string | number) { str = 'string' === typeof str ? str : '' + str; for (let i = 0; i < str.length; i++) { this.buffer[this.offset++] = str.charCodeAt(i); } } writeString(str: string) { if (!str) return; if (typeof str !== 'string') return; for (let i = 0; i < str.length; i++) { const c = str.charCodeAt(i); if (c < 128) { this.buffer[this.offset++] = c; } else if (c > 127 && c < 2048) { this.buffer[this.offset++] = (c >> 6) | 192; this.buffer[this.offset++] = ((c & 63) | 128); } else { this.buffer[this.offset++] = (c >> 12) | 224; this.buffer[this.offset++] = ((c >> 6) & 63) | 128; this.buffer[this.offset++] = (c & 63) | 128; } } } getBigIntBSONType(value: bigint): number { if (BSON_INT32_MIN <= value && value <= BSON_INT32_MAX) { return BSONType.INT; } else if (LONG_MIN <= value && value <= LONG_MAX) { return BSONType.LONG; } else { return BSONType.BINARY; } } writeBigIntLong(value: bigint) { if (value < 0) { this.writeInt32(~Number(-value % BigInt(TWO_PWR_32_DBL_N)) + 1 | 0); //low this.writeInt32(~(Number(-value / BigInt(TWO_PWR_32_DBL_N))) | 0); //high } else { this.writeInt32(Number(value % BigInt(TWO_PWR_32_DBL_N)) | 0); //low this.writeInt32(Number(value / BigInt(TWO_PWR_32_DBL_N)) | 0); //high } } writeBigIntBinary(value: bigint) { //custom binary let hex = value.toString(16); if (hex[0] === '-') hex = hex.slice(1); if (hex === '0') { this.writeUint32(0); this.writeByte(BSON_BINARY_SUBTYPE_DEFAULT); return; } if (hex.length % 2) hex = '0' + hex; let size = Math.ceil(hex.length / 2); this.writeUint32(size); this.writeByte(BSON_BINARY_SUBTYPE_DEFAULT); for (let i = 0; i < size; i++) { this.buffer[this.offset++] = hexToByte(hex, i); } } writeSignedBigIntBinary(value: bigint) { //custom binary let hex = value.toString(16); let signum = 0; if (hex[0] === '-') { //negative number signum = 1; hex = hex.slice(1); } if (hex === '0') { this.writeUint32(0); this.writeByte(BSON_BINARY_SUBTYPE_DEFAULT); return; } if (hex.length % 2) hex = '0' + hex; let size = Math.ceil(hex.length / 2); this.writeUint32(1 + size); this.writeByte(BSON_BINARY_SUBTYPE_DEFAULT); this.buffer[this.offset++] = signum === 1 ? 255 : 0; //0xff means negative, 0 means positive for (let i = 0; i < size; i++) { this.buffer[this.offset++] = hexToByte(hex, i); } } writeLong(value: number) { if (value > 9223372036854775807) value = 9223372036854775807; if (value < -9223372036854775807) value = -9223372036854775807; if (value < 0) { this.writeInt32(~(-value % TWO_PWR_32_DBL_N) + 1 | 0); //low this.writeInt32(~(-value / TWO_PWR_32_DBL_N) | 0); //high } else { this.writeInt32((value % TWO_PWR_32_DBL_N) | 0); //low this.writeInt32((value / TWO_PWR_32_DBL_N) | 0); //high } } writeUUID(value: string) { this.writeUint32(16); this.writeByte(BSON_BINARY_SUBTYPE_UUID); this.buffer[this.offset + 0] = uuidStringToByte(value, 0); this.buffer[this.offset + 1] = uuidStringToByte(value, 1); this.buffer[this.offset + 2] = uuidStringToByte(value, 2); this.buffer[this.offset + 3] = uuidStringToByte(value, 3); //- this.buffer[this.offset + 4] = uuidStringToByte(value, 4); this.buffer[this.offset + 5] = uuidStringToByte(value, 5); //- this.buffer[this.offset + 6] = uuidStringToByte(value, 6); this.buffer[this.offset + 7] = uuidStringToByte(value, 7); //- this.buffer[this.offset + 8] = uuidStringToByte(value, 8); this.buffer[this.offset + 9] = uuidStringToByte(value, 9); //- this.buffer[this.offset + 10] = uuidStringToByte(value, 10); this.buffer[this.offset + 11] = uuidStringToByte(value, 11); this.buffer[this.offset + 12] = uuidStringToByte(value, 12); this.buffer[this.offset + 13] = uuidStringToByte(value, 13); this.buffer[this.offset + 14] = uuidStringToByte(value, 14); this.buffer[this.offset + 15] = uuidStringToByte(value, 15); this.offset += 16; } writeObjectId(value: string) { this.buffer[this.offset + 0] = hexToByte(value, 0); this.buffer[this.offset + 1] = hexToByte(value, 1); this.buffer[this.offset + 2] = hexToByte(value, 2); this.buffer[this.offset + 3] = hexToByte(value, 3); this.buffer[this.offset + 4] = hexToByte(value, 4); this.buffer[this.offset + 5] = hexToByte(value, 5); this.buffer[this.offset + 6] = hexToByte(value, 6); this.buffer[this.offset + 7] = hexToByte(value, 7); this.buffer[this.offset + 8] = hexToByte(value, 8); this.buffer[this.offset + 9] = hexToByte(value, 9); this.buffer[this.offset + 10] = hexToByte(value, 10); this.buffer[this.offset + 11] = hexToByte(value, 11); this.offset += 12; } write(value: any, nameWriter?: () => void): void { if (value instanceof ValueWithBSONSerializer) { if (isUUIDType(value.type)) { if (nameWriter) { this.writeByte(BSONType.BINARY); nameWriter(); } this.writeUUID(value.value); } else if (isMongoIdType(value.type)) { if (nameWriter) { this.writeByte(BSONType.OID); nameWriter(); } this.writeObjectId(value.value); } else if (isBinaryBigIntType(value.type)) { if (nameWriter) { this.writeByte(BSONType.BINARY); nameWriter(); } const binary = binaryBigIntAnnotation.getFirst(value.type)!; if (binary === BinaryBigIntType.signed) { this.writeSignedBigIntBinary(value.value); } else { this.writeBigIntBinary(value.value); } } else { this.write(value.value, nameWriter); } } else if ('boolean' === typeof value) { if (nameWriter) { this.writeByte(BSONType.BOOLEAN); nameWriter(); } this.writeByte(value ? 1 : 0); } else if (value instanceof RegExp) { if (nameWriter) { this.writeByte(BSONType.REGEXP); nameWriter(); } this.writeString(value.source); this.writeNull(); if (value.ignoreCase) this.writeString('i'); if (value.global) this.writeString('s'); //BSON does not use the RegExp flag format if (value.multiline) this.writeString('m'); this.writeNull(); } else if ('string' === typeof value) { //size + content + null if (nameWriter) { this.writeByte(BSONType.STRING); nameWriter(); } const start = this.offset; this.offset += 4; //size placeholder this.writeString(value); this.writeByte(0); //null this.writeDelayedSize(this.offset - start - 4, start); } else if ('number' === typeof value) { if (Math.floor(value) === value && value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { //32bit int if (nameWriter) { this.writeByte(BSONType.INT); nameWriter(); } this.writeInt32(value); } else { //double if (nameWriter) { this.writeByte(BSONType.NUMBER); nameWriter(); } this.writeDouble(value); } } else if (value instanceof Date) { if (nameWriter) { this.writeByte(BSONType.DATE); nameWriter(); } this.writeLong(value.valueOf()); } else if ('bigint' === typeof value) { //this is only called for bigint in any structures. //to make sure the deserializing yields a bigint as well, we have to always use binary representation if (nameWriter) { this.writeByte(BSONType.BINARY); nameWriter(); } this.writeBigIntBinary(value); } else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) { if (nameWriter) { this.writeByte(BSONType.BINARY); nameWriter(); } this.writeArrayBuffer(value); } else if (isArray(value)) { if (nameWriter) { this.writeByte(BSONType.ARRAY); nameWriter(); } const start = this.offset; this.offset += 4; //size for (let i = 0; i < value.length; i++) { this.write(value[i], () => { this.writeAsciiString('' + i); this.writeByte(0); }); } this.writeNull(); this.writeDelayedSize(this.offset - start, start); } else if (value === undefined) { if (nameWriter) { this.writeByte(BSONType.UNDEFINED); nameWriter(); } } else if (value === null) { if (nameWriter) { this.writeByte(BSONType.NULL); nameWriter(); } } else if (isObject(value)) { if (nameWriter) { this.writeByte(BSONType.OBJECT); nameWriter(); } const start = this.offset; this.offset += 4; //size for (let i in value) { if (!value.hasOwnProperty(i)) continue; this.write(value[i], () => { this.writeString(i); this.writeByte(0); }); } this.writeNull(); this.writeDelayedSize(this.offset - start, start); } else { //the sizer incldues the type and name, so we have to write that if (nameWriter) { this.writeByte(BSONType.UNDEFINED); nameWriter(); } } } writeArrayBuffer(value: ArrayBuffer | ArrayBufferView) { let view = value instanceof ArrayBuffer ? new Uint8Array(value) : new Uint8Array(value.buffer, value.byteOffset, value.byteLength); if ((value as any)['_bsontype'] === 'Binary') { view = (value as any).buffer; } this.writeUint32(value.byteLength); this.writeByte(BSON_BINARY_SUBTYPE_DEFAULT); for (let i = 0; i < value.byteLength; i++) { this.buffer[this.offset++] = view[i]; } } } function getNameWriterCode(name: string): string { const nameSetter: string[] = []; //todo: support utf8 names for (let i = 0; i < name.length; i++) { nameSetter.push(`state.writer.buffer[state.writer.offset++] = ${name.charCodeAt(i)};`); } return ` //write name: '${name}' ${nameSetter.join('\n')} state.writer.writeByte(0); //null `; } function sizerObjectLiteral(type: TypeClass | TypeObjectLiteral, state: TemplateState, options: BSONSerializerOptions) { handleObjectLiteral(type, state, 'sizer', options); } function serializeObjectLiteral(type: TypeClass | TypeObjectLiteral, state: TemplateState, options: BSONSerializerOptions) { handleObjectLiteral(type, state, 'serialization', options); } function handleObjectLiteral( type: TypeClass | TypeObjectLiteral, state: TemplateState, target: 'serialization' | 'sizer', options: BSONSerializerOptions ) { let before: string = 'state.size += 4; //object size'; let after: string = 'state.size += 1; //null'; if (target === 'serialization') { const start = state.compilerContext.reserveName('start'); before = ` var ${start} = state.writer.offset; state.writer.offset += 4; //size`; after = ` state.writer.writeNull(); state.writer.writeDelayedSize(state.writer.offset - ${start}, ${start});`; } //emdedded for the moment disabled. treat it as normal property. // const embedded = embeddedAnnotation.getFirst(type); // if (embedded) { // if (type.kind !== ReflectionKind.class) throw new SerializationError(`Object literals can not be embedded`, collapsePath(state.path)); // const constructorProperties = getConstructorProperties(type); // if (!constructorProperties.properties.length) throw new BSONError(`Can not embed class ${getClassName(type.classType)} since it has no constructor properties`); // // if (constructorProperties.properties.length === 1) { // const first = constructorProperties.properties[0]; // let name = getNameExpression(state.namingStrategy.getPropertyName(first), state); // const setter = getEmbeddedAccessor(type, false, '', state.namingStrategy, first, embedded); // state.addCode(executeTemplates(state.fork('', new ContainerAccessor(state.accessor, name)).forPropertyName(setter || state.propertyName), first.type)); // } else { // const lines: string[] = []; // const containerProperty = getEmbeddedProperty(type); // // for (const property of constructorProperties.properties) { // const setter = getEmbeddedAccessor(type, true, '', state.namingStrategy, property, embedded); // lines.push(executeTemplates(state.fork('', new ContainerAccessor(state.accessor, JSON.stringify(property.name))).forPropertyName(setter), property.type)); // } // // if (containerProperty) { // state.addCode(` // ${lines.join('\n')} // `); // } else { // if (target === 'serialization') { // serializePropertyNameAware(type, state, BSONType.OBJECT, `'object' === typeof ${state.accessor}`, ` // //embedded class with multiple properties // ${before} // ${lines.join('\n')} // ${after} // `); // } else { // sizerPropertyNameAware(type, state, `'object' === typeof ${state.accessor}`, ` // //embedded class with multiple properties // ${before} // ${lines.join('\n')} // ${after} // `); // } // } // } // return; // } const existingCalled = callExtractedFunctionIfAvailable(state, type); const extract = existingCalled ? undefined : extractStateToFunctionAndCallIt(state, type); if (target === 'serialization') { serializePropertyNameAware(type, state, BSONType.OBJECT, `'object' === typeof ${state.accessor}`, ''); } else { sizerPropertyNameAware(type, state, `'object' === typeof ${state.accessor}`, ''); } if (type.kind === ReflectionKind.class && referenceAnnotation.hasAnnotations(type)) { state.setContext({ isObject, isReferenceInstance, isReferenceHydrated }); const reflection = ReflectionClass.from(type.classType); //the primary key is serialised for unhydrated references const index = getNameExpression(reflection.getPrimary().getName(), state); const primaryKey = reflection.getPrimary().getType(); //if a reference or forMongoDatabase=true only the foreign primary key is serialized state.replaceTemplate(` if ((${options.forMongoDatabase === true}) || (isReferenceInstance(${state.accessor}) && !isReferenceHydrated(${state.accessor}))) { ${executeTemplates(state.fork(state.setter, `${state.accessor}[${index}]`).forPropertyName(state.propertyName), primaryKey)} } else { ${state.template} } `); } //wrap circular check if necessary if (hasCircularReference(type)) { state.replaceTemplate(` if (!state._stack || !state._stack.includes(${state.accessor})) { ${state.template} } `); } if (!extract) return; state = extract.state; const lines: string[] = []; const signatures: TypeIndexSignature[] = []; const existing: string[] = []; state.setContext({ unpopulatedSymbol }); for (const member of resolveTypeMembers(type)) { if (member.kind === ReflectionKind.indexSignature) { if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; signatures.push(member); } if (member.kind !== ReflectionKind.property && member.kind !== ReflectionKind.propertySignature) continue; if (!isSerializable(member.type)) continue; const writeName = String(state.namingStrategy.getPropertyName(member, state.registry.serializer.name)); const readName = getNameExpression(memberNameToString(member.name), state); existing.push(readName); //back references are only serialized when it's not forMongoDatabase if (isBackReferenceType(member.type) && options.forMongoDatabase === true) continue; if (excludedAnnotation.isExcluded(member.type, state.registry.serializer.name)) continue; const accessor = `${state.accessor}[${readName}]`; const propertyState = state.fork('', accessor).extendPath(writeName); const setUndefined = isOptional(member) ? executeTemplates(propertyState.fork().forPropertyName(writeName), { kind: ReflectionKind.undefined }) : isNullable(member) ? executeTemplates(propertyState.fork().forPropertyName(writeName), { kind: ReflectionKind.null }) : ''; const template = executeTemplates(propertyState.fork().forPropertyName(writeName), member.type); if (!template) { throw new BSONError(`No template found for ${member.type.kind}`); } let converter = ` if (${accessor} === undefined || ${accessor} === unpopulatedSymbol) { ${setUndefined} } else { ${template} } `; if (isOptional(member)) { lines.push(` if (${readName} in ${state.accessor}) { ${converter} } `); } else { lines.push(converter); } } if (signatures.length) { const i = state.compilerContext.reserveName('i'); const existingCheck = existing.map(v => `${i} === ${v}`).join(' || ') || 'false'; const signatureLines: string[] = []; sortSignatures(signatures); for (const signature of signatures) { const accessor = new ContainerAccessor(state.accessor, i); const propertyState = state.fork(undefined, accessor).extendPath(new RuntimeCode(i)).forPropertyName(new RuntimeCode(i)); const setUndefined = isOptional(signature.type) ? executeTemplates(propertyState.fork().forPropertyName(new RuntimeCode(i)), { kind: ReflectionKind.undefined }) : isNullable(signature.type) ? executeTemplates(propertyState.fork().forPropertyName(new RuntimeCode(i)), { kind: ReflectionKind.null }) : ''; signatureLines.push(`else if (${getIndexCheck(state, i, signature.index)}) { if (${accessor} === undefined) { ${setUndefined} } else { ${executeTemplates(propertyState, signature.type)} } }`); } //the index signature type could be: string, number, symbol. //or a literal when it was constructed by a mapped type. lines.push(` for (const ${i} in ${state.accessor}) { if (!${state.accessor}.hasOwnProperty(${i})) continue; if (${existingCheck}) continue; if (false) {} ${signatureLines.join(' ')} } `); } state.addCode(` //handle objectLiteral via propertyName ${state.propertyName ? collapsePath([state.propertyName]) : ''} ${before} ${lines.join('\n')} ${after} `); extract.setFunction(buildFunction(state, type)); } function propertyNameWriter(state: TemplateState) { if (state.propertyName) { if (state.propertyName instanceof RuntimeCode) { return ` state.writer.writeAsciiString(${state.propertyName.code}); state.writer.writeByte(0); `; } else { return getNameWriterCode(state.propertyName); } } return ''; } function serializePropertyNameAware(type: Type, state: TemplateState, bsonType: BSONType, typeChecker: string, code: string): void { //when this call is reached first, and it's an object, then no type byte is needed. //todo: that does not work when arbitrary offset and already prefilled buffer is given const isInitialObject = `${bsonType === BSONType.OBJECT} && state.writer.offset === 0`; state.template = ` //serializer for ${type.kind} ${typeChecker ? `if (!(${typeChecker})) ${state.throwCode(type)}` : ''} if (${!!state.propertyName}) state.writer.writeByte(${bsonType}); ${propertyNameWriter(state)} ${state.template} ${code} `; } export class DigitByteRuntimeCode extends RuntimeCode { constructor(public code: string) { super(code); } } function sizerPropertyNameAware(type: Type, state: TemplateState, typeChecker: string, code: string): void { if (state.propertyName) { if (state.propertyName instanceof DigitByteRuntimeCode) { state.setContext({ digitByteSize }); //type + string size + null code = ` state.size += 1 + digitByteSize(${state.propertyName.code}); //type + byte of ${state.propertyName.code} ${code} `; } else if (state.propertyName instanceof RuntimeCode) { state.setContext({ stringByteLength }); //type + string size + null code = ` state.size += 1 + stringByteLength(${state.propertyName.code}) + 1; //type + string size of ${state.propertyName.code} + null ${code} `; } else { //type + string size + null code = ` state.size += 1 + ${stringByteLength(state.propertyName)} + 1; //type + string size of ${state.propertyName} + null ${code} `; } } const checker = typeChecker ? `if (!(${typeChecker})) ${state.throwCode(type)}` : ''; state.template = ` ${checker} ${state.template} ${code} `; } function sizerAny(type: Type, state: TemplateState) { state.setContext({ getValueSize }); sizerPropertyNameAware(type, state, ``, `state.size += getValueSize(${state.accessor});`); } function serializeAny(type: Type, state: TemplateState) { state.addCode(` state.writer.write(${state.accessor}, () => { ${propertyNameWriter(state)} }); `); } function sizerBoolean(type: Type, state: TemplateState) { sizerPropertyNameAware(type, state, `typeof ${state.accessor} === 'boolean'`, ` state.size += 1; `); } function sizerNumber(type: Type, state: TemplateState) { state.setContext({ getValueSize }); //per default bigint will be serialized as long, to be compatible with default mongo driver and mongo database. //We should add a new annotation, maybe like `bigint & Binary` to make it binary (unlimited size) sizerPropertyNameAware(type, state, `(typeof ${state.accessor} === 'number' || typeof ${state.accessor} === 'bigint') && !Number.isNaN(${state.accessor})`, ` state.size += getValueSize(${state.accessor}); `); } function serializeBoolean(type: Type, state: TemplateState) { serializePropertyNameAware(type, state, BSONType.BOOLEAN, `typeof ${state.accessor} === 'boolean'`, ` state.writer.writeByte(${state.accessor} ? 1 : 0); `); } function serializeString(type: Type, state: TemplateState) { if (uuidAnnotation.getFirst(type)) { serializePropertyNameAware(type, state, BSONType.BINARY, `typeof ${state.accessor} === 'string' && ${state.accessor}.length === 36`, `state.writer.writeUUID(${state.accessor});`); return; } if (mongoIdAnnotation.getFirst(type)) { serializePropertyNameAware(type, state, BSONType.OID, `typeof ${state.accessor} === 'string' && ${state.accessor}.length === 24`, `state.writer.writeObjectId(${state.accessor});`); return; } const start = state.compilerContext.reserveName('start'); serializePropertyNameAware(type, state, BSONType.STRING, `typeof ${state.accessor} === 'string'`, ` var ${start} = state.writer.offset; state.writer.offset += 4; //size placeholder state.writer.writeString(${state.accessor}); state.writer.writeByte(0); //null state.writer.writeDelayedSize(state.writer.offset - ${start} - 4, ${start}); `); } function sizeString(type: Type, state: TemplateState) { if (uuidAnnotation.getFirst(type)) { sizerPropertyNameAware(type, state, `typeof ${state.accessor} === 'string' && ${state.accessor}.length === 36`, ` state.size += 4 + 1 + 16; `); return; } if (mongoIdAnnotation.getFirst(type)) { sizerPropertyNameAware(type, state, `typeof ${state.accessor} === 'string' && ${state.accessor}.length === 24`, ` state.size += 12; `); return; } state.setContext({ getValueSize }); sizerPropertyNameAware(type, state, `typeof ${state.accessor} === 'string'`, ` state.size += getValueSize(${state.accessor}); `); } function serializeNumber(type: Type, state: TemplateState) { const nameWriter = propertyNameWriter(state); state.addCode(` if ('bigint' === typeof ${state.accessor}) { //long state.writer.writeByte(${BSONType.LONG}); ${nameWriter} state.writer.writeBigIntLong(${state.accessor}); } else if ('number' === typeof ${state.accessor} && !Number.isNaN(${state.accessor})) { if (Math.floor(${state.accessor}) === ${state.accessor} && ${state.accessor} >= ${BSON_INT32_MIN} && ${state.accessor} <= ${BSON_INT32_MAX}) { //32bit int state.writer.writeByte(${BSONType.INT}); ${nameWriter} state.writer.writeInt32(${state.accessor}); } else { //double, 64bit state.writer.writeByte(${BSONType.NUMBER}); ${nameWriter} state.writer.writeDouble(${state.accessor}); } } `); } function sizerBigInt(type: TypeBigInt, state: TemplateState) { const binaryBigInt = binaryBigIntAnnotation.getFirst(type); if (binaryBigInt !== undefined) { state.setContext({ getBinaryBigIntSize, getSignedBinaryBigIntSize }); const bigIntSize = binaryBigInt === BinaryBigIntType.unsigned ? 'getBinaryBigIntSize' : 'getSignedBinaryBigIntSize'; //per default bigint will be serialized as long, to be compatible with default mongo driver and mongo database. //We should add a new annotation, maybe like `bigint & Binary` to make it binary (unlimited size) sizerPropertyNameAware(type, state, `(typeof ${state.accessor} === 'number' || typeof ${state.accessor} === 'bigint') && !Number.isNaN(${state.accessor})`, ` state.size += ${bigIntSize}(${state.accessor}); `); } else { sizerNumber(type, state); } } function serializeBigInt(type: TypeBigInt, state: TemplateState) { const binaryBigInt = binaryBigIntAnnotation.getFirst(type); if (binaryBigInt !== undefined) { const nameWriter = propertyNameWriter(state); const writeBigInt = binaryBigInt === BinaryBigIntType.unsigned ? 'writeBigIntBinary' : 'writeSignedBigIntBinary'; state.addCode(` if (('bigint' === typeof ${state.accessor} || 'number' === typeof ${state.accessor}) && !Number.isNaN(${state.accessor})) { //long state.writer.writeByte(${BSONType.BINARY}); ${nameWriter} state.writer.${writeBigInt}(${state.accessor}); }`); } else { serializeNumber(type, state); } } function sizerRegExp(type: Type, state: TemplateState) { state.setContext({ stringByteLength }); sizerPropertyNameAware(type, state, `${state.accessor} instanceof RegExp`, ` state.size += stringByteLength(${state.accessor}.source) + 1 + (${state.accessor}.global ? 1 : 0) + (${state.accessor}.ignoreCase ? 1 : 0) + (${state.accessor}.multiline ? 1 : 0) + 1; `); } function serializeRegExp(type: Type, state: TemplateState) { serializePropertyNameAware(type, state, BSONType.REGEXP, `${state.accessor} instanceof RegExp`, ` state.writer.writeString(${state.accessor}.source); state.writer.writeNull(); if (${state.accessor}.ignoreCase) state.writer.writeString('i'); if (${state.accessor}.global) state.writer.writeString('s'); //BSON does not use the RegExp flag format if (${state.accessor}.multiline) state.writer.writeString('m'); state.writer.writeNull(); `); } function sizerLiteral(type: TypeLiteral, state: TemplateState) { if ('string' === typeof type.literal) { sizeString(type, state); } else if ('number' === typeof type.literal || 'bigint' === typeof type.literal) { sizerNumber(type, state); } else if ('boolean' === typeof type.literal) { sizerBoolean(type, state); } else if (type.literal instanceof RegExp) { sizerRegExp(type, state); } } function serializeLiteral(type: TypeLiteral, state: TemplateState) { if ('string' === typeof type.literal) { serializeString(type, state); } else if ('number' === typeof type.literal || 'bigint' === typeof type.literal) { serializeNumber(type, state); } else if ('boolean' === typeof type.literal) { serializeBoolean(type, state); } else if (type.literal instanceof RegExp) { serializeRegExp(type, state); } } function sizerBinary(type: TypeClass, state: TemplateState) { state.setContext({ ArrayBuffer }); sizerPropertyNameAware(type, state, `${state.accessor} instanceof ArrayBuffer || ArrayBuffer.isView(${state.accessor})`, ` state.size += 4 + 1 + ${state.accessor}.byteLength; `); } function serializeBinary(type: TypeClass, state: TemplateState) { state.setContext({ ArrayBuffer }); serializePropertyNameAware(type, state, BSONType.BINARY, `${state.accessor} instanceof ArrayBuffer || ArrayBuffer.isView(${state.accessor})`, ` state.writer.writeArrayBuffer(${state.accessor}); `); } function sizerArray(elementType: Type, state: TemplateState) { state.setContext({ isIterable }); const i = state.compilerContext.reserveName('i'); const item = state.compilerContext.reserveName('item'); sizerPropertyNameAware(elementType, state, `isIterable(${state.accessor})`, ` state.size += 4; //array size let ${i} = 0; for (const ${item} of ${state.accessor}) { ${executeTemplates(state.fork('', item).extendPath(new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), elementType)} ${i}++; } state.size += 1; //null `); } function serializeArray(elementType: Type, state: TemplateState) { state.setContext({ isIterable }); const start = state.compilerContext.reserveName('start'); const i = state.compilerContext.reserveName('i'); const item = state.compilerContext.reserveName('item'); serializePropertyNameAware(elementType, state, BSONType.ARRAY, `isIterable(${state.accessor})`, ` var ${start} = state.writer.offset; state.writer.offset += 4; //size let ${i} = 0; for (const ${item} of ${state.accessor}) { ${executeTemplates(state.fork('', item).extendPath(new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), elementType)} ${i}++; } state.writer.writeNull(); state.writer.writeDelayedSize(state.writer.offset - ${start}, ${start}); `); } function serializeTuple(type: TypeTuple, state: TemplateState) { //[string, number], easy //[...string, number], easy //[number, ...string], easy //[number, ...string, number, string], medium const lines: string[] = []; let restEndOffset = 0; const i = state.compilerContext.reserveName('i'); for (let i = 0; i < type.types.length; i++) { if (type.types[i].type.kind === ReflectionKind.rest) { restEndOffset = type.types.length - (i + 1); break; } } for (const member of type.types) { if (member.type.kind === ReflectionKind.rest) { lines.push(` for (; ${i} < ${state.accessor}.length - ${restEndOffset}; ${i}++) { ${executeTemplates(state.fork('', `${state.accessor}[${i}]`).extendPath(member.name || new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), member.type.type)} } `); } else { const optionalCheck = member.optional ? `${state.accessor}[${i}] !== undefined` : 'true'; lines.push(` if (${optionalCheck}) { ${executeTemplates(state.fork('', `${state.accessor}[${i}]`).extendPath(member.name || new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), member.type)} } ${i}++; `); } } const start = state.compilerContext.reserveName('start'); state.setContext({ isArray }); serializePropertyNameAware(type, state, BSONType.ARRAY, `isArray(${state.accessor})`, ` let ${i} = 0; var ${start} = state.writer.offset; state.writer.offset += 4; //size ${lines.join('\n')} state.writer.writeNull(); state.writer.writeDelayedSize(state.writer.offset - ${start}, ${start}); `); } function sizerTuple(type: TypeTuple, state: TemplateState) { //[string, number], easy //[...string, number], easy //[number, ...string], easy //[number, ...string, number, string], medium const lines: string[] = []; let restEndOffset = 0; const i = state.compilerContext.reserveName('i'); for (let i = 0; i < type.types.length; i++) { if (type.types[i].type.kind === ReflectionKind.rest) { restEndOffset = type.types.length - (i + 1); break; } } for (const member of type.types) { if (member.type.kind === ReflectionKind.rest) { lines.push(` for (; ${i} < ${state.accessor}.length - ${restEndOffset}; ${i}++) { ${executeTemplates(state.fork('', `${state.accessor}[${i}]`).extendPath(member.name || new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), member.type.type)} } `); } else { const optionalCheck = member.optional ? `${state.accessor}[${i}] !== undefined` : 'true'; lines.push(` if (${optionalCheck}) { ${executeTemplates(state.fork('', `${state.accessor}[${i}]`).extendPath(member.name || new RuntimeCode(i)).forPropertyName(new DigitByteRuntimeCode(i)), member.type)} } ${i}++; `); } } state.setContext({ isArray }); sizerPropertyNameAware(type, state, `isArray(${state.accessor})`, ` let ${i} = 0; state.size += 4; //array size ${lines.join('\n')} state.size += 1; //null `); } interface BSONSerializerOptions { /** * If true the serializes changes slightly its behaviour to make it compatible with the mongo database. * For example are fields marked as BackReference excluded. * Fields marked as Reference() will only serialize its primary key. * * */ forMongoDatabase?: true; } export class BSONBinarySerializer extends Serializer { name = 'bson'; serializeId: symbol = Symbol('BSONBinarySerializer'); deserializeId: symbol = Symbol('BSONBinarySerializer'); sizerId: symbol = Symbol('BSONBinarySerializer'); public sizerRegistry = new TemplateRegistry(this); public bsonSerializeRegistry = new TemplateRegistry(this); public bsonDeserializeRegistry = new TemplateRegistry(this); public bsonTypeGuards = new TypeGuardRegistry(this); constructor(protected options: BSONSerializerOptions = {}) { super(); this.registerSizer(); this.registerBsonSerializers(); this.registerBsonDeserializers(); this.registerBsonTypeGuards(); } protected registerSizer() { this.sizerRegistry.register(ReflectionKind.any, sizerAny); this.sizerRegistry.register(ReflectionKind.unknown, sizerAny); this.sizerRegistry.register(ReflectionKind.never, () => undefined); this.sizerRegistry.register(ReflectionKind.class, (type, state) => sizerObjectLiteral(type, state, this.options)); this.sizerRegistry.register(ReflectionKind.objectLiteral, (type, state) => sizerObjectLiteral(type, state, this.options)); this.sizerRegistry.register(ReflectionKind.string, sizeString); this.sizerRegistry.register(ReflectionKind.templateLiteral, sizeString); this.sizerRegistry.register(ReflectionKind.boolean, sizerBoolean); this.sizerRegistry.register(ReflectionKind.promise, ((type, state) => executeTemplates(state, type.type))); this.sizerRegistry.register(ReflectionKind.number, sizerNumber); this.sizerRegistry.register(ReflectionKind.bigint, sizerBigInt); this.sizerRegistry.register(ReflectionKind.literal, sizerLiteral); this.sizerRegistry.register(ReflectionKind.regexp, sizerRegExp); this.sizerRegistry.register(ReflectionKind.array, (type, state) => sizerArray(type.type as Type, state)); this.sizerRegistry.register(ReflectionKind.tuple, sizerTuple); this.sizerRegistry.registerClass(Map, (type, state) => sizerArray(copyAndSetParent({ kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, name: 'key', type: type.arguments![0] }, { kind: ReflectionKind.tupleMember, name: 'value', type: type.arguments![1] }, ] }), state)); this.sizerRegistry.registerClass(Set, (type, state) => sizerArray(type.arguments![0] as Type, state)); this.sizerRegistry.registerClass(Date, (type, state) => sizerPropertyNameAware(type, state, `${state.accessor} instanceof Date`, `state.size += 8;`)); this.sizerRegistry.register(ReflectionKind.undefined, (type, state) => sizerPropertyNameAware(type, state, `${state.accessor} === undefined || ${state.accessor} === null`, ``)); this.sizerRegistry.register(ReflectionKind.void, (type, state) => sizerPropertyNameAware(type, state, `${state.accessor} === undefined || ${state.accessor} === null`, ``)); this.sizerRegistry.register(ReflectionKind.null, (type, state) => sizerPropertyNameAware(type, state, `${state.accessor} === undefined || ${state.accessor} === null`, ``)); this.sizerRegistry.registerBinary(sizerBinary); this.sizerRegistry.register(ReflectionKind.union, handleUnion); this.sizerRegistry.register(ReflectionKind.promise, (type, state) => executeTemplates(state, type.type)); this.sizerRegistry.register(ReflectionKind.enum, (type, state) => executeTemplates(state, type.indexType)); } protected registerBsonSerializers() { this.bsonSerializeRegistry.register(ReflectionKind.any, serializeAny); this.bsonSerializeRegistry.register(ReflectionKind.unknown, serializeAny); this.bsonSerializeRegistry.register(ReflectionKind.never, () => undefined); this.bsonSerializeRegistry.register(ReflectionKind.class, (type, state) => serializeObjectLiteral(type, state, this.options)); this.bsonSerializeRegistry.register(ReflectionKind.objectLiteral, (type, state) => serializeObjectLiteral(type, state, this.options)); this.bsonSerializeRegistry.register(ReflectionKind.string, serializeString); this.bsonSerializeRegistry.register(ReflectionKind.templateLiteral, serializeString); this.bsonSerializeRegistry.register(ReflectionKind.boolean, serializeBoolean); this.bsonSerializeRegistry.register(ReflectionKind.promise, ((type, state) => executeTemplates(state, type.type))); this.bsonSerializeRegistry.register(ReflectionKind.number, serializeNumber); this.bsonSerializeRegistry.register(ReflectionKind.bigint, serializeBigInt); this.bsonSerializeRegistry.register(ReflectionKind.literal, serializeLiteral); this.bsonSerializeRegistry.register(ReflectionKind.regexp, serializeRegExp); this.bsonSerializeRegistry.register(ReflectionKind.array, (type, state) => serializeArray(type.type, state)); this.bsonSerializeRegistry.register(ReflectionKind.tuple, serializeTuple); this.bsonSerializeRegistry.register(ReflectionKind.promise, (type, state) => executeTemplates(state, type.type)); this.bsonSerializeRegistry.register(ReflectionKind.enum, (type, state) => executeTemplates(state, type.indexType)); this.bsonSerializeRegistry.registerClass(Map, (type, state) => serializeArray(copyAndSetParent({ kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: type.arguments![0] }, { kind: ReflectionKind.tupleMember, type: type.arguments![1] }, ] }), state)); this.bsonSerializeRegistry.registerClass(Set, (type, state) => serializeArray(type.arguments![0] as Type, state)); this.bsonSerializeRegistry.registerClass(Date, (type, state) => { serializePropertyNameAware(type, state, BSONType.DATE, `${state.accessor} instanceof Date`, `state.writer.writeLong(${state.accessor}.valueOf());`); }); this.bsonSerializeRegistry.register(ReflectionKind.undefined, (type, state) => serializePropertyNameAware(type, state, BSONType.NULL, `${state.accessor} === undefined || ${state.accessor} === null`, ``)); this.bsonSerializeRegistry.register(ReflectionKind.void, (type, state) => serializePropertyNameAware(type, state, BSONType.NULL, `${state.accessor} === undefined || ${state.accessor} === null`, ``)); this.bsonSerializeRegistry.register(ReflectionKind.null, (type, state) => serializePropertyNameAware(type, state, BSONType.NULL, `${state.accessor} === null || ${state.accessor} === undefined`, ``)); this.bsonSerializeRegistry.registerBinary(serializeBinary); this.bsonSerializeRegistry.register(ReflectionKind.union, handleUnion); } protected registerBsonTypeGuards() { const numberTypes = [BSONType.NUMBER, BSONType.INT, BSONType.LONG]; //first all exact matches this.bsonTypeGuards.register(1, ReflectionKind.any, (type, state) => state.addSetter('true')); this.bsonTypeGuards.register(1, ReflectionKind.unknown, (type, state) => state.addSetter('true')); this.bsonTypeGuards.register(1, ReflectionKind.never, (type, state) => state.addSetter('false')); this.bsonTypeGuards.register(1, ReflectionKind.objectLiteral, bsonTypeGuardObjectLiteral); this.bsonTypeGuards.register(1, ReflectionKind.class, bsonTypeGuardObjectLiteral); this.bsonTypeGuards.register(1, ReflectionKind.string, (type, state) => { if (uuidAnnotation.getFirst(type)) { bsonTypeGuardForBsonTypes([BSONType.STRING, BSONType.BINARY])(type, state); } else if (mongoIdAnnotation.getFirst(type)) { bsonTypeGuardForBsonTypes([BSONType.STRING, BSONType.OID])(type, state); } else { bsonTypeGuardForBsonTypes([BSONType.STRING])(type, state); } }); this.bsonTypeGuards.register(1, ReflectionKind.number, bsonTypeGuardForBsonTypes(numberTypes)); this.bsonTypeGuards.register(1, ReflectionKind.boolean, bsonTypeGuardForBsonTypes([BSONType.BOOLEAN])); this.bsonTypeGuards.register(1, ReflectionKind.undefined, bsonTypeGuardForBsonTypes([BSONType.UNDEFINED])); this.bsonTypeGuards.register(1, ReflectionKind.void, bsonTypeGuardForBsonTypes([BSONType.UNDEFINED])); this.bsonTypeGuards.register(1, ReflectionKind.bigint, bsonTypeGuardForBsonTypes([...numberTypes, BSONType.BINARY])); this.bsonTypeGuards.register(1, ReflectionKind.null, bsonTypeGuardForBsonTypes([BSONType.NULL])); this.bsonTypeGuards.register(1, ReflectionKind.literal, bsonTypeGuardLiteral); this.bsonTypeGuards.register(1, ReflectionKind.templateLiteral, bsonTypeGuardTemplateLiteral); this.bsonTypeGuards.register(1, ReflectionKind.regexp, bsonTypeGuardForBsonTypes([BSONType.REGEXP])); this.bsonTypeGuards.register(1, ReflectionKind.union, (type, state) => bsonTypeGuardUnion(this.bsonTypeGuards, type, state)); this.bsonTypeGuards.register(1, ReflectionKind.array, (type, state) => bsonTypeGuardArray(type.type as Type, state)); this.bsonTypeGuards.register(1, ReflectionKind.tuple, bsonTypeGuardTuple); this.bsonTypeGuards.register(1, ReflectionKind.promise, (type, state) => executeTemplates(state, type.type)); this.bsonTypeGuards.register(1, ReflectionKind.enum, (type, state) => executeTemplates(state, type.indexType)); this.bsonTypeGuards.registerClass(1, Date, bsonTypeGuardForBsonTypes([...numberTypes, BSONType.DATE, BSONType.TIMESTAMP])); this.bsonTypeGuards.registerBinary(1, bsonTypeGuardForBsonTypes([BSONType.BINARY])); this.bsonTypeGuards.registerClass(1, Map, (type, state) => bsonTypeGuardArray(copyAndSetParent({ kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, name: 'key', type: type.arguments![0] }, { kind: ReflectionKind.tupleMember, name: 'value', type: type.arguments![1] }, ] }), state)); this.bsonTypeGuards.registerClass(1, Set, (type, state) => bsonTypeGuardArray(type.arguments![0] as Type, state)); //many deserializes support other types as well as fallback, we register them under specificality > 1 this.bsonTypeGuards.register(1.5, ReflectionKind.undefined, bsonTypeGuardForBsonTypes([BSONType.NULL])); this.bsonTypeGuards.register(1.5, ReflectionKind.void, bsonTypeGuardForBsonTypes([BSONType.NULL])); this.bsonTypeGuards.register(2, ReflectionKind.string, bsonTypeGuardForBsonTypes([BSONType.TIMESTAMP, BSONType.STRING, BSONType.NULL, BSONType.UNDEFINED, BSONType.BOOLEAN])); this.bsonTypeGuards.register(2, ReflectionKind.number, bsonTypeGuardForBsonTypes([BSONType.TIMESTAMP, BSONType.STRING, BSONType.NULL, BSONType.UNDEFINED, BSONType.BOOLEAN, BSONType.BINARY])); this.bsonTypeGuards.register(2, ReflectionKind.bigint, bsonTypeGuardForBsonTypes([BSONType.TIMESTAMP, BSONType.STRING, BSONType.NULL, BSONType.UNDEFINED, BSONType.BOOLEAN])); this.bsonTypeGuards.register(2, ReflectionKind.boolean, bsonTypeGuardForBsonTypes([BSONType.TIMESTAMP, BSONType.STRING, BSONType.NULL, BSONType.UNDEFINED])); this.bsonTypeGuards.register(2, ReflectionKind.literal, bsonTypeGuardForBsonTypes([BSONType.NULL, BSONType.UNDEFINED])); this.bsonTypeGuards.registerClass(2, Date, bsonTypeGuardForBsonTypes([...numberTypes])); this.bsonTypeGuards.getRegistry(1).addDecorator(isReferenceType, (type, state) => { if (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral) return; state.setContext({ isObject, createReference, isReferenceHydrated }); const reflection = ReflectionClass.from(type); // in deserialization a reference is created when only the primary key is provided (no object given) state.template = ` if (state.elementType === ${BSONType.OBJECT}) { ${state.template} } else { ${executeTemplates(state.fork().extendPath(String(reflection.getPrimary().getName())).forPropertyName(state.propertyName), reflection.getPrimary().getType())} } `; }); } protected registerBsonDeserializers() { this.bsonDeserializeRegistry.register(ReflectionKind.any, deserializeAny); this.bsonDeserializeRegistry.register(ReflectionKind.unknown, deserializeAny); this.bsonDeserializeRegistry.register(ReflectionKind.never, () => undefined); this.bsonDeserializeRegistry.register(ReflectionKind.class, deserializeObjectLiteral); this.bsonDeserializeRegistry.register(ReflectionKind.objectLiteral, deserializeObjectLiteral); this.bsonDeserializeRegistry.register(ReflectionKind.number, deserializeNumber); this.bsonDeserializeRegistry.register(ReflectionKind.bigint, deserializeBigInt); this.bsonDeserializeRegistry.register(ReflectionKind.string, deserializeString); this.bsonDeserializeRegistry.register(ReflectionKind.templateLiteral, deserializeTemplateLiteral); this.bsonDeserializeRegistry.register(ReflectionKind.boolean, deserializeBoolean); this.bsonDeserializeRegistry.register(ReflectionKind.undefined, deserializeUndefined); this.bsonDeserializeRegistry.register(ReflectionKind.void, deserializeUndefined); this.bsonDeserializeRegistry.register(ReflectionKind.null, deserializeNull); this.bsonDeserializeRegistry.register(ReflectionKind.literal, deserializeLiteral); this.bsonDeserializeRegistry.register(ReflectionKind.regexp, deserializeRegExp); this.bsonDeserializeRegistry.register(ReflectionKind.tuple, deserializeTuple); this.bsonDeserializeRegistry.register(ReflectionKind.union, (type, state) => deserializeUnion(this.bsonTypeGuards, type, state)); this.bsonDeserializeRegistry.register(ReflectionKind.array, (type, state) => deserializeArray(type.type as Type, state)); this.bsonDeserializeRegistry.register(ReflectionKind.promise, (type, state) => executeTemplates(state, type.type)); this.bsonDeserializeRegistry.register(ReflectionKind.enum, (type, state) => executeTemplates(state, type.indexType)); this.bsonDeserializeRegistry.registerClass(Date, deserializeDate); this.bsonDeserializeRegistry.registerBinary(deserializeBinary); this.bsonDeserializeRegistry.registerClass(Map, (type, state) => { deserializeArray(copyAndSetParent({ kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: type.arguments![0] }, { kind: ReflectionKind.tupleMember, type: type.arguments![1] }, ] }), state); state.addSetter(`new Map(${state.setter})`); }); this.bsonDeserializeRegistry.registerClass(Set, (type, state) => { deserializeArray(type.arguments![0] as Type, state); state.addSetter(`new Set(${state.setter})`); }); this.bsonDeserializeRegistry.addDecorator( type => isReferenceType(type) || isBackReferenceType(type) || (type.parent !== undefined && isBackReferenceType(type.parent)), (type, state) => { if (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral) return; state.setContext({ isObject, createReference, isReferenceHydrated }); const reflection = ReflectionClass.from(type); const referenceClassTypeVar = state.setVariable('referenceClassType', type.kind === ReflectionKind.class ? type.classType : Object); // in deserialization a reference is created when only the primary key is provided (no object given) state.template = ` if (state.elementType === ${BSONType.OBJECT}) { ${state.template} } else { let pk; ${executeTemplates(state.fork('pk').extendPath(String(reflection.getPrimary().getName())).forPropertyName(state.propertyName), reflection.getPrimary().getType())} ${state.setter} = createReference(${referenceClassTypeVar}, {${JSON.stringify(reflection.getPrimary().getName())}: pk}); } `; }); } } export const bsonBinarySerializer = new BSONBinarySerializer(); function createBSONSerializer(type: Type, serializer: BSONBinarySerializer, namingStrategy: NamingStrategy = new NamingStrategy(), path: string = '', jitStack: JitStack = new JitStack()): BSONSerializer { const compiler = new CompilerContext(); compiler.context.set('typeSettings', typeSettings); compiler.context.set('Writer', Writer); compiler.context.set('seekElementSize', seekElementSize); compiler.context.set('createBuffer', createBuffer); compiler.context.set('sizer', getBSONSizer(serializer, type)); compiler.context.set('UnpopulatedCheck', UnpopulatedCheck); const state = new TemplateState('', 'data', compiler, serializer.bsonSerializeRegistry, namingStrategy, jitStack, [path]).disableSetter(); const code = ` state = state || {}; const size = sizer(data); state.writer = state.writer || new Writer(createBuffer(size)); const unpopulatedCheck = typeSettings.unpopulatedCheck; typeSettings.unpopulatedCheck = UnpopulatedCheck.ReturnSymbol; ${executeTemplates(state, type)} typeSettings.unpopulatedCheck = unpopulatedCheck; return state.writer.buffer; `; return compiler.build(code, 'data', 'state'); } export function createBSONSizer<T>(type?: ReceiveType<T>, serializer: BSONBinarySerializer = bsonBinarySerializer, jitStack: JitStack = new JitStack()): (data: object) => number { const compiler = new CompilerContext(); type = resolveReceiveType(type); compiler.context.set('typeSettings', typeSettings); compiler.context.set('unpopulatedSymbol', unpopulatedSymbol); compiler.context.set('UnpopulatedCheck', UnpopulatedCheck); compiler.context.set('seekElementSize', seekElementSize); const state = new TemplateState('', 'data', compiler, serializer.sizerRegistry, new NamingStrategy(), jitStack, []).disableSetter(); const code = ` state = state || {}; state.size = 0; const unpopulatedCheck = typeSettings.unpopulatedCheck; typeSettings.unpopulatedCheck = UnpopulatedCheck.ReturnSymbol; ${executeTemplates(state, type)} typeSettings.unpopulatedCheck = unpopulatedCheck; return state.size; `; return compiler.build(code, 'data', 'state'); } export function serializeWithoutOptimiser(data: any): Uint8Array { const size = getValueSize(data); const writer = new Writer(createBuffer(size)); writer.write(data); return writer.buffer; } export type BSONSerializer = (data: any, state?: { writer?: Writer }) => Uint8Array; export type BSONSizer = (data: any) => number; export function getBSONSerializer<T>(serializer: BSONBinarySerializer = bsonBinarySerializer, receiveType?: ReceiveType<T>): BSONSerializer { const type = resolveReceiveType(receiveType); const jit = getTypeJitContainer(type); if (jit[serializer.serializeId]) return jit[serializer.serializeId]; jit[serializer.serializeId] = createBSONSerializer(type, serializer); toFastProperties(jit); return jit[serializer.serializeId]; } export function getBSONSizer<T>(serializer: BSONBinarySerializer = bsonBinarySerializer, receiveType?: ReceiveType<T>): BSONSizer { const type = resolveReceiveType(receiveType); const jit = getTypeJitContainer(type); if (jit[serializer.sizerId]) return jit[serializer.sizerId]; jit[serializer.sizerId] = createBSONSizer(type, serializer); toFastProperties(jit); return jit[serializer.sizerId]; } export function serializeBSON<T>(data: T, serializer: BSONBinarySerializer = bsonBinarySerializer, receiveType?: ReceiveType<T>): Uint8Array { return getBSONSerializer(serializer, receiveType)(data); }
the_stack
// Copyright (c) 2019 Erin Catto // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import * as b2 from "@box2d"; export class Camera { public readonly m_center: b2.Vec2 = new b2.Vec2(0, 20); ///public readonly m_roll: b2.Rot = new b2.Rot(b2.DegToRad(0)); public m_extent: number = 25; public m_zoom: number = 1; public m_width: number = 1280; public m_height: number = 800; public ConvertScreenToWorld(screenPoint: b2.Vec2, out: b2.Vec2): b2.Vec2 { return this.ConvertElementToWorld(screenPoint, out); } public ConvertWorldToScreen(worldPoint: b2.Vec2, out: b2.Vec2): b2.Vec2 { return this.ConvertWorldToElement(worldPoint, out); } public ConvertViewportToElement(viewport: b2.Vec2, out: b2.Vec2): b2.Vec2 { // 0,0 at center of canvas, x right and y up const element_x: number = viewport.x + (0.5 * this.m_width); const element_y: number = (0.5 * this.m_height) - viewport.y; return out.Set(element_x, element_y); } public ConvertElementToViewport(element: b2.Vec2, out: b2.Vec2): b2.Vec2 { // 0,0 at center of canvas, x right and y up const viewport_x: number = element.x - (0.5 * this.m_width); const viewport_y: number = (0.5 * this.m_height) - element.y; return out.Set(viewport_x, viewport_y); } public ConvertProjectionToViewport(projection: b2.Vec2, out: b2.Vec2): b2.Vec2 { const viewport: b2.Vec2 = out.Copy(projection); b2.Vec2.MulSV(1 / this.m_zoom, viewport, viewport); ///b2.Vec2.MulSV(this.m_extent, viewport, viewport); b2.Vec2.MulSV(0.5 * this.m_height / this.m_extent, projection, projection); return viewport; } public ConvertViewportToProjection(viewport: b2.Vec2, out: b2.Vec2): b2.Vec2 { const projection: b2.Vec2 = out.Copy(viewport); ///b2.Vec2.MulSV(1 / this.m_extent, projection, projection); b2.Vec2.MulSV(2 * this.m_extent / this.m_height, projection, projection); b2.Vec2.MulSV(this.m_zoom, projection, projection); return projection; } public ConvertWorldToProjection(world: b2.Vec2, out: b2.Vec2): b2.Vec2 { const projection: b2.Vec2 = out.Copy(world); b2.Vec2.SubVV(projection, this.m_center, projection); ///b2.Rot.MulTRV(this.m_roll, projection, projection); return projection; } public ConvertProjectionToWorld(projection: b2.Vec2, out: b2.Vec2): b2.Vec2 { const world: b2.Vec2 = out.Copy(projection); ///b2.Rot.MulRV(this.m_roll, world, world); b2.Vec2.AddVV(this.m_center, world, world); return world; } public ConvertElementToWorld(element: b2.Vec2, out: b2.Vec2): b2.Vec2 { const viewport: b2.Vec2 = this.ConvertElementToViewport(element, out); const projection: b2.Vec2 = this.ConvertViewportToProjection(viewport, out); return this.ConvertProjectionToWorld(projection, out); } public ConvertWorldToElement(world: b2.Vec2, out: b2.Vec2): b2.Vec2 { const projection: b2.Vec2 = this.ConvertWorldToProjection(world, out); const viewport: b2.Vec2 = this.ConvertProjectionToViewport(projection, out); return this.ConvertViewportToElement(viewport, out); } public ConvertElementToProjection(element: b2.Vec2, out: b2.Vec2): b2.Vec2 { const viewport: b2.Vec2 = this.ConvertElementToViewport(element, out); return this.ConvertViewportToProjection(viewport, out); } } // This class implements debug drawing callbacks that are invoked // inside b2World::Step. export class DebugDraw extends b2.Draw { public m_ctx: CanvasRenderingContext2D | null = null; constructor() { super(); } public PushTransform(xf: b2.Transform): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.save(); ctx.translate(xf.p.x, xf.p.y); ctx.rotate(xf.q.GetAngle()); } } public PopTransform(xf: b2.Transform): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.restore(); } } public DrawPolygon(vertices: b2.Vec2[], vertexCount: number, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.beginPath(); ctx.moveTo(vertices[0].x, vertices[0].y); for (let i: number = 1; i < vertexCount; i++) { ctx.lineTo(vertices[i].x, vertices[i].y); } ctx.closePath(); ctx.strokeStyle = color.MakeStyleString(1); ctx.stroke(); } } public DrawSolidPolygon(vertices: b2.Vec2[], vertexCount: number, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.beginPath(); ctx.moveTo(vertices[0].x, vertices[0].y); for (let i: number = 1; i < vertexCount; i++) { ctx.lineTo(vertices[i].x, vertices[i].y); } ctx.closePath(); ctx.fillStyle = color.MakeStyleString(0.5); ctx.fill(); ctx.strokeStyle = color.MakeStyleString(1); ctx.stroke(); } } public DrawCircle(center: b2.Vec2, radius: number, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, b2.pi * 2, true); ctx.strokeStyle = color.MakeStyleString(1); ctx.stroke(); } } public DrawSolidCircle(center: b2.Vec2, radius: number, axis: b2.Vec2, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { const cx: number = center.x; const cy: number = center.y; ctx.beginPath(); ctx.arc(cx, cy, radius, 0, b2.pi * 2, true); ctx.moveTo(cx, cy); ctx.lineTo((cx + axis.x * radius), (cy + axis.y * radius)); ctx.fillStyle = color.MakeStyleString(0.5); ctx.fill(); ctx.strokeStyle = color.MakeStyleString(1); ctx.stroke(); } } // #if B2_ENABLE_PARTICLE public DrawParticles(centers: b2.Vec2[], radius: number, colors: b2.Color[] | null, count: number) { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { if (colors !== null) { for (let i = 0; i < count; ++i) { const center = centers[i]; const color = colors[i]; ctx.fillStyle = color.MakeStyleString(); // ctx.fillRect(center.x - radius, center.y - radius, 2 * radius, 2 * radius); ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, b2.pi * 2, true); ctx.fill(); } } else { ctx.fillStyle = "rgba(255,255,255,0.5)"; // ctx.beginPath(); for (let i = 0; i < count; ++i) { const center = centers[i]; // ctx.rect(center.x - radius, center.y - radius, 2 * radius, 2 * radius); ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, b2.pi * 2, true); ctx.fill(); } // ctx.fill(); } } } // #endif public DrawSegment(p1: b2.Vec2, p2: b2.Vec2, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.strokeStyle = color.MakeStyleString(1); ctx.stroke(); } } public DrawTransform(xf: b2.Transform): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { this.PushTransform(xf); ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(1, 0); ctx.strokeStyle = b2.Color.RED.MakeStyleString(1); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(0, 1); ctx.strokeStyle = b2.Color.GREEN.MakeStyleString(1); ctx.stroke(); this.PopTransform(xf); } } public DrawPoint(p: b2.Vec2, size: number, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.fillStyle = color.MakeStyleString(); size *= g_camera.m_zoom; size /= g_camera.m_extent; const hsize: number = size / 2; ctx.fillRect(p.x - hsize, p.y - hsize, size, size); } } private static DrawString_s_color: b2.Color = new b2.Color(0.9, 0.6, 0.6); public DrawString(x: number, y: number, message: string): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.font = "15px DroidSans"; const color: b2.Color = DebugDraw.DrawString_s_color; ctx.fillStyle = color.MakeStyleString(); ctx.fillText(message, x, y); ctx.restore(); } } private static DrawStringWorld_s_p: b2.Vec2 = new b2.Vec2(); private static DrawStringWorld_s_cc: b2.Vec2 = new b2.Vec2(); private static DrawStringWorld_s_color: b2.Color = new b2.Color(0.5, 0.9, 0.5); public DrawStringWorld(x: number, y: number, message: string): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { const p: b2.Vec2 = DebugDraw.DrawStringWorld_s_p.Set(x, y); // world -> viewport const vt: b2.Vec2 = g_camera.m_center; b2.Vec2.SubVV(p, vt, p); ///const vr = g_camera.m_roll; ///b2.Rot.MulTRV(vr, p, p); const vs: number = g_camera.m_zoom; b2.Vec2.MulSV(1 / vs, p, p); // viewport -> canvas const cs: number = 0.5 * g_camera.m_height / g_camera.m_extent; b2.Vec2.MulSV(cs, p, p); p.y *= -1; const cc: b2.Vec2 = DebugDraw.DrawStringWorld_s_cc.Set(0.5 * ctx.canvas.width, 0.5 * ctx.canvas.height); b2.Vec2.AddVV(p, cc, p); ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.font = "15px DroidSans"; const color: b2.Color = DebugDraw.DrawStringWorld_s_color; ctx.fillStyle = color.MakeStyleString(); ctx.fillText(message, p.x, p.y); ctx.restore(); } } public DrawAABB(aabb: b2.AABB, color: b2.Color): void { const ctx: CanvasRenderingContext2D | null = this.m_ctx; if (ctx) { ctx.strokeStyle = color.MakeStyleString(); const x: number = aabb.lowerBound.x; const y: number = aabb.lowerBound.y; const w: number = aabb.upperBound.x - aabb.lowerBound.x; const h: number = aabb.upperBound.y - aabb.lowerBound.y; ctx.strokeRect(x, y, w, h); } } } export const g_debugDraw: DebugDraw = new DebugDraw(); export const g_camera: Camera = new Camera();
the_stack
import { Component, ElementRef, KeyValueDiffers, IterableDiffers, ChangeDetectionStrategy, ChangeDetectorRef, Renderer2 } from '@angular/core'; import { IgGridBase } from './iggridbase'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: 'ig-grid', template: '<ng-content></ng-content>', inputs: ['widgetId', 'options', 'changeDetectionInterval', 'disabled', 'create', 'width', 'height', 'autoAdjustHeight', 'avgRowHeight', 'avgColumnWidth', 'defaultColumnWidth', 'autoGenerateColumns', 'virtualization', 'virtualizationMode', 'requiresDataBinding', 'rowVirtualization', 'columnVirtualization', 'virtualizationMouseWheelStep', 'adjustVirtualHeights', 'templatingEngine', 'columns', 'dataSource', 'dataSourceUrl', 'dataSourceType', 'responseDataKey', 'responseTotalRecCountKey', 'requestType', 'responseContentType', 'showHeader', 'showFooter', 'fixedHeaders', 'fixedFooters', 'caption', 'features', 'tabIndex', 'localSchemaTransform', 'primaryKey', 'serializeTransactionLog', 'autoCommit', 'aggregateTransactions', 'autoFormat', 'renderCheckboxes', 'updateUrl', 'restSettings', 'alternateRowStyles', 'autofitLastColumn', 'enableHoverStyles', 'enableUTCDates', 'mergeUnboundColumns', 'jsonpRequest', 'enableResizeContainerCheck', 'featureChooserIconDisplay', 'scrollSettings'], outputs: ['cellClick', 'cellRightClick', 'dataBinding', 'dataBound', 'rendering', 'rendered', 'dataRendering', 'dataRendered', 'headerRendering', 'headerRendered', 'footerRendering', 'footerRendered', 'headerCellRendered', 'rowsRendering', 'rowsRendered', 'schemaGenerated', 'columnsCollectionModified', 'requestError', 'created', 'destroyed'] }) export class IgGridComponent extends IgGridBase<IgGrid> { constructor(el: ElementRef, renderer: Renderer2, differs: IterableDiffers, kvalDiff: KeyValueDiffers, cdr: ChangeDetectorRef) { super(el, renderer, differs, kvalDiff, cdr); } /** * Returns the element holding the data records */ /* istanbul ignore next */ public widget(): void { return; } /** * Returns whether grid has non-data fixed columns(e.g. row selectors column) */ /* istanbul ignore next */ public hasFixedDataSkippedColumns(): boolean { return; } /** * Returns true if grid has at least one fixed columns(even if a non-data column - like row-selectors column) */ /* istanbul ignore next */ public hasFixedColumns(): boolean { return; } /** * Returns the current fixing direction. NOTE - use only if ColumnFixing feature is enabled * @return left|right */ /* istanbul ignore next */ public fixingDirection(): string { return; } /** * Returns whether the column with identifier colKey is fixed * * @param colKey An identifier of the column which should be checked. It can be a key or visible index. */ /* istanbul ignore next */ public isFixedColumn(colKey: object): boolean { return; } /** * Called to detect whether grid container is resized. * When autoAdjustHeight is true and height of the grid is changed then the height of grid is re-set. */ /* istanbul ignore next */ public resizeContainer(): void { return; } /** * Returns whether the header identified by colKey is multicolumn header(has children) * * @param colKey value of the column key */ /* istanbul ignore next */ public isGroupHeader(colKey: string): object { return; } /** * Returns an object that contains information on the passed Dom element * * rowId - the id of the record associated with the element - if primaryKey is not set this will be null. * rowIndex - the index (in the DOM) of the row associated with the element. * recordIndex - index of the data record associated with this element in the current dataView. * columnObject - the column object associated with this element ( if the element is tr this will be null) * * @param elem The Dom element or jQuery object which can be a TD or TR element from the grid. */ /* istanbul ignore next */ public getElementInfo(elem: Element): object { return; } /** * Returns the ID of the TABLE element where data records are rendered */ /* istanbul ignore next */ public id(): string { return; } /** * Returns the DIV that is the topmost container of the grid widget */ /* istanbul ignore next */ public container(): Element { return; } /** * Returns the table that contains the header cells */ /* istanbul ignore next */ public headersTable(): Element { return; } /** * Returns the table that contains the footer cells */ /* istanbul ignore next */ public footersTable(): Element { return; } /** * Returns the DIV that is used as a scroll container for the grid contents */ /* istanbul ignore next */ public scrollContainer(): Element { return; } /** * Returns the DIV that is the topmost container of the fixed grid - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedContainer(): Element { return; } /** * Returns the DIV that is the topmost container of the fixed body grid - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedBodyContainer(): Element { return; } /** * Returns container(jQuery representation) containing fixed footer - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedFooterContainer(): object { return; } /** * Returns container(jQuery representation) containing fixed header - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedHeaderContainer(): object { return; } /** * Returns the table that contains the FIXED header cells - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedHeadersTable(): Element { return; } /** * Returns the table that contains the footer cells - contains fixed columns(in ColumnFixing scenario) */ /* istanbul ignore next */ public fixedFootersTable(): Element { return; } /** * Returns the cell TD element at the specified location * * @param x The column index. * @param y The row index. * @param isFixed Optional parameter - if true get cell TD at the specified location from the fixed table */ /* istanbul ignore next */ public cellAt(x: number, y: number, isFixed: boolean): Element { return; } /** * Returns the cell TD element by row id and column key * * @param rowId The id of the row. * @param columnKey The column key. */ /* istanbul ignore next */ public cellById(rowId: object, columnKey: string): Element { return; } /** * Returns the fixed table - contains fixed columns(in ColumnFixing scenario). If there aren't fixed columns returns the grid table */ /* istanbul ignore next */ public fixedTable(): object { return; } /** * Gets all immediate children of the current grid */ /* istanbul ignore next */ public immediateChildrenWidgets(): any[] { return; } /** * Gets all children of the current grid, recursively */ /* istanbul ignore next */ public childrenWidgets(): any[] { return; } /** * Gets all children's elements of the current grid, recursively */ /* istanbul ignore next */ public children(): any[] { return; } /** * Gets all immediate children's elements of the current grid */ /* istanbul ignore next */ public immediateChildren(): any[] { return; } /** * Returns the row (TR element) at the specified index. jQuery selectors aren't used for performance reasons * * @param i The row index. */ /* istanbul ignore next */ public rowAt(i: number): Element { return; } /** * Returns the row TR element by row id * * @param rowId The id of the row. * @param isFixed Specify search in the fixed container. */ /* istanbul ignore next */ public rowById(rowId: object, isFixed?: boolean): Element { return; } /** * Returns the fixed row (TR element) at the specified index. * jQuery selectors aren't used for performance reasons(in ColumnFixing scenario - only when there is at least one fixed column) * * @param i The row index. */ /* istanbul ignore next */ public fixedRowAt(i: number): Element { return; } /** * Returns a list of all fixed TR elements holding data in the grid, * in ColumnFixing scenario - only when there is at least one fixed column */ /* istanbul ignore next */ public fixedRows(): any[] { return; } /** * Returns a list of all TR elements holding data in the grid, * when there is at least one fixed column returns rows only in the UNFIXED table */ /* istanbul ignore next */ public rows(): any[] { return; } /** * Returns all data fixed rows recursively, not only the immediate ones, * in ColumnFixing scenario - only when there is at least one fixed column */ /* istanbul ignore next */ public allFixedRows(): any[] { return; } /** * Returns all data rows recursively, not only the immediate ones, * when there is at least one fixed column returns rows only in the UNFIXED table */ /* istanbul ignore next */ public allRows(): any[] { return; } /** * Returns a column object by the specified column key * * @param key The column key. */ /* istanbul ignore next */ public columnByKey(key: string): object { return; } /** * Returns a column object by the specified header text. If there are multiple matches, returns the first one. * * @param text The column header text. */ /* istanbul ignore next */ public columnByText(text: string): object { return; } /** * Returns an array of selected cells in arbitrary order where every objects has the format * { element: , row: , index: , rowIndex: , columnKey: } . * If multiple selection is disabled the function will return null. */ /* istanbul ignore next */ public selectedCells(): any[] { return; } /** * Returns an array of selected rows in arbitrary order where every object has the format { element: , index: }. * If multiple selection is disabled the function will return null. */ /* istanbul ignore next */ public selectedRows(): any[] { return; } /** * Returns the currently selected cell that has the format { element: , row: , index: , rowIndex: , columnKey: }, if any. * If multiple selection is enabled the function will return null. */ /* istanbul ignore next */ public selectedCell(): object { return; } /** * Returns the currently selected row that has the format { element: , index: }, if any. * If multiple selection is enabled the function will return null. */ /* istanbul ignore next */ public selectedRow(): object { return; } /** * Returns the currently active (focused) cell that has the format { element: , row: , index: , rowIndex: , columnKey: }, if any. */ /* istanbul ignore next */ public activeCell(): object { return; } /** * Returns the currently active (focused) row that has the format { element: , index: }, if any. */ /* istanbul ignore next */ public activeRow(): object { return; } /** * Retrieves a cell value using the row index and the column key. * If a primaryKey is defined, rowId is assumed to be the row Key (not index). * If primary key is not defined, then rowId is converted to a number and is used as a row index. * * @param rowId Row index or row key (primary key). * @param colKey The column key. */ /* istanbul ignore next */ public getCellValue(rowId: any, colKey: string): any { return; } /** * Returns the cell text. If colKey is a number, the index of the column is used (instead of a column name) * - does not apply when using a Multi-Row Layout grid. * This is the actual text (or HTML string) for the contents of the cell. * * @param rowId Row index or row data key (primary key) * @param colKey Column key. */ /* istanbul ignore next */ public getCellText(rowId: object, colKey: string): string { return; } /** * Sets a new template for a column after initialization and renders the grid if not explicitly disabled. * This method will replace any existing explicitly set row template and will build one anew from the column ones. * * @param col An identifier of the column to set template for (index or key) * @param tmpl The column template to set * @param render Should the grid rerender after template is set */ /* istanbul ignore next */ public setColumnTemplate(col: object, tmpl: string, render?: boolean): void { return; } /** * Commits all pending transactions to the client data source. * Note that there won't be anything to commit on the UI, since it is updated instantly. * In order to rollback the actual UI, a call to dataBind() is required. * * @param rowId If specified, will commit only that transaction corresponding to the specified record key. */ /* istanbul ignore next */ public commit(rowId?: object): void { return; } /** * Clears the transaction log (delegates to igDataSource). Note that this does not update the UI. * In case the UI must be updated, set the second parameter "updateUI" to true, * which will trigger a call to dataBind() to re-render the contents. * * @param rowId If specified, will only rollback the transactions with that row id. * @param updateUI Whether to update the UI or not. */ /* istanbul ignore next */ public rollback(rowId?: object, updateUI?: boolean): any[] { return; } /** * Returns a record by a specified key (requires that primaryKey is set in the settings). * That is a wrapper for this.dataSource.findRecordByKey(key). * * @param key Primary key of the record */ /* istanbul ignore next */ public findRecordByKey(key: object): object { return; } /** * Returns a standalone object (copy) that represents the committed transactions, but detached from the data source. * That is a wrapper for this.dataSource.getDetachedRecord(t). * * @param t A transaction object. */ /* istanbul ignore next */ public getDetachedRecord(t: object): object { return; } /** * Returns a list of all transaction objects that are pending to be committed or rolled back to the data source. * That is a wrapper for this.dataSource.pendingTransactions(). */ /* istanbul ignore next */ public pendingTransactions(): any[] { return; } /** * Returns a list of all transaction objects that are either pending, or have been committed in the data source. * That is a wrapper for this.dataSource.allTransactions(). */ /* istanbul ignore next */ public allTransactions(): any[] { return; } /** * Returns the accumulated transaction log as a string. The purpose of this is to be passed to URLs or used conveniently. * That is a wrapper for this.dataSource.transactionsAsString(). */ /* istanbul ignore next */ public transactionsAsString(): string { return; } /** * Invokes an AJAX request to the updateUrl option (if specified) and passes the serialized transaction log * (a serialized JSON string) as part of the POST request. * * @param success Specifies a custom function to be called when AJAX request to the updateUrl option succeeds(optional) * @param error Specifies a custom function to be called when AJAX request to the updateUrl option fails(optional) */ /* istanbul ignore next */ public saveChanges(success: () => void, error: () => void): void { return; } /** * Adds a new row (TR) to the grid, by taking a data row object. Assumes the record will have the primary key. * * @param rec Identifier/key of row. If missing, then number of rows in grid is used. */ /* istanbul ignore next */ public renderNewRow(rec?: string): void { return; } /** * If the data source points to a local JSON array of data, and it is necessary to reset it at runtime, * it must be done through this API member instead of the options (options.dataSource) * * @param dataSource New data source object. */ /* istanbul ignore next */ public dataSourceObject(dataSource: object): void { return; } /** * Returns the total number of records in the underlying backend. * If paging or filtering is enabled, this may differ from the number of records in the client-side data source. * In order for this to work, the response JSON/XML must include a property that specifies the total number of records, * which name is specified by options.responseTotalRecCountKey. * This functionality is completely delegated to the data source control. */ /* istanbul ignore next */ public totalRecordsCount(): number { return; } /** * Causes the grid to data bind to the data source (local or remote) , and re-render all of the data as well * * @param internal internal call flag */ /* istanbul ignore next */ dataBind(internal: object): void { return; } /** * Moves a visible column at a specified place, in front or behind a target column or at a target index * Note: This method is asynchronous which means that it returns immediately and any subsequent code will execute in parallel. * This may lead to runtime errors. To avoid them put the subsequent code in the callback parameter provided by the method. * * @param column An identifier of the column to be moved. * It can be a key, a Multi-Column Header identificator, or an index in a number format. * The latter is not supported when the grid contains multi-column headers. * @param target An identifier of a column where the moved column should move to or an index at which the moved * column should be moved to. In the case of a column identifier the column will be moved after it by default. * @param after Specifies whether the column moved should be moved after or before the target column. * This parameter is disregarded if there is no target column specified but a target index is used. * @param inDom Specifies whether the column moving will be enacted through DOM manipulation or through rerendering of the grid. * @param callback Specifies a custom function to be called when the column is moved. */ /* istanbul ignore next */ public moveColumn(column: object, target: object, after?: boolean, inDom?: boolean, callback?: () => void): void { return; } /** * Shows a hidden column. If the column is not hidden the method does nothing. * Note: This method is asynchronous which means that it returns immediately and any subsequent code will execute in parallel. * This may lead to runtime errors. To avoid them put the subsequent code in the callback parameter provided by the method. * * @param column An identifier for the column. If a number is provided it will be used as a column index. * If a string is provided it will be used as a column key. * @param callback Specifies a custom function to be called when the column is shown(optional) */ /* istanbul ignore next */ public showColumn(column: object, callback: () => void): void { return; } /** * Hides a visible column. If the column is hidden the method does nothing. * Note: This method is asynchronous which means that it returns immediately and any subsequent code will execute in parallel. * This may lead to runtime errors. To avoid them put the subsequent code in the callback parameter provided by the method. * * @param column An identifier for the column. * If a number is provided it will be used as a column index else if a string is provided it will be used as a column key. * @param callback Specifies a custom function to be called when the column is hidden(optional) */ /* istanbul ignore next */ public hideColumn(column: object, callback: () => void): void { return; } /** * Gets unbound values for the specified column key. If key is not specified returns all unboundvalues * * @param key column key */ /* istanbul ignore next */ public getUnboundValues(key: string): object { return; } /** * Sets unbound values for the unbound column with the specified key. * If removeOldValues is true then values(if any) for the unbound columns are re-set with the new values * * @param key key of the unbound column * @param values array of values to be set on unbound values * @param removeOldValues if true removes current unbound values(if any) for the specified column and apply the new ones specified * in parameter values. Otherwise merge current values with the specified in parameter values */ /* istanbul ignore next */ public setUnboundValues(key: string, values: any[], removeOldValues: object): void { return; } /** * Sets unbound value for the unbound cell by the specified column key and row primary key. * * @param col key of the unbound column * @param rowId primary key value of the row * @param val value to be set on unbound cell * @param notToRender if false will re-render the row */ /* istanbul ignore next */ public setUnboundValueByPK(col: string, rowId: string, val: object, notToRender: object): void { return; } /** * Returns an unbound column with the specified key. If not found returns null * * @param key a column key */ /* istanbul ignore next */ public getUnboundColumnByKey(key: string): object { return; } /** * Returns whether there is vertical scrollbar. Because of perfrormance issues in older Internet Explorer especially 8,9 - * there is no need to check if height is not set - there is no scrollbar OR if row virtualization is enabled - * it is supposed there is vertical scrollbar */ /* istanbul ignore next */ public hasVerticalScrollbar(): object { return; } /** * Auto resize columns that have property width set to "*" so content to be auto-fitted(not shrinked/cutted). * Auto-resizing is applied ONLY for visible columns */ /* istanbul ignore next */ public autoSizeColumns(): void { return; } /** * Calculates the width of the column so its content to be auto-fitted to the width of the data in it * (the content should NOT be shrinked/cutted) * * @param columnIndex Visible column index */ /* istanbul ignore next */ public calculateAutoFitColumnWidth(columnIndex: number): number { return; } /** * Get visible index by specified column key. If column is not found or is hidden then returns -1. * Note: Method does not count column groups (Multi-Column Headers). * * @param columnKey columnKey * @param includeDataSkip Optional parameter - if set to true include non data columns * (like expander column, row selectors column, etc.) in calculations */ /* istanbul ignore next */ public getVisibleIndexByKey(columnKey: string, includeDataSkip: boolean): number { return; } /** * When called the method re-renders the whole grid(also rebinds to the data source) and renders the cols object * * @param cols an array of column objects */ /* istanbul ignore next */ public renderMultiColumnHeader(cols: any[]): void { return; } /** * Scroll to the specified row or specified position(in pixels) * * @param scrollerPosition An identifier of the vertical scroll position. * When it is string then it is interpreted as pixels otherwise it is the row number */ /* istanbul ignore next */ public virtualScrollTo(scrollerPosition: object): void { return; } /** * Returns column object and visible index for the table cell(TD) which is passed as argument * * @param $td cell(TD) - either DOM TD element or jQuery object */ /* istanbul ignore next */ public getColumnByTD($td: object): object { return; } /** * Destroy is part of the jQuery UI widget API and does the following: * 1. Remove custom CSS classes that were added. * 2. Unwrap any wrapping elements such as scrolling divs and other containers. * 3. Unbind all events that were bound. * * @param notToCallDestroy flag whether to propagate the destroy call */ /* istanbul ignore next */ public destroy(notToCallDestroy: object): void { return; } }
the_stack
import path from 'path'; import gulp, { TaskFunction } from 'gulp'; import gulpHbsRuntime from '../plugins/gulp-hbs-runtime'; import { Logger } from '../common/logger'; import { PackerOptions } from '../model/packer-options'; import { TestEnvironment } from '../model/test-environment'; /** * Parse script transpiler by preprocessor type and extract extension glob depending on enzyme support. * @param packerOptions Packer options object. * @param scriptExt Script file extension. */ export const parseSpecScriptExtension = (packerOptions: PackerOptions, scriptExt: string): string => { if (packerOptions.useEnzyme) { return `{${scriptExt},${scriptExt}x}`; } else { return scriptExt; } }; /** * Copy jasmine configuration file. * @param packerOptions Packer options object. * @param testEnvironment Test environment type. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJasmineConfig = ( packerOptions: PackerOptions, testEnvironment: TestEnvironment, projectDir: string, log: Logger ): TaskFunction => { const jasmine = path.join(__dirname, '../resources/dynamic/jasmine.json.hbs'); log.trace('jasmine.json path: %s', jasmine); return () => { return gulp .src([jasmine]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe( gulpHbsRuntime( { isTypescript: packerOptions.scriptPreprocessor === 'typescript', useEnzyme: packerOptions.useEnzyme, useJsDom: testEnvironment === 'jsdom' }, { replaceExt: '' } ) ) .pipe(gulp.dest(projectDir)); }; }; /** * Copy jasmine helper script files. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJasmineHelpers = (projectDir: string, log: Logger): TaskFunction => { const helpersGlob = path.join(__dirname, '../resources/dynamic/example/test/jasmine/helpers/**/*'); log.trace('jasmine helpers path glob: %s', helpersGlob); return () => { return gulp .src([helpersGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'helpers'))); }; }; /** * Copy jasmine test spec files. * @param scriptGlob Script extension glob. * @param scriptExt Script file extension. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJasmineSpec = ( scriptGlob: string, scriptExt: string, projectDir: string, log: Logger ): TaskFunction => { const specGlob = path.join( __dirname, '../resources/dynamic/example/test/jasmine', scriptExt, `spec/**/*.${scriptGlob}` ); log.trace('jasmine spec path glob: %s', specGlob); return () => { return gulp .src([specGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'spec'))); }; }; /** * Copy karma jasmine test spec files. * @param scriptGlob Script extension glob. * @param scriptExt Script file extension. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyKarmaJasmineSpec = ( scriptGlob: string, scriptExt: string, projectDir: string, log: Logger ): TaskFunction => { const specGlob = path.join( __dirname, '../resources/dynamic/example/test/karma/jasmine', scriptExt, `spec/**/*.${scriptGlob}` ); log.trace('jasmine spec path glob: %s', specGlob); return () => { return gulp .src([specGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'spec'))); }; }; /** * Copy jasmine configuration file. * @param packerOptions Packer options object. * @param testEnvironment Test environment type. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyMochaConfig = ( packerOptions: PackerOptions, testEnvironment: TestEnvironment, projectDir: string, log: Logger ): TaskFunction => { const mocha = path.join(__dirname, '../resources/dynamic/mocha.opts.hbs'); log.trace('mocha.opts path: %s', mocha); return () => { return gulp .src([mocha]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe( gulpHbsRuntime( { isTypescript: packerOptions.scriptPreprocessor === 'typescript', useEnzyme: packerOptions.useEnzyme, useJsDom: testEnvironment === 'jsdom' }, { replaceExt: '' } ) ) .pipe(gulp.dest(projectDir)); }; }; /** * Copy mocha helper script files. Used as mocha require scripts. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyMochaHelpers = (projectDir: string, log: Logger): TaskFunction => { const helpersGlob = path.join(__dirname, '../resources/dynamic/example/test/mocha/helpers/**/*'); log.trace('mocha helpers path glob: %s', helpersGlob); return () => { return gulp .src([helpersGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'helpers'))); }; }; /** * Copy mocha test spec files. * @param scriptGlob Script extension glob. * @param scriptExt Script file extension. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyMochaTestSpec = ( scriptGlob: string, scriptExt: string, projectDir: string, log: Logger ): TaskFunction => { const testGlob = path.join( __dirname, '../resources/dynamic/example/test/mocha', scriptExt, `test/**/*.${scriptGlob}` ); log.trace('mocha test spec path glob: %s', testGlob); return () => { return gulp .src([testGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'test'))); }; }; /** * Copy karma mocha test spec files. * @param scriptExt Script file extension. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyKarmaMochaTestSpec = (scriptExt: string, projectDir: string, log: Logger): TaskFunction => { const testGlob = path.join(__dirname, '../resources/dynamic/example/test/karma/mocha', scriptExt, 'spec/**/*'); log.trace('mocha test spec path glob: %s', testGlob); return () => { return gulp .src([testGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, 'test'))); }; }; /** * Copy jest configuration file. * @param packerOptions Packer options object. * @param testEnvironment Test environment type. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJestConfig = ( packerOptions: PackerOptions, testEnvironment: TestEnvironment, projectDir: string, log: Logger ): TaskFunction => { const jest = path.join(__dirname, '../resources/dynamic/jest.config.js.hbs'); log.trace('jest.config.js path: %s', jest); return () => { return gulp .src([jest]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe( gulpHbsRuntime( { isTypescript: packerOptions.scriptPreprocessor === 'typescript', testEnvironment, useEnzyme: packerOptions.useEnzyme }, { replaceExt: '' } ) ) .pipe(gulp.dest(projectDir)); }; }; /** * Copy jest mock scripts. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJestMockScripts = (projectDir: string, log: Logger): TaskFunction => { const mockScriptGlob = path.join(__dirname, '../resources/dynamic/example/test/jest/__mocks__/**/*'); log.trace('mock script glob bath: %s', mockScriptGlob); return () => { return gulp .src([mockScriptGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, '__mocks__'))); }; }; /** * Copy jest test files. * @param scriptGlob Script extension glob. * @param scriptExt Script file extension. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyJestTests = (scriptGlob: string, scriptExt: string, projectDir: string, log: Logger): TaskFunction => { const testsGlob = path.join( __dirname, '../resources/dynamic/example/test/jest', scriptExt, `__tests__/**/*.${scriptGlob}` ); log.trace('jest tests path glob: %s', testsGlob); return () => { return gulp .src([testsGlob]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(path.join(projectDir, '__tests__'))); }; }; /** * Copy test typescript configuration (tsconfig.test.json) file. * @param packerOptions Packer options object reference. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyTestTypescriptConfig = ( packerOptions: PackerOptions, projectDir: string, log: Logger ): TaskFunction => { const tsconfig = path.join(__dirname, '../resources/dynamic/tsconfig.test.json.hbs'); log.trace('tsconfig.test.json.hbs path: %s', tsconfig); return () => { return gulp .src([tsconfig]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe( gulpHbsRuntime( { isJest: packerOptions.testFramework === 'jest' }, { replaceExt: '' } ) ) .pipe(gulp.dest(projectDir)); }; }; /** * Copy karma configuration (karma.conf.js) file. * @param projectDir Project root directory. * @param log Logger reference. */ export const copyKarmaConfig = (projectDir: string, log: Logger): TaskFunction => { const karma = path.join(__dirname, '../resources/static/karma.conf.js'); log.trace('karma.conf.js path: %s', karma); return () => { return gulp .src([karma]) .on('error', (e) => { log.error('missing config file: %s\n', e.stack || e.message); process.exit(1); }) .pipe(gulp.dest(projectDir)); }; }; /** * Get test specification generator gulp task functions. * @param packerOptions Packer options object. * @param scriptExt Script file extension. * @param testEnvironment Test environment type. * @param projectDir Project root directory. * @param log Logger reference. */ export const getTestSpecGeneratorTasks = ( packerOptions: PackerOptions, scriptExt: string, testEnvironment: TestEnvironment, projectDir: string, log: Logger ): TaskFunction[] => { const tasks: TaskFunction[] = []; const scriptGlob = parseSpecScriptExtension(packerOptions, scriptExt); if (packerOptions.testFramework === 'jest') { tasks.push(copyJestConfig(packerOptions, testEnvironment, projectDir, log)); tasks.push(copyJestMockScripts(projectDir, log)); tasks.push(copyJestTests(scriptGlob, scriptExt, projectDir, log)); if (packerOptions.scriptPreprocessor === 'typescript') { tasks.push(copyTestTypescriptConfig(packerOptions, projectDir, log)); } } else { if (testEnvironment === 'browser') { tasks.push(copyKarmaConfig(projectDir, log)); if (packerOptions.testFramework === 'jasmine') { tasks.push(copyKarmaJasmineSpec(scriptGlob, scriptExt, projectDir, log)); } if (packerOptions.testFramework === 'mocha') { tasks.push(copyKarmaMochaTestSpec(scriptExt, projectDir, log)); } } else { if (packerOptions.scriptPreprocessor === 'typescript') { tasks.push(copyTestTypescriptConfig(packerOptions, projectDir, log)); } if (packerOptions.testFramework === 'jasmine') { tasks.push(copyJasmineConfig(packerOptions, testEnvironment, projectDir, log)); tasks.push(copyJasmineHelpers(projectDir, log)); tasks.push(copyJasmineSpec(scriptGlob, scriptExt, projectDir, log)); } if (packerOptions.testFramework === 'mocha') { tasks.push(copyMochaConfig(packerOptions, testEnvironment, projectDir, log)); tasks.push(copyMochaHelpers(projectDir, log)); tasks.push(copyMochaTestSpec(scriptGlob, scriptExt, projectDir, log)); } } } return tasks; };
the_stack
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { cookError, isSearchBot, safeStringifyError } from '@app/shared/utilities'; import { environment as env } from '@env/environment'; import { del, get, keys, set } from 'idb-keyval'; import { BehaviorSubject, throwError } from 'rxjs'; import { catchError, last, retry, tap } from 'rxjs/operators'; import { unzipSync, strFromU8 } from 'fflate'; @Injectable() export class DestinyCacheService { public cache: Cache; public readonly ready$: BehaviorSubject<boolean> = new BehaviorSubject(false); public readonly version$: BehaviorSubject<string> = new BehaviorSubject(''); public readonly checkingCache: BehaviorSubject<boolean> = new BehaviorSubject(false); public readonly percent: BehaviorSubject<number> = new BehaviorSubject(0); public readonly unzipping: BehaviorSubject<boolean> = new BehaviorSubject(false); public readonly error: BehaviorSubject<string> = new BehaviorSubject(null); public readonly errorDetails: BehaviorSubject<any> = new BehaviorSubject(null); public readonly searchBot: boolean = isSearchBot(); constructor(private http: HttpClient) { if (!this.searchBot) { this.init(); } } private async init() { this.checkingCache.next(true); const t0 = performance.now(); const key = 'manifest-' + env.versions.manifest; console.log(`Loading cache ${key}`); try { const manifest = await get(key); this.checkingCache.next(false); // if nothing found, perhaps version has changed, clear old values if (manifest == null) { console.log('No cached value found'); const ks = await keys(); for (const k of ks) { if (k.toString().startsWith('manifest')) { del(k); } } await this.load(key); } else { this.cache = manifest as Cache; } if (this.cache?.version) { this.version$.next(this.cache.version); } this.percent.next(100); this.ready$.next(true); const t1 = performance.now(); console.log((t1 - t0) + ' ms to load manifest'); } catch (exc) { console.log(`Error loading Bungie Manifest DB ${key}`); const s = safeStringifyError(exc); console.log(s); this.errorDetails.next(s); try { console.log('Deleting any existing cache entry'); await del(key); } catch (exc2) { console.log('Secondary error deleting cache entry'); console.dir(exc2); } this.error.next('There was an error loading the Bungie Manifest DB, please refresh the page and try again.'); } finally { this.checkingCache.next(false); this.percent.next(100); } } async unzip(blob: Blob): Promise<void> { let ab: ArrayBuffer; // if blob.arraybuffer is not suppported, copy to a new request if (!blob.arrayBuffer) { ab = await new Response(blob).arrayBuffer(); } else { ab = await blob.arrayBuffer(); } const unzipMe = new Uint8Array(ab); const decompressed = unzipSync(unzipMe); const binaryData = decompressed['destiny2.json']; const data2 = strFromU8(binaryData); this.cache = JSON.parse(data2); this.ready$.next(true); } private showProgress(evt: HttpEvent<any>) { switch (evt.type) { case HttpEventType.Sent: this.percent.next(5); break; case HttpEventType.ResponseHeader: this.percent.next(10); break; case HttpEventType.DownloadProgress: const kbLoaded = Math.round(evt.loaded / 1024); console.log(`Download in progress! ${kbLoaded}Kb loaded`); this.percent.next(15 + 80 * evt.loaded / evt.total); break; case HttpEventType.Response: { this.percent.next(95); } } } private async download(cacheBuster?: string): Promise<Blob> { console.log(`--- load remote cache ${env.versions.manifest} ---`); let uri = `/assets/destiny2.zip?ngsw-bypass=true&v=${env.versions.manifest}`; if (cacheBuster && cacheBuster.trim().length > 0) { uri = `/assets/destiny2.zip?ngsw-bypass=true&v=${env.versions.manifest}-${cacheBuster}`; } console.log(`Downloading zip from URI: ${uri}`); const req = new HttpRequest<Blob>('GET', uri, { reportProgress: true, responseType: 'blob' }); const finalHttpEvt = await this.http.request(req).pipe( tap((evt: HttpEvent<any>) => this.showProgress(evt)), retry(1), last(), catchError(err => throwError(cookError(err))) ).toPromise(); if (finalHttpEvt.type !== HttpEventType.Response) { throw new Error(`Unexpected final http event type ${finalHttpEvt.type}`); } const dl = finalHttpEvt as HttpResponse<Blob>; this.percent.next(100); return dl.body; } async load(key: string, isRetry?: boolean): Promise<void> { let blob = await this.download(); // retry if size zero to try to get to the bottom of weird problem if (blob.size == 0) { console.log(` Retrieved zero length blob, adding cache buster and retrying.`); blob = await this.download('' + new Date().getTime()); } console.log(` Retrieved Blob size ${blob.size}. Beginning unzip...`); this.unzipping.next(true); try { try { await this.unzip(blob); } catch (unzipExc) { console.dir(unzipExc); if (!isRetry) { console.log('Initial error unzipping blob. Retrying...'); await this.load(key, true); } else { console.log('Secondary error unzipping blob. Fail'); throw unzipExc; } } set(key, this.cache); return; } finally { this.unzipping.next(false); } } } export interface Cache { version: string; destiny2CoreSettings: Destiny2CoreSettings; Vendor?: any; Race?: any; Gender?: any; EnergyType?: any; Class?: any; Activity?: any; ActivityType?: any; ActivityMode?: any; Milestone?: any; Faction?: any; Progression?: any; PowerCap?: any; InventoryItem?: { [key: string]: ManifestInventoryItem }; Stat?: any; Objective?: { [key: string]: Objective }; ActivityModifier?: any; Perk?: any; SocketType?: any; PlugSet?: any; SocketCategory?: any; Checklist?: any; InventoryBucket?: any; EquipmentSlot?: any; PresentationNode?: any; Record?: any; Collectible?: any; ItemTierType?: any; HistoricalStats?: any; RecordSeasons?: any; PursuitTags?: { [key: string]: string[] }; Season?: { [key: string]: Season }; SeasonPass?: { [key: string]: SeasonPass }; TagWeights?: { [key: string]: number }; } export interface Destiny2CoreSettings { collectionRootNode: number; badgesRootNode: number; recordsRootNode: number; medalsRootNode: number; metricsRootNode: number; activeTriumphsRootNodeHash: number; activeSealsRootNodeHash: number; legacyTriumphsRootNodeHash: number; legacySealsRootNodeHash: number; medalsRootNodeHash: number; exoticCatalystsRootNodeHash: number; loreRootNodeHash: number; currentRankProgressionHashes: number[]; undiscoveredCollectibleImage: string; ammoTypeHeavyIcon: string; ammoTypeSpecialIcon: string; ammoTypePrimaryIcon: string; currentSeasonalArtifactHash: number; currentSeasonHash: number; seasonalChallengesPresentationNodeHash: number; futureSeasonHashes: number[]; pastSeasonHashes: number[]; } export interface ManifestInventoryItem { displayProperties: DisplayProperties; iconWatermark: string; tooltipNotifications: any[]; backgroundColor: any; itemTypeDisplayName: string; uiItemDisplayStyle: string; itemTypeAndTierDisplayName: string; displaySource: string; tooltipStyle: string; inventory: any; damageTypes: any[]; stats: any; value: any; objectives: Objectives; acquireRewardSiteHash: number; acquireUnlockHash: number; investmentStats: any[]; perks: any[]; allowActions: boolean; doesPostmasterPullHaveSideEffects: boolean; nonTransferrable: boolean; itemCategoryHashes: number[]; specialItemType: number; itemType: number; itemSubType: number; classType: number; breakerType: number; equippable: boolean; defaultDamageType: number; isWrapper: boolean; hash: number; index: number; redacted: boolean; blacklisted: boolean; quality: Quality; sockets: any; plug: any; } interface Quality { currentVersion: number; displayVersionWatermarkIcons: string[]; infusionCategoryHash: number; infusionCategoryHashes: number[]; infusionCategoryName: string; itemLevels: any[]; progressionLevelRequirementHash: number; qualityLevel: number; versions: Version[]; } interface Version { powerCapHash: number; } // part of Inventory Item interface Objectives { objectiveHashes: number[]; displayActivityHashes: number[]; requireFullObjectiveCompletion: boolean; questlineItemHash: number; narrative: string; objectiveVerbName: string; questTypeIdentifier: string; questTypeHash: number; completionRewardSiteHash: number; nextQuestStepRewardSiteHash: number; timestampUnlockValueHash: number; isGlobalObjectiveItem: boolean; useOnObjectiveCompletion: boolean; inhibitCompletionUnlockValueHash: number; perObjectiveDisplayProperties: any[]; } // an Objective record looked up from an objective-hash export interface Objective { displayProperties: DisplayProperties; unlockValueHash: number; completionValue: number; scope: number; locationHash: number; allowNegativeValue: boolean; allowValueChangeWhenCompleted: boolean; isCountingDownward: boolean; valueStyle: number; progressDescription: string; perks: any; stats: any; minimumVisibilityThreshold: number; allowOvercompletion: boolean; showValueOnComplete: boolean; isDisplayOnlyObjective: boolean; completedValueStyle: number; inProgressValueStyle: number; hash: number; index: number; redacted: boolean; blacklisted: boolean; } export interface Season { artifactItemHash: string; backgroundImagePath: string; blacklisted: boolean; displayProperties: DisplayProperties; endDate: string; hash: string; index: number; redacted: boolean; sealPresentationNodeHash: number; seasonNumber: number; seasonPassHash: string; seasonPassProgressionHash: string; seasonPassUnlockHash: string; startDate: string; startTimeInSeconds: string; } export interface SeasonPass { blacklisted: boolean; displayProperties: DisplayProperties; hash: string; index: number; prestigeProgressionHash: string; redacted: boolean; rewardProgressionHash: string; } interface DisplayProperties { description: string; name: string; icon: string; hasIcon: boolean; }
the_stack
import { Injectable } from '@angular/core'; import { CoreSyncBlockedError } from '@classes/base-sync'; import { CoreNetworkError } from '@classes/errors/network-error'; import { CoreCourseActivitySyncBaseProvider } from '@features/course/classes/activity-sync'; import { CoreCourse } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreApp } from '@services/app'; import { CoreSites, CoreSitesReadingStrategy } from '@services/sites'; import { CoreSync } from '@services/sync'; import { CoreTimeUtils } from '@services/utils/time'; import { CoreUrlUtils } from '@services/utils/url'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModLessonRetakeFinishedInSyncDBRecord, RETAKES_FINISHED_SYNC_TABLE_NAME } from './database/lesson'; import { AddonModLessonGetPasswordResult, AddonModLessonPrefetchHandler } from './handlers/prefetch'; import { AddonModLesson, AddonModLessonLessonWSData, AddonModLessonProvider } from './lesson'; import { AddonModLessonOffline, AddonModLessonPageAttemptRecord } from './lesson-offline'; /** * Service to sync lesson. */ @Injectable({ providedIn: 'root' }) export class AddonModLessonSyncProvider extends CoreCourseActivitySyncBaseProvider<AddonModLessonSyncResult> { static readonly AUTO_SYNCED = 'addon_mod_lesson_autom_synced'; protected componentTranslatableString = 'lesson'; constructor() { super('AddonModLessonSyncProvider'); } /** * Unmark a retake as finished in a synchronization. * * @param lessonId Lesson ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteRetakeFinishedInSync(lessonId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); // Ignore errors, maybe there is none. await CoreUtils.ignoreErrors(site.getDb().deleteRecords(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); } /** * Get a retake finished in a synchronization for a certain lesson (if any). * * @param lessonId Lesson ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the retake entry (undefined if no retake). */ async getRetakeFinishedInSync( lessonId: number, siteId?: string, ): Promise<AddonModLessonRetakeFinishedInSyncDBRecord | undefined> { const site = await CoreSites.getSite(siteId); return CoreUtils.ignoreErrors(site.getDb().getRecord(RETAKES_FINISHED_SYNC_TABLE_NAME, { lessonid: lessonId })); } /** * Check if a lesson has data to synchronize. * * @param lessonId Lesson ID. * @param retake Retake number. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether it has data to sync. */ async hasDataToSync(lessonId: number, retake: number, siteId?: string): Promise<boolean> { const [hasAttempts, hasFinished] = await Promise.all([ CoreUtils.ignoreErrors(AddonModLessonOffline.hasRetakeAttempts(lessonId, retake, siteId)), CoreUtils.ignoreErrors(AddonModLessonOffline.hasFinishedRetake(lessonId, siteId)), ]); return !!(hasAttempts || hasFinished); } /** * Mark a retake as finished in a synchronization. * * @param lessonId Lesson ID. * @param retake The retake number. * @param pageId The page ID to start reviewing from. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async setRetakeFinishedInSync(lessonId: number, retake: number, pageId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.getDb().insertRecord(RETAKES_FINISHED_SYNC_TABLE_NAME, <AddonModLessonRetakeFinishedInSyncDBRecord> { lessonid: lessonId, retake: Number(retake), pageid: Number(pageId), timefinished: CoreTimeUtils.timestamp(), }); } /** * Try to synchronize all the lessons in a certain site or in all sites. * * @param siteId Site ID to sync. If not defined, sync all sites. * @param force Wether to force sync not depending on last execution. * @return Promise resolved if sync is successful, rejected if sync fails. */ syncAllLessons(siteId?: string, force = false): Promise<void> { return this.syncOnSites('all lessons', this.syncAllLessonsFunc.bind(this, !!force), siteId); } /** * Sync all lessons on a site. * * @param force Wether to force sync not depending on last execution. * @param siteId Site ID to sync. * @param Promise resolved if sync is successful, rejected if sync fails. */ protected async syncAllLessonsFunc(force: boolean, siteId: string): Promise<void> { // Get all the lessons that have something to be synchronized. const lessons = await AddonModLessonOffline.getAllLessonsWithData(siteId); // Sync all lessons that need it. await Promise.all(lessons.map(async (lesson) => { const result = force ? await this.syncLesson(lesson.id, false, false, siteId) : await this.syncLessonIfNeeded(lesson.id, false, siteId); if (result?.updated) { // Sync successful, send event. CoreEvents.trigger(AddonModLessonSyncProvider.AUTO_SYNCED, { lessonId: lesson.id, warnings: result.warnings, }, siteId); } })); } /** * Sync a lesson only if a certain time has passed since the last time. * * @param lessonId Lesson ID. * @param askPreflight Whether we should ask for password if needed. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the lesson is synced or if it doesn't need to be synced. */ async syncLessonIfNeeded( lessonId: number, askPassword = false, siteId?: string, ): Promise<AddonModLessonSyncResult | undefined> { const needed = await this.isSyncNeeded(lessonId, siteId); if (needed) { return this.syncLesson(lessonId, askPassword, false, siteId); } } /** * Try to synchronize a lesson. * * @param lessonId Lesson ID. * @param askPassword True if we should ask for password if needed, false otherwise. * @param ignoreBlock True to ignore the sync block setting. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success. */ async syncLesson( lessonId: number, askPassword = false, ignoreBlock = false, siteId?: string, ): Promise<AddonModLessonSyncResult> { siteId = siteId || CoreSites.getCurrentSiteId(); let syncPromise = this.getOngoingSync(lessonId, siteId); if (syncPromise) { // There's already a sync ongoing for this lesson, return the promise. return syncPromise; } // Verify that lesson isn't blocked. if (!ignoreBlock && CoreSync.isBlocked(AddonModLessonProvider.COMPONENT, lessonId, siteId)) { this.logger.debug('Cannot sync lesson ' + lessonId + ' because it is blocked.'); throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate })); } this.logger.debug('Try to sync lesson ' + lessonId + ' in site ' + siteId); syncPromise = this.performSyncLesson(lessonId, askPassword, ignoreBlock, siteId); return this.addOngoingSync(lessonId, syncPromise, siteId); } /** * Try to synchronize a lesson. * * @param lessonId Lesson ID. * @param askPassword True if we should ask for password if needed, false otherwise. * @param ignoreBlock True to ignore the sync block setting. * @param siteId Site ID. If not defined, current site. * @return Promise resolved in success. */ protected async performSyncLesson( lessonId: number, askPassword = false, ignoreBlock = false, siteId?: string, ): Promise<AddonModLessonSyncResult> { // Sync offline logs. await CoreUtils.ignoreErrors( CoreCourseLogHelper.syncActivity(AddonModLessonProvider.COMPONENT, lessonId, siteId), ); const result: AddonModLessonSyncResult = { warnings: [], updated: false, }; // Try to synchronize the page attempts first. const passwordData = await this.syncAttempts(lessonId, result, askPassword, siteId); // Now sync the retake. await this.syncRetake(lessonId, result, passwordData, askPassword, ignoreBlock, siteId); if (result.updated && result.courseId) { try { // Data has been sent to server, update data. const module = await CoreCourse.getModuleBasicInfoByInstance(lessonId, 'lesson', { siteId }); await this.prefetchAfterUpdate(AddonModLessonPrefetchHandler.instance, module, result.courseId, undefined, siteId); } catch { // Ignore errors. } } // Sync finished, set sync time. await CoreUtils.ignoreErrors(this.setSyncTime(lessonId, siteId)); // All done, return the result. return result; } /** * Sync all page attempts. * * @param lessonId Lesson ID. * @param result Sync result where to store the result. * @param askPassword True if we should ask for password if needed, false otherwise. * @param siteId Site ID. If not defined, current site. */ protected async syncAttempts( lessonId: number, result: AddonModLessonSyncResult, askPassword = false, siteId?: string, ): Promise<AddonModLessonGetPasswordResult | undefined> { let attempts = await AddonModLessonOffline.getLessonAttempts(lessonId, siteId); if (!attempts.length) { return; } else if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } result.courseId = attempts[0].courseid; const attemptsLength = attempts.length; // Get the info, access info and the lesson password if needed. const lesson = await AddonModLesson.getLessonById(result.courseId, lessonId, { siteId }); const passwordData = await AddonModLessonPrefetchHandler.getLessonPassword(lessonId, { readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, askPassword, siteId, }); const promises: Promise<void>[] = []; passwordData.lesson = passwordData.lesson || lesson; // Filter the attempts, get only the ones that belong to the current retake. attempts = attempts.filter((attempt) => { if (attempt.retake == passwordData.accessInfo.attemptscount) { return true; } // Attempt doesn't belong to current retake, delete. promises.push(CoreUtils.ignoreErrors(AddonModLessonOffline.deleteAttempt( lesson.id, attempt.retake, attempt.pageid, attempt.timemodified, siteId, ))); return false; }); if (attempts.length != attemptsLength) { // Some attempts won't be sent, add a warning. this.addOfflineDataDeletedWarning( result.warnings, lesson.name, Translate.instant('addon.mod_lesson.warningretakefinished'), ); } await Promise.all(promises); if (!attempts.length) { return passwordData; } // Send the attempts in the same order they were answered. attempts.sort((a, b) => a.timemodified - b.timemodified); const promisesData = attempts.map((attempt) => ({ function: this.sendAttempt.bind(this, lesson, passwordData.password, attempt, result, siteId), blocking: true, })); await CoreUtils.executeOrderedPromises(promisesData); return passwordData; } /** * Send an attempt to the site and delete it afterwards. * * @param lesson Lesson. * @param password Password (if any). * @param attempt Attempt to send. * @param result Result where to store the data. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ protected async sendAttempt( lesson: AddonModLessonLessonWSData, password: string, attempt: AddonModLessonPageAttemptRecord, result: AddonModLessonSyncResult, siteId?: string, ): Promise<void> { const retake = attempt.retake; const pageId = attempt.pageid; const timemodified = attempt.timemodified; try { // Send the page data. await AddonModLesson.processPageOnline(lesson.id, attempt.pageid, attempt.data || {}, { password, siteId, }); result.updated = true; await AddonModLessonOffline.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); } catch (error) { if (!error || !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server. throw error; } // The WebService has thrown an error, this means that the attempt cannot be submitted. Delete it. result.updated = true; await AddonModLessonOffline.deleteAttempt(lesson.id, retake, pageId, timemodified, siteId); // Attempt deleted, add a warning. this.addOfflineDataDeletedWarning(result.warnings, lesson.name, error); } } /** * Sync retake. * * @param lessonId Lesson ID. * @param result Sync result where to store the result. * @param passwordData Password data. If not provided it will be calculated. * @param askPassword True if we should ask for password if needed, false otherwise. * @param ignoreBlock True to ignore the sync block setting. * @param siteId Site ID. If not defined, current site. */ protected async syncRetake( lessonId: number, result: AddonModLessonSyncResult, passwordData?: AddonModLessonGetPasswordResult, askPassword = false, ignoreBlock = false, siteId?: string, ): Promise<void> { // Attempts sent or there was none. If there is a finished retake, send it. const retake = await CoreUtils.ignoreErrors(AddonModLessonOffline.getRetake(lessonId, siteId)); if (!retake) { // No retake to sync. return; } if (!retake.finished) { // The retake isn't marked as finished, nothing to send. Delete the retake. await AddonModLessonOffline.deleteRetake(lessonId, siteId); return; } else if (!CoreApp.isOnline()) { // Cannot sync in offline. throw new CoreNetworkError(); } result.courseId = retake.courseid || result.courseId; if (!passwordData?.lesson) { // Retrieve the needed data. const lesson = await AddonModLesson.getLessonById(result.courseId!, lessonId, { siteId }); passwordData = await AddonModLessonPrefetchHandler.getLessonPassword(lessonId, { readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, askPassword, siteId, }); passwordData.lesson = passwordData.lesson || lesson; } if (retake.retake != passwordData.accessInfo.attemptscount) { // The retake changed, add a warning if it isn't there already. if (!result.warnings.length) { this.addOfflineDataDeletedWarning( result.warnings, passwordData.lesson.name, Translate.instant('addon.mod_lesson.warningretakefinished'), ); } await AddonModLessonOffline.deleteRetake(lessonId, siteId); } try { // All good, finish the retake. const response = await AddonModLesson.finishRetakeOnline(lessonId, { password: passwordData.password, siteId, }); result.updated = true; // Mark the retake as finished in a sync if it can be reviewed. if (!ignoreBlock && response.data?.reviewlesson) { const params = CoreUrlUtils.extractUrlParams(<string> response.data.reviewlesson.value); if (params.pageid) { // The retake can be reviewed, mark it as finished. Don't block the user for this. this.setRetakeFinishedInSync(lessonId, retake.retake, Number(params.pageid), siteId); } } await AddonModLessonOffline.deleteRetake(lessonId, siteId); } catch (error) { if (!error || !CoreUtils.isWebServiceError(error)) { // Couldn't connect to server. throw error; } // The WebService has thrown an error, this means that responses cannot be submitted. Delete them. result.updated = true; await AddonModLessonOffline.deleteRetake(lessonId, siteId); // Retake deleted, add a warning. this.addOfflineDataDeletedWarning(result.warnings, passwordData.lesson.name, error); } } } export const AddonModLessonSync = makeSingleton(AddonModLessonSyncProvider); /** * Data returned by a lesson sync. */ export type AddonModLessonSyncResult = { warnings: string[]; // List of warnings. updated: boolean; // Whether some data was sent to the server or offline data was updated. courseId?: number; // Course the lesson belongs to (if known). }; /** * Data passed to AUTO_SYNCED event. */ export type AddonModLessonAutoSyncData = { lessonId: number; warnings: string[]; };
the_stack
import { Enum, Field, Method, NamespaceBase, OneOf, Root, Service, Type, util } from 'protobufjs' import { EnumOptions, FieldOptions, FileOptions, IDescriptorProto, IEnumDescriptorProto, IFieldDescriptorProto, IFileDescriptorSet, IMethodDescriptorProto, IOneofDescriptorProto, IServiceDescriptorProto, MessageOptions, MethodOptions, ServiceOptions } from 'protobufjs/ext/descriptor' // This code is heavily tweaked from protobufjs/ext/descriptor to make it typesafe and add support // for comments interface ISourceCodeInfo { location: ILocation[] } interface ILocation { path: number[] span: number[] leadingComments?: string trailingComments?: string leadingDetachedComments?: string[] } const numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/ const FILE_MESSAGE_TYPE_LOCATION = 4 const FILE_ENUM_TYPE_LOCATION = 5 const FILE_SERVICE_LOCATION = 6 const FILE_EXTENSION_LOCATION = 7 const MESSAGE_FIELD_LOCATION = 2 const MESSAGE_NESTED_TYPE_LOCATION = 3 const MESSAGE_ENUM_TYPE_LOCATION = 4 const MESSAGE_EXTENSION_LOCATION = 6 const ENUM_VALUE_LOCATION = 2 const SERVICE_METHOD_LOCATION = 2 let unnamedMessageIndex = 0 let unnamedEnumIndex = 0 let unnamedOneofIndex = 0 let unnamedServiceIndex = 0 let unnamedMethodIndex = 0 export const buildRoot = (descriptor: IFileDescriptorSet): Root => { const root = new Root() if (descriptor.file) { for (const fileDescriptor of descriptor.file) { let filePackage: NamespaceBase = root const filename = fileDescriptor.name || null const sourceCodeInfo = fileDescriptor.sourceCodeInfo as ISourceCodeInfo | undefined const sourceLocations = sourceCodeInfo ? sourceCodeInfo.location : [] if (fileDescriptor.package && fileDescriptor.package.length) { filePackage = root.define(fileDescriptor.package) } if (fileDescriptor.name && fileDescriptor.name.length) { filePackage.filename = fileDescriptor.name root.files.push(fileDescriptor.name) } if (fileDescriptor.messageType) { for (let i = 0; i < fileDescriptor.messageType.length; ++i) { const messageSourceLocations = sourceLocations.filter(isLocation(0, i, FILE_MESSAGE_TYPE_LOCATION)) filePackage.add(buildType(fileDescriptor.messageType[i], messageSourceLocations, 2, filename, fileDescriptor.syntax)) } } if (fileDescriptor.enumType) { for (let i = 0; i < fileDescriptor.enumType.length; ++i) { const enumSourceLocations = sourceLocations.filter(isLocation(0, i, FILE_ENUM_TYPE_LOCATION)) filePackage.add(buildEnum(fileDescriptor.enumType[i], enumSourceLocations, 2, filename)) } } if (fileDescriptor.extension) { for (let i = 0; i < fileDescriptor.extension.length; ++i) { const extensionSourceLocations = sourceLocations.filter(isLocation(0, i, FILE_EXTENSION_LOCATION)) filePackage.add(buildField(fileDescriptor.extension[i], extensionSourceLocations, 2, filename)) } } if (fileDescriptor.service) { for (let i = 0; i < fileDescriptor.service.length; ++i) { const serviceSourceLocations = sourceLocations.filter(isLocation(0, i, FILE_SERVICE_LOCATION)) filePackage.add(buildService(fileDescriptor.service[i], serviceSourceLocations, 2, filename)) } } const opts = fromDescriptorOptions(fileDescriptor.options, FileOptions) if (opts) { const ks = Object.keys(opts) for (const key of ks) { filePackage.setOption(key, opts[key]) } } } } return root } const buildType = (descriptor: IDescriptorProto, sourceLocations: ILocation[], sourcePathIndex: number, filename: string | null, syntax?: string): Type => { // Create the message type const name = descriptor.name const finalName = (name && name.length) ? name : 'Type' + unnamedMessageIndex++ const typeOptions = fromDescriptorOptions(descriptor.options, MessageOptions) const type = new Type(finalName, typeOptions) type.filename = filename type.comment = extractComment(sourceLocations, sourcePathIndex) /* Oneofs */ if (descriptor.oneofDecl) { for (const oneofDecl of descriptor.oneofDecl) { type.add(buildOneOf(oneofDecl, filename)) } } /* Fields */ if (descriptor.field) { for (let i = 0; i < descriptor.field.length; ++i) { const fieldSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, MESSAGE_FIELD_LOCATION)) const field = buildField(descriptor.field[i], fieldSourceLocations, sourcePathIndex + 2, filename, syntax) type.add(field) if (descriptor.field[i].hasOwnProperty('oneofIndex')) { type.oneofsArray[descriptor.field[i].oneofIndex || 0].add(field) } } } /* Extension fields */ if (descriptor.extension) { for (let i = 0; i < descriptor.extension.length; ++i) { const extensionSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, MESSAGE_EXTENSION_LOCATION)) const field = buildField(descriptor.extension[i], extensionSourceLocations, sourcePathIndex + 2, filename, syntax) type.add(field) } } /* Nested types */ if (descriptor.nestedType) { for (let i = 0; i < descriptor.nestedType.length; ++i) { const messageSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, MESSAGE_NESTED_TYPE_LOCATION)) const nestedType = buildType(descriptor.nestedType[i], messageSourceLocations, sourcePathIndex + 2, filename, syntax) type.add(nestedType) const options = descriptor.nestedType[i].options if (options && options.mapEntry) { type.setOption('map_entry', true) } } } /* Nested enums */ if (descriptor.enumType) { for (let i = 0; i < descriptor.enumType.length; ++i) { const enumSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, MESSAGE_ENUM_TYPE_LOCATION)) type.add(buildEnum(descriptor.enumType[i], enumSourceLocations, sourcePathIndex + 2, filename)) } } /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { type.extensions = [] for (const extensionRange of descriptor.extensionRange) { type.extensions.push([extensionRange.start || 0, extensionRange.end || 0]) } } /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { type.reserved = [] /* Ranges */ if (descriptor.reservedRange) { for (const reservedRange of descriptor.reservedRange) { type.reserved.push([reservedRange.start || 0, reservedRange.end || 0]) } } /* Names */ if (descriptor.reservedName) { for (const reservedName of descriptor.reservedName) { type.reserved.push(reservedName) } } } return type } const buildField = (descriptor: IFieldDescriptorProto, sourceLocations: ILocation[], sourcePathIndex: number, filename: string | null, syntax?: string): Field => { if (typeof descriptor.number !== 'number') { throw Error('missing field id') } // Rewire field type let fieldType if (descriptor.typeName && descriptor.typeName.length) { fieldType = descriptor.typeName } else { fieldType = fromDescriptorType(descriptor.type) } // Rewire field rule let fieldRule switch (descriptor.label) { // 0 is reserved for errors case 1: fieldRule = undefined break case 2: fieldRule = 'required' break case 3: fieldRule = 'repeated' break default: throw Error('illegal label: ' + descriptor.label) } let extendee = descriptor.extendee if (extendee) { extendee = extendee.length ? extendee : undefined } const field = new Field( (descriptor.name && descriptor.name.length) ? descriptor.name : 'field' + descriptor.number, descriptor.number, fieldType, fieldRule, extendee ) field.filename = filename field.comment = extractComment(sourceLocations, sourcePathIndex) field.options = fromDescriptorOptions(descriptor.options, FieldOptions) if (descriptor.defaultValue && descriptor.defaultValue.length) { let defaultValue: string | number | boolean = descriptor.defaultValue switch (defaultValue) { case 'true': case 'TRUE': defaultValue = true break case 'false': case 'FALSE': defaultValue = false break default: const match = numberRe.exec(defaultValue) if (match) { defaultValue = parseInt(defaultValue, 10) } break } field.setOption('default', defaultValue) } if (packableDescriptorType(descriptor.type)) { if (syntax === 'proto3') { // defaults to packed=true (internal preset is packed=true) if (descriptor.options && !descriptor.options.packed) { field.setOption('packed', false) } } else if (!(descriptor.options && descriptor.options.packed)) {// defaults to packed=false field.setOption('packed', false) } } return field } const buildEnum = (descriptor: IEnumDescriptorProto, sourceLocations: ILocation[], sourcePathIndex: number, filename: string | null): Enum => { // Construct values object const values = {} const comments = {} if (descriptor.value) { for (let i = 0; i < descriptor.value.length; ++i) { const name = descriptor.value[i].name const value = descriptor.value[i].number || 0 const finalName = name && name.length ? name : 'NAME' + value values[finalName] = value const enumValueSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, ENUM_VALUE_LOCATION)) comments[finalName] = extractComment(enumValueSourceLocations, sourcePathIndex + 2) } } const enumeration = new Enum( descriptor.name && descriptor.name.length ? descriptor.name : 'Enum' + unnamedEnumIndex++, values, fromDescriptorOptions(descriptor.options, EnumOptions) ) enumeration.filename = filename enumeration.comment = extractComment(sourceLocations, sourcePathIndex) return enumeration } const buildOneOf = (descriptor: IOneofDescriptorProto, filename: string | null): OneOf => { return new OneOf( // unnamedOneOfIndex is global, not per type, because we have no ref to a type here descriptor.name && descriptor.name.length ? descriptor.name : 'oneof' + unnamedOneofIndex++ // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option ) } const buildService = (descriptor: IServiceDescriptorProto, sourceLocations: ILocation[], sourcePathIndex: number, filename: string | null): Service => { const finalName = descriptor.name && descriptor.name.length ? descriptor.name : 'Service' + unnamedServiceIndex++ const serviceOptions = fromDescriptorOptions(descriptor.options, ServiceOptions) const service = new Service(finalName, serviceOptions) service.filename = filename service.comment = extractComment(sourceLocations, sourcePathIndex) if (descriptor.method) { for (let i = 0; i < descriptor.method.length; ++i) { const methodSourceLocations = sourceLocations.filter(isLocation(sourcePathIndex, i, SERVICE_METHOD_LOCATION)) service.add(buildMethod(descriptor.method[i], methodSourceLocations, sourcePathIndex + 2, filename)) } } return service } const buildMethod = (descriptor: IMethodDescriptorProto, sourceLocations: ILocation[], sourcePathIndex: number, filename: string | null): Method => { const method = new Method( // unnamedMethodIndex is global, not per service, because we have no ref to a service here descriptor.name && descriptor.name.length ? descriptor.name : 'Method' + unnamedMethodIndex++, 'rpc', descriptor.inputType || '', descriptor.outputType || '', Boolean(descriptor.clientStreaming), Boolean(descriptor.serverStreaming), fromDescriptorOptions(descriptor.options, MethodOptions) ) method.filename = filename method.comment = extractComment(sourceLocations, sourcePathIndex) return method } const isLocation = (sourcePathIndex: number, index: number, locationType: number): (location: ILocation) => boolean => { return (l: ILocation) => l.path[sourcePathIndex] === locationType && l.path[sourcePathIndex + 1] === index } const extractComment = (sourceLocations: ILocation[], sourcePathIndex: number): string | null => { for (const location of sourceLocations) { if (location.path.length === sourcePathIndex) { const comment = location.leadingComments || location.trailingComments || null if (comment) { return comment } } } return null } const fromDescriptorType = (type: number | undefined): string => { switch (type) { // 0 is reserved for errors case 1: return 'double' case 2: return 'float' case 3: return 'int64' case 4: return 'uint64' case 5: return 'int32' case 6: return 'fixed64' case 7: return 'fixed32' case 8: return 'bool' case 9: return 'string' case 12: return 'bytes' case 13: return 'uint32' case 15: return 'sfixed32' case 16: return 'sfixed64' case 17: return 'sint32' case 18: return 'sint64' } throw Error('illegal type: ' + type) } const packableDescriptorType = (type: number | undefined): boolean => { switch (type) { case 1: // double case 2: // float case 3: // int64 case 4: // uint64 case 5: // int32 case 6: // fixed64 case 7: // fixed32 case 8: // bool case 13: // uint32 case 14: // enum (!) case 15: // sfixed32 case 16: // sfixed64 case 17: // sint32 case 18: // sint64 return true } return false } const fromDescriptorOptions = (options: any, type: any) => { if (!options) { return undefined } const out = [] for (const field of type.fieldsArray) { const key = field.name if (key !== 'uninterpretedOption') { if (options.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins let val = options[key] if (field.resolvedType instanceof Enum && typeof val === 'number' && field.resolvedType.valuesById[val] !== undefined) { val = field.resolvedType.valuesById[val] } out.push(underScore(key), val) } } } return out.length ? util.toObject(out) : undefined } const underScore = (str: string) => { return str.substring(0, 1) + str.substring(1).replace(/([A-Z])(?=[a-z]|$)/g, ($0, $1) => '_' + $1.toLowerCase()) }
the_stack
import { ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons'; import { ModalForm, ProFormDependency, ProFormSelect, ProFormSwitch, ProFormText } from '@ant-design/pro-form'; import { PageContainer } from '@ant-design/pro-layout'; import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table'; import { Button, Checkbox, Divider, FormInstance, Input, message, Modal, Space, Switch, Tag } from 'antd'; import React, { useState, useRef, useEffect } from 'react'; import { getIntl, getLocale, Link, useIntl} from 'umi'; import UpdateForm from './comps/updateForm'; import { AppListItem, AppListParams, AppListResult, UserAppAuth } from './data'; import { addApp, editApp, delApp, queryApps, inheritancedApps,enableOrdisableApp, saveAppAuth, getAppGroups } from './service'; import { adminUsers } from '@/pages/User/service'; import UserAuth from './comps/userAuth'; import AuthorizedEle from '@/components/Authorized/AuthorizedElement'; import functionKeys from '@/models/functionKeys'; import { current } from '@/services/user'; import { getUserInfo, setAuthority, setFunctions } from '@/utils/authority'; const { confirm } = Modal; const fetchSystemInfo = async () => { const result = await current(); setAuthority(result.currentUser.currentAuthority); setFunctions(result.currentUser.currentFunctions) } const handleAdd = async (fields: AppListItem) => { const intl = getIntl(getLocale()); const hide = message.loading(intl.formatMessage({ id:'saving' })); try { const result = await addApp({ ...fields }); hide(); const success = result.success; if (success) { fetchSystemInfo(); message.success(intl.formatMessage({ id:'save_success' })); } else { message.error(result.message); } return success; } catch (error) { hide(); message.error(intl.formatMessage({ id:'save_fail' })); return false; } }; const handleEdit = async (app: AppListItem) => { const intl = getIntl(getLocale()); const hide = message.loading(intl.formatMessage({ id:'saving' })); try { const result = await editApp({ ...app }); hide(); const success = result.success; if (success) { fetchSystemInfo(); message.success(intl.formatMessage({ id:'save_success' })); } else { message.error(result.message); } return success; } catch (error) { hide(); message.error(intl.formatMessage({ id:'save_fail' })); return false; } }; const handleDel = async (fields: AppListItem) => { const intl = getIntl(getLocale()); const hide = message.loading(intl.formatMessage({ id:'deleting' })); try { const result = await delApp({ ...fields }); hide(); const success = result.success; if (success) { fetchSystemInfo(); message.success(intl.formatMessage({ id:'delete_success' })); } else { message.error(intl.formatMessage({ id:'delete_fail' })); } return success; } catch (error) { hide(); message.error(intl.formatMessage({ id:'delete_fail' })); return false; } }; const handleUserAppAuth = async (model: UserAppAuth) => { const intl = getIntl(getLocale()); const hide = message.loading(intl.formatMessage({ id:'saving' })); try { const result = await saveAppAuth({ ...model }); hide(); const success = result.success; if (success) { fetchSystemInfo(); message.success(intl.formatMessage({ id:'save_success' })); } else { message.error(result.message); } return success; } catch (error) { hide(); message.error(intl.formatMessage({ id:'save_fail' })); return false; } }; const appList: React.FC = (props) => { const actionRef = useRef<ActionType>(); const addFormRef = useRef<FormInstance>(); const intl = useIntl(); const [createModalVisible, setCreateModalVisible] = useState<boolean>(false); const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false); const [userAuthModalVisible, setUserAuthModalVisible] = useState<boolean>(false); const [currentRow, setCurrentRow] = useState<AppListItem>(); const [dataSource, setDataSource] = useState<AppListResult>(); const [appGroups, setAppGroups] = useState<{label:string, value:string}[]>([]); const [newAppGroupName, setNewAppGroupName] = useState<string>(''); const [appGroupsEnums, setAppGroupsEnums] = useState<{}>({}); const [tableGrouped, setTableGrouped] = useState<boolean>(false); useEffect(()=>{ getAppGroups().then(x=>{ if (x.success) { const groups:{label:string, value:string}[] = []; const groupEnums = {}; x.data.forEach((i: any)=>{ groups.push({ label:i, value: i }); groupEnums[i]={text:i}; }) setAppGroups(groups); setAppGroupsEnums(groupEnums); } }) },[dataSource]); const handleQuery = async (params: AppListParams) => { const result = await queryApps(params); setDataSource(result); return result; } const handleEnabledChange =async (checked:boolean, entity:AppListItem) => { const result = await enableOrdisableApp(entity.id); const qiyong = intl.formatMessage({ id: 'enabled.1' }); const jinyong = intl.formatMessage({ id: 'enabled.0' }); const success = intl.formatMessage({ id: 'success' }); const failed = intl.formatMessage({ id: 'failed' }); if (result.success) { const msg = (checked?qiyong:jinyong) + success; message.success(msg); if (dataSource) { const app = dataSource?.data?.find(x=>x.id === entity.id); if (app) { app.enabled = checked; } setDataSource({...dataSource}); } } else{ message.error((checked?qiyong:jinyong) + failed) } } const columns: ProColumns<AppListItem>[] = [ { title: intl.formatMessage({ id:'pages.app.table.cols.appname' }), dataIndex: 'name', sorter: true, }, { title: intl.formatMessage({ id:'pages.app.table.cols.appid' }), dataIndex: 'id', copyable: true, sorter: true, }, { title: intl.formatMessage({ id:'pages.app.table.cols.secret' }), dataIndex: 'secret', valueType: 'password', hideInSearch: true, copyable: true, }, { title: '应用组', sorter: true, valueType: 'select', dataIndex: 'group', valueEnum: appGroupsEnums // request:async ()=>{ // const groups = await getAppGroups(); // const arr:{label:string, value:string}[] = []; // groups.data.forEach( (x: string)=>{ // arr.push({ // value: x, // label: x, // }); // }); // return arr; // } }, { title: intl.formatMessage({ id:'pages.app.table.cols.create_time' }), dataIndex: 'createTime', valueType: 'dateTime', hideInSearch: true, sorter: true, }, { title: '管理员', dataIndex: 'appAdminName', hideInSearch: true, }, { title: intl.formatMessage({ id:'pages.app.table.cols.public' }), dataIndex: 'inheritanced', hideInSearch: true, valueEnum: { false: { text: intl.formatMessage({ id:'pages.app.inheritanced.false' }), status: 'default' }, true: { text: intl.formatMessage({ id:'pages.app.inheritanced.true' }), status: 'success' } } }, { title: intl.formatMessage({ id:'pages.app.table.cols.link' }), dataIndex: 'inheritancedApps', search: false, renderFormItem: (_, { defaultRender }) => { return defaultRender(_); }, render: (_, record) => ( <Space> {record.inheritancedAppNames?.map((name:string) => ( <Tag color="blue" key={name}> {name} </Tag> ))} </Space> ), }, { title: intl.formatMessage({ id:'pages.app.table.cols.enabled' }), dataIndex: 'enabled', render: (dom, entity) => { return <AuthorizedEle appId={entity.id} judgeKey={functionKeys.App_Edit} noMatch={ <Switch checked={entity.enabled} size="small" /> }> <Switch checked={entity.enabled} size="small" onChange={ (e)=>{ handleEnabledChange(e, entity); } }/> </AuthorizedEle> }, hideInSearch: true }, { title: intl.formatMessage({ id:'pages.app.table.cols.action' }), valueType: 'option', render: (text, record, _, action) => [ <Link key="0" to={ { pathname:'/app/config/' + record.id + '/' + record.name, } } >{intl.formatMessage({ id:'pages.app.table.cols.action.configs' })}</Link>, <AuthorizedEle key="1" appId={record.id} judgeKey={functionKeys.App_Edit}> <a onClick={() => { setUpdateModalVisible(true); setCurrentRow(record); }} > { intl.formatMessage({ id:'pages.app.table.cols.action.edit' }) } </a> </AuthorizedEle> , <a key="2" onClick={()=>{ setUserAuthModalVisible(true); setCurrentRow(record); }}> 授权 </a> , <AuthorizedEle key="3" appId={record.id} judgeKey={functionKeys.App_Delete}> <Button type="link" danger onClick={() => { const msg = intl.formatMessage({ id:'pages.app.delete_msg' }) + `【${record.name}】?`; confirm({ icon: <ExclamationCircleOutlined />, content: msg, async onOk() { console.log('delete app ' + record.name); const success = await handleDel(record); if (success) { actionRef.current?.reload(); } }, onCancel() { console.log('Cancel'); }, }); }} > { intl.formatMessage({ id:'pages.app.table.cols.action.delete' }) } </Button> </AuthorizedEle> ] } ]; return ( <PageContainer> <ProTable actionRef={actionRef} options={ false } search={{ labelWidth: 'auto', }} rowKey={row=>row.id} columns={columns} request={(params, sorter, filter) => { let sortField = 'createTime'; let ascOrDesc = 'descend'; for (const key in sorter) { sortField = key; const val = sorter[key]; if (val) { ascOrDesc = val; } } console.log(sortField, ascOrDesc); return handleQuery({ tableGrouped, sortField, ascOrDesc, ...params }) } } headerTitle = { <Checkbox onChange={(e)=>{ setTableGrouped(e.target.checked); actionRef.current?.reload(); }}>分组聚合</Checkbox> } toolBarRender={() => { return [ <AuthorizedEle key="0" judgeKey={functionKeys.App_Add} > <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => { setCreateModalVisible(true) }}> { intl.formatMessage({ id:'pages.app.table.cols.action.add' }) } </Button> </AuthorizedEle> ] }} //dataSource={dataSource} /> <ModalForm formRef={addFormRef} title={ intl.formatMessage({ id: 'pages.app.form.title.add' }) } visible={createModalVisible} onVisibleChange={setCreateModalVisible} onFinish={ async (value) => { const success = await handleAdd(value as AppListItem); if (success) { setCreateModalVisible(false); if (actionRef.current) { actionRef.current.reload(); } } addFormRef.current?.resetFields(); } } > <ProFormText rules={[ { required: true, }, ]} label={ intl.formatMessage({ id: 'pages.app.form.name' }) } name="name" /> <ProFormText rules={[ { required: true, }, ]} label={ intl.formatMessage({ id: 'pages.app.form.id' }) } name="id" /> <ProFormText.Password rules={[ { }, ]} label={ intl.formatMessage({ id: 'pages.app.form.secret' }) } name="secret" /> <ProFormSelect placeholder="应用所属的组" label="应用组" name="group" options={appGroups} fieldProps={{ dropdownRender: (menu) => ( <div> {menu} <Divider style={{ margin: '4px 0' }} /> <div style={{ display: 'flex', flexWrap: 'nowrap', padding: 8 }}> <Input placeholder="输入组名" style={{ flex: 'auto' }} value={newAppGroupName} onChange={(e)=>{ setNewAppGroupName(e.target.value) }} /> <a style={{ flex: 'none', padding: '8px', display: 'block', cursor: 'pointer' }} onClick={()=>{ if(newAppGroupName){ setAppGroups([...appGroups, { label: newAppGroupName, value: newAppGroupName }]); setNewAppGroupName(''); } }} > <PlusOutlined /> </a> </div> </div> ) }} ></ProFormSelect> <ProFormSwitch tooltip={ intl.formatMessage({ id: 'pages.app.form.public.tooltip' }) } label={ intl.formatMessage({ id: 'pages.app.form.public' }) } name="inheritanced" checkedChildren={true} unCheckedChildren={false}> </ProFormSwitch> <ProFormDependency name={ ["inheritanced"] }> { (e) => { return !e.inheritanced ? <ProFormSelect tooltip={ intl.formatMessage({ id: 'pages.app.form.connected.tooltip' }) } label={ intl.formatMessage({ id: 'pages.app.form.connected' }) } name="inheritancedApps" mode="multiple" request={async () => { const result = await inheritancedApps(''); return result.data.map( (x: { name: string, id: string })=> { console.log(x); return { label:x.name, value:x.id}; }); }} ></ProFormSelect> : null } } </ProFormDependency> <ProFormSelect rules={[ { required: true, }, ]} initialValue={getUserInfo().userid} label="管理员" name="appAdmin" request={async () => { const result = await adminUsers(); return result.data.map( (x: { userName: string, id: string, team:string })=> { console.log(x); return { label:x.userName + ' - ' + (x.team?x.team:''), value:x.id}; }); }} ></ProFormSelect> <ProFormSwitch label={ intl.formatMessage({ id: 'pages.app.form.enabled' }) } name="enabled" initialValue={true} checkedChildren={true} unCheckedChildren={false}> </ProFormSwitch> </ModalForm> { updateModalVisible && <UpdateForm value={currentRow} setValue={setCurrentRow} updateModalVisible={updateModalVisible} onCancel={ () => { setCurrentRow(undefined); setUpdateModalVisible(false); console.log('set currentrow undefined'); } } onSubmit={ async (value) => { setCurrentRow(undefined); const success = await handleEdit(value); if (success) { setUpdateModalVisible(false); if (actionRef.current) { actionRef.current.reload(); } } addFormRef.current?.resetFields(); } }/> } { userAuthModalVisible && <UserAuth value = {currentRow} userAuthModalVisible={userAuthModalVisible} onCancel={ () => { setUserAuthModalVisible(false); } } onSubmit={ async (value) => { const success = await handleUserAppAuth(value); if (success) { setUserAuthModalVisible(false); } } } > </UserAuth> } </PageContainer> ); } export default appList;
the_stack
import * as jsonx from './index'; import * as _jsonxProps from './props'; import { getComputedProps, } from './props'; import mochaJSDOM from 'jsdom-global'; import chai from 'chai'; import sinon from 'sinon'; import React from 'react'; import ReactDOM from 'react-dom'; import ReactDOMElements from 'react-dom-factories'; import { expect as EXPECTChai, } from 'chai'; import { JSDOM, } from 'jsdom'; chai.use(require('sinon-chai')); // import 'mocha-sinon'; const sampleJSONX = { component: 'div', props: { id: 'generatedJSONX', className:'jsonx', }, children: [ { component: 'p', props: { style: { color: 'red', fontWeight:'bold', }, }, children:'hello world', }, ], }; const traverseObject = { user: { name: 'jsonx', description: 'react withouth javascript', }, stats: { logins: 102, comments: 3, }, authentication: 'OAuth2', }; describe('jsonx props', function () { describe('getComputedProps', () => { it('should return resolved computed props', () => { const dynamicprops = { auth: ['authentication', ], username: ['user', 'name', ], }; const evalProps = { getUsername: '()=>\'jsonx\'', }; const bindEvalProps = { getUsernameFunction: '(function () { return "jsonx"; })', }; const compProps = { myComponent: { component: 'p', children:'hello world', }, }; const renderIndex = 1; const resources = traverseObject; const testJSONX = Object.assign({}, sampleJSONX, { asyncprops: dynamicprops, __dangerouslyEvalProps: evalProps, __dangerouslyBindEvalProps: bindEvalProps, __dangerouslyInsertComponents: compProps, }); const computedProps = getComputedProps.call({}, { disableRenderIndexKey:false, jsonx: testJSONX, resources, renderIndex, }); EXPECTChai(computedProps.auth).to.eql(resources.authentication); EXPECTChai(computedProps.username).to.eql(resources.user.name); EXPECTChai(computedProps.key).to.eql(renderIndex); EXPECTChai(computedProps.getUsername).to.be.a('string'); EXPECTChai(computedProps.getUsernameFunction).to.be.a('function'); EXPECTChai(computedProps.myComponent).to.be.an('object'); EXPECTChai(computedProps.myComponent).to.haveOwnProperty('$$typeof'); EXPECTChai(computedProps.myComponent).to.haveOwnProperty('type'); EXPECTChai(computedProps.myComponent).to.haveOwnProperty('key'); EXPECTChai(computedProps.myComponent).to.haveOwnProperty('ref'); EXPECTChai(computedProps.myComponent).to.haveOwnProperty('props'); }); it('should remove props with "useremoveprops"',()=>{ const jsonx = { component: "input", props:{ name:'firstName', pleaseRemove1:'ok', pleaseRemove2:'ok', }, } const remove2 = { ...jsonx, useremoveprops: ['pleaseRemove1', 'pleaseRemove2'], } const remove0 = { ...jsonx, useremoveprops: [], } const computedProps = getComputedProps.call({}, { disableRenderIndexKey:false, jsonx:remove2, renderIndex:1, }); const computedProps0 = getComputedProps.call({}, { disableRenderIndexKey:false, jsonx:remove0, renderIndex:1, }); EXPECTChai(computedProps).to.eql({ key: 1, name: 'firstName' }); EXPECTChai(computedProps0).to.eql({ key: 1, name: 'firstName', pleaseRemove1: 'ok', pleaseRemove2: 'ok' }); }) it('should only include props with "useincludeprops"',()=>{ const jsonx = { component: "input", props:{ name:'firstName', pleaseRemove1:'ok', pleaseRemove2:'keep2', }, } const remove1 = { ...jsonx, useincludeprops: ['pleaseRemove1', 'name'], } const removeAll = { ...jsonx, useincludeprops: [], } const computedProps = getComputedProps.call({}, { disableRenderIndexKey:false, jsonx:remove1, renderIndex:1, }); const computedProps0 = getComputedProps.call({}, { disableRenderIndexKey:false, jsonx:removeAll, renderIndex:1, }); EXPECTChai(computedProps).to.eql({ pleaseRemove1: 'ok',key:1, name: 'firstName' }); EXPECTChai(computedProps0).to.eql({ key:1, }); }) it('should apply a form hook register with "useformregister"',()=>{ const context = { reactHookForm:{ register:()=>({ref:'FORM REGISTER'}) } } const jsonx = { component: "input", props:{ name:'firstName', }, useformregister: true, } const computedProps = getComputedProps.call(context, { disableRenderIndexKey:false, jsonx, renderIndex:1, }); // console.log({computedProps}) //@ts-ignore expect(computedProps.ref).toBe(context.reactHookForm.register().ref); //@ts-ignore expect(_jsonxProps.useFormRegisterHandler.call(context,{jsonx})).toMatchObject(context.reactHookForm.register()); }); it('should handle getComputedProps errors',()=>{ const mockCallback = jest.fn(()=>{}); //@ts-ignore const props = getComputedProps.call({props:{getState:()=>{throw new Error('testing error')}}},{ debug:true, jsonx:{ component:'div', ignoreReduxProps:false, thisprops:{ } }, resources:new Error('testing error handling'), logError:mockCallback }) expect(mockCallback.mock.calls.length).toBe(1); expect(props).toBe(null) }) }); describe('getJSONXProps', () => { const getJSONXProps = _jsonxProps.getJSONXProps; it('should return with no input',()=>{ expect(getJSONXProps()).toMatchObject({}) expect(getJSONXProps({})).toMatchObject({}) }) it('should return context props', () => { const functionContext = { name: 'custom context', content:'this should be the children content', returnJSON: true, }; const testVals = { contextName: ['name'], _children: ['content'] }; const contextJSONX = { component: 'div', props: { title: 'context jsonx', }, thiscontext:testVals, }; const JSONXCP = getJSONXProps({ jsonx: contextJSONX, traverseObject: functionContext, propName: 'thiscontext', }); const JSONXJSONX = jsonx.getReactElementFromJSONX.call(functionContext, contextJSONX); EXPECTChai(JSONXCP).to.haveOwnProperty('contextName'); EXPECTChai(JSONXCP).to.haveOwnProperty('_children'); EXPECTChai(JSONXCP.contextName).to.eql(functionContext.name); EXPECTChai(JSONXCP._children).to.eql(functionContext.content); //@ts-ignore EXPECTChai(JSONXJSONX.children).to.eql(functionContext.content); // const JSONXCP = getJSONXProps.call(functionContext, contextJSONX, { thiscontext: testVals, }); // console.log({ JSONXCP,JSONXJSONX }); }); it('should return resolved dynamic prop', () => { const testVals = { auth: ['authentication', ], username: ['user', 'name', ], }; const testJSONX = Object.assign({}, sampleJSONX, { asyncprops: testVals, }); const testJSONX2 = Object.assign({}, sampleJSONX, { thisprops: testVals, }); const JSONXP = getJSONXProps({ jsonx: testJSONX, traverseObject, }); const JSONXP2 = getJSONXProps({ jsonx: testJSONX2, traverseObject, propName:'thisprops', }); EXPECTChai(JSONXP.auth).to.eql(traverseObject.authentication); EXPECTChai(JSONXP.username).to.eql(traverseObject.user.name); EXPECTChai(JSONXP2.auth).to.eql(traverseObject.authentication); EXPECTChai(JSONXP2.username).to.eql(traverseObject.user.name); }); it('should return resolved dynamic prop with undefined values if reference is invalid', () => { const testVals = { auth: ['wrong', ], username: ['no', 'ref', ], }; const testJSONX = Object.assign({}, sampleJSONX, { asyncprops: testVals, }); const JSONXP = getJSONXProps({ jsonx: testJSONX, traverseObject, }); EXPECTChai(JSONXP.auth).to.be.undefined; EXPECTChai(JSONXP.username).to.be.undefined; }); }); describe('getChildrenComponents', () => { const getChildrenComponents = _jsonxProps.getChildrenComponents; it('should return undefined children if missing __spread prop', () => { //@ts-ignore EXPECTChai(getChildrenComponents().children).to.be.undefined; }); it('should return error in children if missing __spread prop and if in debug mode', () => { //@ts-ignore EXPECTChai(getChildrenComponents({ jsonx:{ debug:true ,}, }).children).to.be.a('string'); EXPECTChai(getChildrenComponents.call({ debug:true ,}).children).to.be.a('string'); }); it('should spread data as a component on __spread prop', () => { const options = { allProps: { __spread: [ 1, 2, 3, 4, 5, ], }, jsonx: { __spreadComponent: { component: 'div', }, }, }; //@ts-ignore const spreadChilds = getChildrenComponents(options); EXPECTChai(spreadChilds).to.haveOwnProperty('_children'); EXPECTChai(spreadChilds._children).to.have.lengthOf(options.allProps.__spread.length); // EXPECTChai(getChildrenComponents({ jsonx:{ debug:true ,}, }).children).to.be.a('string'); }); }); describe('boundArgsReducer', () => { const {boundArgsReducer} =_jsonxProps it('should return reducer function', () => { //@ts-ignore EXPECTChai(_jsonxProps.boundArgsReducer.bind()).to.be.a('function'); }); it('should return the stateful properties',()=>{ const thisObject = { state:{ cool:'beans', wow:'factor', not:undefined } } const reducer = boundArgsReducer.call(thisObject) const statefulVal = reducer(['cool'],'cool') const statefulVal2 = reducer(['cool'],'cool2') const statefulVal3 = reducer([],'cool2') const statefulVal4 = reducer([],'cool') const statefulVal5 = reducer([undefined],'cool2') const statefulVal6 = reducer([undefined],'not') expect(statefulVal).toMatchObject([ 'cool', 'beans' ]) expect(statefulVal2).toMatchObject([ 'cool' ]) expect(statefulVal3).toMatchObject([]) expect(statefulVal4).toMatchObject([ 'beans' ]) expect(statefulVal5).toMatchObject([]) expect(statefulVal6).toMatchObject([]) }); it('should return the props properties',()=>{ const thisObject = { props:{ cool:'beans', wow:'factor', not:undefined } } const reducer = boundArgsReducer.call(thisObject) const propsVal = reducer(['cool'],'cool') const propsVal2 = reducer(['cool'],'cool2') const propsVal3 = reducer([],'cool2') const propsVal4 = reducer([],'cool') const propsVal5 = reducer([undefined],'cool2') const propsVal6 = reducer([undefined],'not') expect(propsVal).toMatchObject([ 'cool', 'beans' ]) expect(propsVal2).toMatchObject([ 'cool' ]) expect(propsVal3).toMatchObject([]) expect(propsVal4).toMatchObject([ 'beans' ]) expect(propsVal5).toMatchObject([]) expect(propsVal6).toMatchObject([]) }); it('should return the jsonx properties',()=>{ const jsonx={ props:{ cool:'beans', wow:'factor', not:undefined } } const reducer = boundArgsReducer.call({},jsonx) const jsonxVal = reducer(['cool'],'cool') const jsonxVal2 = reducer(['cool'],'cool2') const jsonxVal3 = reducer([],'cool2') const jsonxVal4 = reducer([],'cool') const jsonxVal5 = reducer([undefined],'cool2') const jsonxVal6 = reducer([undefined],'not') //@ts-ignore const jsonxVal7 = reducer([undefined],undefined) expect(jsonxVal).toMatchObject([ 'cool', 'beans' ]) expect(jsonxVal2).toMatchObject([ 'cool' ]) expect(jsonxVal3).toMatchObject([]) expect(jsonxVal4).toMatchObject([ 'beans' ]) expect(jsonxVal5).toMatchObject([]) expect(jsonxVal6).toMatchObject([]) expect(jsonxVal7).toMatchObject([]) }); }); describe('getEvalProps', () => { const getEvalProps = _jsonxProps.getEvalProps; it('should return evaluated props dangerously using eval', () => { const testVals = { auth: 'true', username: '()=>(user={})=>user.name', }; const testJSONX = Object.assign({}, sampleJSONX, { __dangerouslyEvalProps: testVals, __dangerouslyBindEvalProps: { email: '(function getUser(user={}){ return this.testBound(); })', }, }); // console.log({ testJSONX }); //@ts-ignore const JSONXP = getEvalProps.call({ testBound: () => 'bounded', }, { jsonx: testJSONX, }); //@ts-ignore const evalutedComputedFunc = JSONXP.username({ name: 'bob', }); //@ts-ignore const evalutedComputedBoundFunc = JSONXP.email({ email:'test@email.domain', }); //@ts-ignore EXPECTChai(JSONXP.auth).to.be.true; EXPECTChai(evalutedComputedFunc).to.eql('bob'); EXPECTChai(evalutedComputedBoundFunc).to.eql('bounded'); }); it('should return all evaluated props using __dangerouslyEvalAllProps',()=>{ const jsonx = { component:"div", __dangerouslyEvalAllProps: function(){ return {title:'div title', foo:'bar'} }, children:'Hello World' } const evaledProps = getEvalProps.call({},{jsonx}) expect(evaledProps).toMatchObject( { title: 'div title', foo: 'bar' }) }) it('should throw errors using __dangerouslyEvalAllProps',()=>{ const jsonx = { component:"div", __dangerouslyEvalAllProps: 'INVALID', children:'Hello World' } const evaledProps = getEvalProps.call({ debug: true },{jsonx}) const evaledPropsNoDebug = getEvalProps.call({},{jsonx}) //@ts-ignore expect(evaledProps.error).toBeInstanceOf(Error) expect(evaledPropsNoDebug).toMatchObject({}) // expect(evaledProps).toMatchObject( { title: 'div title', foo: 'bar' }) }); it('should handle errors with __dangerouslyEvalProps',()=>{ const jsonx = { component:"div", __dangerouslyEvalProps:{ title:'INVALID', }, children:'Hello World' } const evaledProps = getEvalProps.call({ debug: true },{jsonx}) const evaledPropsNoDebug = getEvalProps.call({},{jsonx}) //@ts-ignore expect(evaledProps.title).toBeInstanceOf(Error) //@ts-ignore expect(evaledPropsNoDebug.title).toBe(undefined) const evaledPropsExposed = getEvalProps.call({ exposeEval: true },{ jsonx:{ component:"div", __dangerouslyEvalProps:{ title:function(jsonx){return true}, }, }, //@ts-ignore children:'Hello World' }) //@ts-ignore expect(evaledPropsExposed.__eval_title).toBe('function (jsonx) { return true; }') // console.log({evaledPropsExposed}) }) it('should handle __dangerouslyBindEvalProps',()=>{ const jsonx = { component:"div", __dangerouslyBindEvalProps:{ title:function(a:string){ return 'text for title: '+a }, }, __functionargs:{ title: ['customTitle'] }, children:'Hello World' } //@ts-ignore const evaledProps = getEvalProps.call({ debug: true, state:{ customTitle:'inserted funcArg'} },{jsonx}) //@ts-ignore const calcTitle = evaledProps.title() expect(calcTitle).toBe('text for title: inserted funcArg') }) it('should handle errors from __dangerouslyBindEvalProps',()=>{ const jsonx = { component:"div", __dangerouslyBindEvalProps:{ title:'INVALID', }, children:'Hello World' } //@ts-ignore const evaledProps = getEvalProps.call({ debug: true, },{jsonx}) //@ts-ignore expect(evaledProps.title).toBeInstanceOf(Error) }) }); describe('getWindowComponents', () => { const getWindowComponents = _jsonxProps.getWindowComponents; // beforeAll(function () { // // this.jsdom = mochaJSDOM(); // // console.log('this.jsdom', this.jsdom,{mochaJSDOM}); // console.log({window}); // }); it('should return react element from jsonx.__windowComponents', function () { class Welcome extends React.Component { render() { //@ts-ignore return React.createElement('h1', { name: 'Welcome', }, `Hello, ${this.props.name} ${this.props.title||'NA'}`); } } const __windowComponents = { myWelcome: 'Welcome', }; const allProps = { __windowComponents, __windowComponentProps: { name: 'from window', title: 'pull it', }, }; const testJSONX = { component: 'div', children: 'hello world', __windowComponents: { useWelcome:'func:window.__jsonx_custom_elements.Welcome', }, }; const thisProp = { window: { __jsonx_custom_elements: { Welcome, }, }, }; const windowProps = getWindowComponents.call(thisProp, { allProps, jsonx: testJSONX, }); EXPECTChai(windowProps.useWelcome.type).to.eql(Welcome); EXPECTChai(windowProps.useWelcome.props.name).to.eql(allProps.__windowComponentProps.name); }); // afterAll(function () { // // this.jsdom(); // }); }); describe('getFunctionProps', () => { const getFunctionProps = _jsonxProps.getFunctionProps; it('should resolve functions from jsonx.__functionProps from function strings', () => { const logError = sinon.spy(); const thisProp = { logError, debug: true, window: { print: () => 'printed', localStorage: { getItem:()=>'gotItem', }, }, props: { onClick:()=>'clicked', reduxRouter: { push:()=>'pushed', pop:()=>'poped', }, }, }; const jsonxTest = { component:'div', props: { name:'test', }, __functionProps: { onclick:'func:this.props.onClick', printPage: 'func:window.print', nav:'func:this.props.reduxRouter.push', }, }; const jsonxObj = getFunctionProps.call(thisProp, { jsonx: jsonxTest, }); EXPECTChai(jsonxObj).is.an('object'); EXPECTChai(Object.keys(jsonxObj)).to.eql(Object.keys(jsonxTest.__functionProps)); EXPECTChai(jsonxObj.onclick()).to.eq('clicked'); EXPECTChai(jsonxObj.printPage()).to.eql('printed'); EXPECTChai(jsonxObj.nav()).to.eql('pushed'); }); }); describe('getFunctionFromProps', () => { const getFunctionFromProps = _jsonxProps.getFunctionFromProps; const getFunctionProps = _jsonxProps.getFunctionProps; it('should return an empty function by default', () => { const logError = sinon.spy(); const thisProp = { logError, debug:true, }; //@ts-ignore const func = getFunctionFromProps.call(thisProp, { //@ts-ignore propFunc: () => { }, }); //@ts-ignore const defaultFunc = getFunctionFromProps.call(thisProp, {}); // const emptyFunction = function () {}; EXPECTChai(func).to.be.a('function'); EXPECTChai(defaultFunc).to.be.a('function'); // EXPECTChai(func.toString()).to.eq(emptyFunction.toString()); // EXPECTChai(defaultFunc.toString()).to.eq(emptyFunction.toString()); EXPECTChai(logError.called).to.be.true; }); it('should return a library function like this.props.reduxRouter.push', () => { const logError = sinon.spy(); const thisProp = { logError, debug: true, props: { reduxRouter: { push:()=>'pushed', pop:()=>'poped', }, }, }; //@ts-ignore const func = getFunctionFromProps.call(thisProp, { propFunc: 'func:this.props.reduxRouter.push', }); EXPECTChai(func).to.be.a('function'); EXPECTChai(func()).to.eq('pushed'); EXPECTChai(logError.called).to.be.false; }); it('should return a function on this.props like this.props.onClick', () => { const logError = sinon.spy(); const thisProp = { logError, debug: true, props: { onClick:()=>'clicked', }, }; //@ts-ignore const func = getFunctionFromProps.call(thisProp, { propFunc: 'func:this.props.onClick', }); EXPECTChai(func).to.be.a('function'); EXPECTChai(func()).to.eq('clicked'); EXPECTChai(logError.called).to.be.false; }); it('should return a window function like window.print or window.localStorage.getItem', () => { const logError = sinon.spy(); const thisProp = { logError, debug: true, window: { print: () => 'printed', localStorage: { getItem:()=>'gotItem', }, }, }; //@ts-ignore const func = getFunctionFromProps.call(thisProp, { //@ts-ignore propFunc: 'func:window.print', }); //@ts-ignore const funcDeep = getFunctionFromProps.call(thisProp, { propFunc: 'func:window.localStorage.getItem', }); EXPECTChai(func).to.be.a('function'); EXPECTChai(funcDeep).to.be.a('function'); EXPECTChai(func()).to.eq('printed'); EXPECTChai(funcDeep()).to.eq('gotItem'); EXPECTChai(logError.called).to.be.false; }); it('should generate inline functions',()=>{ const jsonx = { component: "button", props: { name: "test" }, __functionargs: { onClick: ["name"] }, __inline: { onClick: ` return ("the name of this component from the prop is:" +arguments[0])` }, __functionProps: { onClick: "func:inline.onClick" } }; const inlineFunction = getFunctionFromProps.call({},{ propFunc:'func:inline.onClick', propBody: ` return ("the name of this component from the prop is:" +arguments[0])`, functionProperty:'onClick', jsonx, }) const inlineOutput = inlineFunction() const fromFunctionProps = getFunctionProps.call({},{ allProps:{}, jsonx, }) expect(typeof inlineFunction).toBe('function') expect(inlineOutput).toBe('the name of this component from the prop is:test') expect(inlineFunction()).toMatch(fromFunctionProps.onClick()) }) }); describe('getComponentProps', () => { const getComponentProps = _jsonxProps.getComponentProps; it('should return evaluated props dangerously using eval', () => { const testVals = { myComponent: { component: 'p', children:'hello world', }, }; const testJSONX = Object.assign({}, sampleJSONX, { __dangerouslyInsertComponents: testVals, }); const JSONXP = getComponentProps.call({ }, { jsonx: testJSONX, }); EXPECTChai(JSONXP.myComponent).to.be.an('object'); EXPECTChai(JSONXP.myComponent).to.haveOwnProperty('$$typeof'); EXPECTChai(JSONXP.myComponent).to.haveOwnProperty('type'); EXPECTChai(JSONXP.myComponent).to.haveOwnProperty('key'); EXPECTChai(JSONXP.myComponent).to.haveOwnProperty('ref'); EXPECTChai(JSONXP.myComponent).to.haveOwnProperty('props'); }); it('should handle errors',()=>{ const erroredComponent = getComponentProps.call({debug:true, logError:()=>{}},{ jsonx:{ component:'div', __dangerouslyInsertComponents:{ children:{ component:'invalid', props:false } } } }) //@ts-ignore expect(erroredComponent.children).toMatch("ReferenceError: Invalid React Component (invalid)") // console.log({erroredComponent}) }) }); describe('getReactComponents',()=>{ const getReactComponents = _jsonxProps.getReactComponents; it('should create a function component from a function',()=>{ const jsonxWithFunc = getReactComponents.call({},{ jsonx:{ component:'div', __dangerouslyInsertFunctionComponents:{ tick:{ function:function(){ console.log('clicked!') return { component:'span', children:'from func' } }, options:{ name:'spanFunc' } } }, children:'click me' } }); expect(jsonxWithFunc.tick.name).toBe('spanFunc'); }); it('should invoke a function component from a function',()=>{ const jsonxWithFunc = getReactComponents.call({},{ jsonx:{ component:'div', __dangerouslyInsertFunctionComponents:{ children:{ function:function(){ // console.log('clicked!') return { component:'p', children:'from func' } }, options:{ name:'spanFunc' }, invoke:true, } }, children:'click me' } }); // console.log('typeof jsonxWithFunc.children',typeof jsonxWithFunc.children) // console.log('jsonxWithFunc.children',jsonxWithFunc.children) expect(jsonxWithFunc.children.type).toBe('p'); }); it('should create a function component from createFunctionComponent args',()=>{ const jsonxWithFunc = getReactComponents.call({},{ jsonx:{ component:'div', __dangerouslyInsertFunctionComponents:{ tick:{ functionBody:'console.log("clicked!")', reactComponent:{ component:'span', children:'from func', }, options:{ name:'spanFunc' } } }, children:'click me' } }); expect(jsonxWithFunc.tick.name).toBe('spanFunc'); }); it('should handle errors create a function component from createFunctionComponent args',()=>{ const jsonxWithFunc = getReactComponents.call({debug:true},{ jsonx:{ component:'div', __dangerouslyInsertFunctionComponents:{ tick:{ functionBody:'INVALID', reactComponent:{ component:'INVALID COMPONENT', }, options:{ name:'000INVALID' } } }, children:'click me' } }); expect(jsonxWithFunc.tick).toBeInstanceOf(Error); // console.log('jsonxWithFunc',jsonxWithFunc) }); it('should handle errors create a class component from classComponents args',()=>{ const jsonxWithFunc = getReactComponents.call({debug:true},{ jsonx:{ component:'div', __dangerouslyInsertClassComponents:{ tick:{ reactComponent:{ component:'INVALID COMPONENT', }, options:{ name:'000INVALID' } } }, children:'click me' } }); expect(jsonxWithFunc.tick).toBeInstanceOf(Error); }); it('should create a class component from classComponents args',()=>{ const jsonxWithFunc = getReactComponents.call({debug:true},{ jsonx:{ component:'div', __dangerouslyInsertClassComponents:{ tick:{ reactComponent:{ render:{ body:{ component:'span', children:'Class Component' }, }, }, options:{ name:'spanClass' } } }, children:'click me' } }); expect(typeof jsonxWithFunc.tick).toBe('function'); }); }); describe('getReactComponentProps', () => { const getReactComponentProps = _jsonxProps.getReactComponentProps; it('should return react component props dangerously using eval', () => { const testVals = { myComponent: 'p', }; const testJSONX = Object.assign({}, sampleJSONX, { __dangerouslyInsertReactComponents: testVals, }); const JSONXP = getReactComponentProps.call({}, { jsonx: testJSONX, }); //@ts-ignore EXPECTChai(JSONXP.myComponent).to.be.an('string'); //@ts-ignore EXPECTChai(JSONXP.myComponent).to.eql('p'); }); }); });
the_stack
import { types } from "mobx-state-tree"; import { Decimal } from "decimal.js-light"; import { ConversionError, ConversionValue, Field, Form, converters, StateConverterOptionsWithContext, FieldAccessor, } from "../src"; import { ConverterOrFactory, makeConverter } from "../src/converter"; const baseOptions = { // a BIG lie. but we don't really have an accessor in these // tests and it's safe to leave it null, even though in // the integrated code accessor always *does* exist accessor: null as unknown as FieldAccessor<any, any>, }; function check( converter: ConverterOrFactory<any, any>, value: any, expected: any ) { converter = makeConverter(converter); const processedValue = converter.preprocessRaw(value, baseOptions); const r = converter.convert(processedValue, baseOptions); expect(r).toBeInstanceOf(ConversionValue); expect((r as ConversionValue<any>).value).toEqual(expected); } function checkDecimal( converter: ConverterOrFactory<any, any>, value: string, expected: Decimal ) { converter = makeConverter(converter); const processedValue = converter.preprocessRaw(value, baseOptions); const r = converter.convert(processedValue, baseOptions); expect(r).toBeInstanceOf(ConversionValue); expect((r as ConversionValue<Decimal>).value.equals(expected)); } function checkWithOptions( converter: ConverterOrFactory<any, any>, value: any, expected: any, options: StateConverterOptionsWithContext ) { converter = makeConverter(converter); const processedValue = converter.preprocessRaw(value, options); const r = converter.convert(processedValue, options); expect(r).toBeInstanceOf(ConversionValue); expect((r as ConversionValue<any>).value).toEqual(expected); } function checkDecimalWithOptions( converter: ConverterOrFactory<any, any>, value: string, expected: Decimal, options: StateConverterOptionsWithContext ) { converter = makeConverter(converter); const processedValue = converter.preprocessRaw(value, options); const r = converter.convert(processedValue, options); expect(r).toBeInstanceOf(ConversionValue); expect((r as ConversionValue<Decimal>).value.equals(expected)); } function fails(converter: ConverterOrFactory<any, any>, value: any) { converter = makeConverter(converter); const r = converter.convert(value, baseOptions); expect(r).toBeInstanceOf(ConversionError); } function failsWithOptions( converter: ConverterOrFactory<any, any>, value: any, options: StateConverterOptionsWithContext ) { converter = makeConverter(converter); const processedValue = converter.preprocessRaw(value, options); const r = converter.convert(processedValue, options); expect(r).toBeInstanceOf(ConversionError); } test("string converter", () => { check(converters.string, "foo", "foo"); check(converters.string, "", ""); }); test("string converter with options", () => { check(converters.string({ maxLength: 32 }), "foo", "foo"); fails(converters.string({ maxLength: 2 }), "foo"); }); test("number converter", () => { check(converters.number, "3", 3); check(converters.number, "3.14", 3.14); check(converters.number, ".14", 0.14); check(converters.number, "19.14", 19.14); check(converters.number, "19.", 19); check(converters.number, "-3.14", -3.14); checkWithOptions(converters.number, "1234,56", 1234.56, { decimalSeparator: ",", ...baseOptions, }); checkWithOptions(converters.number, "4.000,000000", 4000, { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); fails(converters.number, "foo"); fails(converters.number, "1foo"); fails(converters.number, ""); failsWithOptions(converters.number, "1,23.45", { decimalSeparator: ".", thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.number, ",12345", { thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.number, "1234,567", { thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.number, "12.3,456", { decimalSeparator: ".", thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.number, "1.1,1", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); failsWithOptions(converters.number, "1,1.1", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); }); test("number converter with both options", () => { checkWithOptions(converters.number, "4.314.314,31", 4314314.31, { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); }); test("integer converter", () => { check(converters.integer, "3", 3); fails(converters.integer, "3.14"); fails(converters.integer, ".14"); check(converters.integer, "0", 0); check(converters.integer, "-3", -3); fails(converters.integer, "foo"); fails(converters.integer, "1foo"); fails(converters.integer, ""); }); test("decimal converter", () => { check(converters.stringDecimal, "3", "3"); check(converters.stringDecimal, "3.14", "3.14"); check(converters.stringDecimal, "43.14", "43.14"); check(converters.stringDecimal, "4313", "4313"); check(converters.stringDecimal, "-3.14", "-3.14"); check(converters.stringDecimal, "0", "0"); check(converters.stringDecimal, ".14", ".14"); check(converters.stringDecimal, "14.", "14."); checkWithOptions(converters.stringDecimal, "43,14", "43.14", { decimalSeparator: ",", ...baseOptions, }); checkWithOptions( converters.stringDecimal({ decimalPlaces: 6 }), "4.000,000000", "4000.000000", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, } ); checkWithOptions( converters.stringDecimal({ decimalPlaces: 2 }), "36.365,21", "36365.21", { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, ...baseOptions, } ); fails(converters.stringDecimal, "foo"); fails(converters.stringDecimal, "1foo"); fails(converters.stringDecimal, ""); fails(converters.stringDecimal, "."); fails(converters.stringDecimal({ maxWholeDigits: 4 }), "12345.34"); fails(converters.stringDecimal({ decimalPlaces: 2 }), "12.444"); fails(converters.stringDecimal({ allowNegative: false }), "-45.34"); failsWithOptions(converters.stringDecimal, "1,23.45", { decimalSeparator: ".", thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.stringDecimal, ",12345", { thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.stringDecimal, "1234,567", { thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.stringDecimal, "12.3,456", { decimalSeparator: ".", thousandSeparator: ",", ...baseOptions, }); failsWithOptions(converters.stringDecimal, "1.1,1", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); failsWithOptions(converters.stringDecimal, "1,1.1", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); failsWithOptions(converters.stringDecimal, "1234.56", { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, ...baseOptions, }); }); test("decimal converter for decimal type", () => { checkDecimal(converters.decimal, "3", new Decimal("3")); checkDecimal(converters.decimal, "3.14", new Decimal("3.14")); checkDecimal(converters.decimal, "-3.14", new Decimal("-3.14")); checkDecimalWithOptions(converters.decimal, "43,14", new Decimal("43.14"), { decimalSeparator: ",", ...baseOptions, }); fails(converters.decimal, "foo"); fails(converters.decimal, "1foo"); fails(converters.decimal, ""); fails(converters.decimal, "."); }); test("decimal converter with normalizedDecimalPlaces", () => { const options = { normalizedDecimalPlaces: 4 }; check(converters.stringDecimal(options), "3", "3.0000"); check(converters.stringDecimal(options), "3.14", "3.1400"); check(converters.stringDecimal(options), "43.14", "43.1400"); check(converters.stringDecimal(options), "4313", "4313.0000"); check(converters.stringDecimal(options), "-3.14", "-3.1400"); check(converters.stringDecimal(options), "0", "0.0000"); check(converters.stringDecimal(options), ".14", ".1400"); check(converters.stringDecimal(options), "14.", "14.0000"); checkWithOptions(converters.stringDecimal(options), "43,14", "43.1400", { decimalSeparator: ",", ...baseOptions, }); checkWithOptions( converters.stringDecimal({ decimalPlaces: 6, normalizedDecimalPlaces: 7 }), "4.000,000000", "4000.0000000", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, } ); checkWithOptions( converters.stringDecimal({ decimalPlaces: 2, normalizedDecimalPlaces: 4 }), "36.365,21", "36365.2100", { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, ...baseOptions, } ); }); test("decimal converter with both options", () => { checkWithOptions(converters.stringDecimal, "4.314.314,31", "4314314.31", { decimalSeparator: ",", thousandSeparator: ".", ...baseOptions, }); }); test("decimal converter render with renderThousands false", () => { const converter = converters.stringDecimal({}); const options = { decimalSeparator: ",", thousandSeparator: ".", renderThousands: false, ...baseOptions, }; const value = "4.314.314,31"; const processedValue = converter.preprocessRaw(value, options); const converted = converter.convert(processedValue, options); const rendered = converter.render( (converted as ConversionValue<any>).value, options ); expect(rendered).toEqual("4314314,31"); }); test("decimal converter render with six decimals", () => { const converter = converters.stringDecimal({ decimalPlaces: 6 }); const options = { decimalSeparator: ".", thousandSeparator: ",", renderThousands: true, ...baseOptions, }; const value = "4.000000"; const processedValue = converter.preprocessRaw(value, options); const converted = converter.convert(processedValue, options); const rendered = converter.render( (converted as ConversionValue<any>).value, options ); expect(rendered).toEqual("4.000000"); }); test("decimal converter render with six decimals and thousand separators", () => { const converter = converters.stringDecimal({ decimalPlaces: 6 }); const options = { decimalSeparator: ".", thousandSeparator: ",", renderThousands: true, ...baseOptions, }; const value = "4000000.000000"; const processedValue = converter.preprocessRaw(value, options); const converted = converter.convert(processedValue, options); const rendered = converter.render( (converted as ConversionValue<any>).value, options ); expect(rendered).toEqual("4,000,000.000000"); }); test("decimal converter render with six decimals, only showing three", () => { const converter = converters.stringDecimal({ decimalPlaces: 3 }); const options = { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, ...baseOptions, }; const value = "4000.000000"; const rendered = converter.render(value, options); expect(rendered).toEqual("4.000,000"); }); test("decimal converter with thousandSeparator . and no decimalSeparator can't convert", () => { let message = false; const converter = converters.stringDecimal(); const options = { thousandSeparator: ".", renderThousands: true, ...baseOptions, }; const value = "4.000"; const processedValue = converter.preprocessRaw(value, options); try { converter.convert(processedValue, options); } catch (e) { message = e.message; } expect(message).toBeTruthy(); }); test("do not convert a normal string with decimal options", () => { checkWithOptions(converters.string, "43,14", "43,14", { decimalSeparator: ",", ...baseOptions, }); }); test("boolean converter", () => { check(converters.boolean, false, false); check(converters.boolean, true, true); }); test("maybe number converter", () => { check(converters.maybe(converters.number), "3", 3); check(converters.maybe(converters.number), "", undefined); }); test("maybeNull number converter", () => { check(converters.maybeNull(converters.number), "3", 3); check(converters.maybeNull(converters.number), "", null); }); test("maybe decimal converter", () => { check(converters.maybe(converters.stringDecimal()), "3.14", "3.14"); check(converters.maybe(converters.stringDecimal()), "", undefined); const c = converters.maybe(converters.stringDecimal()); expect(c.render(undefined, baseOptions)).toEqual(""); }); test("maybeNull decimal converter", () => { check(converters.maybeNull(converters.stringDecimal()), "3.14", "3.14"); check(converters.maybeNull(converters.stringDecimal()), "", null); const c = converters.maybeNull(converters.stringDecimal()); expect(c.render(null, baseOptions)).toEqual(""); }); test("maybe string converter", () => { check(converters.maybe(converters.string), "foo", "foo"); check(converters.maybe(converters.string), "", undefined); }); test("maybeNull string converter", () => { check(converters.maybeNull(converters.string), "foo", "foo"); check(converters.maybeNull(converters.string), "", null); }); test("model converter", () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO", }); const converter = converters.model(M); const r = converter.convert({ foo: "value" }, baseOptions); expect(r).toEqual({ value: { foo: "value" } }); const r2 = converter.convert(o, baseOptions); expect(r2).toEqual({ value: o }); }); test("maybe model converter", () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO", }); const converter = converters.maybe(converters.model(M)); const r = converter.convert({ foo: "value" }, baseOptions); expect(r).toEqual({ value: { foo: "value" } }); const r2 = converter.convert(o, baseOptions); expect(r2).toEqual({ value: o }); // we use null as the sentinel value for raw const r3 = converter.convert(null, baseOptions); expect(r3).toEqual({ value: undefined }); }); test("maybeNull model converter", () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO", }); const converter = converters.maybeNull(converters.model(M)); const r = converter.convert({ foo: "value" }, baseOptions); expect(r).toEqual({ value: { foo: "value" } }); const r2 = converter.convert(o, baseOptions); expect(r2).toEqual({ value: o }); const r3 = converter.convert(null, baseOptions); expect(r3).toEqual({ value: null }); }); test("object converter", () => { const M = types.model("M", { foo: types.string, }); const o = M.create({ foo: "FOO", }); const converter = converters.object; const r = converter.convert({ foo: "value" }, baseOptions); expect(r).toEqual({ value: { foo: "value" } }); const r2 = converter.convert(o, baseOptions); expect(r2).toEqual({ value: o }); const r3 = converter.convert(null, baseOptions); expect(r3).toEqual({ value: null }); }); test("dynamic decimal converter", () => { const context = { options: { decimalPlaces: 0 } }; const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field( converters.dynamic(converters.stringDecimal, (context) => context.options) ), }); const o = M.create({ foo: "4" }); const state = form.state(o, { context: context }); const field = state.field("foo"); field.setRaw("3.141"); expect(field.raw).toEqual("3.141"); expect(field.value).toEqual("4"); // conversion error expect(field.error).toEqual("Could not convert"); context.options = { decimalPlaces: 3 }; field.setRaw("3.141"); expect(field.raw).toEqual("3.141"); expect(field.value).toEqual("3.141"); // conversion succeeds expect(field.error).toBeUndefined(); context.options = { decimalPlaces: 2 }; expect(field.raw).toEqual("3.141"); expect(field.value).toEqual("3.141"); // nothing happens until field is touched expect(field.error).toBeUndefined(); field.setRaw("3.141"); // touch field again expect(field.raw).toEqual("3.141"); expect(field.value).toEqual("3.141"); expect(field.error).toEqual("Could not convert"); }); test("text string array converter", () => { const M = types.model("M", { foo: types.array(types.string), }); const form = new Form(M, { foo: new Field(converters.textStringArray), }); const o = M.create({ foo: ["A", "B", "C"] }); const state = form.state(o); const field = state.field("foo"); field.setRaw("A\nB\nC"); expect(field.raw).toEqual("A\nB\nC"); expect(field.value).toEqual(["A", "B", "C"]); field.setRaw("D"); expect(field.raw).toEqual("D"); expect(field.value).toEqual(["D"]); field.setRaw("1\n2 \n3"); expect(field.raw).toEqual("1\n2 \n3"); expect(field.value).toEqual(["1", "2", "3"]); field.setRaw(""); expect(field.raw).toEqual(""); expect(field.value).toEqual([]); field.setRaw("\n"); expect(field.raw).toEqual("\n"); expect(field.value).toEqual([]); field.setRaw(" "); expect(field.raw).toEqual(" "); expect(field.value).toEqual([]); field.setRaw("1\n2 \n3\n"); expect(field.raw).toEqual("1\n2 \n3\n"); expect(field.value).toEqual(["1", "2", "3"]); }); test("render decimal number without decimals with decimal separator", () => { // this exposed a dispose bug that occurred when we had a previous state // and thus two onPatch event handlers. Now we properly dispose of the // previous form state when we attach a new form state to the same // node const M = types.model("M", { foo: types.string, }); const form = new Form(M, { foo: new Field( converters.dynamic(converters.stringDecimal, (context) => ({ allowNegative: false, decimalPlaces: getCurrencyDecimals(context.getCurrency()), })) ), }); function getCurrencyDecimals(currency: string) { if (currency === "EUR") { return 2; } return 4; } const currency = "EUR"; const o = M.create({ foo: "12.3456" }); // this state is essential to replicate the bug, don't remove! const previousState = form.state(o, { focus: () => undefined, converterOptions: { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, }, context: { getCurrency: () => currency, }, }); const state = form.state(o, { converterOptions: { decimalSeparator: ",", thousandSeparator: ".", renderThousands: true, }, context: { getCurrency: () => currency, }, }); const field = state.field("foo"); field.setRaw("12,34"); expect(field.raw).toEqual("12,34"); expect(field.value).toEqual("12.34"); field.setRaw("12,"); expect(field.raw).toEqual("12,"); expect(field.value).toEqual("12."); }); test("obey addZeroes false", () => { const M = types.model("M", { foo: types.maybeNull(types.string), }); const form = new Form(M, { foo: new Field( converters.maybeNull( converters.stringDecimal({ decimalPlaces: 6, addZeroes: false }) ) ), }); const o = M.create({ foo: "1" }); const state = form.state(o); const field = state.field("foo"); expect(field.raw).toEqual("1"); }); test("obey addZeroes true", () => { const M = types.model("M", { foo: types.maybeNull(types.string), }); const form = new Form(M, { foo: new Field( converters.maybeNull( converters.stringDecimal({ decimalPlaces: 6, addZeroes: true }) ) ), }); const o = M.create({ foo: "1" }); const state = form.state(o); const field = state.field("foo"); expect(field.raw).toEqual("1.000000"); }); test("maybe decimal converter/render for empty", () => { const M = types.model("M", { foo: types.maybeNull(types.string), }); const form = new Form(M, { foo: new Field( converters.maybeNull( converters.stringDecimal({ decimalPlaces: 6, addZeroes: false }) ) ), }); const o = M.create({ foo: "" }); const state = form.state(o); const field = state.field("foo"); expect(field.raw).toEqual(""); field.setRaw("3.1412"); expect(field.raw).toEqual("3.1412"); expect(field.value).toEqual("3.1412"); field.setRaw(""); expect(field.value).toBeNull(); field.setRawFromValue(); expect(field.raw).toEqual(""); }); test("literal string converter", () => { check(converters.literalString<"foo" | "bar">(), "foo", "foo"); check( converters.literalString<"aap" | "kwarktaart">(), "kwarktaart", "kwarktaart" ); });
the_stack
* This file was automatically generated by https://github.com/Maxim-Mazurok/google-api-typings-generator. Please do not edit it manually. * In case of any problems please post issue to https://github.com/Maxim-Mazurok/google-api-typings-generator **/ gapi.load('client', () => { /** now we can use gapi.client */ gapi.client.load('photoslibrary', 'v1', () => { /** now we can use gapi.client.photoslibrary */ /** don't forget to authenticate your client before sending any request to resources: */ /** declare client_id registered in Google Developers Console */ const client_id = '<<PUT YOUR CLIENT ID HERE>>'; const scope = [ /** View and manage your Google Photos library */ 'https://www.googleapis.com/auth/photoslibrary', /** Add to your Google Photos library */ 'https://www.googleapis.com/auth/photoslibrary.appendonly', /** View your Google Photos library */ 'https://www.googleapis.com/auth/photoslibrary.readonly', /** Manage photos added by this app */ 'https://www.googleapis.com/auth/photoslibrary.readonly.appcreateddata', /** Manage and add to shared albums on your behalf */ 'https://www.googleapis.com/auth/photoslibrary.sharing', ]; const immediate = false; gapi.auth.authorize({ client_id, scope, immediate }, authResult => { if (authResult && !authResult.error) { /** handle successful authorization */ run(); } else { /** handle authorization error */ } }); }); async function run() { /** Adds an enrichment at a specified position in a defined album. */ await gapi.client.photoslibrary.albums.addEnrichment({ albumId: "Test string", }, { albumPosition: { position: "Test string", relativeEnrichmentItemId: "Test string", relativeMediaItemId: "Test string", }, newEnrichmentItem: { locationEnrichment: { location: { latlng: { latitude: 42, longitude: 42, }, locationName: "Test string", }, }, mapEnrichment: { destination: { latlng: { latitude: 42, longitude: 42, }, locationName: "Test string", }, origin: { latlng: { latitude: 42, longitude: 42, }, locationName: "Test string", }, }, textEnrichment: { text: "Test string", }, }, }); /** * Adds one or more media items in a user's Google Photos library to * an album. The media items and albums must have been created by the * developer via the API. * * Media items are added to the end of the album. If multiple media items are * given, they are added in the order specified in this call. * * Each album can contain up to 20,000 media items. * * Only media items that are in the user's library can be added to an * album. For albums that are shared, the album must either be owned by the * user or the user must have joined the album as a collaborator. * * Partial success is not supported. The entire request will fail if an * invalid media item or album is specified. */ await gapi.client.photoslibrary.albums.batchAddMediaItems({ albumId: "Test string", }, { mediaItemIds: [ "Test string" ], }); /** * Removes one or more media items from a specified album. The media items and * the album must have been created by the developer via the API. * * For albums that are shared, this action is only supported for media items * that were added to the album by this user, or for all media items if the * album was created by this user. * * Partial success is not supported. The entire request will fail and no * action will be performed on the album if an invalid media item or album is * specified. */ await gapi.client.photoslibrary.albums.batchRemoveMediaItems({ albumId: "Test string", }, { mediaItemIds: [ "Test string" ], }); /** Creates an album in a user's Google Photos library. */ await gapi.client.photoslibrary.albums.create({ }, { album: { coverPhotoBaseUrl: "Test string", coverPhotoMediaItemId: "Test string", id: "Test string", isWriteable: true, mediaItemsCount: "Test string", productUrl: "Test string", shareInfo: { isJoined: true, isOwned: true, shareToken: "Test string", shareableUrl: "Test string", sharedAlbumOptions: { isCollaborative: true, isCommentable: true, }, }, title: "Test string", }, }); /** * Returns the album based on the specified `albumId`. * The `albumId` must be the ID of an album owned by the user or a shared * album that the user has joined. */ await gapi.client.photoslibrary.albums.get({ albumId: "Test string", }); /** * Lists all albums shown to a user in the Albums tab of the Google * Photos app. */ await gapi.client.photoslibrary.albums.list({ excludeNonAppCreatedData: true, pageSize: 42, pageToken: "Test string", }); /** * Marks an album as shared and accessible to other users. This action can * only be performed on albums which were created by the developer via the * API. */ await gapi.client.photoslibrary.albums.share({ albumId: "Test string", }, { sharedAlbumOptions: { isCollaborative: true, isCommentable: true, }, }); /** * Marks a previously shared album as private. This means that the album is * no longer shared and all the non-owners will lose access to the album. All * non-owner content will be removed from the album. If a non-owner has * previously added the album to their library, they will retain all photos in * their library. This action can only be performed on albums which were * created by the developer via the API. */ await gapi.client.photoslibrary.albums.unshare({ albumId: "Test string", }, { }); /** * Creates one or more media items in a user's Google Photos library. * * This is the second step for creating a media item. For details regarding * Step 1, uploading the raw bytes to a Google Server, see * <a href="/photos/library/guides/upload-media">Uploading media</a>. * * This call adds the media item to the library. If an album `id` is * specified, the call adds the media item to the album too. Each album can * contain up to 20,000 media items. By default, the media item will be added * to the end of the library or album. * * If an album `id` and position are both defined, the media item is * added to the album at the specified position. * * If the call contains multiple media items, they're added at the specified * position. * If you are creating a media item in a shared album where you are not the * owner, you are not allowed to position the media item. Doing so will result * in a `BAD REQUEST` error. */ await gapi.client.photoslibrary.mediaItems.batchCreate({ }, { albumId: "Test string", albumPosition: { position: "Test string", relativeEnrichmentItemId: "Test string", relativeMediaItemId: "Test string", }, newMediaItems: [ { description: "Test string", simpleMediaItem: { fileName: "Test string", uploadToken: "Test string", }, } ], }); /** * Returns the list of media items for the specified media item identifiers. * Items are returned in the same order as the supplied identifiers. */ await gapi.client.photoslibrary.mediaItems.batchGet({ mediaItemIds: "Test string", }); /** Returns the media item for the specified media item identifier. */ await gapi.client.photoslibrary.mediaItems.get({ mediaItemId: "Test string", }); /** List all media items from a user's Google Photos library. */ await gapi.client.photoslibrary.mediaItems.list({ pageSize: 42, pageToken: "Test string", }); /** * Searches for media items in a user's Google Photos library. * If no filters are set, then all media items in the user's library are * returned. * If an album is set, all media items in the specified album are returned. * If filters are specified, media items that match the filters from the * user's library are listed. If you set both the album and the filters, the * request results in an error. */ await gapi.client.photoslibrary.mediaItems.search({ }, { albumId: "Test string", filters: { contentFilter: { excludedContentCategories: [ "Test string" ], includedContentCategories: [ "Test string" ], }, dateFilter: { dates: [ { day: 42, month: 42, year: 42, } ], ranges: [ { endDate: { day: 42, month: 42, year: 42, }, startDate: { day: 42, month: 42, year: 42, }, } ], }, excludeNonAppCreatedData: true, featureFilter: { includedFeatures: [ "Test string" ], }, includeArchivedMedia: true, mediaTypeFilter: { mediaTypes: [ "Test string" ], }, }, pageSize: 42, pageToken: "Test string", }); /** Returns the album based on the specified `shareToken`. */ await gapi.client.photoslibrary.sharedAlbums.get({ shareToken: "Test string", }); /** Joins a shared album on behalf of the Google Photos user. */ await gapi.client.photoslibrary.sharedAlbums.join({ }, { shareToken: "Test string", }); /** * Leaves a previously-joined shared album on behalf of the Google Photos * user. The user must not own this album. */ await gapi.client.photoslibrary.sharedAlbums.leave({ }, { shareToken: "Test string", }); /** * Lists all shared albums available in the Sharing tab of the * user's Google Photos app. */ await gapi.client.photoslibrary.sharedAlbums.list({ excludeNonAppCreatedData: true, pageSize: 42, pageToken: "Test string", }); } });
the_stack
import { IInputs, IOutputs } from "./generated/ManifestTypes"; export class TableControl implements ComponentFramework.StandardControl<IInputs, IOutputs> { // Flag to track if control is in full screen mode or not private _isFullScreen: boolean; // Reference to HTMLTableElement rendered by control private _tableElement: HTMLTableElement; // Reference to 'Set Full Screen' HTMLButtonElement private _setFullScreenButton: HTMLButtonElement; // Reference to 'Lookup Objects' HTMLButtonElement private _lookupObjectsButton: HTMLButtonElement; // Reference to 'Lookup Result Div' HTMLDivElement // Used to display information about the item selected by the lookup private _lookupObjectsResultDiv: HTMLDivElement; // Reference to the control container HTMLDivElement // This element contains all elements of our custom control example private _container: HTMLDivElement; // Reference to ComponentFramework Context object private _context: ComponentFramework.Context<IInputs>; // Flag if control view has been rendered private _controlViewRendered: boolean; // Label displayed in lookup result div // NOTE: See localization sample control for information on how to localize strings into multiple languages private LOOKUP_OBJECRESULT_DIV_STRING = "Item selected by lookupObjects method:"; // Prefix for label displayed // NOTE: See localization sample control for information on how to localize strings into multiple languages private BUTTON_LABEL_CLICK_STRING = "Click to invoke:"; // Name of entity to use for metadata retrieve example (this entity needs to exist in your org) private ENTITY_LOGICAL_NAME_FOR_METADATA_EXAMPLE = "account"; /** * Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here. * Data-set values are not initialized here, use updateView. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions. * @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously. * @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface. * @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content. */ public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container: HTMLDivElement): void { this._isFullScreen = false; this._controlViewRendered = false; this._context = context; this._container = document.createElement("div"); this._container.classList.add("Table_Container"); container.appendChild(this._container); } /** * Creates an HTMLButtonElement with the provided label * Attaches the provided method to the "onclick" event of the button element * @param buttonLabel : Label to set on button element * @param onClickHandler : event handler to attach to button's "onclick" event * @param entityName : entityName to store in the button's attribute */ private createHTMLButtonElement(buttonLabel: string, onClickHandler: (event: Event) => void, entityName: string | null): HTMLButtonElement { const button: HTMLButtonElement = document.createElement("button"); button.innerHTML = buttonLabel; entityName && button.setAttribute("entityName", entityName); button.classList.add("SampleControlHtmlTable_ButtonClass"); button.addEventListener("click", onClickHandler); return button; } /** * Returns the label to display on the 'set full screen' button * @param isFullScreenVal : True if control is currently in 'full screen' mode */ private getSetFullScreenButtonLabel(isFullScreenVal: boolean): string { return `${this.BUTTON_LABEL_CLICK_STRING} setFullScreen(${String(isFullScreenVal)})`; } /** * Event handler for 'Set Full Screen' button * * This method will transition the control to full screen state if it is currently in non-full screen state, or transition * the control out of full screen state if it is currently in full screen state * * It will also update the label on the 'Set Full Screen' button, and update the interal _isFullScreen state variable * to maintain the control's updated state * * @param event : OnClick Event */ private onSetFullScreenButtonClick(event: Event): void { this._context.mode.setFullScreen(!this._isFullScreen); this._setFullScreenButton.innerHTML = this.getSetFullScreenButtonLabel((this._isFullScreen)); this._isFullScreen = !this._isFullScreen; } /** * Event handler for 'lookup objects' button * * This method invokes the lookup dialog for the entity name specified by the buttons attribute * Once the user selects an item in the lookup, the selected item is passed back to our callback method. * Our callback method retrieves the id, name, entity type fields from the selected item and injects the * values into a resultDiv on the control to showcase the selected values. * * @param event : OnClick Event */ private onLookupObjectsButtonClick(event: Event): void { // Get the entity name for the button const entityName: string | null = (event.target as Element)?.getAttribute("entityName"); const lookUpOptions: ComponentFramework.UtilityApi.LookupOptions = { // Note: lookup can support multiple entity types with the below syntax // entityTypes: ["account", "contact"] entityTypes: [entityName] } as any; const lookUpPromise = this._context.utils.lookupObjects(lookUpOptions); lookUpPromise.then( // Callback method - invoked after user has selected an item from the lookup dialog // Data parameter is the item selected in the lookup dialog (data: ComponentFramework.LookupValue[]) => { if (data?.[0] && this._lookupObjectsResultDiv) { const id: string = data[0].id; const name: string | undefined = data[0].name; const entityType: string = data[0].entityType; let resultHTML: string = this.LOOKUP_OBJECRESULT_DIV_STRING; resultHTML += `<br/>Entity ID: ${id}`; resultHTML += `<br/>Entity Name: ${name}`; resultHTML += `<br/>Entity Type: ${entityType}`; this._lookupObjectsResultDiv.innerHTML = resultHTML; } }, (error) => { // Error handling code here } ); } /** * Generates HTML Button that invokes the lookup dialog and appends to custom control container * Generates HTML Div that displays the result of the call to the lookup dialog * @param entityName : name of entity that should be used by the lookup dialog */ private GenerateLookupObjectElements(entityName: string): void { this._lookupObjectsButton = this.createHTMLButtonElement( `${this.BUTTON_LABEL_CLICK_STRING} lookupObjects(${entityName})`, this.onLookupObjectsButtonClick.bind(this), entityName); this._container.appendChild(this._lookupObjectsButton); this._lookupObjectsResultDiv = document.createElement("div"); this._lookupObjectsResultDiv.setAttribute("class", "lookupObjectsResultDiv"); let resultDivString: string = this.LOOKUP_OBJECRESULT_DIV_STRING; resultDivString += "<br />"; resultDivString += "none"; this._lookupObjectsResultDiv.innerHTML = resultDivString; this._container.appendChild(this._lookupObjectsResultDiv); } /** * Creates an HTML Table that showcases examples of basic methods available to the custom control * The left column of the table shows the method name or property that is being used * The right column of the table shows the result of that method name or property */ private createHTMLTableElement(): HTMLTableElement { // Create HTML Table Element const tableElement: HTMLTableElement = document.createElement("table"); tableElement.setAttribute("class", "SampleControlHtmlTable_HtmlTable"); // Create header row for table let key = "Example Method"; let value = "Result"; tableElement.appendChild(this.createHTMLTableRowElement(key, value, true)); // Example use of getFormFactor() method // Open the control on different form factors to see the value change key = "getFormFactor()"; value = String(this._context.client.getFormFactor()); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example use of getClient() method // Open the control on different clients (phone / tablet/ web) to see the value change key = "getClient()"; value = String(this._context.client.getClient()); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example of userName property // Log in with a different user to see the user name change key = "userName"; value = String(this._context.userSettings.userName); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example of isRTL property // Update your language to an RTL language (for example: Hebrew) to see this value change key = "User Language isRTL"; value = String(this._context.userSettings.isRTL); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example of numberFormattingInfo and formatCurrency // Retrieve the currencyDecimalDigits and currencySymbol from the numberFormattingInfo object to retrieve the // preferences set in the current users 'User Settings' // Pass these values as parameters into the formatting.formatCurrency utility method to format the number per the users preferences key = "formatting formatCurrency"; const numberFormattingInfo: ComponentFramework.UserSettingApi.NumberFormattingInfo = this._context.userSettings.numberFormattingInfo; const percision: number = numberFormattingInfo.currencyDecimalDigits; const currencySymbol: string = numberFormattingInfo.currencySymbol; value = this._context.formatting.formatCurrency(100500, percision, currencySymbol); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example of formatDateLong // Pass a JavaScript Data object set to the current time into formatDateLong method to format the data // per the users preferences in 'User Settings' key = "formatting formatDateLong"; value = this._context.formatting.formatDateLong(new Date()); tableElement.appendChild(this.createHTMLTableRowElement(key, value, false)); // Example of getEntityMetadata // Retrieve the Entity Metadata for the entityName parameter. In the callback method, retrieve the primaryNameAttribute, logicalName, // and isCustomEntity attributes and inject the results into the Example HTML Table this._context.utils.getEntityMetadata(this.ENTITY_LOGICAL_NAME_FOR_METADATA_EXAMPLE).then( entityMetadata => { // Generate the HTML Elements used for the lookup control example this.GenerateLookupObjectElements(this.ENTITY_LOGICAL_NAME_FOR_METADATA_EXAMPLE); }, error => { // Error handling code here } ); return tableElement; } /** * Helper method to create an HTML Table Row Element * * @param key : string value to show in left column cell * @param value : string value to show in right column cell * @param isHeaderRow : true if method should generate a header row */ private createHTMLTableRowElement(key: string, value: string, isHeaderRow: boolean): HTMLTableRowElement { const keyCell: HTMLTableCellElement = this.createHTMLTableCellElement(key, "SampleControlHtmlTable_HtmlCell_Key", isHeaderRow); const valueCell: HTMLTableCellElement = this.createHTMLTableCellElement(value, "SampleControlHtmlTable_HtmlCell_Value", isHeaderRow); const rowElement: HTMLTableRowElement = document.createElement("tr"); rowElement.setAttribute("class", "SampleControlHtmlTable_HtmlRow"); rowElement.appendChild(keyCell); rowElement.appendChild(valueCell); return rowElement; } /** * Helper method to create an HTML Table Cell Element * * @param cellValue : string value to inject in the cell * @param className : class name for the cell * @param isHeaderRow : true if method should generate a header row cell */ private createHTMLTableCellElement(cellValue: string, className: string, isHeaderRow: boolean): HTMLTableCellElement { let cellElement: HTMLTableCellElement; if (isHeaderRow) { cellElement = document.createElement("th"); cellElement.setAttribute("class", `SampleControlHtmlTable_HtmlHeaderCell ${className}`); } else { cellElement = document.createElement("td"); cellElement.setAttribute("class", `SampleControlHtmlTable_HtmlCell ${className}`); } const textElement: Text = document.createTextNode(cellValue); cellElement.appendChild(textElement); return cellElement; } /** * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions */ public updateView(context: ComponentFramework.Context<IInputs>): void { if (!this._controlViewRendered) { // Render and add HTMLTable to the custom control container element const tableElement: HTMLTableElement = this.createHTMLTableElement(); this._container.appendChild(tableElement); // Render and add set full screen button to the custom control container element this._setFullScreenButton = this.createHTMLButtonElement( this.getSetFullScreenButtonLabel(!this._isFullScreen), this.onSetFullScreenButtonClick.bind(this), null); this._container.appendChild(this._setFullScreenButton); this._controlViewRendered = true; } } /** * It is called by the framework prior to a control receiving new data. * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as "bound" or "output" */ public getOutputs(): IOutputs { // no-op: method not leveraged by this example custom control return {}; } /** * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup. * i.e. cancelling any pending remote calls, removing listeners, etc. */ public destroy(): void { // no-op: method not leveraged by this example custom control } }
the_stack
import { isLeft } from "fp-ts/lib/Either" import { pipe } from "fp-ts/lib/function" import { TaskEither, tryCatch, chain, right, left } from "fp-ts/lib/TaskEither" import * as qjs from "quickjs-emscripten" import { marshalObjectToVM } from "./utils" /** * The response object structure exposed to the test script */ export type TestResponse = { /** Status Code of the response */ status: number, /** List of headers returned */ headers: { key: string, value: string }[], /** * Body of the response, this will be the JSON object if it is a JSON content type, else body string */ body: string | object } /** * The result of an expectation statement */ type ExpectResult = | { status: "pass" | "fail" | "error", message: string } // The expectation failed (fail) or errored (error) /** * An object defining the result of the execution of a * test block */ export type TestDescriptor = { /** * The name of the test block */ descriptor: string /** * Expectation results of the test block */ expectResults: ExpectResult[] /** * Children test blocks (test blocks inside the test block) */ children: TestDescriptor[] } /** * Creates an Expectation object for use inside the sandbox * @param vm The QuickJS sandbox VM instance * @param expectVal The expecting value of the expectation * @param negated Whether the expectation is negated (negative) * @param currTestStack The current state of the test execution stack * @returns Handle to the expectation object in VM */ function createExpectation( vm: qjs.QuickJSVm, expectVal: any, negated: boolean, currTestStack: TestDescriptor[] ): qjs.QuickJSHandle { const resultHandle = vm.newObject() const toBeFnHandle = vm.newFunction("toBe", (expectedValHandle) => { const expectedVal = vm.dump(expectedValHandle) let assertion = expectVal === expectedVal if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be '${expectedVal}'` }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be '${expectedVal}'`, }) } return { value: vm.undefined } }) const toBeLevel2xxHandle = vm.newFunction("toBeLevel2xx", () => { // Check if the expected value is a number, else it is an error if (typeof expectVal === "number" && !Number.isNaN(expectVal)) { let assertion = expectVal >= 200 && expectVal <= 299 if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 200-level status`, }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 200-level status`, }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Expected 200-level status but could not parse value '${expectVal}'`, }) } return { value: vm.undefined } }) const toBeLevel3xxHandle = vm.newFunction("toBeLevel3xx", () => { // Check if the expected value is a number, else it is an error if (typeof expectVal === "number" && !Number.isNaN(expectVal)) { let assertion = expectVal >= 300 && expectVal <= 399 if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 300-level status`, }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 300-level status`, }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Expected 300-level status but could not parse value '${expectVal}'`, }) } return { value: vm.undefined } }) const toBeLevel4xxHandle = vm.newFunction("toBeLevel4xx", () => { // Check if the expected value is a number, else it is an error if (typeof expectVal === "number" && !Number.isNaN(expectVal)) { let assertion = expectVal >= 400 && expectVal <= 499 if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 400-level status`, }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 400-level status`, }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Expected 400-level status but could not parse value '${expectVal}'`, }) } return { value: vm.undefined } }) const toBeLevel5xxHandle = vm.newFunction("toBeLevel5xx", () => { // Check if the expected value is a number, else it is an error if (typeof expectVal === "number" && !Number.isNaN(expectVal)) { let assertion = expectVal >= 500 && expectVal <= 599 if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 500-level status`, }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be 500-level status` }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Expected 500-level status but could not parse value '${expectVal}'`, }) } return { value: vm.undefined } }) const toBeTypeHandle = vm.newFunction("toBeType", (expectedValHandle) => { const expectedType = vm.dump(expectedValHandle) // Check if the expectation param is a valid type name string, else error if (["string", "boolean", "number", "object", "undefined", "bigint", "symbol", "function"].includes(expectedType)) { let assertion = typeof expectVal === expectedType if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected '${expectVal}' to${negated ? " not" : ""} be type '${expectedType}'` }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected '${expectVal}' to${negated ? " not" : ""} be type '${expectedType}'`, }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Argument for toBeType should be "string", "boolean", "number", "object", "undefined", "bigint", "symbol" or "function"` }) } return { value: vm.undefined } }) const toHaveLengthHandle = vm.newFunction( "toHaveLength", (expectedValHandle) => { const expectedLength = vm.dump(expectedValHandle) if (!(Array.isArray(expectVal) || typeof expectVal === "string")) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Expected toHaveLength to be called for an array or string`, }) return { value: vm.undefined } } // Check if the parameter is a number, else error if (typeof expectedLength === "number" && !Number.isNaN(expectedLength)) { let assertion = (expectVal as any[]).length === expectedLength if (negated) assertion = !assertion if (assertion) { currTestStack[currTestStack.length - 1].expectResults.push({ status: "pass", message: `Expected the array to${negated ? " not" : ""} be of length '${expectedLength}'`, }) } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "fail", message: `Expected the array to${negated ? " not" : ""} be of length '${expectedLength}'` }) } } else { currTestStack[currTestStack.length - 1].expectResults.push({ status: "error", message: `Argument for toHaveLength should be a number` }) } return { value: vm.undefined } } ) vm.setProp(resultHandle, "toBe", toBeFnHandle) vm.setProp(resultHandle, "toBeLevel2xx", toBeLevel2xxHandle) vm.setProp(resultHandle, "toBeLevel3xx", toBeLevel3xxHandle) vm.setProp(resultHandle, "toBeLevel4xx", toBeLevel4xxHandle) vm.setProp(resultHandle, "toBeLevel5xx", toBeLevel5xxHandle) vm.setProp(resultHandle, "toBeType", toBeTypeHandle) vm.setProp(resultHandle, "toHaveLength", toHaveLengthHandle) vm.defineProp(resultHandle, "not", { get: () => { return createExpectation(vm, expectVal, !negated, currTestStack) }, }) toBeFnHandle.dispose() toBeLevel2xxHandle.dispose() toBeLevel3xxHandle.dispose() toBeLevel4xxHandle.dispose() toBeLevel5xxHandle.dispose() toBeTypeHandle.dispose() toHaveLengthHandle.dispose() return resultHandle } export const execTestScript = ( testScript: string, response: TestResponse ): TaskEither<string, TestDescriptor[]> => pipe( tryCatch( async () => await qjs.getQuickJS(), (reason) => `QuickJS initialization failed: ${reason}` ), chain( // TODO: Make this more functional ? (QuickJS) => { const vm = QuickJS.createVm() const pwHandle = vm.newObject() const testRunStack: TestDescriptor[] = [ { descriptor: "root", expectResults: [], children: [] }, ] const testFuncHandle = vm.newFunction( "test", (descriptorHandle, testFuncHandle) => { const descriptor = vm.getString(descriptorHandle) testRunStack.push({ descriptor, expectResults: [], children: [], }) const result = vm.unwrapResult(vm.callFunction(testFuncHandle, vm.null)) result.dispose() const child = testRunStack.pop() as TestDescriptor testRunStack[testRunStack.length - 1].children.push(child) } ) const expectFnHandle = vm.newFunction("expect", (expectValueHandle) => { const expectVal = vm.dump(expectValueHandle) return { value: createExpectation(vm, expectVal, false, testRunStack), } }) // Marshal response object const responseObjHandle = marshalObjectToVM(vm, response) if (isLeft(responseObjHandle)) return left(`Response marshalling failed: ${responseObjHandle.left}`) vm.setProp(pwHandle, "response", responseObjHandle.right) responseObjHandle.right.dispose() vm.setProp(pwHandle, "expect", expectFnHandle) expectFnHandle.dispose() vm.setProp(pwHandle, "test", testFuncHandle) testFuncHandle.dispose() vm.setProp(vm.global, "pw", pwHandle) pwHandle.dispose() const evalRes = vm.evalCode(testScript) if (evalRes.error) { const errorData = vm.dump(evalRes.error) evalRes.error.dispose() return left(`Script evaluation failed: ${errorData}`) } vm.dispose() return right(testRunStack) } ) )
the_stack
import map, { Delegate, MatchCallback, Route } from "./route-recognizer/dsl"; import { encodePathSegment, normalizePath, normalizeSegment } from "./route-recognizer/normalizer"; import { createMap } from "./route-recognizer/util"; export { Delegate, MatchCallback } from "./route-recognizer/dsl"; const enum CHARS { ANY = -1, STAR = 42, SLASH = 47, COLON = 58 } const escapeRegex = /(\/|\.|\*|\+|\?|\||\(|\)|\[|\]|\{|\}|\\)/g; const isArray = Array.isArray; // eslint-disable-next-line @typescript-eslint/unbound-method const hasOwnProperty = Object.prototype.hasOwnProperty; function getParam(params: Params | null | undefined, key: string): string { if (typeof params !== "object" || params === null) { throw new Error( "You must pass an object as the second argument to `generate`." ); } if (!hasOwnProperty.call(params, key)) { throw new Error("You must provide param `" + key + "` to `generate`."); } const value = params[key]; const str = typeof value === "string" ? value : "" + value; if (str.length === 0) { throw new Error("You must provide a param `" + key + "`."); } return str; } const enum SegmentType { Static = 0, Dynamic = 1, Star = 2, Epsilon = 4 } const enum SegmentFlags { Static = SegmentType.Static, Dynamic = SegmentType.Dynamic, Star = SegmentType.Star, Epsilon = SegmentType.Epsilon, Named = Dynamic | Star, Decoded = Dynamic, Counted = Static | Dynamic | Star } type Counted = SegmentType.Static | SegmentType.Dynamic | SegmentType.Star; const eachChar: (<THandler>( segment: Segment, currentState: State<THandler> ) => State<THandler>)[] = []; eachChar[SegmentType.Static] = function<THandler>( segment: Segment, currentState: State<THandler> ) { let state = currentState; const value = segment.value; for (let i = 0; i < value.length; i++) { const ch = value.charCodeAt(i); state = state.put(ch, false, false); } return state; }; eachChar[SegmentType.Dynamic] = function<THandler>( _: Segment, currentState: State<THandler> ) { return currentState.put(CHARS.SLASH, true, true); }; eachChar[SegmentType.Star] = function<THandler>( _: Segment, currentState: State<THandler> ) { return currentState.put(CHARS.ANY, false, true); }; eachChar[SegmentType.Epsilon] = function<THandler>( _: Segment, currentState: State<THandler> ) { return currentState; }; const regex: ((segment: Segment) => string)[] = []; regex[SegmentType.Static] = function(segment: Segment) { return segment.value.replace(escapeRegex, "\\$1"); }; regex[SegmentType.Dynamic] = function() { return "([^/]+)"; }; regex[SegmentType.Star] = function() { return "(.+)"; }; regex[SegmentType.Epsilon] = function() { return ""; }; const generate: (( segment: Segment, params?: Params | null, shouldEncode?: boolean ) => string)[] = []; generate[SegmentType.Static] = function(segment: Segment) { return segment.value; }; generate[SegmentType.Dynamic] = function( segment: Segment, params?: Params | null, shouldEncode?: boolean ) { const value = getParam(params, segment.value); if (shouldEncode) { return encodePathSegment(value); } else { return value; } }; generate[SegmentType.Star] = function( segment: Segment, params?: Params | null ) { return getParam(params, segment.value); }; generate[SegmentType.Epsilon] = function() { return ""; }; // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat interface Segment { type: SegmentType; value: string; } export interface Params { [key: string]: unknown; [key: number]: unknown; queryParams?: { [key: string]: unknown; [key: number]: unknown; } | null; } interface ParsedHandler { names: string[]; shouldDecodes: boolean[]; } const EmptyObject = Object.freeze({}); type EmptyObject = typeof EmptyObject; const EmptyArray = Object.freeze([]) as ReadonlyArray<unknown>; type EmptyArray = typeof EmptyArray; // The `names` will be populated with the paramter name for each dynamic/star // segment. `shouldDecodes` will be populated with a boolean for each dyanamic/star // segment, indicating whether it should be decoded during recognition. function parse( segments: Segment[], route: string, types: [number, number, number] ): ParsedHandler { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.length > 0 && route.charCodeAt(0) === CHARS.SLASH) { route = route.substr(1); } const parts = route.split("/"); let names: undefined | string[] = undefined; let shouldDecodes: undefined | boolean[] = undefined; for (let i = 0; i < parts.length; i++) { let part = parts[i]; let type: SegmentType = 0; if (part === "") { type = SegmentType.Epsilon; } else if (part.charCodeAt(0) === CHARS.COLON) { type = SegmentType.Dynamic; } else if (part.charCodeAt(0) === CHARS.STAR) { type = SegmentType.Star; } else { type = SegmentType.Static; } if (type & SegmentFlags.Named) { part = part.slice(1); names = names || []; names.push(part); shouldDecodes = shouldDecodes || []; shouldDecodes.push((type & SegmentFlags.Decoded) !== 0); } if (type & SegmentFlags.Counted) { types[type as Counted]++; } segments.push({ type, value: normalizeSegment(part) }); } return { names: names || EmptyArray, shouldDecodes: shouldDecodes || EmptyArray } as ParsedHandler; } function isEqualCharSpec( spec: CharSpec, char: number, negate: boolean ): boolean { return spec.char === char && spec.negate === negate; } interface Handler<THandler> { handler: THandler; names: string[]; shouldDecodes: boolean[]; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. class State<THandler> implements CharSpec { states: State<THandler>[]; id: number; negate: boolean; char: number; nextStates: number[] | number | null; pattern: string; _regex: RegExp | undefined; handlers: Handler<THandler>[] | undefined; types: [number, number, number] | undefined; constructor( states: State<THandler>[], id: number, char: number, negate: boolean, repeat: boolean ) { this.states = states; this.id = id; this.char = char; this.negate = negate; this.nextStates = repeat ? id : null; this.pattern = ""; this._regex = undefined; this.handlers = undefined; this.types = undefined; } regex(): RegExp { if (!this._regex) { this._regex = new RegExp(this.pattern); } return this._regex; } get(char: number, negate: boolean): State<THandler> | void { const nextStates = this.nextStates; if (nextStates === null) return; if (isArray(nextStates)) { for (let i = 0; i < nextStates.length; i++) { const child = this.states[nextStates[i]]; if (isEqualCharSpec(child, char, negate)) { return child; } } } else { const child = this.states[nextStates]; if (isEqualCharSpec(child, char, negate)) { return child; } } } put(char: number, negate: boolean, repeat: boolean): State<THandler> { let state: State<THandler> | void; // If the character specification already exists in a child of the current // state, just return that state. if ((state = this.get(char, negate))) { return state; } // Make a new state for the character spec const states = this.states; state = new State(states, states.length, char, negate, repeat); states[states.length] = state; // Insert the new state as a child of the current state if (this.nextStates == null) { this.nextStates = state.id; } else if (isArray(this.nextStates)) { this.nextStates.push(state.id); } else { this.nextStates = [this.nextStates, state.id]; } // Return the new state return state; } // Find a list of child states matching the next character match(ch: number): State<THandler>[] { const nextStates = this.nextStates; if (!nextStates) return []; const returned: State<THandler>[] = []; if (isArray(nextStates)) { for (let i = 0; i < nextStates.length; i++) { const child = this.states[nextStates[i]]; if (isMatch(child, ch)) { returned.push(child); } } } else { const child = this.states[nextStates]; if (isMatch(child, ch)) { returned.push(child); } } return returned; } } function isMatch(spec: CharSpec, char: number): boolean { return spec.negate ? spec.char !== char && spec.char !== CHARS.ANY : spec.char === char || spec.char === CHARS.ANY; } // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. // // This strategy generally prefers more static and less dynamic matching. // Specifically, it // // * prefers fewer stars to more, then // * prefers using stars for less of the match to more, then // * prefers fewer dynamic segments to more, then // * prefers more static segments to more function sortSolutions<THandler>(states: State<THandler>[]): State<THandler>[] { return states.sort(function(a, b) { const [astatics, adynamics, astars] = a.types || [0, 0, 0]; const [bstatics, bdynamics, bstars] = b.types || [0, 0, 0]; if (astars !== bstars) { return astars - bstars; } if (astars) { if (astatics !== bstatics) { return bstatics - astatics; } if (adynamics !== bdynamics) { return bdynamics - adynamics; } } if (adynamics !== bdynamics) { return adynamics - bdynamics; } if (astatics !== bstatics) { return bstatics - astatics; } return 0; }); } function recognizeChar<THandler>( states: State<THandler>[], ch: number ): State<THandler>[] { let nextStates: State<THandler>[] = []; for (let i = 0, l = states.length; i < l; i++) { const state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } export interface QueryParams { [param: string]: string[] | string | null | undefined; } export interface Result<THandler> { handler: THandler; params: Params; isDynamic: boolean; } export interface Results<THandler> extends ArrayLike<Result<THandler>> { queryParams: QueryParams; slice(start?: number, end?: number): Result<THandler>[]; splice( start: number, deleteCount: number, ...items: Result<THandler>[] ): Result<THandler>[]; push(...results: Result<THandler>[]): number; } class RecognizeResults<THandler> implements Results<THandler> { queryParams: QueryParams; length = 0; [index: number]: Result<THandler>; splice!: ( start: number, deleteCount: number, ...items: Result<THandler>[] ) => Result<THandler>[]; slice!: (start?: number, end?: number) => Result<THandler>[]; push!: (...results: Result<THandler>[]) => number; constructor(queryParams?: QueryParams) { this.queryParams = queryParams || {}; } } // eslint-disable-next-line @typescript-eslint/unbound-method RecognizeResults.prototype.splice = Array.prototype.splice; // eslint-disable-next-line @typescript-eslint/unbound-method RecognizeResults.prototype.slice = Array.prototype.slice; // eslint-disable-next-line @typescript-eslint/unbound-method RecognizeResults.prototype.push = Array.prototype.push; function findHandler<THandler>( state: State<THandler>, originalPath: string, queryParams: QueryParams, shouldDecode: boolean ): Results<THandler> { const handlers = state.handlers; const regex: RegExp = state.regex(); if (!regex || !handlers) throw new Error("state not initialized"); const captures: RegExpMatchArray | null = regex.exec(originalPath); let currentCapture = 1; const result = new RecognizeResults<THandler>(queryParams); result.length = handlers.length; for (let i = 0; i < handlers.length; i++) { const handler = handlers[i]; const names = handler.names; const shouldDecodes = handler.shouldDecodes; let params: Params = EmptyObject; let isDynamic = false; if (names !== (EmptyArray as string[]) && shouldDecodes !== EmptyArray) { for (let j = 0; j < names.length; j++) { isDynamic = true; const name = names[j]; const capture = captures && captures[currentCapture++]; if (params === EmptyObject) { params = {}; } if (shouldDecode && shouldDecodes[j]) { params[name] = capture && decodeURIComponent(capture); } else { params[name] = capture; } } } result[i] = { handler: handler.handler, params, isDynamic }; } return result; } function decodeQueryParamPart(part: string): string { // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 part = part.replace(/\+/gm, "%20"); let result; try { result = decodeURIComponent(part); } catch (error) { result = ""; } return result; } interface NamedRoute<THandler> { segments: Segment[]; handlers: Handler<THandler>[]; } class RouteRecognizer<THandler = string> { private rootState: State<THandler>; private names: { [name: string]: NamedRoute<THandler> | undefined; } = createMap<NamedRoute<THandler>>(); map!: ( context: MatchCallback<THandler>, addCallback?: (router: this, routes: Route<THandler>[]) => void ) => void; delegate: Delegate<THandler> | undefined; constructor() { const states: State<THandler>[] = []; const state = new State(states, 0, CHARS.ANY, true, false); states[0] = state; this.rootState = state; } static VERSION = "VERSION_STRING_PLACEHOLDER"; // Set to false to opt-out of encoding and decoding path segments. // See https://github.com/tildeio/route-recognizer/pull/55 static ENCODE_AND_DECODE_PATH_SEGMENTS = true; static Normalizer = { normalizeSegment, normalizePath, encodePathSegment }; add(routes: Route<THandler>[], options?: { as: string }): void { let currentState = this.rootState; let pattern = "^"; const types: [number, number, number] = [0, 0, 0]; const handlers: Handler<THandler>[] = new Array(routes.length); const allSegments: Segment[] = []; let isEmpty = true; let j = 0; for (let i = 0; i < routes.length; i++) { const route = routes[i]; const { names, shouldDecodes } = parse(allSegments, route.path, types); // preserve j so it points to the start of newly added segments for (; j < allSegments.length; j++) { const segment = allSegments[j]; if (segment.type === SegmentType.Epsilon) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put(CHARS.SLASH, false, false); pattern += "/"; // Add a representation of the segment to the NFA and regex currentState = eachChar[segment.type](segment, currentState); pattern += regex[segment.type](segment); } handlers[i] = { handler: route.handler, names, shouldDecodes }; } if (isEmpty) { currentState = currentState.put(CHARS.SLASH, false, false); pattern += "/"; } currentState.handlers = handlers; currentState.pattern = pattern + "$"; currentState.types = types; let name: string | undefined; if (typeof options === "object" && options !== null && options.as) { name = options.as; } if (name) { // if (this.names[name]) { // throw new Error("You may not add a duplicate route named `" + name + "`."); // } this.names[name] = { segments: allSegments, handlers }; } } handlersFor(name: string): Handler<THandler>[] { const route = this.names[name]; if (!route) { throw new Error("There is no route named " + name); } const result: Handler<THandler>[] = new Array(route.handlers.length); for (let i = 0; i < route.handlers.length; i++) { const handler = route.handlers[i]; result[i] = handler; } return result; } hasRoute(name: string): boolean { return !!this.names[name]; } generate(name: string, params?: Params | null): string { const shouldEncode = RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS; const route = this.names[name]; let output = ""; if (!route) { throw new Error("There is no route named " + name); } const segments: Segment[] = route.segments; for (let i = 0; i < segments.length; i++) { const segment: Segment = segments[i]; if (segment.type === SegmentType.Epsilon) { continue; } output += "/"; output += generate[segment.type](segment, params, shouldEncode); } if (!output.startsWith("/")) { output = "/" + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams); } return output; } generateQueryString(params: Params): string { const pairs: string[] = []; const keys: string[] = Object.keys(params); keys.sort(); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = params[key]; if (value == null) { continue; } let pair = encodeURIComponent(key); if (isArray(value)) { for (let j = 0; j < value.length; j++) { const arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value as string); pairs.push(pair); } } if (pairs.length === 0) { return ""; } return "?" + pairs.join("&"); } parseQueryString(queryString: string): QueryParams { const pairs = queryString.split("&"); const queryParams: QueryParams = {}; for (let i = 0; i < pairs.length; i++) { const pair = pairs[i].split("="); let key = decodeQueryParamPart(pair[0]); const keyLength = key.length; let isArray = false; let value: string; if (pair.length === 1) { value = "true"; } else { // Handle arrays if (keyLength > 2 && key.endsWith("[]")) { isArray = true; key = key.slice(0, keyLength - 2); if (!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeQueryParamPart(pair[1]) : ""; } if (isArray) { (queryParams[key] as string[]).push(value); } else { queryParams[key] = value; } } return queryParams; } recognize(path: string): Results<THandler> | undefined { const shouldNormalize = RouteRecognizer.ENCODE_AND_DECODE_PATH_SEGMENTS; let results: Results<THandler> | undefined; let states: State<THandler>[] = [this.rootState]; let queryParams = {}; let isSlashDropped = false; const hashStart = path.indexOf("#"); if (hashStart !== -1) { path = path.substr(0, hashStart); } const queryStart = path.indexOf("?"); if (queryStart !== -1) { const queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } if (!path.startsWith("/")) { path = "/" + path; } let originalPath = path; if (shouldNormalize) { path = normalizePath(path); } else { path = decodeURI(path); originalPath = decodeURI(originalPath); } const pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); originalPath = originalPath.substr(0, originalPath.length - 1); isSlashDropped = true; } for (let i = 0; i < path.length; i++) { states = recognizeChar(states, path.charCodeAt(i)); if (!states.length) { break; } } const solutions: State<THandler>[] = []; for (let i = 0; i < states.length; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); const state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.char === CHARS.ANY) { originalPath = originalPath + "/"; } results = findHandler(state, originalPath, queryParams, shouldNormalize); } return results; } } RouteRecognizer.prototype.map = map; export default RouteRecognizer; interface CharSpec { negate: boolean; char: number; }
the_stack
import { CoreSites } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { CoreH5P } from '@features/h5p/services/h5p'; import { CoreH5PCore, CoreH5PDisplayOptionBehaviour, CoreH5PContentDependencyData, CoreH5PLibraryData, CoreH5PLibraryAddonData, CoreH5PContentDepsTreeDependency, CoreH5PLibraryBasicData, CoreH5PLibraryBasicDataWithPatch, } from './core'; import { CONTENT_TABLE_NAME, LIBRARIES_CACHEDASSETS_TABLE_NAME, CoreH5PLibraryCachedAssetsDBRecord, LIBRARIES_TABLE_NAME, LIBRARY_DEPENDENCIES_TABLE_NAME, CONTENTS_LIBRARIES_TABLE_NAME, CoreH5PContentDBRecord, CoreH5PLibraryDBRecord, CoreH5PLibraryDependencyDBRecord, CoreH5PContentsLibraryDBRecord, } from '../services/database/h5p'; import { CoreError } from '@classes/errors/error'; import { CoreH5PSemantics } from './content-validator'; import { CoreH5PContentBeingSaved, CoreH5PLibraryBeingSaved } from './storage'; import { CoreH5PLibraryAddTo, CoreH5PLibraryMetadataSettings } from './validator'; import { CoreH5PMetadata } from './metadata'; /** * Equivalent to Moodle's implementation of H5PFrameworkInterface. */ export class CoreH5PFramework { /** * Will clear filtered params for all the content that uses the specified libraries. * This means that the content dependencies will have to be rebuilt and the parameters re-filtered. * * @param libraryIds Array of library ids. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async clearFilteredParameters(libraryIds: number[], siteId?: string): Promise<void> { if (!libraryIds || !libraryIds.length) { return; } const db = await CoreSites.getSiteDb(siteId); const whereAndParams = db.getInOrEqual(libraryIds); whereAndParams.sql = 'mainlibraryid ' + whereAndParams.sql; await db.updateRecordsWhere(CONTENT_TABLE_NAME, { filtered: null }, whereAndParams.sql, whereAndParams.params); } /** * Delete cached assets from DB. * * @param libraryId Library identifier. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the removed entries. */ async deleteCachedAssets(libraryId: number, siteId?: string): Promise<CoreH5PLibraryCachedAssetsDBRecord[]> { const db = await CoreSites.getSiteDb(siteId); // Get all the hashes that use this library. const entries = await db.getRecords<CoreH5PLibraryCachedAssetsDBRecord>( LIBRARIES_CACHEDASSETS_TABLE_NAME, { libraryid: libraryId }, ); const hashes = entries.map((entry) => entry.hash); if (hashes.length) { // Delete the entries from DB. await db.deleteRecordsList(LIBRARIES_CACHEDASSETS_TABLE_NAME, 'hash', hashes); } return entries; } /** * Delete content data from DB. * * @param id Content ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteContentData(id: number, siteId?: string): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await Promise.all([ // Delete the content data. db.deleteRecords(CONTENT_TABLE_NAME, { id }), // Remove content library dependencies. this.deleteLibraryUsage(id, siteId), ]); } /** * Delete library data from DB. * * @param id Library ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteLibrary(id: number, siteId?: string): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(LIBRARIES_TABLE_NAME, { id }); } /** * Delete all dependencies belonging to given library. * * @param libraryId Library ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteLibraryDependencies(libraryId: number, siteId?: string): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(LIBRARY_DEPENDENCIES_TABLE_NAME, { libraryid: libraryId }); } /** * Delete what libraries a content item is using. * * @param id Package ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async deleteLibraryUsage(id: number, siteId?: string): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await db.deleteRecords(CONTENTS_LIBRARIES_TABLE_NAME, { h5pid: id }); } /** * Get all conent data from DB. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the list of content data. */ async getAllContentData(siteId?: string): Promise<CoreH5PContentDBRecord[]> { const db = await CoreSites.getSiteDb(siteId); return db.getAllRecords<CoreH5PContentDBRecord>(CONTENT_TABLE_NAME); } /** * Get conent data from DB. * * @param id Content ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the content data. */ async getContentData(id: number, siteId?: string): Promise<CoreH5PContentDBRecord> { const db = await CoreSites.getSiteDb(siteId); return db.getRecord<CoreH5PContentDBRecord>(CONTENT_TABLE_NAME, { id }); } /** * Get conent data from DB. * * @param fileUrl H5P file URL. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the content data. */ async getContentDataByUrl(fileUrl: string, siteId?: string): Promise<CoreH5PContentDBRecord> { const site = await CoreSites.getSite(siteId); const db = site.getDb(); // Try to use the folder name, it should be more reliable than the URL. const folderName = await CoreH5P.h5pCore.h5pFS.getContentFolderNameByUrl(fileUrl, site.getId()); try { return await db.getRecord<CoreH5PContentDBRecord>(CONTENT_TABLE_NAME, { foldername: folderName }); } catch (error) { // Cannot get folder name, the h5p file was probably deleted. Just use the URL. return db.getRecord<CoreH5PContentDBRecord>(CONTENT_TABLE_NAME, { fileurl: fileUrl }); } } /** * Get the latest library version. * * @param machineName The library's machine name. * @return Promise resolved with the latest library version data. */ async getLatestLibraryVersion(machineName: string, siteId?: string): Promise<CoreH5PLibraryParsedDBRecord> { const db = await CoreSites.getSiteDb(siteId); try { const records = await db.getRecords<CoreH5PLibraryDBRecord>( LIBRARIES_TABLE_NAME, { machinename: machineName }, 'majorversion DESC, minorversion DESC, patchversion DESC', '*', 0, 1, ); if (records && records[0]) { return this.parseLibDBData(records[0]); } } catch (error) { // Library not found. } throw new CoreError(`Missing required library: ${machineName}`); } /** * Get a library data stored in DB. * * @param machineName Machine name. * @param majorVersion Major version number. * @param minorVersion Minor version number. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library data, rejected if not found. */ protected async getLibrary( machineName: string, majorVersion?: string | number, minorVersion?: string | number, siteId?: string, ): Promise<CoreH5PLibraryParsedDBRecord> { const db = await CoreSites.getSiteDb(siteId); const libraries = await db.getRecords<CoreH5PLibraryDBRecord>(LIBRARIES_TABLE_NAME, { machinename: machineName, majorversion: majorVersion, minorversion: minorVersion, }); if (!libraries.length) { throw new CoreError('Libary not found.'); } return this.parseLibDBData(libraries[0]); } /** * Get a library data stored in DB. * * @param libraryData Library data. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library data, rejected if not found. */ getLibraryByData(libraryData: CoreH5PLibraryBasicData, siteId?: string): Promise<CoreH5PLibraryParsedDBRecord> { return this.getLibrary(libraryData.machineName, libraryData.majorVersion, libraryData.minorVersion, siteId); } /** * Get a library data stored in DB by ID. * * @param id Library ID. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library data, rejected if not found. */ async getLibraryById(id: number, siteId?: string): Promise<CoreH5PLibraryParsedDBRecord> { const db = await CoreSites.getSiteDb(siteId); const library = await db.getRecord<CoreH5PLibraryDBRecord>(LIBRARIES_TABLE_NAME, { id }); return this.parseLibDBData(library); } /** * Get a library ID. If not found, return null. * * @param machineName Machine name. * @param majorVersion Major version number. * @param minorVersion Minor version number. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library ID, null if not found. */ async getLibraryId( machineName: string, majorVersion?: string | number, minorVersion?: string | number, siteId?: string, ): Promise<number | undefined> { try { const library = await this.getLibrary(machineName, majorVersion, minorVersion, siteId); return library.id || undefined; } catch (error) { return undefined; } } /** * Get a library ID. If not found, return null. * * @param libraryData Library data. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library ID, null if not found. */ getLibraryIdByData(libraryData: CoreH5PLibraryBasicData, siteId?: string): Promise<number | undefined> { return this.getLibraryId(libraryData.machineName, libraryData.majorVersion, libraryData.minorVersion, siteId); } /** * Get the default behaviour for the display option defined. * * @param name Identifier for the setting. * @param defaultValue Optional default value if settings is not set. * @return Return the value for this display option. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getOption(name: string, defaultValue: unknown): unknown { // For now, all them are disabled by default, so only will be rendered when defined in the display options. return CoreH5PDisplayOptionBehaviour.CONTROLLED_BY_AUTHOR_DEFAULT_OFF; } /** * Check whether the user has permission to execute an action. * * @param permission Permission to check. * @param id H5P package id. * @return Whether the user has permission to execute an action. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars hasPermission(permission: number, id: number): boolean { // H5P capabilities have not been introduced. return true; } /** * Determines if content slug is used. * * @param slug The content slug. * @return Whether the content slug is used */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isContentSlugAvailable(slug: string): boolean { // By default the slug should be available as it's currently generated as a unique value for each h5p content. return true; } /** * Check whether a library is a patched version of the one installed. * * @param library Library to check. * @param dbData Installed library. If not supplied it will be calculated. * @return Promise resolved with boolean: whether it's a patched library. */ async isPatchedLibrary(library: CoreH5PLibraryBasicDataWithPatch, dbData?: CoreH5PLibraryParsedDBRecord): Promise<boolean> { if (!dbData) { dbData = await this.getLibraryByData(library); } return library.patchVersion > dbData.patchversion; } /** * Convert list of library parameter values to csv. * * @param libraryData Library data as found in library.json files. * @param key Key that should be found in libraryData. * @param searchParam The library parameter (Default: 'path'). * @return Library parameter values separated by ', ' */ libraryParameterValuesToCsv(libraryData: CoreH5PLibraryBeingSaved, key: string, searchParam: string = 'path'): string { if (typeof libraryData[key] != 'undefined') { const parameterValues: string[] = []; libraryData[key].forEach((file) => { for (const index in file) { if (index === searchParam) { parameterValues.push(file[index]); } } }); return parameterValues.join(','); } return ''; } /** * Load addon libraries. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the addon libraries. */ async loadAddons(siteId?: string): Promise<CoreH5PLibraryAddonData[]> { const db = await CoreSites.getSiteDb(siteId); const query = 'SELECT l1.id AS libraryId, l1.machinename AS machineName, ' + 'l1.majorversion AS majorVersion, l1.minorversion AS minorVersion, ' + 'l1.patchversion AS patchVersion, l1.addto AS addTo, ' + 'l1.preloadedjs AS preloadedJs, l1.preloadedcss AS preloadedCss ' + 'FROM ' + LIBRARIES_TABLE_NAME + ' l1 ' + 'JOIN ' + LIBRARIES_TABLE_NAME + ' l2 ON l1.machinename = l2.machinename AND (' + 'l1.majorversion < l2.majorversion OR (l1.majorversion = l2.majorversion AND ' + 'l1.minorversion < l2.minorversion)) ' + 'WHERE l1.addto IS NOT NULL AND l2.machinename IS NULL'; const result = await db.execute(query); const addons: CoreH5PLibraryAddonData[] = []; for (let i = 0; i < result.rows.length; i++) { addons.push(this.parseLibAddonData(result.rows.item(i))); } return addons; } /** * Load content data from DB. * * @param id Content ID. * @param fileUrl H5P file URL. Required if id is not provided. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the content data. */ async loadContent(id?: number, fileUrl?: string, siteId?: string): Promise<CoreH5PFrameworkContentData> { siteId = siteId || CoreSites.getCurrentSiteId(); let contentData: CoreH5PContentDBRecord; if (id) { contentData = await this.getContentData(id, siteId); } else if (fileUrl) { contentData = await this.getContentDataByUrl(fileUrl, siteId); } else { throw new CoreError('No id or fileUrl supplied to loadContent.'); } // Load the main library data. const libData = await this.getLibraryById(contentData.mainlibraryid, siteId); // Map the values to the names used by the H5P core (it's the same Moodle web does). const content = { id: contentData.id, params: contentData.jsoncontent, embedType: 'iframe', // Always use iframe. disable: null, folderName: contentData.foldername, title: libData.title, slug: CoreH5PCore.slugify(libData.title) + '-' + contentData.id, filtered: contentData.filtered, libraryId: libData.id, libraryName: libData.machinename, libraryMajorVersion: libData.majorversion, libraryMinorVersion: libData.minorversion, libraryEmbedTypes: libData.embedtypes, libraryFullscreen: libData.fullscreen, metadata: null, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const params = CoreTextUtils.parseJSON<any>(contentData.jsoncontent); if (!params.metadata) { params.metadata = {}; } content.metadata = params.metadata; content.params = JSON.stringify(typeof params.params != 'undefined' && params.params != null ? params.params : params); return content; } /** * Load dependencies for the given content of the given type. * * @param id Content ID. * @param type The dependency type. * @return Content dependencies, indexed by machine name. */ async loadContentDependencies( id: number, type?: string, siteId?: string, ): Promise<{[machineName: string]: CoreH5PContentDependencyData}> { const db = await CoreSites.getSiteDb(siteId); let query = 'SELECT hl.id AS libraryId, hl.machinename AS machineName, ' + 'hl.majorversion AS majorVersion, hl.minorversion AS minorVersion, ' + 'hl.patchversion AS patchVersion, hl.preloadedcss AS preloadedCss, ' + 'hl.preloadedjs AS preloadedJs, hcl.dropcss AS dropCss, ' + 'hcl.dependencytype as dependencyType ' + 'FROM ' + CONTENTS_LIBRARIES_TABLE_NAME + ' hcl ' + 'JOIN ' + LIBRARIES_TABLE_NAME + ' hl ON hcl.libraryid = hl.id ' + 'WHERE hcl.h5pid = ?'; const queryArgs: (string | number)[] = []; queryArgs.push(id); if (type) { query += ' AND hcl.dependencytype = ?'; queryArgs.push(type); } query += ' ORDER BY hcl.weight'; const result = await db.execute(query, queryArgs); const dependencies: {[machineName: string]: CoreH5PContentDependencyData} = {}; for (let i = 0; i < result.rows.length; i++) { const dependency = result.rows.item(i); dependencies[dependency.machineName] = dependency; } return dependencies; } /** * Loads a library and its dependencies. * * @param machineName The library's machine name. * @param majorVersion The library's major version. * @param minorVersion The library's minor version. * @param siteId The site ID. If not defined, current site. * @return Promise resolved with the library data. */ async loadLibrary( machineName: string, majorVersion: number, minorVersion: number, siteId?: string, ): Promise<CoreH5PLibraryData> { // First get the library data from DB. const library = await this.getLibrary(machineName, majorVersion, minorVersion, siteId); const libraryData: CoreH5PLibraryData = { libraryId: library.id, title: library.title, machineName: library.machinename, majorVersion: library.majorversion, minorVersion: library.minorversion, patchVersion: library.patchversion, runnable: library.runnable, fullscreen: library.fullscreen, embedTypes: library.embedtypes, preloadedJs: library.preloadedjs || undefined, preloadedCss: library.preloadedcss || undefined, dropLibraryCss: library.droplibrarycss || undefined, semantics: library.semantics || undefined, preloadedDependencies: [], dynamicDependencies: [], editorDependencies: [], }; // Now get the dependencies. const sql = 'SELECT hl.id, hl.machinename, hl.majorversion, hl.minorversion, hll.dependencytype ' + 'FROM ' + LIBRARY_DEPENDENCIES_TABLE_NAME + ' hll ' + 'JOIN ' + LIBRARIES_TABLE_NAME + ' hl ON hll.requiredlibraryid = hl.id ' + 'WHERE hll.libraryid = ? ' + 'ORDER BY hl.id ASC'; const sqlParams = [ library.id, ]; const db = await CoreSites.getSiteDb(siteId); const result = await db.execute(sql, sqlParams); for (let i = 0; i < result.rows.length; i++) { const dependency: LibraryDependency = result.rows.item(i); const key = dependency.dependencytype + 'Dependencies'; libraryData[key].push({ machineName: dependency.machinename, majorVersion: dependency.majorversion, minorVersion: dependency.minorversion, }); } return libraryData; } /** * Parse library addon data. * * @param library Library addon data. * @return Parsed library. */ parseLibAddonData(library: LibraryAddonDBData): CoreH5PLibraryAddonData { const parsedLib = <CoreH5PLibraryAddonData> library; parsedLib.addTo = CoreTextUtils.parseJSON<CoreH5PLibraryAddTo | null>(library.addTo, null); return parsedLib; } /** * Parse library DB data. * * @param library Library DB data. * @return Parsed library. */ protected parseLibDBData(library: CoreH5PLibraryDBRecord): CoreH5PLibraryParsedDBRecord { return Object.assign(library, { semantics: library.semantics ? CoreTextUtils.parseJSON(library.semantics, null) : null, addto: library.addto ? CoreTextUtils.parseJSON(library.addto, null) : null, metadatasettings: library.metadatasettings ? CoreTextUtils.parseJSON(library.metadatasettings, null) : null, }); } /** * Resets marked user data for the given content. * * @param contentId Content ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars async resetContentUserData(conentId: number, siteId?: string): Promise<void> { // Currently, we do not store user data for a content. } /** * Stores hash keys for cached assets, aggregated JavaScripts and stylesheets, and connects it to libraries so that we * know which cache file to delete when a library is updated. * * @param key Hash key for the given libraries. * @param libraries List of dependencies used to create the key. * @param folderName The name of the folder that contains the H5P. * @param siteId The site ID. * @return Promise resolved when done. */ async saveCachedAssets( hash: string, dependencies: {[machineName: string]: CoreH5PContentDependencyData}, folderName: string, siteId?: string, ): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await Promise.all(Object.keys(dependencies).map(async (key) => { const data: Partial<CoreH5PLibraryCachedAssetsDBRecord> = { hash: key, libraryid: dependencies[key].libraryId, foldername: folderName, }; await db.insertRecord(LIBRARIES_CACHEDASSETS_TABLE_NAME, data); })); } /** * Save library data in DB. * * @param libraryData Library data to save. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async saveLibraryData(libraryData: CoreH5PLibraryBeingSaved, siteId?: string): Promise<void> { // Some special properties needs some checking and converting before they can be saved. const preloadedJS = this.libraryParameterValuesToCsv(libraryData, 'preloadedJs', 'path'); const preloadedCSS = this.libraryParameterValuesToCsv(libraryData, 'preloadedCss', 'path'); const dropLibraryCSS = this.libraryParameterValuesToCsv(libraryData, 'dropLibraryCss', 'machineName'); if (typeof libraryData.semantics == 'undefined') { libraryData.semantics = []; } if (typeof libraryData.fullscreen == 'undefined') { libraryData.fullscreen = 0; } let embedTypes = ''; if (typeof libraryData.embedTypes != 'undefined') { embedTypes = libraryData.embedTypes.join(', '); } const site = await CoreSites.getSite(siteId); const db = site.getDb(); const data: Partial<CoreH5PLibraryDBRecord> = { title: libraryData.title, machinename: libraryData.machineName, majorversion: libraryData.majorVersion, minorversion: libraryData.minorVersion, patchversion: libraryData.patchVersion, runnable: libraryData.runnable, fullscreen: libraryData.fullscreen, embedtypes: embedTypes, preloadedjs: preloadedJS, preloadedcss: preloadedCSS, droplibrarycss: dropLibraryCSS, semantics: typeof libraryData.semantics != 'undefined' ? JSON.stringify(libraryData.semantics) : null, addto: typeof libraryData.addTo != 'undefined' ? JSON.stringify(libraryData.addTo) : null, metadatasettings: typeof libraryData.metadataSettings != 'undefined' ? CoreH5PMetadata.boolifyAndEncodeSettings(libraryData.metadataSettings) : null, }; if (libraryData.libraryId) { data.id = libraryData.libraryId; } await db.insertRecord(LIBRARIES_TABLE_NAME, data); if (!data.id) { // New library. Get its ID. const entry = await db.getRecord<CoreH5PLibraryDBRecord>(LIBRARIES_TABLE_NAME, data); libraryData.libraryId = entry.id; } else { // Updated libary. Remove old dependencies. await this.deleteLibraryDependencies(data.id, site.getId()); } } /** * Save what libraries a library is depending on. * * @param libraryId Library Id for the library we're saving dependencies for. * @param dependencies List of dependencies as associative arrays containing machineName, majorVersion, minorVersion. * @param dependencytype The type of dependency. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async saveLibraryDependencies( libraryId: number, dependencies: CoreH5PLibraryBasicData[], dependencyType: string, siteId?: string, ): Promise<void> { const db = await CoreSites.getSiteDb(siteId); await Promise.all(dependencies.map(async (dependency) => { // Get the ID of the library. const dependencyId = await this.getLibraryIdByData(dependency, siteId); // Create the relation. const entry: Partial<CoreH5PLibraryDependencyDBRecord> = { libraryid: libraryId, requiredlibraryid: dependencyId, dependencytype: dependencyType, }; await db.insertRecord(LIBRARY_DEPENDENCIES_TABLE_NAME, entry); })); } /** * Saves what libraries the content uses. * * @param id Id identifying the package. * @param librariesInUse List of libraries the content uses. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async saveLibraryUsage( id: number, librariesInUse: {[key: string]: CoreH5PContentDepsTreeDependency}, siteId?: string, ): Promise<void> { const db = await CoreSites.getSiteDb(siteId); // Calculate the CSS to drop. const dropLibraryCssList: Record<string, string> = {}; for (const key in librariesInUse) { const dependency = librariesInUse[key]; if ('dropLibraryCss' in dependency.library && dependency.library.dropLibraryCss) { const split = dependency.library.dropLibraryCss.split(', '); split.forEach((css) => { dropLibraryCssList[css] = css; }); } } // Now save the uusage. await Promise.all(Object.keys(librariesInUse).map((key) => { const dependency = librariesInUse[key]; const data: Partial<CoreH5PContentsLibraryDBRecord> = { h5pid: id, libraryid: dependency.library.libraryId, dependencytype: dependency.type, dropcss: dropLibraryCssList[dependency.library.machineName] ? 1 : 0, weight: dependency.weight, }; return db.insertRecord(CONTENTS_LIBRARIES_TABLE_NAME, data); })); } /** * Save content data in DB and clear cache. * * @param content Content to save. * @param folderName The name of the folder that contains the H5P. * @param fileUrl The online URL of the package. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with content ID. */ async updateContent(content: CoreH5PContentBeingSaved, folderName: string, fileUrl: string, siteId?: string): Promise<number> { const db = await CoreSites.getSiteDb(siteId); // If the libraryid declared in the package is empty, get the latest version. if (content.library && typeof content.library.libraryId == 'undefined') { const mainLibrary = await this.getLatestLibraryVersion(content.library.machineName, siteId); content.library.libraryId = mainLibrary.id; } const data: Partial<CoreH5PContentDBRecord> = { id: undefined, jsoncontent: content.params, mainlibraryid: content.library?.libraryId, timemodified: Date.now(), filtered: null, foldername: folderName, fileurl: fileUrl, timecreated: undefined, }; if (typeof content.id != 'undefined') { data.id = content.id; } else { data.timecreated = data.timemodified; } await db.insertRecord(CONTENT_TABLE_NAME, data); if (!data.id) { // New content. Get its ID. const entry = await db.getRecord<CoreH5PContentDBRecord>(CONTENT_TABLE_NAME, data); content.id = entry.id; } return content.id!; } /** * This will update selected fields on the given content. * * @param id Content identifier. * @param fields Object with the fields to update. * @param siteId Site ID. If not defined, current site. */ async updateContentFields(id: number, fields: Partial<CoreH5PContentDBRecord>, siteId?: string): Promise<void> { const db = await CoreSites.getSiteDb(siteId); const data = Object.assign({}, fields); await db.updateRecords(CONTENT_TABLE_NAME, data, { id }); } } /** * Content data returned by loadContent. */ export type CoreH5PFrameworkContentData = { id: number; // The id of the content. params: string; // The content in json format. embedType: string; // Embed type to use. disable: number | null; // H5P Button display options. folderName: string; // Name of the folder that contains the contents. title: string; // Main library's title. slug: string; // Lib title and ID slugified. filtered: string | null; // Filtered version of json_content. libraryId: number; // Main library's ID. libraryName: string; // Main library's machine name. libraryMajorVersion: number; // Main library's major version. libraryMinorVersion: number; // Main library's minor version. libraryEmbedTypes: string; // Main library's list of supported embed types. libraryFullscreen: number; // Main library's display fullscreen button. metadata: unknown; // Content metadata. }; export type CoreH5PLibraryParsedDBRecord = Omit<CoreH5PLibraryDBRecord, 'semantics'|'addto'|'metadatasettings'> & { semantics: CoreH5PSemantics[] | null; addto: CoreH5PLibraryAddTo | null; metadatasettings: CoreH5PLibraryMetadataSettings | null; }; type LibraryDependency = { id: number; machinename: string; majorversion: number; minorversion: number; dependencytype: string; }; type LibraryAddonDBData = Omit<CoreH5PLibraryAddonData, 'addTo'> & { addTo: string; };
the_stack
import React, { useContext, useEffect, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { useActor } from "@xstate/react"; import ReCAPTCHA from "react-google-recaptcha"; import { Button } from "components/ui/Button"; import { OuterPanel, Panel } from "components/ui/Panel"; import { Section, useScrollIntoView } from "lib/utils/hooks/useScrollIntoView"; import * as Auth from "features/auth/lib/Provider"; import { Context } from "features/game/GameProvider"; import { Modal } from "react-bootstrap"; import { Share } from "./Share"; import { HowToPlay } from "./howToPlay/HowToPlay"; import { Settings } from "./Settings"; import mobileMenu from "assets/icons/hamburger_menu.png"; import questionMark from "assets/icons/expression_confused.png"; import radish from "assets/icons/radish.png"; import town from "assets/icons/town.png"; import water from "assets/icons/expression_working.png"; import timer from "assets/icons/timer.png"; import wood from "assets/resources/wood.png"; import leftArrow from "assets/icons/arrow_left.png"; import close from "assets/icons/close.png"; import goblin from "assets/npcs/goblin_head.png"; import { useIsNewFarm } from "../lib/onboarding"; import { GoblinVillageModal } from "features/farming/town/components/GoblinVillageModal"; /** * TODO: * create menu level parent mapping if more than 2 levels. * currently only 1 level deep so setMenuLevel("ROOT") satisfies */ enum MENU_LEVELS { ROOT = "root", MAP = "map", VIEW = "view", } export const Menu = () => { const { authService } = useContext(Auth.Context); const { gameService } = useContext(Context); const [authState] = useActor(authService); const [gameState] = useActor(gameService); const [menuOpen, setMenuOpen] = useState(false); const [scrollIntoView] = useScrollIntoView(); const [showShareModal, setShowShareModal] = useState(false); const [showLogoutModal, setShowSettings] = useState(false); const [showGoblinModal, setShowGoblinModal] = useState(false); const [showHowToPlay, setShowHowToPlay] = useState(useIsNewFarm()); const [showCaptcha, setShowCaptcha] = useState(false); const [farmURL, setFarmURL] = useState(""); const [menuLevel, setMenuLevel] = useState(MENU_LEVELS.ROOT); const ref = useRef<HTMLDivElement>(null); const navigate = useNavigate(); const handleMenuClick = () => { setMenuOpen(!menuOpen); }; const handleNavigationClick = (section: Section) => { scrollIntoView(section); setMenuOpen(false); }; const handleHowToPlay = () => { setShowHowToPlay(true); setMenuOpen(false); }; const handleShareClick = () => { setShowShareModal(true); setMenuOpen(false); }; const handleSettingsClick = () => { setShowSettings(true); setMenuOpen(false); }; const handleClick = (e: Event) => { // inside click if (ref?.current?.contains(e.target as Node)) return; // outside click setMenuOpen(false); }; const syncOnChain = async () => { setShowCaptcha(true); }; const onCaptchaSolved = async (captcha: string | null) => { await new Promise((res) => setTimeout(res, 1000)); gameService.send("SYNC", { captcha }); setMenuOpen(false); setShowCaptcha(false); }; const autosave = async () => { gameService.send("SAVE"); }; const goBack = () => { const res = authService.send("RETURN"); // fallback incase state doesn't change // [TODO]: add proper transitions in both machines if (!res.changed) { navigate("/"); } }; const visitFarm = () => { authService.send("EXPLORE"); }; // Handles closing the menu if someone clicks outside useEffect(() => { document.addEventListener("mousedown", handleClick); document.addEventListener("touchstart", handleClick); const _farmURL = window.location.href.replace("/farm", "/visit"); setFarmURL(_farmURL); return () => { document.removeEventListener("mousedown", handleClick); document.removeEventListener("touchstart", handleClick); }; }, []); return ( <div ref={ref} className="w-5/12 sm:w-60 fixed top-2 left-2 z-50 shadow-lg"> <OuterPanel> <div className="flex justify-center p-1"> <Button className="mr-2 bg-brown-200 active:bg-brown-200" onClick={handleMenuClick} > <img className="md:hidden w-6" src={mobileMenu} alt="hamburger-menu" /> <span className="hidden md:flex">Menu</span> </Button> {!gameState.matches("readonly") && ( <Button onClick={autosave} disabled={gameState.matches("autosaving") ? true : false} > {gameState.matches("autosaving") ? ( <img src={timer} className="animate-pulsate" alt="saving" /> ) : ( <span>Save</span> )} </Button> )} {gameState.matches("readonly") && ( <Button onClick={goBack}> <span>Back</span> </Button> )} </div> <div className={`transition-all ease duration-200 ${ menuOpen ? "max-h-100" : "max-h-0" }`} > <ul className={`list-none pt-1 transition-all ease duration-200 origin-top ${ menuOpen ? "scale-y-1" : "scale-y-0" }`} > {/* Root menu */} {menuLevel === MENU_LEVELS.ROOT && ( <> {!gameState.matches("readonly") && ( <li className="p-1"> <Button onClick={syncOnChain}> <span className="sm:text-sm">Sync on chain</span> </Button> </li> )} <li className="p-1 flex"> <Button onClick={handleHowToPlay}> <span className="sm:text-sm flex-1">How to play</span> <img src={questionMark} className="w-3 ml-2" alt="question-mark" /> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={() => setMenuLevel(MENU_LEVELS.MAP)} > <span className="sm:text-sm flex-1">Map</span> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={() => setMenuLevel(MENU_LEVELS.VIEW)} > <span className="sm:text-sm flex-1">Community</span> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={handleSettingsClick} > <span className="sm:text-sm flex-1">Settings</span> </Button> </li> </> )} {/* Back button when not Root */} {menuLevel !== MENU_LEVELS.ROOT && ( <li className="p-1"> <Button onClick={() => setMenuLevel(MENU_LEVELS.ROOT)}> <img src={leftArrow} className="w-4 mr-2" alt="left" /> </Button> </li> )} {/* Map menu */} {menuLevel === MENU_LEVELS.MAP && ( <> {!gameState.matches("readonly") && ( <li className="p-1"> <Button className="flex justify-between" onClick={() => setShowGoblinModal(true)} > <span className="sm:text-sm flex-1">Goblin Village</span> <img src={goblin} className="w-6 ml-2" alt="town" /> </Button> </li> )} <li className="p-1"> <Button className="flex justify-between" onClick={() => handleNavigationClick(Section.Town)} > <span className="sm:text-sm flex-1">Town</span> <img src={town} className="w-6 ml-2" alt="town" /> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={() => handleNavigationClick(Section.Crops)} > <span className="sm:text-sm flex-1">Crops</span> <img src={radish} className="w-4 ml-2" alt="crop" /> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={() => handleNavigationClick(Section.Water)} > <span className="sm:text-sm flex-1">Water</span> <img src={water} className="w-4 ml-2" alt="water" /> </Button> </li> <li className="p-1"> <Button className="flex justify-between" onClick={() => handleNavigationClick(Section.Forest)} > <span className="sm:text-sm flex-1">Forest</span> <img src={wood} className="w-4 ml-2" alt="wood" /> </Button> </li> </> )} {/* View menu */} {menuLevel === MENU_LEVELS.VIEW && ( <> <li className="p-1"> <Button onClick={handleShareClick}> <span className="sm:text-sm">Share</span> </Button> </li> {!gameState.matches("readonly") && ( <li className="p-1"> <Button onClick={visitFarm}> <span className="sm:text-sm">Visit Farm</span> </Button> </li> )} </> )} </ul> </div> </OuterPanel> <Share isOpen={showShareModal} onClose={() => setShowShareModal(false)} farmURL={farmURL} /> <HowToPlay isOpen={showHowToPlay} onClose={() => setShowHowToPlay(false)} /> <Settings isOpen={showLogoutModal} onClose={() => setShowSettings(false)} /> {showCaptcha && ( <Modal show={showCaptcha} onHide={() => setShowCaptcha(false)} centered> <Panel> <img src={close} className="h-6 top-3 right-4 absolute cursor-pointer" alt="Close Logout Confirmation Modal" onClick={() => setShowCaptcha(false)} /> <ReCAPTCHA sitekey="6Lfqm6MeAAAAAFS5a0vwAfTGUwnlNoHziyIlOl1s" onChange={onCaptchaSolved} onExpired={() => setShowCaptcha(false)} className="w-full m-4 flex items-center justify-center" /> </Panel> </Modal> )} <Modal centered show={showGoblinModal} onHide={() => setShowGoblinModal(false)} > <GoblinVillageModal onClose={() => setShowGoblinModal(false)} /> </Modal> </div> ); };
the_stack
import * as React from 'react'; import { IPropertyFieldFontPickerPropsInternal } from './PropertyFieldFontPicker'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import GuidHelper from './GuidHelper'; /** * @interface * PropertyFieldFontPickerHost properties interface * */ export interface IPropertyFieldFontPickerHostProps extends IPropertyFieldFontPickerPropsInternal { } /** * @interface * PropertyFieldFontPickerHost state interface * */ export interface IPropertyFieldFontPickerHostState { isOpen: boolean; isHoverDropdown?: boolean; hoverFont?: string; selectedFont?: string; safeSelectedFont?: string; errorMessage?: string; } /** * @interface * Define a safe font object * */ interface ISafeFont { Name: string; SafeValue: string; } /** * @class * Renders the controls for PropertyFieldFontPicker component */ export default class PropertyFieldFontPickerHost extends React.Component<IPropertyFieldFontPickerHostProps, IPropertyFieldFontPickerHostState> { /** * @var * Defines the font series */ private fonts: ISafeFont[] = [ {Name: "Andale Mono", SafeValue: '"Andale Mono",AndaleMono,monospace'}, {Name: "Arial", SafeValue: 'Arial,""Helvetica Neue",Helvetica,sans-serif'}, {Name: "Arial Black", SafeValue: '"Arial Black","Arial Bold",Gadget,sans-serif'}, {Name: "Arial Narrow", SafeValue: '"Arial Narrow",Arial,sans-serif'}, {Name: "Arial Rounded MT Bold", SafeValue: '"Arial Rounded MT Bold","Helvetica Rounded",Arial,sans-serif'}, {Name: "Avant Garde", SafeValue: '"Avant Garde",Avantgarde,"Century Gothic",CenturyGothic,AppleGothic,sans-serif'}, {Name: "Baskerville", SafeValue: 'Baskerville,"Baskerville Old Face","Hoefler Text",Garamond,"Times New Roman",serif'}, {Name: "Big Caslon", SafeValue: '"Big Caslon","Book Antiqua","Palatino Linotype",Georgia,serif'}, {Name: "Bodoni MT", SafeValue: '"Bodoni MT",Didot,"Didot LT STD","Hoefler Text",Garamond,"Times New Roman",serif'}, {Name: "Book Antiqua", SafeValue: '"Book Antiqua",Palatino,"Palatino Linotype","Palatino LT STD",Georgia,serif'}, {Name: "Brush Script MT", SafeValue: '"Brush Script MT",cursive'}, {Name: "Calibri", SafeValue: 'Calibri,Candara,Segoe,"Segoe UI",Optima,Arial,sans-serif'}, {Name: "Calisto MT", SafeValue: '"Calisto MT","Bookman Old Style",Bookman,"Goudy Old Style",Garamond,"Hoefler Text","Bitstream Charter",Georgia,serif'}, {Name: "Cambria", SafeValue: 'Cambria,Georgia,serif'}, {Name: "Candara", SafeValue: 'Candara,Calibri,Segoe,"Segoe UI",Optima,Arial,sans-serif'}, {Name: "Century Gothic", SafeValue: '"Century Gothic",CenturyGothic,AppleGothic,sans-serif'}, {Name: "Consolas", SafeValue: 'Consolas,monaco,monospace'}, {Name: "Copperplate", SafeValue: 'Copperplate,"Copperplate Gothic Light",fantasy'}, {Name: "Courier New", SafeValue: '"Courier New",Courier,"Lucida Sans Typewriter","Lucida Typewriter",monospace'}, {Name: "Didot", SafeValue: 'Didot,"Didot LT STD","Hoefler Text",Garamond,"Times New Roman",serif'}, {Name: "Franklin Gothic Medium", SafeValue: '"Franklin Gothic Medium","Franklin Gothic","ITC Franklin Gothic",Arial,sans-serif'}, {Name: "Futura", SafeValue: 'Futura,"Trebuchet MS",Arial,sans-serif'}, {Name: "Garamond", SafeValue: 'Garamond,Baskerville,"Baskerville Old Face","Hoefler Text","Times New Roman",serif'}, {Name: "Geneva", SafeValue: 'Geneva,Tahoma,Verdana,sans-serif'}, {Name: "Georgia", SafeValue: 'Georgia,Times,"Times New Roman",serif'}, {Name: "Gill Sans", SafeValue: '"Gill Sans","Gill Sans MT",Calibri,sans-serif'}, {Name: "Goudy Old Style", SafeValue: '"Goudy Old Style",Garamond,"Big Caslon","Times New Roman",serif'}, {Name: "Helvetica", SafeValue: '"Helvetica Neue",Helvetica,Arial,sans-serif'}, {Name: "Hoefler Text", SafeValue: '"Hoefler Text","Baskerville Old Face",Garamond,"Times New Roman",serif'}, {Name: "Impact", SafeValue: 'Impact,Haettenschweiler,"Franklin Gothic Bold",Charcoal,"Helvetica Inserat","Bitstream Vera Sans Bold","Arial Black","sans serif"'}, {Name: "Lucida Bright", SafeValue: '"Lucida Bright",Georgia,serif'}, {Name: "Lucida Console", SafeValue: '"Lucida Console","Lucida Sans Typewriter",monaco,"Bitstream Vera Sans Mono",monospace'}, {Name: "Lucida Grande", SafeValue: '"Lucida Grande","Lucida Sans Unicode","Lucida Sans",Geneva,Verdana,sans-serif'}, {Name: "Lucida Sans Typewriter", SafeValue: '"Lucida Sans Typewriter","Lucida Console",monaco,"Bitstream Vera Sans Mono",monospace'}, {Name: "Monaco", SafeValue: 'monaco,Consolas,"Lucida Console",monospace'}, {Name: "Optima", SafeValue: 'Optima,Segoe,"Segoe UI",Candara,Calibri,Arial,sans-serif'}, {Name: "Palatino", SafeValue: 'Palatino,"Palatino Linotype","Palatino LT STD","Book Antiqua",Georgia,serif'}, {Name: "Papyrus", SafeValue: 'Papyrus,fantasy'}, {Name: "Perpetua", SafeValue: 'Perpetua,Baskerville,"Big Caslon","Palatino Linotype",Palatino,"URW Palladio L","Nimbus Roman No9 L",serif'}, {Name: "Segoe UI", SafeValue: '"Segoe UI",Frutiger,"Frutiger Linotype","Dejavu Sans","Helvetica Neue",Arial,sans-serif'}, {Name: "Rockwell", SafeValue: 'Rockwell,"Courier Bold",Courier,Georgia,Times,"Times New Roman",serif'}, {Name: "Rockwell Extra Bold", SafeValue: '"Rockwell Extra Bold","Rockwell Bold",monospace'}, {Name: "Tahoma", SafeValue: 'Tahoma,Verdana,Segoe,sans-serif'}, {Name: "Times New Roman", SafeValue: 'TimesNewRoman,"Times New Roman",Times,Baskerville,Georgia,serif'}, {Name: "Trebuchet MS", SafeValue: '"Trebuchet MS","Lucida Grande","Lucida Sans Unicode","Lucida Sans",Tahoma,sans-serif'}, {Name: "Verdana", SafeValue: 'Verdana,Geneva,sans-serif'} ]; private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; private _key: string; /** * @function * Constructor */ constructor(props: IPropertyFieldFontPickerHostProps) { super(props); //Bind the current object to the external called onSelectDate method this.onOpenDialog = this.onOpenDialog.bind(this); this.toggleHover = this.toggleHover.bind(this); this.toggleHoverLeave = this.toggleHoverLeave.bind(this); this.onClickFont = this.onClickFont.bind(this); this.onFontDropdownChanged = this.onFontDropdownChanged.bind(this); this.mouseEnterDropDown = this.mouseEnterDropDown.bind(this); this.mouseLeaveDropDown = this.mouseLeaveDropDown.bind(this); this._key = GuidHelper.getGuid(); //Init the state this.state = { isOpen: false, isHoverDropdown: false, errorMessage: '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); //Inits the default value if (props.initialValue != null && props.initialValue != '') { for (var i = 0; i < this.fonts.length; i++) { var font = this.fonts[i]; //Checks if we must use the font name or the font safe value if (props.useSafeFont === false && props.initialValue === font.Name) { this.state.selectedFont = font.Name; this.state.safeSelectedFont = font.SafeValue; } else if (props.initialValue === font.SafeValue) { this.state.selectedFont = font.Name; this.state.safeSelectedFont = font.SafeValue; } } } } /** * @function * Function to refresh the Web Part properties */ private changeSelectedFont(newValue: string): void { this.delayedValidate(newValue); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValue, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(this.props.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.props.onPropertyChange && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * @function * Function to open the dialog */ private onOpenDialog(): void { if (this.props.disabled === true) return; this.state.isOpen = !this.state.isOpen; this.setState(this.state); } /** * @function * Mouse is hover a font */ private toggleHover(element?: any) { var hoverFont: string = element.currentTarget.textContent; this.state.hoverFont = hoverFont; this.setState(this.state); } /** * @function * Mouse is leaving a font */ private toggleHoverLeave(element?: any) { this.state.hoverFont = ''; this.setState(this.state); } /** * @function * Mouse is hover the fontpicker */ private mouseEnterDropDown(element?: any) { this.state.isHoverDropdown = true; this.setState(this.state); } /** * @function * Mouse is leaving the fontpicker */ private mouseLeaveDropDown(element?: any) { this.state.isHoverDropdown = false; this.setState(this.state); } /** * @function * User clicked on a font */ private onClickFont(element?: any) { var clickedFont: string = element.currentTarget.textContent; this.state.selectedFont = clickedFont; this.state.safeSelectedFont = this.getSafeFont(clickedFont); this.onOpenDialog(); if (this.props.useSafeFont === false) { this.changeSelectedFont(this.state.selectedFont); } else { this.changeSelectedFont(this.state.safeSelectedFont); } } /** * @function * Gets a safe font value from a font name */ private getSafeFont(fontName: string): string { for (var i = 0; i < this.fonts.length; i++) { var font = this.fonts[i]; if (font.Name === fontName) return font.SafeValue; } return ''; } /** * @function * The font dropdown selected value changed (used when the previewFont property equals false) */ private onFontDropdownChanged(option: IDropdownOption, index?: number): void { this.changeSelectedFont(option.key as string); } /** * @function * Renders the control */ public render(): JSX.Element { if (this.props.previewFonts === false) { //If the user don't want to use the preview font picker, //we're building a classical drop down picker var dropDownOptions: IDropdownOption[] = []; var selectedKey: string; this.fonts.map((font: ISafeFont) => { var isSelected: boolean = false; if (this.props.useSafeFont === false && font.Name == this.props.initialValue) { isSelected = true; selectedKey = font.Name; } else if (font.SafeValue == this.props.initialValue) { isSelected = true; selectedKey = font.SafeValue; } dropDownOptions.push( { key: this.props.useSafeFont === false ? font.Name : font.SafeValue, text: font.Name, isSelected: isSelected } ); }); return ( <div> <Dropdown label={this.props.label} options={dropDownOptions} selectedKey={selectedKey} onChanged={this.onFontDropdownChanged} disabled={this.props.disabled} /> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } else { //User wants to use the preview font picker, so just build it var fontSelect = { fontSize: '16px', width: '100%', position: 'relative', display: 'inline-block', zoom: 1 }; var dropdownColor = '1px solid #c8c8c8'; if (this.props.disabled === true) dropdownColor = '1px solid #f4f4f4'; else if (this.state.isOpen === true) dropdownColor = '1px solid #3091DE'; else if (this.state.isHoverDropdown === true) dropdownColor = '1px solid #767676'; var fontSelectA = { backgroundColor: this.props.disabled === true ? '#f4f4f4' : '#fff', borderRadius : '0px', backgroundClip : 'padding-box', border: dropdownColor, display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', position: 'relative', height: '26px', lineHeight: '26px', padding: '0 0 0 8px', color: this.props.disabled === true ? '#a6a6a6' : '#444', textDecoration: 'none', cursor: this.props.disabled === true ? 'default' : 'pointer' }; var fontSelectASpan = { marginRight: '26px', display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', lineHeight: '1.8', textOverflow: 'ellipsis', cursor: this.props.disabled === true ? 'default' : 'pointer', fontFamily: this.state.safeSelectedFont != null && this.state.safeSelectedFont != '' ? this.state.safeSelectedFont : 'Arial', fontWeight: 400 }; var fontSelectADiv = { borderRadius : '0 0px 0px 0', backgroundClip : 'padding-box', border: '0px', position: 'absolute', right: '0', top: '0', display: 'block', height: '100%', width: '22px' }; var fontSelectADivB = { display: 'block', width: '100%', height: '100%', cursor: this.props.disabled === true ? 'default' : 'pointer', marginTop: '2px' }; var fsDrop = { background: '#fff', border: '1px solid #aaa', borderTop: '0', position: 'absolute', top: '29px', left: '0', width: 'calc(100% - 2px)', //boxShadow: '0 4px 5px rgba(0,0,0,.15)', zIndex: 999, display: this.state.isOpen ? 'block' : 'none' }; var fsResults = { margin: '0 4px 4px 0', maxHeight: '190px', width: 'calc(100% - 4px)', padding: '0 0 0 4px', position: 'relative', overflowX: 'hidden', overflowY: 'auto' }; var carret: string = this.state.isOpen ? 'ms-Icon ms-Icon--ChevronUp' : 'ms-Icon ms-Icon--ChevronDown'; //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <div style={fontSelect}> <a style={fontSelectA} onClick={this.onOpenDialog} onMouseEnter={this.mouseEnterDropDown} onMouseLeave={this.mouseLeaveDropDown} role="menuitem"> <span style={fontSelectASpan}>{this.state.selectedFont}</span> <div style={fontSelectADiv}> <i style={fontSelectADivB} className={carret}></i> </div> </a> <div style={fsDrop}> <ul style={fsResults}> {this.fonts.map((font: ISafeFont, index: number) => { var backgroundColor: string = 'transparent'; if (this.state.selectedFont === font.Name) backgroundColor = '#c7e0f4'; else if (this.state.hoverFont === font.Name) backgroundColor = '#eaeaea'; var innerStyle = { lineHeight: '80%', padding: '7px 7px 8px', margin: '0', listStyle: 'none', fontSize: '18px', fontFamily: font.SafeValue, backgroundColor: backgroundColor, cursor: 'pointer' }; return ( <li value={font.Name} key={this._key + '-fontpicker-' + index} role="menuitem" onMouseEnter={this.toggleHover} onClick={this.onClickFont} onMouseLeave={this.toggleHoverLeave} style={innerStyle}>{font.Name}</li> ); }) } </ul> </div> </div> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } } }
the_stack
import { AuthClientErrorCode, FirebaseAuthError, ErrorInfo } from '../utils/error'; import * as util from '../utils/index'; import * as validator from '../utils/validator'; import { DecodedToken, decodeJwt, JwtError, JwtErrorCode, EmulatorSignatureVerifier, PublicKeySignatureVerifier, ALGORITHM_RS256, SignatureVerifier, } from '../utils/jwt'; import { App } from '../app/index'; /** * Interface representing a decoded Firebase ID token, returned from the * {@link BaseAuth.verifyIdToken} method. * * Firebase ID tokens are OpenID Connect spec-compliant JSON Web Tokens (JWTs). * See the * [ID Token section of the OpenID Connect spec](http://openid.net/specs/openid-connect-core-1_0.html#IDToken) * for more information about the specific properties below. */ export interface DecodedIdToken { /** * The audience for which this token is intended. * * This value is a string equal to your Firebase project ID, the unique * identifier for your Firebase project, which can be found in [your project's * settings](https://console.firebase.google.com/project/_/settings/general/android:com.random.android). */ aud: string; /** * Time, in seconds since the Unix epoch, when the end-user authentication * occurred. * * This value is not set when this particular ID token was created, but when the * user initially logged in to this session. In a single session, the Firebase * SDKs will refresh a user's ID tokens every hour. Each ID token will have a * different [`iat`](#iat) value, but the same `auth_time` value. */ auth_time: number; /** * The email of the user to whom the ID token belongs, if available. */ email?: string; /** * Whether or not the email of the user to whom the ID token belongs is * verified, provided the user has an email. */ email_verified?: boolean; /** * The ID token's expiration time, in seconds since the Unix epoch. That is, the * time at which this ID token expires and should no longer be considered valid. * * The Firebase SDKs transparently refresh ID tokens every hour, issuing a new * ID token with up to a one hour expiration. */ exp: number; /** * Information about the sign in event, including which sign in provider was * used and provider-specific identity details. * * This data is provided by the Firebase Authentication service and is a * reserved claim in the ID token. */ firebase: { /** * Provider-specific identity details corresponding * to the provider used to sign in the user. */ identities: { [key: string]: any; }; /** * The ID of the provider used to sign in the user. * One of `"anonymous"`, `"password"`, `"facebook.com"`, `"github.com"`, * `"google.com"`, `"twitter.com"`, `"apple.com"`, `"microsoft.com"`, * `"yahoo.com"`, `"phone"`, `"playgames.google.com"`, `"gc.apple.com"`, * or `"custom"`. * * Additional Identity Platform provider IDs include `"linkedin.com"`, * OIDC and SAML identity providers prefixed with `"saml."` and `"oidc."` * respectively. */ sign_in_provider: string; /** * The type identifier or `factorId` of the second factor, provided the * ID token was obtained from a multi-factor authenticated user. * For phone, this is `"phone"`. */ sign_in_second_factor?: string; /** * The `uid` of the second factor used to sign in, provided the * ID token was obtained from a multi-factor authenticated user. */ second_factor_identifier?: string; /** * The ID of the tenant the user belongs to, if available. */ tenant?: string; [key: string]: any; }; /** * The ID token's issued-at time, in seconds since the Unix epoch. That is, the * time at which this ID token was issued and should start to be considered * valid. * * The Firebase SDKs transparently refresh ID tokens every hour, issuing a new * ID token with a new issued-at time. If you want to get the time at which the * user session corresponding to the ID token initially occurred, see the * [`auth_time`](#auth_time) property. */ iat: number; /** * The issuer identifier for the issuer of the response. * * This value is a URL with the format * `https://securetoken.google.com/<PROJECT_ID>`, where `<PROJECT_ID>` is the * same project ID specified in the [`aud`](#aud) property. */ iss: string; /** * The phone number of the user to whom the ID token belongs, if available. */ phone_number?: string; /** * The photo URL for the user to whom the ID token belongs, if available. */ picture?: string; /** * The `uid` corresponding to the user who the ID token belonged to. * * As a convenience, this value is copied over to the [`uid`](#uid) property. */ sub: string; /** * The `uid` corresponding to the user who the ID token belonged to. * * This value is not actually in the JWT token claims itself. It is added as a * convenience, and is set as the value of the [`sub`](#sub) property. */ uid: string; /** * Other arbitrary claims included in the ID token. */ [key: string]: any; } // Audience to use for Firebase Auth Custom tokens const FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit'; // URL containing the public keys for the Google certs (whose private keys are used to sign Firebase // Auth ID tokens) const CLIENT_CERT_URL = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'; // URL containing the public keys for Firebase session cookies. This will be updated to a different URL soon. const SESSION_COOKIE_CERT_URL = 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys'; const EMULATOR_VERIFIER = new EmulatorSignatureVerifier(); /** * User facing token information related to the Firebase ID token. * * @internal */ export const ID_TOKEN_INFO: FirebaseTokenInfo = { url: 'https://firebase.google.com/docs/auth/admin/verify-id-tokens', verifyApiName: 'verifyIdToken()', jwtName: 'Firebase ID token', shortName: 'ID token', expiredErrorCode: AuthClientErrorCode.ID_TOKEN_EXPIRED, }; /** * User facing token information related to the Firebase session cookie. * * @internal */ export const SESSION_COOKIE_INFO: FirebaseTokenInfo = { url: 'https://firebase.google.com/docs/auth/admin/manage-cookies', verifyApiName: 'verifySessionCookie()', jwtName: 'Firebase session cookie', shortName: 'session cookie', expiredErrorCode: AuthClientErrorCode.SESSION_COOKIE_EXPIRED, }; /** * Interface that defines token related user facing information. * * @internal */ export interface FirebaseTokenInfo { /** Documentation URL. */ url: string; /** verify API name. */ verifyApiName: string; /** The JWT full name. */ jwtName: string; /** The JWT short name. */ shortName: string; /** JWT Expiration error code. */ expiredErrorCode: ErrorInfo; } /** * Class for verifying general purpose Firebase JWTs. This verifies ID tokens and session cookies. * * @internal */ export class FirebaseTokenVerifier { private readonly shortNameArticle: string; private readonly signatureVerifier: SignatureVerifier; constructor(clientCertUrl: string, private issuer: string, private tokenInfo: FirebaseTokenInfo, private readonly app: App) { if (!validator.isURL(clientCertUrl)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The provided public client certificate URL is an invalid URL.', ); } else if (!validator.isURL(issuer)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT issuer is an invalid URL.', ); } else if (!validator.isNonNullObject(tokenInfo)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT information is not an object or null.', ); } else if (!validator.isURL(tokenInfo.url)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The provided JWT verification documentation URL is invalid.', ); } else if (!validator.isNonEmptyString(tokenInfo.verifyApiName)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT verify API name must be a non-empty string.', ); } else if (!validator.isNonEmptyString(tokenInfo.jwtName)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public full name must be a non-empty string.', ); } else if (!validator.isNonEmptyString(tokenInfo.shortName)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT public short name must be a non-empty string.', ); } else if (!validator.isNonNullObject(tokenInfo.expiredErrorCode) || !('code' in tokenInfo.expiredErrorCode)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'The JWT expiration error code must be a non-null ErrorInfo object.', ); } this.shortNameArticle = tokenInfo.shortName.charAt(0).match(/[aeiou]/i) ? 'an' : 'a'; this.signatureVerifier = PublicKeySignatureVerifier.withCertificateUrl(clientCertUrl, app.options.httpAgent); // For backward compatibility, the project ID is validated in the verification call. } /** * Verifies the format and signature of a Firebase Auth JWT token. * * @param jwtToken - The Firebase Auth JWT token to verify. * @param isEmulator - Whether to accept Auth Emulator tokens. * @returns A promise fulfilled with the decoded claims of the Firebase Auth ID token. */ public verifyJWT(jwtToken: string, isEmulator = false): Promise<DecodedIdToken> { if (!validator.isString(jwtToken)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, `First argument to ${this.tokenInfo.verifyApiName} must be a ${this.tokenInfo.jwtName} string.`, ); } return this.ensureProjectId() .then((projectId) => { return this.decodeAndVerify(jwtToken, projectId, isEmulator); }) .then((decoded) => { const decodedIdToken = decoded.payload as DecodedIdToken; decodedIdToken.uid = decodedIdToken.sub; return decodedIdToken; }); } private ensureProjectId(): Promise<string> { return util.findProjectId(this.app) .then((projectId) => { if (!validator.isNonEmptyString(projectId)) { throw new FirebaseAuthError( AuthClientErrorCode.INVALID_CREDENTIAL, 'Must initialize app with a cert credential or set your Firebase project ID as the ' + `GOOGLE_CLOUD_PROJECT environment variable to call ${this.tokenInfo.verifyApiName}.`, ); } return Promise.resolve(projectId); }) } private decodeAndVerify(token: string, projectId: string, isEmulator: boolean): Promise<DecodedToken> { return this.safeDecode(token) .then((decodedToken) => { this.verifyContent(decodedToken, projectId, isEmulator); return this.verifySignature(token, isEmulator) .then(() => decodedToken); }); } private safeDecode(jwtToken: string): Promise<DecodedToken> { return decodeJwt(jwtToken) .catch((err: JwtError) => { if (err.code == JwtErrorCode.INVALID_ARGUMENT) { const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; const errorMessage = `Decoding ${this.tokenInfo.jwtName} failed. Make sure you passed ` + `the entire string JWT which represents ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}.` + verifyJwtTokenDocsMessage; throw new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } throw new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR, err.message); }); } /** * Verifies the content of a Firebase Auth JWT. * * @param fullDecodedToken - The decoded JWT. * @param projectId - The Firebase Project Id. * @param isEmulator - Whether the token is an Emulator token. */ private verifyContent( fullDecodedToken: DecodedToken, projectId: string | null, isEmulator: boolean): void { const header = fullDecodedToken && fullDecodedToken.header; const payload = fullDecodedToken && fullDecodedToken.payload; const projectIdMatchMessage = ` Make sure the ${this.tokenInfo.shortName} comes from the same ` + 'Firebase project as the service account used to authenticate this SDK.'; const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; let errorMessage: string | undefined; if (!isEmulator && typeof header.kid === 'undefined') { const isCustomToken = (payload.aud === FIREBASE_AUDIENCE); const isLegacyCustomToken = (header.alg === 'HS256' && payload.v === 0 && 'd' in payload && 'uid' in payload.d); if (isCustomToken) { errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}, but was given a custom token.`; } else if (isLegacyCustomToken) { errorMessage = `${this.tokenInfo.verifyApiName} expects ${this.shortNameArticle} ` + `${this.tokenInfo.shortName}, but was given a legacy custom token.`; } else { errorMessage = 'Firebase ID token has no "kid" claim.'; } errorMessage += verifyJwtTokenDocsMessage; } else if (!isEmulator && header.alg !== ALGORITHM_RS256) { errorMessage = `${this.tokenInfo.jwtName} has incorrect algorithm. Expected "` + ALGORITHM_RS256 + '" but got ' + '"' + header.alg + '".' + verifyJwtTokenDocsMessage; } else if (payload.aud !== projectId) { errorMessage = `${this.tokenInfo.jwtName} has incorrect "aud" (audience) claim. Expected "` + projectId + '" but got "' + payload.aud + '".' + projectIdMatchMessage + verifyJwtTokenDocsMessage; } else if (payload.iss !== this.issuer + projectId) { errorMessage = `${this.tokenInfo.jwtName} has incorrect "iss" (issuer) claim. Expected ` + `"${this.issuer}` + projectId + '" but got "' + payload.iss + '".' + projectIdMatchMessage + verifyJwtTokenDocsMessage; } else if (typeof payload.sub !== 'string') { errorMessage = `${this.tokenInfo.jwtName} has no "sub" (subject) claim.` + verifyJwtTokenDocsMessage; } else if (payload.sub === '') { errorMessage = `${this.tokenInfo.jwtName} has an empty string "sub" (subject) claim.` + verifyJwtTokenDocsMessage; } else if (payload.sub.length > 128) { errorMessage = `${this.tokenInfo.jwtName} has "sub" (subject) claim longer than 128 characters.` + verifyJwtTokenDocsMessage; } if (errorMessage) { throw new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } } private verifySignature(jwtToken: string, isEmulator: boolean): Promise<void> { const verifier = isEmulator ? EMULATOR_VERIFIER : this.signatureVerifier; return verifier.verify(jwtToken) .catch((error) => { throw this.mapJwtErrorToAuthError(error); }); } /** * Maps JwtError to FirebaseAuthError * * @param error - JwtError to be mapped. * @returns FirebaseAuthError or Error instance. */ private mapJwtErrorToAuthError(error: JwtError): Error { const verifyJwtTokenDocsMessage = ` See ${this.tokenInfo.url} ` + `for details on how to retrieve ${this.shortNameArticle} ${this.tokenInfo.shortName}.`; if (error.code === JwtErrorCode.TOKEN_EXPIRED) { const errorMessage = `${this.tokenInfo.jwtName} has expired. Get a fresh ${this.tokenInfo.shortName}` + ` from your client app and try again (auth/${this.tokenInfo.expiredErrorCode.code}).` + verifyJwtTokenDocsMessage; return new FirebaseAuthError(this.tokenInfo.expiredErrorCode, errorMessage); } else if (error.code === JwtErrorCode.INVALID_SIGNATURE) { const errorMessage = `${this.tokenInfo.jwtName} has invalid signature.` + verifyJwtTokenDocsMessage; return new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } else if (error.code === JwtErrorCode.NO_MATCHING_KID) { const errorMessage = `${this.tokenInfo.jwtName} has "kid" claim which does not ` + `correspond to a known public key. Most likely the ${this.tokenInfo.shortName} ` + 'is expired, so get a fresh token from your client app and try again.'; return new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, errorMessage); } return new FirebaseAuthError(AuthClientErrorCode.INVALID_ARGUMENT, error.message); } } /** * Creates a new FirebaseTokenVerifier to verify Firebase ID tokens. * * @internal * @param app - Firebase app instance. * @returns FirebaseTokenVerifier */ export function createIdTokenVerifier(app: App): FirebaseTokenVerifier { return new FirebaseTokenVerifier( CLIENT_CERT_URL, 'https://securetoken.google.com/', ID_TOKEN_INFO, app ); } /** * Creates a new FirebaseTokenVerifier to verify Firebase session cookies. * * @internal * @param app - Firebase app instance. * @returns FirebaseTokenVerifier */ export function createSessionCookieVerifier(app: App): FirebaseTokenVerifier { return new FirebaseTokenVerifier( SESSION_COOKIE_CERT_URL, 'https://session.firebase.google.com/', SESSION_COOKIE_INFO, app ); }
the_stack
import { } from "jquery"; import { CommunityData, GraphEdge, GraphNode, GSON, InitData, LoadGraphOption, LoadGraphOptionCallback, NodesEdges, PAIR, QUERY_RESULTS, RELATION_PATH } from '../types'; import { Utils } from '../utils'; import { GraphService } from './service'; export class LocalGraph implements GraphService { private _nodes: object[]; private _communityData: CommunityData; private _edges: object[]; private _labels: object; private _loadGraphOption: object; private _performLoadData: (callbackAfterLoad: () => void) => void; private _taskManager = new FindRelationsTaskManager(); private _eventHandlers = {}; private DEFAULT_GET_DESCRIPTION = function (node) { var description = "<p align=center>"; if (node.image !== undefined) { description += "<img src='" + node.image + "' width=150/><br>"; } description += "<b>" + node.label + "</b>" + "[" + node.id + "]"; description += "</p>"; if (node.info !== undefined) { description += "<p align=left>" + node.info + "</p>"; } else { if (node.title !== undefined) description += "<p align=left>" + node.title + "</p>"; } return description; } //indices private _indexDB = { _mapId2Node: new Map<string, object>(), _mapId2Edge: new Map<string, object>(), _mapNodeId2NeighbourNodeIds: new Map<string, Set<string>>(), _mapNodePair2EdgeIds: new Map<string, Set<string>>(), }; //cells private _cells = new Array<Array<string>>(); private l=0; private r=0; private t=0; private b=0; private w=0; private h=0; private cell_col_num=0; private cell_w=0; private cell_h=0; private NODE_PRE_CELL = 100; private _translate(gson: GSON): NodesEdges { var nodes = gson.data.nodes; var edges = gson.data.edges; var counterNode = 1; var counterEdge = 1; nodes.forEach((node: any) => { if (node.id === undefined) node.id = counterNode++; //set title if (node.title === undefined && node.label !== undefined) node.title = "<b>" + node.label + "</b>" + "[" + node.id + "]"; //set group if (node.group === undefined && node.categories instanceof Array) node.group = node.categories[0]; }); edges.forEach((edge: any) => { if (edge.id === undefined) edge.id = counterEdge++; }); return { nodes: nodes, edges: edges }; } private constructor() { } private _processGson(gson: GSON) { this._labels = gson.categories; var local = this; //translate gson to composite empty fields var data = this._translate(gson); this._nodes = data.nodes; this._edges = data.edges; //set loadGraphOption this._loadGraphOption = gson.option || { autoLayout: gson.data.communities === undefined }; this._createIndexDB(); if (!this._loadGraphOption["autoLayout"]) { this._createCells(); } this._communityData = { communities: gson.data.communities, nodeMap: data.nodes.map((x: object) => { return { node: x['id'], community: x['community'], }; }) }; } //Cut data into many cells private _createCells() { this._nodes.forEach( (n:any) =>{ this.r = n.x > this.r? n.x: this.r; this.l = n.x < this.l? n.x: this.l; this.t = n.y > this.t? n.y: this.t; this.b = n.y < this.b? n.y: this.b; }); this.w = Math.ceil(this.r - this.l ); this.h = Math.ceil(this.t - this.b ); this.cell_col_num = Math.ceil( Math.sqrt(this._nodes.length / this.NODE_PRE_CELL)); // console.log(this.t, this.b, this.l, this.r, this.w, this.h,this._nodes.length, this.cell_col_num); this.cell_w = Math.ceil(this.w / this.cell_col_num); this.cell_h = Math.ceil(this.h / this.cell_col_num); for (let i = 0; i < this.cell_col_num * this.cell_col_num; i++){ let cell = new Array<string>(); this._cells.push(cell) } this._nodes.forEach( (n:any) => { let cell_x = Math.floor((n['x'] - this.l) / this.cell_w); let cell_y = Math.floor((this.t - n['y']) / this.cell_h); this._cells[cell_y * this.cell_col_num + cell_x].push(n.id) }); // let sum = 0; // this._cells.forEach(c=>{ // console.log(c.length, c[0]); // sum += c.length; // }); // console.log(sum) } private _createIndexDB() { //create indices var indexDB = this._indexDB; this._nodes.forEach((x: any) => { indexDB._mapId2Node.set(x.id, x); }); this._edges.forEach((x: any) => { indexDB._mapId2Edge.set(x.id, x); //create adjacent matrix var pairs = [{ _1: x.from, _2: x.to }, { _1: x.to, _2: x.from }]; pairs.forEach((pair: PAIR<string, string>) => { if (!indexDB._mapNodeId2NeighbourNodeIds.has(pair._1)) indexDB._mapNodeId2NeighbourNodeIds.set(pair._1, new Set<string>()); var neighbours = indexDB._mapNodeId2NeighbourNodeIds.get(pair._1); neighbours.add(pair._2); }); //create node pair->edges pairs.forEach((pair: PAIR<string, string>) => { var key = "" + pair._1 + "-" + pair._2; if (!indexDB._mapNodePair2EdgeIds.has(key)) indexDB._mapNodePair2EdgeIds.set(key, new Set<string>()); var edges = indexDB._mapNodePair2EdgeIds.get(key); edges.add(x.id); }); }); } public static fromGson(gson: GSON) { var graph = new LocalGraph(); graph._performLoadData = (callback: () => void) => { graph._processGson(gson); callback(); }; return graph; } private static _string2GSON(gsonString: string): GSON { /* var __gson__: GSON; eval("__gson__=" + gsonString); return __gson__; */ return JSON.parse(gsonString); } public static fromGsonString(gsonString: string) { var graph = new LocalGraph(); graph._performLoadData = (callback: () => void) => { graph._processGson(LocalGraph._string2GSON(gsonString)); callback(); }; return graph; } public static fromGsonFile(gsonUrl: string, eventHandlers: object) { var graph = new LocalGraph(); graph._performLoadData = (callback: () => void) => { $.get(gsonUrl, { t: new Date().getTime() }, function (data) { graph._eventHandlers = eventHandlers || {}; graph._processGson(LocalGraph._string2GSON(data)); callback(); }, "text"); }; return graph; } requestGetNodeCategories(callback: (catagoryMap: object) => void) { var local: LocalGraph = this; this._async(() => { callback(local._labels); }); } _async(fn: (timerId: number) => void) { var timerId; timerId = window.setTimeout(() => { fn(timerId); }, 1); } requestConnect(callback: (data:InitData) => void) { var local: LocalGraph = this; this._async(() => { local._performLoadData(()=> { console.log(local) let option: InitData = { categories: [], nodesNum: this._nodes.length, edgesNum: this._edges.length, autoLayout: this._loadGraphOption["autoLayout"] || false }; callback(option) }); }); } requestGetCommunityData(callback: (data: CommunityData) => void) { var local: LocalGraph = this; this._async(() => callback(local._communityData) ); } requestGetNodeInfos(nodeIds: string[], callback: (infos: string[]) => void) { var local: LocalGraph = this; this._async(() => callback(nodeIds.map(nodeId => { let node: any = local._getNode(nodeId); let handler = local._eventHandlers['onGetNodeDescription'] || local.DEFAULT_GET_DESCRIPTION; return handler(node); }))); } //TODO load a batch of data requestLoadGraph(option: LoadGraphOption, callback: (nodes: GraphNode[], edges: GraphEdge[], back: LoadGraphOptionCallback) => void) { let local: LocalGraph = this; if ( option.dynamic ){ let cell_x = Math.floor((option.centerPointX - this.l) / this.cell_w); let cell_y = Math.floor((this.t - option.centerPointY) / this.cell_h); let point_cell = cell_y * this.cell_col_num + cell_x; let cells = []; let ids = []; //TODO preload [-1,0,1].forEach(i=>{ [-1,0,1].forEach(j=>{ let c = point_cell + i*this.cell_col_num + j; if (c >= 0 && c < this.cell_col_num*this.cell_col_num){ cells.push(c); ids = ids.concat(this._cells[c]); } }) }); this.getDataByNodeId(ids,(nodes, edges)=>{ this._async(() => callback(nodes, edges, { width: 3 * this.cell_w, height: 3 * this.cell_h })); }); }else { this._async(() => callback(local._nodes, local._edges, { width: 0, height: 0, })); } } private getDataByNodeId(ids:string[], callback: (nodes:GraphNode[], edges:GraphEdge[])=>void){ let nodes=[]; let edges=[]; ids.forEach(node=>{ nodes.push(this._getNode(node)); let nei = this._indexDB ._mapNodeId2NeighbourNodeIds .get(node); if (nei) { nei.forEach(neighbour => { //nodes.push(neighbour); this._indexDB ._mapNodePair2EdgeIds .get("" + node + "-" + neighbour) .forEach(edge=>{ edges.push(this._indexDB._mapId2Edge.get(edge)); }) }) } }); this._async(() => callback(nodes, edges)); } requestSearch(expr: any, limit: number, callback: (nodes: GraphNode[]) => void) { var local: LocalGraph = this; this._async(() => { var results = expr instanceof Array ? local._searchByExprArray(expr, limit) : local._searchBySingleExpr(expr, limit); callback(results); } ); } private _searchBySingleExpr(expr: any, limit: number): GraphNode[] { if (typeof (expr) === 'string') return this._searchByKeyword(expr.toString(), limit); return this._searchByExample(expr, limit); } private _searchByKeyword(keyword: string, limit: number): GraphNode[] { var results = []; var node: any; for (node of this._nodes) { if (node.label.indexOf(keyword) > -1) { results.push(node); if (results.length > limit) break; } } return results; } private _searchByExample(example: any, limit: number): GraphNode[] { var results = []; for (var node of this._nodes) { var matches = true; for (let key in example) { if (node[key] != example[key]) { matches = false; break; } } if (matches) { results.push(node); if (results.length > limit) break; } } return results; } private _searchByExprArray(exprs: any[], limit: number): GraphNode[] { var results = []; exprs.forEach((expr) => { results = results.concat(this._searchBySingleExpr(expr, limit)); }); return results; } requestGetNeighbours(nodeId: string, callback: (neighbourNodes: GraphNode[], neighbourEdges: GraphNode[]) => void) { var local: LocalGraph = this; this._async(() => { var neighbourEdges: GraphNode[] = Utils.distinct( local._edges.filter((edge: any) => { return edge.from == nodeId || edge.from == nodeId; }) ); var neighbourNodeIds = Utils.distinct( Utils.flatMap(neighbourEdges, (edge: any) => { return [edge.from, edge.to]; }) ); var neighbourNodes: GraphNode[] = neighbourNodeIds.map((nodeId: string) => { return local._getNode(nodeId); }); callback(neighbourNodes, neighbourEdges); }); } requestFilterNodesByCategory(className: string, nodeIds: any[], callback: (filteredNodeIds: any[]) => void) { var local: LocalGraph = this; this._async(() => { var filteredNodeIds = []; nodeIds.forEach((nodeId) => { var node: any = local._getNode(nodeId); var nls: string[] = node.categories; if (nls.indexOf(className) > -1) { filteredNodeIds.push(nodeId); } }); callback(filteredNodeIds); }); } private _getNode(nodeId: string) { return this._indexDB._mapId2Node.get(nodeId); } private _getEdge(edgeId: string) { return this._indexDB._mapId2Edge.get(edgeId); } private _getEdgesInPath(path: string[]): string[] { var edges = []; var lastNodeId = null; for (var node of path) { if (lastNodeId != null) { this._getEdgesBetween(lastNodeId, node).forEach((edge) => { edges.push(edge); }); } lastNodeId = node; } return edges; } private _getEdgesBetween(startNodeId, endNodeId): Set<string> { return this._indexDB._mapNodePair2EdgeIds.get("" + startNodeId + "-" + endNodeId); } requestFindRelations(startNodeId: string, endNodeId: string, maxDepth: number, callback: (queryId: string) => void) { var task = this._taskManager.createTask(); task.start(this, startNodeId, endNodeId, maxDepth); callback("" + task._taskId); } requestGetMoreRelations(queryId: string, callback: (queryResults: QUERY_RESULTS) => void) { var task = this._taskManager.getTask(queryId); callback(task.readMore(10)); } requestStopFindRelations(queryId: string) { var task = this._taskManager.getTask(queryId); task.stop(); } private _wrapPath(pathOfNodes: string[]): RELATION_PATH { return { nodes: pathOfNodes.map((id: string) => { return this._getNode(id); }), edges: this._getEdgesInPath(pathOfNodes).map((id: string) => { return this._getEdge(id); }), }; } findRelations(algDfsOrBfs: boolean, startNodeId: string, endNodeId: string, maxDepth: number, paths: RELATION_PATH[]) { if (algDfsOrBfs) this._findRelationsDFS(startNodeId, endNodeId, maxDepth, paths, [], 0); else this._findRelationsBFS(startNodeId, endNodeId, maxDepth, paths); } private _findRelationsDFS(startNodeId: string, endNodeId: string, maxDepth: number, paths: RELATION_PATH[], pathOfNodes: string[], depth: number) { if (depth > maxDepth) return; var newPath = pathOfNodes.concat([startNodeId]); if (startNodeId == endNodeId) { //BINGO!!! var wpath = this._wrapPath(newPath); paths.push(wpath); return; } var local = this; //get all adjant nodes var neighbours = this._indexDB._mapNodeId2NeighbourNodeIds.get(startNodeId); neighbours.forEach((nodeId: string) => { //no loop if (pathOfNodes.indexOf(nodeId) < 0) { local._findRelationsDFS(nodeId, endNodeId, maxDepth, paths, newPath, depth + 1); } } ); } private _findRelationsBFS(startNodeId: string, endNodeId: string, maxDepth: number, results: RELATION_PATH[]) { var queue = new Array<{ nodeId: string, depth: number, pathOfNodes: string[] }>(); queue.push({ nodeId: startNodeId, depth: 0, pathOfNodes: [startNodeId] }); while (queue.length > 0) { var one = queue.shift(); if (one.depth > maxDepth) continue; if (one.nodeId == endNodeId) { //BINGO!!! var wpath = this._wrapPath(one.pathOfNodes); results.push(wpath); continue; } var neighbours = this._indexDB._mapNodeId2NeighbourNodeIds.get(one.nodeId); for (var neighbour of neighbours) { if (one.pathOfNodes.indexOf(neighbour) >= 0) continue; var newPath = one.pathOfNodes.concat([neighbour]); queue.push({ nodeId: neighbour, depth: one.depth + 1, pathOfNodes: newPath }); } } } requestImageSearch(img: any, limit: number, callback: (nodes: GraphNode[]) => void) { //TODO image recognization let index = Math.floor((Math.random()*this._nodes.length)+1); let nodes = [this._nodes[index]]; callback(nodes); } } class FindRelationsTask { _taskId = 0; _pointer = 0; _completed = false; _timerId = 0; paths: RELATION_PATH[] = []; public constructor(taskId: number) { this._taskId = taskId; } start(graph: LocalGraph, startNodeId: string, endNodeId: string, maxDepth: number) { graph._async((timerId: number) => { this._timerId = timerId; graph.findRelations(true, startNodeId, endNodeId, maxDepth, this.paths); this._completed = true; }); } readMore(limit: number): QUERY_RESULTS { var token = this.paths.slice(this._pointer, limit); this._pointer += token.length; return { 'paths': token, 'completed': this._completed }; } stop() { clearTimeout(this._timerId); } } class FindRelationsTaskManager { private _seq = 1224; private _allTasks = {}; createTask(): FindRelationsTask { var taskId = this._seq++; var task = new FindRelationsTask(taskId); this._allTasks["" + taskId] = task; return task; } getTask(taskId: string): FindRelationsTask { return this._allTasks[taskId]; } }
the_stack
import {Constants} from "../../../../scripts/constants"; import {ClipperState} from "../../../../scripts/clipperUI/clipperState"; import {ClipMode} from "../../../../scripts/clipperUI/clipMode"; import {Status} from "../../../../scripts/clipperUI/status"; import {RegionPreview} from "../../../../scripts/clipperUI/components/previewViewer/regionPreview"; import {Assert} from "../../../assert"; import {MithrilUtils} from "../../../mithrilUtils"; import {MockProps} from "../../../mockProps"; import {TestModule} from "../../../testModule"; declare function require(name: string); export class RegionPreviewTests extends TestModule { private stringsJson = require("../../../../strings.json"); protected module() { return "regionPreview"; } protected tests() { test("The tab order flow from the header to the preview title is correct in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); Assert.tabOrderIsIncremental([Constants.Ids.addAnotherRegionButton, Constants.Ids.previewHeaderInput]); }); test("The tab order flow from the preview title through the region delete buttons is correct in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let elementsInExpectedTabOrder = [ { name: Constants.Ids.previewHeaderInput, elem: document.getElementById(Constants.Ids.previewHeaderInput) } ]; let removeButtons = document.getElementsByClassName(Constants.Classes.regionSelectionRemoveButton); for (let i = 0; i < removeButtons.length; i++) { elementsInExpectedTabOrder.push({ name: Constants.Classes.regionSelectionRemoveButton + i, elem: removeButtons[i] as HTMLElement }); } // Check the flow from the title to the first button Assert.tabOrderIsIncrementalForElements(elementsInExpectedTabOrder.slice(0, 2)); for (let i = 2 /* Check buttons */; i < elementsInExpectedTabOrder.length; i++) { // Note the '>=' ok(elementsInExpectedTabOrder[i].elem.tabIndex >= elementsInExpectedTabOrder[i - 1].elem.tabIndex, "Element " + elementsInExpectedTabOrder[i].name + " should have a greater or equal tabIndex than element " + elementsInExpectedTabOrder[i - 1].name); } for (let i = 0; i < elementsInExpectedTabOrder.length; i++) { ok(elementsInExpectedTabOrder[i].elem.tabIndex >= 0); } }); test("The region header and all related controls should be displayed in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); ok(document.getElementById(Constants.Ids.addRegionControl), "The region control should exist"); ok(!document.getElementById(Constants.Ids.highlightControl), "The highlight control should not exist"); ok(!document.getElementById(Constants.Ids.serifControl), "The font family control should not exist"); ok(!document.getElementById(Constants.Ids.decrementFontSize), "The decrement font size button should not exist"); ok(!document.getElementById(Constants.Ids.incrementFontSize), "The increment font size button should not exist"); }); test("The editable title of the page should be displayed in the preview title in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement; strictEqual(previewHeaderInput.value, mockClipperState.previewGlobalInfo.previewTitleText, "The title of the page should be displayed in the preview title"); ok(!previewHeaderInput.readOnly); }); test("There should be one image rendered for every data url in state in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let previewBody = document.getElementById(Constants.Ids.previewBody); let selections = previewBody.getElementsByClassName(Constants.Classes.regionSelection); strictEqual(selections.length, mockClipperState.regionResult.data.length); for (let i = 0; i < selections.length; i++) { let selection = selections[i]; let imagesRenderedInSelection = selection.getElementsByClassName(Constants.Classes.regionSelectionImage); strictEqual(imagesRenderedInSelection.length, 1); strictEqual((imagesRenderedInSelection[0] as HTMLImageElement).src, mockClipperState.regionResult.data[i], "The image should render the data url in state"); } }); test("When multiple images are rendered, clicking a middle image's remove button should remove it and only it in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let previewBody = document.getElementById(Constants.Ids.previewBody); let selections = previewBody.getElementsByClassName(Constants.Classes.regionSelection); let indexToRemove = 1; // This does not represent a user action, but is done to make testing easier mockClipperState.regionResult.data.splice(indexToRemove, 1); let removeButton = selections[indexToRemove].getElementsByClassName(Constants.Classes.regionSelectionRemoveButton)[0] as HTMLAnchorElement; MithrilUtils.simulateAction(() => { removeButton.click(); }); strictEqual(selections.length, mockClipperState.regionResult.data.length); for (let i = 0; i < selections.length; i++) { let selection = selections[i]; let imagesRenderedInSelection = selection.getElementsByClassName(Constants.Classes.regionSelectionImage); strictEqual(imagesRenderedInSelection.length, 1); strictEqual((imagesRenderedInSelection[0] as HTMLImageElement).src, mockClipperState.regionResult.data[i], "The image should render the data url in state"); } }); test("When multiple images are rendered, clicking the first image's remove button should remove it and only it in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let previewBody = document.getElementById(Constants.Ids.previewBody); let selections = previewBody.getElementsByClassName(Constants.Classes.regionSelection); let indexToRemove = 0; // This does not represent a user action, but is done to make testing easier mockClipperState.regionResult.data.splice(indexToRemove, 1); let removeButton = selections[indexToRemove].getElementsByClassName(Constants.Classes.regionSelectionRemoveButton)[0] as HTMLAnchorElement; MithrilUtils.simulateAction(() => { removeButton.click(); }); strictEqual(selections.length, mockClipperState.regionResult.data.length); for (let i = 0; i < selections.length; i++) { let selection = selections[i]; let imagesRenderedInSelection = selection.getElementsByClassName(Constants.Classes.regionSelectionImage); strictEqual(imagesRenderedInSelection.length, 1); strictEqual((imagesRenderedInSelection[0] as HTMLImageElement).src, mockClipperState.regionResult.data[i], "The image should render the data url in state"); } }); test("When multiple images are rendered, clicking the last image's remove button should remove it and only it in Region mode", () => { let mockClipperState = this.getMockRegionModeState(); let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let previewBody = document.getElementById(Constants.Ids.previewBody); let selections = previewBody.getElementsByClassName(Constants.Classes.regionSelection); let indexToRemove = mockClipperState.regionResult.data.length - 1; // This does not represent a user action, but is done to make testing easier mockClipperState.regionResult.data.splice(indexToRemove, 1); let removeButton = selections[indexToRemove].getElementsByClassName(Constants.Classes.regionSelectionRemoveButton)[0] as HTMLAnchorElement; MithrilUtils.simulateAction(() => { removeButton.click(); }); strictEqual(selections.length, mockClipperState.regionResult.data.length); for (let i = 0; i < selections.length; i++) { let selection = selections[i]; let imagesRenderedInSelection = selection.getElementsByClassName(Constants.Classes.regionSelectionImage); strictEqual(imagesRenderedInSelection.length, 1); strictEqual((imagesRenderedInSelection[0] as HTMLImageElement).src, mockClipperState.regionResult.data[i], "The image should render the data url in state"); } }); test("When region clipping is disabled, remove image buttons are not rendered. The mode itself is still available because of context image selection mode.", () => { let mockClipperState = this.getMockRegionModeState(); mockClipperState.injectOptions.enableRegionClipping = false; let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let regionButtons = document.getElementsByClassName(Constants.Classes.regionSelectionRemoveButton); strictEqual(regionButtons.length, 0, "No remove image buttons should be rendered"); }); test("When region clipping is disabled, the add another region button should not be rendered.", () => { let mockClipperState = this.getMockRegionModeState(); mockClipperState.injectOptions.enableRegionClipping = false; let defaultComponent = <RegionPreview clipperState={mockClipperState} />; MithrilUtils.mountToFixture(defaultComponent); let addAnotherRegionButton = document.getElementById(Constants.Ids.addAnotherRegionButton); ok(!addAnotherRegionButton, "The add another region button should not be rendered"); }); } private getMockRegionModeState(): ClipperState { let state = MockProps.getMockClipperState() as ClipperState; state.currentMode.set(ClipMode.Region); state.regionResult = { data: ["data:image/png;base64,123", "data:image/png;base64,456", "data:image/png;base64,789", "data:image/png;base64,0"], status: Status.Succeeded }; return state; } } (new RegionPreviewTests()).runTests();
the_stack
import Panel from '@playcanvas/pcui/Panel/component'; // @ts-ignore: library file import import Container from '@playcanvas/pcui/Container/component'; // @ts-ignore: library file import import BooleanInput from '@playcanvas/pcui/BooleanInput/component'; // @ts-ignore: library file import import Label from '@playcanvas/pcui/Label/component'; // @ts-ignore: library file import import SliderInput from '@playcanvas/pcui/SliderInput/component'; // @ts-ignore: library file import import Button from '@playcanvas/pcui/Button/component'; // @ts-ignore: library file import import TreeViewItem from '@playcanvas/pcui/TreeViewItem/component'; // @ts-ignore: library file import import TreeView from '@playcanvas/pcui/TreeView/component'; // @ts-ignore: library file import import VectorInput from '@playcanvas/pcui/VectorInput/component'; // @ts-ignore: library file import import SelectInput from '@playcanvas/pcui/SelectInput/component'; // @ts-ignore: library file import import BindingTwoWay from '@playcanvas/pcui/BindingTwoWay'; // @ts-ignore: library file import import React, { useEffect, useState, useContext } from 'react'; import { Morph, Option, Observer, HierarchyNode } from './types'; const ObserverContext = React.createContext(null); const ObserverProvider = ObserverContext.Provider; const useObserverState = (observer: Observer, path: string, json?: boolean) => { const parseFunc = (observerValue: any) => json ? JSON.parse(observerValue) : observerValue; const [value, setValue] = useState(parseFunc(observer.get(path))); observer.on(`${path}:set`, (value) => setValue(parseFunc(value))); return value; }; const Detail = (props: { name: string, path:string, label?: string, enabled?: boolean}) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} /> <Label link={{ observer, path: props.path }} binding={new BindingTwoWay()} enabled={props.enabled}/> </Container>; }; const Vector = (props: { name: string, path:string, label?: string, dimensions: number, enabled?: boolean}) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} /> <VectorInput link={{ observer, path: props.path }} binding={new BindingTwoWay()} dimensions={props.dimensions} enabled={props.enabled}/> </Container>; }; const Toggle = (props: { name: string, path:string, label?: string, enabled?: boolean}) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} /> <BooleanInput type='toggle' link={{ observer, path: props.path }} binding={new BindingTwoWay()} enabled={props.enabled}/> </Container>; }; Toggle.defaultProps = { enabled: true }; const Slider = (props: { name: string, path:string, precision: number, min: number, max: number, label?: string, enabled?: boolean }) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} /> <SliderInput min={props.min} max={props.max} sliderMin={props.min} sliderMax={props.max} precision={props.precision} step={0.01} link={{ observer, path: props.path }} binding={new BindingTwoWay()} enabled={props.enabled} /> </Container>; }; Slider.defaultProps = { enabled: true }; const MorphSlider = (props: { name: string, path:string, precision: number, min: number, max: number, label?: string, enabled?: boolean }) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label flexGrow={1} text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} flex /> <SliderInput flexGrow={0} flexShrink={0} min={props.min} max={props.max} sliderMin={props.min} sliderMax={props.max} precision={props.precision} step={0.01} link={{ observer, path: props.path }} binding={new BindingTwoWay()} enabled={props.enabled} /> </Container>; }; MorphSlider.defaultProps = { enabled: true }; const Select = (props: { name: string, path:string, type: string, options: Array<Option>, label?: string, enabled?: boolean }) => { const observer: Observer = useContext(ObserverContext); return <Container class='panel-option'> <Label text={props.label ? props.label : props.name.substring(0, 1).toUpperCase() + props.name.substring(1, props.name.length)} /> <SelectInput type={props.type} options={props.options} link={{ observer, path: props.path }} binding={new BindingTwoWay()} enabled={props.enabled} /> </Container>; }; Select.defaultProps = { enabled: true }; const ShowPanel = () => { return ( <Panel headerText='SHOW' collapsible> <Toggle name='stats' path='show.stats' /> <Toggle name='wireframe' path='show.wireframe' /> <Toggle name='bounds' path='show.bounds' /> <Toggle name='skeleton' path='show.skeleton' /> <Slider name='normals' precision={2} min={0} max={1} path='show.normals' /> <Slider name='fov' precision={0} min={35} max={150} path='show.fov' /> </Panel> ); }; const LightingPanel = () => { const observer: Observer = useContext(ObserverContext); const skyboxOptions: Array<Option> = useObserverState(observer, 'lighting.skybox.options', true); return ( <Panel headerText='LIGHTING' collapsible> <Slider name='lightingDirect' precision={2} min={0} max={6} path='lighting.direct' label='Direct' /> <Toggle name='lightingShadow' path='lighting.shadow' label='Shadow' /> <Slider name='lightingEnv' precision={2} min={0} max={6} path='lighting.env' label='Env' /> <Select name='lightingSkybox' type='string' options={skyboxOptions} path='lighting.skybox.value' label='Skybox' /> <Select name='lightingSkyboxMip' type='number' options={[0, 1, 2, 3, 4, 5, 6].map((v) => ({ v, t: Number(v).toString() }))} path='lighting.skybox.mip' label='Mip' /> <Slider name='lightingRotation' precision={0} min={-180} max={180} path='lighting.rotation' label='Rotation' /> <Select name='lightingTonemapping' type='string' options={['Linear', 'Filmic', 'Hejl', 'ACES'].map((v) => ({ v, t: v }))} path='lighting.tonemapping' label='Tonemap' /> </Panel> ); }; const ModelPanel = () => { const observer: Observer = useContext(ObserverContext); const modelHierarchy: Array<HierarchyNode> = useObserverState(observer, 'model.nodes', true); const enabled: boolean = modelHierarchy.length > 0; const mapNodes = (nodes: Array<HierarchyNode>) => { return nodes.map((node:HierarchyNode) => <TreeViewItem text={`${node.name}`} key={node.path} onSelected={() => observer.set('model.selectedNode.path', node.path)}> { mapNodes(node.children) } </TreeViewItem>); }; return ( <Panel headerText='MODEL' collapsible > <Detail name='meshCount' label='Meshes:' path='model.meshCount'/> <Detail name='vertexCount' label='Verts:' path='model.vertexCount'/> <Detail name='primitiveCount' label='Primitives:' path='model.primitiveCount'/> <Panel headerText='SELECTED NODE' collapsible class={'modelSelectedNodePanel'} enabled={enabled}> <Detail name='selectedNodeName' label='Name:' path='model.selectedNode.name'/> <Vector name='selectedNodePosition' label='Position:' dimensions={3} path='model.selectedNode.position' enabled={false}/> <Vector name='selectedNodeRotation' label='Rotation:' dimensions={4} path='model.selectedNode.rotation' enabled={false}/> <Vector name='selectedNodeScale' label='Scale:' dimensions={3} path='model.selectedNode.scale' enabled={false}/> </Panel> <Panel headerText='HIERARCHY' collapsible class={'modelHierarchyPanel'} enabled={enabled}> { modelHierarchy.length > 0 && <TreeView allowReordering={false} allowDrag={false}> { mapNodes(modelHierarchy) } </TreeView> } </Panel> </Panel> ); }; const AnimationPanel = () => { const observer: Observer = useContext(ObserverContext); const playing: boolean = useObserverState(observer, 'animation.playing'); const animationsList: Array<string> = useObserverState(observer, 'animation.list', true); const enabled: boolean = animationsList.length > 0; let selectTrackOptions: Array<{ v: string, t: string }> = animationsList.map((animation: string) => ({ v: animation, t: animation })); if (selectTrackOptions.length > 1) { selectTrackOptions = [{ v: 'ALL_TRACKS', t: 'All tracks' }, ...selectTrackOptions]; if (!animationsList.includes(observer.get('animation.selectedTrack'))) { observer.set('animation.selectedTrack', selectTrackOptions[0].v); } } else if (selectTrackOptions.length === 1) { observer.set('animation.selectedTrack', selectTrackOptions[0].v); } const allTracks: boolean = useObserverState(observer, 'animation.selectedTrack') === 'ALL_TRACKS'; return ( <Panel headerText='ANIMATION' collapsible> <Select name='animationTrack' type='string' options={selectTrackOptions} path='animation.selectedTrack' label='Track' enabled={enabled} /> <Container class='panel-option'> <Button icon={ playing ? 'E376' : 'E286' } text='' onClick={() => observer.set('animation.playing', !observer.get('animation.playing'))} enabled={enabled} /> </Container> <Slider name='animationSpeed' precision={2} min={0} max={4} path='animation.speed' label='Speed' enabled={enabled} /> { !allTracks && <Slider name='animationFrameTimeline' precision={2} min={0} max={1} path='animation.progress' label='Timeline' enabled={enabled} /> } { allTracks && <Slider name='animationTransition' precision={2} min={0} max={4} path='animation.transition' label='Transition' enabled={enabled} /> } { allTracks && <Select name='animationLoops' type='number' options={[1, 2, 3, 4].map((v) => ({ v, t: Number(v).toString() }))} path='animation.loops' label='Loops' enabled={enabled} /> } </Panel> ); }; const MorphPanel = () => { const observer: Observer = useContext(ObserverContext); const morphTargets: Record<string, {name: string, morphs: Record<string, Morph>}> = useObserverState(observer, 'morphTargets'); if (!morphTargets) return null; return ( <Panel headerText='MORPH TARGETS' collapsible> {Object.keys(morphTargets).map((key) => { const panel = morphTargets[key]; return ( <Panel key={`${key}.${panel.name}`} headerText={panel.name} collapsible class='morph-target-panel'> {Object.keys(panel.morphs).map((morphKey) => { const morph: Morph = panel.morphs[morphKey]; return <MorphSlider key={`${key}.${morphKey}`} name={`${morph.name}`} precision={2} min={0} max={1} path={`morphTargets.${key}.morphs.${morph.targetIndex}.weight`} />; })} </Panel> ); } )} </Panel> ); }; const Controls = (props: { observer: Observer }) => { useEffect(() => { // set up the control panel toggle button const panelToggleDiv = document.getElementById('panel-toggle'); const wrapper = document.getElementById('wrapper'); panelToggleDiv.addEventListener('click', function () { wrapper.classList.toggle('collapsed'); props.observer.emit('canvasResized'); }); if (document.body.clientWidth <= 600) { wrapper.classList.toggle('collapsed'); } }); return ( <div id='controls'> <ObserverProvider value={props.observer}> <ShowPanel /> <LightingPanel /> <ModelPanel /> <AnimationPanel /> <MorphPanel /> </ObserverProvider> </div> ); }; export default Controls;
the_stack
'use strict'; import * as fs from 'fs'; import * as path from 'path'; import * as _ from 'lodash'; import {Tabletojson as tabletojson} from '../lib/Tabletojson'; describe('TableToJSON Local', function () { let html = ''; let noTables = ''; beforeAll(() => { html = fs.readFileSync(path.resolve(__dirname, 'tables.html'), 'utf8'); noTables = fs.readFileSync(path.resolve(__dirname, 'notables.html'), 'utf8'); }); it('Options: Strip HTML from header AND from body', async function () { const converted = await tabletojson.convert(html, { stripHtmlFromHeadings: true, stripHtmlFromCells: true, }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Age')).toBeTruthy(); expect(firstTable[0].Age).toBe('2'); }); it('Options: Strip HTML from header AND from body using stripHtml-shortcut ', async function () { const converted = await tabletojson.convert(html, { stripHtml: true, }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Age')).toBeTruthy(); expect(firstTable[0].Age).toBe('2'); }); it('Options: Strip HTML from header but not from body', async function () { const converted = await tabletojson.convert(html, { stripHtmlFromHeadings: true, stripHtmlFromCells: false, }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Age')).toBeTruthy(); expect(firstTable[0].Age).toBe('<i>2</i>'); }); it('Options: Strip HTML from body but not from header', async function () { const converted = await tabletojson.convert(html, { stripHtmlFromHeadings: false, stripHtmlFromCells: true, }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], '<b>Age</b>')).toBeTruthy(); expect(firstTable[0]['<b>Age</b>']).toBe('2'); }); // ADDED TO FIX: https://github.com/maugenst/tabletojson/issues/15 it('Double Header Entry: handle double header entries in different tables', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const firstTable = converted[0]; const secondTable = converted[1]; expect(_.has(firstTable[0], 'Age')).toBeTruthy(); expect(_.has(secondTable[0], 'Age')).toBeTruthy(); }); it('Double Header Entry: handle double header entries', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'isDumb')).toBeTruthy(); expect(_.has(firstTable[0], 'isDumb_2')).toBeTruthy(); }); it('Directly local html content: Table with header', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Dog')).toBeTruthy(); expect(_.has(firstTable[0], 'Race')).toBeTruthy(); expect(_.has(firstTable[0], 'Age')).toBeTruthy(); }); it('Do not strip HTML from header', async function () { const converted = await tabletojson.convert(html, { stripHtml: false, }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Dog')).toBeTruthy(); expect(_.has(firstTable[0], 'Race')).toBeTruthy(); expect(_.has(firstTable[0], '<b>Age</b>')).toBeTruthy(); }); it('Directly passing html content: Table without header', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const thirdTable = converted[2]; expect(_.has(thirdTable[0], '0')).toBeTruthy(); expect(_.has(thirdTable[0], '1')).toBeTruthy(); expect(_.has(thirdTable[0], '2')).toBeTruthy(); expect(thirdTable[0]['0']).toBe('Dog'); expect(thirdTable[0]['1']).toBe('Race'); expect(thirdTable[0]['2']).toBe('Age'); }); // ADDED TO FIX: https://github.com/maugenst/tabletojson/issues/14 it('Empty header: to be converted into their column count and not to the underline field name', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const forthTable = converted[3]; expect(_.has(forthTable[0], 'Dog')).toBeTruthy(); expect(_.has(forthTable[0], '1')).toBeTruthy(); expect(_.has(forthTable[0], '2')).toBeTruthy(); expect(_.has(forthTable[0], 'Height')).toBeTruthy(); expect(_.has(forthTable[0], '4')).toBeTruthy(); }); // ADDED TO FIX: https://github.com/maugenst/tabletojson/pull/18 it('Double Header Entry: countDuplicateHeadings:false', async function () { const converted = await tabletojson.convert(html, { countDuplicateHeadings: false, }); expect(converted).toBeDefined(); const table = converted[4]; expect(_.has(table[0], 'PLACE')).toBeTruthy(); expect(_.has(table[0], 'VALUE')).toBeTruthy(); expect(_.has(table[0], 'PLACE_2')).toBeFalsy(); expect(_.has(table[0], 'VALUE_2')).toBeFalsy(); expect(_.has(table[1], 'PLACE')).toBeTruthy(); expect(_.has(table[1], 'VALUE')).toBeTruthy(); expect(_.has(table[1], 'PLACE_2')).toBeFalsy(); expect(_.has(table[1], 'VALUE_2')).toBeFalsy(); expect(table[0].PLACE).toBe('def'); expect(table[0].VALUE).toBe('2'); expect(table[1].PLACE).toBe('jkl'); expect(table[1].VALUE).toBe('4'); }); // ADDED TO FIX: https://github.com/maugenst/tabletojson/pull/18 it('Double Header Entry: countDuplicateHeadings:true', async function () { const converted = await tabletojson.convert(html, { countDuplicateHeadings: true, }); expect(converted).toBeDefined(); const table = converted[4]; expect(_.has(table[0], 'PLACE')).toBeTruthy(); expect(_.has(table[0], 'VALUE')).toBeTruthy(); expect(_.has(table[0], 'PLACE_2')).toBeTruthy(); expect(_.has(table[0], 'VALUE_2')).toBeTruthy(); expect(_.has(table[1], 'PLACE')).toBeTruthy(); expect(_.has(table[1], 'VALUE')).toBeTruthy(); expect(_.has(table[1], 'PLACE_2')).toBeTruthy(); expect(_.has(table[1], 'VALUE_2')).toBeTruthy(); expect(table[0].PLACE).toBe('abc'); expect(table[0].VALUE).toBe('1'); expect(table[0].PLACE_2).toBe('def'); expect(table[0].VALUE_2).toBe('2'); expect(table[1].PLACE).toBe('ghi'); expect(table[1].VALUE).toBe('3'); expect(table[1].PLACE_2).toBe('jkl'); expect(table[1].VALUE_2).toBe('4'); }); // FEATURE 'ignoreColumns' it('Option: ignoreColumns: [2, 3]', async function () { const converted = await tabletojson.convert(html, { ignoreColumns: [2, 3], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'NAME')).toBeTruthy(); expect(_.has(table[0], 'PLACE')).toBeTruthy(); expect(_.has(table[0], 'WEIGHT')).toBeFalsy(); expect(_.has(table[0], 'SEX')).toBeFalsy(); expect(_.has(table[0], 'AGE')).toBeTruthy(); expect(table[0].NAME).toBe('Mel'); expect(table[0].PLACE).toBe('1'); expect(table[0].AGE).toBe('23'); expect(_.has(table[1], 'NAME')).toBeTruthy(); expect(_.has(table[1], 'PLACE')).toBeTruthy(); expect(_.has(table[1], 'WEIGHT')).toBeFalsy(); expect(_.has(table[1], 'SEX')).toBeFalsy(); expect(_.has(table[1], 'AGE')).toBeTruthy(); expect(table[1].NAME).toBe('Tom'); expect(table[1].PLACE).toBe('2'); expect(table[1].AGE).toBe('54'); expect(_.has(table[2], 'NAME')).toBeTruthy(); expect(_.has(table[2], 'PLACE')).toBeTruthy(); expect(_.has(table[2], 'WEIGHT')).toBeFalsy(); expect(_.has(table[2], 'SEX')).toBeFalsy(); expect(_.has(table[2], 'AGE')).toBeTruthy(); expect(table[2].NAME).toBe('Bill'); expect(table[2].PLACE).toBe('3'); expect(table[2].AGE).toBe('31'); }); // FEATURE 'onlyColumns' it('Option: onlyColumns: [0, 4]', async function () { const converted = await tabletojson.convert(html, { onlyColumns: [0, 4], ignoreColumns: [2, 4], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'NAME')).toBeTruthy(); expect(_.has(table[0], 'PLACE')).toBeFalsy(); expect(_.has(table[0], 'WEIGHT')).toBeFalsy(); expect(_.has(table[0], 'SEX')).toBeFalsy(); expect(_.has(table[0], 'AGE')).toBeTruthy(); expect(table[0].NAME).toBe('Mel'); expect(table[0].AGE).toBe('23'); expect(_.has(table[1], 'NAME')).toBeTruthy(); expect(_.has(table[1], 'PLACE')).toBeFalsy(); expect(_.has(table[1], 'WEIGHT')).toBeFalsy(); expect(_.has(table[1], 'SEX')).toBeFalsy(); expect(_.has(table[1], 'AGE')).toBeTruthy(); expect(table[1].NAME).toBe('Tom'); expect(table[1].AGE).toBe('54'); expect(_.has(table[2], 'NAME')).toBeTruthy(); expect(_.has(table[2], 'PLACE')).toBeFalsy(); expect(_.has(table[2], 'WEIGHT')).toBeFalsy(); expect(_.has(table[2], 'SEX')).toBeFalsy(); expect(_.has(table[2], 'AGE')).toBeTruthy(); expect(table[2].NAME).toBe('Bill'); expect(table[2].AGE).toBe('31'); }); // FEATURE 'ignoreHiddenRows:true' it('Option: ignoreHiddenRows:true', async function () { const converted = await tabletojson.convert(html, { ignoreHiddenRows: true, }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'NAME')).toBeTruthy(); expect(_.has(table[0], 'PLACE')).toBeTruthy(); expect(_.has(table[0], 'WEIGHT')).toBeTruthy(); expect(_.has(table[0], 'SEX')).toBeTruthy(); expect(_.has(table[0], 'AGE')).toBeTruthy(); expect(table.length).toBe(3); }); // FEATURE 'ignoreHiddenRows:false' it('Option: ignoreHiddenRows:false', async function () { const converted = await tabletojson.convert(html, { ignoreHiddenRows: false, }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'NAME')).toBeTruthy(); expect(_.has(table[0], 'PLACE')).toBeTruthy(); expect(_.has(table[0], 'WEIGHT')).toBeTruthy(); expect(_.has(table[0], 'SEX')).toBeTruthy(); expect(_.has(table[0], 'AGE')).toBeTruthy(); expect(table.length).toBe(4); }); // FEATURE 'headings: ['A', 'B', 'C', 'D', 'E']' it('Option: headings: ["A","B","C","D","E"]', async function () { const converted = await tabletojson.convert(html, { headings: ['A', 'B', 'C', 'D', 'E'], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeTruthy(); expect(_.has(table[0], 'C')).toBeTruthy(); expect(_.has(table[0], 'D')).toBeTruthy(); expect(_.has(table[0], 'E')).toBeTruthy(); expect(table.length).toBe(3); }); // FEATURE 'headings: ['A', 'B', 'C']' it('Option: headings: ["A","B","C"]', async function () { const converted = await tabletojson.convert(html, { headings: ['A', 'B', 'C'], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeTruthy(); expect(_.has(table[0], 'C')).toBeTruthy(); expect(_.has(table[0], 'D')).toBeFalsy(); expect(_.has(table[0], 'E')).toBeFalsy(); expect(table.length).toBe(3); }); /** * | NAME | PLACE | WEIGHT | SEX | AGE | * | Mel | 1 | 58 | W | 23 | * | Tom | 2 | 78 | M | 54 | * | Bill | 3 | 92 | M | 31 | */ // FEATURE 'headings: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']' it('Option: headings: ["A","B","C","E","E","F","G","H","I"]', async function () { const converted = await tabletojson.convert(html, { headings: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeTruthy(); expect(_.has(table[0], 'C')).toBeTruthy(); expect(_.has(table[0], 'D')).toBeTruthy(); expect(_.has(table[0], 'E')).toBeTruthy(); expect(table.length).toBe(3); expect(table[0].A).toEqual('Mel'); expect(table[0].B).toEqual('1'); expect(table[0].C).toEqual('58'); expect(table[0].D).toEqual('W'); expect(table[0].E).toEqual('23'); expect(table[1].A).toEqual('Tom'); expect(table[1].B).toEqual('2'); expect(table[1].C).toEqual('78'); expect(table[1].D).toEqual('M'); expect(table[1].E).toEqual('54'); expect(table[2].A).toEqual('Bill'); expect(table[2].B).toEqual('3'); expect(table[2].C).toEqual('92'); expect(table[2].D).toEqual('M'); expect(table[2].E).toEqual('31'); }); /** * | NAME | PLACE | WEIGHT | SEX | AGE | * | Mel | 1 | 58 | W | 23 | * | Tom | 2 | 78 | M | 54 | * | Bill | 3 | 92 | M | 31 | */ // FEATURE 'headings: ['A', 'B', 'C'] && ignoreColumns: [1, 2]' it('Option: headings: ["A","B","C"] && ignoreColumns: [1, 2]', async function () { const converted = await tabletojson.convert(html, { headings: ['A', 'B', 'C'], ignoreColumns: [1, 2], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeTruthy(); expect(_.has(table[0], 'C')).toBeTruthy(); expect(_.has(table[0], 'D')).toBeFalsy(); expect(_.has(table[0], 'E')).toBeFalsy(); expect(table.length).toBe(3); expect(table[0].A).toEqual('Mel'); expect(table[0].B).toEqual('W'); expect(table[0].C).toEqual('23'); expect(table[1].A).toEqual('Tom'); expect(table[1].B).toEqual('M'); expect(table[1].C).toEqual('54'); expect(table[2].A).toEqual('Bill'); expect(table[2].B).toEqual('M'); expect(table[2].C).toEqual('31'); }); /** * | NAME | PLACE | WEIGHT | SEX | AGE | * | Mel | 1 | 58 | W | 23 | * | Tom | 2 | 78 | M | 54 | * | Bill | 3 | 92 | M | 31 | */ // FEATURE 'headings: ['A', 'B', 'C'] && ignoreColumns: [1, 2] && onlyColumns: [0, 4]' it('Option: headings: ["A","B","C"] && ignoreColumns: [1, 2] && onlyColumns: [0, 4]', async function () { const converted = await tabletojson.convert(html, { headings: ['A', 'B', 'C'], ignoreColumns: [1, 2], onlyColumns: [0, 4], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeTruthy(); expect(_.has(table[0], 'C')).toBeFalsy(); expect(_.has(table[0], 'D')).toBeFalsy(); expect(_.has(table[0], 'E')).toBeFalsy(); expect(table.length).toBe(3); expect(table[0].A).toEqual('Mel'); expect(table[0].B).toEqual('23'); expect(table[1].A).toEqual('Tom'); expect(table[1].B).toEqual('54'); expect(table[2].A).toEqual('Bill'); expect(table[2].B).toEqual('31'); }); /** * | NAME | PLACE | WEIGHT | SEX | AGE | * | Mel | 1 | 58 | W | 23 | * | Tom | 2 | 78 | M | 54 | * | Bill | 3 | 92 | M | 31 | */ // FEATURE 'headings: ['A'] && ignoreColumns: [1, 2] && onlyColumns: [0, 4]' it('Option: headings: ["A"] && ignoreColumns: [1, 2] && onlyColumns: [0, 4]', async function () { const converted = await tabletojson.convert(html, { headings: ['A'], ignoreColumns: [1, 2], onlyColumns: [0, 4], }); expect(converted).toBeDefined(); const table = converted[5]; expect(_.has(table[0], 'A')).toBeTruthy(); expect(_.has(table[0], 'B')).toBeFalsy(); expect(_.has(table[0], 'C')).toBeFalsy(); expect(_.has(table[0], 'D')).toBeFalsy(); expect(_.has(table[0], 'E')).toBeFalsy(); expect(table.length).toBe(3); expect(table[0].A).toEqual('Mel'); expect(table[1].A).toEqual('Tom'); expect(table[2].A).toEqual('Bill'); }); // FIX/TEST: https://github.com/maugenst/tabletojson/issues/19 it('Test to check conversion and handling of Kanji, Hiragana, Katakana and latin texts', async function () { const converted = await tabletojson.convert(html); expect(converted).toBeDefined(); const table = converted[6]; expect(_.has(table[0], 'Kanji')).toBeTruthy(); expect(_.has(table[0], 'Hiragana')).toBeTruthy(); expect(_.has(table[0], 'Katakana')).toBeTruthy(); expect(_.has(table[0], 'Rōmaji')).toBeTruthy(); expect(_.has(table[0], 'English')).toBeTruthy(); expect(table[0].Kanji).toEqual('私'); expect(table[0].Hiragana).toEqual('わたし'); expect(table[0].Katakana).toEqual('ワタシ'); expect(table[0].Rōmaji).toEqual('watashi'); expect(table[0].English).toEqual('I, me'); }); // ENHANCEMENT: https://github.com/maugenst/tabletojson/issues/30 it('limit results to only get a configurable amount of rows', async function () { let converted = await tabletojson.convert(html); expect(converted).toBeDefined(); let table = converted[9]; expect(table.length).toBe(200); converted = await tabletojson.convert(html, { limitrows: 5, }); expect(converted).toBeDefined(); table = converted[9]; expect(table.length).toBe(5); }); // ENHANCEMENT: Coverage improvement to also cover rowspan tables // | PARENT | CHILD | AGE | // | | Sue | 15 | // | Marry | Steve | 12 | // | | Tom | 3 | it('Rowspan usage leads to correct object representation', async function () { const converted = await tabletojson.convert(html, { id: ['table11'], }); expect(converted).toBeDefined(); expect(converted.length).toBe(1); const table = converted[0]; expect(table.length).toBe(3); expect(_.has(table[0], 'Parent')).toBeTruthy(); expect(table[0].Parent).toBe('Marry'); expect(table[1].Parent).toBe('Marry'); expect(table[2].Parent).toBe('Marry'); }); // ENHANCEMENT: Coverage improvement to also cover complex rowspan tables // | PARENT | CHILD | AGE | // +--------+-------+-----+ // | | Sue | 15 | // + +-------+-----+ // | Marry | Steve | 12 | // + +-------+-----+ // | | | | // +--------+ Tom | 3 + // | | | | // + Taylor +-------+-----+ // | | Peter | 17 | // +--------+-------+-----+ it('Complex rowspan usage leads to correct object representation', async function () { const converted = await tabletojson.convert(html, { id: ['table12'], }); expect(converted).toBeDefined(); expect(converted.length).toBe(1); const table = converted[0]; expect(table.length).toBe(5); expect(_.has(table[0], 'Parent')).toBeTruthy(); expect(table[0].Parent).toBe('Marry'); expect(table[1].Parent).toBe('Marry'); expect(table[2].Parent).toBe('Marry'); expect(table[3].Parent).toBe('Taylor'); expect(table[4].Parent).toBe('Taylor'); expect(table[0].Child).toBe('Sue'); expect(table[1].Child).toBe('Steve'); expect(table[2].Child).toBe('Tom'); expect(table[3].Child).toBe('Tom'); expect(table[4].Child).toBe('Peter'); expect(table[0].Age).toBe('15'); expect(table[1].Age).toBe('12'); expect(table[2].Age).toBe('3'); expect(table[3].Age).toBe('3'); expect(table[4].Age).toBe('17'); }); it('Options: containsClasses', async function () { const converted = await tabletojson.convert(html, { containsClasses: ['table'], }); expect(converted).toBeDefined(); const firstTable = converted[0]; expect(_.has(firstTable[0], 'Age')).toBeTruthy(); expect(firstTable[0].Age).toBe('2'); }); it('Options: byId', async function () { const converted = await tabletojson.convert(html, { id: ['table9'], }); expect(converted).toBeDefined(); expect(converted.length).toBe(1); const table = converted[0]; expect(_.has(table[0], 'Age')).toBeTruthy(); expect(table[0].Age).toBe('2'); }); it('Options: useFirstRowForHeadings', async function () { const converted = await tabletojson.convert(html, { id: ['table13'], useFirstRowForHeadings: true, }); expect(converted).toBeDefined(); expect(converted.length).toBe(1); const table = converted[0]; expect(_.has(table[0], 'Age')).toBeTruthy(); expect(table[0].Dog).toEqual('Dog'); expect(table[0].Race).toEqual('Race'); expect(table[0].Age).toEqual('Age'); expect(table[1].Dog).toEqual('Donald'); expect(table[1].Race).toEqual('Bobtail'); expect(table[1].Age).toEqual('2'); }); it('Converting a table with no content', async function () { const converted = await tabletojson.convert(html, { id: ['table14'], }); expect(converted).toBeDefined(); expect(Array.isArray(converted)).toBeTruthy(); expect(converted.length).toBe(0); }); it('Options: converting an html page with no tables', async function () { const converted = await tabletojson.convert(noTables); expect(converted).toBeDefined(); expect(converted.length).toBe(0); }); });
the_stack
import type {Class} from "@swim/util"; import {Affinity, MemberFastenerClass} from "@swim/component"; import type {Trait} from "@swim/model"; import type {View} from "@swim/view"; import type {HtmlView} from "@swim/dom"; import type {Graphics} from "@swim/graphics"; import {Controller, TraitViewRef, TraitViewControllerRef, TraitViewControllerSet} from "@swim/controller"; import type {TableLayout} from "../layout/TableLayout"; import type {ColLayout} from "../layout/ColLayout"; import type {CellView} from "../cell/CellView"; import {TextCellView} from "../cell/TextCellView"; import type {CellTrait} from "../cell/CellTrait"; import type {CellController} from "../cell/CellController"; import type {LeafView} from "../leaf/LeafView"; import type {LeafTrait} from "../leaf/LeafTrait"; import type {RowView} from "../row/RowView"; import type {RowTrait} from "../row/RowTrait"; import {RowController} from "../row/RowController"; import type {ColView} from "../col/ColView"; import type {ColTrait} from "../col/ColTrait"; import {ColController} from "../col/ColController"; import type {HeaderView} from "../header/HeaderView"; import type {HeaderTrait} from "../header/HeaderTrait"; import {HeaderController} from "../header/HeaderController"; import {TableView} from "./TableView"; import {TableTrait} from "./TableTrait"; import type {TableControllerObserver} from "./TableControllerObserver"; /** @public */ export interface TableControllerHeaderExt { attachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void; detachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void; attachHeaderView(headerView: HeaderView, headerController: HeaderController): void; detachHeaderView(headerView: HeaderView, headerController: HeaderController): void; } /** @public */ export interface TableControllerColExt { attachColTrait(colTrait: ColTrait, colController: ColController): void; detachColTrait(colTrait: ColTrait, colController: ColController): void; attachColView(colView: ColView, colController: ColController): void; detachColView(colView: ColView, colController: ColController): void; attachColLabelView(colLabelView: HtmlView, colController: ColController): void; detachColLabelView(colLabelView: HtmlView, colController: ColController): void; } /** @public */ export interface TableControllerRowExt { attachRowTrait(rowTrait: RowTrait, rowController: RowController): void; detachRowTrait(rowTrait: RowTrait, rowController: RowController): void; attachRowView(rowView: RowView, rowController: RowController): void; detachRowView(rowView: RowView, rowController: RowController): void; attachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void; detachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void; attachLeafView(leafView: LeafView, rowController: RowController): void; detachLeafView(leafView: LeafView, rowController: RowController): void; attachCell(cellController: CellController, rowController: RowController): void; detachCell(cellController: CellController, rowController: RowController): void; attachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void; detachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void; attachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void; detachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void; attachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void; detachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void; attachTree(treeController: TableController, rowController: RowController): void; detachTree(treeController: TableController, rowController: RowController): void; attachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void; detachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void; attachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void; detachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void; } /** @public */ export class TableController extends Controller { override readonly observerType?: Class<TableControllerObserver>; protected layoutTable(tableLayout: TableLayout, tableView: TableView): void { tableView.layout.setValue(tableLayout, Affinity.Intrinsic); } @TraitViewRef<TableController, TableTrait, TableView>({ traitType: TableTrait, observesTrait: true, willAttachTrait(tableTrait: TableTrait): void { this.owner.callObservers("controllerWillAttachTableTrait", tableTrait, this.owner); }, didAttachTrait(tableTrait: TableTrait): void { const headerTrait = tableTrait.header.trait; if (headerTrait !== null) { this.owner.header.setTrait(headerTrait); } const colTraits = tableTrait.cols.traits; for (const traitId in colTraits) { const colTrait = colTraits[traitId]!; this.owner.cols.addTraitController(colTrait, null, colTrait.key); } const rowTraits = tableTrait.rows.traits; for (const traitId in rowTraits) { const rowTrait = rowTraits[traitId]!; this.owner.rows.addTraitController(rowTrait); } const tableView = this.view; if (tableView !== null) { const tableLayout = tableTrait.layout.value; if (tableLayout !== null) { this.owner.layoutTable(tableLayout, tableView); } } }, willDetachTrait(tableTrait: TableTrait): void { const rowTraits = tableTrait.rows.traits; for (const traitId in rowTraits) { const rowTrait = rowTraits[traitId]!; this.owner.rows.deleteTraitController(rowTrait); } const colTraits = tableTrait.cols.traits; for (const traitId in colTraits) { const colTrait = colTraits[traitId]!; this.owner.cols.deleteTraitController(colTrait); } const headerTrait = tableTrait.header.trait; if (headerTrait !== null) { this.owner.header.deleteTrait(headerTrait); } }, didDetachTrait(tableTrait: TableTrait): void { this.owner.callObservers("controllerDidDetachTableTrait", tableTrait, this.owner); }, traitWillSetTableLayout(newTableLayout: TableLayout | null, oldTableLayout: TableLayout | null): void { this.owner.callObservers("controllerWillSetTableLayout", newTableLayout, oldTableLayout, this.owner); }, traitDidSetTableLayout(newTableLayout: TableLayout | null, oldTableLayout: TableLayout | null): void { this.owner.callObservers("controllerDidSetTableLayout", newTableLayout, oldTableLayout, this.owner); }, traitWillAttachHeader(headerTrait: HeaderTrait): void { this.owner.header.setTrait(headerTrait); }, traitDidDetachHeader(headerTrait: HeaderTrait): void { this.owner.header.deleteTrait(headerTrait); }, traitWillAttachCol(colTrait: ColTrait, targetTrait: Trait): void { this.owner.cols.addTraitController(colTrait, targetTrait, colTrait.key); }, traitDidDetachCol(colTrait: ColTrait): void { this.owner.cols.deleteTraitController(colTrait); }, traitWillAttachRow(rowTrait: RowTrait, targetTrait: Trait): void { this.owner.rows.addTraitController(rowTrait, targetTrait); }, traitDidDetachRow(rowTrait: RowTrait): void { this.owner.rows.deleteTraitController(rowTrait); }, viewType: TableView, observesView: true, initView(tableView: TableView): void { const headerController = this.owner.header.controller; if (headerController !== null) { headerController.header.insertView(tableView); if (tableView.header.view === null) { tableView.header.setView(headerController.header.view); } } const rowControllers = this.owner.rows.controllers; for (const controllerId in rowControllers) { const rowController = rowControllers[controllerId]!; const rowView = rowController.row.view; if (rowView !== null && rowView.parent === null) { rowController.row.insertView(tableView); } } const tableTrait = this.trait; if (tableTrait !== null) { const tableLayout = tableTrait.layout.value; if (tableLayout !== null) { this.owner.layoutTable(tableLayout, tableView); } } }, willAttachView(tableView: TableView): void { this.owner.callObservers("controllerWillAttachTableView", tableView, this.owner); }, didDetachView(tableView: TableView): void { this.owner.callObservers("controllerDidDetachTableView", tableView, this.owner); }, viewWillAttachHeader(headerView: HeaderView): void { const headerController = this.owner.header.controller; if (headerController !== null) { headerController.header.setView(headerView); } }, viewDidDetachHeader(headerView: HeaderView): void { const headerController = this.owner.header.controller; if (headerController !== null) { headerController.header.setView(null); } }, }) readonly table!: TraitViewRef<this, TableTrait, TableView>; static readonly table: MemberFastenerClass<TableController, "table">; @TraitViewControllerRef<TableController, HeaderTrait, HeaderView, HeaderController, TableControllerHeaderExt>({ implements: true, type: HeaderController, binds: true, observes: true, get parentView(): TableView | null { return this.owner.table.view; }, getTraitViewRef(headerController: HeaderController): TraitViewRef<unknown, HeaderTrait, HeaderView> { return headerController.header; }, initController(headerController: HeaderController): void { const tableTrait = this.owner.table.trait; if (tableTrait !== null) { const headerTrait = tableTrait.header.trait; if (headerTrait !== null) { headerController.header.setTrait(headerTrait); } } }, willAttachController(headerController: HeaderController): void { this.owner.callObservers("controllerWillAttachHeader", headerController, this.owner); }, didAttachController(headerController: HeaderController): void { const headerTrait = headerController.header.trait; if (headerTrait !== null) { this.attachHeaderTrait(headerTrait, headerController); } const headerView = headerController.header.view; if (headerView !== null) { this.attachHeaderView(headerView, headerController); } }, willDetachController(headerController: HeaderController): void { const headerView = headerController.header.view; if (headerView !== null) { this.detachHeaderView(headerView, headerController); } const headerTrait = headerController.header.trait; if (headerTrait !== null) { this.detachHeaderTrait(headerTrait, headerController); } }, didDetachController(headerController: HeaderController): void { this.owner.callObservers("controllerDidDetachHeader", headerController, this.owner); }, controllerWillAttachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void { this.owner.callObservers("controllerWillAttachHeaderTrait", headerTrait, this.owner); this.attachHeaderTrait(headerTrait, headerController); }, controllerDidDetachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void { this.detachHeaderTrait(headerTrait, headerController); this.owner.callObservers("controllerDidDetachHeaderTrait", headerTrait, this.owner); }, attachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void { // hook }, detachHeaderTrait(headerTrait: HeaderTrait, headerController: HeaderController): void { // hook }, controllerWillAttachHeaderView(headerView: HeaderView, headerController: HeaderController): void { this.owner.callObservers("controllerWillAttachHeaderView", headerView, this.owner); this.attachHeaderView(headerView, headerController); }, controllerDidDetachHeaderView(headerView: HeaderView, headerController: HeaderController): void { this.detachHeaderView(headerView, headerController); this.owner.callObservers("controllerDidDetachHeaderView", headerView, this.owner); }, attachHeaderView(headerView: HeaderView, headerController: HeaderController): void { //const tableView = this.owner.table.view; //if (tableView !== null && tableView.header.view === null) { // tableView.header.setView(headerView); //} }, detachHeaderView(headerView: HeaderView, headerController: HeaderController): void { headerView.remove(); }, detectController(controller: Controller): HeaderController | null { return controller instanceof HeaderController ? controller : null; }, }) readonly header!: TraitViewControllerRef<this, HeaderTrait, HeaderView, HeaderController>; static readonly header: MemberFastenerClass<TableController, "header">; @TraitViewControllerSet<TableController, ColTrait, ColView, ColController, TableControllerColExt>({ implements: true, type: ColController, binds: true, observes: true, getTraitViewRef(colController: ColController): TraitViewRef<unknown, ColTrait, ColView> { return colController.col; }, willAttachController(colController: ColController): void { this.owner.callObservers("controllerWillAttachCol", colController, this.owner); }, didAttachController(colController: ColController): void { const colTrait = colController.col.trait; if (colTrait !== null) { this.attachColTrait(colTrait, colController); } const colView = colController.col.view; if (colView !== null) { this.attachColView(colView, colController); } }, willDetachController(colController: ColController): void { const colTrait = colController.col.trait; if (colTrait !== null) { this.detachColTrait(colTrait, colController); } const colView = colController.col.view; if (colView !== null) { this.detachColView(colView, colController); } }, didDetachController(colController: ColController): void { this.owner.callObservers("controllerDidDetachCol", colController, this.owner); }, controllerWillAttachColTrait(colTrait: ColTrait, colController: ColController): void { this.owner.callObservers("controllerWillAttachColTrait", colTrait, colController, this.owner); this.attachColTrait(colTrait, colController); }, controllerDidDetachColTrait(colTrait: ColTrait, colController: ColController): void { this.detachColTrait(colTrait, colController); this.owner.callObservers("controllerDidDetachColTrait", colTrait, colController, this.owner); }, attachColTrait(colTrait: ColTrait, colController: ColController): void { // hook }, detachColTrait(colTrait: ColTrait, colController: ColController): void { // hook }, controllerWillSetColLayout(newColLayout: ColLayout | null, oldColLayout: ColLayout | null, colController: ColController): void { this.owner.callObservers("controllerWillSetColLayout", newColLayout, oldColLayout, colController, this.owner); }, controllerDidSetColLayout(newColLayout: ColLayout | null, oldColLayout: ColLayout | null, colController: ColController): void { this.owner.callObservers("controllerDidSetColLayout", newColLayout, oldColLayout, colController, this.owner); }, controllerWillAttachColView(colView: ColView, colController: ColController): void { this.owner.callObservers("controllerWillAttachColView", colView, colController, this.owner); this.attachColView(colView, colController); }, controllerDidDetachColView(colView: ColView, colController: ColController): void { this.detachColView(colView, colController); this.owner.callObservers("controllerDidDetachColView", colView, colController, this.owner); }, attachColView(colView: ColView, colController: ColController): void { const colLabelView = colView.label.view; if (colLabelView !== null) { this.attachColLabelView(colLabelView, colController); } }, detachColView(colView: ColView, colController: ColController): void { const colLabelView = colView.label.view; if (colLabelView !== null) { this.detachColLabelView(colLabelView, colController); } colView.remove(); }, controllerWillAttachColLabelView(colLabelView: HtmlView, colController: ColController): void { this.owner.callObservers("controllerWillAttachColLabelView", colLabelView, colController, this.owner); this.attachColLabelView(colLabelView, colController); }, controllerDidDetachColLabelView(colLabelView: HtmlView, colController: ColController): void { this.detachColLabelView(colLabelView, colController); this.owner.callObservers("controllerDidDetachColLabelView", colLabelView, colController, this.owner); }, attachColLabelView(colLabelView: HtmlView, colController: ColController): void { // hook }, detachColLabelView(colLabelView: HtmlView, colController: ColController): void { // hook }, }) readonly cols!: TraitViewControllerSet<this, ColTrait, ColView, ColController>; static readonly cols: MemberFastenerClass<TableController, "cols">; @TraitViewControllerSet<TableController, RowTrait, RowView, RowController, TableControllerRowExt>({ implements: true, type: RowController, binds: true, observes: true, get parentView(): View | null { return this.owner.table.view; }, getTraitViewRef(rowController: RowController): TraitViewRef<unknown, RowTrait, RowView> { return rowController.row; }, willAttachController(rowController: RowController): void { this.owner.callObservers("controllerWillAttachRow", rowController, this.owner); }, didAttachController(rowController: RowController): void { const rowTrait = rowController.row.trait; if (rowTrait !== null) { this.attachRowTrait(rowTrait, rowController); } const rowView = rowController.row.view; if (rowView !== null) { this.attachRowView(rowView, rowController); } }, willDetachController(rowController: RowController): void { const rowView = rowController.row.view; if (rowView !== null) { this.detachRowView(rowView, rowController); } const rowTrait = rowController.row.trait; if (rowTrait !== null) { this.detachRowTrait(rowTrait, rowController); } }, didDetachController(rowController: RowController): void { this.owner.callObservers("controllerDidDetachRow", rowController, this.owner); }, controllerWillAttachRowTrait(rowTrait: RowTrait, rowController: RowController): void { this.owner.callObservers("controllerWillAttachRowTrait", rowTrait, rowController, this.owner); this.attachRowTrait(rowTrait, rowController); }, controllerDidDetachRowTrait(rowTrait: RowTrait, rowController: RowController): void { this.detachRowTrait(rowTrait, rowController); this.owner.callObservers("controllerDidDetachRowTrait", rowTrait, rowController, this.owner); }, attachRowTrait(rowTrait: RowTrait, rowController: RowController): void { // hook }, detachRowTrait(rowTrait: RowTrait, rowController: RowController): void { // hook }, controllerWillAttachRowView(rowView: RowView, rowController: RowController): void { this.owner.callObservers("controllerWillAttachRowView", rowView, rowController, this.owner); this.attachRowView(rowView, rowController); }, controllerDidDetachRowView(rowView: RowView, rowController: RowController): void { this.detachRowView(rowView, rowController); this.owner.callObservers("controllerDidDetachRowView", rowView, rowController, this.owner); }, attachRowView(rowView: RowView, rowController: RowController): void { // hook }, detachRowView(rowView: RowView, rowController: RowController): void { rowView.remove(); }, controllerWillAttachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void { this.owner.callObservers("controllerWillAttachLeafTrait", leafTrait, rowController, this.owner); this.attachLeafTrait(leafTrait, rowController); }, controllerDidDetachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void { this.detachLeafTrait(leafTrait, rowController); this.owner.callObservers("controllerDidDetachLeafTrait", leafTrait, rowController, this.owner); }, attachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void { // hook }, detachLeafTrait(leafTrait: LeafTrait, rowController: RowController): void { // hook }, controllerWillAttachLeafView(leafView: LeafView, rowController: RowController): void { this.owner.callObservers("controllerWillAttachLeafView", leafView, rowController, this.owner); this.attachLeafView(leafView, rowController); }, controllerDidDetachLeafView(leafView: LeafView, rowController: RowController): void { this.detachLeafView(leafView, rowController); this.owner.callObservers("controllerDidDetachLeafView", leafView, rowController, this.owner); }, attachLeafView(leafView: LeafView, rowController: RowController): void { // hook }, detachLeafView(leafView: LeafView, rowController: RowController): void { // hook }, controllerWillAttachCell(cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachCell", cellController, rowController, this.owner); this.attachCell(cellController, rowController); }, controllerDidDetachCell(cellController: CellController, rowController: RowController): void { this.detachCell(cellController, rowController); this.owner.callObservers("controllerDidDetachCell", cellController, rowController, this.owner); }, attachCell(cellController: CellController, rowController: RowController): void { const cellTrait = cellController.cell.trait; if (cellTrait !== null) { this.attachCellTrait(cellTrait, cellController, rowController); } const cellView = cellController.cell.view; if (cellView !== null) { this.attachCellView(cellView, cellController, rowController); } }, detachCell(cellController: CellController, rowController: RowController): void { const cellTrait = cellController.cell.trait; if (cellTrait !== null) { this.detachCellTrait(cellTrait, cellController, rowController); } const cellView = cellController.cell.view; if (cellView !== null) { this.detachCellView(cellView, cellController, rowController); } }, controllerWillAttachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachCellTrait", cellTrait, cellController, rowController, this.owner); this.attachCellTrait(cellTrait, cellController, rowController); }, controllerDidDetachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void { this.detachCellTrait(cellTrait, cellController, rowController); this.owner.callObservers("controllerDidDetachCellTrait", cellTrait, cellController, rowController, this.owner); }, attachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void { // hook }, detachCellTrait(cellTrait: CellTrait, cellController: CellController, rowController: RowController): void { // hook }, controllerWillAttachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachCellView", cellView, cellController, rowController, this.owner); this.attachCellView(cellView, cellController, rowController); }, controllerDidDetachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void { this.detachCellView(cellView, cellController, rowController); this.owner.callObservers("controllerDidDetachCellView", cellView, cellController, rowController, this.owner); }, attachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void { if (cellView instanceof TextCellView) { const cellContentView = cellView.content.view; if (cellContentView !== null) { this.attachCellContentView(cellContentView, cellController, rowController); } } }, detachCellView(cellView: CellView, cellController: CellController, rowController: RowController): void { if (cellView instanceof TextCellView) { const cellContentView = cellView.content.view; if (cellContentView !== null) { this.detachCellContentView(cellContentView, cellController, rowController); } } }, controllerWillAttachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachCellContentView", cellContentView, cellController, rowController, this.owner); this.attachCellContentView(cellContentView, cellController, rowController); }, controllerDidDetachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void { this.detachCellContentView(cellContentView, cellController, rowController); this.owner.callObservers("controllerDidDetachCellContentView", cellContentView, cellController, rowController, this.owner); }, attachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void { // hook }, detachCellContentView(cellContentView: HtmlView, cellController: CellController, rowController: RowController): void { // hook }, controllerWillSetCellIcon(newCellIcon: Graphics | null, oldCellIcon: Graphics | null, cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerWillSetCellIcon", newCellIcon, oldCellIcon, cellController, rowController, this.owner); }, controllerDidSetCellIcon(newCellIcon: Graphics | null, oldCellIcon: Graphics | null, cellController: CellController, rowController: RowController): void { this.owner.callObservers("controllerDidSetCellIcon", newCellIcon, oldCellIcon, cellController, rowController, this.owner); }, controllerWillAttachTree(treeController: TableController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachTree", treeController, rowController, this.owner); this.attachTree(treeController, rowController); }, controllerDidDetachTree(treeController: TableController, rowController: RowController): void { this.detachTree(treeController, rowController); this.owner.callObservers("controllerDidDetachTree", treeController, rowController, this.owner); }, attachTree(treeController: TableController, rowController: RowController): void { const treeTrait = treeController.table.trait; if (treeTrait !== null) { this.attachTreeTrait(treeTrait, treeController, rowController); } const treeView = treeController.table.view; if (treeView !== null) { this.attachTreeView(treeView, treeController, rowController); } }, detachTree(treeController: TableController, rowController: RowController): void { const treeTrait = treeController.table.trait; if (treeTrait !== null) { this.detachTreeTrait(treeTrait, treeController, rowController); } const treeView = treeController.table.view; if (treeView !== null) { this.detachTreeView(treeView, treeController, rowController); } }, controllerWillAttachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachTreeTrait", treeTrait, treeController, rowController, this.owner); this.attachTreeTrait(treeTrait, treeController, rowController); }, controllerDidDetachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void { this.detachTreeTrait(treeTrait, treeController, rowController); this.owner.callObservers("controllerDidDetachTreeTrait", treeTrait, treeController, rowController, this.owner); }, attachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void { // hook }, detachTreeTrait(treeTrait: TableTrait, treeController: TableController, rowController: RowController): void { // hook }, controllerWillAttachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void { this.owner.callObservers("controllerWillAttachTreeView", treeView, treeController, rowController, this.owner); this.attachTreeView(treeView, treeController, rowController); }, controllerDidDetachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void { this.detachTreeView(treeView, treeController, rowController); this.owner.callObservers("controllerDidDetachTreeView", treeView, treeController, rowController, this.owner); }, attachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void { // hook }, detachTreeView(treeView: TableView, treeController: TableController, rowController: RowController): void { // hook }, controllerWillExpandRowView(rowView: RowView, rowController: RowController): void { this.owner.callObservers("controllerWillExpandRowView", rowView, rowController, this.owner); }, controllerDidExpandRowView(rowView: RowView, rowController: RowController): void { this.owner.callObservers("controllerDidExpandRowView", rowView, rowController, this.owner); }, controllerWillCollapseRowView(rowView: RowView, rowController: RowController): void { this.owner.callObservers("controllerWillCollapseRowView", rowView, rowController, this.owner); }, controllerDidCollapseRowView(rowView: RowView, rowController: RowController): void { this.owner.callObservers("controllerDidCollapseRowView", rowView, rowController, this.owner); }, }) readonly rows!: TraitViewControllerSet<this, RowTrait, RowView, RowController>; static readonly rows: MemberFastenerClass<TableController, "rows">; }
the_stack
// FP Interfaces interface CurriedFn1<A, R> { <A>(a: A): R } interface CurriedFn2<A, B, R> { <A>(a: A): CurriedFn1<B, R> <A, B>(a: A, b: B): R } interface CurriedFn3<A, B, C, R> { <A>(a: A): CurriedFn2<B, C, R> <A, B>(a: A, b: B): CurriedFn1<C, R> <A, B, C>(a: A, b: B, c: C): R } interface CurriedFn4<A, B, C, D, R> { <A>(a: A): CurriedFn3<B, C, D, R> <A, B>(a: A, b: B): CurriedFn2<C, D, R> <A, B, C>(a: A, b: B, c: C): CurriedFn1<D, R> <A, B, C, D>(a: A, b: B, c: C, d: D): R } declare module 'date-fns-tz' { import { Locale } from 'date-fns' export type OptionsWithTZ = { weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6 firstWeekContainsDate?: 1 | 2 | 3 | 4 | 5 | 6 | 7 additionalDigits?: 0 | 1 | 2 timeZone?: string locale?: Locale includeSeconds?: boolean addSuffix?: boolean unit?: 'second' | 'minute' | 'hour' | 'day' | 'month' | 'year' roundingMethod?: 'floor' | 'ceil' | 'round' awareOfUnicodeTokens?: boolean } } // Regular Functions declare module 'date-fns-tz' { import { OptionsWithTZ } from 'date-fns-tz' function format(date: Date | string | number, format: string, options?: OptionsWithTZ): string namespace format {} function getTimezoneOffset(timeZone: string, date?: Date | number): number namespace getTimezoneOffset {} function toDate(argument: Date | string | number, options?: OptionsWithTZ): Date namespace toDate {} function utcToZonedTime( date: Date | string | number, timeZone: string, options?: OptionsWithTZ ): Date namespace utcToZonedTime {} function zonedTimeToUtc( date: Date | string | number, timeZone: string, options?: OptionsWithTZ ): Date namespace zonedTimeToUtc {} } declare module 'date-fns-tz/format' { import { format } from 'date-fns-tz' export = format } declare module 'date-fns-tz/getTimezoneOffset' { import { getTimezoneOffset } from 'date-fns-tz' export = getTimezoneOffset } declare module 'date-fns-tz/toDate' { import { toDate } from 'date-fns-tz' export = toDate } declare module 'date-fns-tz/utcToZonedTime' { import { utcToZonedTime } from 'date-fns-tz' export = utcToZonedTime } declare module 'date-fns-tz/zonedTimeToUtc' { import { zonedTimeToUtc } from 'date-fns-tz' export = zonedTimeToUtc } declare module 'date-fns-tz/format/index' { import { format } from 'date-fns-tz' export = format } declare module 'date-fns-tz/getTimezoneOffset/index' { import { getTimezoneOffset } from 'date-fns-tz' export = getTimezoneOffset } declare module 'date-fns-tz/toDate/index' { import { toDate } from 'date-fns-tz' export = toDate } declare module 'date-fns-tz/utcToZonedTime/index' { import { utcToZonedTime } from 'date-fns-tz' export = utcToZonedTime } declare module 'date-fns-tz/zonedTimeToUtc/index' { import { zonedTimeToUtc } from 'date-fns-tz' export = zonedTimeToUtc } declare module 'date-fns-tz/format/index.js' { import { format } from 'date-fns-tz' export = format } declare module 'date-fns-tz/getTimezoneOffset/index.js' { import { getTimezoneOffset } from 'date-fns-tz' export = getTimezoneOffset } declare module 'date-fns-tz/toDate/index.js' { import { toDate } from 'date-fns-tz' export = toDate } declare module 'date-fns-tz/utcToZonedTime/index.js' { import { utcToZonedTime } from 'date-fns-tz' export = utcToZonedTime } declare module 'date-fns-tz/zonedTimeToUtc/index.js' { import { zonedTimeToUtc } from 'date-fns-tz' export = zonedTimeToUtc } // FP Functions declare module 'date-fns-tz/fp' { import { OptionsWithTZ } from 'date-fns-tz' const format: CurriedFn2<string, Date | string | number, string> namespace format {} const formatWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, string> namespace formatWithOptions {} const getTimezoneOffset: CurriedFn2<Date | number, string, number> namespace getTimezoneOffset {} const toDate: CurriedFn1<Date | string | number, Date> namespace toDate {} const toDateWithOptions: CurriedFn2<OptionsWithTZ, Date | string | number, Date> namespace toDateWithOptions {} const utcToZonedTime: CurriedFn2<string, Date | string | number, Date> namespace utcToZonedTime {} const utcToZonedTimeWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, Date> namespace utcToZonedTimeWithOptions {} const zonedTimeToUtc: CurriedFn2<string, Date | string | number, Date> namespace zonedTimeToUtc {} const zonedTimeToUtcWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, Date> namespace zonedTimeToUtcWithOptions {} } declare module 'date-fns-tz/fp/format' { import { format } from 'date-fns-tz/fp' export = format } declare module 'date-fns-tz/fp/formatWithOptions' { import { formatWithOptions } from 'date-fns-tz/fp' export = formatWithOptions } declare module 'date-fns-tz/fp/getTimezoneOffset' { import { getTimezoneOffset } from 'date-fns-tz/fp' export = getTimezoneOffset } declare module 'date-fns-tz/fp/toDate' { import { toDate } from 'date-fns-tz/fp' export = toDate } declare module 'date-fns-tz/fp/toDateWithOptions' { import { toDateWithOptions } from 'date-fns-tz/fp' export = toDateWithOptions } declare module 'date-fns-tz/fp/utcToZonedTime' { import { utcToZonedTime } from 'date-fns-tz/fp' export = utcToZonedTime } declare module 'date-fns-tz/fp/utcToZonedTimeWithOptions' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/fp' export = utcToZonedTimeWithOptions } declare module 'date-fns-tz/fp/zonedTimeToUtc' { import { zonedTimeToUtc } from 'date-fns-tz/fp' export = zonedTimeToUtc } declare module 'date-fns-tz/fp/zonedTimeToUtcWithOptions' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/fp' export = zonedTimeToUtcWithOptions } declare module 'date-fns-tz/fp/format/index' { import { format } from 'date-fns-tz/fp' export = format } declare module 'date-fns-tz/fp/formatWithOptions/index' { import { formatWithOptions } from 'date-fns-tz/fp' export = formatWithOptions } declare module 'date-fns-tz/fp/getTimezoneOffset/index' { import { getTimezoneOffset } from 'date-fns-tz/fp' export = getTimezoneOffset } declare module 'date-fns-tz/fp/toDate/index' { import { toDate } from 'date-fns-tz/fp' export = toDate } declare module 'date-fns-tz/fp/toDateWithOptions/index' { import { toDateWithOptions } from 'date-fns-tz/fp' export = toDateWithOptions } declare module 'date-fns-tz/fp/utcToZonedTime/index' { import { utcToZonedTime } from 'date-fns-tz/fp' export = utcToZonedTime } declare module 'date-fns-tz/fp/utcToZonedTimeWithOptions/index' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/fp' export = utcToZonedTimeWithOptions } declare module 'date-fns-tz/fp/zonedTimeToUtc/index' { import { zonedTimeToUtc } from 'date-fns-tz/fp' export = zonedTimeToUtc } declare module 'date-fns-tz/fp/zonedTimeToUtcWithOptions/index' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/fp' export = zonedTimeToUtcWithOptions } declare module 'date-fns-tz/fp/format/index.js' { import { format } from 'date-fns-tz/fp' export = format } declare module 'date-fns-tz/fp/formatWithOptions/index.js' { import { formatWithOptions } from 'date-fns-tz/fp' export = formatWithOptions } declare module 'date-fns-tz/fp/getTimezoneOffset/index.js' { import { getTimezoneOffset } from 'date-fns-tz/fp' export = getTimezoneOffset } declare module 'date-fns-tz/fp/toDate/index.js' { import { toDate } from 'date-fns-tz/fp' export = toDate } declare module 'date-fns-tz/fp/toDateWithOptions/index.js' { import { toDateWithOptions } from 'date-fns-tz/fp' export = toDateWithOptions } declare module 'date-fns-tz/fp/utcToZonedTime/index.js' { import { utcToZonedTime } from 'date-fns-tz/fp' export = utcToZonedTime } declare module 'date-fns-tz/fp/utcToZonedTimeWithOptions/index.js' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/fp' export = utcToZonedTimeWithOptions } declare module 'date-fns-tz/fp/zonedTimeToUtc/index.js' { import { zonedTimeToUtc } from 'date-fns-tz/fp' export = zonedTimeToUtc } declare module 'date-fns-tz/fp/zonedTimeToUtcWithOptions/index.js' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/fp' export = zonedTimeToUtcWithOptions } // ECMAScript Module Functions declare module 'date-fns-tz/esm' { import { OptionsWithTZ } from 'date-fns-tz' function format(date: Date | string | number, format: string, options?: OptionsWithTZ): string namespace format {} function getTimezoneOffset(timeZone: string, date?: Date | number): number namespace getTimezoneOffset {} function toDate(argument: Date | string | number, options?: OptionsWithTZ): Date namespace toDate {} function utcToZonedTime( date: Date | string | number, timeZone: string, options?: OptionsWithTZ ): Date namespace utcToZonedTime {} function zonedTimeToUtc( date: Date | string | number, timeZone: string, options?: OptionsWithTZ ): Date namespace zonedTimeToUtc {} } declare module 'date-fns-tz/esm/format' { import { format } from 'date-fns-tz/esm' export default format } declare module 'date-fns-tz/esm/getTimezoneOffset' { import { getTimezoneOffset } from 'date-fns-tz/esm' export default getTimezoneOffset } declare module 'date-fns-tz/esm/toDate' { import { toDate } from 'date-fns-tz/esm' export default toDate } declare module 'date-fns-tz/esm/utcToZonedTime' { import { utcToZonedTime } from 'date-fns-tz/esm' export default utcToZonedTime } declare module 'date-fns-tz/esm/zonedTimeToUtc' { import { zonedTimeToUtc } from 'date-fns-tz/esm' export default zonedTimeToUtc } declare module 'date-fns-tz/esm/format/index' { import { format } from 'date-fns-tz/esm' export default format } declare module 'date-fns-tz/esm/getTimezoneOffset/index' { import { getTimezoneOffset } from 'date-fns-tz/esm' export default getTimezoneOffset } declare module 'date-fns-tz/esm/toDate/index' { import { toDate } from 'date-fns-tz/esm' export default toDate } declare module 'date-fns-tz/esm/utcToZonedTime/index' { import { utcToZonedTime } from 'date-fns-tz/esm' export default utcToZonedTime } declare module 'date-fns-tz/esm/zonedTimeToUtc/index' { import { zonedTimeToUtc } from 'date-fns-tz/esm' export default zonedTimeToUtc } declare module 'date-fns-tz/esm/format/index.js' { import { format } from 'date-fns-tz/esm' export default format } declare module 'date-fns-tz/esm/getTimezoneOffset/index.js' { import { getTimezoneOffset } from 'date-fns-tz/esm' export default getTimezoneOffset } declare module 'date-fns-tz/esm/toDate/index.js' { import { toDate } from 'date-fns-tz/esm' export default toDate } declare module 'date-fns-tz/esm/utcToZonedTime/index.js' { import { utcToZonedTime } from 'date-fns-tz/esm' export default utcToZonedTime } declare module 'date-fns-tz/esm/zonedTimeToUtc/index.js' { import { zonedTimeToUtc } from 'date-fns-tz/esm' export default zonedTimeToUtc } // ECMAScript Module FP Functions declare module 'date-fns-tz/esm/fp' { import { OptionsWithTZ } from 'date-fns-tz' const format: CurriedFn2<string, Date | string | number, string> namespace format {} const formatWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, string> namespace formatWithOptions {} const getTimezoneOffset: CurriedFn2<Date | number, string, number> namespace getTimezoneOffset {} const toDate: CurriedFn1<Date | string | number, Date> namespace toDate {} const toDateWithOptions: CurriedFn2<OptionsWithTZ, Date | string | number, Date> namespace toDateWithOptions {} const utcToZonedTime: CurriedFn2<string, Date | string | number, Date> namespace utcToZonedTime {} const utcToZonedTimeWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, Date> namespace utcToZonedTimeWithOptions {} const zonedTimeToUtc: CurriedFn2<string, Date | string | number, Date> namespace zonedTimeToUtc {} const zonedTimeToUtcWithOptions: CurriedFn3<OptionsWithTZ, string, Date | string | number, Date> namespace zonedTimeToUtcWithOptions {} } declare module 'date-fns-tz/esm/fp/format' { import { format } from 'date-fns-tz/esm/fp' export default format } declare module 'date-fns-tz/esm/fp/formatWithOptions' { import { formatWithOptions } from 'date-fns-tz/esm/fp' export default formatWithOptions } declare module 'date-fns-tz/esm/fp/getTimezoneOffset' { import { getTimezoneOffset } from 'date-fns-tz/esm/fp' export default getTimezoneOffset } declare module 'date-fns-tz/esm/fp/toDate' { import { toDate } from 'date-fns-tz/esm/fp' export default toDate } declare module 'date-fns-tz/esm/fp/toDateWithOptions' { import { toDateWithOptions } from 'date-fns-tz/esm/fp' export default toDateWithOptions } declare module 'date-fns-tz/esm/fp/utcToZonedTime' { import { utcToZonedTime } from 'date-fns-tz/esm/fp' export default utcToZonedTime } declare module 'date-fns-tz/esm/fp/utcToZonedTimeWithOptions' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/esm/fp' export default utcToZonedTimeWithOptions } declare module 'date-fns-tz/esm/fp/zonedTimeToUtc' { import { zonedTimeToUtc } from 'date-fns-tz/esm/fp' export default zonedTimeToUtc } declare module 'date-fns-tz/esm/fp/zonedTimeToUtcWithOptions' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/esm/fp' export default zonedTimeToUtcWithOptions } declare module 'date-fns-tz/esm/fp/format/index' { import { format } from 'date-fns-tz/esm/fp' export default format } declare module 'date-fns-tz/esm/fp/formatWithOptions/index' { import { formatWithOptions } from 'date-fns-tz/esm/fp' export default formatWithOptions } declare module 'date-fns-tz/esm/fp/getTimezoneOffset/index' { import { getTimezoneOffset } from 'date-fns-tz/esm/fp' export default getTimezoneOffset } declare module 'date-fns-tz/esm/fp/toDate/index' { import { toDate } from 'date-fns-tz/esm/fp' export default toDate } declare module 'date-fns-tz/esm/fp/toDateWithOptions/index' { import { toDateWithOptions } from 'date-fns-tz/esm/fp' export default toDateWithOptions } declare module 'date-fns-tz/esm/fp/utcToZonedTime/index' { import { utcToZonedTime } from 'date-fns-tz/esm/fp' export default utcToZonedTime } declare module 'date-fns-tz/esm/fp/utcToZonedTimeWithOptions/index' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/esm/fp' export default utcToZonedTimeWithOptions } declare module 'date-fns-tz/esm/fp/zonedTimeToUtc/index' { import { zonedTimeToUtc } from 'date-fns-tz/esm/fp' export default zonedTimeToUtc } declare module 'date-fns-tz/esm/fp/zonedTimeToUtcWithOptions/index' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/esm/fp' export default zonedTimeToUtcWithOptions } declare module 'date-fns-tz/esm/fp/format/index.js' { import { format } from 'date-fns-tz/esm/fp' export default format } declare module 'date-fns-tz/esm/fp/formatWithOptions/index.js' { import { formatWithOptions } from 'date-fns-tz/esm/fp' export default formatWithOptions } declare module 'date-fns-tz/esm/fp/getTimezoneOffset/index.js' { import { getTimezoneOffset } from 'date-fns-tz/esm/fp' export default getTimezoneOffset } declare module 'date-fns-tz/esm/fp/toDate/index.js' { import { toDate } from 'date-fns-tz/esm/fp' export default toDate } declare module 'date-fns-tz/esm/fp/toDateWithOptions/index.js' { import { toDateWithOptions } from 'date-fns-tz/esm/fp' export default toDateWithOptions } declare module 'date-fns-tz/esm/fp/utcToZonedTime/index.js' { import { utcToZonedTime } from 'date-fns-tz/esm/fp' export default utcToZonedTime } declare module 'date-fns-tz/esm/fp/utcToZonedTimeWithOptions/index.js' { import { utcToZonedTimeWithOptions } from 'date-fns-tz/esm/fp' export default utcToZonedTimeWithOptions } declare module 'date-fns-tz/esm/fp/zonedTimeToUtc/index.js' { import { zonedTimeToUtc } from 'date-fns-tz/esm/fp' export default zonedTimeToUtc } declare module 'date-fns-tz/esm/fp/zonedTimeToUtcWithOptions/index.js' { import { zonedTimeToUtcWithOptions } from 'date-fns-tz/esm/fp' export default zonedTimeToUtcWithOptions }
the_stack
import { Framebuffer, Texture2D, isWebGL2, readPixelsToArray, cssToDeviceRatio, cssToDevicePixels } from '@luma.gl/core'; import GL from '@luma.gl/constants'; import PickLayersPass, {PickingColorDecoder} from '../passes/pick-layers-pass'; import {getClosestObject, getUniqueObjects, PickedPixel} from './picking/query-object'; import { processPickInfo, getLayerPickingInfo, getEmptyPickingInfo, PickingInfo } from './picking/pick-info'; import type {Framebuffer as LumaFramebuffer} from '@luma.gl/webgl'; import type {FilterContext} from '../passes/layers-pass'; import type Layer from './layer'; import type Effect from './effect'; import type View from '../views/view'; import type Viewport from '../viewports/viewport'; export type PickByPointOptions = { // User config x: number; y: number; radius?: number; depth?: number; mode?: string; unproject3D?: boolean; // Deck context layers: Layer[]; views: Record<string, View>; viewports: Viewport[]; onViewportActive: (viewport: Viewport) => void; effects: Effect[]; }; export type PickByRectOptions = { // User config x: number; y: number; width?: number; height?: number; mode?: string; maxObjects?: number | null; // Deck context layers: Layer[]; views: Record<string, View>; viewports: Viewport[]; onViewportActive: (viewport: Viewport) => void; effects: Effect[]; }; type Rect = {x: number; y: number; width: number; height: number}; /** Manages picking in a Deck context */ export default class DeckPicker { gl: WebGLRenderingContext; pickingFBO?: LumaFramebuffer; depthFBO?: LumaFramebuffer; pickLayersPass: PickLayersPass; layerFilter?: (context: FilterContext) => boolean; /** Identifiers of the previously picked object, for callback tracking and auto highlight */ lastPickedInfo: { index: number; layerId: string | null; info: PickingInfo | null; }; _pickable: boolean = true; constructor(gl: WebGLRenderingContext) { this.gl = gl; this.pickLayersPass = new PickLayersPass(gl); this.lastPickedInfo = { index: -1, layerId: null, info: null }; } setProps(props: any): void { if ('layerFilter' in props) { this.layerFilter = props.layerFilter; } if ('_pickable' in props) { this._pickable = props._pickable; } } finalize() { if (this.pickingFBO) { this.pickingFBO.delete(); } if (this.depthFBO) { this.depthFBO.color.delete(); this.depthFBO.delete(); } } /** Pick the closest info at given coordinate */ pickObject(opts: PickByPointOptions) { return this._pickClosestObject(opts); } /** Get all unique infos within a bounding box */ pickObjects(opts: PickByRectOptions) { return this._pickVisibleObjects(opts); } // Returns a new picking info object by assuming the last picked object is still picked getLastPickedObject({x, y, layers, viewports}, lastPickedInfo = this.lastPickedInfo.info) { const lastPickedLayerId = lastPickedInfo && lastPickedInfo.layer && lastPickedInfo.layer.id; const lastPickedViewportId = lastPickedInfo && lastPickedInfo.viewport && lastPickedInfo.viewport.id; const layer = lastPickedLayerId ? layers.find(l => l.id === lastPickedLayerId) : null; const viewport = (lastPickedViewportId && viewports.find(v => v.id === lastPickedViewportId)) || viewports[0]; const coordinate = viewport && viewport.unproject([x - viewport.x, y - viewport.y]); const info = { x, y, viewport, coordinate, layer }; return {...lastPickedInfo, ...info}; } // Private /** Ensures that picking framebuffer exists and matches the canvas size */ _resizeBuffer() { const {gl} = this; // Create a frame buffer if not already available if (!this.pickingFBO) { this.pickingFBO = new Framebuffer(gl); if (Framebuffer.isSupported(gl, {colorBufferFloat: true})) { const depthFBO = new Framebuffer(gl); depthFBO.attach({ [GL.COLOR_ATTACHMENT0]: new Texture2D(gl, { format: isWebGL2(gl) ? GL.RGBA32F : GL.RGBA, type: GL.FLOAT }) }); this.depthFBO = depthFBO; } } // Resize it to current canvas size (this is a noop if size hasn't changed) this.pickingFBO?.resize({width: gl.canvas.width, height: gl.canvas.height}); this.depthFBO?.resize({width: gl.canvas.width, height: gl.canvas.height}); } /** Preliminary filtering of the layers list. Skid picking pass if no layer is pickable. */ _getPickable(layers: Layer[]): Layer[] | null { if (this._pickable === false) { return null; } const pickableLayers = layers.filter(layer => layer.isPickable() && !layer.isComposite); return pickableLayers.length ? pickableLayers : null; } // eslint-disable-next-line max-statements,complexity /** Pick the closest object at the given coordinate */ _pickClosestObject({ layers, views, viewports, x, y, radius = 0, depth = 1, mode = 'query', unproject3D, onViewportActive, effects }: PickByPointOptions): { result: PickingInfo[]; emptyInfo: PickingInfo | undefined; } { const pickableLayers = this._getPickable(layers); const pixelRatio = cssToDeviceRatio(this.gl); if (!pickableLayers) { return { result: [], emptyInfo: getEmptyPickingInfo({viewports, x, y, pixelRatio}) }; } this._resizeBuffer(); // Convert from canvas top-left to WebGL bottom-left coordinates // Top-left coordinates [x, y] to bottom-left coordinates [deviceX, deviceY] // And compensate for pixelRatio const devicePixelRange = cssToDevicePixels(this.gl, [x, y], true); const devicePixel = [ devicePixelRange.x + Math.floor(devicePixelRange.width / 2), devicePixelRange.y + Math.floor(devicePixelRange.height / 2) ]; const deviceRadius = Math.round(radius * pixelRatio); const {width, height} = this.pickingFBO as LumaFramebuffer; const deviceRect = this._getPickingRect({ deviceX: devicePixel[0], deviceY: devicePixel[1], deviceRadius, deviceWidth: width, deviceHeight: height }); let infos: Map<string | null, PickingInfo> | undefined; const result: PickingInfo[] = []; const affectedLayers = new Set<Layer>(); for (let i = 0; i < depth; i++) { let pickInfo: PickedPixel; if (deviceRect) { const pickedResult = this._drawAndSample({ layers: pickableLayers, views, viewports, onViewportActive, deviceRect, effects, pass: `picking:${mode}` }); pickInfo = getClosestObject({ ...pickedResult, deviceX: devicePixel[0], deviceY: devicePixel[1], deviceRadius, deviceRect }); } else { pickInfo = { pickedColor: null, pickedObjectIndex: -1 }; } let z; if (pickInfo.pickedLayer && unproject3D && this.depthFBO) { const pickedResultPass2 = this._drawAndSample( { layers: [pickInfo.pickedLayer], views, viewports, onViewportActive, deviceRect: { x: pickInfo.pickedX as number, y: pickInfo.pickedY as number, width: 1, height: 1 }, effects, pass: `picking:${mode}:z` }, true ); // picked value is in common space (pixels) from the camera target (viewport.position) // convert it to meters from the ground z = pickedResultPass2.pickedColors[0]; } // Only exclude if we need to run picking again. // We need to run picking again if an object is detected AND // we have not exhausted the requested depth. if (pickInfo.pickedLayer && i + 1 < depth) { affectedLayers.add(pickInfo.pickedLayer); pickInfo.pickedLayer.disablePickingIndex(pickInfo.pickedObjectIndex); } // This logic needs to run even if no object is picked. infos = processPickInfo({ pickInfo, lastPickedInfo: this.lastPickedInfo, mode, layers: pickableLayers, viewports, x, y, z, pixelRatio }); for (const info of infos.values()) { if (info.layer) { result.push(info); } } // If no object is picked stop. if (!pickInfo.pickedColor) { break; } } // reset only affected buffers for (const layer of affectedLayers) { layer.restorePickingColors(); } return {result, emptyInfo: infos && infos.get(null)}; } /** Pick all objects within the given bounding box */ _pickVisibleObjects({ layers, views, viewports, x, y, width = 1, height = 1, mode = 'query', maxObjects = null, onViewportActive, effects }: PickByRectOptions): PickingInfo[] { const pickableLayers = this._getPickable(layers); if (!pickableLayers) { return []; } this._resizeBuffer(); // Convert from canvas top-left to WebGL bottom-left coordinates // And compensate for pixelRatio const pixelRatio = cssToDeviceRatio(this.gl); const leftTop = cssToDevicePixels(this.gl, [x, y], true); // take left and top (y inverted in device pixels) from start location const deviceLeft = leftTop.x; const deviceTop = leftTop.y + leftTop.height; // take right and bottom (y inverted in device pixels) from end location const rightBottom = cssToDevicePixels(this.gl, [x + width, y + height], true); const deviceRight = rightBottom.x + rightBottom.width; const deviceBottom = rightBottom.y; const deviceRect = { x: deviceLeft, y: deviceBottom, // deviceTop and deviceRight represent the first pixel outside the desired rect width: deviceRight - deviceLeft, height: deviceTop - deviceBottom }; const pickedResult = this._drawAndSample({ layers: pickableLayers, views, viewports, onViewportActive, deviceRect, effects, pass: `picking:${mode}` }); const pickInfos = getUniqueObjects(pickedResult); // Only return unique infos, identified by info.object const uniqueInfos = new Map(); const isMaxObjects = Number.isFinite(maxObjects); for (let i = 0; i < pickInfos.length; i++) { if (isMaxObjects && maxObjects && uniqueInfos.size >= maxObjects) { break; } const pickInfo = pickInfos[i]; let info: PickingInfo = { color: pickInfo.pickedColor, layer: null, index: pickInfo.pickedObjectIndex, picked: true, x, y, pixelRatio }; info = getLayerPickingInfo({layer: pickInfo.pickedLayer as Layer, info, mode}); if (!uniqueInfos.has(info.object)) { uniqueInfos.set(info.object, info); } } return Array.from(uniqueInfos.values()); } /** Renders layers into the picking buffer with picking colors and read the pixels. */ _drawAndSample(params: { deviceRect: Rect; pass: string; layers: Layer[]; views: Record<string, View>; viewports: Viewport[]; onViewportActive: (viewport: Viewport) => void; effects: Effect[]; }): { pickedColors: Uint8Array; decodePickingColor: PickingColorDecoder; }; /** Renders layers into the picking buffer with encoded z values and read the pixels. */ _drawAndSample( params: { deviceRect: Rect; pass: string; layers: Layer[]; views: Record<string, View>; viewports: Viewport[]; onViewportActive: (viewport: Viewport) => void; effects: Effect[]; }, pickZ: true ): { pickedColors: Float32Array; decodePickingColor: null; }; _drawAndSample( { layers, views, viewports, onViewportActive, deviceRect, effects, pass }: { deviceRect: Rect; pass: string; layers: Layer[]; views: Record<string, View>; viewports: Viewport[]; onViewportActive: (viewport: Viewport) => void; effects: Effect[]; }, pickZ: boolean = false ): { pickedColors: Uint8Array | Float32Array; decodePickingColor: PickingColorDecoder | null; } { const pickingFBO = pickZ ? this.depthFBO : this.pickingFBO; const {decodePickingColor} = this.pickLayersPass.render({ layers, layerFilter: this.layerFilter, views, viewports, onViewportActive, pickingFBO, deviceRect, effects, pass, pickZ }); // Read from an already rendered picking buffer // Returns an Uint8ClampedArray of picked pixels const {x, y, width, height} = deviceRect; const pickedColors = new (pickZ ? Float32Array : Uint8Array)(width * height * 4); readPixelsToArray(pickingFBO, { sourceX: x, sourceY: y, sourceWidth: width, sourceHeight: height, target: pickedColors }); return {pickedColors, decodePickingColor}; } // Calculate a picking rect centered on deviceX and deviceY and clipped to device // Returns null if pixel is outside of device _getPickingRect({ deviceX, deviceY, deviceRadius, deviceWidth, deviceHeight }: { deviceX: number; deviceY: number; deviceRadius: number; deviceWidth: number; deviceHeight: number; }): Rect | null { // Create a box of size `radius * 2 + 1` centered at [deviceX, deviceY] const x = Math.max(0, deviceX - deviceRadius); const y = Math.max(0, deviceY - deviceRadius); const width = Math.min(deviceWidth, deviceX + deviceRadius + 1) - x; const height = Math.min(deviceHeight, deviceY + deviceRadius + 1) - y; // x, y out of bounds. if (width <= 0 || height <= 0) { return null; } return {x, y, width, height}; } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { CancellationToken, Command, CompletionContext, CompletionItem, CompletionItemKind, CompletionItemProvider, Position, Range, SnippetString, TextDocument, Uri, workspace, WorkspaceConfiguration } from "vscode"; import { AttributeQuoteType, Attributes, IncludeAttributesCustom, IncludeAttributesSetType, parseAttributes, VALUE_PATTERN } from "../entities/attribute"; import { CatchInfo, catchProperties, CatchPropertyDetails, parseCatches } from "../entities/catch"; import { cgiVariables } from "../entities/cgi"; import { Component, componentDottedPathPrefix, componentExtendsPathPrefix, COMPONENT_EXT, isInComponentHead, isSubcomponentOrEqual } from "../entities/component"; import { IPropertyData, IAtDirectiveData } from "../entities/css/cssLanguageTypes"; import { cssDataManager, getEntryDescription as getCSSEntryDescription, cssWordRegex } from "../entities/css/languageFacts"; import { DataType } from "../entities/dataType"; import { constructSyntaxString } from "../entities/function"; import { constructAttributeSnippet, constructTagSnippet, GlobalFunction, GlobalFunctions, GlobalTag, GlobalTags, globalTagSyntaxToScript } from "../entities/globals"; import { IAttributeData as HTMLAttributeData, IValueData as HTMLValueData } from "../entities/html/htmlLanguageTypes"; import { constructHTMLAttributeSnippet } from "../entities/html/htmlTag"; import { getAttribute, htmlDataProvider, isKnownTag as isKnownHTMLTag } from "../entities/html/languageFacts"; import { KeywordDetails, keywords } from "../entities/keyword"; import { Parameter } from "../entities/parameter"; import { isQuery, queryObjectProperties } from "../entities/query"; import { getValidScopesPrefixPattern, getVariableScopePrefixPattern, Scope, scopes, unscopedPrecedence } from "../entities/scope"; import { Signature } from "../entities/signature"; import { ComponentPathAttributes, expressionCfmlTags, getCfScriptTagAttributePattern, getCfTagAttributePattern, getComponentPathAttributes, getTagAttributePattern, getTagPrefixPattern } from "../entities/tag"; import { Access, parseScriptFunctions, parseTagFunctions, UserFunction } from "../entities/userFunction"; import { collectDocumentVariableAssignments, getApplicationVariables, getBestMatchingVariable, getMatchingVariables, getServerVariables, getVariableExpressionPrefixPattern, getVariablePrefixPattern, getVariableTypeString, usesConstantConvention, Variable } from "../entities/variable"; import { CFMLEngine } from "../utils/cfdocs/cfmlEngine"; import { MyMap, MySet } from "../utils/collections"; import { getCfScriptRanges, isInCss, isInRanges } from "../utils/contextUtil"; import { DocumentPositionStateContext, getDocumentPositionStateContext } from "../utils/documentUtil"; import { CFMLMapping, filterComponents, filterDirectories, resolveDottedPaths, resolveRootPath } from "../utils/fileUtil"; import { equalsIgnoreCase, escapeMarkdown, textToMarkdownString } from "../utils/textUtil"; import { getAllGlobalFunctions, getAllGlobalTags, getComponent, getGlobalTag } from "./cachedEntities"; const snippets: Snippets = require("../../snippets/snippets.json"); const triggerCompletionCommand: Command = { title: "Trigger Suggest", command: "editor.action.triggerSuggest" }; export interface CompletionEntry { detail?: string; description?: string; } interface Snippets { [key: string]: Snippet; } interface Snippet { prefix: string; body: string | string[]; description: string; } /** * Tests whether the word being completed matches a given suggestion * @param word The word being completed * @param suggestion A completion candidate to test */ function matches(word: string, suggestion: string): boolean { return word.length === 0 || (suggestion.length >= word.length && equalsIgnoreCase(suggestion.substr(0, word.length), word)); } function createNewProposal(name: string, kind: CompletionItemKind, entry?: CompletionEntry, sortPrefix?: string): CompletionItem { const proposal: CompletionItem = new CompletionItem(name, kind); if (entry) { if (entry.detail) { proposal.detail = entry.detail; } if (entry.description) { proposal.documentation = textToMarkdownString(entry.description); } } if (sortPrefix) { proposal.sortText = `${sortPrefix}${name}`; } return proposal; } interface CompletionState extends DocumentPositionStateContext { completionContext: CompletionContext; cfmlCompletionSettings: WorkspaceConfiguration; currentWordMatches: (name: string) => boolean; } export default class CFMLCompletionItemProvider implements CompletionItemProvider { /** * Provide completion items for the given position and document. * @param document The document in which the command was invoked. * @param position The position at which the command was invoked. * @param _token A cancellation token. * @param context How the completion was triggered. */ public async provideCompletionItems(document: TextDocument, position: Position, _token: CancellationToken, context: CompletionContext): Promise<CompletionItem[]> { let result: CompletionItem[] = []; const documentUri: Uri = document.uri; const cfmlCompletionSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.suggest", documentUri); const shouldProvideCompletions = cfmlCompletionSettings.get<boolean>("enable", true); if (!shouldProvideCompletions) { return result; } const cfscriptRanges: Range[] = getCfScriptRanges(document); const documentPositionStateContext: DocumentPositionStateContext = getDocumentPositionStateContext(document, position); const currentWordMatches = (name: string): boolean => { return matches(documentPositionStateContext.currentWord, name); }; const completionState: CompletionState = Object.assign(documentPositionStateContext, { completionContext: context, cfmlCompletionSettings: cfmlCompletionSettings, currentWordMatches: currentWordMatches } ); const userEngine: CFMLEngine = completionState.userEngine; const docIsCfmFile: boolean = completionState.isCfmFile; const docIsCfcFile: boolean = completionState.isCfcFile; const thisComponent: Component = completionState.component; const positionIsCfScript: boolean = completionState.positionIsScript; const docPrefix: string = completionState.docPrefix; const isContinuingExpression: boolean = completionState.isContinuingExpression; if (completionState.positionInComment) { return result; } // Global tag attributes if (!positionIsCfScript || userEngine.supportsScriptTags()) { const ignoredTags: string[] = expressionCfmlTags; const cfTagAttributePattern: RegExp = positionIsCfScript ? getCfScriptTagAttributePattern() : getCfTagAttributePattern(); const cfTagAttributeMatch: RegExpExecArray = cfTagAttributePattern.exec(docPrefix); if (cfTagAttributeMatch) { const cfTagAttributeMatchOffset: number = cfTagAttributeMatch.index; const tagAttributePrefix: string = cfTagAttributeMatch[1]; const tagAttributeStartOffset: number = cfTagAttributeMatchOffset + tagAttributePrefix.length; const tagName: string = cfTagAttributeMatch[2]; const tagAttributesLength: number = cfTagAttributeMatch[3].length; const globalTag: GlobalTag = getGlobalTag(tagName); if (globalTag && !ignoredTags.includes(globalTag.name)) { const attributeValueMatch: RegExpExecArray = VALUE_PATTERN.exec(docPrefix); if (attributeValueMatch) { const attributeName: string = attributeValueMatch[1]; const currentValue: string = attributeValueMatch[3] !== undefined ? attributeValueMatch[3] : attributeValueMatch[4]; let attributeDocs: MyMap<string, Parameter> = new MyMap<string, Parameter>(); globalTag.signatures.forEach((sig: Signature) => { sig.parameters.forEach((param: Parameter) => { attributeDocs.set(param.name.toLowerCase(), param); }); }); const attributeValueCompletions: CompletionItem[] = getGlobalTagAttributeValueCompletions(completionState, globalTag, attributeName, currentValue); if (attributeValueCompletions.length > 0) { return attributeValueCompletions; } } else { return getGlobalTagAttributeCompletions(completionState, globalTag, tagAttributeStartOffset, tagAttributesLength); } } } } // TODO: Global function attributes in CF2018+ and Lucee (don't return) // HTML tag attributes if (!positionIsCfScript) { const tagAttributePattern: RegExp = getTagAttributePattern(); const tagAttributeMatch: RegExpExecArray = tagAttributePattern.exec(docPrefix); if (tagAttributeMatch) { const tagAttributeMatchOffset: number = tagAttributeMatch.index; const tagAttributePrefix: string = tagAttributeMatch[1]; const tagAttributeStartOffset: number = tagAttributeMatchOffset + tagAttributePrefix.length; const tagName: string = tagAttributeMatch[2].toLowerCase(); const tagAttributesLength: number = tagAttributeMatch[3].length; if (isKnownHTMLTag(tagName)) { const attributeValueMatch: RegExpExecArray = VALUE_PATTERN.exec(docPrefix); if (attributeValueMatch) { const attributeName: string = attributeValueMatch[1].toLowerCase(); const currentValue: string = attributeValueMatch[3] !== undefined ? attributeValueMatch[3] : attributeValueMatch[4]; const attributeValueCompletions: CompletionItem[] = getHTMLTagAttributeValueCompletions(tagName, attributeName, currentValue); if (attributeValueCompletions.length > 0) { return attributeValueCompletions; } } else { return getHTMLTagAttributeCompletions(completionState, tagName, tagAttributeStartOffset, tagAttributesLength); } } } } if (docIsCfcFile && isInComponentHead(documentPositionStateContext)) { // extends and implements path completion. does not apply to docblock const componentDottedPathMatch: RegExpExecArray = componentExtendsPathPrefix.exec(docPrefix); if (componentDottedPathMatch) { const componentDottedPath: string = componentDottedPathMatch[3]; const parentDottedPath: string = componentDottedPath.split(".").slice(0, -1).join("."); return getDottedPathCompletions(completionState, parentDottedPath); } } // Snippets const shouldProvideSnippetItems = cfmlCompletionSettings.get<boolean>("snippets.enable", true); if (shouldProvideSnippetItems && !isContinuingExpression) { const excludedSnippetItems = cfmlCompletionSettings.get<string[]>("snippets.exclude", []); const snippetCompletions: CompletionItem[] = getStandardSnippetCompletions(completionState, excludedSnippetItems); result = result.concat(snippetCompletions); } // Assigned document variables let allVariableAssignments: Variable[] = collectDocumentVariableAssignments(documentPositionStateContext); // TODO: Add struct keys? // Application variables const applicationDocVariables: Variable[] = getApplicationVariables(documentUri); allVariableAssignments = allVariableAssignments.concat(applicationDocVariables.filter((variable: Variable) => { return getMatchingVariables(allVariableAssignments, variable.identifier, variable.scope).length === 0; })); // Server variables const serverDocVariables: Variable[] = getServerVariables(documentUri); allVariableAssignments = allVariableAssignments.concat(serverDocVariables.filter((variable: Variable) => { return getMatchingVariables(allVariableAssignments, variable.identifier, variable.scope).length === 0; })); // Variable completions result = result.concat(getVariableCompletions(completionState, allVariableAssignments)); // Catch variable const catchInfoArr: CatchInfo[] = parseCatches(documentPositionStateContext, documentPositionStateContext.docIsScript); const applicableCatches: CatchInfo[] = catchInfoArr.filter((catchInfo: CatchInfo) => { return catchInfo.bodyRange.contains(position); }); if (applicableCatches.length > 0) { const closestCatch: CatchInfo = applicableCatches.pop(); if (!isContinuingExpression && currentWordMatches(closestCatch.variableName)) { result.push(createNewProposal( closestCatch.variableName, CompletionItemKind.Struct, { detail: closestCatch.variableName, description: "A structure that contains information about the exception" } )); } if (getVariablePrefixPattern(closestCatch.variableName).test(docPrefix)) { for (const propName in catchProperties) { const catchProp: CatchPropertyDetails = catchProperties[propName]; const catchType: string = closestCatch.type.toLowerCase(); if (currentWordMatches(propName) && (catchType === "any" || catchProp.appliesToTypes === undefined || catchProp.appliesToTypes.includes(catchType))) { result.push(createNewProposal(propName, CompletionItemKind.Property, catchProp)); } } } // TODO: rethrow } // CGI variables if (getValidScopesPrefixPattern([Scope.CGI], false).test(docPrefix)) { for (const name in cgiVariables) { if (currentWordMatches(name)) { result.push(createNewProposal(name, CompletionItemKind.Property, cgiVariables[name])); } } } // Document user functions if (docIsCfmFile) { if (getValidScopesPrefixPattern([Scope.Variables], true).test(docPrefix)) { const tagFunctions: UserFunction[] = parseTagFunctions(documentPositionStateContext); const scriptFunctions: UserFunction[] = parseScriptFunctions(documentPositionStateContext).filter((func: UserFunction) => { return isInRanges(cfscriptRanges, func.location.range.start); }); const allTemplateFunctions: UserFunction[] = tagFunctions.concat(scriptFunctions); allTemplateFunctions.filter((func: UserFunction) => { return currentWordMatches(func.name); }).forEach((func: UserFunction) => { result.push(createNewProposal( func.name, CompletionItemKind.Function, { detail: `(function) ${constructSyntaxString(func)}`, description: func.description } )); }); } } else if (docIsCfcFile) { const componentFunctionCompletions: CompletionItem[] = getComponentFunctionCompletions(completionState, thisComponent); result = result.concat(componentFunctionCompletions); } // External user/member functions const varPrefixMatch: RegExpExecArray = getVariableExpressionPrefixPattern().exec(docPrefix); if (varPrefixMatch) { const varMatchText: string = varPrefixMatch[0]; const varScope: string = varPrefixMatch[2]; const varQuote: string = varPrefixMatch[3]; const varName: string = varPrefixMatch[4]; let dotSeparatedCount = 2; if (varScope && !varQuote) { dotSeparatedCount++; } if (varMatchText.split(".").length === dotSeparatedCount) { // From super keyword if (docIsCfcFile && !varScope && equalsIgnoreCase(varName, "super")) { let addedFunctions: MySet<string> = new MySet(); let baseComponent: Component = getComponent(thisComponent.extends); let currComponent: Component = baseComponent; while (currComponent) { currComponent.functions.filter((_func: UserFunction, funcKey: string) => { return currentWordMatches(funcKey) && !addedFunctions.has(funcKey); }).forEach((func: UserFunction, funcKey: string) => { addedFunctions.add(funcKey); result.push(createNewProposal( func.name, CompletionItemKind.Function, { detail: `(function) ${currComponent.name}.${constructSyntaxString(func)}`, description: func.description } )); }); if (currComponent.extends) { currComponent = getComponent(currComponent.extends); } else { currComponent = undefined; } } // From variable } else { const scopeVal: Scope = varScope ? Scope.valueOf(varScope) : undefined; const foundVar: Variable = getBestMatchingVariable(allVariableAssignments, varName, scopeVal); if (foundVar) { // From component variable if (foundVar.dataTypeComponentUri) { const initialFoundComp: Component = getComponent(foundVar.dataTypeComponentUri); if (initialFoundComp) { let addedFunctions: MySet<string> = new MySet(); let addedVariables: MySet<string> = new MySet(); let validFunctionAccess: MySet<Access> = new MySet([Access.Remote, Access.Public]); if (thisComponent) { if (isSubcomponentOrEqual(thisComponent, initialFoundComp)) { validFunctionAccess.add(Access.Private); validFunctionAccess.add(Access.Package); } } if (!validFunctionAccess.has(Access.Package) && path.dirname(documentUri.fsPath) === path.dirname(initialFoundComp.uri.fsPath)) { validFunctionAccess.add(Access.Package); } let foundComponent: Component = initialFoundComp; while (foundComponent) { // component functions foundComponent.functions.filter((func: UserFunction, funcKey: string) => { return currentWordMatches(funcKey) && validFunctionAccess.has(func.access) && !addedFunctions.has(funcKey); }).forEach((func: UserFunction, funcKey: string) => { result.push(createNewProposal( func.name, CompletionItemKind.Function, { detail: `(function) ${foundComponent.name}.${constructSyntaxString(func)}`, description: func.description } )); addedFunctions.add(funcKey); }); // component this-scoped variables foundComponent.variables.filter((variable: Variable) => { const varKey = variable.identifier.toLowerCase(); return variable.scope === Scope.This && !addedVariables.has(varKey); }).forEach((variable: Variable) => { const varKey = variable.identifier.toLowerCase(); const varKind: CompletionItemKind = usesConstantConvention(variable.identifier) || variable.final ? CompletionItemKind.Constant : CompletionItemKind.Variable; const varType: string = getVariableTypeString(variable); result.push(createNewProposal( variable.identifier, varKind, { detail: `(${variable.scope}) ${variable.identifier}: ${varType}`, description: variable.description } )); addedVariables.add(varKey); }); if (foundComponent.extends) { foundComponent = getComponent(foundComponent.extends); } else { foundComponent = undefined; } } } // From other variable type } else { if (foundVar.dataType === DataType.Query) { if (isQuery(foundVar)) { foundVar.selectColumnNames.filter((column: string) => { return currentWordMatches(column); }).forEach((column: string) => { result.push(createNewProposal( column, CompletionItemKind.EnumMember, { detail: `(query column) ${column}` } )); }); } for (const queryPropertyName in queryObjectProperties) { const queryProperty = queryObjectProperties[queryPropertyName]; result.push(createNewProposal( queryPropertyName, CompletionItemKind.Property, { detail: queryProperty.detail, description: queryProperty.description } )); } } // TODO: Add member functions based on foundVar.dataType } } } } } // Global functions const shouldProvideGFItems: boolean = cfmlCompletionSettings.get<boolean>("globalFunctions.enable", true); if (shouldProvideGFItems) { const globalFunctionCompletions: CompletionItem[] = getGlobalFunctionCompletions(completionState); result = result.concat(globalFunctionCompletions); } // Global tags const shouldProvideGTItems: boolean = cfmlCompletionSettings.get<boolean>("globalTags.enable", true); if (shouldProvideGTItems) { const globalTagCompletions: CompletionItem[] = positionIsCfScript ? getGlobalTagScriptCompletions(completionState) : getGlobalTagCompletions(completionState); result = result.concat(globalTagCompletions); } // HTML tags const shouldProvideHtmlTags: boolean = cfmlCompletionSettings.get<boolean>("htmlTags.enable", true); if (shouldProvideHtmlTags && docIsCfmFile && !positionIsCfScript) { result = result.concat(getHTMLTagCompletions(completionState)); } // CSS const shouldProvideCss: boolean = cfmlCompletionSettings.get<boolean>("css.enable", true); if (shouldProvideCss && docIsCfmFile && isInCss(documentPositionStateContext, position)) { const cssWordRange: Range = document.getWordRangeAtPosition(position, cssWordRegex); const currentCssWord: string = cssWordRange ? document.getText(cssWordRange) : ""; // Properties if (/[{;]\s*([a-z-]*)$/i.test(docPrefix)) { completionState.wordRange = cssWordRange; completionState.currentWord = currentCssWord; result = result.concat(getCSSPropertyCompletions(completionState)); } // TODO: Property values // At directives if (currentCssWord.startsWith("@")) { completionState.wordRange = cssWordRange; completionState.currentWord = currentCssWord; result = result.concat(getCSSAtDirectiveCompletions(completionState)); } } // Keywords if (!isContinuingExpression) { for (const name in keywords) { const keyword: KeywordDetails = keywords[name]; if (currentWordMatches(name) && (!keyword.onlyScript || positionIsCfScript)) { result.push(createNewProposal(name, CompletionItemKind.Keyword, keyword)); } } if (thisComponent && thisComponent.extends) { result.push(createNewProposal("super", CompletionItemKind.Keyword, { description: "Reference to the base component" })); } } // Scopes if (!isContinuingExpression) { // TODO: Filter by engine for (const name in scopes) { if (currentWordMatches(name)) { result.push(createNewProposal(name, CompletionItemKind.Struct, scopes[name])); } } } // Component instantiation const componentDottedPathMatch: RegExpExecArray = componentDottedPathPrefix.exec(docPrefix); if (componentDottedPathMatch) { const componentDottedPath: string = componentDottedPathMatch[3]; const parentDottedPath: string = componentDottedPath.split(".").slice(0, -1).join("."); const newInstanceCompletions: CompletionItem[] = getDottedPathCompletions(completionState, parentDottedPath); result = result.concat(newInstanceCompletions); } return result; } } /** * Gets a global entity's attribute as completion items * @param state An object representing the state of completion * @param globalTag The global entity that's attributes will be checked * @param attributeStartOffset The offset within the document that the entity's attributes start * @param attributesLength The length of the entity's attributes string */ function getGlobalTagAttributeCompletions(state: CompletionState, globalTag: GlobalTag, attributeStartOffset: number, attributesLength: number): CompletionItem[] { let attributeDocs: MyMap<string, Parameter> = new MyMap<string, Parameter>(); globalTag.signatures.forEach((sig: Signature) => { sig.parameters.forEach((param: Parameter) => { attributeDocs.set(param.name.toLowerCase(), param); }); }); const attributeNames: MySet<string> = new MySet(attributeDocs.keys()); const tagAttributeRange = new Range(state.document.positionAt(attributeStartOffset), state.document.positionAt(attributeStartOffset + attributesLength)); const parsedAttributes: Attributes = parseAttributes(state.document, tagAttributeRange, attributeNames); const usedAttributeNames: MySet<string> = new MySet(parsedAttributes.keys()); const attributeCompletions: CompletionItem[] = getCFTagAttributeCompletions(state, globalTag, Array.from(attributeDocs.values()), usedAttributeNames); return attributeCompletions; } /** * Gets a CF tag's attribute as completion items * @param state An object representing the state of completion * @param globalTag The global entity that's attributes will be checked * @param params All of the possible parameters that could be presented * @param usedAttributeNames The set of attribute names that are already being used */ function getCFTagAttributeCompletions(state: CompletionState, globalTag: GlobalTag, params: Parameter[], usedAttributeNames: MySet<string>): CompletionItem[] { const cfmlGTAttributesQuoteType: AttributeQuoteType = state.cfmlCompletionSettings.get<AttributeQuoteType>("globalTags.attributes.quoteType", AttributeQuoteType.Double); const cfmlGTAttributesDefault: boolean = state.cfmlCompletionSettings.get<boolean>("globalTags.attributes.defaultValue", false); const attributeCompletions: CompletionItem[] = params.filter((param: Parameter) => { return !usedAttributeNames.has(param.name.toLowerCase()) && state.currentWordMatches(param.name); }).map((param: Parameter) => { let attributeItem = new CompletionItem(param.name, CompletionItemKind.Property); attributeItem.detail = `${param.required ? "(required) " : ""}${param.name}: ${param.dataType}`; attributeItem.documentation = param.description; const wordSuffix: string = state.sanitizedDocumentText.slice(state.document.offsetAt(state.wordRange.end)); if (!wordSuffix.trim().startsWith("=")) { if (cfmlGTAttributesQuoteType === AttributeQuoteType.None) { attributeItem.insertText = param.name + "="; } else { attributeItem.insertText = new SnippetString(constructAttributeSnippet(param, 0, cfmlGTAttributesQuoteType, cfmlGTAttributesDefault)); } } attributeItem.sortText = "!" + param.name + "="; const attributeValueCompletions: CompletionItem[] = getGlobalTagAttributeValueCompletions(state, globalTag, param.name.toLowerCase(), ""); if (attributeValueCompletions.length > 0) { attributeItem.command = triggerCompletionCommand; } return attributeItem; }); return attributeCompletions; } /** * Gets a global tag's attribute values as completion items for a given attribute * @param state An object representing the state of completion * @param globalTag The global tag that's attribute values will be checked * @param attributeName The name of the attribute that's values will be presented * @param currentValue The current value of the given attribute */ function getGlobalTagAttributeValueCompletions(state: CompletionState, globalTag: GlobalTag, attributeName: string, currentValue: string): CompletionItem[] { let attrValCompletions: CompletionItem[] = []; let attributeDocs: MyMap<string, Parameter> = new MyMap<string, Parameter>(); globalTag.signatures.forEach((sig: Signature) => { sig.parameters.forEach((param: Parameter) => { attributeDocs.set(param.name.toLowerCase(), param); }); }); const param: Parameter = attributeDocs.get(attributeName); if (param) { if (param.dataType === DataType.Boolean) { attrValCompletions.push(createNewProposal("true", CompletionItemKind.Unit, undefined, "!!")); attrValCompletions.push(createNewProposal("false", CompletionItemKind.Unit, undefined, "!!")); } else { if (param.enumeratedValues) { param.enumeratedValues.forEach((enumVal: string) => { enumVal = enumVal.toString(); if (matches(currentValue, enumVal)) { attrValCompletions.push(createNewProposal(enumVal, CompletionItemKind.Unit, undefined, "!!")); } }); } } // TODO: Check if attribute uses or assigns variables } const componentPathAttributes: ComponentPathAttributes = getComponentPathAttributes(); if (componentPathAttributes.hasOwnProperty(globalTag.name) && componentPathAttributes[globalTag.name].includes(attributeName)) { const parentDottedPath: string = currentValue.split(".").slice(0, -1).join("."); attrValCompletions = attrValCompletions.concat(getDottedPathCompletions(state, parentDottedPath)); } return attrValCompletions; } /** * Gets an HTML tag's attribute as completion items * @param state An object representing the state of completion * @param htmlTag The HTML tag that's attributes will be checked * @param attributeStartOffset The offset within the document that the tag's attributes start * @param attributesLength The length of the tag's attributes string */ function getHTMLTagAttributeCompletions(state: CompletionState, htmlTagName: string, attributeStartOffset: number, attributesLength: number): CompletionItem[] { const attributeNames: string[] = htmlDataProvider.provideAttributes(htmlTagName.toLowerCase()).map((a) => a.name); const tagAttributeRange = new Range(state.document.positionAt(attributeStartOffset), state.document.positionAt(attributeStartOffset + attributesLength)); const parsedAttributes: Attributes = parseAttributes(state.document, tagAttributeRange, new MySet(attributeNames)); const usedAttributeNames: MySet<string> = new MySet(parsedAttributes.keys()); const unusedAttributeNames: string[] = attributeNames.filter((attr: string) => { return !usedAttributeNames.has(attr.toLowerCase()) && state.currentWordMatches(attr); }); const attributeCompletions: CompletionItem[] = unusedAttributeNames.map((attr: string) => { const htmlTagAttributesQuoteType: AttributeQuoteType = state.cfmlCompletionSettings.get<AttributeQuoteType>("htmlTags.attributes.quoteType", AttributeQuoteType.Double); const attribute: HTMLAttributeData = getAttribute(htmlTagName, attr); let attributeItem = new CompletionItem(attr, CompletionItemKind.Property); const wordSuffix: string = state.sanitizedDocumentText.slice(state.document.offsetAt(state.wordRange.end)); if (!wordSuffix.trim().startsWith("=")) { attributeItem.insertText = new SnippetString(constructHTMLAttributeSnippet(htmlTagName.toLowerCase(), attr, htmlTagAttributesQuoteType)); } attributeItem.sortText = "!" + attr + "="; attributeItem.documentation = attribute.description; const attributeValueCompletions: CompletionItem[] = getHTMLTagAttributeValueCompletions(htmlTagName.toLowerCase(), attr, ""); if (attributeValueCompletions.length > 0) { attributeItem.command = triggerCompletionCommand; } return attributeItem; }); return attributeCompletions; } /** * Gets an HTML tag's attribute values as completion items for a given attribute * @param htmlTagName The name of the HTML tag that's attribute values will be checked * @param attributeName The name of the attribute that's values will be presented * @param currentValue The current value of the given attribute */ function getHTMLTagAttributeValueCompletions(htmlTagName: string, attributeName: string, currentValue: string): CompletionItem[] { let attrValCompletions: CompletionItem[] = []; htmlDataProvider.provideValues(htmlTagName.toLowerCase(), attributeName.toLowerCase()).filter((val: HTMLValueData) => { return matches(currentValue, val.name); }).forEach((val: HTMLValueData) => { attrValCompletions.push(createNewProposal(val.name, CompletionItemKind.Unit, { description: val.description }, "!")); }); return attrValCompletions; } /** * Gets the standard included snippets as completion items * @param state An object representing the state of completion * @param excludedSnippetItems The snippets that should be excluded */ function getStandardSnippetCompletions(state: CompletionState, excludedSnippetItems: string[] = []): CompletionItem[] { let snippetCompletions: CompletionItem[] = []; for (const key in snippets) { if (!excludedSnippetItems.includes(key)) { let snippet: Snippet = snippets[key]; // TODO: Use key to determine if script vs tag if (state.currentWordMatches(snippet.prefix) && state.positionIsScript) { let standardSnippet = new CompletionItem(snippet.prefix, CompletionItemKind.Snippet); standardSnippet.detail = `(snippet) ${snippet.description}`; const snippetString: string = Array.isArray(snippet.body) ? snippet.body.join("\n") : snippet.body; // standardSnippet.documentation = snippetString; standardSnippet.insertText = new SnippetString(snippetString); snippetCompletions.push(standardSnippet); } } } return snippetCompletions; } /** * Gets the variable completions for the given state * @param state An object representing the state of completion * @param variables All variable declarations */ function getVariableCompletions(state: CompletionState, variables: Variable[]): CompletionItem[] { let variableCompletions: CompletionItem[] = []; const variableScopePrefixPattern: RegExp = getVariableScopePrefixPattern(); const variableScopePrefixMatch: RegExpExecArray = variableScopePrefixPattern.exec(state.docPrefix); if (variableScopePrefixMatch) { const scopePrefix: string = variableScopePrefixMatch[1]; let prefixScope: Scope; if (scopePrefix) { prefixScope = Scope.valueOf(scopePrefix); } variableCompletions = variables.filter((variable: Variable) => { if (!state.currentWordMatches(variable.identifier) || variable.declarationLocation.range.contains(state.position)) { return false; } if (prefixScope) { return (variable.scope === prefixScope || (variable.scope === Scope.Unknown && unscopedPrecedence.includes(prefixScope))); } return (unscopedPrecedence.includes(variable.scope) || variable.scope === Scope.Unknown); }).map((variable: Variable) => { const varKind: CompletionItemKind = usesConstantConvention(variable.identifier) || variable.final ? CompletionItemKind.Constant : CompletionItemKind.Variable; const varType: string = getVariableTypeString(variable); return createNewProposal(variable.identifier, varKind, { detail: `(${variable.scope}) ${variable.identifier}: ${varType}`, description: variable.description }); }); } return variableCompletions; } /** * Gets the function completions for the given component and state * @param state An object representing the state of completion * @param component The component in which to suggest functions */ function getComponentFunctionCompletions(state: CompletionState, component: Component): CompletionItem[] { let componentFunctionCompletions: CompletionItem[] = []; if (component) { let addedFunctions: MySet<string> = new MySet(); const privateAccessPrefixMatched: boolean = getValidScopesPrefixPattern([Scope.Variables], true).test(state.docPrefix); const otherAccessPrefixMatched: boolean = getValidScopesPrefixPattern([Scope.Variables, Scope.This], true).test(state.docPrefix); const getterSetterPrefixMatched: boolean = getValidScopesPrefixPattern([Scope.This], true).test(state.docPrefix); let currComponent: Component = component; while (currComponent) { currComponent.functions.filter((func: UserFunction, funcKey: string) => { let hasValidScopes: boolean = false; if (func.access === Access.Private) { hasValidScopes = privateAccessPrefixMatched; } else if (func.isImplicit) { hasValidScopes = getterSetterPrefixMatched; } else { hasValidScopes = otherAccessPrefixMatched; } return (hasValidScopes && state.currentWordMatches(funcKey) && !addedFunctions.has(funcKey)); }).forEach((func: UserFunction, funcKey: string) => { addedFunctions.add(funcKey); componentFunctionCompletions.push( createNewProposal(func.name, CompletionItemKind.Function, { detail: `(function) ${currComponent.name}.${constructSyntaxString(func)}`, description: func.description }) ); }); if (currComponent.extends) { currComponent = getComponent(currComponent.extends); } else { currComponent = undefined; } } } return componentFunctionCompletions; } /** * Gets the global function completions for the given state * @param state An object representing the state of completion */ function getGlobalFunctionCompletions(state: CompletionState): CompletionItem[] { const cfmlGFFirstLetterCase: string = state.cfmlCompletionSettings.get<string>("globalFunctions.firstLetterCase", "unchanged"); let globalFunctionCompletions: CompletionItem[] = []; if (!state.isContinuingExpression) { const globalFunctions: GlobalFunctions = getAllGlobalFunctions(); for (const name in globalFunctions) { if (state.currentWordMatches(name)) { const globalFunction: GlobalFunction = globalFunctions[name]; let functionDetail = globalFunction.syntax; if (!functionDetail.startsWith("function ")) { functionDetail = "function " + globalFunction.syntax; } let globalFunctionName: string = globalFunction.name; if (cfmlGFFirstLetterCase === "lower") { globalFunctionName = `${globalFunctionName.charAt(0).toLowerCase()}${globalFunctionName.substr(1)}`; } else if (cfmlGFFirstLetterCase === "upper") { globalFunctionName = `${globalFunctionName.charAt(0).toUpperCase()}${globalFunctionName.substr(1)}`; } globalFunctionCompletions.push( createNewProposal( globalFunctionName, CompletionItemKind.Function, { detail: globalFunction.syntax, description: globalFunction.description } ) ); } } } return globalFunctionCompletions; } /** * Gets the global tag completions for the given state * @param state An object representing the state of completion */ function getGlobalTagCompletions(state: CompletionState): CompletionItem[] { let globalTagCompletions: CompletionItem[] = []; const tagPrefixPattern: RegExp = getTagPrefixPattern(); const tagPrefixMatch: RegExpExecArray = tagPrefixPattern.exec(state.docPrefix); if (tagPrefixMatch) { const closingSlash: string = tagPrefixMatch[1]; const cfmlGTAttributesQuoteType: AttributeQuoteType = state.cfmlCompletionSettings.get<AttributeQuoteType>("globalTags.attributes.quoteType", AttributeQuoteType.Double); const cfmlGTAttributesDefault: boolean = state.cfmlCompletionSettings.get<boolean>("globalTags.attributes.defaultValue", false); const cfmlGTAttributesSetType: IncludeAttributesSetType = state.cfmlCompletionSettings.get<IncludeAttributesSetType>("globalTags.includeAttributes.setType", IncludeAttributesSetType.None); const cfmlGTAttributesCustom: IncludeAttributesCustom = state.cfmlCompletionSettings.get<IncludeAttributesCustom>("globalTags.includeAttributes.custom", {}); const globalTags: GlobalTags = getAllGlobalTags(); for (const tagName in globalTags) { if (state.currentWordMatches(tagName)) { const globalTag: GlobalTag = globalTags[tagName]; let thisGlobalTagCompletion: CompletionItem = createNewProposal( globalTag.name, CompletionItemKind.TypeParameter, { detail: globalTag.syntax, description: globalTag.description } ); if (!closingSlash && (cfmlGTAttributesSetType !== IncludeAttributesSetType.None || cfmlGTAttributesCustom.hasOwnProperty(tagName))) { thisGlobalTagCompletion.insertText = constructTagSnippet(globalTag, cfmlGTAttributesSetType, cfmlGTAttributesQuoteType, cfmlGTAttributesCustom[tagName], cfmlGTAttributesDefault, false); } globalTagCompletions.push(thisGlobalTagCompletion); } } } return globalTagCompletions; } /** * Gets the global tag script completions for the given state * @param state An object representing the state of completion */ function getGlobalTagScriptCompletions(state: CompletionState): CompletionItem[] { let globalTagScriptCompletions: CompletionItem[] = []; if (state.userEngine.supportsScriptTags() && !state.isContinuingExpression) { const cfmlGTAttributesQuoteType: AttributeQuoteType = state.cfmlCompletionSettings.get<AttributeQuoteType>("globalTags.attributes.quoteType", AttributeQuoteType.Double); const cfmlGTAttributesDefault: boolean = state.cfmlCompletionSettings.get<boolean>("globalTags.attributes.defaultValue", false); const cfmlGTAttributesSetType: IncludeAttributesSetType = state.cfmlCompletionSettings.get<IncludeAttributesSetType>("globalTags.includeAttributes.setType", IncludeAttributesSetType.None); const cfmlGTAttributesCustom: IncludeAttributesCustom = state.cfmlCompletionSettings.get<IncludeAttributesCustom>("globalTags.includeAttributes.custom", {}); const globalTags: GlobalTags = getAllGlobalTags(); for (const tagName in globalTags) { const globalTag: GlobalTag = globalTags[tagName]; if (globalTag.scriptSyntax && globalTag.scriptSyntax.startsWith(tagName) && state.currentWordMatches(tagName)) { let thisGlobalTagScriptCompletion: CompletionItem = createNewProposal( globalTag.name, CompletionItemKind.Function, { detail: globalTagSyntaxToScript(globalTag), description: globalTag.description } ); if (cfmlGTAttributesSetType !== IncludeAttributesSetType.None || cfmlGTAttributesCustom.hasOwnProperty(tagName)) { thisGlobalTagScriptCompletion.insertText = constructTagSnippet(globalTag, cfmlGTAttributesSetType, cfmlGTAttributesQuoteType, cfmlGTAttributesCustom[tagName], cfmlGTAttributesDefault, true); } globalTagScriptCompletions.push(thisGlobalTagScriptCompletion); } } } return globalTagScriptCompletions; } /** * Gets the HTML tag completions for the given state * @param state An object representing the state of completion */ function getHTMLTagCompletions(state: CompletionState): CompletionItem[] { let htmlTagCompletions: CompletionItem[] = []; const tagPrefixPattern: RegExp = getTagPrefixPattern(); const tagPrefixMatch: RegExpExecArray = tagPrefixPattern.exec(state.docPrefix); if (tagPrefixMatch) { for (const htmlTag of htmlDataProvider.provideTags()) { if (state.currentWordMatches(htmlTag.name)) { let thisHTMLTagCompletion: CompletionItem = createNewProposal( htmlTag.name, CompletionItemKind.TypeParameter, { description: htmlTag.description } ); htmlTagCompletions.push(thisHTMLTagCompletion); } } } return htmlTagCompletions; } /** * Gets the CSS property completions for the given state * @param state An object representing the state of completion */ function getCSSPropertyCompletions(state: CompletionState): CompletionItem[] { let cssPropertyCompletions: CompletionItem[] = []; const cssProperties: IPropertyData[] = cssDataManager.getProperties(); cssProperties.filter((prop: IPropertyData) => { return state.currentWordMatches(prop.name); }).forEach((prop: IPropertyData) => { let entry: CompletionEntry = { detail: prop.name, description: getCSSEntryDescription(prop) }; if (prop.syntax) { entry.detail = `${prop.name}: ${prop.syntax}`; } let thisCssPropertyCompletion: CompletionItem = createNewProposal( prop.name, CompletionItemKind.Property, entry ); thisCssPropertyCompletion.range = state.wordRange; cssPropertyCompletions.push(thisCssPropertyCompletion); }); return cssPropertyCompletions; } /** * Gets the CSS at directive completions for the given state * @param state An object representing the state of completion */ function getCSSAtDirectiveCompletions(state: CompletionState): CompletionItem[] { let cssPropertyCompletions: CompletionItem[] = []; const cssAtDirectives: IAtDirectiveData[] = cssDataManager.getAtDirectives(); cssAtDirectives.filter((atDir: IAtDirectiveData) => { return state.currentWordMatches(atDir.name); }).forEach((atDir: IAtDirectiveData) => { let entry: CompletionEntry = { detail: atDir.name, description: getCSSEntryDescription(atDir) }; let thisCssPropertyCompletion: CompletionItem = createNewProposal( atDir.name, CompletionItemKind.Keyword, entry ); thisCssPropertyCompletion.range = state.wordRange; cssPropertyCompletions.push(thisCssPropertyCompletion); }); return cssPropertyCompletions; } /** * Gets dotted path completions for the given state * @param state An object representing the state of completion * @param parentDottedPath The dotted path part that is higher in the hierarchy */ function getDottedPathCompletions(state: CompletionState, parentDottedPath: string): CompletionItem[] { const newInstanceCompletions: CompletionItem[] = []; const paths: string[] = resolveDottedPaths(parentDottedPath, state.document.uri); paths.forEach((thisPath: string) => { const files: string[] = fs.readdirSync(thisPath); const directories: string[] = filterDirectories(files, thisPath); directories.filter((directory: string) => { return state.currentWordMatches(directory); }).forEach((directory: string) => { newInstanceCompletions.push(createNewProposal( directory, CompletionItemKind.Folder, { detail: `(folder) ${directory}`, description: escapeMarkdown(path.join(thisPath, directory)) }, "!" )); }); const componentFiles: string[] = filterComponents(files); componentFiles.filter((componentFile: string) => { const componentName: string = path.basename(componentFile, COMPONENT_EXT); return state.currentWordMatches(componentName); }).forEach((componentFile: string) => { const componentName: string = path.basename(componentFile, COMPONENT_EXT); newInstanceCompletions.push(createNewProposal( componentName, CompletionItemKind.Class, { detail: `(component) ${componentName}`, description: escapeMarkdown(path.join(thisPath, componentFile)) }, "!" )); }); }); // custom mappings const cfmlMappings: CFMLMapping[] = workspace.getConfiguration("cfml", state.document.uri).get<CFMLMapping[]>("mappings", []); const splitParentPath: string[] = parentDottedPath === "" ? [] : parentDottedPath.split("."); for (const cfmlMapping of cfmlMappings) { const slicedLogicalPath: string = cfmlMapping.logicalPath.slice(1); const splitLogicalPath: string[] = slicedLogicalPath.split("/"); if (splitParentPath.length >= splitLogicalPath.length) { continue; } const invalidPath: boolean = splitParentPath.some((parentPathPart: string, idx: number) => { return parentPathPart !== splitLogicalPath[idx]; }); if (invalidPath) { continue; } const completionName: string = splitLogicalPath[splitParentPath.length]; let completionEntry: CompletionEntry; let dottedLogicalPath: string = splitLogicalPath.slice(0, splitParentPath.length + 1).join("."); if (splitLogicalPath.length - splitParentPath.length === 1) { const directoryPath: string = cfmlMapping.isPhysicalDirectoryPath === undefined || cfmlMapping.isPhysicalDirectoryPath ? cfmlMapping.directoryPath : resolveRootPath(state.document.uri, cfmlMapping.directoryPath); completionEntry = { detail: `(mapping) ${dottedLogicalPath}` }; if (directoryPath) { completionEntry.description = escapeMarkdown(directoryPath); } } else { completionEntry = { detail: `(partial mapping) ${dottedLogicalPath}` }; } newInstanceCompletions.push(createNewProposal( completionName, CompletionItemKind.Folder, completionEntry )); } return newInstanceCompletions; }
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_accountleads: 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_activitymonitor: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_adminsettingsentity: 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_bookableresource: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcebooking: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcebookingexchangesyncidmapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcebookingheader: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcecategoryassn: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcecharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookableresourcegroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bookingstatus: 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_bulkoperation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_bulkoperationlog: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_campaign: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_campaignactivity: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_campaignactivityitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_campaignitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_campaignresponse: 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_characteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_childincidentcount: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_commitment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_competitor: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_competitoraddress: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_competitorproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_competitorsalesliterature: 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_constraintbasedgroup: 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_contactinvoices: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contactleads: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contactorders: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contactquotes: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contract: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contractdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_contracttemplate: 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_customeropportunityrole: 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_discount: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_discounttype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_dynamicproperty: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_dynamicpropertyassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_dynamicpropertyinstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_dynamicpropertyoptionsetitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementchannel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementcontacts: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementproducts: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementtemplatechannel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_entitlementtemplateproducts: 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_equipment: 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_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_incident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_incidentknowledgebaserecord: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_incidentresolution: 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_invoice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_invoicedetail: 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_knowledgearticleincident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_lead: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_leadaddress: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_leadcompetitors: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_leadproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_leadtoopportunitysalesprocess: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_list: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_listmember: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_listoperation: 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_marketingformdisplayattributes: 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_msdynsm_marketingsitemap: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdynsm_salessitemap: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdynsm_servicessitemap: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdynsm_settingssitemap: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_3dmodel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_accountpricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_actioncardregarding: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_actioncardrolesetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_actual: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_adaptivecardconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_adminappstate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agentstatushistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_agreementsubstatus: 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_analysiscomponent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analysisjob: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analysisresult: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analytics: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analyticsadminsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_analyticsforcs: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_appconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_applicationextension: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_approval: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_assetcategorytemplateassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_assettemplateassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_authenticationsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_autocapturerule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_autocapturesettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_batchjob: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingalert: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingchange: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingjournal: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingrule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingsetupmetadata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_477c16f59170487b8b4dc895c5dcd09b: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_665e73aa18c247d886bfc50499c73b82: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_989e9b1857e24af18787d5143b67523b: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_baa0a411a239410cb8bded8b5fdd88e3: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_d3d97bac8c294105840e99e37a9d1c39: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_bpf_d8f9dc7f099f44db9d641dd81fbd470d: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_businessclosure: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_callablecontext: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_cannedmessage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_capacityprofile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_caseenrichment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_casesuggestionrequestpayload: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_casetopic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_casetopicsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_casetopicsummary: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_casetopic_incident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_cdsentityengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_channel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_channelcapability: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_channelprovider: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_chatansweroption: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_chatquestionnaireresponse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_chatquestionnaireresponseitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ciprovider: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_clientextension: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_collabgraphresource: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_configuration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_consoleappparameterdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_contactpricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_contractperformance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationinsight: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationtopic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationtopicsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationtopicsummary: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_conversationtopic_conversation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_customengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_customerasset: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_customerassetattachment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_customerassetcategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataanalyticsreport: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataanalyticsreport_csrmanager: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataanalyticsreport_ksinsights: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataanalyticsreport_oc: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataanalyticsreport_ocvoice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_databaseversion: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dataexport: 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_datainsightsandanalyticsfeature: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_decisioncontract: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_decisionruleset: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_delegation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dimension: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_entitlementapplication: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_entityconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_entityconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_entityrankingrule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_entityroutingconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_estimate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_estimateline: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_expense: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_expensecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_expensereceipt: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_facebookengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_fact: 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_fieldcomputation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_fieldservicesetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_fieldserviceslaconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_fieldservicesystemjob: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_findworkevent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_flowcardtype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_forecastdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_forecastinstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_functionallocation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_gdprdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_geofence: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_geofenceevent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_geofencingsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_geolocationsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_geolocationtracking: 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_icebreakersconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inspection: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inspectionattachment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inspectioninstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inspectionresponse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_integrationjob: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_integrationjobdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inventoryjournal: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_invoicefrequency: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotalert: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotprovider: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iotsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_iottocaseprocess: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_journal: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_journalline: 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_kbenrichment: 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_kpieventdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_lineengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_livechatconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_livechatengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_livechatwidgetlocation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_liveconversation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_liveworkstream: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_macrosession: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_maskingrule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_migrationtracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_mlresultcache: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_msteamssetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_msteamssettingsv2: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_notesanalysisconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_notificationfield: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_notificationtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocfbapplication: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocfbpage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_oclanguage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkitemsentiment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocphonenumber: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocrequest: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocruleitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsession: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsessionsentiment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsimltraining: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsitdskill: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_octag: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_octwitterapplication: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_octwitterhandle: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_omnichannelpersonalization: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_omnichannelqueue: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_operatinghour: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_orderpricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_organizationalunit: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_paneconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_payment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_paymentdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_paymentmethod: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_paymentterm: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_personalmessage: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_playbookactivity: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_playbookcategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_playbookinstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_playbooktemplate: 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_postalbum: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_postalcode: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_postconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_postruleconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_presence: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_priority: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_problematicasset: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_processnotes: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productinventory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivityagentscript: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_project: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectapproval: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectpricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projecttask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectteam: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_property: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_propertyassetassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_propertylog: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_propertytemplateassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_provider: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseorder: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_questionsequence: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotebookingincident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotebookingservice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_quotepricelist: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementdependency: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementgroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementrelationship: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_requirementstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resolution: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourceassignment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcepaytype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcerequest: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcerequirement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_resourceterritory: 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_rma: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rmaproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rmareceipt: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rmasubstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_roleutilization: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_routingconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_routingrequest: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rtv: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rtvproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_scenario: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_schedulingparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_searchconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sentimentanalysis: 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_servicetasktype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sessiondata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sessionevent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sessionparticipant: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sessiontemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_shipvia: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_siconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_sikeyvalueconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_skillattachmenttarget: 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_smartassistconfig: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_smsengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_smsnumber: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_soundfile: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_suggestioninteraction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_suggestionrequestpayload: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_suggestionsmodelsummary: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_suggestionssetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_surveyquestion: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_taxcode: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_taxcodedetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_teamscollaboration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_templateforproperties: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_templateparameter: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_templatetags: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timeentry: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timeentrysetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timegroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_timeoffrequest: 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_msdyn_transactioncategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactionconnection: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactionorigin: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transactiontype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_transcript: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_uniquenumber: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_untrackedappointment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_upgraderun: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_upgradestep: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_upgradeversion: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_usersetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_userworkhistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_visitorjourney: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_wallsavedquery: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_wallsavedqueryusersettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_warehouse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_wechatengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_whatsappengagementctx: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workhourtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorder: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderincident: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderresolution: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderservice: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workordersubstatus: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyn_workordertype: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_actioncallworkflow: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_answer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_auditanddiagnosticssetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_configuration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_customizationfiles: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_entityassignment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_entitysearch: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_form: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_languagemodule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_scriptlet: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_scripttasktrigger: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_search: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_sessioninformation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_sessiontransfer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_task: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_ucisettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_uiievent: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_usersettings: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msdyusd_windowroute: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_alert: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_alertrule: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_emailtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_fileresponse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_localizedemailtemplate: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_project: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_question: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_questionresponse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_satisfactionmetric: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_survey: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_surveyreminder: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_surveyresponse: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_msfp_unsubscribedrecipient: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_opportunity: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_opportunityclose: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_opportunitycompetitors: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_opportunityproduct: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_opportunitysalesprocess: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_orderclose: 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_phonetocaseprocess: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_pricelevel: 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_product: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_productassociation: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_productpricelevel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_productsalesliterature: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_productsubstitute: 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_quote: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_quoteclose: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_quotedetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_ratingmodel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_ratingvalue: 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_resource: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_resourcegroup: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_resourcegroupexpansion: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_resourcespec: 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_salesliterature: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_salesliteratureitem: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_salesorder: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_salesorderdetail: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_salesprocessinstance: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_service: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_serviceappointment: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_servicecontractcontacts: 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_settingdefinition: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_site: 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_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_topic: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_topichistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_topicmodel: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_topicmodelconfiguration: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_topicmodelexecutionhistory: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_action: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_audit: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_context: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_hostedapplication: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_nonhostedapplication: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_option: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_savedsession: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_sessiontransfer: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_workflow: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_workflowstep: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uom: DevKit.WebApi.LookupValue; /** The regarding object such as Account, Contact, Lead etc. that the folder relates to. */ regardingobjectid_uomschedule: 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 Boom from '@hapi/boom'; import TwindTypography from '@twind/typography'; import { htmlEscape } from 'escape-goat'; import jsesc from 'jsesc'; import * as React from 'react'; import { renderToString } from 'react-dom/server'; import * as Markup from 'react-helmet-async'; import * as ReactQuery from 'react-query'; import * as ReactQueryHydration from 'react-query/hydration'; import type * as ReactRouter from 'react-router'; import * as ReactRouterDOM from 'react-router-dom'; import { install } from 'source-map-support'; import * as Twind from 'twind'; import * as TwindServer from 'twind/shim/server'; import type { ChunkDependencies } from '../../../build/types'; import type { ClientAuth } from '../../auth'; import { AuthContext, ServerAuth } from '../../auth/server'; import { ServerQueryContextProvider, ServerQueryExecutorImpl } from '../../functions/server'; import type { ServerFunction, ServerFunctionContext } from '../../functions/types'; import { LazyContext } from '../../lazy/context'; import type { ChunkManager } from '../../lazy/types'; import { defaultMarkupProps } from '../../markup'; import { TwindContext } from '../../styling/internal'; import type { BootstrapOptions } from '../bootstrap/bootstrap'; declare global { var __nostalgie_css: (buildPath: string, css: string) => void; } // const injectedCss = new Map<string, string>(); // global.__nostalgie_css = (buildPath: string, css: string) => { // injectedCss.set(buildPath, css); // } if (process.env.NODE_ENV === 'development') { install({ environment: 'node', }); } export interface ServerRenderRequest { auth: ServerAuth; automaticReload?: boolean; path: string; } interface ServerRendererSettings { defaultDeadline: number; enableTailwind: boolean; maxIterations: number; } export interface ServerRendererOptions extends Partial<ServerRendererSettings> {} export class ServerRenderer { private readonly app: React.ComponentType; private readonly functions: Record<string, ServerFunction | undefined>; private readonly chunkDependencies: ChunkDependencies; private readonly settings: ServerRendererSettings; constructor( app: React.ComponentType, functions: Record<string, ServerFunction>, chunkDependencies: ChunkDependencies, options: ServerRendererOptions = {} ) { this.app = app; this.functions = functions; this.chunkDependencies = chunkDependencies; this.settings = { defaultDeadline: options.defaultDeadline ?? 500, enableTailwind: !!options.enableTailwind, maxIterations: options.maxIterations ?? 5, }; } async invokeFunction(functionName: string, ctx: ServerFunctionContext, args: any[]) { const functionImpl = this.functions[functionName] as ServerFunction | undefined; if (!functionImpl) { throw Boom.notFound(); } return functionImpl(ctx, ...args); } async renderAppOnServer( request: ServerRenderRequest ): Promise<{ headers?: Record<string, string>; html: string; queries: number; renderCount: number; statusCode?: number; latency: number; }> { const start = Date.now(); const bootstrapChunk = 'static/build/bootstrap.js'; const markupCtx: Markup.ProviderProps = {}; const chunkCtx: ChunkManager = { chunks: [], lazyComponentState: new Map(), }; const queryClient = new ReactQuery.QueryClient(); const initialReactQueryState = ReactQueryHydration.dehydrate(queryClient); const auth = this.serverAuthToClientAuth(request.auth); const queryExecutor = new ServerQueryExecutorImpl({ auth: request.auth, queryClient }); // Set up twind for parsing the result and generating markup const customSheet = TwindServer.virtualSheet(); const routerCtx: ReactRouter.StaticRouterContext = {}; const { tw } = Twind.create({ sheet: customSheet, mode: 'silent', prefix: true, preflight: this.settings.enableTailwind, plugins: { ...(this.settings.enableTailwind ? TwindTypography() : {}), }, }); const model = ( <TwindContext.Provider value={tw}> <LazyContext.Provider value={chunkCtx}> <ServerQueryContextProvider queryExecutor={queryExecutor}> <ReactQueryHydration.Hydrate state={initialReactQueryState}> <Markup.HelmetProvider context={markupCtx}> <AuthContext.Provider value={auth}> <ReactRouterDOM.StaticRouter location={request.path} context={routerCtx}> <Markup.Helmet {...defaultMarkupProps}></Markup.Helmet> <this.app /> </ReactRouterDOM.StaticRouter> </AuthContext.Provider> </Markup.HelmetProvider> </ReactQueryHydration.Hydrate> </ServerQueryContextProvider> </LazyContext.Provider> </TwindContext.Provider> ); // We'll give ourselves a budget for the number of render passes we're willing to undertake let renderCount = 1; let renderedMarkup = ''; try { // We're going to give a maximum amount of time for this render. const deadlineAt = Date.now() + this.settings.defaultDeadline; // We've given ourselves a deadline so let's get a Promise that will resolve // when the deadline is reached to race against data-loading promises (if any). const deadlinePromise = new Promise((r) => setTimeout(r, this.settings.defaultDeadline)); // A first SSR async pass through the tree for critical stuff like dynamic imports // await ssrPrepass(model); // We'll give ourselves a budget for the number of async passes we're willing to undertake let remainingIterations = this.settings.maxIterations; customSheet.reset(); let html: string | undefined = renderToString(model); // Loop while we haven't exceeded our deadline or iteration budget and while we have pending queries for ( ; // Condition Date.now() <= deadlineAt && queryExecutor.promises.size && remainingIterations && !routerCtx.url && !routerCtx.statusCode; // Loop update (after loop block) remainingIterations-- ) { try { // We're always going to race against our deadline promise so that we can interrupt potentially // earlier than the first query will settle. await Promise.race([deadlinePromise, ...queryExecutor.promises]); // Re-render the page, triggering any new queries unlocked by the new state. customSheet.reset(); html = renderToString(model); renderCount++; // await ssrPrepass(model); } catch { // Break out and do the final rendering break; } } renderedMarkup = html ?? (customSheet.reset(), renderCount++, renderToString(model)); } catch (err) { // TODO: Bake error into dev builds for devex if (process.env.NODE_ENV === 'development') { console.error(err); } } // Any outstanding queries should be cancelled at this point since our client's lifetime // is limited to this request anyway. queryClient.cancelQueries(); if (routerCtx.url) { return { headers: { location: routerCtx.url, }, statusCode: routerCtx.statusCode || 302, html: `<p>You are being redirected to ${htmlEscape(routerCtx.url)}</p>`, renderCount: renderCount, queries: queryExecutor.promises.size, latency: Date.now() - start, }; } const queryClientData = ReactQueryHydration.dehydrate(queryClient); renderedMarkup ??= (customSheet.reset(), renderCount++, renderToString(model)); if (this.settings.enableTailwind) { renderedMarkup = TwindServer.shim(renderedMarkup, tw); } const headTags = []; const { helmet } = markupCtx as Markup.FilledContext; const requiredChunks = [bootstrapChunk, ...chunkCtx.chunks.map((chunk) => chunk.chunk)]; const seenChunks = new Set(); while (requiredChunks.length) { const chunk = requiredChunks.shift()!; // Make sure we don't process twice if (seenChunks.has(chunk)) continue; seenChunks.add(chunk); const chunkDeps = this.chunkDependencies[chunk]; if (chunkDeps) { for (const chunkDep of chunkDeps.modules) { headTags.push(`<link rel="modulepreload" href="${chunkDep}">`); // Capture transitive dependencies // Chunk dependencies are stored as absolute paths. We need to trim // the leading '/` or it won't match the key format requiredChunks.push(chunkDep.slice(1)); } for (const chunkDep of chunkDeps.styles) { headTags.push( `<style data-ns-css=${JSON.stringify(chunkDep.relPath)}>${chunkDep.css}</style>` ); } } } const publicUrl = encodeURI('/'); const htmlAttrs = helmet.htmlAttributes.toString(); const bodyAttrs = helmet.bodyAttributes.toString(); const bootstrapOptions: BootstrapOptions = { auth: this.serverAuthToClientAuth(request.auth), automaticReload: request.automaticReload, enableTailwind: this.settings.enableTailwind, // errStack: errStack || undefined, lazyComponents: chunkCtx.chunks, publicUrl, reactQueryState: queryClientData, }; const wrapper = ` <!doctype html> <html ${htmlAttrs}> <head> ${helmet.title.toString()} ${helmet.meta.toString()} <link rel="modulepreload" href="${publicUrl}static/build/bootstrap.js" /> ${chunkCtx.chunks .map(({ chunk }) => `<link rel="modulepreload" href="${publicUrl}${encodeURI(chunk)}" />`) .join('\n')} ${helmet.link.toString()} ${headTags.join('\n')} ${helmet.noscript.toString()} ${helmet.script.toString()} ${TwindServer.getStyleTag(customSheet)} ${helmet.style.toString()} </head> <body ${bodyAttrs}> <div id="root">${renderedMarkup}</div> <script async type="module"> import { start } from "${publicUrl}static/build/bootstrap.js"; start(${jsesc(bootstrapOptions, { es6: true, isScriptContext: true, minimal: true })}); </script> </body> </html>`.trim(); return { html: wrapper, renderCount: renderCount, queries: queryExecutor.promises.size, latency: Date.now() - start, }; } private serverAuthToClientAuth(auth: ServerAuth): ClientAuth { return auth.isAuthenticated ? { isAuthenticated: true, credentials: auth.credentials, loginUrl: '/.nostalgie/login', logoutUrl: '/.nostalgie/logout', } : { isAuthenticated: false, error: auth.error, loginUrl: '/.nostalgie/login', logoutUrl: '/.nostalgie/logout', }; } }
the_stack
module VORLON { export class Tools { public static QueryString () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = decodeURIComponent(pair[1]); // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(decodeURIComponent(pair[1])); } } return query_string; } public static QuerySelectorById(root: HTMLElement, id: string): HTMLElement { if (root.querySelector) { return <HTMLElement>root.querySelector("#" + id); } return document.getElementById(id); } public static SetImmediate(func: () => void): void { if (window.setImmediate) { setImmediate(func); } else { setTimeout(func, 0); } } public static setLocalStorageValue(key: string, data: string) { if (localStorage) { try { localStorage.setItem(key, data); } catch (e) { //local storage is not available (private mode maybe) } } } public static getLocalStorageValue(key: string) { if (localStorage) { try { return localStorage.getItem(key); } catch (e) { //local storage is not available (private mode maybe) return ""; } } } // Intercept addEventListener calls by changing the prototype public static interceptAddEventListener () { var code = function() { var current = window.addEventListener; var customAddEventListener = function (name, func: () => void, capture) { if (name === "message") { var previousFunction = func; func = (...optionalParams: any[]) => { var event = optionalParams[0]; // filtering messages sent by Vorlon code in the context of the page // they should only be intercepted by the code of the content script // otherwise we could break some logic of certain web pages if (!(event && event.data && event.data.isVorlonMessage)) { previousFunction.apply(window, optionalParams); } } } current.call(this, name, func, capture); }; window.addEventListener = customAddEventListener; } var script = document.createElement('script'); var scriptCode = '(' + code + ')()'; script.textContent = scriptCode; (document.head||document.documentElement).appendChild(script); script.parentNode.removeChild(script); } public static Hook(rootObject: any, functionToHook: string, hookingFunction: (...optionalParams: any[]) => void): void { var previousFunction = rootObject[functionToHook]; rootObject[functionToHook] = (...optionalParams: any[]) => { hookingFunction(optionalParams); previousFunction.apply(rootObject, optionalParams); } return previousFunction; } static _callBackID = 1; public static HookProperty(rootObjectName: string, propertyToHook: string, callback: (stackData: any) => void){ var currentCallbackID = this._callBackID++; window.addEventListener("message", function(event) { var isVorlonMessage = true; // We only accept messages from ourselves if (event.source != window) return; if (event.data.id && (event.data.id === currentCallbackID)) { var result = JSON.parse(event.data.value); result.property = propertyToHook; callback(result); } }, false); var code = function() { var getCallStack; //We have access to topframe - no longer a contentscript var rootObject = window[rootObjectName]; var initialValue = rootObject[propertyToHook]; Object.defineProperty(rootObject, propertyToHook, { get: function() { var callStackObject = getCallStack(1); window.postMessage({ id: currentCallbackID, value: JSON.stringify(callStackObject), isVorlonMessage: true }, "*"); return initialValue; } }); }; var script = document.createElement('script'); var scriptCode = '(' + code + ')()'; scriptCode = scriptCode.replace("currentCallbackID", currentCallbackID.toString()); scriptCode = scriptCode.replace("rootObjectName", "\"" + rootObjectName + "\""); scriptCode = scriptCode.replace(/propertyToHook/g, "\"" + propertyToHook + "\""); scriptCode = scriptCode.replace("var getCallStack;", "var getCallStack = " + Tools.getCallStack); script.textContent = scriptCode; (document.head||document.documentElement).appendChild(script); script.parentNode.removeChild(script); } public static getCallStack(skipped){ skipped = skipped || 0; try { //Throw an error to generate a stack trace throw new Error(); } catch(e) { //Split the stack trace into each line var stackLines = e.stack.split('\n'); var callerIndex = 0; //Now walk though each line until we find a path reference for(var i=2 + skipped, l = stackLines.length; i<l; i++){ if(!(stackLines[i].indexOf("http://") >= 0) && !(stackLines[i].indexOf("https://") >= 0)) continue; //We skipped all the lines with out an http so we now have a script reference //This one is the class constructor, the next is the getScriptPath() call //The one after that is the user code requesting the path info (so offset by 2) callerIndex = i; break; } var res = <any>{ stack : e.stack, // fullPath : pathParts ? pathParts[1] : null, // path : pathParts ? pathParts[2] : null, // file : pathParts ? pathParts[3] : null }; var linetext = stackLines[callerIndex]; //Now parse the string for each section we want to return //var pathParts = linetext.match(/((http[s]?:\/\/.+\/)([^\/]+\.js))([\/]):/); // if (pathParts){ // // } var opening = linetext.indexOf("http://"); if (opening < 0) { opening = linetext.indexOf("https://"); } if (opening >= 0){ var closing = linetext.indexOf(")", opening); if (closing < 0) closing = linetext.length - 1; var filename = linetext.substr(opening, closing - opening); var linestart = filename.indexOf(":", filename.lastIndexOf("/")); res.file = filename.substr(0, linestart); res.line = filename.substr(linestart + 1); } return res; } } public static CreateCookie(name: string, value: string, days: number): void { var expires: string; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; } public static ReadCookie(name: string): string { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return ""; } // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 public static CreateGUID(): string { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,(c) => { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } public static RemoveEmpties(arr: string[]): number { var len = arr.length; for (var i = len - 1; i >= 0; i--) { if (!arr[i]) { arr.splice(i, 1); len--; } } return len; } public static AddClass(e: HTMLElement, name: string): HTMLElement { if (e.classList) { if (name.indexOf(" ") < 0) { e.classList.add(name); } else { var namesToAdd = name.split(" "); Tools.RemoveEmpties(namesToAdd); for (var i = 0, len = namesToAdd.length; i < len; i++) { e.classList.add(namesToAdd[i]); } } return e; } else { var className = e.className; var names = className.split(" "); var l = Tools.RemoveEmpties(names); var toAdd; if (name.indexOf(" ") >= 0) { namesToAdd = name.split(" "); Tools.RemoveEmpties(namesToAdd); for (i = 0; i < l; i++) { var found = namesToAdd.indexOf(names[i]); if (found >= 0) { namesToAdd.splice(found, 1); } } if (namesToAdd.length > 0) { toAdd = namesToAdd.join(" "); } } else { var saw = false; for (i = 0; i < l; i++) { if (names[i] === name) { saw = true; break; } } if (!saw) { toAdd = name; } } if (toAdd) { if (l > 0 && names[0].length > 0) { e.className = className + " " + toAdd; } else { e.className = toAdd; } } return e; } } public static RemoveClass(e: HTMLElement, name: string): HTMLElement { if (e.classList) { if (e.classList.length === 0) { return e; } var namesToRemove = name.split(" "); Tools.RemoveEmpties(namesToRemove); for (var i = 0, len = namesToRemove.length; i < len; i++) { e.classList.remove(namesToRemove[i]); } return e; } else { var original = e.className; if (name.indexOf(" ") >= 0) { namesToRemove = name.split(" "); Tools.RemoveEmpties(namesToRemove); } else { if (original.indexOf(name) < 0) { return e; } namesToRemove = [name]; } var removed; var names = original.split(" "); var namesLen = Tools.RemoveEmpties(names); for (i = namesLen - 1; i >= 0; i--) { if (namesToRemove.indexOf(names[i]) >= 0) { names.splice(i, 1); removed = true; } } if (removed) { e.className = names.join(" "); } return e; } } public static ToggleClass(e: HTMLElement, name: string, callback? : (hasClass:boolean) => void) { if (e.className.match(name)) { Tools.RemoveClass(e, name); if (callback) callback(false); } else { Tools.AddClass(e, name); if (callback) callback(true); } } public static htmlToString(text) { return text; } } export class FluentDOM { public element: HTMLElement; public childs: Array<FluentDOM>; public parent: FluentDOM; constructor(nodeType: string, className?: string, parentElt?: Element, parent?: FluentDOM) { this.childs = []; if (nodeType) { this.element = document.createElement(nodeType); if (className) this.element.className = className; if (parentElt) parentElt.appendChild(this.element); this.parent = parent; if (parent) { parent.childs.push(this); } } } public static forElement(element: HTMLElement) { var res = new FluentDOM(null); res.element = element; return res; } addClass(classname: string) { this.element.classList.add(classname); return this; } toggleClass(classname: string) { this.element.classList.toggle(classname); return this; } hasClass(classname: string): boolean { return this.element.classList.contains(classname); } className(classname: string) { this.element.className = classname; return this; } opacity(opacity: string) { this.element.style.opacity = opacity; return this; } display(display: string) { this.element.style.display = display; return this; } hide() { this.element.style.display = 'none'; return this; } visibility(visibility: string) { this.element.style.visibility = visibility; return this; } text(text: string) { this.element.textContent = text; return this; } html(text: string) { this.element.innerHTML = text; return this; } attr(name: string, val: string) { this.element.setAttribute(name, val); return this; } editable(editable: boolean) { this.element.contentEditable = editable ? "true" : "false"; return this; } style(name: string, val: string) { this.element.style[name] = val; return this; } appendTo(elt: Element) { elt.appendChild(this.element); return this; } append(nodeType: string, className?: string, callback?: (fdom: FluentDOM) => void) { var child = new FluentDOM(nodeType, className, this.element, this); if (callback) { callback(child); } return this; } createChild(nodeType: string, className?: string) { var child = new FluentDOM(nodeType, className, this.element, this); return child; } click(callback: (EventTarget) => void) { this.element.addEventListener('click', callback); return this; } blur(callback: (EventTarget) => void) { this.element.addEventListener('blur', callback); return this; } keydown(callback: (EventTarget) => void) { this.element.addEventListener('keydown', callback); return this; } } }
the_stack
// clang-format off import {assertNotReached} from 'chrome://resources/js/assert.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {AutofillManagerProxy, PasswordEditDialogElement, PasswordListItemElement, PasswordMoveMultiplePasswordsToAccountDialogElement, PasswordsExportDialogElement, PasswordsSectionElement, PaymentsManagerProxy, PersonalDataChangedListener} from 'chrome://settings/lazy_load.js'; import {MultiStoreExceptionEntry, MultiStorePasswordUiEntry, PasswordManagerProxy} from 'chrome://settings/settings.js'; import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {TestPasswordManagerProxy} from './test_password_manager_proxy.js'; // clang-format on export type PasswordEntryParams = { url?: string, username?: string, federationText?: string, id?: number, frontendId?: number, fromAccountStore?: boolean, }; /** * Creates a single item for the list of passwords, in the format sent by the * password manager native code. If no |params.id| is passed, it is set to a * default, value so this should probably not be done in tests with multiple * entries (|params.id| is unique). If no |params.frontendId| is passed, it is * set to the same value set for |params.id|. */ export function createPasswordEntry(params?: PasswordEntryParams): chrome.passwordsPrivate.PasswordUiEntry { // Generate fake data if param is undefined. params = params || {}; const url = params.url !== undefined ? params.url : 'www.foo.com'; const username = params.username !== undefined ? params.username : 'user'; const id = params.id !== undefined ? params.id : 42; const frontendId = params.frontendId !== undefined ? params.frontendId : id; const fromAccountStore = params.fromAccountStore || false; return { urls: { origin: 'http://' + url + '/login', shown: url, link: 'http://' + url + '/login', }, username: username, federationText: params.federationText, id: id, frontendId: frontendId, fromAccountStore: fromAccountStore, }; } export type MultyStorePasswordEntryParams = { url?: string, username?: string, federationText?: string, accountId?: number, deviceId?: number, }; /** * Creates a multi-store password item with the same mock data as * createPasswordEntry(), so can be used for verifying deduplication result. * At least one of |params.accountId| and |params.deviceId| must be set. */ export function createMultiStorePasswordEntry( params: MultyStorePasswordEntryParams): MultiStorePasswordUiEntry { const dummyFrontendId = 42; let deviceEntry, accountEntry; if (params.deviceId !== undefined) { deviceEntry = createPasswordEntry({ url: params.url, username: params.username, federationText: params.federationText, id: params.deviceId, frontendId: dummyFrontendId, fromAccountStore: false }); } if (params.accountId !== undefined) { accountEntry = createPasswordEntry({ url: params.url, username: params.username, federationText: params.federationText, id: params.accountId, frontendId: dummyFrontendId, fromAccountStore: true }); } if (deviceEntry && accountEntry) { const mergedEntry = new MultiStorePasswordUiEntry(deviceEntry); mergedEntry.mergeInPlace(accountEntry); return mergedEntry; } if (deviceEntry) { return new MultiStorePasswordUiEntry(deviceEntry); } if (accountEntry) { return new MultiStorePasswordUiEntry(accountEntry); } assertNotReached(); return new MultiStorePasswordUiEntry(createPasswordEntry()); } export type ExceptionEntryParams = { url?: string, id?: number, frontendId?: number, fromAccountStore?: boolean, }; /** * Creates a single item for the list of password exceptions. If no |id| is * passed, it is set to a default, value so this should probably not be done in * tests with multiple entries (|id| is unique). If no |frontendId| is passed, * it is set to the same value set for |id|. */ export function createExceptionEntry(params?: ExceptionEntryParams): chrome.passwordsPrivate.ExceptionEntry { params = params || {}; const url = params.url !== undefined ? params.url : 'www.foo.com'; const id = params.id !== undefined ? params.id : 42; const frontendId = params.frontendId !== undefined ? params.frontendId : id; const fromAccountStore = params.fromAccountStore || false; return { urls: { origin: 'http://' + url + '/login', shown: url, link: 'http://' + url + '/login', }, id: id, frontendId: frontendId, fromAccountStore: fromAccountStore, }; } export type MultiStoreExceptionEntryParams = { url?: string, accountId?: number, deviceId?: number, }; /** * Creates a multi-store password item with the same mock data as * createExceptionEntry(), so it can be used for verifying deduplication result. * At least one of |accountId| and |deviceId| must be set. */ export function createMultiStoreExceptionEntry( params: MultiStoreExceptionEntryParams): MultiStoreExceptionEntry { const dummyFrontendId = 42; let deviceEntry, accountEntry; if (params.deviceId !== undefined) { deviceEntry = createExceptionEntry({ url: params.url, id: params.deviceId, frontendId: dummyFrontendId, fromAccountStore: false }); } if (params.accountId !== undefined) { accountEntry = createExceptionEntry({ url: params.url, id: params.accountId, frontendId: dummyFrontendId, fromAccountStore: true }); } if (deviceEntry && accountEntry) { const mergedEntry = new MultiStoreExceptionEntry(deviceEntry); mergedEntry.mergeInPlace(accountEntry); return mergedEntry; } if (deviceEntry) { return new MultiStoreExceptionEntry(deviceEntry); } if (accountEntry) { return new MultiStoreExceptionEntry(accountEntry); } assertNotReached(); return new MultiStoreExceptionEntry(createExceptionEntry()); } /** * Creates a new fake address entry for testing. */ export function createEmptyAddressEntry(): chrome.autofillPrivate.AddressEntry { return {}; } /** * Creates a fake address entry for testing. */ export function createAddressEntry(): chrome.autofillPrivate.AddressEntry { const fullName = 'John Doe'; const addressLines = patternMaker_('xxxx Main St', 10); return { guid: makeGuid_(), fullNames: [fullName], companyName: 'Google', addressLines: addressLines, addressLevel1: 'CA', addressLevel2: 'Venice', postalCode: patternMaker_('xxxxx', 10), countryCode: 'US', phoneNumbers: [patternMaker_('(xxx) xxx-xxxx', 10)], emailAddresses: [patternMaker_('userxxxx@gmail.com', 16)], languageCode: 'EN-US', metadata: { isLocal: true, summaryLabel: fullName, summarySublabel: ', ' + addressLines, }, }; } /** * Creates a new empty credit card entry for testing. */ export function createEmptyCreditCardEntry(): chrome.autofillPrivate.CreditCardEntry { const now = new Date(); const expirationMonth = now.getMonth() + 1; return { expirationMonth: expirationMonth.toString(), expirationYear: now.getFullYear().toString(), }; } /** * Creates a new random credit card entry for testing. */ export function createCreditCardEntry(): chrome.autofillPrivate.CreditCardEntry { const cards = ['Visa', 'Mastercard', 'Discover', 'Card']; const card = cards[Math.floor(Math.random() * cards.length)]; const cardNumber = patternMaker_('xxxx xxxx xxxx xxxx', 10); return { guid: makeGuid_(), name: 'Jane Doe', cardNumber: cardNumber, expirationMonth: Math.ceil(Math.random() * 11).toString(), expirationYear: (2016 + Math.floor(Math.random() * 5)).toString(), network: `${card}_network`, metadata: { isLocal: true, summaryLabel: card + ' ' + '****' + cardNumber.substr(-4), }, }; } /** * Creates a new insecure credential. */ export function makeInsecureCredential( url: string, username: string, id?: number): chrome.passwordsPrivate.InsecureCredential { return { id: id || 0, formattedOrigin: url, changePasswordUrl: `http://${url}/`, username: username, detailedOrigin: '', isAndroidCredential: false, signonRealm: '', }; } /** * Creates a new compromised credential. */ export function makeCompromisedCredential( url: string, username: string, type: chrome.passwordsPrivate.CompromiseType, id?: number, elapsedMinSinceCompromise?: number): chrome.passwordsPrivate.InsecureCredential { const credential = makeInsecureCredential(url, username, id); elapsedMinSinceCompromise = elapsedMinSinceCompromise || 0; credential.compromisedInfo = { compromiseTime: Date.now() - (elapsedMinSinceCompromise * 60000), elapsedTimeSinceCompromise: `${elapsedMinSinceCompromise} minutes ago`, compromiseType: type, }; return credential; } /** * Creates a new password check status. */ export function makePasswordCheckStatus( state?: chrome.passwordsPrivate.PasswordCheckState, checked?: number, remaining?: number, lastCheck?: string): chrome.passwordsPrivate.PasswordCheckStatus { return { state: state || chrome.passwordsPrivate.PasswordCheckState.IDLE, alreadyProcessed: checked, remainingInQueue: remaining, elapsedTimeSinceLastCheck: lastCheck, }; } /** * Creates a new random GUID for testing. */ function makeGuid_(): string { return patternMaker_('xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', 16); } /** * Replaces any 'x' in a string with a random number of the base. * @param pattern The pattern that should be used as an input. * @param base The number base. ie: 16 for hex or 10 for decimal. */ function patternMaker_(pattern: string, base: number): string { return pattern.replace(/x/g, function() { return Math.floor(Math.random() * base).toString(base); }); } /** * Helper class for creating password-section sub-element from fake data and * appending them to the document. */ export class PasswordSectionElementFactory { document: HTMLDocument; /** * @param document The test's |document| object. */ constructor(document: HTMLDocument) { this.document = document; } /** * Helper method used to create a password section for the given lists. */ createPasswordsSection( passwordManager: TestPasswordManagerProxy, passwordList: chrome.passwordsPrivate.PasswordUiEntry[], exceptionList: chrome.passwordsPrivate.ExceptionEntry[]): PasswordsSectionElement { // Override the TestPasswordManagerProxy data for testing. passwordManager.data.passwords = passwordList; passwordManager.data.exceptions = exceptionList; // Create a passwords-section to use for testing. const passwordsSection = this.document.createElement('passwords-section'); passwordsSection.prefs = { credentials_enable_service: {}, profile: { password_manager_leak_detection: { value: true, } }, }; this.document.body.appendChild(passwordsSection); flush(); return passwordsSection; } /** * Helper method used to create a password list item. */ createPasswordListItem(passwordEntry: chrome.passwordsPrivate.PasswordUiEntry): PasswordListItemElement { const passwordListItem = this.document.createElement('password-list-item'); passwordListItem.entry = new MultiStorePasswordUiEntry(passwordEntry); this.document.body.appendChild(passwordListItem); flush(); return passwordListItem; } /** * Helper method used to create a password editing dialog. */ createPasswordEditDialog( passwordEntry: MultiStorePasswordUiEntry|null = null, passwords?: MultiStorePasswordUiEntry[], isAccountStoreUser: boolean = false): PasswordEditDialogElement { const passwordDialog = this.document.createElement('password-edit-dialog'); passwordDialog.existingEntry = passwordEntry; if (passwordEntry && !passwordEntry.federationText) { // Edit dialog is always opened with plaintext password for non-federated // credentials since user authentication is required before opening the // edit dialog. passwordDialog.existingEntry!.password = 'password'; } passwordDialog.savedPasswords = passwords || (passwordEntry ? [passwordEntry] : []); passwordDialog.isAccountStoreUser = isAccountStoreUser; this.document.body.appendChild(passwordDialog); flush(); return passwordDialog; } /** * Helper method used to create an export passwords dialog. */ createExportPasswordsDialog(passwordManager: PasswordManagerProxy): PasswordsExportDialogElement { passwordManager.requestExportProgressStatus = callback => { callback(chrome.passwordsPrivate.ExportProgressStatus.NOT_STARTED); }; passwordManager.exportPasswords = (callback) => { callback(); }; const dialog = this.document.createElement('passwords-export-dialog'); this.document.body.appendChild(dialog); flush(); return dialog; } } /** * Helper class for creating password-device-section sub-element from fake data * and appending them to the document. */ export class PasswordDeviceSectionElementFactory { document: HTMLDocument; /** * @param document The test's |document| object. */ constructor(document: HTMLDocument) { this.document = document; } /** * Helper method used to create a move multiple password to the Google Account * dialog. */ createMoveMultiplePasswordsDialog(passwordsToMove: MultiStorePasswordUiEntry[]): PasswordMoveMultiplePasswordsToAccountDialogElement { const moveDialog = this.document.createElement( 'password-move-multiple-passwords-to-account-dialog'); moveDialog.passwordsToMove = passwordsToMove; this.document.body.appendChild(moveDialog); flush(); return moveDialog; } } /** Helper class to track AutofillManager expectations. */ export class AutofillManagerExpectations { requestedAddresses: number = 0; listeningAddresses: number = 0; removeAddress: number = 0; } /** * Test implementation */ export class TestAutofillManager implements AutofillManagerProxy { private actual_: AutofillManagerExpectations; data: { addresses: chrome.autofillPrivate.AddressEntry[], }; lastCallback: {setPersonalDataManagerListener: PersonalDataChangedListener|null}; constructor() { this.actual_ = new AutofillManagerExpectations(); // Set these to have non-empty data. this.data = { addresses: [], }; // Holds the last callbacks so they can be called when needed. this.lastCallback = { setPersonalDataManagerListener: null, }; } setPersonalDataManagerListener(listener: PersonalDataChangedListener) { this.actual_.listeningAddresses++; this.lastCallback.setPersonalDataManagerListener = listener; } removePersonalDataManagerListener(_listener: PersonalDataChangedListener) { this.actual_.listeningAddresses--; } getAddressList( callback: (entries: chrome.autofillPrivate.AddressEntry[]) => void) { this.actual_.requestedAddresses++; callback(this.data.addresses); } saveAddress(_address: chrome.autofillPrivate.AddressEntry) {} removeAddress(_guid: string) { this.actual_.removeAddress++; } /** * Verifies expectations. */ assertExpectations(expected: AutofillManagerExpectations) { const actual = this.actual_; assertEquals(expected.requestedAddresses, actual.requestedAddresses); assertEquals(expected.listeningAddresses, actual.listeningAddresses); assertEquals(expected.removeAddress, actual.removeAddress); } } /** Helper class to track PaymentsManager expectations. */ export class PaymentsManagerExpectations { requestedCreditCards: number = 0; listeningCreditCards: number = 0; requestedUpiIds: number = 0; } /** * Test implementation */ export class TestPaymentsManager implements PaymentsManagerProxy { private actual_: PaymentsManagerExpectations; data: { creditCards: chrome.autofillPrivate.CreditCardEntry[], upiIds: string[], }; lastCallback: {setPersonalDataManagerListener: PersonalDataChangedListener|null}; constructor() { this.actual_ = new PaymentsManagerExpectations(); // Set these to have non-empty data. this.data = { creditCards: [], upiIds: [], }; // Holds the last callbacks so they can be called when needed. this.lastCallback = { setPersonalDataManagerListener: null, }; } setPersonalDataManagerListener(listener: PersonalDataChangedListener) { this.actual_.listeningCreditCards++; this.lastCallback.setPersonalDataManagerListener = listener; } removePersonalDataManagerListener(_listener: PersonalDataChangedListener) { this.actual_.listeningCreditCards--; } getCreditCardList( callback: (entries: chrome.autofillPrivate.CreditCardEntry[]) => void) { this.actual_.requestedCreditCards++; callback(this.data.creditCards); } getUpiIdList(callback: (entries: string[]) => void) { this.actual_.requestedUpiIds++; callback(this.data.upiIds); } clearCachedCreditCard(_guid: string) {} logServerCardLinkClicked() {} migrateCreditCards() {} removeCreditCard(_guid: string) {} saveCreditCard(_creditCard: chrome.autofillPrivate.CreditCardEntry) {} setCreditCardFIDOAuthEnabledState(_enabled: boolean) {} /** * Verifies expectations. */ assertExpectations(expected: PaymentsManagerExpectations) { const actual = this.actual_; assertEquals(expected.requestedCreditCards, actual.requestedCreditCards); assertEquals(expected.listeningCreditCards, actual.listeningCreditCards); } }
the_stack
import '@/style/masonry.less' import { CONSTANTS } from '@/util/common' import Exception from '@/components/Exception' import PageTitle from '@/components/PageTitle' import applicationModel from '@/models/application/model' import applicationService from '@/models/application/service' import { connect } from '@/util/store' import filesize from 'filesize' import _ from 'lodash' import './style.less' import { Col, Collapse, Icon, Input, Layout, Radio, Row, Tooltip } from 'antd' import * as d3 from 'd3' import React from 'react' import { RouteComponentProps, withRouter } from 'react-router' import AppTbs from '@/components/appTbs' const Content = Layout.Content const Panel = Collapse.Panel const Search = Input.Search const CategoryTag = (props: { versionTabData: any }) => { const { versionTabData } = props return ( <div className="category-tag-container"> <Tooltip title="唯一依赖"> <div className="tag tag-normal"> <p>normal:({versionTabData.normalCount})</p> <Icon type="question-circle" /> </div> </Tooltip> <Tooltip title="初始依赖"> <div className="tag tag-start"> <p>start</p> <Icon type="question-circle" /> </div> </Tooltip> <Tooltip title="该 jar 包被多个库依赖, 且有多个版本, 如 : spring-web: '4.3.9.RELEASE', '4.3.17.RELEASE', '4.3.20.RELEASE', 并且当前安装的依赖包版本号 < 声明的最高版本号"> <div className="tag tag-low"> <p>low:({versionTabData.lowCount})</p> <Icon type="question-circle" /> </div> </Tooltip> <Tooltip title="该 jar 包被多个库依赖, 且有多个版本, 如 : spring-web: '4.3.9.RELEASE', '4.3.17.RELEASE', '4.3.20.RELEASE'"> <div className="tag tag-many"> <p>many:({versionTabData.manyCount})</p> <Icon type="question-circle" /> </div> </Tooltip> </div> ) } interface IJarState { currentNodeData: any currentSegment: any frameworkVersion: any jarDeps: any versionTabData: any isFetched: boolean searchFilter: string noData: boolean } class Jar extends React.Component<RouteComponentProps<{ id: string }>, IJarState> { public state: IJarState = { currentSegment: 'Net', currentNodeData: null, frameworkVersion: {}, jarDeps: {}, versionTabData: {}, isFetched: false, searchFilter: '', noData: false, } private isDragging: boolean = false private dragMovedCount: number = 0 // when click, dragStart and dragEnd will trigger, use this flag to prevent fire both of the event private simulation: any private currentSelectedNodeIndex: number = -1 private currentSimulationStopped: boolean = false private debouncedSearchJarDeps = _.debounce((value: any) => { return this.setState({ searchFilter: value }) }, 250) public componentDidMount() { const { match } = this.props applicationService .fetchApplicationJar(match.params.id) .then(data => { data.pomInfos = data.pomInfos.filter((i: any) => { return i.groupId && i.artifactId }) this.drawCart(data) }) .catch((e: RequestError) => { if (e.errorCode === 404) { this.setState({ noData: true, }) } }) } public render() { const { currentNodeData, currentSegment, frameworkVersion, isFetched, noData } = this.state return ( <div className="page-jar"> <Row> <Col span={24}> <AppTbs MenuData={this.props} /> </Col> </Row> <Layout className="page jardeps"> <Row> <Col span={24}> <PageTitle name="查看依赖" info="查看当前实例的依赖情况" /> </Col> </Row> <Content style={{ background: '#fff', position: 'relative', }}> {noData && <Exception type="302" />} {!noData && <div className={currentSegment === 'Net' ? '' : 'hidden'} id="chart" />} {!noData && currentSegment === 'Tree' && <div>{this.renderTree()}</div>} </Content> </Layout> {isFetched && this.renderJarTab(currentSegment === 'Tree')} {isFetched && currentSegment === 'Net' && ( <CategoryTag versionTabData={this.state.versionTabData} /> )} {isFetched && currentSegment === 'Net' && this.renderVersion(frameworkVersion)} {currentSegment === 'Net' && this.renderDepsBoard(currentNodeData)} </div> ) } private drawCart(json: any) { this.setState({ isFetched: true, jarDeps: json, frameworkVersion: { springBootVersion: json.springBootVersion, springCloudVersion: json.springCloudVersion, summerframeworkVersion: json.summerframeworkVersion, totalJarCount: json.pomInfos.length, }, }) const nodes: any[] = [] let links: any[] = [] const versionTabData = { normalCount: 0, lowCount: 0, manyCount: 0, } const depsMap = new Map() json.pomInfos.forEach((data: any) => { const node = { group: data.groupId, name: data.artifactId, version: data.version, } nodes.push(node) if (Array.isArray(data.dependencies)) { data.dependencies = data.dependencies.map((dep: any) => { dep.source = dep.artifactId dep.target = data.artifactId const findData = json.pomInfos.find((rawNode: any) => { return rawNode.artifactId === dep.artifactId }) if (findData) { if (!findData.usage) { findData.usage = [] } findData.usage.push(node) } if (dep.version) { const versions = depsMap.get(dep.artifactId) || [] versions.push(dep.version) depsMap.set(dep.artifactId, versions) } return dep }) links.push(...data.dependencies) } }) // @ts-ignore for (const [key, value] of depsMap) { const filteredValue = _.uniqWith(value, (a: any, b: any) => { return this.versionToNum(a) === this.versionToNum(b) }).sort((a: any, b: any) => { // @ts-ignore return this.versionToNum(a) - this.versionToNum(b) }) depsMap.set(key, filteredValue) } links = links .filter((dep: any) => { const find = nodes.find((n: any) => { return n.artifactId === dep.target }) return !find }) .map((l: any) => { l.source = nodes.findIndex((n: any) => { return n.name === l.source }) l.target = nodes.findIndex((n: any) => { return n.name === l.target }) return l.source > 0 && l.target > 0 ? l : null }) .filter((dep: any) => dep !== null) const width = CONSTANTS.CHART_CONTENT_WIDTH const height = 1000 const simulation = d3.forceSimulation() const force = simulation .force( 'charge', d3 .forceManyBody() .theta(0.1) .strength(-700) .distanceMin(-120) .distanceMax(400) ) .force( 'link', d3 .forceLink() .id((d: any) => d.index) .distance(140) ) .force('center', d3.forceCenter(width / 2, height / 2)) .force('y', d3.forceY(0.0001)) .force('x', d3.forceX(0.0001)) as any this.simulation = simulation const svg = d3 .select('#chart') .append('svg') .attr('width', width) .attr('height', height) const g = svg.append('g') const z = d3 .zoom() .scaleExtent([1, 10]) .on('zoom', () => { g.attr('transform', d3.event.transform) }) svg // @ts-ignore .call(z) .on('dblclick.zoom', null) .on('click', () => { if (d3.event.path[0].tagName === 'svg') { // click on the black space debouncedHandleMouseOut() this.setState({ currentNodeData: null, }) } }) g.append('svg:defs') .selectAll('marker') .data(['end']) .enter() .append('svg:marker') .attr('id', String) .attr('markerUnits', 'userSpaceOnUse') .attr('viewBox', '0 -5 10 10') .attr('refX', 18) .attr('refY', 0) .attr('markerWidth', 12) .attr('markerHeight', 12) .attr('orient', 'auto') .attr('stroke-width', 2) .append('svg:path') .attr('d', 'M2,0 L0,-3 L9,0 L0,3 M2,0 L0,-3') force .nodes(nodes) // @ts-ignore .force('link') .links(links) const link = g .selectAll('.link') .data(links) .enter() .append('svg:line') .attr('class', 'link') .attr('marker-end', 'url(#end)') // @ts-ignore const handleMouseOver = (data: any, i: number, allNode: [any]) => { if (this.isDragging || !allNode) { return } this.currentSelectedNodeIndex = i if (!this.currentSimulationStopped) { this.simulation.stop() nodes.forEach(node => { node.fixed = true }) this.currentSimulationStopped = true } const hoverNodeData = json.pomInfos.find((info: any) => { return info.artifactId === data.name }) d3.selectAll('circle').attr('opacity', (d: any) => { const isMouseOver = d.name === hoverNodeData.artifactId const isDep = hoverNodeData.dependencies.find((dep: any) => { return dep.artifactId === d.name }) return isDep || isMouseOver ? 1 : 0.2 }) d3.selectAll('text').attr('opacity', (d: any) => { const isMouseOver = d.name === hoverNodeData.artifactId const isDep = hoverNodeData.dependencies.find((dep: any) => { return dep.artifactId === d.name }) return isDep || isMouseOver ? 1 : 0.2 }) d3.selectAll('.link').attr('opacity', (l: any) => { const isDep = hoverNodeData.dependencies.find((dep: any) => { return dep === l }) return isDep ? 1 : 0.2 }) } const debouncedHandleMouseOver = _.debounce(handleMouseOver.bind(this), 200) // start after mouse out anim finish const handleMouseOut = () => { if (this.isDragging) { return } this.currentSelectedNodeIndex = -1 if (this.currentSimulationStopped) { this.simulation.restart() nodes.forEach(node => { node.fixed = false }) this.currentSimulationStopped = false } this.resetChartAnim() } const debouncedHandleMouseOut = _.debounce(handleMouseOut.bind(this), 50) // @ts-ignore const clicked = (data: any, i: number, allNode: [any]) => { if (d3.event.defaultPrevented) { return } const currentNodeData = json.pomInfos.find((j: any) => { return j.artifactId === allNode[i].__data__.name }) if (this.currentSelectedNodeIndex === i) { debouncedHandleMouseOut() } else { debouncedHandleMouseOver(data, i, allNode) } this.setState({ currentNodeData, }) } const dragstarted = (d: any) => { if (!this.currentSimulationStopped) { this.resetChartAnim() } if (!d3.event.active && !this.currentSimulationStopped) { force.alphaTarget(0.5).restart() } d.fx = d.x d.fy = d.y } const dragged = (d: any) => { this.isDragging = true this.dragMovedCount++ d.fx = d3.event.x d.fy = d3.event.y } const dragended = (d: any) => { this.isDragging = false if (this.dragMovedCount > 8) { this.dragMovedCount = 0 if (!d3.event.active && !this.currentSimulationStopped) { force.alphaTarget(0.5) } d.fx = null d.fy = null } } const d3Node = g .selectAll('.node') .data(nodes) .enter() .append('g') .attr('class', 'node') .call( // @ts-ignore d3 .drag() .on('start', dragstarted) .on('drag', dragged) .on('end', dragended) ) .on('click', clicked) d3Node .append('circle') .attr('r', 13) .attr('fill', (d: any) => { let fillColor = CONSTANTS.CHART_COLOR.GREEN d.type = 'normal' if (nodes.indexOf(d) === 0) { d.type = 'start' fillColor = CONSTANTS.CHART_COLOR.YELLOW versionTabData.normalCount++ } else { const curVersion = d.version const versions = depsMap.get(d.name) || [] if (versions.length > 0) { if (curVersion !== versions[versions.length - 1]) { d.type = 'low' fillColor = CONSTANTS.CHART_COLOR.RED versionTabData.lowCount++ } else if (versions.length > 1) { d.type = 'many' fillColor = CONSTANTS.CHART_COLOR.LIGNT_YELLOW versionTabData.manyCount++ } } } if (d.type === 'normal') { versionTabData.normalCount++ } this.setState({ versionTabData: { ...versionTabData }, }) return fillColor }) d3Node .append('text') .attr('dx', -18) .attr('dy', 6) .style('font-size', '14px') .text((d: any) => { return d.name }) force.on('tick', () => { link .attr('x1', (d: any) => { return d.source.x }) .attr('y1', (d: any) => { return d.source.y }) .attr('x2', (d: any) => { return d.target.x }) .attr('y2', (d: any) => { return d.target.y }) d3Node.attr('transform', (d: any) => { return 'translate(' + d.x + ',' + d.y + ')' }) }) return } private renderTree() { const { jarDeps, searchFilter } = this.state if (!jarDeps || !Array.isArray(jarDeps.pomInfos)) { return null } const filteredDeps = jarDeps.pomInfos.filter((dep: any) => { return dep.artifactId.indexOf(searchFilter) !== -1 }) return ( <Collapse className="tree-chart-container"> {filteredDeps.map((jar: any) => { return ( <Panel disabled={!jar.dependencies || jar.dependencies.length === 0} header={this.titleForJar(jar)} key={jar.artifactId + jar.groupId + jar.scope}> <div className="panel-content-container"> {jar.dependencies && <div className="title">Dependencies : </div>} {jar.dependencies && jar.dependencies.map((dep: any, i: number) => { return ( <p className="dep" key={i}> {this.titleForJar(dep)} </p> ) })} {jar.usage && <div className="title">Usage : </div>} {jar.usage && jar.usage.map((dep: any, i: number) => { return ( <p className="dep" key={i}>{`${dep.group}:${dep.name}:${ !dep.version || dep.version === 'null' ? '' : dep.version }`}</p> ) })} </div> </Panel> ) })} </Collapse> ) } private renderJarTab(showSearch: boolean) { return ( <div className="jar-chart-tab"> <Radio.Group defaultValue="Net" onChange={this.handleSegmentChange}> <Radio.Button value="Net">Net</Radio.Button> <Radio.Button value="Tree">Tree</Radio.Button> </Radio.Group> {showSearch && ( <Search className="search-deps" placeholder="搜索依赖" onChange={this.searchJarDeps} style={{ width: 200 }} /> )} </div> ) } private searchJarDeps = (e: any) => { return this.debouncedSearchJarDeps(e.currentTarget.value) } private renderDepsBoard(currentNodeData: any) { if (!currentNodeData) { return null } if (Array.isArray(currentNodeData.usage)) { currentNodeData.usage = _.uniqWith(currentNodeData.usage, (a: any, b: any) => { return a.name === b.name && a.group === b.group && a.version === b.version }) } return ( <div className="node-data-panel"> <p> {currentNodeData.artifactId} : {currentNodeData.version} </p> <p>Location: {currentNodeData.location}</p> <p>Size: {filesize(currentNodeData.size)}</p> {currentNodeData.dependencies && currentNodeData.dependencies.length > 0 && ( <p>Dependencies:</p> )} {currentNodeData.dependencies && currentNodeData.dependencies.map((dep: any) => { return ( <p className="dep" key={dep.artifactId + dep.groupId + dep.scope}> {this.titleForJar(dep)} </p> ) })} {currentNodeData.usage && <p>Usage:</p>} {currentNodeData.usage && currentNodeData.usage.map((u: any) => { return ( <p className="dep" key={u.name + u.group}>{`${u.group}:${u.name}:${ !u.version || u.version === 'null' ? '' : u.version }`}</p> ) })} </div> ) } private renderVersion = (version: any) => { const { springCloudVersion, springBootVersion, totalJarCount } = version return ( <div className="page-section jar-framework-panel"> <div className="page-section-content page-section-list"> <Row> <Col span={12}>springCloudVersion</Col> <Col span={12}>{springCloudVersion}</Col> </Row> <Row> <Col span={12}>springBootVersion</Col> <Col span={12}>{springBootVersion}</Col> </Row> <Row> <Col span={12}>totalJarCount</Col> <Col span={12}>{totalJarCount}</Col> </Row> </div> </div> ) } private titleForJar(jar: any) { return `${jar.artifactId}:${jar.groupId}${ !jar.version || jar.version === 'null' ? '' : ':' + jar.version }` } private applyAnim(ele: any, reset: boolean = false) { ele .transition() .ease(d3.easeCubicInOut) .duration(175) .attr('r', reset ? 13 : 18) .attr('opacity', 1) } private handleSegmentChange = (e: any) => { this.setState({ currentSegment: e.target.value, }) } private resetChartAnim() { this.applyAnim(d3.selectAll('circle'), true) this.applyAnim(d3.selectAll('text'), true) this.applyAnim(d3.selectAll('.link'), true) } private versionToNum(v: any) { let matchs // prettier-ignore if (v && (matchs = v.match(/\d+\.\d+\.\d+|\d+\.\d+/g)) !== null) { // tslint:disable-line const parts = matchs.shift().split('.'); let num = 0; if (parts.length === 2) { parts.push(0); } for (let i = 0; i < parts.length; i++) { num += (parts[i] - 0) * Math.pow(10000, 2 - i); } return num; } return v } } export default connect({ Jar: applicationModel.Jar })(withRouter(Jar))
the_stack
import { CopyOutlined, DeleteOutlined, PlusOutlined, RedoOutlined } from '@ant-design/icons'; import React, { useEffect, useState } from 'react'; import * as QueryString from 'query-string'; import { useLocation } from 'react-router'; import { Button, Empty, Image, message, Modal, Pagination, Tooltip, Typography } from 'antd'; import styled from 'styled-components'; import cronstrue from 'cronstrue'; import { useCreateIngestionExecutionRequestMutation, useCreateIngestionSourceMutation, useDeleteIngestionSourceMutation, useListIngestionSourcesQuery, useUpdateIngestionSourceMutation, } from '../../../graphql/ingestion.generated'; import { Message } from '../../shared/Message'; import TabToolbar from '../../entity/shared/components/styled/TabToolbar'; import { IngestionSourceBuilderModal } from './builder/IngestionSourceBuilderModal'; import { StyledTable } from '../../entity/shared/components/styled/StyledTable'; import { IngestionSourceExecutionList } from './IngestionSourceExecutionList'; import { getExecutionRequestStatusDisplayColor, getExecutionRequestStatusDisplayText, getExecutionRequestStatusIcon, sourceTypeToIconUrl, } from './utils'; import { DEFAULT_EXECUTOR_ID, SourceBuilderState } from './builder/types'; import { UpdateIngestionSourceInput } from '../../../types.generated'; import { capitalizeFirstLetter } from '../../shared/textUtil'; import { SearchBar } from '../../search/SearchBar'; import { useEntityRegistry } from '../../useEntityRegistry'; const SourceContainer = styled.div``; const SourcePaginationContainer = styled.div` display: flex; justify-content: center; `; const PreviewImage = styled(Image)` max-height: 28px; width: auto; object-fit: contain; margin: 0px; background-color: transparent; `; const StatusContainer = styled.div` display: flex; justify-content: left; align-items: center; `; const ActionButtonContainer = styled.div` display: flex; justify-content: right; `; const DEFAULT_PAGE_SIZE = 25; const removeExecutionsFromIngestionSource = (source) => { if (source) { return { name: source.name, type: source.type, schedule: source.schedule, config: source.config, }; } return undefined; }; export const IngestionSourceList = () => { const entityRegistry = useEntityRegistry(); const location = useLocation(); const params = QueryString.parse(location.search, { arrayFormat: 'comma' }); const paramsQuery = (params?.query as string) || undefined; const [query, setQuery] = useState<undefined | string>(undefined); useEffect(() => setQuery(paramsQuery), [paramsQuery]); const [page, setPage] = useState(1); const pageSize = DEFAULT_PAGE_SIZE; const start = (page - 1) * pageSize; const [isBuildingSource, setIsBuildingSource] = useState<boolean>(false); const [focusSourceUrn, setFocusSourceUrn] = useState<undefined | string>(undefined); const [lastRefresh, setLastRefresh] = useState(0); // Set of removed urns used to account for eventual consistency const [removedUrns, setRemovedUrns] = useState<string[]>([]); // Ingestion Source Queries const { loading, error, data, refetch } = useListIngestionSourcesQuery({ variables: { input: { start, count: pageSize, query, }, }, }); const [createIngestionSource] = useCreateIngestionSourceMutation(); const [updateIngestionSource] = useUpdateIngestionSourceMutation(); // Execution Request queries const [createExecutionRequestMutation] = useCreateIngestionExecutionRequestMutation(); const [removeIngestionSourceMutation] = useDeleteIngestionSourceMutation(); const totalSources = data?.listIngestionSources?.total || 0; const sources = data?.listIngestionSources?.ingestionSources || []; const filteredSources = sources.filter((user) => !removedUrns.includes(user.urn)); const focusSource = (focusSourceUrn && filteredSources.find((source) => source.urn === focusSourceUrn)) || undefined; const onCreateOrUpdateIngestionSourceSuccess = () => { setTimeout(() => refetch(), 2000); setIsBuildingSource(false); setFocusSourceUrn(undefined); }; const createOrUpdateIngestionSource = (input: UpdateIngestionSourceInput, resetState: () => void) => { if (focusSourceUrn) { // Update: updateIngestionSource({ variables: { urn: focusSourceUrn as string, input } }) .then(() => { message.success({ content: `Successfully updated ingestion source!`, duration: 3, }); onCreateOrUpdateIngestionSourceSuccess(); resetState(); }) .catch((e) => { message.destroy(); message.error({ content: `Failed to update ingestion source!: \n ${e.message || ''}`, duration: 3, }); }); } else { // Create createIngestionSource({ variables: { input } }) .then(() => { setTimeout(() => refetch(), 2000); setIsBuildingSource(false); setFocusSourceUrn(undefined); resetState(); message.success({ content: `Successfully created ingestion source!`, duration: 3, }); // onCreateOrUpdateIngestionSourceSuccess(); }) .catch((e) => { message.destroy(); message.error({ content: `Failed to create ingestion source!: \n ${e.message || ''}`, duration: 3, }); }); } }; const onChangePage = (newPage: number) => { setPage(newPage); }; const onRefresh = () => { refetch(); // Used to force a re-render of the child execution request list. setLastRefresh(new Date().getMilliseconds()); }; const executeIngestionSource = (urn: string) => { createExecutionRequestMutation({ variables: { input: { ingestionSourceUrn: urn, }, }, }) .then(() => { message.success({ content: `Successfully submitted ingestion execution request!`, duration: 3, }); setInterval(() => onRefresh(), 3000); }) .catch((e) => { message.destroy(); message.error({ content: `Failed to submit ingestion execution request!: \n ${e.message || ''}`, duration: 3, }); }); }; const deleteIngestionSource = async (urn: string) => { removeIngestionSourceMutation({ variables: { urn }, }) .then(() => { message.success({ content: 'Removed ingestion source.', duration: 2 }); const newRemovedUrns = [...removedUrns, urn]; setRemovedUrns(newRemovedUrns); setTimeout(function () { refetch?.(); }, 3000); }) .catch((e: unknown) => { message.destroy(); if (e instanceof Error) { message.error({ content: `Failed to remove ingestion source: \n ${e.message || ''}`, duration: 3 }); } }); }; const onSubmit = (recipeBuilderState: SourceBuilderState, resetState: () => void) => { createOrUpdateIngestionSource( { type: recipeBuilderState.type as string, name: recipeBuilderState.name as string, config: { recipe: recipeBuilderState.config?.recipe as string, version: (recipeBuilderState.config?.version?.length && (recipeBuilderState.config?.version as string)) || undefined, executorId: (recipeBuilderState.config?.executorId?.length && (recipeBuilderState.config?.executorId as string)) || DEFAULT_EXECUTOR_ID, }, schedule: recipeBuilderState.schedule && { interval: recipeBuilderState.schedule?.interval as string, timezone: recipeBuilderState.schedule?.timezone as string, }, }, resetState, ); }; const onEdit = (urn: string) => { setIsBuildingSource(true); setFocusSourceUrn(urn); }; const onExecute = (urn: string) => { Modal.confirm({ title: `Confirm Source Execution`, content: "Click 'Execute' to run this ingestion source.", onOk() { executeIngestionSource(urn); }, onCancel() {}, okText: 'Execute', maskClosable: true, closable: true, }); }; const onDelete = (urn: string) => { Modal.confirm({ title: `Confirm Ingestion Source Removal`, content: `Are you sure you want to remove this ingestion source? Removing will terminate any scheduled ingestion runs.`, onOk() { deleteIngestionSource(urn); }, onCancel() {}, okText: 'Yes', maskClosable: true, closable: true, }); }; const onCancel = () => { setIsBuildingSource(false); setFocusSourceUrn(undefined); }; const tableColumns = [ { title: 'Type', dataIndex: 'type', key: 'type', render: (type: string) => { const iconUrl = sourceTypeToIconUrl(type); const typeDisplayName = capitalizeFirstLetter(type); return ( (iconUrl && ( <Tooltip overlay={typeDisplayName}> <PreviewImage preview={false} src={iconUrl} alt={type || ''} /> </Tooltip> )) || <Typography.Text strong>{typeDisplayName}</Typography.Text> ); }, }, { title: 'Name', dataIndex: 'name', key: 'name', render: (name: string) => name || '', }, { title: 'Schedule', dataIndex: 'schedule', key: 'schedule', render: (schedule: any, record: any) => { const tooltip = schedule && `Runs ${cronstrue.toString(schedule).toLowerCase()} (${record.timezone})`; return ( <Tooltip title={tooltip || 'Not scheduled'}> <Typography.Text code>{schedule || 'None'}</Typography.Text> </Tooltip> ); }, }, { title: 'Execution Count', dataIndex: 'execCount', key: 'execCount', render: (execCount: any) => { return <Typography.Text>{execCount || '0'}</Typography.Text>; }, }, { title: 'Last Execution', dataIndex: 'lastExecTime', key: 'lastExecTime', render: (time: any) => { const executionDate = time && new Date(time); const localTime = executionDate && `${executionDate.toLocaleDateString()} at ${executionDate.toLocaleTimeString()}`; return <Typography.Text>{localTime || 'N/A'}</Typography.Text>; }, }, { title: 'Last Status', dataIndex: 'lastExecStatus', key: 'lastExecStatus', render: (status: any) => { const Icon = getExecutionRequestStatusIcon(status); const text = getExecutionRequestStatusDisplayText(status); const color = getExecutionRequestStatusDisplayColor(status); return ( <StatusContainer> {Icon && <Icon style={{ color }} />} <Typography.Text strong style={{ color, marginLeft: 8 }}> {text || 'N/A'} </Typography.Text> </StatusContainer> ); }, }, { title: '', dataIndex: '', key: 'x', render: (_, record: any) => ( <ActionButtonContainer> {navigator.clipboard && ( <Tooltip title="Copy Ingestion Source URN"> <Button style={{ marginRight: 16 }} icon={<CopyOutlined />} onClick={() => { navigator.clipboard.writeText(record.urn); }} /> </Tooltip> )} <Button style={{ marginRight: 16 }} onClick={() => onEdit(record.urn)}> EDIT </Button> <Button disabled={record.lastExecStatus === 'RUNNING'} style={{ marginRight: 16 }} onClick={() => onExecute(record.urn)} > EXECUTE </Button> <Button onClick={() => onDelete(record.urn)} type="text" shape="circle" danger> <DeleteOutlined /> </Button> </ActionButtonContainer> ), }, ]; const tableData = filteredSources?.map((source) => ({ urn: source.urn, type: source.type, name: source.name, schedule: source.schedule?.interval, timezone: source.schedule?.timezone, execCount: source.executions?.total || 0, lastExecTime: source.executions?.total && source.executions?.total > 0 && source.executions?.executionRequests[0].result?.startTimeMs, lastExecStatus: source.executions?.total && source.executions?.total > 0 && source.executions?.executionRequests[0].result?.status, })); return ( <> {!data && loading && <Message type="loading" content="Loading ingestion sources..." />} {error && message.error({ content: `Failed to load ingestion sources! \n ${error.message || ''}`, duration: 3 })} <SourceContainer> <TabToolbar> <div> <Button type="text" onClick={() => setIsBuildingSource(true)}> <PlusOutlined /> Create new source </Button> <Button type="text" onClick={onRefresh}> <RedoOutlined /> Refresh </Button> </div> <SearchBar initialQuery={query || ''} placeholderText="Search sources..." suggestions={[]} style={{ maxWidth: 220, padding: 0, }} inputStyle={{ height: 32, fontSize: 12, }} onSearch={() => null} onQueryChange={(q) => setQuery(q)} entityRegistry={entityRegistry} /> </TabToolbar> <StyledTable columns={tableColumns} dataSource={tableData} rowKey="urn" locale={{ emptyText: <Empty description="No Ingestion Sources!" image={Empty.PRESENTED_IMAGE_SIMPLE} />, }} expandable={{ expandedRowRender: (record) => { return ( <IngestionSourceExecutionList urn={record.urn} lastRefresh={lastRefresh} onRefresh={onRefresh} /> ); }, rowExpandable: (record) => { return record.execCount > 0; }, defaultExpandAllRows: false, indentSize: 0, }} pagination={false} /> <SourcePaginationContainer> <Pagination style={{ margin: 40 }} current={page} pageSize={pageSize} total={totalSources} showLessItems onChange={onChangePage} showSizeChanger={false} /> </SourcePaginationContainer> </SourceContainer> <IngestionSourceBuilderModal initialState={removeExecutionsFromIngestionSource(focusSource)} visible={isBuildingSource} onSubmit={onSubmit} onCancel={onCancel} /> </> ); };
the_stack
import {IApp} from '../../../IApp'; import {SoundCloudAPIResponse} from './SoundCloudAPIResponse'; import {SoundCloudAudioType} from './SoundCloudAudioType'; declare var App: IApp; declare var SC: any; export class SoundCloudAPI { static _QueryReturns: number; static QueryTotal: number; static QueryList: any[]; static Initialize() { if (typeof(SC) !== "undefined") { SC.initialize({ client_id: App.Config.SoundCloudClientId }); } this.QueryTotal = 5; } //------------------------------------------------------------------------------------------- // LOADING TRACKS //------------------------------------------------------------------------------------------- static PickRandomTrack(t:SoundCloudAudioType) { switch (t) { case SoundCloudAudioType.Soundcloud: var defaults = App.Config.SoundCloudDefaultTracks; break; case SoundCloudAudioType.Granular: var defaults = App.Config.GranularDefaultTracks; break; case SoundCloudAudioType.Convolution: var defaults = App.Config.ConvolverDefaultTracks; break; default: var defaults = App.Config.SoundCloudDefaultTracks; } var track = defaults[Math.floor((Math.random() * defaults.length))]; return 'https://api.soundcloud.com/tracks/'+ track +'/stream?client_id='+ App.Config.SoundCloudClientId; } static PickTrack(t:SoundCloudAudioType,n:number) { switch (t) { case SoundCloudAudioType.Soundcloud: var defaults = App.Config.SoundCloudDefaultTracks; break; case SoundCloudAudioType.Granular: var defaults = App.Config.GranularDefaultTracks; break; case SoundCloudAudioType.Convolution: var defaults = App.Config.ConvolverDefaultTracks; break; default: var defaults = App.Config.SoundCloudDefaultTracks; } var track = defaults[n]; return 'https://api.soundcloud.com/tracks/'+ track +'/stream?client_id='+ App.Config.SoundCloudClientId; } static LoadTrack(track: any) { // ERROR CHECK // /*SC.get('/tracks/'+track.id, function(track, error) { if (error) { App.Message("Something went wrong, try another track.") } }); */ var trackUrl = track.URI; //TODO: loading track's in safari throw errors return ''+ trackUrl +'/stream?client_id='+ App.Config.SoundCloudClientId; } //------------------------------------------------------------------------------------------- // APP DATA //------------------------------------------------------------------------------------------- static Monitor() { if (window.SC) { SC.get('/apps', { }).then((app) => { console.log(app); }); } } //------------------------------------------------------------------------------------------- // SINGLE SEARCH //------------------------------------------------------------------------------------------- /** * * @param query String to search for * @param callback This passes as its only parameter an array of track objects * * */ /** * Search the Soundcloud API for any tracks containing a string. * @param query - String to search for * @param seconds - Song duration limit * @param successResponse - Successful response callback * @param failedResponse - Unsuccessful response callback */ static Search(query: string, seconds: number, successResponse: (track: SoundCloudAPIResponse.Success) => any, failedResponse: (error: SoundCloudAPIResponse.Error) => any){ if (window.SC) { SC.get('/tracks', { q: query, duration: { to: seconds * 1000 }, limit: 200, offset: 0 }).then((tracks:SoundCloudAPIResponse.Success[]) => { // Successful search if (tracks) { let tracksRemainAfterElimination: boolean = false; tracks.forEach((track) => { // Check track is streamable and public if (track.streamable && track.sharing === "public" && ( // Check track is not set to all rights reserved or has a blokdust tag track.license.indexOf('all-rights-reserved') === -1 || track.tag_list.toLowerCase().indexOf('blokdust') !== -1) ) { tracksRemainAfterElimination = true; successResponse(track); } }); // Tracks were found but failed the filtering process if (!tracksRemainAfterElimination) { const err = { "status": 452, // Blokdust specific code for unqualified tracks (ie. no blokdust tag OR cc license) "message": App.L10n.Errors.SoundCloud.FailedTrackFiltering }; this.SearchError(err); failedResponse(err); } } }, (error:SoundCloudAPIResponse.Error) => { this.SearchError(error); failedResponse(error); }); } else { // No window.SC App.Message(App.L10n.Errors.SoundCloud.Uninitialized); console.error(App.L10n.Errors.SoundCloud.Uninitialized); } } //------------------------------------------------------------------------------------------- // MULTI SEARCH //------------------------------------------------------------------------------------------- // PERFORMS MULTIPLE QUERIES AND COMBINES RESULTS // static MultiSearch(query: string, seconds: number, block: any) { if (window.SC) { this._QueryReturns = 0; this.QueryList = []; // SEARCH 1 // this.OptionSearch(query, seconds, {license:"cc-by"},(tracks) => { this.MultiCallback(block, tracks,"cc-by"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); }); // SEARCH 2 // /*this.OptionSearch(query, seconds, {license:"cc-by-nc-nd"},(tracks) => { this.MultiCallback(block, tracks,"cc-by-nc-nd"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); });*/ // SEARCH 3 // this.OptionSearch(query, seconds, {license:"cc-by-nc-sa"},(tracks) => { this.MultiCallback(block, tracks,"cc-by-nc-sa"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); }); // SEARCH 4 // this.OptionSearch(query, seconds, {license:"to_use_commercially"},(tracks) => { this.MultiCallback(block, tracks,"to_use_commercially"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); }); // SEARCH 5 // this.OptionSearch(query, seconds, {license:"to_share"},(tracks) => { this.MultiCallback(block, tracks,"to_share"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); }); // SEARCH 6 // this.OptionSearch(query, seconds, {tag:"blokdust"},(tracks) => { this.MultiCallback(block, tracks,"blokdust"); }, (error: SoundCloudAPIResponse.Error) => { this.MultiCallback(block, [],"error"); }); } else { // No window.SC App.Message(App.L10n.Errors.SoundCloud.Uninitialized); console.error(App.L10n.Errors.SoundCloud.Uninitialized); } } // A SEARCH QUERY WITH SUBMITTABLE LICENSE OR TAG // static OptionSearch(query: string, seconds: number, options: any, successResponse: (tracks) => any, failedResponse: (error: SoundCloudAPIResponse.Error) => any) { // ASSEMBLE THE QUERY // options = options || {}; var searchOptions = {}; if (options.license) { searchOptions = { q: query, license: options.license, duration: {to: seconds * 1000}, limit: 200 }; } else if (options.tag) { searchOptions = { q: query, tags: options.tag, duration: {to: seconds * 1000}, limit: 200 }; } else { searchOptions = { q: query, duration: {to: seconds * 1000}, limit: 200 }; } // DO THE QUERY // SC.get('/tracks', searchOptions).then((tracks:SoundCloudAPIResponse.Success[]) => { if (tracks) { var trackList = []; tracks.forEach((track) => { if (track.streamable && track.sharing === "public") { trackList.push(track); } }); successResponse(trackList); } }, (error:SoundCloudAPIResponse.Error) => { this.SearchError(error); failedResponse(error); }); } // GETS CALLED AFTER EACH QUERY AND ADDS TOGETHER RESULTS // static MultiCallback(block,results,string) { //console.log(""+string+": "+results.length); var i; var maxResults = 200; // IF WE HAVE RESULTS // if (results.length) { var count = 0; // IF FIRST RESULTS JUST ADD THEM ALL // if (this.QueryList.length===0) { for (i=0; i<results.length; i++) { this.QueryList.push(results[i]); } } // ELSE CHECK FOR DUPLICATES // else { for (i=0; i<results.length; i++) { if (!this.Exists(this.QueryList,results[i].id) ) { // IF IT DOESN'T EXIST, PUSH IT // if (this.QueryList.length<maxResults) { this.QueryList.push(results[i]); } } } } } this._QueryReturns += 1; if (this._QueryReturns===this.QueryTotal) { // ALL QUERIES ARE IN - CONTINUE // block.SetSearchResults(this.QueryList); } } // CHECK IF THIS IS A DUPLICATE TRACK // static Exists(list,id) { var len = list.length; for (var h=0; h<len; h++) { if (id===list[h].id) { return true; } } return false; } //------------------------------------------------------------------------------------------- // ERRORS //------------------------------------------------------------------------------------------- static SearchError(error) { switch (error.status) { case 429: //Too many requests App.Message(App.L10n.Errors.SoundCloud.TooManyRequests); break; case 452: //results filtered out break; case 500: //Internal Server Error App.Message(App.L10n.Errors.SoundCloud.InternalServerError); break; case 503: // Service Unavailable App.Message(App.L10n.Errors.SoundCloud.ServiceUnavailable); break; default: if (error.message) { App.Message(`SoundCloud error: ${error.message}`); } else { App.Message(`SoundCloud error, check console`); } } console.error(error); //NOTE: More info on SoundCloud errors: https://developers.soundcloud.com/docs/api/guide#errors } //------------------------------------------------------------------------------------------- // AUTH CONNECTION //------------------------------------------------------------------------------------------- static Connect() { // initiate auth popup SC.connect().then(() => { return SC.get('/me'); }).then((me: SoundCloudAPIResponse.SoundCloudUser) => { alert('Hello, ' + me.username); }, (error: SoundCloudAPIResponse.Error) => { App.Message(`SoundCloud couldn't connect: ${error.message}`); console.log(error.message, error.status); }); } static Upload(blob: Blob, title: string) { // When you have recorded a song with the SDK or any Web Audio application, // you can upload it if it's in a format that is accepted SC.upload({ file: blob, title: title, tag_list: 'blokdust', license: 'cc-by-nc', sharing: 'public', progress: (e: ProgressEvent) => { const percentCompleted = (e.loaded / e.total) * 100; console.log(`${percentCompleted}% completed`); } }).then((track: SoundCloudAPIResponse.Success) => { alert('Upload is done! Check your sound at ' + track.permalink_url); }, (error:SoundCloudAPIResponse.Error) => { console.error(error); }); } }
the_stack
// Copyright 2013 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. interface NodeData { id:number; nodeType?:number; name?:string; publicId?:string; systemId?:string; textContent?:string; tagName?:string; attributes?:StringMap<string>; childNodes?:NodeData[]; } interface PositionData extends NodeData { previousSibling:NodeData; parentNode:NodeData; } interface AttributeData extends NodeData { attributes:StringMap<string>; } interface TextData extends NodeData{ textContent:string; } class TreeMirror { private idMap:NumberMap<Node>; constructor(public root:Node, public delegate?:any) { this.idMap = {}; } initialize(rootId:number, children:NodeData[]) { this.idMap[rootId] = this.root; for (var i = 0; i < children.length; i++) this.deserializeNode(children[i], <Element>this.root); } applyChanged(removed:NodeData[], addedOrMoved:PositionData[], attributes:AttributeData[], text:TextData[]) { // NOTE: Applying the changes can result in an attempting to add a child // to a parent which is presently an ancestor of the parent. This can occur // based on random ordering of moves. The way we handle this is to first // remove all changed nodes from their parents, then apply. addedOrMoved.forEach((data:PositionData) => { var node = this.deserializeNode(data); var parent = this.deserializeNode(data.parentNode); var previous = this.deserializeNode(data.previousSibling); if (node.parentNode) node.parentNode.removeChild(node); }); removed.forEach((data:NodeData) => { var node = this.deserializeNode(data); if (node.parentNode) node.parentNode.removeChild(node); }); addedOrMoved.forEach((data:PositionData) => { var node = this.deserializeNode(data); var parent = this.deserializeNode(data.parentNode); var previous = this.deserializeNode(data.previousSibling); parent.insertBefore(node, previous ? previous.nextSibling : parent.firstChild); }); attributes.forEach((data:AttributeData) => { var node = <Element> this.deserializeNode(data); Object.keys(data.attributes).forEach((attrName) => { var newVal = data.attributes[attrName]; if (newVal === null) { node.removeAttribute(attrName); } else { if (!this.delegate || !this.delegate.setAttribute || !this.delegate.setAttribute(node, attrName, newVal)) { node.setAttribute(attrName, newVal); } } }); }); text.forEach((data:TextData) => { var node = this.deserializeNode(data); node.textContent = data.textContent; }); removed.forEach((node:NodeData) => { delete this.idMap[node.id]; }); } private deserializeNode(nodeData:NodeData, parent?:Element):Node { if (nodeData === null) return null; var node:Node = this.idMap[nodeData.id]; if (node) return node; var doc = this.root.ownerDocument; if (doc === null) doc = <HTMLDocument>this.root; switch(nodeData.nodeType) { case Node.COMMENT_NODE: node = doc.createComment(nodeData.textContent); break; case Node.TEXT_NODE: node = doc.createTextNode(nodeData.textContent); break; case Node.DOCUMENT_TYPE_NODE: node = doc.implementation.createDocumentType(nodeData.name, nodeData.publicId, nodeData.systemId); break; case Node.ELEMENT_NODE: if (this.delegate && this.delegate.createElement) node = this.delegate.createElement(nodeData.tagName); if (!node) node = doc.createElement(nodeData.tagName); Object.keys(nodeData.attributes).forEach((name) => { if (!this.delegate || !this.delegate.setAttribute || !this.delegate.setAttribute(node, name, nodeData.attributes[name])) { (<Element>node).setAttribute(name, nodeData.attributes[name]); } }); break; } if (!node) throw "ouch"; this.idMap[nodeData.id] = node; if (parent) parent.appendChild(node); if (nodeData.childNodes) { for (var i = 0; i < nodeData.childNodes.length; i++) this.deserializeNode(nodeData.childNodes[i], <Element>node); } return node; } } class TreeMirrorClient { private nextId:number; private mutationSummary:MutationSummary; private knownNodes:NodeMap<number>; constructor(public target:Node, public mirror:any, testingQueries:Query[]) { this.nextId = 1; this.knownNodes = new MutationSummary.NodeMap<number>(); var rootId = this.serializeNode(target).id; var children:NodeData[] = []; for (var child = target.firstChild; child; child = child.nextSibling) children.push(this.serializeNode(child, true)); this.mirror.initialize(rootId, children); var self = this; var queries = [{ all: true }]; if (testingQueries) queries = queries.concat(testingQueries); this.mutationSummary = new MutationSummary({ rootNode: target, callback: (summaries:Summary[]) => { this.applyChanged(summaries); }, queries: queries }); } disconnect() { if (this.mutationSummary) { this.mutationSummary.disconnect(); this.mutationSummary = undefined; } } private rememberNode(node:Node):number { var id = this.nextId++; this.knownNodes.set(node, id); return id; } private forgetNode(node:Node) { this.knownNodes.delete(node); } private serializeNode(node:Node, recursive?:boolean):NodeData { if (node === null) return null; var id = this.knownNodes.get(node); if (id !== undefined) { return { id: id }; } var data:NodeData = { nodeType: node.nodeType, id: this.rememberNode(node) }; switch(data.nodeType) { case Node.DOCUMENT_TYPE_NODE: var docType = <DocumentType>node; data.name = docType.name; data.publicId = docType.publicId; data.systemId = docType.systemId; break; case Node.COMMENT_NODE: case Node.TEXT_NODE: data.textContent = node.textContent; break; case Node.ELEMENT_NODE: var elm = <Element>node; data.tagName = elm.tagName; data.attributes = {}; for (var i = 0; i < elm.attributes.length; i++) { var attr = elm.attributes[i]; data.attributes[attr.name] = attr.value; } if (recursive && elm.childNodes.length) { data.childNodes = []; for (var child = elm.firstChild; child; child = child.nextSibling) data.childNodes.push(this.serializeNode(child, true)); } break; } return data; } private serializeAddedAndMoved(added:Node[], reparented:Node[], reordered:Node[]):PositionData[] { var all = added.concat(reparented).concat(reordered); var parentMap = new MutationSummary.NodeMap<NodeMap<boolean>>(); all.forEach((node) => { var parent = node.parentNode; var children = parentMap.get(parent) if (!children) { children = new MutationSummary.NodeMap<boolean>(); parentMap.set(parent, children); } children.set(node, true); }); var moved:PositionData[] = []; parentMap.keys().forEach((parent) => { var children = parentMap.get(parent); var keys = children.keys(); while (keys.length) { var node = keys[0]; while (node.previousSibling && children.has(node.previousSibling)) node = node.previousSibling; while (node && children.has(node)) { var data = <PositionData>this.serializeNode(node); data.previousSibling = this.serializeNode(node.previousSibling); data.parentNode = this.serializeNode(node.parentNode); moved.push(<PositionData>data); children.delete(node); node = node.nextSibling; } var keys = children.keys(); } }); return moved; } private serializeAttributeChanges(attributeChanged:StringMap<Element[]>):AttributeData[] { var map = new MutationSummary.NodeMap<AttributeData>(); Object.keys(attributeChanged).forEach((attrName) => { attributeChanged[attrName].forEach((element) => { var record = map.get(element); if (!record) { record = <AttributeData>this.serializeNode(element); record.attributes = {}; map.set(element, record); } record.attributes[attrName] = element.getAttribute(attrName); }); }); return map.keys().map((node:Node) => { return map.get(node); }); } applyChanged(summaries:Summary[]) { var summary:Summary = summaries[0] var removed:NodeData[] = summary.removed.map((node:Node) => { return this.serializeNode(node); }); var moved:PositionData[] = this.serializeAddedAndMoved(summary.added, summary.reparented, summary.reordered); var attributes:AttributeData[] = this.serializeAttributeChanges(summary.attributeChanged); var text:TextData[] = summary.characterDataChanged.map((node:Node) => { var data = this.serializeNode(node); data.textContent = node.textContent; return <TextData>data; }); this.mirror.applyChanged(removed, moved, attributes, text); summary.removed.forEach((node:Node) => { this.forgetNode(node); }); } }
the_stack
import {createEvent, createStore, Event, guard, split} from 'effector' const typecheck = '{global}' it('infer type by given predicate (should pass)', () => { const event: Event<number | string> = createEvent() const {onlyNumbers} = split(event, { onlyNumbers: (value): value is number => typeof value === 'number', }) const shouldBeOk: Event<number> = onlyNumbers expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case stores / case functions (should pass)', () => { const source: Event<number | string> = createEvent() const firstBool = createStore(true) const firstTarget: Event<number | string> = createEvent() const secondTarget: Event<number | string> = createEvent() const defaultarget: Event<number | string> = createEvent() split({ source, match: { a: firstBool, b: e => true, }, cases: { a: firstTarget, b: secondTarget, __: defaultarget, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('matcher store (should pass)', () => { const source: Event<number> = createEvent() const caseStore = createStore<'a' | 'b'>('a') const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() split({ source, match: caseStore, cases: { a: firstTarget, b: secondTarget, __: defaultarget, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('matcher store case mismatch (should fail)', () => { const source: Event<number> = createEvent() const caseStore = createStore<'a' | 'c'>('a') const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() //@ts-expect-error split({ source, match: caseStore, cases: { a: firstTarget, b: secondTarget, __: defaultarget, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<number>; match: { [name: string]: Store<boolean> | ((payload: number) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"c\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: number) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"c\\">'. Overload 2 of 4, '(config: { source: Unit<number>; match: (p: number) => \\"a\\" | \\"b\\" | \\"__\\"; cases: Partial<{ a: Event<number>; b: Event<number>; __: Event<number>; } & { __: Event<number>; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"c\\">' is not assignable to type '(p: number) => \\"a\\" | \\"b\\" | \\"__\\"'. Type 'Store<\\"a\\" | \\"c\\">' provides no match for the signature '(p: number): \\"a\\" | \\"b\\" | \\"__\\"'. Overload 3 of 4, '(config: { source: Unit<number>; match: Unit<\\"a\\" | \\"c\\">; cases: Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>; }): void', gave the following error. Type '{ a: Event<number>; b: Event<number>; __: Event<number>; }' is not assignable to type 'Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>'. " `) }) test('matcher function (should pass)', () => { const source: Event<number> = createEvent() const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() split({ source, match: x => (x > 0 ? 'a' : 'b'), cases: { a: firstTarget, b: secondTarget, __: defaultarget, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('matcher function case mismatch (should fail)', () => { const source: Event<number> = createEvent() const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() //@ts-expect-error split({ source, match: x => (x > 0 ? 'a' : 'c'), cases: { a: firstTarget, b: secondTarget, __: defaultarget, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<number>; match: { [name: string]: Store<boolean> | ((payload: number) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(x: number) => \\"a\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: number) => boolean); }'. Index signature for type 'string' is missing in type '(x: number) => \\"a\\" | \\"c\\"'. Overload 2 of 4, '(config: { source: Unit<number>; match: (p: number) => \\"a\\" | \\"c\\"; cases: Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>; }): void', gave the following error. Type '{ a: Event<number>; b: Event<number>; __: Event<number>; }' is not assignable to type 'Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Event<number>; c: Event<number>; } & { __: Event<number>; }>'. Overload 3 of 4, '(config: { source: Unit<number>; match: Unit<\\"a\\" | \\"b\\" | \\"__\\">; cases: Partial<{ a: Event<number>; b: Event<number>; __: Event<number>; } & { __: Event<number>; }>; }): void', gave the following error. Type '(x: number) => \\"a\\" | \\"c\\"' is missing the following properties from type 'Unit<\\"a\\" | \\"b\\" | \\"__\\">': kind, __ " `) }) test('event with unknown payload in target (should pass)', () => { const source = createEvent<string>() const target = createEvent<unknown>() split({ source, match: { test: value => value === 'ok', }, cases: { test: target, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('edge case with target (should pass)', () => { const intervalStore = createStore(Date.now()) const filter = createStore(true) const enumType = 3 const typeStore = createStore(enumType) const source = guard({source: intervalStore, filter}) const caseA = createEvent() const caseB = createEvent() split({source, match: typeStore, cases: {[enumType]: caseA, __: caseB}}) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) describe('array cases', () => { describe('case store', () => { /** type: source == cases, arrays only */ test('case name: match == cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source == cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\">'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; }>; match: (p: { foo: 1; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type 'Store<\\"a\\">' is not assignable to type '(p: { foo: 1; }) => \\"a\\" | \\"b\\"'. Type 'Store<\\"a\\">' provides no match for the signature '(p: { foo: 1; }): \\"a\\" | \\"b\\"'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. " `) }) /** type: source == cases, array case + unit case */ test('case name: match == cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) test('case name: match > cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b' | 'c'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\" | \\"c\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) test('case name: match < cases, type: source == cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) /** type: source > cases, arrays only */ test('case name: match == cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source > cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { ...; }>; }): void', gave the following error. Type 'Store<\\"a\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\">'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: (p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type 'Store<\\"a\\">' is not assignable to type '(p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"'. Type 'Store<\\"a\\">' provides no match for the signature '(p: { foo: 1; bar: number; }): \\"a\\" | \\"b\\"'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. " `) }) /** type: source > cases, array case + unit case */ test('case name: match == cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) test('case name: match > cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a' | 'b' | 'c'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\" | \\"b\\" | \\"c\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) test('case name: match < cases, type: source > cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is not assignable to type 'Event<{ foo: 1; }>'. " `) }) /** type: source < cases, arrays only */ test('case name: match == cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) test('case name: match > cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1; bar: number}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [\\"incompatible unit in target\\"]; b: [\\"incompatible unit in target\\"]; } & { __: [\\"incompatible unit in target\\"]; }>; }): void', gave the following error. Type 'Event<{ foo: 1; bar: number; }>' is not assignable to type '\\"incompatible unit in target\\"'. " `) }) test('case name: match < cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a'>('a') const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\">; cases: Partial<{ a: [\\"incompatible unit in target\\"]; } & { __: [\\"incompatible unit in target\\"]; }>; }): void', gave the following error. Type 'Event<{ foo: 1; bar: number; }>' is not assignable to type '\\"incompatible unit in target\\"'. " `) }) /** type: source < cases, array case + unit case */ test('case name: match == cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) test('case name: match > cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b' | 'c'>('a') const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\" | \\"c\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\" | \\"c\\">'. " `) }) test('case name: match < cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() const c = createEvent<{foo: 1}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) /** type: source != cases, arrays only */ test('case name: match == cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) test('case name: match > cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 2}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [\\"incompatible unit in target\\"]; b: [\\"incompatible unit in target\\"]; } & { __: [\\"incompatible unit in target\\"]; }>; }): void', gave the following error. Type 'Event<{ foo: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'. " `) }) test('case name: match < cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a'>('a') const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: $case, cases: { //@ts-expect-error a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\">; cases: Partial<{ a: [\\"incompatible unit in target\\"]; } & { __: [\\"incompatible unit in target\\"]; }>; }): void', gave the following error. Type 'Event<{ foo: 2; }>' is not assignable to type '\\"incompatible unit in target\\"'. " `) }) /** type: source != cases, array case + unit case */ test('case name: match == cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) test('case name: match > cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b' | 'c'>('a') const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\" | \\"c\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\" | \\"c\\">'. " `) }) test('case name: match < cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const $case = createStore<'a' | 'b'>('a') const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() const c = createEvent<{foo: 2}>() split({ source, //@ts-expect-error match: $case, cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"b\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type 'Store<\\"a\\" | \\"b\\">'. " `) }) }) describe('case function', () => { /** type: source == cases, arrays only */ test('case name: match == cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source == cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: { foo: 1; }) => \\"a\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: { foo: 1; }) => \\"a\\"'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; }>; match: (p: { foo: 1; }) => \\"a\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '(src: { foo: 1; }) => \\"a\\"' is missing the following properties from type 'Unit<\\"a\\" | \\"b\\">': kind, __ " `) }) /** type: source == cases, array case + unit case */ test('case name: match == cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " Parameter 'src' implicitly has an 'any' type. No overload matches this call. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; }>; match: (p: { foo: 1; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is missing the following properties from type 'Event<{ foo: 1; }>': watch, filterMap, prepend, subscribe, and 7 more. " `) }) test('case name: match > cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' | 'c' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source == cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " Parameter 'src' implicitly has an 'any' type. No overload matches this call. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; }>; match: (p: { foo: 1; }) => \\"a\\" | \\"b\\" | \\"c\\"; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is missing the following properties from type 'Event<{ foo: 1; }>': watch, filterMap, prepend, subscribe, and 7 more. " `) }) /** type: source > cases, arrays only */ test('case name: match == cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source > cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { ...; }>; }): void', gave the following error. Type '(src: { foo: 1; bar: number; }) => \\"a\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: { foo: 1; bar: number; }) => \\"a\\"'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: (p: { foo: 1; bar: number; }) => \\"a\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '(src: { foo: 1; bar: number; }) => \\"a\\"' is missing the following properties from type 'Unit<\\"a\\" | \\"b\\">': kind, __ " `) }) /** type: source > cases, array case + unit case */ test('case name: match == cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " Parameter 'src' implicitly has an 'any' type. No overload matches this call. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: (p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; } & { __: Event<{ foo: 1; }>; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is missing the following properties from type 'Event<{ foo: 1; }>': watch, filterMap, prepend, subscribe, and 7 more. " `) }) test('case name: match > cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' | 'c' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { ...; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; bar: number; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source > cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " Parameter 'src' implicitly has an 'any' type. No overload matches this call. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: (p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\" | \\"c\\"; cases: Partial<{ a: Event<{ foo: 1; }>; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; } & { ...; }>; }): void', gave the following error. Type 'Event<{ foo: 1; }>[]' is missing the following properties from type 'Event<{ foo: 1; }>': watch, filterMap, prepend, subscribe, and 7 more. " `) }) /** type: source < cases, arrays only */ test('case name: match == cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ //@ts-expect-error source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match > cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ //@ts-expect-error source, match: (src): 'a' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) /** type: source < cases, array case + unit case */ test('case name: match == cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ //@ts-expect-error source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match > cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: (src): 'a' | 'b' | 'c' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() const c = createEvent<{foo: 1}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) /** type: source != cases, arrays only */ test('case name: match == cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ //@ts-expect-error source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match > cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() split({ source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ //@ts-expect-error source, match: (src): 'a' => 'a', cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) /** type: source != cases, array case + unit case */ test('case name: match == cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ //@ts-expect-error source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match > cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: (src): 'a' | 'b' | 'c' => 'a', cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\" | \\"c\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) test('case name: match < cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() const c = createEvent<{foo: 2}>() split({ //@ts-expect-error source, match: (src): 'a' | 'b' => 'a', cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: any) => \\"a\\" | \\"b\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: { foo: 1; }) => boolean); }'. Index signature for type 'string' is missing in type '(src: any) => \\"a\\" | \\"b\\"'. Parameter 'src' implicitly has an 'any' type. " `) }) }) describe('matcher function', () => { /** type: source == cases, arrays only */ test('case name: match == cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source == cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source == cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: { a: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Target; } & { __: Target; }>'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; }>; match: (p: { foo: 1; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: (src: { foo: 1; }) => true; }' is not assignable to type '(p: { foo: 1; }) => \\"a\\" | \\"b\\"'. Object literal may only specify known properties, and 'a' does not exist in type '(p: { foo: 1; }) => \\"a\\" | \\"b\\"'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: (src: { foo: 1; }) => true; }' is not assignable to type 'Unit<\\"a\\" | \\"b\\">'. Object literal may only specify known properties, and 'a' does not exist in type 'Unit<\\"a\\" | \\"b\\">'. " `) }) /** type: source == cases, array case + unit case */ test('case name: match == cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source == cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, c: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source == cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; b: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; b: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; }' is not assignable to type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'c' does not exist in type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. " `) }) /** type: source > cases, arrays only */ test('case name: match == cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source > cases, arrays only (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source > cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: { a: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: { a: (src: { foo: 1; bar: number; }) => true; }; cases: Partial<{ a: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>[]; }' is not assignable to type 'Partial<{ a: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Target; } & { __: Target; }>'. Overload 2 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: (p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: (src: { foo: 1; bar: number; }) => true; }' is not assignable to type '(p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"'. Object literal may only specify known properties, and 'a' does not exist in type '(p: { foo: 1; bar: number; }) => \\"a\\" | \\"b\\"'. Overload 3 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: Unit<\\"a\\" | \\"b\\">; cases: Partial<{ a: [Event<{ foo: 1; }>]; b: [Event<{ foo: 1; }>]; } & { __: [Event<{ foo: 1; }>]; }>; }): void', gave the following error. Type '{ a: (src: { foo: 1; bar: number; }) => true; }' is not assignable to type 'Unit<\\"a\\" | \\"b\\">'. Object literal may only specify known properties, and 'a' does not exist in type 'Unit<\\"a\\" | \\"b\\">'. " `) }) /** type: source > cases, array case + unit case */ test('case name: match == cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source > cases, array case + unit case (should pass)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() split({ source, match: { a: src => true, b: src => true, c: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source > cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1; bar: number}>() const a = createEvent<{foo: 1}>() const b = createEvent<{foo: 1}>() const c = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; bar: number; }>; match: { a: (src: { foo: 1; bar: number; }) => true; b: (src: { foo: 1; bar: number; }) => true; }; cases: Partial<{ a: Target; b: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; }>]; b: Event<{ foo: 1; }>; c: Event<{ foo: 1; }>; }' is not assignable to type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'c' does not exist in type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. " `) }) /** type: source < cases, arrays only */ test('case name: match == cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source < cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: { a: src => true, }, cases: { a: [a], //@ts-expect-error b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; bar: number; }>]; b: Event<{ foo: 1; bar: string; }>[]; }' is not assignable to type 'Partial<{ a: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Target; } & { __: Target; }>'. " `) }) /** type: source < cases, array case + unit case */ test('case name: match == cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() split({ source, match: { a: src => true, b: src => true, c: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source < cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 1; bar: number}>() const b = createEvent<{foo: 1; bar: string}>() const c = createEvent<{foo: 1}>() //@ts-expect-error split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; b: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; b: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 1; bar: number; }>]; b: Event<{ foo: 1; bar: string; }>; c: Event<{ foo: 1; }>; }' is not assignable to type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'c' does not exist in type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. " `) }) /** type: source != cases, arrays only */ test('case name: match == cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source != cases, arrays only (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: { a: src => true, }, cases: { a: [a], //@ts-expect-error b: [b], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 2; }>]; b: Event<{ foo: 2; }>[]; }' is not assignable to type 'Partial<{ a: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Target; } & { __: Target; }>'. " `) }) /** type: source != cases, array case + unit case */ test('case name: match == cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match > cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() split({ source, match: { a: src => true, b: src => true, c: src => true, }, cases: { a: [a], b, }, }) expect(typecheck).toMatchInlineSnapshot(` " no errors " `) }) test('case name: match < cases, type: source != cases, array case + unit case (should fail)', () => { const source = createEvent<{foo: 1}>() const a = createEvent<{foo: 2}>() const b = createEvent<{foo: 2}>() const c = createEvent<{foo: 2}>() split({ source, match: { a: src => true, b: src => true, }, cases: { a: [a], b, //@ts-expect-error c, }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<{ foo: 1; }>; match: { a: (src: { foo: 1; }) => true; b: (src: { foo: 1; }) => true; }; cases: Partial<{ a: Target; b: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<{ foo: 2; }>]; b: Event<{ foo: 2; }>; c: Event<{ foo: 2; }>; }' is not assignable to type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'c' does not exist in type 'Partial<{ a: Target; b: Target; } & { __: Target; }>'. " `) }) }) test('case store case mismatch (should fail)', () => { const source: Event<number> = createEvent() const caseStore = createStore<'a' | 'c'>('a') const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() //@ts-expect-error split({ source, match: caseStore, cases: { a: [firstTarget], b: [secondTarget], __: [defaultarget], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<number>; match: { [name: string]: Store<boolean> | ((payload: number) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"c\\">' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: number) => boolean); }'. Overload 2 of 4, '(config: { source: Unit<number>; match: (p: number) => \\"a\\" | \\"b\\" | \\"__\\"; cases: Partial<{ a: [Event<number>]; b: [Event<number>]; __: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type 'Store<\\"a\\" | \\"c\\">' is not assignable to type '(p: number) => \\"a\\" | \\"b\\" | \\"__\\"'. Overload 3 of 4, '(config: { source: Unit<number>; match: Unit<\\"a\\" | \\"c\\">; cases: Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type '{ a: [Event<number>]; b: Event<number>[]; __: [Event<number>]; }' is not assignable to type 'Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>'. " `) }) test('case function case mismatch (should fail)', () => { const source: Event<number> = createEvent() const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() //@ts-expect-error split({ source, match: (src): 'a' | 'c' => 'a', cases: { a: [firstTarget], b: [secondTarget], __: [defaultarget], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<number>; match: { [name: string]: Store<boolean> | ((payload: number) => boolean); }; cases: Partial<{ [x: string]: Target; } & { __: Target; }>; }): void', gave the following error. Type '(src: number) => \\"a\\" | \\"c\\"' is not assignable to type '{ [name: string]: Store<boolean> | ((payload: number) => boolean); }'. Index signature for type 'string' is missing in type '(src: number) => \\"a\\" | \\"c\\"'. Overload 2 of 4, '(config: { source: Unit<number>; match: (p: number) => \\"a\\" | \\"c\\"; cases: Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type '{ a: [Event<number>]; b: Event<number>[]; __: [Event<number>]; }' is not assignable to type 'Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: [Event<number>]; c: [Event<number>]; } & { __: [Event<number>]; }>'. Overload 3 of 4, '(config: { source: Unit<number>; match: Unit<\\"a\\" | \\"b\\" | \\"__\\">; cases: Partial<{ a: [Event<number>]; b: [Event<number>]; __: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type '(src: number) => \\"a\\" | \\"c\\"' is missing the following properties from type 'Unit<\\"a\\" | \\"b\\" | \\"__\\">': kind, __ " `) }) test('matcher function case mismatch (should fail)', () => { const source: Event<number> = createEvent() const firstTarget: Event<number> = createEvent() const secondTarget: Event<number> = createEvent() const defaultarget: Event<number> = createEvent() //@ts-expect-error split({ source, match: { a: src => true, c: src => true, }, cases: { a: [firstTarget], b: [secondTarget], __: [defaultarget], }, }) expect(typecheck).toMatchInlineSnapshot(` " No overload matches this call. Overload 1 of 4, '(config: { source: Unit<number>; match: { a: (src: number) => true; c: (src: number) => true; }; cases: Partial<{ a: Target; c: Target; } & { __: Target; }>; }): void', gave the following error. Type '{ a: [Event<number>]; b: Event<number>[]; __: [Event<number>]; }' is not assignable to type 'Partial<{ a: Target; c: Target; } & { __: Target; }>'. Object literal may only specify known properties, and 'b' does not exist in type 'Partial<{ a: Target; c: Target; } & { __: Target; }>'. Overload 2 of 4, '(config: { source: Unit<number>; match: (p: number) => \\"a\\" | \\"b\\" | \\"__\\"; cases: Partial<{ a: [Event<number>]; b: [Event<number>]; __: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type '{ a: (src: number) => true; c: (src: number) => true; }' is not assignable to type '(p: number) => \\"a\\" | \\"b\\" | \\"__\\"'. Object literal may only specify known properties, and 'a' does not exist in type '(p: number) => \\"a\\" | \\"b\\" | \\"__\\"'. Overload 3 of 4, '(config: { source: Unit<number>; match: Unit<\\"a\\" | \\"b\\" | \\"__\\">; cases: Partial<{ a: [Event<number>]; b: [Event<number>]; __: [Event<number>]; } & { __: [Event<number>]; }>; }): void', gave the following error. Type '{ a: (src: number) => true; c: (src: number) => true; }' is not assignable to type 'Unit<\\"a\\" | \\"b\\" | \\"__\\">'. Object literal may only specify known properties, and 'a' does not exist in type 'Unit<\\"a\\" | \\"b\\" | \\"__\\">'. " `) }) })
the_stack
import React, { useRef, useState } from 'react' import PhotoSwipe from 'photoswipe' import PhotoswipeUIDefault from 'photoswipe/dist/photoswipe-ui-default' import { mount, shallow } from 'enzyme' import toJson from 'enzyme-to-json' import { NoRefError } from '../no-ref-error' import { shuffle } from '../helpers' import { InternalItem } from '../types' import { Gallery, CustomGallery, GalleryProps, Item, DefaultLayout, LayoutProps, useGallery, } from '..' const PhotoSwipeMocked = PhotoSwipe as jest.MockedClass<typeof PhotoSwipe> const applyZoomPan = jest.fn() jest.mock('photoswipe', () => { return jest.fn().mockImplementation(() => { return { init: () => {}, applyZoomPan } }) }) beforeEach(() => { PhotoSwipeMocked.mockClear() applyZoomPan.mockClear() }) const photoswipeArgsMock = ( items: InternalItem[] | null, index: number, galleryUID?: string, ): [any, any, any, any] => [ expect.anything(), expect.anything(), items === null ? expect.anything() : items.map(({ original, thumbnail, width, height, title, id }) => ({ src: original, msrc: thumbnail, w: width, h: height, title, el: expect.anything(), pid: id, })), { getThumbBoundsFn: expect.anything(), history: false, ...(galleryUID !== undefined ? { history: true, galleryUID } : {}), index, }, ] const createItem = (index: number): InternalItem => ({ original: `https://placekitten.com/1024/768?image=${index}`, thumbnail: `https://placekitten.com/160/120?image=${index}`, width: 1024, height: 768, title: `kitty #${index}`, }) const createItems = (length: number): InternalItem[] => Array.from({ length }, (_, i) => createItem(i)) const TestGallery: React.FC<{ items: InternalItem[] } & GalleryProps> = ({ items, ...rest }) => ( <Gallery {...rest}> {items.map(({ original, thumbnail, width, height, title, id }) => ( <Item key={original} original={original} thumbnail={thumbnail} width={width} height={height} title={title} id={id} > {({ ref, open }) => ( <img onClick={open} src={thumbnail} ref={ref as React.MutableRefObject<HTMLImageElement>} /> )} </Item> ))} </Gallery> ) const ItemsWithHooks: React.FC<{ items: InternalItem[]; index: number }> = ({ items, index, }) => { const { open } = useGallery() return ( <> {items.map(({ original, thumbnail, width, height, title, id }) => ( <Item key={original} original={original} thumbnail={thumbnail} width={width} height={height} title={title} id={id} > {({ ref }) => ( <img src={thumbnail} ref={ref as React.MutableRefObject<HTMLImageElement>} /> )} </Item> ))} <button type="button" onClick={() => open(index)} id="show"> show </button> </> ) } const TestGalleryHooks: React.FC< { items: InternalItem[]; index: number } & GalleryProps > = ({ items, index, ...rest }) => { return ( <Gallery {...rest}> <ItemsWithHooks items={items} index={index} /> </Gallery> ) } const StatefulItem: React.FC<{ title: string }> = (props) => { // eslint-disable-next-line react/destructuring-assignment const [title, setTitle] = useState(props.title) return ( <Item original="https://placekitten.com/1024/768?image=1" thumbnail="https://placekitten.com/160/120?image=1" width={1024} height={768} title={title} > {({ ref, open }) => ( <> <img onClick={open} src="https://placekitten.com/160/120?image=1" ref={ref as React.MutableRefObject<HTMLImageElement>} /> <button type="button" onClick={() => setTitle('Really first')} /> </> )} </Item> ) } const TestGalleryWithStatefulItem: React.FC = () => { return ( <Gallery> <StatefulItem title="First" /> <Item original="https://placekitten.com/1024/768?image=2" thumbnail="https://placekitten.com/160/120?image=2" width={1024} height={768} title="Second" > {({ ref, open }) => ( <img onClick={open} src="https://placekitten.com/160/120?image=2" ref={ref as React.MutableRefObject<HTMLImageElement>} /> )} </Item> </Gallery> ) } const TestGalleryWithLayout: React.FC<{ items: InternalItem[] } & LayoutProps> = ({ items, ...rest }) => { const layoutRef = useRef() return ( <> <CustomGallery layoutRef={layoutRef} ui={PhotoswipeUIDefault}> {items.map(({ original, thumbnail, width, height, title }, i) => ( <Item key={original} original={original} thumbnail={thumbnail} width={width} height={height} title={title} > {({ ref, open }) => ( <img onClick={open} src={thumbnail} ref={ref as React.MutableRefObject<HTMLImageElement>} /> )} </Item> ))} </CustomGallery> <DefaultLayout ref={layoutRef} {...rest} /> </> ) } describe('gallery', () => { test('item click should init photoswipe', () => { const items = createItems(3) const wrapper = mount(<TestGallery items={items} />) wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 0), ) wrapper.find(Item).last().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 2), ) }) test('add one, then item click should init photoswipe', () => { const items = createItems(3) const wrapper = mount(<TestGallery items={items} />) const newItems = [createItem(items.length + 1), ...items] wrapper.setProps({ items: newItems }) wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(newItems, 0), ) wrapper.find(Item).last().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(newItems, 3), ) }) test('shuffle, then item click should init photoswipe', () => { const items = createItems(20) const wrapper = mount(<TestGallery items={items} />) const newItems = shuffle(items) wrapper.find(Item).at(5).simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 5), ) wrapper.setProps({ items: newItems }) wrapper.find(Item).at(10).simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(newItems, 10), ) wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(newItems, 0), ) wrapper.find(Item).last().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(newItems, 19), ) }) test('should render with external layout', () => { const items = createItems(1) const wrapper = shallow(<TestGalleryWithLayout items={items} />) expect(toJson(wrapper)).toMatchSnapshot() }) test('should preserve right order after re-rendering just one item', () => { const wrapper = mount(<TestGalleryWithStatefulItem />) wrapper.find(Item).first().find('button').simulate('click') wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(null, 0), ) }) test('should throw when there is no ref and more than one item', () => { /* eslint-disable no-console */ const consoleError = console.error console.error = jest.fn() const items = createItems(2) expect(() => { mount( <Gallery> {items.map((item) => ( <Item key={item.original} {...item}> {({ open }) => <img onClick={open} src={item.thumbnail} />} </Item> ))} </Gallery>, ) .find(Item) .first() .simulate('click') }).toThrow(new NoRefError()) console.error = consoleError /* eslint-enable no-console */ }) test('should not throw when there is no ref and only one item', () => { const item: InternalItem = { original: 'https://placekitten.com/1024/768', thumbnail: 'https://placekitten.com/160/120', width: 1024, height: 768, } const wrapper = mount( <Gallery> <Item {...item}> {({ open }) => <img onClick={open} src={item.thumbnail} />} </Item> </Gallery>, ) wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(null, 0), ) }) test('should init photoswipe when location.hash contains valid gid and pid', () => { const items = createItems(3) const galleryID = 'my-gallery' window.location.hash = `&gid=${galleryID}&pid=2` mount(<TestGallery id={galleryID} items={items} />) expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 1, galleryID), ) }) test('should only init photoswipe when location.hash contains gid and pid and items are provided', () => { const galleryID = 'my-gallery' window.location.hash = `&gid=${galleryID}&pid=2` const gallery = mount(<TestGallery id={galleryID} items={[]} />) expect(PhotoSwipeMocked).toHaveBeenCalledTimes(0) const items = createItems(3) gallery.setProps({ items, }) gallery.unmount() gallery.mount() expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 1, galleryID), ) }) test('should init photoswipe when location.hash contains valid gid and custom pid, passed via Item id prop', () => { const items = createItems(3).map((item, index) => ({ ...item, id: `picture-${index + 1}`, })) const galleryID = 'my-gallery' window.location.hash = `&gid=${galleryID}&pid=picture-3` const gallery = mount(<TestGallery id={galleryID} items={[]} />) expect(PhotoSwipeMocked).toBeCalledTimes(0) gallery.setProps({ items, }) expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 2, galleryID), ) }) test('should call exposed photoswipe instance method after open', () => { const items = createItems(1) const wrapper = mount( <TestGallery items={items} onOpen={(pswp) => pswp.applyZoomPan(0, 0, 0)} />, ) wrapper.find(Item).first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 0), ) expect(applyZoomPan).toHaveBeenCalled() }) test('useGallery hook - open method should init photoswipe item at chosen index', () => { const items = createItems(3) const wrapper = mount(<TestGalleryHooks index={3} items={items} />) wrapper.find('#show').first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 3), ) wrapper.setProps({ index: 2 }) wrapper.find('#show').first().simulate('click') expect(PhotoSwipeMocked).toHaveBeenCalledWith( ...photoswipeArgsMock(items, 2), ) }) })
the_stack
import MContent from "@/components/MContent.vue"; import MMain from "@/components/MMain.vue"; interface RouteMeta { icon: string; title: string; islink: number; mode: string; } const routes = [ { path: "/overview", // 临时比对本地版本用 version: +new Date(), component: MMain, meta: { icon: "iconjiankonggaikuang_huaban", title: "经营概况", islink: 1, }, children: [ { path: "", name: "OverView", meta: { title: "经营概况", isShow: 1, }, show: true, component: () => import("@/views/manage/Index.vue"), }, ], }, { path: "", component: MMain, meta: { icon: "iconshangpinguanli", title: "商品管理", }, children: [ { path: "goods", component: MContent, meta: { title: "商品列表", }, show: true, children: [ { path: "", name: "Goods", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, { path: "addGood", name: "AddGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/AddGood.vue" ), meta: { title: "发布商品", noPadding: true, }, show: true, }, ], }, { path: "goodRegion", // name: "goodRegion", component: MContent, meta: { title: "设置专区", }, show: true, children: [ { path: "", name: "goodRegion", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/GoodRegion.vue" ), }, { path: "class", name: "class", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/GoodClass.vue" ), meta: { title: "商品分类", }, }, ], }, { path: "attributeTemple", name: "Attribute", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/AttributeTemple.vue" ), meta: { title: "属性模板", }, }, { path: "supplier", name: "sup", show: true, component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/goodManage/SupplierManage.vue" ), meta: { title: "供货商", }, }, { path: "csvImport", name: "csvImport", show: true, component: MContent, meta: { title: "素材导入", }, children: [ { path: "", name: "csvList", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/csvImport/CsvIndex.vue" ), }, { path: "editGood", name: "editGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/csvImport/EditGood.vue" ), meta: { title: "编辑商品", noPadding: true, }, show: true, }, ], }, ], }, { path: "/order", component: MMain, meta: { title: "订单管理", icon: "icondingdan", }, children: [ { path: "delivery", meta: { title: "快递订单", }, show: true, component: MContent, children: [ { meta: { title: "", }, path: "", component: () => import( /* webpackChunkName: "order" */ "@/views/order/DeliveryOrder.vue" ), }, { path: "send", meta: { title: "批量发货", noPadding: true, }, component: () => import( /* webpackChunkName: "order" */ "@/views/order/DeliverySend.vue" ), }, ], }, { path: "evaluation", component: () => import( /* webpackChunkName: "order" */ "@/views/order/Evaluation.vue" ), meta: { title: "评价管理", }, show: true, }, { path: "afterSale", component: () => import( /* webpackChunkName: "order" */ "@/views/order/AfterSaleOrder.vue" ), meta: { title: "售后工单", }, show: true, }, ], }, { path: "/customer", component: MMain, meta: { title: "客户管理", icon: "iconkehu", }, children: [ { path: "list", component: MContent, children: [ { path: "", name: "list", component: () => import( /* webpackChunkName: "goods" */ "@/views/customer/list/Index.vue" ), }, ], meta: { title: "客户列表", }, show: true, }, { path: "blacklist", name: "blacklist", component: () => import( /* webpackChunkName: "blacklist" */ "@/views/customer/blacklist/Index.vue" ), meta: { title: "黑名单", }, show: true, }, ], }, { path: "/distribution", component: MMain, meta: { title: "配送方式", icon: "icondaifahuo", }, children: [ { path: "logistics", component: () => import( /* webpackChunkName: "finance" */ "@/views/logistics/logistics/Index.vue" ), meta: { title: "快递配送", }, show: true, }, ], }, { path: "/setting", component: MMain, meta: { title: "商城设置", icon: "iconshangpinxiangqing-dianpu", }, children: [ { path: "channel", component: () => import(/* webpackChunkName: "setting" */ "@/views/channel/Index.vue"), meta: { title: "销售渠道", }, show: true, }, { path: "editorPage", redirect: "/editorPage", component: () => import( /* webpackChunkName: "setting" */ "@/views/decoration/components/EditorPage/src/Editor.vue" ), meta: { title: "装修", // isShow: 1, }, show: true, }, { path: "", name: "setting", component: () => import(/* webpackChunkName: "setting" */ "@/views/setting/Index.vue"), meta: { title: "通用设置", }, show: true, }, ], }, { path: "/logistics", component: MMain, meta: { title: "物流管理", isShow: 1, }, children: [ { path: "logistics", name: "logistics", component: () => import( /* webpackChunkName: "logistics" */ "@/views/logistics/logistics/Index.vue" ), meta: { title: "快递配送", }, show: true, }, ], }, { path: "/market", component: MMain, meta: { title: "商超系统", isShow: 1, }, children: [ { path: "goods", component: MContent, meta: { title: "商品列表", }, show: true, children: [ { path: "", name: "Goods", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, { path: "addGood", name: "AddGood", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/AddGood.vue" ), meta: { title: "发布商品", }, }, ], }, ], }, { path: "/CategoryTem", component: MMain, meta: { title: "商品属性", isShow: 1, }, children: [ { path: "/", name: "CategoryTem", component: () => import( /* webpackChunkName: "CategoryTem" */ "@/views/goods/goodManage/components/CategoryTem.vue" ), meta: { title: "商品属性", }, show: true, }, ], }, { path: "/business", component: MMain, meta: { title: "商家中心", isShow: 1, }, children: [ { path: "/", name: "businessCenter", component: () => import( /* webpackChunkName: "businessCenter" */ "@/views/businessCenter/Index.vue" ), meta: { title: "", }, show: true, }, ], }, { path: "/editorPage", name: "editorPage", component: () => import( /* webpackChunkName: "CategoryTem" */ "@/views/decoration/components/EditorPage/src/Editor.vue" ), meta: { title: "装修", isShow: 1, }, }, { path: "/changepass", name: "changepass", component: () => import( /* webpackChunkName: "changepass" */ "@/views/businessCenter/Account/ChangePassword.vue" ), meta: { title: "修改密码", isShow: 1, }, }, { path: "/redirect/:type", name: "redirect", component: () => import(/* webpackChunkName: "CategoryTem" */ "@/views/sign/Redirect.vue"), meta: { title: "重定向页面", isShow: 1, }, }, { path: "/static", component: MContent, meta: { title: "", isShow: 1, }, children: [ { path: "protocol", name: "protocol", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Protocol.vue" ), meta: { title: "注册协议", }, }, { path: "privacy", name: "privacy", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Privacy.vue" ), meta: { title: "隐私政策", }, }, { path: "order", name: "order", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Order.vue" ), meta: { title: "订购及服务协议", }, }, { path: "register", name: "register", component: () => import( /* webpackChunkName: "meal" */ "@/views/businessCenter/Static/Register.vue" ), meta: { title: "开户及服务协议", }, }, ], }, { path: "/", component: MMain, meta: { title: "商品管理", isShow: 1, }, children: [ { path: "", component: MContent, meta: { title: "商超商品", }, show: true, children: [ { path: "", name: "index", component: () => import( /* webpackChunkName: "goods" */ "@/views/goods/marketModel/Goods.vue" ), }, ], }, ], }, { path: "*", name: "404", component: () => import(/* webpackChunkName: "404" */ "@/views/sign/404.vue"), meta: { title: "404", isShow: 1, }, }, ]; export default routes;
the_stack
import {Attribute} from '../../../attribute'; import {Graph} from '../../../graph'; import {Upsample} from '../../../ops/upsample'; import {Tensor} from '../../../tensor'; import {CpuInferenceHandler} from '../inference-handler'; export declare namespace Upsample { interface GetNearestPixelFunc { (a: number, b: boolean): number; } interface GetOriginalCoordinateFunc { (xResized: number, xScale: number, lengthResized: number, lengthOriginal: number, roiStart: number, roiEnd: number): number; } } export class CpuUpsample extends Upsample { run(inferenceHandler: CpuInferenceHandler, inputs: Tensor[]): Tensor[] { const [roi, scales, yDims] = this.prepareInputs(inputs); const y = new Tensor(yDims, inputs[0].type); this.compute(inputs[0], y, roi, scales); return [y]; } initialize(attributes: Attribute, node: Graph.Node, graph: Graph): void { super.initialize(attributes, node, graph); this.getOriginalCoordinate = getOriginalCoordinateFromResizedCoordinate(this.coordinateTransformMode); this.getNearestPixel = getNearestPixelFromOriginal(this.nearestMode); } compute(x: Tensor, y: Tensor, roi: ReadonlyArray<number>, scales: ReadonlyArray<number>): void { const xDims = x.dims; const yDims = y.dims; if (yDims.length !== xDims.length) { throw new Error('Rank of input and output tensor should be same.'); } if (y.size === 0) { return; } if (xDims.length !== scales.length) { throw new Error('input tensor\'s dimension does not match the scales.'); } if (roi.length !== 2 * xDims.length) { throw new Error('size of roi array should be 2 * N where N is the rank of input tensor X.'); } const noScale = xDims.every((d, i) => yDims[i] === d); if (noScale) { y.numberData.set(x.numberData); return; } if (this.mode === 'nearest') { upsampleNearest( x.data, y.data, xDims, yDims, scales, roi, this.isResize, this.useExtrapolation, this.extrapolationValue, this.useNearest2xOptimization, this.getOriginalCoordinate, this.getNearestPixel); } else { if (xDims.length !== 2 && xDims.length !== 4) { throw new Error('\'Linear\' mode only support 2-D inputs or 4-D inputs'); } const is2D = xDims.length === 2; const batchSize = is2D ? 1 : xDims[0]; const numChannels = is2D ? 1 : xDims[1]; const inputHeight = is2D ? xDims[0] : xDims[2]; const inputWidth = is2D ? xDims[1] : xDims[3]; const outputHeight = is2D ? yDims[0] : yDims[2]; const outputWidth = is2D ? yDims[1] : yDims[3]; if (this.mode === 'linear') { upsampleBilinear( batchSize, numChannels, inputHeight, inputWidth, outputHeight, outputWidth, is2D ? scales[0] : scales[2], is2D ? scales[1] : scales[3], roi, this.useExtrapolation, this.extrapolationValue, x.numberData, y.numberData, this.getOriginalCoordinate); } else { upsampleBiCubic( batchSize, numChannels, inputHeight, inputWidth, outputHeight, outputWidth, is2D ? scales[0] : scales[2], is2D ? scales[1] : scales[3], this.cubicCoefficientA, this.useExtrapolation, this.extrapolationValue, this.excludeOutside, roi, x.numberData, y.numberData, this.getOriginalCoordinate); } } } protected getOriginalCoordinate: Upsample.GetOriginalCoordinateFunc; protected getNearestPixel: Upsample.GetNearestPixelFunc; } function upsampleNearest( xData: Tensor.DataTypeMap[Tensor.DataType], yData: Tensor.DataTypeMap[Tensor.DataType], xDims: ReadonlyArray<number>, yDims: ReadonlyArray<number>, scales: ReadonlyArray<number>, roi: ReadonlyArray<number>, isResize: boolean, extrapolationEnabled: boolean, extrapolationValue: number, useNearest2xOptimization: boolean, getOriginalCoordinate: Upsample.GetOriginalCoordinateFunc, getNearestPixel: Upsample.GetNearestPixelFunc) { const dim = xDims.length; if (useNearest2xOptimization && dim === 4 && scales[0] === 1 && scales[1] === 1 && scales[2] === 2 && scales[3] === 2) { // TODO: 2x optimization } const inputDimCounter = new Array<number>(dim).fill(0); const inputDimFactor = new Array<number>(dim); const useExtrapolationValue = new Array<boolean>(dim); inputDimFactor[dim - 1] = 1; // initialize dimension factor for (let i = dim - 2; i >= 0; i--) { inputDimFactor[i] = inputDimFactor[i + 1] * xDims[i + 1]; } let yIdx = 0; let xIdx = 0; const oneDimensionProcessor = (dimIdx: number, yDim: number) => { useExtrapolationValue[dimIdx] = false; const originalIdx = getOriginalCoordinate(yDim, scales[dimIdx], yDims[dimIdx], xDims[dimIdx], roi[dimIdx], roi[dim + dimIdx]); if (extrapolationEnabled && (originalIdx < 0 || originalIdx > xDims[dimIdx] - 1)) { useExtrapolationValue[dimIdx] = true; } let currentInputDimCounter = getNearestPixel(originalIdx, scales[dimIdx] < 1); currentInputDimCounter = Math.max(0, Math.min(currentInputDimCounter, (xDims[dimIdx] - 1))); if (currentInputDimCounter !== inputDimCounter[dimIdx]) { xIdx += (currentInputDimCounter - inputDimCounter[dimIdx]) * inputDimFactor[dimIdx]; inputDimCounter[dimIdx] = currentInputDimCounter; } }; if (dim === 1) { for (let yDim0 = 0; yDim0 < yDims[0]; yDim0++) { oneDimensionProcessor(0, yDim0); yData[yIdx++] = useExtrapolationValue[0] ? extrapolationValue : xData[xIdx]; } } else if (dim === 2) { for (let yDim0 = 0; yDim0 < yDims[0]; yDim0++) { oneDimensionProcessor(0, yDim0); for (let yDim1 = 0; yDim1 < yDims[1]; yDim1++) { oneDimensionProcessor(1, yDim1); yData[yIdx++] = useExtrapolationValue.some(i => i) ? extrapolationValue : xData[xIdx]; } } } else if (dim === 3) { for (let yDim0 = 0; yDim0 < yDims[0]; yDim0++) { oneDimensionProcessor(0, yDim0); for (let yDim1 = 0; yDim1 < yDims[1]; yDim1++) { oneDimensionProcessor(1, yDim1); for (let yDim2 = 0; yDim2 < yDims[2]; yDim2++) { oneDimensionProcessor(2, yDim2); yData[yIdx++] = useExtrapolationValue.some(i => i) ? extrapolationValue : xData[xIdx]; } } } } else if (dim === 4) { for (let yDim0 = 0; yDim0 < yDims[0]; yDim0++) { oneDimensionProcessor(0, yDim0); for (let yDim1 = 0; yDim1 < yDims[1]; yDim1++) { oneDimensionProcessor(1, yDim1); for (let yDim2 = 0; yDim2 < yDims[2]; yDim2++) { oneDimensionProcessor(2, yDim2); for (let yDim3 = 0; yDim3 < yDims[3]; yDim3++) { oneDimensionProcessor(3, yDim3); yData[yIdx++] = useExtrapolationValue.some(i => i) ? extrapolationValue : xData[xIdx]; } } } } } else { const outputDimCounter = new Array<number>(dim).fill(0); outputDimCounter[dim - 1] = -1; for (; yIdx < yData.length; yIdx++) { for (let dimIdx = dim - 1; dimIdx >= 0; dimIdx--) { if (++outputDimCounter[dimIdx] < yDims[dimIdx]) { let currentInputDimCounter = 0; const originalIdx = getOriginalCoordinate( outputDimCounter[dimIdx], scales[dimIdx], yDims[dimIdx], xDims[dimIdx], roi[dimIdx], roi[dim + dimIdx]); currentInputDimCounter = getNearestPixel(originalIdx, scales[dimIdx] < 1); currentInputDimCounter = Math.max(0, Math.min(currentInputDimCounter, (xDims[dimIdx] - 1))); if (currentInputDimCounter !== inputDimCounter[dimIdx]) { xIdx += (currentInputDimCounter - inputDimCounter[dimIdx]) * inputDimFactor[dimIdx]; inputDimCounter[dimIdx] = currentInputDimCounter; } break; } else { outputDimCounter[dimIdx] = 0; xIdx += (0 - inputDimCounter[dimIdx]) * inputDimFactor[dimIdx]; inputDimCounter[dimIdx] = 0; } } yData[yIdx] = xData[xIdx]; } } } function upsampleBilinear( batchSize: number, numChannels: number, inputHeight: number, inputWidth: number, outputHeight: number, outputWidth: number, heightScale: number, widthScale: number, roi: ReadonlyArray<number>, useExtrapolation: boolean, extrapolationValue: number, xData: Tensor.NumberType, yData: Tensor.NumberType, getOriginalCoordinate: Upsample.GetOriginalCoordinateFunc) { const yOriginal: number[] = []; const xOriginal: number[] = []; const inputWidthMulY1 = new Array<number>(outputHeight); const inputWidthMulY2 = new Array<number>(outputHeight); const inX1 = new Array<number>(outputWidth); const inX2 = new Array<number>(outputWidth); const dy1 = new Array<number>(outputHeight); const dy2 = new Array<number>(outputHeight); const dx1 = new Array<number>(outputWidth); const dx2 = new Array<number>(outputWidth); const roiYStart = roi.length / 2 - 2; const roiYEnd = roi.length - 2; for (let y = 0; y < outputHeight; ++y) { let inY = getOriginalCoordinate(y, heightScale, outputHeight, inputHeight, roi[roiYStart], roi[roiYEnd]); yOriginal.push(inY); inY = Math.max(0, Math.min(inY, inputHeight - 1)); const inY1 = Math.min(Math.floor(inY), inputHeight - 1); const inY2 = Math.min(inY1 + 1, inputHeight - 1); if (inY1 === inY2) { dy1[y] = 0.5; dy2[y] = 0.5; } else { dy1[y] = Math.abs(inY - inY1); dy2[y] = Math.abs(inY - inY2); } inputWidthMulY1[y] = inputWidth * inY1; inputWidthMulY2[y] = inputWidth * inY2; } const roiXStart = roi.length / 2 - 1; const roiXEnd = roi.length - 1; for (let x = 0; x < outputWidth; ++x) { let inX = getOriginalCoordinate(x, widthScale, outputWidth, inputWidth, roi[roiXStart], roi[roiXEnd]); xOriginal.push(inX); inX = Math.max(0, Math.min(inX, inputWidth - 1)); inX1[x] = Math.min(Math.floor(inX), inputWidth - 1); inX2[x] = Math.min(inX1[x] + 1, inputWidth - 1); if (inX1[x] === inX2[x]) { dx1[x] = 0.5; dx2[x] = 0.5; } else { dx1[x] = Math.abs(inX - inX1[x]); dx2[x] = Math.abs(inX - inX2[x]); } } let xOffset = 0; let yOffset = 0; for (let n = 0; n < batchSize; ++n) { for (let c = 0; c < numChannels; ++c) { for (let y = 0; y < outputHeight; ++y) { for (let x = 0; x < outputWidth; ++x) { if (useExtrapolation && ((yOriginal[y] < 0 || yOriginal[y] > inputHeight - 1) || (xOriginal[x] < 0 || xOriginal[x] > inputWidth - 1))) { yData[outputWidth * y + x] = extrapolationValue; continue; } const x11 = xData[xOffset + inputWidthMulY1[y] + inX1[x]]; const x21 = xData[xOffset + inputWidthMulY1[y] + inX2[x]]; const x12 = xData[xOffset + inputWidthMulY2[y] + inX1[x]]; const x22 = xData[xOffset + inputWidthMulY2[y] + inX2[x]]; yData[yOffset + outputWidth * y + x] = (dx2[x] * dy2[y] * x11 + dx1[x] * dy2[y] * x21 + dx2[x] * dy1[y] * x12 + dx1[x] * dy1[y] * x22); } } xOffset += inputHeight * inputWidth; yOffset += outputWidth * outputHeight; } } } const CUBIC_MODE_GRID_LENGTH = 4; function getCubicCoeffs(s: number, cubicCoeffA = -0.75): number[] { s = Math.abs(s); return [ (((cubicCoeffA * (s + 1) - 5 * cubicCoeffA) * (s + 1) + 8 * cubicCoeffA) * (s + 1) - 4 * cubicCoeffA), (((cubicCoeffA + 2) * s - (cubicCoeffA + 3)) * s * s + 1), (((cubicCoeffA + 2) * (1 - s) - (cubicCoeffA + 3)) * (1 - s) * (1 - s) + 1), (((cubicCoeffA * (2 - s) - 5 * cubicCoeffA) * (2 - s) + 8 * cubicCoeffA) * (2 - s) - 4 * cubicCoeffA) ]; } function getDataForCoordinate( xData: Tensor.NumberType, x: number, y: number, inputHeight: number, inputWidth: number): number { x = Math.max(0, Math.min(x, inputWidth - 1)); y = Math.max(0, Math.min(y, inputHeight - 1)); return xData[y * inputWidth + x]; } function cubicInterpolation1D( xData: Tensor.NumberType, x: number, y: number, inputHeight: number, inputWidth: number, coeffArray: number[], coeffSum: number, cache: Map<number, number>): number { // When calculating cubic interpolation we move the 4*4 grid across the original data and therefore there is // opportunity to cache the results for previously seen combinations. // Check if the result is already available in the cache const gridStartPosition = (y) * inputWidth + (x - 1); let result = cache.get(gridStartPosition); if (result !== undefined) { return result; } // get the neighbors in 1D and find interpolation for this dimension // for 1D cubic interpolation 4 samples are used. 2 on the left and 2 on the right of x result = 0; for (let i = 0, j = -1; i < CUBIC_MODE_GRID_LENGTH; i++, j++) { const originalData = getDataForCoordinate(xData, x + j, y, inputHeight, inputWidth); result += coeffArray[i] / coeffSum * originalData; } cache.set(gridStartPosition, result); return result; } function upsampleBiCubic( batchSize: number, numChannels: number, inputHeight: number, inputWidth: number, outputHeight: number, outputWidth: number, heightScale: number, widthScale: number, cubicCoefficientA: number, useExtrapolation: boolean, extrapolationValue: number, excludeOutside: boolean, roi: ReadonlyArray<number>, xData: Tensor.NumberType, yData: Tensor.NumberType, getOriginalCoordinate: Upsample.GetOriginalCoordinateFunc) { const yOriginal: number[] = []; const xOriginal: number[] = []; const cubicCoeffs = new Map<number, number[]>(); const coeffTo1DinterpolationMap = new Map<number, Map<number, number>>(); const roiYStart = roi.length / 2 - 2; const roiYEnd = roi.length - 2; const roiXStart = roi.length / 2 - 1; const roiXEnd = roi.length - 1; // generate coefficients in y direction for (let y = 0; y < outputHeight; ++y) { const inY = getOriginalCoordinate(y, heightScale, outputHeight, inputHeight, roi[roiYStart], roi[roiYEnd]); yOriginal.push(inY); const s = yOriginal[y] - Math.floor(yOriginal[y]); if (!cubicCoeffs.has(s)) { cubicCoeffs.set(s, getCubicCoeffs(s, cubicCoefficientA)); coeffTo1DinterpolationMap.set(s, new Map()); } } // generate coefficients in x direction for (let x = 0; x < outputWidth; ++x) { const inX = getOriginalCoordinate(x, widthScale, outputWidth, inputWidth, roi[roiXStart], roi[roiXEnd]); xOriginal.push(inX); const s = xOriginal[x] - Math.floor(xOriginal[x]); if (!cubicCoeffs.has(s)) { cubicCoeffs.set(s, getCubicCoeffs(s, cubicCoefficientA)); coeffTo1DinterpolationMap.set(s, new Map()); } } // setup up temp arrays to hold coefficients when exclude_outside is set to true const yCoeffHolder = new Array<number>(CUBIC_MODE_GRID_LENGTH); const xCoeffHolder = new Array<number>(CUBIC_MODE_GRID_LENGTH); let yCoeffSum = 1; let xCoeffSum = 1; for (let n = 0; n < batchSize; n++) { for (let c = 0; c < numChannels; c++) { for (let y = 0; y < outputHeight; y++) { const inY = yOriginal[y]; // when use_extrapolation is set and original index is out of the dim range // then use extrapolation_value as the output value. if (useExtrapolation && (inY < 0 || inY > inputHeight - 1)) { for (let x = 0; x < outputWidth; x++) { yData[y * outputWidth + x] = extrapolationValue; } continue; } const yInt = Math.floor(inY); const sY = inY - yInt; const coeffY = excludeOutside ? yCoeffHolder : cubicCoeffs.get(sY)!; yCoeffSum = 1; if (excludeOutside) { // When true, the weight of sampling locations outside the grid will be set to 0 // and the weight will be renormalized so that their sum is 1.0 yCoeffSum = 0; const origYCoeffs = cubicCoeffs.get(sY)!; for (let i = 0, yVal = yInt - 1; yVal <= yInt + 2; yVal++, i++) { yCoeffHolder[i] = (yVal < 0 || yVal >= inputHeight) ? 0.0 : origYCoeffs[i]; yCoeffSum += yCoeffHolder[i]; } } for (let x = 0; x < outputWidth; x++) { const inX = xOriginal[x]; // when use_extrapolation is set and original index is out of the dim range // then use extrapolation_value as the output value. if (useExtrapolation && (inX < 0 || inX > inputWidth - 1)) { yData[y * outputWidth + x] = extrapolationValue; continue; } const xInt = Math.floor(inX); const sX = inX - xInt; const coeffX = excludeOutside ? xCoeffHolder : cubicCoeffs.get(sX)!; xCoeffSum = 1; if (excludeOutside) { // When true, the weight of sampling locations outside the grid will be set to 0 // and the weight will be renormalized so that their sum is 1.0 xCoeffSum = 0; const origXCoeffs = cubicCoeffs.get(sX)!; for (let i = 0, xVal = xInt - 1; xVal <= xInt + 2; xVal++, i++) { xCoeffHolder[i] = (xVal < 0 || xVal >= inputWidth) ? 0.0 : origXCoeffs[i]; xCoeffSum += xCoeffHolder[i]; } } // Compute cubic interpolation in x dimension using the x coefficients. // From the result of cubic interpolation in x dim, compute cubic interpolation in y dimension const interpolationResultCache = coeffTo1DinterpolationMap.get(sX)!; let result = 0; for (let yVal = yInt - 1, i = 0; yVal <= yInt + 2; yVal++, i++) { const xResult = cubicInterpolation1D( xData, xInt, yVal, inputHeight, inputWidth, coeffX, xCoeffSum, interpolationResultCache); result += xResult * coeffY[i] / yCoeffSum; } yData[y * outputWidth + x] = result; } } xData = xData.subarray(inputHeight * inputWidth); yData = yData.subarray(outputHeight * outputWidth); // clear the cache when moving to the next channel coeffTo1DinterpolationMap.clear(); } } } function getOriginalCoordinateFromResizedCoordinate(mode: string): Upsample.GetOriginalCoordinateFunc { switch (mode) { case 'asymmetric': return (xResized: number, xScale: number) => xResized / xScale; case 'pytorch_half_pixel': return (xResized: number, xScale: number, lengthResized: number) => lengthResized > 1 ? (xResized + 0.5) / xScale - 0.5 : 0.0; case 'tf_half_pixel_for_nn': return (xResized: number, xScale: number) => (xResized + 0.5) / xScale; case 'align_corners': return (xResized: number, xScale: number, lengthResized: number, lengthOriginal: number) => lengthResized === 1 ? 0 : xResized * (lengthOriginal - 1) / (lengthResized - 1); case 'tf_crop_and_resize': return (xResized: number, xScale: number, lengthResized: number, lengthOriginal: number, roiStart: number, roiEnd: number) => (lengthResized > 1 ? roiStart * (lengthOriginal - 1) + (xResized * (roiEnd - roiStart) * (lengthOriginal - 1)) / (lengthResized - 1) : 0.5 * (roiStart + roiEnd) * (lengthOriginal - 1)); default: //'half_pixel' return (xResized: number, xScale: number) => (xResized + 0.5) / xScale - 0.5; } } function getNearestPixelFromOriginal(mode: string): Upsample.GetNearestPixelFunc { switch (mode) { case '': return (xOriginal: number, isDownSample: boolean) => isDownSample ? Math.ceil(xOriginal) : Math.floor(xOriginal); case 'round_prefer_ceil': return (xOriginal: number) => Math.round(xOriginal); case 'floor': return (xOriginal: number) => Math.floor(xOriginal); case 'ceil': return (xOriginal: number) => Math.ceil(xOriginal); default: // round_prefer_floor return (xOriginal: number) => xOriginal === Math.floor(xOriginal) + 0.5 ? Math.floor(xOriginal) : Math.round(xOriginal); } }
the_stack
import {Observable} from 'data/observable'; import {ObservableArray} from 'data/observable-array'; import TypeUtils = require('utils/types'); import Xml = require('xml'); /** * A XML name. */ export class XName { private _localName: string; private _namespace: string; /** * Initializes a new instance of that class. * * @param {string} name The full name. * * @throws Name is invalid. */ constructor(name: string) { if (TypeUtils.isNullOrUndefined(name)) { throw "Name cannot be (null) or (undefined)!"; } name = ('' + name).trim(); var ns: string = null; var ln: string = name; if (ln.indexOf(':') > -1) { var parts = ln.split(':'); if (2 !== parts.length) { throw "Cannot have more than one separator!"; } ns = parts[0].trim(); ln = parts[1].trim(); } if ('' === ln) { throw "Local name cannot be empty!"; } if (null !== ns) { ns = ns.trim(); if ('' === ns) { ns = null; } } this._namespace = ns; this._localName = ln; } /** * Checks if a value is equal to the full name of that instance. * * @param any v The value to check. * * @return {Boolean} Is equal or not. */ public equals(v: any): boolean { if (TypeUtils.isNullOrUndefined(v)) { return false; } if (v instanceof XName) { v = v.toString(); } return this.toString() === ('' + v); } /** * Gets the local name. */ public get localName(): string { return this._localName; } /** * Gets the namespace. */ public get namespace(): string { return this._namespace; } /** * Returns the full name. * * @return {string} The full name. */ public toString(): string { var str = this._localName; if (null !== this._namespace) { str = this._namespace + ":" + str; } return str; } } /** * A XML object. */ export abstract class XObject extends Observable { /** * Gets the underlying document. */ public get document(): XDocument { return !TypeUtils.isNullOrUndefined(this.parent) ? this.parent.document : null; } /** * Gets or sets the parent element. */ public parent: XElement; /** * Gets the string representation of that object. * * @return {String} The object as string. */ public abstract toString(): string; } /** * A XML attribute. */ export class XAttribute { private _name: XName; /** * Initializes a new instance of that class. * * @param any name The name of the element. * * @throws Name is invalid. */ constructor(name: XName | string) { if (!(name instanceof XName)) { name = new XName(<any>name); } this._name = <any>name; } /** * Gets the name of the element. */ public get name(): XName { return this._name; } /** * Gets or sets the value. */ public value: any; /** * Gets the string representation of that object. * * @return {String} The object as string. */ public toString(): string { var str = this.name.toString(); var v = this.value; if (!TypeUtils.isNullOrUndefined(v)) { str += '="' + parseXmlEntities(v) + '"'; } return str; } } /** * A XML node. */ export abstract class XNode extends XObject { } /** * XML text. */ export class XText extends XNode { /** * Gets or sets the value of the text. */ public value: any; /** @inheritdoc */ public toString(): string { return parseXmlEntities(this.value); } } /** * XML CDATA */ export class XCData extends XText { /** @inheritdoc */ public toString(): string { return '<![CDATA[' + parseXmlEntities(this.value) + ']]>'; } } /** * A XML comment. */ export class XComment extends XNode { /** * Gets or sets the value of the comment. */ public value: any; /** @inheritdoc */ public toString(): string { return '<!--' + parseXmlEntities(this.value) + '-->'; } } /** * A XML container. */ export abstract class XContainer extends XNode { private _nodes = new ObservableArray<XNode>(); /** * Adds content. * * @param any content The content to add. */ public add(content: any) { if (TypeUtils.isNullOrUndefined(content)) { return; } if (!(content instanceof XNode)) { var txt = new XText(); txt.value = '' + content; content = txt; } this._nodes.push(content); } /** * Returns the first element by name. * * @param any name The name of the attribute. * * @return {XElement} The element or (null) if not found. */ public element(name: string | XName): XElement { var elementList = this.elements(name); return elementList.length > 0 ? elementList[0] : null; } /** * Gets the element of the container. * * @param any [name] The custom name filter. * * @return {XElement[]} The elements. * * @throws Name is invalid. */ public elements(name?: string | XName): XElement[] { var validator = this.getElementValidator(name); var elementList = []; for (var i = 0; i < this._nodes.length; i++) { var n = this._nodes.getItem(i); if (n instanceof XElement) { if (validator(n)) { elementList.push(n); } } } return elementList; } /** * Returns an element validator by name. * * @param any name The XML name. * * @return {Function} The validator. * * @throws Name is invalid. */ protected getElementValidator(name: string | XName): (element: XElement) => boolean { if (TypeUtils.isNullOrUndefined(name)) { return () => true; } if (!(name instanceof XName)) { name = new XName(<any>name); } return (e) => e.name.equals(name); } /** * Gets the nodes of the container. * * @return {XNode[]} The nodes. */ public nodes(): XNode[] { var nodeList = []; for (var i = 0; i < this._nodes.length; i++) { nodeList.push(this._nodes.getItem(i)); } return nodeList; } } /** * A XML container with attributes. */ export abstract class XContainerWithAttributes extends XContainer { private _attributes: XAttribute[] = []; /** @inheritdoc */ public add(content: any) { if (content instanceof XAttribute) { this._attributes.push(content); } else { super.add(content); } } /** * Returns an attribute by name. * * @param any name The name of the attribute. * * @return {XAttribute} The attribute or (null) if not found. */ public attribute(name: string | XName): XAttribute { var attribList = this.attributes(name); return attribList.length > 0 ? attribList[0] : null; } /** * Gets the list of attributes. * * @param any [name] The custom name filter. * * @return {XAttribute[]} The attributes. * * @throws Name is invalid. */ public attributes(name?: string | XName): XAttribute[] { var validator = this.getAttributeValidator(name); var attributeList = []; for (var i = 0; i < this._attributes.length; i++) { var a = this._attributes[i]; if (validator(a)) { attributeList.push(a); } } return attributeList; } /** * Returns an attribute validator by name. * * @param any name The XML name. * * @return {Function} The validator. * * @throws Name is invalid. */ protected getAttributeValidator(name: string | XName): (attrib: XAttribute) => boolean { if (TypeUtils.isNullOrUndefined(name)) { return () => true; } if (!(name instanceof XName)) { name = new XName(<any>name); } return (a) => a.name.equals(name); } } /** * A XML element. */ export class XElement extends XContainerWithAttributes { private _document: XDocument; private _elements = new ObservableArray<XElement>(); private _name: XName; /** * Initializes a new instance of that class. * * @param any name The name of the element. * * @throws Name is invalid. */ constructor(name: XName | string) { super(); if (!(name instanceof XName)) { name = new XName(<any>name); } this._name = <any>name; } /** @inheritdoc */ public add(content: any) { if (content instanceof XContainer) { if (!TypeUtils.isNullOrUndefined(content.parent)) { throw "Parent is already set."; } content.parent = this; } super.add(content); } /** @inheritdoc */ public get document(): XDocument { var p = this.parent; return !TypeUtils.isNullOrUndefined(p) ? p.document : this._document; } public set document(doc: XDocument) { if (!TypeUtils.isNullOrUndefined(this.parent)) { throw "Cannot set document here!"; } if (!TypeUtils.isNullOrUndefined(this._document)) { throw "Document already set!"; } this._document = doc; } /** * Gets the name of the element. */ public get name(): XName { return this._name; } /** @inheritdoc */ public toString(): string { var str = '<' + this.name.toString(); var attribs = this.attributes(); if (attribs.length > 0) { for (var i = 0; i < attribs.length; i++) { var a = attribs[i]; str += " " + a.toString(); } } var nodes = this.nodes(); if (nodes.length > 0) { str += '>'; for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; str += n.toString(); } str += '</' + this.name.toString() + '>'; } else { str += ' />' } return str; } /** * Gets the value of that element. * * @return {any} The value. */ public get value(): any { var childNodes = this.nodes(); if (childNodes.length < 1) { return null; } var elementValue = ''; for (var i = 0; i < childNodes.length; i++) { var node: any = childNodes[i]; var valueToAdd; if (!TypeUtils.isNullOrUndefined(node.value)) { valueToAdd = node.value; } else { valueToAdd = node.toString(); } if (!TypeUtils.isNullOrUndefined(valueToAdd)) { elementValue += valueToAdd; } } return elementValue; } } /** * A XML document. */ export class XDocument extends XContainer { private _root: XElement = null; /** @inheritdoc */ public add(content: any) { var invokeParent = true; if (content instanceof XElement) { if (TypeUtils.isNullOrUndefined(this._root)) { content.document = this; this._root = content; } else { throw "A root element is already defined!"; } } if (invokeParent) { super.add(content); } } /** * Gets the root element. */ public get root(): XElement { return this._root; } /** @inheritdoc */ public toString(): string { var str = ''; var nodes = this.nodes(); for (var i = 0; i < nodes.length; i++) { var n = nodes[i]; str += n.toString(); } return str; } } function getOwnProperties(obj) { if (TypeUtils.isNullOrUndefined(obj)) { return obj; } var properties: any = {}; for (var p in obj) { if (obj.hasOwnProperty(p)) { properties[p] = obj[p]; } } return properties; } /** * Parses an XML string. * * @param {String} xml The string to parse. * @param {Boolean} [processNamespaces] Process namespaces or not. * @param {Boolean} [angularSyntax] Handle Angular syntax or not. * * @return {XDocument} The new document. * * @throws Parse error. */ export function parse(xml: string, processNamespaces?: boolean, angularSyntax?: boolean): XDocument { var doc = new XDocument(); var errors = []; var elementStack: XElement[] = []; var currentContainer: () => XContainer = () => elementStack.length > 0 ? elementStack[elementStack.length - 1] : doc; var xParser = new Xml.XmlParser((e) => { var c = currentContainer(); if (e.eventType === Xml.ParserEventType.StartElement) { var newElement = new XElement(e.elementName); newElement.add(e.data); var attribs = getOwnProperties(e.attributes); if (!TypeUtils.isNullOrUndefined(attribs)) { for (var p in attribs) { var a = new XAttribute(p); a.value = attribs[p]; newElement.add(a); } } currentContainer().add(newElement); elementStack.push(newElement); } else if (e.eventType === Xml.ParserEventType.Text) { var newText = new XText(); newText.value = e.data; currentContainer().add(newText); } else if (e.eventType === Xml.ParserEventType.CDATA) { var newCData = new XCData(); newCData.value = e.data; currentContainer().add(newCData); } else if (e.eventType === Xml.ParserEventType.Comment) { var newComment = new XComment(); newComment.value = e.data; currentContainer().add(newComment); } else if (e.eventType === Xml.ParserEventType.EndElement) { elementStack.pop(); } }, (error, position) => { errors.push([error, position]); }, processNamespaces, angularSyntax); xParser.parse(xml); if (errors.length > 0) { // collect errors and throw var exceptionMsg = 'XML parse error:'; for (var i = 0; i < errors.length; i++) { var err = errors[i][0]; var pos = errors[i][1]; exceptionMsg += "\n(" + pos.column + "," + pos.line + "): [" + err.name + "] " + err.message; } throw exceptionMsg; } return doc; } function parseXmlEntities(v: any): string { if (TypeUtils.isNullOrUndefined(v)) { v = ''; } v = '' + v; v = v.replace('&', '&amp;'); v = v.replace('"', '&quot;'); v = v.replace("'", '&apos;'); v = v.replace('<', '&lt;'); v = v.replace('>', '&gt;'); return v; }
the_stack
import * as angular from 'angular'; import { ContextualMenuDirective, ContextualMenuController } from './../contextualmenu/contextualMenu'; /** * @ngdoc interface * @name INavBarScope * @module officeuifabric.components.navbar * * @description * This is the scoped used by the `<uif-nav-bar>` directive. * * @property {string} overlay - Overlay name for the nav bar, see OverlayMode enum * @property {function} openMenu - Open menu callback * @property {function} closeMenu - Close menu callback */ interface INavBarScope extends angular.IScope { overlay: string; openMenu: () => void; closeMenu: () => void; } /** * @ngdoc controller * @name NavBarController * @module officeuifabric.components.navbar * * @description * Controller used for the `<uif-nav-bar>` directive. */ export class NavBarController { public static $inject: string[] = ['$scope', '$animate', '$element', '$log']; constructor( private $scope: INavBarScope, private $animate: angular.animate.IAnimateService, private $element: angular.IAugmentedJQuery, public $log: angular.ILogService) { } public openMobileMenu(): void { let menuVisible: boolean = this.$element.hasClass('is-open'); this.$animate[menuVisible ? 'removeClass' : 'addClass'](this.$element, 'is-open'); } public closeMobileMenu(): void { if (this.$element.hasClass('is-open')) { this.$animate.removeClass(this.$element, 'is-open'); } } public closeAllContextMenus(): void { let navBarItems: NodeListOf<Element> = this.$element[0].querySelectorAll('.ms-NavBar-item'); for (let i: number = 0; i < navBarItems.length; i++) { let ngElement: angular.IAugmentedJQuery = angular.element(navBarItems[i]); let navBarItemCtrl: NavBarItemController = ngElement.controller(NavBarItemDirective.directiveName); if (navBarItemCtrl) { navBarItemCtrl.closeContextualMenu(); navBarItemCtrl.deselectItem(); } } } public hideSearchTextBox(): void { let navBarItems: NodeListOf<Element> = this.$element[0].querySelectorAll('.ms-NavBar-item--search'); for (let i: number = 0; i < navBarItems.length; i++) { let ngElement: angular.IAugmentedJQuery = angular.element(navBarItems[i]); let navSearchCtrl: NavBarSearchController = ngElement.controller(NavBarSearch.directiveName); if (navSearchCtrl) { navSearchCtrl.closeSearch(); } } } } /** * @ngdoc directive * @name uifNavBar * @module officeuifabric.components.navbar * * @restrict E * * @description * `<uif-nav-bar>` is a nav bar directive. * * @see {link http://dev.office.com/fabric/components/navbar} * * @usage * * <uif-nav-bar uif-overlay="dark"> * <uif-nav-bar-search placeholder="search for smth" uif-on-search="onSearch(search)"> * </uif-nav-bar-search> * <uif-nav-bar-item uif-text="'Home'" ng-click="logClick('Home item clicked')"></uif-nav-bar-item> * <uif-nav-bar-item uif-text="'Contacts'"></uif-nav-bar-item> * <uif-nav-bar-item> * <uif-nav-item-content> * <uif-icon uif-type="arrowRight"></uif-icon><b>Item in bold with icons</b> * <uif-icon uif-type="arrowLeft"></uif-icon> * </uif-nav-item-content> * </uif-nav-bar-item> * </uif-nav-bar> */ export class NavBarDirective implements angular.IDirective { public static directiveName: string = 'uifNavBar'; public static overlayValues: string[] = ['light', 'dark']; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public controller: any = NavBarController; public controllerAs: string = 'nav'; public template: string = ` <div class=\"ms-NavBar\"> <div class="ms-NavBar-openMenu js-openMenu" ng-click="nav.openMobileMenu()"> <uif-icon uif-type="menu"></uif-icon> </div> <uif-overlay uif-mode="{{overlay}}" ng-click="nav.closeMobileMenu()"></uif-overlay> <ul class=\"ms-NavBar-items\"> <div class='uif-nav-items'></div> </ul> </div>`; public scope: {} = { overlay: '@?uifOverlay' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ( $log: angular.ILogService, $animate: angular.animate.IAnimateService, $document: angular.IDocumentService ) => new NavBarDirective($log, $animate, $document); directive.$inject = ['$log', '$animate', '$document']; return directive; } public link: angular.IDirectiveLinkFn = ( $scope: INavBarScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, navBarController: NavBarController, $transclude: angular.ITranscludeFunction): void => { this.$document.on('click', () => { navBarController.closeAllContextMenus(); navBarController.hideSearchTextBox(); }); $transclude((clone: angular.IAugmentedJQuery) => { let elementToReplace: angular.IAugmentedJQuery = angular.element($element[0].querySelector('.uif-nav-items')); elementToReplace.replaceWith(clone); }); } constructor( private $log: angular.ILogService, private $animate: angular.animate.IAnimateService, private $document: angular.IDocumentService) { } } /** * @ngdoc interface * @name INavBarItemScope * @module officeuifabric.components.navbar * * @description * This is the scope used by the `<uif-nav-bar-item>` directive. * * @property {boolean} hasChildMenu - Indicates if nav bar item has child menu (contexual menu) * @property {object} contextMenuCtrl - Reference to contextual menu controller * @property {string} text - Text used by the nav bar item * @property {string} type - Menu type, string represents one of the values for the NavBarItemTypes enum * @property {function} selectItem - Nav bar item click callback * @property {boolean} isDisabled - Indicates that menu item is disabled */ interface INavBarItemScope extends angular.IScope { hasChildMenu: boolean; contextMenuCtrl: ContextualMenuController; text: string; type: string; selectItem: ($event: JQueryEventObject) => void; isDisabled: boolean; } /** * @ngdoc interface * @name INavBarItemAttributes * @module officeuifabric.components.navbar * * @description * Attributs for the `<uif-nav-bar-item>` directive. * * @property {string} uifType - The type of the nav bar menu item, based on `NavBarItemTypes` enum */ interface INavBarItemAttributes extends angular.IAttributes { uifType: string; } /** * @ngdoc enum * @name NavBarItemTypes * @module officeuifabric.components.navbar * * @description * Determines which nav bar item type, default is `link` */ enum NavBarItemTypes { link = 0, menu = 1 } /** * @ngdoc controller * @name NavBarItemController * @module officeuifabric.components.navbar * * @description * Controller used for the `<uif-nav-bar-item>` directive. */ export class NavBarItemController { public static $inject: string[] = ['$scope', '$element']; constructor(private $scope: INavBarItemScope, private $element: angular.IAugmentedJQuery) { } public closeContextualMenu(): void { if (this.$scope.hasChildMenu) { this.$scope.contextMenuCtrl.closeMenu(); } } public deselectItem(): void { this.$element.removeClass('is-selected'); } } /** * @ngdoc directive * @name uifNavBarItem * @module officeuifabric.components.navbar * * @restrict E * * @description * `<uif-nav-bar-item>` is a nav bar item directive. * * @see {link http://dev.office.com/fabric/components/navbar} * * @usage * * <uif-nav-bar-item uif-text="'Regular menu item'" ng-click="logClick('Menu item clicked')"></uif-nav-bar-item> * <uif-nav-bar-item> * <uif-nav-item-content> * <uif-icon uif-type="arrowRight"></uif-icon><b>Item in bold with icons</b> * <uif-icon uif-type="arrowLeft"></uif-icon> * </uif-nav-item-content> * </uif-nav-bar-item> * <uif-nav-bar-item uif-type="menu"> * <uif-nav-item-content>Sub Menu</uif-nav-item-content> * <uif-contextual-menu> * <uif-contextual-menu-item uif-text="'Delete'"></uif-contextual-menu-item> * <uif-contextual-menu-item uif-text="'Flag'"></uif-contextual-menu-item> * </uif-contextual-menu-item> * </uif-contextual-menu> * </uif-nav-bar-item> */ export class NavBarItemDirective implements angular.IDirective { public static directiveName: string = 'uifNavBarItem'; public replace: boolean = true; public restrict: string = 'E'; public transclude: boolean = true; public controller: any = NavBarItemController; public require: string = `^${NavBarDirective.directiveName}`; public scope: {} = { isDisabled: '@?disabled', position: '@?uifPosition', text: '=?uifText', type: '@?uifType' }; private templateTypes: { [menuType: number]: string } = {}; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new NavBarItemDirective($log); directive.$inject = ['$log']; return directive; } constructor(private $log: angular.ILogService) { this.templateTypes[NavBarItemTypes.link] = ` <li class="ms-NavBar-item" ng-class="{\'is-disabled\': isDisabled, 'ms-NavBar-item--right': position === 'right'}"> <a class="ms-NavBar-link" href=""><span class='uif-nav-item-content'></span></a> </li>`; this.templateTypes[NavBarItemTypes.menu] = ` <li class="ms-NavBar-item ms-NavBar-item--hasMenu" ng-class="{\'is-disabled\': isDisabled}"> <a class="ms-NavBar-link" href=""><span class='uif-nav-item-content'></span></a> <i class="ms-NavBar-chevronDown ms-Icon ms-Icon--chevronDown"></i> <div class='uif-submenu'></div> </li>`; } public template: any = ($element?: angular.IAugmentedJQuery, $attrs?: INavBarItemAttributes): string => { let type: string = $attrs.uifType; if (angular.isUndefined(type)) { return this.templateTypes[NavBarItemTypes.link]; } if (NavBarItemTypes[type] === undefined) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.navbar - unsupported nav bar item type:\n' + 'the type \'' + type + '\' is not supported by ng-Office UI Fabric as valid type for nav bar item.' + 'Supported types can be found under NavBarItemTypes enum here:\n' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/navbar/navbarDirective.ts'); return '<div></div>'; } return this.templateTypes[NavBarItemTypes[type]]; } public link: angular.IDirectiveLinkFn = ( $scope: INavBarItemScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, navBarController: NavBarController, $transclude: angular.ITranscludeFunction): void => { if ($scope.isDisabled) { let navBarLinkEelement: JQuery = angular.element($element[0].querySelector('.ms-NavBar-link')); navBarLinkEelement.removeAttr('href'); } if (angular.isUndefined($scope.type)) { $scope.type = NavBarItemTypes[NavBarItemTypes.link]; } $scope.selectItem = ($event: JQueryEventObject) => { $event.stopPropagation(); if ($element.hasClass('is-disabled')) { return; } $element.parent().find('li').removeClass('is-selected'); navBarController.closeAllContextMenus(); navBarController.hideSearchTextBox(); $element.toggleClass('is-selected'); if ($scope.hasChildMenu && $scope.contextMenuCtrl.isMenuOpened()) { $scope.contextMenuCtrl.closeMenu(); $element.removeClass('is-selected'); } else if ($scope.hasChildMenu && !$scope.contextMenuCtrl.isMenuOpened()) { $scope.contextMenuCtrl.openMenu(); $element.addClass('is-selected'); } else if (!$scope.hasChildMenu) { navBarController.closeMobileMenu(); } $scope.$apply(); }; $element.on('click', $scope.selectItem); this.transcludeChilds($scope, $element, $transclude); let contextMenuCtrl: ContextualMenuController = angular.element($element[0].querySelector('.ms-ContextualMenu')) .controller(ContextualMenuDirective.directiveName); if (contextMenuCtrl) { $scope.hasChildMenu = true; $scope.contextMenuCtrl = contextMenuCtrl; $scope.contextMenuCtrl.onRootMenuClosed.push(() => { navBarController.closeMobileMenu(); $element.removeClass('is-selected'); }); } } private transcludeChilds($scope: INavBarItemScope, $element: angular.IAugmentedJQuery, $transclude: angular.ITranscludeFunction): void { $transclude((clone: angular.IAugmentedJQuery) => { let hasContent: boolean = this.hasItemContent(clone); if (!hasContent && !$scope.text) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.navbar - ' + 'you need to provide a text for a nav bar menu item.\n' + 'For <uif-nav-bar-item> you need to specify either \'uif-text\' as attribute or <uif-nav-item-content> as a child directive'); } this.insertLink(clone, $scope, $element); this.insertMenu(clone, $scope, $element); }); } private insertLink(clone: angular.IAugmentedJQuery, $scope: INavBarItemScope, $element: angular.IAugmentedJQuery): void { let elementToReplace: JQuery = angular.element($element[0].querySelector('.uif-nav-item-content')); if (this.hasItemContent(clone)) { /* element provided */ for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { elementToReplace.replaceWith(element); break; } } } else { /* text attribute provided */ elementToReplace.replaceWith(angular.element('<span>' + $scope.text + '</span>')); } } private insertMenu(clone: angular.IAugmentedJQuery, $scope: INavBarItemScope, $element: angular.IAugmentedJQuery): void { for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('ms-ContextualMenu')) { angular.element($element[0].querySelector('.uif-submenu')).replaceWith(element); } } } private hasItemContent(clone: angular.IAugmentedJQuery): boolean { for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { return true; } } return false; } } /** * @ngdoc interface * @name INavBarSearchScope * @module officeuifabric.components.navbar * * @description * This is the scope used by the `<uif-nav-bar-search>` directive. * * @property {string} searchText - Text being searched * @property {function} onSearch - Search UI element click callback * @property {string} placeholder - Placeholder for the html search input * @property {function} onSearchCallback - User defined callback, firing by search event * @property {function} skipOnClick - Helper search div click callback */ interface INavBarSearchScope extends angular.IScope { searchText: string; onSearch: ($event: KeyboardEvent | MouseEvent) => void; placeholder: string; onSearchCallback: (map: { search: string }) => void; skipOnClick: ($event: MouseEvent) => void; } /** * @ngdoc controller * @name NavBarSearchController * @module officeuifabric.components.navbar * * @description * Controller used for the `<uif-nav-bar-search>` directive. */ export class NavBarSearchController { public static $inject: string[] = ['$scope', '$element', '$document', '$animate', '$timeout']; constructor( private $scope: INavBarSearchScope, private $element: angular.IAugmentedJQuery, private $document: angular.IDocumentService, private $animate: angular.animate.IAnimateService, private $timeout: angular.ITimeoutService) { } public closeSearch(): void { this.$timeout(() => { if (!this.$scope.searchText) { this.$animate.removeClass(this.$element, 'is-open'); } this.$animate.removeClass(this.$element, 'is-selected'); }); } } /** * @ngdoc directive * @name uifNavBarSearch * @module officeuifabric.components.navbar * * @restrict E * * @description * `<uif-nav-bar-search>` is a nav bar search directive. * * @see {link http://dev.office.com/fabric/components/navbar} * * @usage * * <uif-nav-bar-search placeholder="search for smth" uif-on-search="onSearch(search)"> * </uif-nav-bar-search> */ export class NavBarSearch implements angular.IDirective { public static directiveName: string = 'uifNavBarSearch'; public replace: boolean = true; public restrict: string = 'E'; public controller: any = NavBarSearchController; public require: string[] = [`^${NavBarDirective.directiveName}`, `${NavBarSearch.directiveName}`]; public transclude: boolean = true; public scope: {} = { onSearchCallback: '&?uifOnSearch', placeholder: '@?placeholder' }; public template: string = ` <li class="ms-NavBar-item ms-NavBar-item--search ms-u-hiddenSm" ng-click="onSearch($event)"> <div class="ms-TextField" ng-click="skipOnClick($event)"> <input placeholder={{placeholder}} class="ms-TextField-field" type="text" ng-keypress="onSearch($event)" ng-model="searchText"> </div> </li>`; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ( $document: angular.IDocumentService, $animate: angular.animate.IAnimateService, $timeout: angular.ITimeoutService) => new NavBarSearch($document, $animate, $timeout); directive.$inject = ['$document', '$animate', '$timeout']; return directive; } constructor( private $document: angular.IDocumentService, private $animate: angular.animate.IAnimateService, private $timeout: angular.ITimeoutService) { } public link: angular.IDirectiveLinkFn = ( $scope: INavBarSearchScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, ctrls: [NavBarController, NavBarSearchController], $transclude: angular.ITranscludeFunction): void => { this.$document.on('click', () => { ctrls[1].closeSearch(); }); $scope.skipOnClick = ($event: MouseEvent) => { this.applyCssClasses($element); $event.stopPropagation(); }; $scope.onSearch = ($event: KeyboardEvent | MouseEvent) => { ctrls[0].closeAllContextMenus(); if ($event instanceof KeyboardEvent && $event.which === 13 && $scope.onSearchCallback) { $scope.onSearchCallback({ search: $scope.searchText }); } else if ($event instanceof MouseEvent && $element.hasClass('is-open') && $scope.onSearchCallback) { $scope.onSearchCallback({ search: $scope.searchText }); } this.applyCssClasses($element); $event.stopPropagation(); }; } private applyCssClasses($element: angular.IAugmentedJQuery): void { if (!$element.hasClass('is-open')) { this.$animate.addClass($element, 'is-open'); this.$timeout( () => { angular.element($element[0].querySelector('.ms-TextField-field'))[0].focus(); }, 1); } $element.parent().find('li').removeClass('is-selected'); this.$animate.addClass($element, 'is-selected'); } } /** * @ngdoc module * @name officeuifabric.components.navbar * * @description * NavBar Module * */ export let module: angular.IModule = angular.module('officeuifabric.components.navbar', [ 'officeuifabric.components']) .directive(NavBarDirective.directiveName, NavBarDirective.factory()) .directive(NavBarItemDirective.directiveName, NavBarItemDirective.factory()) .directive(NavBarSearch.directiveName, NavBarSearch.factory());
the_stack
import { suite } from 'uvu'; import * as assert from 'uvu/assert'; import * as CORS from './cors'; import type { ServerResponse } from 'worktop/response'; import type { ServerRequest } from 'worktop/request'; const Headers = () => { let raw = new Map; let set = raw.set.bind(raw); // @ts-ignore - mutating raw.set = (k, v) => set(k, String(v)); // @ts-ignore - mutating raw.append = (k, v) => { let val = raw.get(k) || ''; if (val) val += ', '; val += String(v); set(k, val); } // @ts-ignore - ctor return raw as Headers; } const Response = () => { let headers = Headers(); let body: any, finished = false; // @ts-ignore return { headers, finished, statusCode: 0, setHeader: headers.set, body: () => body, end(val: any) { finished = true; body = val; } } as ServerResponse; } const Request = (method = 'GET'): ServerRequest => { let headers = Headers(); return { method, headers } as ServerRequest; } // --- const config = suite('config'); config('should be an object', () => { assert.type(CORS.config, 'object'); }); config('should allow "*" origin by default', () => { assert.is(CORS.config.origin, '*'); }); config('should be mutable', () => { const original = CORS.config.methods; assert.equal(original, ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE']); CORS.config.methods = ['GET']; assert.not.equal(CORS.config.methods, original); assert.equal(CORS.config.methods, ['GET']); assert.equal(CORS.config.headers, []); CORS.config.headers!.push('x-foobarbaz'); assert.is(CORS.config.headers!.length, 1); CORS.config.methods = original; // reset CORS.config.headers = []; // reset }); config.run(); // --- const headers = suite('headers'); headers('should be a function', () => { assert.type(CORS.headers, 'function'); }); headers('defaults :: request', () => { let res = Response(); assert.is( CORS.headers(res), undefined ); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], undefined); assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], undefined); assert.is(headers['Access-Control-Max-Age'], undefined); // preflight only assert.is(headers['Access-Control-Allow-Headers'], undefined); // preflight only assert.is(headers['Access-Control-Allow-Methods'], undefined); // preflight only }); headers('defaults :: preflight', () => { let res = Response(); CORS.headers(res, undefined, true); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], undefined); assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], undefined); assert.is(headers['Access-Control-Max-Age'], undefined); assert.is(headers['Access-Control-Allow-Headers'], undefined); assert.is(headers['Access-Control-Allow-Methods'], 'GET,HEAD,PUT,PATCH,POST,DELETE'); }); headers('config :: request', () => { let res = Response(); CORS.headers(res, { origin: 'https://foobar.com', expose: ['X-My-Custom-Header', 'X-Another-Custom-Header'], credentials: true, maxage: 123 }); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], 'Origin'); // static origin assert.is(headers['Access-Control-Allow-Origin'], 'https://foobar.com'); assert.is(headers['Access-Control-Expose-Headers'], 'X-My-Custom-Header,X-Another-Custom-Header'); assert.is(headers['Access-Control-Allow-Credentials'], 'true'); assert.is(headers['Access-Control-Max-Age'], undefined); // not preflight assert.is(headers['Access-Control-Allow-Headers'], undefined); // not preflight assert.is(headers['Access-Control-Allow-Methods'], undefined); // not preflight }); headers('config :: preflight', () => { let res = Response(); CORS.headers(res, { origin: 'https://foobar.com', expose: ['X-My-Custom-Header', 'X-Another-Custom-Header'], headers: ['X-PINGOTHER', 'Content-Type'], methods: ['POST', 'PUT', 'DELETE'], credentials: true, maxage: 123 }, true); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], 'Origin'); // static origin assert.is(headers['Access-Control-Allow-Origin'], 'https://foobar.com'); assert.is(headers['Access-Control-Expose-Headers'], 'X-My-Custom-Header,X-Another-Custom-Header'); assert.is(headers['Access-Control-Allow-Credentials'], 'true'); assert.is(headers['Access-Control-Max-Age'], '123'); assert.is(headers['Access-Control-Allow-Headers'], 'X-PINGOTHER,Content-Type'); assert.is(headers['Access-Control-Allow-Methods'], 'POST,PUT,DELETE'); }); headers('merge :: request', () => { let res = Response(); CORS.headers(res, { credentials: true, maxage: 0 }); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], undefined); // "*" default assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], 'true'); assert.is(headers['Access-Control-Max-Age'], undefined); // not preflight assert.is(headers['Access-Control-Allow-Headers'], undefined); // not preflight assert.is(headers['Access-Control-Allow-Methods'], undefined); // not preflight }); headers('merge :: preflight', () => { let res = Response(); CORS.headers(res, { credentials: true, maxage: 0 }, true); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], undefined); // "*" default assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], 'true'); assert.is(headers['Access-Control-Max-Age'], '0'); // allows 0 assert.is(headers['Access-Control-Allow-Headers'], undefined); assert.is(headers['Access-Control-Allow-Methods'], 'GET,HEAD,PUT,PATCH,POST,DELETE'); // default }); headers.run(); // --- const preflight = suite('preflight'); preflight('should be a function', () => { assert.type(CORS.preflight, 'function'); }); preflight('defaults :: standard', () => { let req=Request(), res=Response(); let handler = CORS.preflight(); assert.type(handler, 'function'); let out = handler(req, res); assert.is(out, undefined); let headers = Object.fromEntries(res.headers); assert.is(headers['Vary'], undefined); assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], undefined); assert.is(headers['Access-Control-Max-Age'], undefined); // preflight only assert.is(headers['Access-Control-Allow-Headers'], undefined); // preflight only assert.is(headers['Access-Control-Allow-Methods'], undefined); // preflight only // @ts-ignore - no response handler assert.is(res.body(), undefined); assert.is(res.statusCode, 0); }); preflight('defaults :: preflight', () => { let req = Request('OPTIONS'); let res = Response(); CORS.preflight()(req, res); let headers = Object.fromEntries(res.headers); // no headers config, must expect to be dynamic/varied assert.is(headers['Vary'], 'Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], '*'); assert.is(headers['Access-Control-Expose-Headers'], undefined); assert.is(headers['Access-Control-Allow-Credentials'], undefined); assert.is(headers['Access-Control-Max-Age'], undefined); // no value assert.is(headers['Access-Control-Allow-Headers'], undefined); // no value assert.is(headers['Access-Control-Allow-Methods'], 'GET,HEAD,PUT,PATCH,POST,DELETE'); // default // @ts-ignore assert.is(res.body(), null); assert.is(res.statusCode, 204); }); preflight('custom :: headers :: static', () => { let req = Request('OPTIONS'); let res = Response(); CORS.preflight({ headers: ['X-PINGOTHER', 'Content-Type'] })(req, res); let headers = Object.fromEntries(res.headers); // had static headers config assert.is(headers['Vary'], undefined); assert.is(headers['Access-Control-Allow-Headers'], 'X-PINGOTHER,Content-Type'); }); preflight('custom :: headers :: reflect', () => { let req = Request('OPTIONS'); let res = Response(); req.headers.set('Access-Control-Request-Headers', 'Content-Type'); CORS.preflight()(req, res); let headers = Object.fromEntries(res.headers); // no static headers config, must expect dynamic value assert.is(headers['Vary'], 'Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Headers'], 'Content-Type'); }); preflight('custom :: origin :: string', () => { let req = Request('OPTIONS'); let res = Response(); CORS.preflight({ origin: 'https://foobar.com' })(req, res); let headers = Object.fromEntries(res.headers); // no static headers config, must expect dynamic value (append) assert.is(headers['Vary'], 'Origin, Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], 'https://foobar.com'); assert.is(headers['Access-Control-Allow-Headers'], undefined); }); preflight('custom :: origin :: false ("*")', () => { let req = Request('OPTIONS'); let res = Response(); CORS.preflight({ origin: false })(req, res); let headers = Object.fromEntries(res.headers); // missing static headers config assert.is(headers['Vary'], 'Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], '*'); }); preflight('custom :: origin :: true (reflect)', () => { let req = Request('OPTIONS'); let res = Response(); req.headers.set('Origin', 'https://hello.com'); CORS.preflight({ origin: true })(req, res); let headers = Object.fromEntries(res.headers); // missing static headers config assert.is(headers['Vary'], 'Origin, Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], 'https://hello.com'); }); preflight('custom :: origin :: RegExp (pass)', () => { let req = Request('OPTIONS'); let res = Response(); req.headers.set('Origin', 'https://foobar.com'); CORS.preflight({ origin: /foobar/ })(req, res); let headers = Object.fromEntries(res.headers); // missing static headers config assert.is(headers['Vary'], 'Origin, Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], 'https://foobar.com'); }); preflight('custom :: origin :: RegExp (fail)', () => { let req = Request('OPTIONS'); let res = Response(); req.headers.set('Origin', 'https://foobar.com'); CORS.preflight({ origin: /hello/ })(req, res); let headers = Object.fromEntries(res.headers); // missing static headers config assert.is(headers['Vary'], 'Origin, Access-Control-Request-Headers'); assert.is(headers['Access-Control-Allow-Origin'], 'false'); }); preflight.run();
the_stack
import { actions, assign, createMachine, DoneInvokeEvent, send } from 'xstate' import type { Model } from 'xstate/lib/model.types' import { PersistenceBackendAPI, ProjectLoadResult, ProjectModel, ProjectWithFileChanges, } from './persistence-types' const { choose } = actions // Keep this file as simple as possible so that it can be used in https://stately.ai/viz // To use this in the visualiser, copy everything from the generic files into one, and call createPersistenceMachine(VisualiserBackend) interface NewEvent<ModelType> { type: 'NEW' projectModel: ProjectModel<ModelType> } export function newEvent<ModelType>(projectModel: ProjectModel<ModelType>): NewEvent<ModelType> { return { type: 'NEW', projectModel: projectModel, } } interface ProjectIdCreatedEvent { type: 'PROJECT_ID_CREATED' projectId: string } function projectIdCreatedEvent(projectId: string): ProjectIdCreatedEvent { return { type: 'PROJECT_ID_CREATED', projectId: projectId, } } interface NewProjectCreatedEvent<ModelType> { type: 'NEW_PROJECT_CREATED' projectId: string projectModel: ProjectModel<ModelType> } function newProjectCreatedEvent<ModelType>( projectId: string, projectModel: ProjectModel<ModelType>, ): NewProjectCreatedEvent<ModelType> { return { type: 'NEW_PROJECT_CREATED', projectId: projectId, projectModel: projectModel, } } interface LoadEvent { type: 'LOAD' projectId: string } export function loadEvent(projectId: string): LoadEvent { return { type: 'LOAD', projectId: projectId, } } interface LoadCompleteEvent<ModelType> { type: 'LOAD_COMPLETE' projectId: string projectModel: ProjectModel<ModelType> } function loadCompleteEvent<ModelType>( projectId: string, projectModel: ProjectModel<ModelType>, ): LoadCompleteEvent<ModelType> { return { type: 'LOAD_COMPLETE', projectId: projectId, projectModel: projectModel, } } interface LoadFailedEvent { type: 'LOAD_FAILED' } function loadFailedEvent(): LoadFailedEvent { return { type: 'LOAD_FAILED', } } export interface SaveEvent<ModelType> { type: 'SAVE' projectModel: ProjectModel<ModelType> } export function saveEvent<ModelType>(projectModel: ProjectModel<ModelType>): SaveEvent<ModelType> { return { type: 'SAVE', projectModel: projectModel, } } interface SaveCompleteEvent<ModelType, FileType> { type: 'SAVE_COMPLETE' saveResult: ProjectWithFileChanges<ModelType, FileType> } function saveCompleteEvent<ModelType, FileType>( saveResult: ProjectWithFileChanges<ModelType, FileType>, ): SaveCompleteEvent<ModelType, FileType> { return { type: 'SAVE_COMPLETE', saveResult: saveResult, } } interface InnerSaveEvent<ModelType> { type: 'INNER_SAVE' projectModel: ProjectModel<ModelType> } function innerSave<ModelType>(projectModel: ProjectModel<ModelType>): InnerSaveEvent<ModelType> { return { type: 'INNER_SAVE', projectModel: projectModel, } } interface ForkEvent { type: 'FORK' } export function forkEvent(): ForkEvent { return { type: 'FORK', } } interface DownloadAssetsCompleteEvent<ModelType, FileType> { type: 'DOWNLOAD_ASSETS_COMPLETE' downloadAssetsResult: ProjectWithFileChanges<ModelType, FileType> } function downloadAssetsCompleteEvent<ModelType, FileType>( downloadAssetsResult: ProjectWithFileChanges<ModelType, FileType>, ): DownloadAssetsCompleteEvent<ModelType, FileType> { return { type: 'DOWNLOAD_ASSETS_COMPLETE', downloadAssetsResult: downloadAssetsResult, } } interface CheckOwnershipCompleteEvent { type: 'CHECK_OWNERSHIP_COMPLETE' isOwner: boolean } function checkOwnershipCompleteEvent(isOwner: boolean): CheckOwnershipCompleteEvent { return { type: 'CHECK_OWNERSHIP_COMPLETE', isOwner: isOwner, } } type CoreEvent<ModelType, FileType> = | NewEvent<ModelType> | ProjectIdCreatedEvent | NewProjectCreatedEvent<ModelType> | LoadEvent | LoadCompleteEvent<ModelType> | LoadFailedEvent | CheckOwnershipCompleteEvent | SaveEvent<ModelType> | SaveCompleteEvent<ModelType, FileType> | ForkEvent | DownloadAssetsCompleteEvent<ModelType, FileType> | InnerSaveEvent<ModelType> interface BackendCreateProjectIdEvent { type: 'BACKEND_CREATE_PROJECT_ID' } function backendCreateProjectIdEvent(): BackendCreateProjectIdEvent { return { type: 'BACKEND_CREATE_PROJECT_ID', } } interface BackendDownloadAssetsEvent<ModelType> { type: 'BACKEND_DOWNLOAD_ASSETS' projectId: string projectModel: ProjectModel<ModelType> } function backendDownloadAssetsEvent<ModelType>( projectId: string, projectModel: ProjectModel<ModelType>, ): BackendDownloadAssetsEvent<ModelType> { return { type: 'BACKEND_DOWNLOAD_ASSETS', projectId: projectId, projectModel: projectModel, } } interface BackendServerSaveEvent<ModelType> { type: 'BACKEND_SERVER_SAVE' projectId: string projectModel: ProjectModel<ModelType> } function backendServerSaveEvent<ModelType>( projectId: string, projectModel: ProjectModel<ModelType>, ): BackendServerSaveEvent<ModelType> { return { type: 'BACKEND_SERVER_SAVE', projectId: projectId, projectModel: projectModel, } } interface BackendLocalSaveEvent<ModelType> { type: 'BACKEND_LOCAL_SAVE' projectId: string projectModel: ProjectModel<ModelType> } function backendLocalSaveEvent<ModelType>( projectId: string, projectModel: ProjectModel<ModelType>, ): BackendLocalSaveEvent<ModelType> { return { type: 'BACKEND_LOCAL_SAVE', projectId: projectId, projectModel: projectModel, } } interface BackendLoadEvent { type: 'BACKEND_LOAD' projectId: string } function backendLoadEvent(projectId: string): BackendLoadEvent { return { type: 'BACKEND_LOAD', projectId: projectId, } } interface BackendCheckOwnershipEvent { type: 'BACKEND_CHECK_OWNERSHIP' projectId: string } function backendCheckOwnershipEvent(projectId: string): BackendCheckOwnershipEvent { return { type: 'BACKEND_CHECK_OWNERSHIP', projectId: projectId, } } interface BackendErrorEvent { type: 'BACKEND_ERROR' message: string } function backendErrorEvent(message: string): BackendErrorEvent { return { type: 'BACKEND_ERROR', message: message, } } type BackendEvent<ModelType> = | BackendCreateProjectIdEvent | BackendDownloadAssetsEvent<ModelType> | BackendServerSaveEvent<ModelType> | BackendLocalSaveEvent<ModelType> | BackendLoadEvent | BackendCheckOwnershipEvent | BackendErrorEvent interface UserLogInEvent { type: 'USER_LOG_IN' } export function userLogInEvent(): UserLogInEvent { return { type: 'USER_LOG_IN', } } interface UserLogOutEvent { type: 'USER_LOG_OUT' } export function userLogOutEvent(): UserLogOutEvent { return { type: 'USER_LOG_OUT', } } type UserEvent = UserLogInEvent | UserLogOutEvent export type PersistenceEvent<ModelType, FileType> = | CoreEvent<ModelType, FileType> | BackendEvent<ModelType> | UserEvent export interface PersistenceContext<ModelType> { projectId?: string project?: ProjectModel<ModelType> queuedSave?: ProjectModel<ModelType> projectOwned: boolean loggedIn: boolean } // Core States export const Empty = 'empty' export const Ready = 'ready' export const CreatingNew = 'creating' export const Loading = 'loading' export const Saving = 'saving' export const Forking = 'forking' // InternalCreatingNewStates export const CreatingProjectId = 'creating-project-id' export const ProjectCreated = 'project-created' // InternalLoadingStates export const LoadingProject = 'loading-project' export const CheckingOwnership = 'checking-ownership' export const ProjectLoaded = 'project-loaded' // InternalForkingStates export const DownloadingAssets = 'downloading-assets' export const ProjectForked = 'project-forked' // Backend States export const BackendIdle = 'idle' export const BackendCreatingProjectId = 'creating-project-id' export const BackendCheckingOwnership = 'checking-ownership' export const BackendDownloadingAssets = 'downloading-assets' export const BackendServerSaving = 'server-saving' export const BackendLocalSaving = 'local-saving' export const BackendLoading = 'loading' // User States export const LoggedOut = 'logged-out' export const LoggedIn = 'logged-in' export function createPersistenceMachine<ModelType, FileType>( backendAPI: PersistenceBackendAPI<ModelType, FileType>, ) { const queuePush = assign<PersistenceContext<ModelType>, SaveEvent<ModelType>>( (_context, event) => { return { queuedSave: event.projectModel, } }, ) const checkQueue = choose<PersistenceContext<ModelType>, PersistenceEvent<ModelType, FileType>>([ { cond: (context) => context.queuedSave != null, actions: send((context) => saveEvent(context.queuedSave!)), }, ]) // The queue clearing has to be handled separately as assign actions are batched and handled before other actions // until xstate v5: https://xstate.js.org/docs/guides/actions.html#action-order const queueClear = assign<PersistenceContext<ModelType>, PersistenceEvent<ModelType, FileType>>({ queuedSave: undefined, }) const logError = ( context: PersistenceContext<ModelType>, event: PersistenceEvent<ModelType, FileType>, ) => { if (event.type === 'BACKEND_ERROR') { console.error(event.message) } } return createMachine< Model<PersistenceContext<ModelType>, PersistenceEvent<ModelType, FileType>>, PersistenceContext<ModelType>, PersistenceEvent<ModelType, FileType> >( { id: 'persistence-parallel', type: 'parallel', context: { projectOwned: false, loggedIn: false }, states: { // Backend Communication backend: { id: 'backend', initial: BackendIdle, states: { [BackendIdle]: { on: { BACKEND_CREATE_PROJECT_ID: BackendCreatingProjectId, BACKEND_CHECK_OWNERSHIP: BackendCheckingOwnership, BACKEND_DOWNLOAD_ASSETS: BackendDownloadingAssets, BACKEND_SERVER_SAVE: BackendServerSaving, BACKEND_LOCAL_SAVE: BackendLocalSaving, BACKEND_LOAD: BackendLoading, }, }, [BackendCreatingProjectId]: { invoke: { id: 'create-project-id', src: 'getNewProjectId', onDone: { target: BackendIdle, actions: [ send((_, event: DoneInvokeEvent<string>) => projectIdCreatedEvent(event.data)), ], }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, [BackendCheckingOwnership]: { invoke: { id: 'check-ownership', src: 'checkProjectOwned', onDone: { target: BackendIdle, actions: [ send((_, event: DoneInvokeEvent<boolean>) => checkOwnershipCompleteEvent(event.data), ), ], }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, [BackendDownloadingAssets]: { invoke: { id: 'download-assets', src: 'downloadAssets', onDone: { target: BackendIdle, actions: [ send((_, event: DoneInvokeEvent<ProjectWithFileChanges<ModelType, FileType>>) => downloadAssetsCompleteEvent(event.data), ), ], }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, [BackendServerSaving]: { invoke: { id: 'server-save-project', src: 'saveProjectToServer', onDone: { target: BackendIdle, actions: send( (_, event: DoneInvokeEvent<ProjectWithFileChanges<ModelType, FileType>>) => saveCompleteEvent(event.data), ), }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, [BackendLocalSaving]: { invoke: { id: 'local-save-project', src: 'saveProjectLocally', onDone: { target: BackendIdle, actions: send( (_, event: DoneInvokeEvent<ProjectWithFileChanges<ModelType, FileType>>) => saveCompleteEvent(event.data), ), }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, [BackendLoading]: { invoke: { id: 'load-project', src: 'loadProject', onDone: { target: BackendIdle, actions: [ send((_, event: DoneInvokeEvent<ProjectLoadResult<ModelType>>) => { if (event.data.type === 'PROJECT_LOAD_SUCCESS') { return loadCompleteEvent(event.data.projectId, event.data.projectModel) } else { return loadFailedEvent() } }), ], }, onError: { target: BackendIdle, actions: send((_, event) => backendErrorEvent(event.data)), }, }, }, }, }, // User Log In State user: { id: 'user', initial: LoggedOut, states: { [LoggedOut]: { on: { USER_LOG_IN: { target: LoggedIn, actions: assign({ loggedIn: (_context, _event) => true }), }, }, }, [LoggedIn]: { on: { USER_LOG_OUT: { target: LoggedOut, actions: assign({ loggedIn: (_context, _event) => false }), }, }, }, }, }, // Core Machine core: { id: 'persistence-core', initial: Empty, states: { // Idle states [Empty]: { on: { NEW: CreatingNew, LOAD: Loading, }, }, [Ready]: { entry: checkQueue, exit: queueClear, on: { NEW: CreatingNew, LOAD: Loading, SAVE: [ { cond: (context, _) => context.projectOwned, target: Saving, }, { target: Forking }, ], FORK: Forking, USER_LOG_IN: [ { cond: (context, _) => context.projectOwned, actions: send((context, _) => saveEvent(context.project!)), }, ], }, }, // Intermediate states [CreatingNew]: { initial: CreatingProjectId, states: { [CreatingProjectId]: { entry: [ assign((_, event) => { return { projectId: undefined, project: (event as NewEvent<ModelType>).projectModel, queuedSave: undefined, projectOwned: true, } }), send(backendCreateProjectIdEvent()), ], on: { PROJECT_ID_CREATED: { actions: [ assign({ projectId: (_, event) => event.projectId }), send((context, event) => newProjectCreatedEvent(event.projectId, context.project!), ), ], }, NEW_PROJECT_CREATED: ProjectCreated, }, }, [ProjectCreated]: { type: 'final' }, }, onDone: { actions: send((context, _) => innerSave(context.project!)), }, on: { INNER_SAVE: Saving, SAVE: { actions: queuePush, }, BACKEND_ERROR: { target: Ready, actions: logError, }, }, }, [Loading]: { initial: LoadingProject, states: { [LoadingProject]: { entry: choose([ { cond: (_, event) => event.type === 'LOAD', actions: send((_, event) => backendLoadEvent((event as LoadEvent).projectId)), }, ]), on: { LOAD_COMPLETE: { target: CheckingOwnership, actions: assign((_, event) => { return { projectId: event.projectId, project: event.projectModel, queuedSave: undefined, } }), }, }, }, [CheckingOwnership]: { entry: send((context, _) => backendCheckOwnershipEvent(context.projectId!)), on: { CHECK_OWNERSHIP_COMPLETE: { target: ProjectLoaded, actions: assign({ projectOwned: (_, event) => event.isOwner, }), }, }, }, [ProjectLoaded]: { type: 'final' }, }, onDone: Ready, on: { BACKEND_ERROR: { target: Ready, actions: logError, }, LOAD_FAILED: { target: Empty, actions: assign((_context, _event) => { return { projectId: undefined, project: undefined, queuedSave: undefined, projectOwned: false, } }), }, }, }, [Saving]: { entry: choose([ { cond: (context, _) => context.loggedIn, actions: send((context, event) => backendServerSaveEvent( context.projectId!, (event as SaveEvent<ModelType>).projectModel, ), ), }, { actions: send((context, event) => backendLocalSaveEvent( context.projectId!, (event as SaveEvent<ModelType>).projectModel, ), ), }, ]), on: { SAVE: { actions: queuePush, }, SAVE_COMPLETE: { target: Ready, actions: assign((_context, event) => { return { projectOwned: true, project: event.saveResult.projectModel, } }), }, BACKEND_ERROR: { target: Ready, actions: logError, }, }, }, [Forking]: { initial: DownloadingAssets, states: { [DownloadingAssets]: { entry: choose([ { cond: (context, _) => context.project != null && context.projectId != null, actions: send((context, _) => backendDownloadAssetsEvent(context.projectId!, context.project!), ), }, ]), on: { DOWNLOAD_ASSETS_COMPLETE: { target: CreatingProjectId, actions: assign({ project: (_, event) => { return { name: `${event.downloadAssetsResult.projectModel.name} (forked)`, content: event.downloadAssetsResult.projectModel.content, } }, }), }, }, }, [CreatingProjectId]: { entry: send(backendCreateProjectIdEvent()), on: { PROJECT_ID_CREATED: { target: ProjectForked, actions: assign({ projectId: (_, event) => event.projectId, }), }, }, }, [ProjectForked]: { type: 'final' }, }, onDone: { actions: [send((context, _) => innerSave(context.project!))], }, on: { INNER_SAVE: Saving, SAVE: { actions: queuePush, }, BACKEND_ERROR: { target: Ready, actions: logError, }, }, }, }, }, }, }, { services: { getNewProjectId: backendAPI.getNewProjectId, checkProjectOwned: (_, event) => { if (event.type === 'BACKEND_CHECK_OWNERSHIP') { return backendAPI.checkProjectOwned(event.projectId) } else { throw new Error( `Incorrect event type triggered check ownership, ${JSON.stringify(event)}`, ) } }, downloadAssets: (_, event) => { if (event.type === 'BACKEND_DOWNLOAD_ASSETS') { return backendAPI.downloadAssets(event.projectId, event.projectModel) } else { throw new Error( `Incorrect event type triggered asset download, ${JSON.stringify(event)}`, ) } }, saveProjectToServer: (context, event) => { if ( event.type === 'BACKEND_SERVER_SAVE' && event.projectModel != null && context.projectId != null ) { return backendAPI.saveProjectToServer(context.projectId, event.projectModel) } else { throw new Error( `Unable to save project with ID ${context.projectId} after event ${JSON.stringify( event, )}`, ) } }, saveProjectLocally: (context, event) => { if ( event.type === 'BACKEND_LOCAL_SAVE' && event.projectModel != null && context.projectId != null ) { return backendAPI.saveProjectLocally(context.projectId, event.projectModel) } else { throw new Error( `Unable to save project with ID ${context.projectId} after event ${JSON.stringify( event, )}`, ) } }, loadProject: (_, event) => { if (event.type === 'BACKEND_LOAD') { return backendAPI.loadProject(event.projectId) } else { throw new Error(`Invalid event type triggered project load ${JSON.stringify(event)}`) } }, }, }, ) }
the_stack
import { Range, TextEditorDecorationType, ThemableDecorationRenderOptions, ThemeColor, window } from "vscode"; export interface VimHighlightUIAttributes { foreground?: number; background?: number; special?: number; reverse?: boolean; italic?: boolean; bold?: boolean; strikethrough?: boolean; // has special color underline?: boolean; // has special color undercurl?: boolean; blend?: number; } export interface HighlightConfiguration { /** * Ignore highlights */ ignoreHighlights: string[]; /** * What to do on unknown highlights. Either accept vim or use vscode decorator configuration */ unknownHighlight: "vim" | ThemableDecorationRenderOptions; /** * Map specific highlight to use either vim configuration or use vscode decorator configuration */ highlights: { [key: string]: "vim" | ThemableDecorationRenderOptions; }; } /** * Convert VIM HL attributes to vscode text decoration attributes * @param uiAttrs VIM UI attribute * @param vimSpecialColor Vim special color */ function vimHighlightToVSCodeOptions(uiAttrs: VimHighlightUIAttributes): ThemableDecorationRenderOptions { const options: ThemableDecorationRenderOptions = {}; // for absent color keys color should not be changed if (uiAttrs.background) { options.backgroundColor = "#" + uiAttrs.background.toString(16); } if (uiAttrs.foreground) { options.color = "#" + uiAttrs.foreground.toString(16); } const specialColor = uiAttrs.special ? "#" + uiAttrs.special.toString(16) : ""; if (uiAttrs.reverse) { options.backgroundColor = new ThemeColor("editor.foreground"); options.color = new ThemeColor("editor.background"); } if (uiAttrs.italic) { options.fontStyle = "italic"; } if (uiAttrs.bold) { options.fontWeight = "bold"; } if (uiAttrs.strikethrough) { options.textDecoration = "line-through solid"; } if (uiAttrs.underline) { options.textDecoration = `underline ${specialColor} solid`; } if (uiAttrs.undercurl) { options.textDecoration = `underline ${specialColor} wavy`; } return options; } function isEditorThemeColor(s: string | ThemeColor | undefined): s is string { return typeof s === "string" && s.startsWith("theme."); } function normalizeDecorationConfig(config: ThemableDecorationRenderOptions): ThemableDecorationRenderOptions { const newConfig: ThemableDecorationRenderOptions = { ...config, after: config.after ? { ...config.after } : undefined, before: config.before ? { ...config.before } : undefined, }; if (isEditorThemeColor(newConfig.backgroundColor)) { newConfig.backgroundColor = new ThemeColor(newConfig.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.borderColor)) { newConfig.borderColor = new ThemeColor(newConfig.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.color)) { newConfig.borderColor = new ThemeColor(newConfig.color.slice(6)); } if (isEditorThemeColor(newConfig.outlineColor)) { newConfig.outlineColor = new ThemeColor(newConfig.outlineColor.slice(6)); } if (isEditorThemeColor(newConfig.overviewRulerColor)) { newConfig.overviewRulerColor = new ThemeColor(newConfig.overviewRulerColor.slice(6)); } if (newConfig.after) { if (isEditorThemeColor(newConfig.after.backgroundColor)) { newConfig.after.backgroundColor = new ThemeColor(newConfig.after.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.after.borderColor)) { newConfig.after.borderColor = new ThemeColor(newConfig.after.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.after.color)) { newConfig.after.color = new ThemeColor(newConfig.after.color.slice(6)); } } if (newConfig.before) { if (isEditorThemeColor(newConfig.before.backgroundColor)) { newConfig.before.backgroundColor = new ThemeColor(newConfig.before.backgroundColor.slice(6)); } if (isEditorThemeColor(newConfig.before.borderColor)) { newConfig.before.borderColor = new ThemeColor(newConfig.before.borderColor.slice(6)); } if (isEditorThemeColor(newConfig.before.color)) { newConfig.before.color = new ThemeColor(newConfig.before.color.slice(6)); } } return newConfig; } export class HighlightProvider { /** * Current HL. key is the grid id and values is two dimension array representing rows and cols. Array may contain empty values */ private highlights: Map<number, number[][]> = new Map(); private prevGridHighlightsIds: Map<number, Set<string>> = new Map(); /** * Maps highlight id to highlight group name */ private highlightIdToGroupName: Map<number, string> = new Map(); /** * HL group name to text decorator * Not all HL groups are supported now */ private highlighGroupToDecorator: Map<string, TextEditorDecorationType> = new Map(); /** * Store configuration per decorator */ private decoratorConfigurations: Map<TextEditorDecorationType, ThemableDecorationRenderOptions> = new Map(); private configuration: HighlightConfiguration; /** * Set of ignored HL group ids. They can still be used with force flag (mainly for statusbar color decorations) */ private ignoredGroupIds: Set<number> = new Set(); /** * List of always ignored groups */ private alwaysIgnoreGroups = [ "Normal", "NormalNC", "NormalFloat", "NonText", "SpecialKey", "TermCursor", "TermCursorNC", "Cursor", "lCursor", "VisualNC", // "Visual", "Conceal", "CursorLine", "CursorLineNr", "ColorColumn", "LineNr", "StatusLine", "StatusLineNC", "VertSplit", "Title", "WildMenu", "Whitespace", ]; public constructor(conf: HighlightConfiguration) { this.configuration = conf; if (this.configuration.unknownHighlight !== "vim") { this.configuration.unknownHighlight = normalizeDecorationConfig(this.configuration.unknownHighlight); } for (const [key, config] of Object.entries(this.configuration.highlights)) { if (config !== "vim") { const options = normalizeDecorationConfig(config); this.configuration.highlights[key] = options; // precreate groups if configuration was defined this.createDecoratorForHighlightGroup(key, options); } } } public addHighlightGroup(id: number, name: string, vimUiAttrs: VimHighlightUIAttributes): void { if ( this.configuration.ignoreHighlights.includes(name) || this.configuration.ignoreHighlights.find((i) => i.startsWith("^") || i.endsWith("$") ? new RegExp(i).test(name) : false, ) ) { this.ignoredGroupIds.add(id); } this.highlightIdToGroupName.set(id, name); if (this.highlighGroupToDecorator.has(name)) { // we have already precreated decorator return; } else { const options = this.configuration.highlights[name] || this.configuration.unknownHighlight; const conf = options === "vim" ? vimHighlightToVSCodeOptions(vimUiAttrs) : options; this.createDecoratorForHighlightGroup(name, conf); } } public getHighlightGroupName(id: number, force = false): string | undefined { if (this.ignoredGroupIds.has(id) && !force) { return; } const name = this.highlightIdToGroupName.get(id); if (name && this.alwaysIgnoreGroups.includes(name)) { return; } return name; } public getDecoratorForHighlightGroup(name: string): TextEditorDecorationType | undefined { let dec = this.highlighGroupToDecorator.get(name); if (!dec && name.endsWith("Default")) { dec = this.highlighGroupToDecorator.get(name.slice(0, -7)); } if (!dec) { dec = this.highlighGroupToDecorator.get(name + "Default"); } return dec; } public getDecoratorOptions(decorator: TextEditorDecorationType): ThemableDecorationRenderOptions { return this.decoratorConfigurations.get(decorator)!; } public cleanRow(grid: number, row: number): void { const gridHl = this.highlights.get(grid); if (!gridHl) { return; } delete gridHl[row]; } public processHLCellsEvent( grid: number, row: number, start: number, external: boolean, cells: [string, number?, number?][], ): boolean { let cellHlId = 0; let cellIdx = start; if (!this.highlights.has(grid)) { this.highlights.set(grid, []); } const gridHl = this.highlights.get(grid)!; let hasUpdates = false; for (const [text, hlId, repeat] of cells) { // 2+bytes chars (such as chinese characters) have "" as second cell if (text === "") { continue; } // tab fill character if (text === "♥") { continue; } if (hlId != null) { cellHlId = hlId; } const groupName = this.getHighlightGroupName(cellHlId, external); const repeatTo = text === "\t" || text === "❥" ? 1 : repeat || 1; // const repeatTo = // text === "\t" || line[cellIdx] === "\t" ? Math.ceil((repeat || tabSize) / tabSize) : repeat || 1; for (let i = 0; i < repeatTo; i++) { if (!gridHl[row]) { gridHl[row] = []; } if (groupName) { hasUpdates = true; gridHl[row][cellIdx] = cellHlId; } else if (gridHl[row][cellIdx]) { hasUpdates = true; delete gridHl[row][cellIdx]; } cellIdx++; } } return hasUpdates; } public shiftGridHighlights(grid: number, by: number, from: number): void { const gridHl = this.highlights.get(grid); if (!gridHl) { return; } if (by > 0) { // remove clipped out rows for (let i = 0; i < by; i++) { delete gridHl[from + i]; } // first get non empty indexes, then process, seems faster than iterating whole array const idxs: number[] = []; gridHl.forEach((_row, idx) => { idxs.push(idx); }); // shift for (const idx of idxs) { if (idx <= from) { continue; } gridHl[idx - by] = gridHl[idx]; delete gridHl[idx]; } } else if (by < 0) { // remove clipped out rows for (let i = 0; i < Math.abs(by); i++) { delete gridHl[from !== 0 ? from + i : gridHl.length - 1 - i]; } const idxs: number[] = []; gridHl.forEach((_row, idx) => { idxs.push(idx); }); for (const idx of idxs.reverse()) { if (idx <= from) { continue; } gridHl[idx + Math.abs(by)] = gridHl[idx]; delete gridHl[idx]; } } } public getGridHighlights(grid: number, topLine: number): [TextEditorDecorationType, Range[]][] { const result: [TextEditorDecorationType, Range[]][] = []; const hlRanges: Map<string, Array<{ lineS: number; lineE: number; colS: number; colE: number }>> = new Map(); const gridHl = this.highlights.get(grid); if (gridHl) { // let currHlId = 0; let currHlName = ""; let currHlStartRow = 0; let currHlEndRow = 0; let currHlStartCol = 0; let currHlEndCol = 0; // forEach faster than for in/of for arrays while iterating on array with empty values gridHl.forEach((rowHighlights, rowIdx) => { rowHighlights.forEach((cellHlId, cellIdx) => { const cellHlName = this.highlightIdToGroupName.get(cellHlId); if ( cellHlName && currHlName === cellHlName && // allow to extend prev HL if on same row and next cell OR previous row and end of range is end col currHlEndRow === rowIdx && currHlEndCol === cellIdx - 1 ) { currHlEndCol = cellIdx; } else { if (currHlName) { if (!hlRanges.has(currHlName)) { hlRanges.set(currHlName, []); } hlRanges.get(currHlName)!.push({ lineS: currHlStartRow, lineE: currHlEndRow, colS: currHlStartCol, colE: currHlEndCol, }); currHlName = ""; currHlStartCol = 0; currHlEndCol = 0; currHlStartRow = 0; currHlEndRow = 0; } if (cellHlName) { currHlName = cellHlName; currHlStartRow = rowIdx; currHlEndRow = rowIdx; currHlStartCol = cellIdx; currHlEndCol = cellIdx; } } }); }); if (currHlName) { if (!hlRanges.has(currHlName)) { hlRanges.set(currHlName, []); } hlRanges.get(currHlName)!.push({ lineS: currHlStartRow, lineE: currHlEndRow, colS: currHlStartCol, colE: currHlEndCol, }); } } for (const [groupName, ranges] of hlRanges) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (!decorator) { continue; } const decoratorRanges = ranges.map( (r) => new Range(topLine + r.lineS, r.colS, topLine + r.lineE, r.colE + 1), ); result.push([decorator, decoratorRanges]); } const prevHighlights = this.prevGridHighlightsIds.get(grid); if (prevHighlights) { for (const groupName of prevHighlights) { if (!hlRanges.has(groupName)) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (!decorator) { continue; } result.push([decorator, []]); } } } this.prevGridHighlightsIds.set(grid, new Set(hlRanges.keys())); return result; } public clearHighlights(grid: number): [TextEditorDecorationType, Range[]][] { const prevHighlights = this.prevGridHighlightsIds.get(grid); this.highlights.delete(grid); this.prevGridHighlightsIds.delete(grid); if (!prevHighlights) { return []; } const result: [TextEditorDecorationType, Range[]][] = []; for (const groupName of prevHighlights) { const decorator = this.getDecoratorForHighlightGroup(groupName); if (decorator) { result.push([decorator, []]); } } return result; } private createDecoratorForHighlightGroup(groupName: string, options: ThemableDecorationRenderOptions): void { const decorator = window.createTextEditorDecorationType(options); this.decoratorConfigurations.set(decorator, options); this.highlighGroupToDecorator.set(groupName, decorator); } }
the_stack
import m from 'mithril'; import h from './h'; import _ from 'underscore'; import c from './c'; import Chart from 'chart.js'; import { Wrap } from './wrap'; import { AdminWrap } from './admin-wrap'; m.originalTrust = m.trust; m.trust = (text) => h.trust(text); (function () { window.m = m; h.SentryInitSDK(); history.pushState = h.attachEventsToHistory('pushState'); history.replaceState = h.attachEventsToHistory('replaceState'); /// Setup an AUTO-SCROLL TOP when change route const pushState = history.pushState; history.pushState = function () { if (typeof window.history.onpushstate == 'function') { window.history.onpushstate.apply(history, arguments); } pushState.apply(history, arguments); h.scrollTop(); }; Chart.defaults.global.responsive = true; Chart.defaults.global.responsive = false; Chart.defaults.global.scaleFontFamily = 'proxima-nova'; // NOTE: comment when need to use multilanguage i18n support window.I18n.defaultLocale = 'pt'; window.I18n.locale = 'pt'; const adminRoot = document.getElementById('new-admin'); if (adminRoot) { m.route.prefix('#'); m.route(adminRoot, '/', { '/': AdminWrap(c.root.AdminContributions, { root: adminRoot, menuTransparency: false, hideFooter: true }), '/home-banners': AdminWrap(c.root.AdminHomeBanners, { menuTransparency: false, hideFooter: true }), '/users': AdminWrap(c.root.AdminUsers, { menuTransparency: false, hideFooter: true }), '/subscriptions': AdminWrap(c.root.AdminSubscriptions, { menuTransparency: false, hideFooter: true }), '/projects': AdminWrap(c.root.AdminProjects, { menuTransparency: false, hideFooter: true }), '/notifications': AdminWrap(c.root.AdminNotifications, { menuTransparency: false, hideFooter: true }), '/balance-transfers': AdminWrap(c.root.AdminBalanceTranfers, { menuTransparency: false, hideFooter: true }), }); } const app = document.getElementById('application'), body = document.body; const urlWithLocale = function (url) { return `/${window.I18n.locale}${url}`; }; if (app) { const rootEl = app, isUserProfile = body.getAttribute('data-controller-name') == 'users' && body.getAttribute('data-action') == 'show' && app.getAttribute('data-hassubdomain') == 'true'; m.route.prefix(''); /** * Contribution/Subscription flow. * * ProjectShow -> * contribution: ProjectsContribution -> ProjectsPayment -> ThankYou * subscription: ProjectsSubscriptionContribution -> ProjectsSubscriptionCheckout -> ProjectsSubscriptionThankYou */ tryMountingRoutes(); let mountingRetries = 3; function tryMountingRoutes() { try { mountRoutes(); mountingRetries = 3; } catch (error) { if (mountingRetries > 0) { h.captureException(error); app.innerHTML = ''; // gets out of recursion setTimeout(tryMountingRoutes); mountingRetries -= 1; } else { console.error('Could not mount the route.'); } } } function mountRoutes() { m.route(rootEl, '/', { '/': Wrap(isUserProfile ? c.root.UsersShow : c.root.ProjectsHome, { menuTransparency: true, footerBig: true, absoluteHome: isUserProfile }), '/explore': Wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }), '/start': Wrap(c.root.Start, { menuTransparency: true, footerBig: true }), '/start-sub': Wrap(c.root.SubProjectNew, { menuTransparency: false }), '/projects/:project_id/contributions/new': Wrap(c.root.ProjectsContribution), '/projects/:project_id/contributions/fallback_create': Wrap(c.root.ProjectsContribution), '/projects/:project_id/contributions/:contribution_id/edit': Wrap(c.root.ProjectsPayment, { menuShort: true }), '/projects/:project_id/subscriptions/start': Wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }), '/projects/:project_id/subscriptions/checkout': Wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }), '/projects/:project_id/subscriptions/thank_you': Wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }), [urlWithLocale('/projects/:project_id/contributions/new')]: Wrap(c.root.ProjectsContribution), [urlWithLocale('/projects/:project_id/contributions/:contribution_id/edit')]: Wrap(c.root.ProjectsPayment, { menuShort: true }), [urlWithLocale('/projects/:project_id/subscriptions/start')]: Wrap(c.root.ProjectsSubscriptionContribution, { menuShort: true, footerBig: false }), [urlWithLocale('/projects/:project_id/subscriptions/checkout')]: Wrap(c.root.ProjectsSubscriptionCheckout, { menuShort: true, footerBig: false }), [urlWithLocale('/projects/subscriptions/thank_you')]: Wrap(c.root.ProjectsSubscriptionThankYou, { menuShort: true, footerBig: false }), '/en': Wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }), '/pt': Wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }), [urlWithLocale('/flexible_projects')]: Wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }), [urlWithLocale('/projects')]: Wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }), '/projects': Wrap(c.root.ProjectsHome, { menuTransparency: true, footerBig: true }), [urlWithLocale('/explore')]: Wrap(c.root.ProjectsExplore, { menuTransparency: true, footerBig: true }), [urlWithLocale('/start')]: Wrap(c.root.Start, { menuTransparency: true, footerBig: true }), [urlWithLocale('/projects/:project_id/contributions/:contribution_id')]: Wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }), '/projects/:project_id/contributions/:contribution_id': Wrap(c.root.ThankYou, { menuTransparency: false, footerBig: false }), '/projects/:project_id/insights': Wrap(c.root.Insights, { menuTransparency: false, footerBig: false }), [urlWithLocale('/projects/:project_id/insights')]: Wrap(c.root.Insights, { menuTransparency: false, footerBig: false }), '/projects/:project_id/coming-soon': Wrap(c.root.ComingSoon, { menuTransparency: false, footerBig: false }), [urlWithLocale('/projects/:project_id/coming-soon')]: Wrap(c.root.ComingSoon, { menuTransparency: false, footerBig: false }), '/projects/:project_id/contributions_report': Wrap(c.root.ProjectsContributionReport, { menuTransparency: false, footerBig: false }), [urlWithLocale('/projects/:project_id/contributions_report')]: Wrap(c.root.ProjectsContributionReport, { menuTransparency: false, footerBig: false, }), '/projects/:project_id/subscriptions_report': Wrap(c.root.ProjectsSubscriptionReport, { menuTransparency: false, footerBig: false }), [urlWithLocale('/projects/:project_id/subscriptions_report')]: Wrap(c.root.ProjectsSubscriptionReport, { menuTransparency: false, footerBig: false, }), '/projects/:project_id/subscriptions_report_download': Wrap(c.root.ProjectsSubscriptionReportDownload, { menuTransparency: false, footerBig: false, }), [urlWithLocale('/projects/:project_id/subscriptions_report_download')]: Wrap(c.root.ProjectsSubscriptionReportDownload, { menuTransparency: false, footerBig: false, }), '/projects/:project_id/surveys': Wrap(c.root.Surveys, { menuTransparency: false, footerBig: false, menuShort: true }), '/projects/:project_id/fiscal': Wrap(c.root.ProjectsFiscal, { menuTransparency: false, footerBig: false, menuShort: true }), '/projects/:project_id/posts': Wrap(c.root.Posts, { menuTransparency: false, footerBig: false }), '/projects/:project_id/posts/:post_id': Wrap(c.root.ProjectShow, { menuTransparency: false, footerBig: true }), [urlWithLocale('/projects/:project_id/posts')]: Wrap(c.root.Posts, { menuTransparency: false, footerBig: false }), [urlWithLocale('/projects/:project_id/posts/:post_id')]: Wrap(c.root.ProjectShow, { menuTransparency: false, footerBig: true }), '/projects/:project_id': Wrap(c.root.ProjectShow, { menuTransparency: false, footerBig: false }), '/users/:user_id': Wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }), [urlWithLocale('/users/:user_id')]: Wrap(c.root.UsersShow, { menuTransparency: true, footerBig: false }), '/contributions/:contribution_id/surveys/:survey_id': Wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }), [urlWithLocale('/contributions/:contribution_id/surveys/:survey_id')]: Wrap(c.root.SurveysShow, { menuTransparency: false, footerBig: false }), '/users/:user_id/edit': Wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }), [urlWithLocale('/users/:user_id/edit')]: Wrap(c.root.UsersEdit, { menuTransparency: true, footerBig: false }), '/projects/:project_id/edit': Wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }), [urlWithLocale('/projects/:project_id/edit')]: Wrap(c.root.ProjectEdit, { menuTransparency: false, hideFooter: true, menuShort: true }), '/projects/:project_id/rewards/:reward_id/surveys/new': Wrap(c.root.SurveyCreate, { menuTransparency: false, hideFooter: true, menuShort: true }), [urlWithLocale('/follow-fb-friends')]: Wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }), '/follow-fb-friends': Wrap(c.root.FollowFoundFriends, { menuTransparency: false, footerBig: false }), [urlWithLocale('/:project')]: Wrap(c.root.ProjectShow, { menuTransparency: false, footerBig: false }), '/:project': Wrap(c.root.ProjectShow, { menuTransparency: false, footerBig: false }), [urlWithLocale('/team')]: Wrap(c.root.Team, { menuTransparency: true, footerBig: true }), '/team': Wrap(c.root.Team, { menuTransparency: true, footerBig: true }), [urlWithLocale('/jobs')]: Wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }), '/jobs': Wrap(c.root.Jobs, { menuTransparency: true, footerBig: true }), '/press': Wrap(c.root.Press, { menuTransparency: true, footerBig: true }), [urlWithLocale('/press')]: Wrap(c.root.Press, { menuTransparency: true, footerBig: true }), [urlWithLocale('/projects/:project_id/publish')]: Wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }), ['/projects/:project_id/publish']: Wrap(c.root.Publish, { menuTransparency: false, hideFooter: true, menuShort: true }), [urlWithLocale('/projects/:project_id/publish-by-steps')]: Wrap(c.root.ProjectsPublishBySteps, { menuTransparency: false, hideFooter: true, menuShort: true }), ['/projects/:project_id/publish-by-steps']: Wrap(c.root.ProjectsPublishBySteps, { menuTransparency: false, hideFooter: true, menuShort: true }), }); } } })();
the_stack
import AppDispatcher from "../../events/AppDispatcher"; import SystemLogActions from "../SystemLogActions"; import { RequestUtil } from "mesosphere-shared-reactjs"; import * as ActionTypes from "../../constants/ActionTypes"; import Config from "#SRC/js/config/Config"; let thisEventSource, thisMessageSpy, thisConfiguration; describe("SystemLogActions", () => { beforeEach(() => { // Mock EventSource thisEventSource = new window.EventSource(); spyOn(global, "EventSource").and.returnValue(thisEventSource); }); afterEach(() => { thisEventSource.close(); }); describe("#startTail", () => { beforeEach(() => { SystemLogActions.startTail("foo", { cursor: "bar", subscriptionID: "subscriptionID", }); }); it("calls #addEventListener from the window.EventSource", () => { thisEventSource.addEventListener = jasmine .createSpy("addEventListener") .and.callThrough(); SystemLogActions.startTail("foo", { cursor: "bar" }); expect(thisEventSource.addEventListener).toHaveBeenCalled(); }); it("fetches data from the correct URL", () => { const mostRecent = window.EventSource.calls.mostRecent(); expect(mostRecent.args[0]).toEqual( "/system/v1/agent/foo/logs/v1/stream/?cursor=bar" ); }); it("dispatches the correct action when successful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual(ActionTypes.REQUEST_SYSTEM_LOG_SUCCESS); }); const event = { data: "{}", eventPhase: window.EventSource.OPEN, origin: window.location.origin, }; thisEventSource.dispatchEvent("message", event); }); it("dispatches the correct information when successful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual([{}]); expect(action.subscriptionID).toEqual("subscriptionID"); }); const event = { data: "{}", eventPhase: window.EventSource.OPEN, origin: window.location.origin, }; thisEventSource.dispatchEvent("message", event); }); it("dispatches the correct action when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual(ActionTypes.REQUEST_SYSTEM_LOG_ERROR); }); thisEventSource.dispatchEvent("error", {}); }); it("dispatches the correct information when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual({}); expect(action.subscriptionID).toEqual("subscriptionID"); }); thisEventSource.dispatchEvent("error", {}); }); }); describe("#stopTail", () => { beforeEach(() => { SystemLogActions.startTail("foo", { cursor: "bar", subscriptionID: "subscriptionID", }); }); it("calls #close on the EventSource", () => { thisEventSource.close = jasmine.createSpy("close"); SystemLogActions.stopTail("subscriptionID"); expect(thisEventSource.close).toHaveBeenCalled(); }); it("unsubscribes event listeners on message", () => { thisMessageSpy = jasmine.createSpy("message"); thisEventSource.addEventListener("message", thisMessageSpy); SystemLogActions.stopTail("subscriptionID"); const event = { data: "{}", eventPhase: window.EventSource.OPEN, origin: window.location.origin, }; thisEventSource.dispatchEvent("message", event); expect(thisMessageSpy).not.toHaveBeenCalled(); }); }); describe("#fetchRange", () => { beforeEach(() => { SystemLogActions.fetchRange("foo", { cursor: "bar", limit: 3, subscriptionID: "subscriptionID", }); }); it("calls #addEventListener from the EventSource", () => { thisEventSource.addEventListener = jasmine .createSpy("addEventListener") .and.callThrough(); SystemLogActions.fetchRange("foo", { cursor: "bar" }); expect(thisEventSource.addEventListener).toHaveBeenCalled(); }); it("fetches data from the correct URL", () => { const mostRecent = window.EventSource.calls.mostRecent(); expect(mostRecent.args[0]).toEqual( "/system/v1/agent/foo/logs/v1/range/?cursor=bar&limit=3&read_reverse=true" ); }); it("dispatches the correct action when closing connection", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual( ActionTypes.REQUEST_PREVIOUS_SYSTEM_LOG_SUCCESS ); }); const event = { data: {}, eventPhase: window.EventSource.CLOSED, origin: window.location.origin, }; thisEventSource.dispatchEvent("error", event); }); it("dispatches the correct information when successful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data.length).toEqual(3); expect(action.subscriptionID).toEqual("subscriptionID"); expect(action.firstEntry).toEqual(false); }); const messageEvent = { data: "{}", eventPhase: window.EventSource.OPEN, origin: window.location.origin, }; thisEventSource.dispatchEvent("message", messageEvent); thisEventSource.dispatchEvent("message", messageEvent); thisEventSource.dispatchEvent("message", messageEvent); const closeEvent = { data: {}, eventPhase: window.EventSource.CLOSED, origin: window.location.origin, }; thisEventSource.dispatchEvent("error", closeEvent); }); it("tells when the top has been reached", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data.length).toEqual(2); expect(action.subscriptionID).toEqual("subscriptionID"); expect(action.firstEntry).toEqual(true); }); const messageEvent = { data: "{}", eventPhase: window.EventSource.OPEN, origin: window.location.origin, }; thisEventSource.dispatchEvent("message", messageEvent); thisEventSource.dispatchEvent("message", messageEvent); // Close before we the 3 events we have requested to show // that we have reached the top const closeEvent = { data: {}, eventPhase: window.EventSource.CLOSED, origin: window.location.origin, }; thisEventSource.dispatchEvent("error", closeEvent); }); it("reverses received data", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data[0].foo).toEqual(1); expect(action.data[1].foo).toEqual(0); }); thisEventSource.dispatchEvent("message", { data: '{"foo": 0}', eventPhase: window.EventSource.OPEN, origin: window.location.origin, }); thisEventSource.dispatchEvent("message", { data: '{"foo": 1}', eventPhase: window.EventSource.OPEN, origin: window.location.origin, }); // Close before we the 3 events we have requested to show // that we have reached the top const closeEvent = { data: {}, eventPhase: window.EventSource.CLOSED, origin: window.location.origin, }; thisEventSource.dispatchEvent("error", closeEvent); }); it("dispatches the correct action when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual( ActionTypes.REQUEST_PREVIOUS_SYSTEM_LOG_ERROR ); }); const event = { eventPhase: window.EventSource.CONNECTING }; thisEventSource.dispatchEvent("error", event); }); it("dispatches the correct information when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual({ eventPhase: window.EventSource.CONNECTING, }); expect(action.subscriptionID).toEqual("subscriptionID"); }); const event = { eventPhase: window.EventSource.CONNECTING }; thisEventSource.dispatchEvent("error", event); }); }); describe("#fetchStreamTypes", () => { beforeEach(() => { spyOn(RequestUtil, "json"); SystemLogActions.fetchStreamTypes("foo"); thisConfiguration = RequestUtil.json.calls.mostRecent().args[0]; }); it("calls #json from the RequestUtil", () => { expect(RequestUtil.json).toHaveBeenCalled(); }); it("fetches data from the correct URL", () => { expect(thisConfiguration.url).toEqual( Config.logsAPIPrefix + "/foo/logs/v1/fields/STREAM" ); }); it("dispatches the correct action when successful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual( ActionTypes.REQUEST_SYSTEM_LOG_STREAM_TYPES_SUCCESS ); }); thisConfiguration.success(["one", "two"]); }); it("dispatches the correct data when successful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual(["one", "two"]); }); thisConfiguration.success(["one", "two"]); }); it("dispatches the correct action when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.type).toEqual( ActionTypes.REQUEST_SYSTEM_LOG_STREAM_TYPES_ERROR ); }); thisConfiguration.error({ responseJSON: { description: "bar" } }); }); it("dispatches the correct error when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual("bar"); }); thisConfiguration.error({ responseJSON: { description: "bar" } }); }); it("dispatches the message when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.data).toEqual("baz"); }); thisConfiguration.error({ foo: "bar", responseJSON: { description: "baz" }, }); }); it("dispatches the xhr when unsuccessful", () => { const id = AppDispatcher.register((payload) => { const action = payload.action; AppDispatcher.unregister(id); expect(action.xhr).toEqual({ foo: "bar", responseJSON: { description: "baz" }, }); }); thisConfiguration.error({ foo: "bar", responseJSON: { description: "baz" }, }); }); }); });
the_stack
import { of as observableOf } from 'rxjs'; import { TestBed } from '@angular/core/testing'; import { provideMockActions } from '@ngrx/effects/testing'; import { LinkService } from '../../core/cache/builders/link.service'; import { cold, hot } from 'jasmine-marbles'; import { SetThemeAction } from './theme.actions'; import { Theme } from '../../../config/theme.model'; import { provideMockStore } from '@ngrx/store/testing'; import { Community } from '../../core/shared/community.model'; import { COMMUNITY } from '../../core/shared/community.resource-type'; import { NoOpAction } from '../ngrx/no-op.action'; import { ITEM } from '../../core/shared/item.resource-type'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { Item } from '../../core/shared/item.model'; import { Collection } from '../../core/shared/collection.model'; import { COLLECTION } from '../../core/shared/collection.resource-type'; import { createNoContentRemoteDataObject$, createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } from '../remote-data.utils'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; import { ThemeService } from './theme.service'; import { ROUTER_NAVIGATED } from '@ngrx/router-store'; import { ActivatedRouteSnapshot } from '@angular/router'; /** * LinkService able to mock recursively resolving DSO parent links * Every time resolveLinkWithoutAttaching is called, it returns the next object in the array of ancestorDSOs until * none are left, after which it returns a no-content remote-date */ class MockLinkService { index = -1; constructor(private ancestorDSOs: DSpaceObject[]) { } resolveLinkWithoutAttaching() { if (this.index >= this.ancestorDSOs.length - 1) { return createNoContentRemoteDataObject$(); } else { this.index++; return createSuccessfulRemoteDataObject$(this.ancestorDSOs[this.index]); } } } describe('ThemeService', () => { let themeService: ThemeService; let linkService: LinkService; let initialState; let ancestorDSOs: DSpaceObject[]; const mockCommunity = Object.assign(new Community(), { type: COMMUNITY.value, uuid: 'top-community-uuid', }); function init() { ancestorDSOs = [ Object.assign(new Collection(), { type: COLLECTION.value, uuid: 'collection-uuid', _links: { owningCommunity: { href: 'owning-community-link' } } }), Object.assign(new Community(), { type: COMMUNITY.value, uuid: 'sub-community-uuid', _links: { parentCommunity: { href: 'parent-community-link' } } }), mockCommunity, ]; linkService = new MockLinkService(ancestorDSOs) as any; initialState = { theme: { currentTheme: 'custom', }, }; } function setupServiceWithActions(mockActions) { init(); const mockDsoService = { findById: () => createSuccessfulRemoteDataObject$(mockCommunity) }; TestBed.configureTestingModule({ providers: [ ThemeService, { provide: LinkService, useValue: linkService }, provideMockStore({ initialState }), provideMockActions(() => mockActions), { provide: DSpaceObjectDataService, useValue: mockDsoService } ] }); themeService = TestBed.inject(ThemeService); spyOn((themeService as any).store, 'dispatch').and.stub(); } describe('updateThemeOnRouteChange$', () => { const url = '/test/route'; const dso = Object.assign(new Community(), { type: COMMUNITY.value, uuid: '0958c910-2037-42a9-81c7-dca80e3892b4', }); function spyOnPrivateMethods() { spyOn((themeService as any), 'getAncestorDSOs').and.returnValue(() => observableOf([dso])); spyOn((themeService as any), 'matchThemeToDSOs').and.returnValue(new Theme({ name: 'custom' })); spyOn((themeService as any), 'getActionForMatch').and.returnValue(new SetThemeAction('custom')); } describe('when no resolved action is present', () => { beforeEach(() => { setupServiceWithActions( hot('--a-', { a: { type: ROUTER_NAVIGATED, payload: { routerState: { url } }, }, }) ); spyOnPrivateMethods(); }); it('should set the theme it receives from the route url', (done) => { themeService.updateThemeOnRouteChange$(url, {} as ActivatedRouteSnapshot).subscribe(() => { expect((themeService as any).store.dispatch).toHaveBeenCalledWith(new SetThemeAction('custom') as any); done(); }); }); it('should return true', (done) => { themeService.updateThemeOnRouteChange$(url, {} as ActivatedRouteSnapshot).subscribe((result) => { expect(result).toEqual(true); done(); }); }); }); describe('when no themes are present', () => { beforeEach(() => { setupServiceWithActions( hot('--a-', { a: { type: ROUTER_NAVIGATED, payload: { routerState: { url } }, }, }) ); (themeService as any).themes = []; }); it('should not dispatch any action', (done) => { themeService.updateThemeOnRouteChange$(url, {} as ActivatedRouteSnapshot).subscribe(() => { expect((themeService as any).store.dispatch).not.toHaveBeenCalled(); done(); }); }); it('should return false', (done) => { themeService.updateThemeOnRouteChange$(url, {} as ActivatedRouteSnapshot).subscribe((result) => { expect(result).toEqual(false); done(); }); }); }); describe('when a dso is present in the snapshot\'s data', () => { let snapshot; beforeEach(() => { setupServiceWithActions( hot('--a-', { a: { type: ROUTER_NAVIGATED, payload: { routerState: { url } }, }, }) ); spyOnPrivateMethods(); snapshot = Object.assign({ data: { dso: createSuccessfulRemoteDataObject(dso) } }); }); it('should match the theme to the dso', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).matchThemeToDSOs).toHaveBeenCalled(); done(); }); }); it('should set the theme it receives from the data dso', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).store.dispatch).toHaveBeenCalledWith(new SetThemeAction('custom') as any); done(); }); }); it('should return true', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe((result) => { expect(result).toEqual(true); done(); }); }); }); describe('when a scope is present in the snapshot\'s parameters', () => { let snapshot; beforeEach(() => { setupServiceWithActions( hot('--a-', { a: { type: ROUTER_NAVIGATED, payload: { routerState: { url } }, }, }) ); spyOnPrivateMethods(); snapshot = Object.assign({ queryParams: { scope: mockCommunity.uuid } }); }); it('should match the theme to the dso found through the scope', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).matchThemeToDSOs).toHaveBeenCalled(); done(); }); }); it('should set the theme it receives from the dso found through the scope', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe(() => { expect((themeService as any).store.dispatch).toHaveBeenCalledWith(new SetThemeAction('custom') as any); done(); }); }); it('should return true', (done) => { themeService.updateThemeOnRouteChange$(url, snapshot).subscribe((result) => { expect(result).toEqual(true); done(); }); }); }); }); describe('private functions', () => { beforeEach(() => { setupServiceWithActions(hot('-', {})); }); describe('getActionForMatch', () => { it('should return a SET action if the new theme differs from the current theme', () => { const theme = new Theme({ name: 'new-theme' }); expect((themeService as any).getActionForMatch(theme, 'old-theme')).toEqual(new SetThemeAction('new-theme')); }); it('should return an empty action if the new theme equals the current theme', () => { const theme = new Theme({ name: 'old-theme' }); expect((themeService as any).getActionForMatch(theme, 'old-theme')).toEqual(new NoOpAction()); }); }); describe('matchThemeToDSOs', () => { let themes: Theme[]; let nonMatchingTheme: Theme; let itemMatchingTheme: Theme; let communityMatchingTheme: Theme; let dsos: DSpaceObject[]; beforeEach(() => { nonMatchingTheme = Object.assign(new Theme({ name: 'non-matching-theme' }), { matches: () => false }); itemMatchingTheme = Object.assign(new Theme({ name: 'item-matching-theme' }), { matches: (url, dso) => (dso as any).type === ITEM.value }); communityMatchingTheme = Object.assign(new Theme({ name: 'community-matching-theme' }), { matches: (url, dso) => (dso as any).type === COMMUNITY.value }); dsos = [ Object.assign(new Item(), { type: ITEM.value, uuid: 'item-uuid', }), Object.assign(new Collection(), { type: COLLECTION.value, uuid: 'collection-uuid', }), Object.assign(new Community(), { type: COMMUNITY.value, uuid: 'community-uuid', }), ]; }); describe('when no themes match any of the DSOs', () => { beforeEach(() => { themes = [ nonMatchingTheme ]; themeService.themes = themes; }); it('should return undefined', () => { expect((themeService as any).matchThemeToDSOs(dsos, '')).toBeUndefined(); }); }); describe('when one of the themes match a DSOs', () => { beforeEach(() => { themes = [ nonMatchingTheme, itemMatchingTheme ]; themeService.themes = themes; }); it('should return the matching theme', () => { expect((themeService as any).matchThemeToDSOs(dsos, '')).toEqual(itemMatchingTheme); }); }); describe('when multiple themes match some of the DSOs', () => { it('should return the first matching theme', () => { themes = [ nonMatchingTheme, itemMatchingTheme, communityMatchingTheme ]; themeService.themes = themes; expect((themeService as any).matchThemeToDSOs(dsos, '')).toEqual(itemMatchingTheme); themes = [ nonMatchingTheme, communityMatchingTheme, itemMatchingTheme ]; themeService.themes = themes; expect((themeService as any).matchThemeToDSOs(dsos, '')).toEqual(communityMatchingTheme); }); }); }); describe('getAncestorDSOs', () => { it('should return an array of the provided DSO and its ancestors', (done) => { const dso = Object.assign(new Item(), { type: ITEM.value, uuid: 'item-uuid', _links: { owningCollection: { href: 'owning-collection-link' } }, }); observableOf(dso).pipe( (themeService as any).getAncestorDSOs() ).subscribe((result) => { expect(result).toEqual([dso, ...ancestorDSOs]); done(); }); }); it('should return an array of just the provided DSO if it doesn\'t have any parents', (done) => { const dso = { type: ITEM.value, uuid: 'item-uuid', }; observableOf(dso).pipe( (themeService as any).getAncestorDSOs() ).subscribe((result) => { expect(result).toEqual([dso]); done(); }); }); }); }); });
the_stack
import * as A from "../../../Collections/Immutable/Chunk" import * as Tp from "../../../Collections/Immutable/Tuple" import * as T from "../../../Effect" import * as Ex from "../../../Exit" import * as O from "../../../Option" import type * as OD from "../../../Ord" import * as CombineChunks from "../_internal/api/combineChunks" import type * as S from "../_internal/core" import type * as C from "./core" class DrainLeft { readonly _tag = "DrainLeft" } class DrainRight { readonly _tag = "DrainRight" } class PullBoth { readonly _tag = "PullBoth" } class PullLeft<K, B> { readonly _tag = "PullLeft" constructor(readonly rightChunk: A.Chunk<Tp.Tuple<[K, B]>>) {} } class PullRight<K, A> { readonly _tag = "PullRight" constructor(readonly leftChunk: A.Chunk<Tp.Tuple<[K, A]>>) {} } type State<K, A, B> = | DrainLeft | DrainRight | PullBoth | PullLeft<K, B> | PullRight<K, A> /** * Zips this stream that is sorted by distinct keys and the specified * stream that is sorted by distinct keys to produce a new stream that is * sorted by distinct keys. Uses the functions `left`, `right`, and `both` * to handle the cases where a key and value exist in this stream, that * stream, or both streams. * * This allows zipping potentially unbounded streams of data by key in * constant space but the caller is responsible for ensuring that the * streams are sorted by distinct keys. * * The execution strategy `exec` will be used to determine whether to pull * from the streams sequentially or in parallel. */ export function zipAllSortedByKeyWithExec_<R, R1, E, E1, K, A, B, C1, C2, C3>( self: C.SortedByKey<R, E, K, A>, that: C.SortedByKey<R1, E1, K, B>, left: (a: A) => C1, right: (b: B) => C2, both: (a: A, b: B) => C3, ord: OD.Ord<K>, exec: T.ExecutionStrategy ): S.Stream<R & R1, E | E1, Tp.Tuple<[K, C1 | C2 | C3]>> { const pull = ( state: State<K, A, B>, pullLeft: T.Effect<R, O.Option<E>, A.Chunk<Tp.Tuple<[K, A]>>>, pullRight: T.Effect<R1, O.Option<E1>, A.Chunk<Tp.Tuple<[K, B]>>> ): T.Effect< R & R1, never, Ex.Exit< O.Option<E | E1>, Tp.Tuple<[A.Chunk<Tp.Tuple<[K, C1 | C2 | C3]>>, State<K, A, B>]> > > => { switch (state._tag) { case "DrainLeft": return T.fold_( pullLeft, (e) => Ex.fail(e), (leftChunk) => Ex.succeed( Tp.tuple( A.map_(leftChunk, ({ tuple: [k, a] }) => Tp.tuple(k, left(a))), new DrainLeft() ) ) ) case "DrainRight": return T.fold_( pullRight, (e) => Ex.fail(e), (rightChunk) => Ex.succeed( Tp.tuple( A.map_(rightChunk, ({ tuple: [k, b] }) => Tp.tuple(k, right(b))), new DrainRight() ) ) ) case "PullBoth": { switch (exec._tag) { case "Sequential": return T.foldM_( pullLeft, O.fold( () => pull(new DrainRight(), pullLeft, pullRight), (e) => T.succeed(Ex.fail(O.some(e))) ), (leftChunk) => A.isEmpty(leftChunk) ? pull(new PullBoth(), pullLeft, pullRight) : pull(new PullRight(leftChunk), pullLeft, pullRight) ) default: return T.foldM_( T.zipPar_(T.unsome(pullLeft), T.unsome(pullRight)), (e) => T.succeed(Ex.fail(O.some(e))), ({ tuple: [a, b] }) => { if (O.isSome(a) && O.isSome(b)) { const leftChunk = a.value const rightChunk = b.value if (A.isEmpty(leftChunk) && A.isEmpty(rightChunk)) { return pull(new PullBoth(), pullLeft, pullRight) } else if (A.isEmpty(leftChunk)) { return pull(new PullLeft(rightChunk), pullLeft, pullRight) } else if (A.isEmpty(rightChunk)) { return pull(new PullRight(leftChunk), pullLeft, pullRight) } else { return T.succeed( Ex.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk)) ) } } else if (O.isSome(a)) { const leftChunk = a.value return A.isEmpty(leftChunk) ? pull(new DrainLeft(), pullLeft, pullRight) : T.succeed( Ex.succeed( Tp.tuple( A.map_(leftChunk, ({ tuple: [k, a] }) => Tp.tuple(k, left(a)) ), new DrainLeft() ) ) ) } else if (O.isSome(b)) { const rightChunk = b.value return A.isEmpty(rightChunk) ? pull(new DrainLeft(), pullLeft, pullRight) : T.succeed( Ex.succeed( Tp.tuple( A.map_(rightChunk, ({ tuple: [k, b] }) => Tp.tuple(k, right(b)) ), new DrainRight() ) ) ) } else { return T.succeed(Ex.fail(O.none)) } } ) } } case "PullLeft": { const rightChunk = state.rightChunk return T.foldM_( pullLeft, O.fold( (): T.Effect< unknown, never, Ex.Exit<O.Option<E>, Tp.Tuple<[A.Chunk<Tp.Tuple<[K, C2]>>, DrainRight]>> > => T.succeed( Ex.succeed( Tp.tuple( A.map_(rightChunk, ({ tuple: [k, b] }) => Tp.tuple(k, right(b))), new DrainRight() ) ) ), (e) => T.succeed(Ex.fail(O.some(e))) ), (leftChunk) => A.isEmpty(leftChunk) ? pull(new PullLeft(rightChunk), pullLeft, pullRight) : T.succeed(Ex.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk))) ) } case "PullRight": { const leftChunk = state.leftChunk return T.foldM_( pullRight, O.fold( (): T.Effect< unknown, never, Ex.Exit<O.Option<E1>, Tp.Tuple<[A.Chunk<Tp.Tuple<[K, C1]>>, DrainLeft]>> > => T.succeed( Ex.succeed( Tp.tuple( A.map_(leftChunk, ({ tuple: [k, a] }) => Tp.tuple(k, left(a))), new DrainLeft() ) ) ), (e) => T.succeed(Ex.fail(O.some(e))) ), (rightChunk) => A.isEmpty(rightChunk) ? pull(new PullRight(leftChunk), pullLeft, pullRight) : T.succeed(Ex.succeed(mergeSortedByKeyChunk(leftChunk, rightChunk))) ) } } } const mergeSortedByKeyChunk = ( leftChunk: A.Chunk<Tp.Tuple<[K, A]>>, rightChunk: A.Chunk<Tp.Tuple<[K, B]>> ): Tp.Tuple<[A.Chunk<Tp.Tuple<[K, C1 | C2 | C3]>>, State<K, A, B>]> => { const builder = A.builder<Tp.Tuple<[K, C1 | C2 | C3]>>() let state: State<K, A, B> | undefined let leftIndex = 0 let rightIndex = 0 let leftTuple = A.unsafeGet_(leftChunk, leftIndex) let rightTuple = A.unsafeGet_(rightChunk, rightIndex) let k1 = leftTuple.get(0) let a = leftTuple.get(1) let k2 = rightTuple.get(0) let b = rightTuple.get(1) let loop = true const hasNext = <T>(c: A.Chunk<T>, index: number) => index < A.size(c) - 1 while (loop) { const compare = ord.compare(k1, k2) if (compare === 0) { builder.append(Tp.tuple(k1, both(a, b))) if (hasNext(leftChunk, leftIndex) && hasNext(rightChunk, rightIndex)) { leftIndex += 1 rightIndex += 1 leftTuple = A.unsafeGet_(leftChunk, leftIndex) rightTuple = A.unsafeGet_(rightChunk, rightIndex) k1 = leftTuple.get(0) a = leftTuple.get(1) k2 = rightTuple.get(0) b = rightTuple.get(1) } else if (hasNext(leftChunk, leftIndex)) { state = new PullRight(A.drop_(leftChunk, leftIndex + 1)) loop = false } else if (hasNext(rightChunk, rightIndex)) { state = new PullLeft(A.drop_(rightChunk, rightIndex + 1)) loop = false } else { state = new PullBoth() loop = false } } else if (compare < 0) { builder.append(Tp.tuple(k1, left(a))) if (hasNext(leftChunk, leftIndex)) { leftIndex += 1 leftTuple = A.unsafeGet_(leftChunk, leftIndex) k1 = leftTuple.get(0) a = leftTuple.get(1) } else { const rightBuilder = A.builder<Tp.Tuple<[K, B]>>() rightBuilder.append(rightTuple) while (hasNext(rightChunk, rightIndex)) { rightIndex += 1 rightTuple = A.unsafeGet_(rightChunk, rightIndex) rightBuilder.append(rightTuple) state = new PullLeft(rightBuilder.build()) loop = false } } } else { builder.append(Tp.tuple(k2, right(b))) if (hasNext(rightChunk, rightIndex)) { rightIndex += 1 rightTuple = A.unsafeGet_(rightChunk, rightIndex) k2 = rightTuple.get(0) b = rightTuple.get(1) } else { const leftBuilder = A.builder<Tp.Tuple<[K, A]>>() leftBuilder.append(leftTuple) while (hasNext(leftChunk, leftIndex)) { leftIndex += 1 leftTuple = A.unsafeGet_(leftChunk, leftIndex) leftBuilder.append(leftTuple) state = new PullRight(leftBuilder.build()) loop = false } } } } return Tp.tuple(builder.build(), state!) } return CombineChunks.combineChunks_(self, that, new PullBoth(), pull) } /** * Zips this stream that is sorted by distinct keys and the specified * stream that is sorted by distinct keys to produce a new stream that is * sorted by distinct keys. Uses the functions `left`, `right`, and `both` * to handle the cases where a key and value exist in this stream, that * stream, or both streams. * * This allows zipping potentially unbounded streams of data by key in * constant space but the caller is responsible for ensuring that the * streams are sorted by distinct keys. * * The execution strategy `exec` will be used to determine whether to pull * from the streams sequentially or in parallel. * * @ets_data_first zipAllSortedByKeyWithExec_ */ export function zipAllSortedByKeyWithExec<R1, E1, K, A, B, C1, C2, C3>( that: C.SortedByKey<R1, E1, K, B>, left: (a: A) => C1, right: (b: B) => C2, both: (a: A, b: B) => C3, ord: OD.Ord<K>, exec: T.ExecutionStrategy ) { return <R, E>(self: C.SortedByKey<R, E, K, A>) => zipAllSortedByKeyWithExec_(self, that, left, right, both, ord, exec) }
the_stack
import moment from 'moment' import { IGlobalControl, ILocalControl, IControlBase, IControlRelatedField, IRenderTreeItem, InteractionType, IFilters } from './types' import { uuid } from 'app/utils/util' import FilterTypes, { FilterTypesOperatorSetting, IS_RANGE_TYPE, FilterTypesDynamicDefaultValueSetting } from './filterTypes' import { DEFAULT_CACHE_EXPIRED, SQL_NUMBER_TYPES, SQL_DATE_TYPES } from 'app/globalConstants' import { IFormedView, IViewModelProps, IViewVariable } from 'app/containers/View/types' import { ViewVariableValueTypes, ViewVariableTypes, ViewModelTypes } from 'app/containers/View/constants' import DatePickerFormats, { DatePickerDefaultValues, DatePickerFormatsSelectSetting } from './datePickerFormats' import OperatorTypes from 'app/utils/operatorTypes' export function getDefaultGlobalControl (): IGlobalControl { const control: IGlobalControl = { key: uuid(8, 16), name: '新建控制器', type: FilterTypes.Select, interactionType: 'column', operator: FilterTypesOperatorSetting[FilterTypes.InputText][0], cache: false, expired: DEFAULT_CACHE_EXPIRED, width: 0, relatedItems: {}, relatedViews: {} } return control } export function getDefaultLocalControl (view: IFormedView): ILocalControl { const model = view.model || {} const modelList = Object.entries(model) const defaultFields = modelList[0] const control: ILocalControl = { key: uuid(8, 16), name: '新建控制器', type: FilterTypes.Select, interactionType: 'column', operator: FilterTypesOperatorSetting[FilterTypes.InputText][0], cache: false, expired: DEFAULT_CACHE_EXPIRED, width: 0, fields: defaultFields && { name: defaultFields[0], type: defaultFields[1].sqlType } } return control } export function getVariableValue (filter: IControlBase, fields: IControlRelatedField | IControlRelatedField[], value) { const { type, dateFormat, multiple } = filter let name let valueType let variable = [] if (value === void 0 || value === null || typeof value === 'string' && !value.trim()) { return variable } if (!Array.isArray(fields)) { name = fields.name valueType = fields.type } switch (type) { case FilterTypes.InputText: variable.push({ name, value: getValidVariableValue(value, valueType) }) break case FilterTypes.Select: if (multiple) { if (value.length && value.length > 0) { variable.push({ name, value: value.map((val) => getValidVariableValue(val, valueType)).join(',') }) } } else { variable.push({ name, value: getValidVariableValue(value, valueType) }) } break case FilterTypes.NumberRange: variable = value.reduce((arr, val, index) => { if (val !== '' && !isNaN(val)) { const { name, type: valueType } = fields[index] return arr.concat({ name, value: getValidVariableValue(val, valueType) }) } return arr }, []) break // case FilterTypes.TreeSelect: // if (value.length && value.length > 0) { // variable.push({ name, value: value.map((val) => getValidVariableValue(val, valueType)).join(',') }) // } // break case FilterTypes.Date: if (multiple) { variable.push({ name, value: value.split(',').map((v) => `'${v}'`).join(',') }) } else { variable.push({ name, value: `'${moment(value).format(dateFormat)}'` }) } break case FilterTypes.DateRange: if (value.length) { variable = value .map((v, index) => { const { name } = fields[index] return { name, value: `'${moment(v).format(dateFormat)}'` } }) } break default: const val = value.target.value.trim() if (val) { variable.push({ name, value: getValidVariableValue(val, valueType) }) } break } return variable } // 全局过滤器 与 本地控制器 filter 操作 export function getModelValue (control: IControlBase, field: IControlRelatedField, value) { const { type, dateFormat, multiple, operator } = control // select '' true in const { name, type: sqlType } = field const filters = [] if (value === void 0 || value === null || typeof value === 'string' && !value.trim()) { return filters } const commanFilterJson: IFilters = { name, type: 'filter', value: getValidColumnValue(value, sqlType), sqlType, operator } switch (type) { case FilterTypes.InputText: filters.push(commanFilterJson) break case FilterTypes.Select: if (multiple) { if (Array.isArray(value) && value.length > 0) { const filterJson = { ...commanFilterJson, value: value.map((val) => getValidColumnValue(val, sqlType)) } filters.push(filterJson) } } else { filters.push(commanFilterJson) } break case FilterTypes.NumberRange: if (value[0] !== '' && !isNaN(value[0])) { const filterJson = { ...commanFilterJson, operator: '>=', value: getValidColumnValue(value[0], sqlType) } filters.push(filterJson) } if (value[1] !== '' && !isNaN(value[1])) { const filterJson = { ...commanFilterJson, operator: '<=', value: getValidColumnValue(value[1], sqlType) } filters.push(filterJson) } break // case FilterTypes.TreeSelect: // if (value.length && value.length > 0) { // filters.push(`${name} ${operator} (${value.map((val) => getValidColumnValue(val, sqlType)).join(',')})`) // } // break case FilterTypes.Date: if (multiple) { const filterJson = { ...commanFilterJson, value: value.split(',').map((val) => getValidColumnValue(val, sqlType)) } filters.push(filterJson) } else { const filterJson = { ...commanFilterJson, value: getValidColumnValue(moment(value).format(dateFormat), sqlType) } filters.push(filterJson) } break case FilterTypes.DateRange: if (value.length) { const filterJson1 = { ...commanFilterJson, operator: '>=', value: getValidColumnValue(moment(value[0]).format(dateFormat), sqlType) } const filterJson2 = { ...commanFilterJson, operator: '<=', value: getValidColumnValue(moment(value[1]).format(dateFormat), sqlType) } filters.push(filterJson1) filters.push(filterJson2) } break default: const inputValue = value.target.value.trim() const filterJson = { ...commanFilterJson, value: getValidColumnValue(inputValue, sqlType) } if (inputValue) { filters.push(filterJson) } break } return filters } export function getValidColumnValue (value, sqlType) { if (!value || !sqlType) { return value } return SQL_NUMBER_TYPES.includes(sqlType) ? value : `'${value}'` } export function getValidVariableValue (value, valueType: ViewVariableValueTypes) { switch (valueType) { case ViewVariableValueTypes.String: case ViewVariableValueTypes.Date: return `'${value}'` case ViewVariableValueTypes.Boolean: return !!value default: return value } } export function deserializeDefaultValue (control: IControlBase) { const { type, dynamicDefaultValue, defaultValue, multiple } = control switch (type) { case FilterTypes.Date: if (dynamicDefaultValue) { switch (dynamicDefaultValue) { case DatePickerDefaultValues.Today: return moment() case DatePickerDefaultValues.Yesterday: return moment().subtract(1, 'days') case DatePickerDefaultValues.Week: return moment().startOf('week') case DatePickerDefaultValues.Day7: return moment().subtract(7, 'days') case DatePickerDefaultValues.LastWeek: return moment().subtract(7, 'days').startOf('week') case DatePickerDefaultValues.Month: return moment().startOf('month') case DatePickerDefaultValues.Day30: return moment().subtract(30, 'days') case DatePickerDefaultValues.LastMonth: return moment().subtract(1, 'months').startOf('month') case DatePickerDefaultValues.Quarter: return moment().startOf('quarter') case DatePickerDefaultValues.Day90: return moment().subtract(90, 'days') case DatePickerDefaultValues.LastQuarter: return moment().subtract(1, 'quarters').startOf('quarter') case DatePickerDefaultValues.Year: return moment().startOf('year') case DatePickerDefaultValues.Day365: return moment().subtract(365, 'days') case DatePickerDefaultValues.LastYear: return moment().subtract(1, 'years').startOf('year') default: return multiple ? defaultValue : defaultValue && moment(defaultValue) } } else { return null } default: return defaultValue } } export function serializeDefaultValue ( control: IControlBase, value ) { const { type, dateFormat, multiple } = control if (type === FilterTypes.Date && !multiple) { return value && value.format(dateFormat) } else { return value } } export function getOperatorOptions (type: FilterTypes, multiple: boolean): OperatorTypes[] { const operatorTypes = FilterTypesOperatorSetting[type] switch (type) { case FilterTypes.Select: case FilterTypes.Date: return multiple ? operatorTypes['multiple'] : operatorTypes['normal'] default: return operatorTypes as OperatorTypes[] } } export function getDatePickerFormatOptions (type: FilterTypes, multiple: boolean): DatePickerFormats[] { switch (type) { case FilterTypes.Date: case FilterTypes.DateRange: return multiple ? DatePickerFormatsSelectSetting['multiple'] : DatePickerFormatsSelectSetting['normal'] default: return [] } } export function getDynamicDefaultValueOptions (type: FilterTypes, multiple: boolean): DatePickerDefaultValues[] { switch (type) { case FilterTypes.Date: return multiple ? FilterTypesDynamicDefaultValueSetting[type]['multiple'] : FilterTypesDynamicDefaultValueSetting[type]['normal'] default: return [] } } export function getControlRenderTree<T extends IControlBase, U extends IControlBase> (controls: T[]): { renderTree: U[], flatTree: { [key: string]: U } } { const renderTree = [] const flatTree = {} while (controls.length) { const control = controls[0] flatTree[control.key] = control if (control.parent) { if (!flatTree[control.parent]) { controls.push(control) controls.shift() continue } if (!flatTree[control.parent].children) { flatTree[control.parent].children = [] } flatTree[control.parent].children.push(control) } else { renderTree.push(control) } controls.shift() } return { renderTree, flatTree } } export function getAllChildren ( key: string, flatTree: { [key: string]: IRenderTreeItem } ) { let keys = [] if (flatTree[key].children) { flatTree[key].children.forEach((c) => { keys = keys.concat(c.key).concat(getAllChildren(c.key, flatTree)) }) } return keys } export function getParents<T extends IControlBase> ( parentKey: string, flatTree: { [key: string]: IRenderTreeItem } ): T[] { let parents = [] const parent = flatTree[parentKey] if (parent) { const { children, ...rest } = parent parents = parents .concat({...rest}) .concat(getParents(rest.parent, flatTree)) } return parents } export function getRelatedFieldsInfo ( view: IFormedView, type: FilterTypes, interactionType: InteractionType, fields: IControlRelatedField | IControlRelatedField[] ): { model: IViewModelProps[], variables: IViewVariable[], fields: IControlRelatedField | IControlRelatedField[] } { const model = Object.entries(view.model) .filter(([k, v]: [string, IViewModelProps]) => { return type === FilterTypes.NumberRange ? v.modelType === ViewModelTypes.Value : v.modelType === ViewModelTypes.Category }) .map(([k, v]: [string, IViewModelProps]) => ({ name: k, ...v })) const variables = view.variable.filter((v) => v.type === ViewVariableTypes.Query) if (interactionType === 'column') { if (!fields) { fields = model.length ? { name: model[0].name, type: model[0].sqlType } : void 0 } } else { if (!fields) { if (variables.length) { const fieldBase = { name: variables[0].name, type: variables[0].valueType } if (IS_RANGE_TYPE[type]) { fields = [fieldBase] } else if (type === FilterTypes.Select) { fields = { ...fieldBase, optionsFromColumn: false, column: model.length ? model[0].name : void 0 } } else { fields = fieldBase } } else { fields = IS_RANGE_TYPE[type] ? [] : void 0 } } else { fields = IS_RANGE_TYPE[type] ? [].concat(fields) : fields } } return { model, variables, fields } }
the_stack
import '../elements/spinner'; import '../elements/tcav_score_bar'; import '@material/mwc-switch'; import {customElement} from 'lit/decorators'; import { html} from 'lit'; import {TemplateResult} from 'lit'; import {classMap} from 'lit/directives/class-map'; import {styleMap} from 'lit/directives/style-map'; import {computed, observable} from 'mobx'; import {app} from '../core/app'; import {LitModule} from '../core/lit_module'; import {TableData} from '../elements/table'; import {CallConfig, ModelInfoMap, Spec} from '../lib/types'; import {doesOutputSpecContain, findSpecKeys} from '../lib/utils'; import {SliceService} from '../services/services'; import {STARRED_SLICE_NAME} from '../services/slice_service'; import {styles as sharedStyles} from '../lib/shared_styles.css'; import {styles} from './tcav_module.css'; const MIN_EXAMPLES_LENGTH = 3; // minimum examples needed to train the CAV. const TCAV_INTERPRETER_NAME = 'tcav'; const COLUMN_NAMES = [ 'Positive Slice', 'Negative Slice', 'Run', 'Embedding', 'Class', 'CAV Score', 'Score Bar' ]; const RELATIVE_TCAV_MIN_EXAMPLES = 6; // MIN_SPLIT_SIZE * MIN_SPLITS in tcav.py const NO_T_TESTING_WARNING = `Did not run t-testing (requires at least ${ RELATIVE_TCAV_MIN_EXAMPLES} positive and ${ RELATIVE_TCAV_MIN_EXAMPLES} negative samples)`; const MAX_P_VAL = 0.05; const HIGH_P_VAL_WARNING = `this run was not statistically significant (p > ${MAX_P_VAL})`; interface TcavResults { positiveSlice: string; negativeSlice: string; config: CallConfig; score: number; // tslint:disable-next-line:enforce-name-casing p_val: number; // tslint:disable-next-line:enforce-name-casing random_mean: number; } /** * The TCAV module. */ @customElement('tcav-module') export class TCAVModule extends LitModule { static override get styles() { return [sharedStyles, styles]; } static override title = 'TCAV Explorer'; static override numCols = 12; static override duplicateForModelComparison = true; static override template = (model = '') => { return html` <tcav-module model=${model}> </tcav-module>`; }; private readonly sliceService = app.getService(SliceService); @observable private readonly selectedSlices = new Set<string>(); @observable private readonly selectedLayers = new Set<string>(); @observable private readonly selectedClasses = new Set<string>(); @observable private readonly negativeSlices = new Set<string>(); @observable private isLoading: boolean = false; @observable private isSliceHidden: boolean = false; @observable private isClassHidden: boolean = true; @observable private isEmbeddingHidden: boolean = true; private resultsTableData: TableData[] = []; private cavCounter = 0; @computed get modelSpec() { return this.appState.getModelSpec(this.model); } @computed get gradKeys() { return findSpecKeys(this.modelSpec.output, 'Gradients'); } @computed get TCAVSliceNames() { return this.sliceService.sliceNames.filter( name => name !== STARRED_SLICE_NAME); } // Returns pairs in the format [positive slice, negative slice (or null)] // for slices selected in the settings. @computed get slicePairs(): Array<[string, string|null]> { const positiveSlices: string[] = Array.from(this.selectedSlices.values()); const negativeSlices: string[] = Array.from(this.negativeSlices.values()); if (positiveSlices.length === 0) return []; if (negativeSlices.length === 0) { return positiveSlices.map((slice: string) => { return [slice, null]; }); } const pairs: Array<[string, string | null]> = []; for (const positiveSlice of positiveSlices) { for (const negativeSlice of negativeSlices) { pairs.push([positiveSlice, negativeSlice]); } } return pairs; } @computed get predClasses() { const predKeys = findSpecKeys(this.modelSpec.output, 'MulticlassPreds'); // TODO(lit-dev): Handle the multi-headed case with more than one pred key. return this.modelSpec.output[predKeys[0]].vocab!; } @computed get nullIndex() { const predKeys = findSpecKeys(this.modelSpec.output, 'MulticlassPreds'); // TODO(lit-dev): Handle the multi-headed case with more than one pred key. return this.modelSpec.output[predKeys[0]].null_idx!; } override firstUpdated() { // Set the first grad key as default in selector. if (this.selectedLayers.size === 0 && this.gradKeys.length > 0) { this.selectedLayers.add(this.gradKeys[0]); } // Set first non-null pred class as default in selector. if (this.selectedClasses.size === 0 && this.predClasses.length > 1) { const initialIndex = this.nullIndex === 0 ? 1 : 0; this.selectedClasses.add(this.predClasses[initialIndex]); } } renderSpinner() { return html` <div class="spinner-container"> <lit-spinner size=${24} color="var(--app-secondary-color)"> </lit-spinner> </div> `; } renderCollapseBar( title: string, barToggled: () => void, isHidden: boolean, items: string[], columnName: string, selectSet: Set<string>, secondSelectName: string = '', secondSelectSet: Set<string>|null = null) { const checkboxChanged = (e: Event, item: string) => { const checkbox = e.target as HTMLInputElement; if (checkbox.checked) { selectSet.add(item); } else { selectSet.delete(item); } }; const data = items.map((item) => { const row = [ // clang-format off html`<lit-checkbox ?checked=${selectSet.has(item)} @change='${(e: Event) => {checkboxChanged(e, item);}}'> </lit-checkbox>`, // clang-format on item ]; if (secondSelectSet != null) { const secondCheckboxChanged = (e: Event, item: string) => { const checkbox = e.target as HTMLInputElement; if (checkbox.checked) { secondSelectSet.add(item); } else { secondSelectSet.delete(item); } }; row.push( // clang-format off html`<lit-checkbox id='compare-switch' ?checked=${secondSelectSet.has(item)} @change='${(e: Event) => {secondCheckboxChanged(e, item);}}'> </lit-checkbox>` // clang-format on ); } return row; }); const columns = ['selected', columnName]; if (secondSelectSet != null) { columns.push(secondSelectName); } // clang-format off return html` <div class='collapse-bar' @click=${barToggled}> <div class="axis-title"> <div>${title}</div> </div> <mwc-icon class="icon-button min-button"> ${isHidden ? 'expand_more' : 'expand_less'} </mwc-icon> </div> <div class='collapse-content' style=${styleMap({'display': `${isHidden ? 'none' : 'block'}`})}> ${data.length === 0 ? html`<div class='require-text label-2'> This module requires at least one ${columnName.toLowerCase()}. </div>` : html`<lit-data-table .verticalAlignMiddle=${true} .columnNames=${columns} .data=${data}></lit-data-table>`} </div> `; // clang-format on } override render() { const shouldDisable = () => { for (const slice of this.selectedSlices) { const examples = this.sliceService.getSliceByName(slice); if (examples == null) return true; const comparisonSetLength = this.appState.currentInputData.length - examples.length; if (examples.length >= MIN_EXAMPLES_LENGTH && comparisonSetLength >= MIN_EXAMPLES_LENGTH) { return false; // only enable if slice has minimum number of examples } } return true; }; const clearOptions = () => { this.selectedClasses.clear(); this.selectedLayers.clear(); this.selectedSlices.clear(); this.negativeSlices.clear(); }; const clearTable = () => { this.resultsTableData = []; this.cavCounter = 0; this.requestUpdate(); }; const toggleSliceCollapse = () => { this.isSliceHidden = !this.isSliceHidden; }; const toggleClassCollapse = () => { this.isClassHidden = !this.isClassHidden; }; const toggleEmbeddingCollapse = () => { this.isEmbeddingHidden = !this.isEmbeddingHidden; }; const cavCount = this.selectedClasses.size * this.selectedSlices.size * this.selectedLayers.size; const disabledText = `select a slice with ${MIN_EXAMPLES_LENGTH} or more examples`; // The width of the SVG increase by 60px for each additional entry after // the first bar, so their labels don't overlap. // clang-format off // TODO(lit-dev): Switch the current barchart viz to a table-based viz. return html` <div class="module-container"> <div class="module-content"> <div class="left-container"> <div class="controls-holder"> ${this.renderCollapseBar('Select Slices', toggleSliceCollapse, this.isSliceHidden, this.TCAVSliceNames, 'Positive slice', this.selectedSlices, 'Negative slice', this.negativeSlices)} ${this.renderCollapseBar('Explainable Classes', toggleClassCollapse, this.isClassHidden, this.predClasses, 'Class', this.selectedClasses)} ${this.renderCollapseBar('Embeddings', toggleEmbeddingCollapse, this.isEmbeddingHidden, this.gradKeys, 'Embedding', this.selectedLayers)} </div> <div class="controls-actions"> <div id='examples-selected-label' class="label-2">${cavCount} CAV Results</div> <div class="controls-buttons"> <button id='clear-button' class="hairline-button" @click=${clearOptions} ?disabled=${this.selectedClasses.size === 0 && this.selectedLayers.size === 0 && this.selectedSlices.size === 0 && this.negativeSlices.size === 0}>Clear</button> <button id='submit' class="hairline-button" title=${shouldDisable() ? disabledText: ''} @click=${() => this.runTCAV()} ?disabled=${ shouldDisable()}>Run TCAV</button> </div> </div> </div> <div id='vis-container' class=${classMap({'loading': this.isLoading})}> ${this.isLoading ? this.renderSpinner(): ''} <lit-data-table .columnNames=${COLUMN_NAMES} .data=${[...this.resultsTableData]} .verticalAlignMiddle=${true}></lit-data-table> </div> </div> <div class="module-footer"> <button class="hairline-button" @click=${clearTable} ?disabled=${this.resultsTableData.length === 0}>Clear</button> </div> </div> `; // clang-format on } private async runSingleTCAV( config: CallConfig, positiveSlice: string, negativeSlice: string): Promise<TcavResults|undefined> { const comparisonSetLength = this.appState.currentInputData.length - config['concept_set_ids'].length; if (config['concept_set_ids'].length < MIN_EXAMPLES_LENGTH || comparisonSetLength < MIN_EXAMPLES_LENGTH) { return; } // All indexed inputs in the dataset are passed in, with the concept set // ids specified in the config. // TODO(b/178210779): Enable caching in the component's predict call. const result = await this.apiService.getInterpretations( this.appState.currentInputData, this.model, this.appState.currentDataset, TCAV_INTERPRETER_NAME, config, `Running ${TCAV_INTERPRETER_NAME}`); if (result === null) { return; } // TODO(lit-dev): Show local TCAV scores in the scalar chart. return { 'positiveSlice': positiveSlice, 'negativeSlice': negativeSlice, 'config': config, 'score': result[0]['result']['score'], 'p_val': result[0]['p_val'], 'random_mean': result[0]['random_mean'] }; } private async runTCAV() { this.isLoading = true; // TODO(lit-dev): Add option to run TCAV on selected examples. // TODO(lit-dev): Add option to run TCAV on categorical features. const promises: Array<Promise<TcavResults|undefined>> = []; for (const slicePair of this.slicePairs) { for (const gradClass of this.selectedClasses.values()) { for (const layer of this.selectedLayers.values()) { const positiveSlice = slicePair[0]; const negativeSlice = slicePair[1]; const conceptSetIds = this.sliceService.getSliceByName(positiveSlice)!; const config: CallConfig = { 'concept_set_ids': conceptSetIds, 'class_to_explain': gradClass, 'grad_layer': layer, 'dataset_name': this.appState.currentDataset, }; if (negativeSlice != null) { const negativeSliceIds = this.sliceService.getSliceByName(negativeSlice)!; config['negative_set_ids'] = negativeSliceIds; } promises.push( this.runSingleTCAV(config, positiveSlice, negativeSlice ?? '-')); } } } const results = await this.loadLatest('getResults', Promise.all(promises)); if (results == null) return; for (const res of results) { if (res == null) continue; if (res['config'] == null || res['score'] == null) continue; // clang-format off let scoreBar: TemplateResult|string = html`<tcav-score-bar score=${res['score']} meanVal=${res['random_mean']} clampVal=${1}> </tcav-score-bar>`; // clang-format on let displayScore = res.score.toFixed(3); if (res['p_val'] != null && res['p_val'] > MAX_P_VAL) { displayScore = '-'; scoreBar = HIGH_P_VAL_WARNING; } if (res['p_val'] == null) { scoreBar = NO_T_TESTING_WARNING; } this.resultsTableData.push({ 'Positive Slice': res['positiveSlice'], 'Negative Slice': res['negativeSlice'], 'Run': this.cavCounter, 'Embedding': res['config']['grad_layer'], 'Class': res['config']['class_to_explain'], 'CAV Score': displayScore, 'Score Bar': scoreBar }); } this.cavCounter++; this.isLoading = false; this.requestUpdate(); } static override shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { // Ensure the models can support TCAV and that the TCAV interpreter is // loaded. const supportsEmbs = doesOutputSpecContain(modelSpecs, 'Embeddings'); const supportsGrads = doesOutputSpecContain(modelSpecs, 'Gradients'); const multiclassPreds = doesOutputSpecContain(modelSpecs, 'MulticlassPreds'); if (!supportsGrads || !supportsEmbs || !multiclassPreds) { return false; } for (const modelInfo of Object.values(modelSpecs)) { if (modelInfo.interpreters.indexOf('tcav') !== -1) { return true; } } return false; } } declare global { interface HTMLElementTagNameMap { 'tcav-module': TCAVModule; } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AppIntegrationsClient } from "./AppIntegrationsClient"; import { CreateDataIntegrationCommand, CreateDataIntegrationCommandInput, CreateDataIntegrationCommandOutput, } from "./commands/CreateDataIntegrationCommand"; import { CreateEventIntegrationCommand, CreateEventIntegrationCommandInput, CreateEventIntegrationCommandOutput, } from "./commands/CreateEventIntegrationCommand"; import { DeleteDataIntegrationCommand, DeleteDataIntegrationCommandInput, DeleteDataIntegrationCommandOutput, } from "./commands/DeleteDataIntegrationCommand"; import { DeleteEventIntegrationCommand, DeleteEventIntegrationCommandInput, DeleteEventIntegrationCommandOutput, } from "./commands/DeleteEventIntegrationCommand"; import { GetDataIntegrationCommand, GetDataIntegrationCommandInput, GetDataIntegrationCommandOutput, } from "./commands/GetDataIntegrationCommand"; import { GetEventIntegrationCommand, GetEventIntegrationCommandInput, GetEventIntegrationCommandOutput, } from "./commands/GetEventIntegrationCommand"; import { ListDataIntegrationAssociationsCommand, ListDataIntegrationAssociationsCommandInput, ListDataIntegrationAssociationsCommandOutput, } from "./commands/ListDataIntegrationAssociationsCommand"; import { ListDataIntegrationsCommand, ListDataIntegrationsCommandInput, ListDataIntegrationsCommandOutput, } from "./commands/ListDataIntegrationsCommand"; import { ListEventIntegrationAssociationsCommand, ListEventIntegrationAssociationsCommandInput, ListEventIntegrationAssociationsCommandOutput, } from "./commands/ListEventIntegrationAssociationsCommand"; import { ListEventIntegrationsCommand, ListEventIntegrationsCommandInput, ListEventIntegrationsCommandOutput, } from "./commands/ListEventIntegrationsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateDataIntegrationCommand, UpdateDataIntegrationCommandInput, UpdateDataIntegrationCommandOutput, } from "./commands/UpdateDataIntegrationCommand"; import { UpdateEventIntegrationCommand, UpdateEventIntegrationCommandInput, UpdateEventIntegrationCommandOutput, } from "./commands/UpdateEventIntegrationCommand"; /** * <p>The Amazon AppIntegrations service enables you to configure and reuse connections to external * applications.</p> * <p>For information about how you can use external applications with Amazon Connect, see <a href="https://docs.aws.amazon.com/connect/latest/adminguide/crm.html">Set up pre-built * integrations</a> and <a href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-wisdom.html">Deliver information to agents using Amazon Connect Wisdom</a> * in the <i>Amazon Connect Administrator Guide</i>.</p> */ export class AppIntegrations extends AppIntegrationsClient { /** * <p>Creates and persists a DataIntegration resource.</p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <code>CreateDataIntegration</code> API.</p> * </note> */ public createDataIntegration( args: CreateDataIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<CreateDataIntegrationCommandOutput>; public createDataIntegration( args: CreateDataIntegrationCommandInput, cb: (err: any, data?: CreateDataIntegrationCommandOutput) => void ): void; public createDataIntegration( args: CreateDataIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateDataIntegrationCommandOutput) => void ): void; public createDataIntegration( args: CreateDataIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDataIntegrationCommandOutput) => void), cb?: (err: any, data?: CreateDataIntegrationCommandOutput) => void ): Promise<CreateDataIntegrationCommandOutput> | void { const command = new CreateDataIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an EventIntegration, given a specified name, description, and a reference to an * Amazon EventBridge bus in your account and a partner event source that pushes events to that bus. No * objects are created in the your account, only metadata that is persisted on the * EventIntegration control plane.</p> */ public createEventIntegration( args: CreateEventIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<CreateEventIntegrationCommandOutput>; public createEventIntegration( args: CreateEventIntegrationCommandInput, cb: (err: any, data?: CreateEventIntegrationCommandOutput) => void ): void; public createEventIntegration( args: CreateEventIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateEventIntegrationCommandOutput) => void ): void; public createEventIntegration( args: CreateEventIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateEventIntegrationCommandOutput) => void), cb?: (err: any, data?: CreateEventIntegrationCommandOutput) => void ): Promise<CreateEventIntegrationCommandOutput> | void { const command = new CreateEventIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the DataIntegration. Only DataIntegrations that don't have any * DataIntegrationAssociations can be deleted. Deleting a DataIntegration also deletes the * underlying Amazon AppFlow flow and service linked role. </p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> API.</p> * </note> */ public deleteDataIntegration( args: DeleteDataIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteDataIntegrationCommandOutput>; public deleteDataIntegration( args: DeleteDataIntegrationCommandInput, cb: (err: any, data?: DeleteDataIntegrationCommandOutput) => void ): void; public deleteDataIntegration( args: DeleteDataIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteDataIntegrationCommandOutput) => void ): void; public deleteDataIntegration( args: DeleteDataIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDataIntegrationCommandOutput) => void), cb?: (err: any, data?: DeleteDataIntegrationCommandOutput) => void ): Promise<DeleteDataIntegrationCommandOutput> | void { const command = new DeleteDataIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified existing event integration. If the event integration is associated * with clients, the request is rejected.</p> */ public deleteEventIntegration( args: DeleteEventIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteEventIntegrationCommandOutput>; public deleteEventIntegration( args: DeleteEventIntegrationCommandInput, cb: (err: any, data?: DeleteEventIntegrationCommandOutput) => void ): void; public deleteEventIntegration( args: DeleteEventIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteEventIntegrationCommandOutput) => void ): void; public deleteEventIntegration( args: DeleteEventIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteEventIntegrationCommandOutput) => void), cb?: (err: any, data?: DeleteEventIntegrationCommandOutput) => void ): Promise<DeleteEventIntegrationCommandOutput> | void { const command = new DeleteEventIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the DataIntegration.</p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> API.</p> * </note> */ public getDataIntegration( args: GetDataIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<GetDataIntegrationCommandOutput>; public getDataIntegration( args: GetDataIntegrationCommandInput, cb: (err: any, data?: GetDataIntegrationCommandOutput) => void ): void; public getDataIntegration( args: GetDataIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetDataIntegrationCommandOutput) => void ): void; public getDataIntegration( args: GetDataIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDataIntegrationCommandOutput) => void), cb?: (err: any, data?: GetDataIntegrationCommandOutput) => void ): Promise<GetDataIntegrationCommandOutput> | void { const command = new GetDataIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the event integration.</p> */ public getEventIntegration( args: GetEventIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<GetEventIntegrationCommandOutput>; public getEventIntegration( args: GetEventIntegrationCommandInput, cb: (err: any, data?: GetEventIntegrationCommandOutput) => void ): void; public getEventIntegration( args: GetEventIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEventIntegrationCommandOutput) => void ): void; public getEventIntegration( args: GetEventIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEventIntegrationCommandOutput) => void), cb?: (err: any, data?: GetEventIntegrationCommandOutput) => void ): Promise<GetEventIntegrationCommandOutput> | void { const command = new GetEventIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of DataIntegration associations in the account.</p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> API.</p> * </note> */ public listDataIntegrationAssociations( args: ListDataIntegrationAssociationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListDataIntegrationAssociationsCommandOutput>; public listDataIntegrationAssociations( args: ListDataIntegrationAssociationsCommandInput, cb: (err: any, data?: ListDataIntegrationAssociationsCommandOutput) => void ): void; public listDataIntegrationAssociations( args: ListDataIntegrationAssociationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDataIntegrationAssociationsCommandOutput) => void ): void; public listDataIntegrationAssociations( args: ListDataIntegrationAssociationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDataIntegrationAssociationsCommandOutput) => void), cb?: (err: any, data?: ListDataIntegrationAssociationsCommandOutput) => void ): Promise<ListDataIntegrationAssociationsCommandOutput> | void { const command = new ListDataIntegrationAssociationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of DataIntegrations in the account.</p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> API.</p> * </note> */ public listDataIntegrations( args: ListDataIntegrationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListDataIntegrationsCommandOutput>; public listDataIntegrations( args: ListDataIntegrationsCommandInput, cb: (err: any, data?: ListDataIntegrationsCommandOutput) => void ): void; public listDataIntegrations( args: ListDataIntegrationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDataIntegrationsCommandOutput) => void ): void; public listDataIntegrations( args: ListDataIntegrationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDataIntegrationsCommandOutput) => void), cb?: (err: any, data?: ListDataIntegrationsCommandOutput) => void ): Promise<ListDataIntegrationsCommandOutput> | void { const command = new ListDataIntegrationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of event integration associations in the account. </p> */ public listEventIntegrationAssociations( args: ListEventIntegrationAssociationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListEventIntegrationAssociationsCommandOutput>; public listEventIntegrationAssociations( args: ListEventIntegrationAssociationsCommandInput, cb: (err: any, data?: ListEventIntegrationAssociationsCommandOutput) => void ): void; public listEventIntegrationAssociations( args: ListEventIntegrationAssociationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListEventIntegrationAssociationsCommandOutput) => void ): void; public listEventIntegrationAssociations( args: ListEventIntegrationAssociationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEventIntegrationAssociationsCommandOutput) => void), cb?: (err: any, data?: ListEventIntegrationAssociationsCommandOutput) => void ): Promise<ListEventIntegrationAssociationsCommandOutput> | void { const command = new ListEventIntegrationAssociationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a paginated list of event integrations in the account.</p> */ public listEventIntegrations( args: ListEventIntegrationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListEventIntegrationsCommandOutput>; public listEventIntegrations( args: ListEventIntegrationsCommandInput, cb: (err: any, data?: ListEventIntegrationsCommandOutput) => void ): void; public listEventIntegrations( args: ListEventIntegrationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListEventIntegrationsCommandOutput) => void ): void; public listEventIntegrations( args: ListEventIntegrationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListEventIntegrationsCommandOutput) => void), cb?: (err: any, data?: ListEventIntegrationsCommandOutput) => void ): Promise<ListEventIntegrationsCommandOutput> | void { const command = new ListEventIntegrationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the tags for the specified resource.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds the specified tags to the specified resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified tags from the specified resource.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the description of a DataIntegration.</p> * <note> * <p>You cannot create a DataIntegration association for a DataIntegration that has been previously associated. * Use a different DataIntegration, or recreate the DataIntegration using the * <a href="https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateDataIntegration.html">CreateDataIntegration</a> API.</p> * </note> */ public updateDataIntegration( args: UpdateDataIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateDataIntegrationCommandOutput>; public updateDataIntegration( args: UpdateDataIntegrationCommandInput, cb: (err: any, data?: UpdateDataIntegrationCommandOutput) => void ): void; public updateDataIntegration( args: UpdateDataIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateDataIntegrationCommandOutput) => void ): void; public updateDataIntegration( args: UpdateDataIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDataIntegrationCommandOutput) => void), cb?: (err: any, data?: UpdateDataIntegrationCommandOutput) => void ): Promise<UpdateDataIntegrationCommandOutput> | void { const command = new UpdateDataIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the description of an event integration.</p> */ public updateEventIntegration( args: UpdateEventIntegrationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateEventIntegrationCommandOutput>; public updateEventIntegration( args: UpdateEventIntegrationCommandInput, cb: (err: any, data?: UpdateEventIntegrationCommandOutput) => void ): void; public updateEventIntegration( args: UpdateEventIntegrationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateEventIntegrationCommandOutput) => void ): void; public updateEventIntegration( args: UpdateEventIntegrationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateEventIntegrationCommandOutput) => void), cb?: (err: any, data?: UpdateEventIntegrationCommandOutput) => void ): Promise<UpdateEventIntegrationCommandOutput> | void { const command = new UpdateEventIntegrationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import U from './util' import { IVisualization } from './index' const POLE_TO_POLE_RADIUS = 9 const POLE_EFFECT_RADIUS = 3 const POLE_SIZE = 1 interface IPole extends IPoint { powerArea: IPoint[] poweredEntityAreas: IPoint[][] powerGiven: number distFromMidOfConsumers: number } interface IGroup extends IPoint { poles: (IPole | IPoint)[] lines: IPole[][] } interface IArea extends IPoint { power: boolean } /* How the algorithm works: 1. form valid pole positions by searching away from the given entities (create a radius around the entity where a pole could spawn) and removing positions that are occupied by entities 2. form possible pole array (data that will help with sorting the poles in the next stage) 3. add poles one by one to the pole array prioritizing (most to least important): - nr of entities powered - distance from the average position of all powered entities and removing poles from the array that no longer have entities to power 4. form lines between poles (DT) a line can only be formed if the 2 poles are within POLE_TO_POLE_RADIUS distance of each other 5. form groups from the lines (group together poles that are connected by lines) 6. add leftover poles (those that couldn't form lines with any other pole) each pole will form a group 7. connect groups together (DT) each iteration, try to connect 2 groups together with one generated pole or at least add a new pole to one of the groups in the direction of another group DT = using delaunay triangulation to form lines between x (for optimization) */ export function generatePoles(entities: { position: IPoint; size: number; power: boolean }[]): { poles: { name: string position: IPoint }[] info: { totalPoles: number } visualizations: IVisualization[] } { const visualizations: IVisualization[] = [] function addVisualization(path: IPoint[], size = 32, alpha = 1, color?: number): void { visualizations.push({ path: path.map(p => ({ x: p.x + 0.5, y: p.y + 0.5 })), size, alpha, color, }) } const entityAreas = entities.map(e => U.range(0, e.size * e.size).map(i => ({ x: Math.floor(e.position.x) + ((i % e.size) - Math.floor(e.size / 2)), y: Math.floor(e.position.y) + (Math.floor(i / e.size) - Math.floor(e.size / 2)), power: e.power, })) ) const occupiedPositions = new Set(entityAreas.flat().map(U.hashPoint)) // addVisualization(entityAreas.flat()) // GENERATE VALID POLE POSITIONS const validPolePositions = U.uniqPoints( entities .filter(e => e.power) .flatMap(e => { const searchSize = e.size + POLE_SIZE * 2 + (POLE_EFFECT_RADIUS - 1) * 2 return U.range(0, searchSize * searchSize).map<IPoint>(i => ({ x: Math.floor(e.position.x) + ((i % searchSize) - Math.floor(searchSize / 2)), y: Math.floor(e.position.y) + (Math.floor(i / searchSize) - Math.floor(searchSize / 2)), })) }) ).filter(p => !occupiedPositions.has(U.hashPoint(p))) // addVisualization(validPolePositions) const pointToEntityArea = entityAreas .filter(area => area.every(p => p.power)) .reduce<Map<string, IArea[]>>((map, area) => { for (const p of area) { map.set(U.hashPoint(p), area) } return map }, new Map()) // GENERATE POSSIBLE POLES let possiblePoles: IPole[] = validPolePositions.map(mid => { const D = POLE_SIZE + POLE_EFFECT_RADIUS * 2 const powerArea = U.range(0, D * D).map(i => ({ x: mid.x + ((i % D) - Math.floor(D / 2)), y: mid.y + (Math.floor(i / D) - Math.floor(D / 2)), })) const powerGiven = powerArea.reduce<IArea[][]>((acc, p) => { const area = pointToEntityArea.get(U.hashPoint(p)) if (area && !acc.includes(area)) acc.push(area) return acc }, []) const midOfConsumers = powerGiven .map(p => p[4]) .reduce<IPoint>( (m, p) => { m.x += p.x m.y += p.y return m }, { x: 0, y: 0 } ) const distFromMidOfConsumers = Math.abs(midOfConsumers.x / powerGiven.length - mid.x) + Math.abs(midOfConsumers.y / powerGiven.length - mid.y) return { ...mid, powerArea, poweredEntityAreas: powerGiven, powerGiven: powerGiven.length, distFromMidOfConsumers, } }) const entAreaToPoles = possiblePoles.reduce<Map<IPoint[], IPole[]>>((map, p) => { for (const area of p.poweredEntityAreas) { const exists = map.get(area) if (exists) { exists.push(p) } else { map.set(area, [p]) } } return map }, new Map()) // GENERATE POLES const poles: IPole[] = [] while (possiblePoles.length) { possiblePoles = possiblePoles .sort((a, b) => a.distFromMidOfConsumers - b.distFromMidOfConsumers) .sort((a, b) => b.powerGiven - a.powerGiven) const pole = possiblePoles.shift() poles.push(pole) const toRemove = pole.poweredEntityAreas.flatMap(area => { const poles = entAreaToPoles.get(area) if (!poles) return [] for (const p of poles) { p.poweredEntityAreas = p.poweredEntityAreas.filter(a => a !== area) p.powerGiven -= 1 } return poles.filter(p => p.poweredEntityAreas.length === 0) }) possiblePoles = possiblePoles.filter(p => !toRemove.includes(p)) } addVisualization(poles, 16, 1, 0x00bfff) // GENERATE LINES const lines = U.pointsToLines(poles).filter(l => U.pointInCircle(l[0], l[1], POLE_TO_POLE_RADIUS) ) // GENERATE GROUPS let groups: IGroup[] = [] const addedPoles: IPole[] = [] while (lines.length) { const l = lines.shift() const g1 = groups.find(g => g.poles.includes(l[0])) const g2 = groups.find(g => g.poles.includes(l[1])) if (!g1 && !g2) { groups.push({ poles: [...l], lines: [l], x: 0, y: 0 }) addedPoles.push(...l) continue } if (g1 && !g2) { g1.poles.push(l[1]) g1.lines.push(l) addedPoles.push(l[1]) continue } if (!g1 && g2) { g2.poles.push(l[0]) g2.lines.push(l) addedPoles.push(l[0]) continue } if (g1 && g2 && g1 !== g2) { g1.poles = g1.poles.concat(g2.poles) g1.lines = g1.lines.concat(g2.lines) groups = groups.filter(g => g !== g2) continue } } // ADD LEFTOVER POLES groups = groups.concat( poles.filter(p => !addedPoles.includes(p)).map(p => ({ poles: [p], lines: [], x: 0, y: 0 })) ) for (const p of poles) { occupiedPositions.add(U.hashPoint(p)) } // groups // .map(g => g.poles.flat()) // .forEach(p => addVisualization(p, 32)) const r2 = POLE_TO_POLE_RADIUS * 2 + 1 const circleOffsets = U.range(0, r2 * r2) .map(i => ({ x: (i % r2) - Math.floor(r2 / 2), y: Math.floor(i / r2) - Math.floor(r2 / 2), })) .filter(o => U.pointInCircle(o, { x: 0, y: 0 }, POLE_TO_POLE_RADIUS)) // CONNECT GROUPS const connectionPoles: IPoint[] = [] let finalGroup: IGroup while (groups.length) { for (const g of groups) { g.x = g.poles.reduce((acc, e) => acc + e.x, 0) / g.poles.length g.y = g.poles.reduce((acc, e) => acc + e.y, 0) / g.poles.length } groups = groups.sort((a, b) => a.poles.length - b.poles.length) const groupsCopy = [...groups] const group = groups.shift() if (!groups.length) { finalGroup = group break } const DATA = U.pointsToLines(groupsCopy) .filter(l => l.includes(group)) .map(l => l.find(g => g !== group)) .map(otherGroup => { const shortestLine = U.pointsToLines([...group.poles, ...otherGroup.poles]) // filter out lines that are in the same group .filter( l => !( (group.poles.includes(l[0]) && group.poles.includes(l[1])) || (otherGroup.poles.includes(l[0]) && otherGroup.poles.includes(l[1])) ) ) .map(l => ({ poles: l, dist: U.euclideanDistance(l[0], l[1]), })) .sort((a, b) => a.dist - b.dist)[0] const g1pole = shortestLine.poles.find(p => group.poles.includes(p)) const g2pole = shortestLine.poles.find(p => otherGroup.poles.includes(p)) const betweenG1AndG2Poles = { x: (g1pole.x + g2pole.x) / 2, y: (g1pole.y + g2pole.y) / 2, } return { g1pole, g2pole, otherGroup, dist: shortestLine.dist, betweenG1AndG2Poles, } }) .sort((a, b) => a.dist - b.dist)[0] const newPolePos = circleOffsets .map(o => ({ x: DATA.g1pole.x + o.x, y: DATA.g1pole.y + o.y, })) .filter(p => !occupiedPositions.has(U.hashPoint(p))) .sort((a, b) => { const point = DATA.dist > POLE_TO_POLE_RADIUS + 2 ? DATA.g2pole : DATA.betweenG1AndG2Poles return U.manhattenDistance(a, point) - U.manhattenDistance(b, point) })[0] connectionPoles.push(newPolePos) if (U.pointInCircle(newPolePos, DATA.g2pole, POLE_TO_POLE_RADIUS)) { DATA.otherGroup.poles.push(...group.poles, newPolePos) } else { group.poles.push(newPolePos) groups.push(group) } } addVisualization(connectionPoles, 16, 1, 0x8a2be2) const info = { totalPoles: finalGroup.poles.length, } return { poles: finalGroup.poles.map(p => ({ name: 'medium_electric_pole', position: { x: p.x + 0.5, y: p.y + 0.5 }, })), info, visualizations, } }
the_stack
import express from 'express'; import * as ThingTalk from 'thingtalk'; import * as Genie from 'genie-toolkit'; import * as db from '../util/db'; import * as model from '../model/mturk'; import * as deviceModel from '../model/device'; import * as example from '../model/example'; import AdminThingpediaClient from '../util/admin-thingpedia-client'; import * as iv from '../util/input_validation'; import * as i18n from '../util/i18n'; import { BadRequestError, ForbiddenError, NotFoundError } from '../util/errors'; import * as MTurkUtils from '../util/mturk'; const router = express.Router(); async function autoValidateParaphrase(dbClient : db.Client, batchId : number, language : string, schemas : ThingTalk.SchemaRetriever, utterance : string, thingtalk : string) { // FIXME this should use Genie's ParaphraseValidator const tokenizer = i18n.get(language).genie.getTokenizer(); const [program, { tokens: preprocessed, entities }] = await Promise.all([ ThingTalk.Syntax.parse(thingtalk, ThingTalk.Syntax.SyntaxType.Normal, { locale: language, timezone: 'UTC' }).typecheck(schemas), tokenizer.tokenize(utterance) ]); let target_code; try { target_code = Genie.ThingTalkUtils.serializePrediction(program, preprocessed, entities, { locale: language, timezone: 'UTC' }); } catch(e) { throw new BadRequestError(e.message); } return example.create(dbClient, { utterance: utterance, preprocessed: preprocessed.join(' '), target_code: target_code.join(' '), target_json: '', // FIXME type: 'turking' + batchId, flags: '', // no "training" flag until validation language: language, is_base: false }); } function inputValidateSubmission(req : express.Request, res : express.Response, next : express.NextFunction) { for (let i = 1; i < MTurkUtils.SYNTHETIC_PER_PARAPHRASE_HIT + 1; i++) { const program_id = req.body[`program_id${i}`]; const thingtalk = req.body[`thingtalk${i}`]; if (!iv.checkKey(program_id, 'string')) { iv.failKey(req, res, `program_id${i}`, {}); return; } if (!iv.checkKey(thingtalk, 'string')) { iv.failKey(req, res, `thingtalk${i}`, {}); return; } for (let j = 1; j < MTurkUtils.PARAPHRASES_PER_SENTENCE + 1; j ++) { const paraphrase = req.body[`paraphrase${i}-${j}`]; if (!iv.checkKey(paraphrase, 'string')) { iv.failKey(req, res, `paraphrase${i}-${j}`, {}); return; } } } next(); } function makeSubmissionId() { // FIXME should probably use a cryptographic ID here return (Math.random() + 1).toString(36).substring(2, 10) + (Math.random() + 1).toString(36).substring(2, 10); } router.post('/submit', iv.validatePOST({ batch: 'string', hit: 'integer', worker: 'string' }), inputValidateSubmission, (req, res, next) => { const submissionId = makeSubmissionId(); db.withTransaction(async (dbClient) => { const submissions = []; const batch = await model.getBatchDetails(dbClient, req.body.batch); if (batch.status === 'created') await model.updateBatch(dbClient, batch.id, { status: 'paraphrasing' }); else if (batch.status !== 'paraphrasing') throw new ForbiddenError(req._("The HIT you're trying to submit was already closed.")); const schemas = new ThingTalk.SchemaRetriever(new AdminThingpediaClient(batch.language, dbClient), null, true); let examples = []; for (let i = 1; i < 5; i ++) { const program_id = Number(req.body[`program_id${i}`]); const thingtalk = req.body[`thingtalk${i}`] as string; //let sentence = req.body[`sentence${i}`]; for (let j = 1; j < 3; j ++) { const paraphrase = req.body[`paraphrase${i}-${j}`] as string; if (paraphrase.toLowerCase().replace(/\./g, '').trim() === 'no idea') continue; examples.push(autoValidateParaphrase(dbClient, batch.id, batch.language, schemas, paraphrase, thingtalk)); submissions.push({ submission_id: submissionId, program_id: program_id, target_count: 3, accept_count: 0, reject_count: 0, example_id: -1 }); } } examples = await Promise.all(examples); for (let i = 0; i < examples.length; i++) submissions[i].example_id = examples[i]; await model.logSubmission(dbClient, submissionId, batch.id, Number(req.body.hit), req.body.worker); await model.insertSubmission(dbClient, submissions); }).then(() => { res.render('mturk-submit', { page_title: req._('Thank you'), token: submissionId }); }).catch(next); }); router.get(`/submit/:batch/:hit`, (req, res, next) => { const hitId = parseInt(req.params.hit); db.withTransaction(async (dbClient) => { const batch = await model.getBatchDetails(dbClient, req.params.batch); if (batch.status !== 'created' && batch.status !== 'paraphrasing') throw new ForbiddenError(req._("The HIT you're trying to submit was already closed.")); const hit = await model.getHIT(dbClient, batch.id, hitId); if (hit.length === 0) throw new NotFoundError(); const allDeviceKinds = new Set<string>(); const program_id = []; const sentences = []; const code = []; let hints = []; for (const row of hit) { program_id.push(row.id); code.push(row.thingtalk); sentences.push(row.sentence); const hint = new Set<string>(); const parsed = ThingTalk.Syntax.parse(row.thingtalk, ThingTalk.Syntax.SyntaxType.Normal, { locale: batch.language, timezone: 'UTC' }); for (const [,prim] of parsed.iteratePrimitives(false)) { if (prim.selector.kind !== 'org.thingpedia.builtin.thingengine.builtin') { allDeviceKinds.add(prim.selector.kind); hint.add(prim.selector.kind); } } hints.push(Array.from(hint)); } const allDevices = await deviceModel.getNamesByKinds(dbClient, Array.from(allDeviceKinds)); // remove hints that refer to devices we did find (unlikely but defensive) hints = hints.map((hint) => hint.filter((d) => !!allDevices[d])); return [program_id, code, sentences, hints, allDevices]; }, 'serializable', 'read only').then(([program_id, code, sentences, hints, allDevices]) => { res.render('mturk', { page_title: req._('Paraphrase'), hit: hitId, batch: req.params.batch, program_id: program_id, code: code, sentences: sentences, hints, allDevices, csrfToken: req.csrfToken() }); }).catch(next); }); router.post('/validate', iv.validatePOST({ batch: 'string', hit: 'integer', worker: 'string' }), (req, res, next) => { db.withTransaction(async (dbClient) => { const batch = await model.getBatchDetails(dbClient, req.body.batch); // catch accidental double-submissions quietly, and do nothing const existing = await model.getExistingValidationSubmission(dbClient, batch.id, Number(req.body.hit), req.body.worker); if (existing.length > 0) return existing[0].submission_id; if (batch.status !== 'validating') throw new ForbiddenError(req._("The HIT you're trying to submit is not open yet, or was already closed.")); const hits = await model.getValidationHIT(dbClient, batch.id, Number(req.body.hit)); const submissionId = makeSubmissionId(); let errors = 0; const validationRows = []; const good = []; const bad = []; for (const hit of hits) { const answer = req.body['validation-' + hit.id]; if (answer !== 'same' && answer !== 'different') { throw new BadRequestError(req._("Missing or invalid parameter %s") .format(`validation-${hit.id}`)); } if (hit.type === 'fake-same' && answer !== 'same') { errors ++; } else if (hit.type === 'fake-different' && answer !== 'different') { errors ++; } else if (hit.type === 'real') { validationRows.push({ validation_sentence_id: hit.id, submission_id: submissionId, answer: answer } as const); if (answer === 'same') good.push(hit.example_id!); else bad.push(hit.example_id!); } } if (errors > 2) throw new BadRequestError(req._("You have made too many mistakes. Please go back and try again.")); await model.logValidationSubmission(dbClient, submissionId, batch.id, Number(req.body.hit), req.body.worker); await model.insertValidationSubmission(dbClient, validationRows); await model.markSentencesGood(dbClient, good); await model.markSentencesBad(dbClient, bad); return submissionId; }).then((submissionId) => { res.render('mturk-submit', { page_title: req._('Thank you'), token: submissionId }); }).catch(next); }); router.get(`/validate/:batch/:hit`, (req, res, next) => { const hitId = Number(req.params.hit); db.withTransaction(async (dbClient) => { const batch = await model.getBatchDetails(dbClient, req.params.batch); if (batch.status !== 'validating') throw new ForbiddenError(req._("The HIT you're trying to submit is not open yet, or was already closed.")); return model.getValidationHIT(dbClient, batch.id, hitId); }, 'serializable', 'read only').then((hit) => { if (hit.length === 0) throw new NotFoundError(); const sentences = []; let current = undefined; for (const row of hit) { if (current && row.program_id === current.synthetic_id) { current.paraphrases.push({ id: row.id, paraphrase: row.paraphrase }); } else { current = { synthetic_id: row.program_id, synthetic: row.synthetic, paraphrases: [{ id: row.id, paraphrase: row.paraphrase }] }; sentences.push(current); } } res.render('mturk_validate', { page_title: req._("Genie - Paraphrase Validation"), hit: hitId, batch: req.params.batch, sentences, csrfToken: req.csrfToken() }); }).catch(next); }); export default router;
the_stack
import { toAsyncIterable } from '@esfx/async-iter-fromsync'; import { AsyncHierarchyIterable } from '@esfx/async-iter-hierarchy'; import { IndexedCollection } from '@esfx/collection-core'; import { HashMap } from "@esfx/collections-hashmap"; import { HashSet } from "@esfx/collections-hashset"; import { Comparer, Comparison, Equaler, EqualityComparison } from "@esfx/equatable"; import { identity, T } from '@esfx/fn'; import * as assert from "@esfx/internal-assert"; import { Index } from "@esfx/interval"; import { HierarchyIterable } from '@esfx/iter-hierarchy'; import { Lookup } from "@esfx/iter-lookup"; import { createGroupingsAsync, flowHierarchy } from './internal/utils'; import { consumeAsync, ConsumeAsyncOptions, emptyAsync } from './queries'; import { prependAsync, takeRightAsync } from './subqueries'; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @category Scalar */ export function reduceAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): Promise<T>; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @category Scalar * @param seed An optional seed value. */ export function reduceAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U): Promise<U>; /** * Computes a scalar value by applying an accumulator callback over each element. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ export function reduceAsync<T, U, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U, resultSelector: (result: U, count: number) => R | PromiseLike<R>): Promise<R>; export function reduceAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T, resultSelector: (result: T, count: number) => PromiseLike<T> | T = identity): Promise<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(accumulator, "accumulator"); assert.mustBeFunction(resultSelector, "resultSelector"); return reduceAsyncCore(source, accumulator, arguments.length > 2, seed, resultSelector); } async function reduceAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, hasCurrent: boolean, current?: T, resultSelector: (result: T, count: number) => PromiseLike<T> | T = identity): Promise<T> { let count = 0; for await (const value of toAsyncIterable(source)) { if (!hasCurrent) { hasCurrent = true; current = value; } else { current = await accumulator(current!, value, count); } count++; } return resultSelector(current!, count); } /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @category Scalar */ export function reduceRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T): Promise<T>; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @category Scalar */ export function reduceRightAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U): Promise<U>; /** * Computes a scalar value by applying an accumulator callback over each element in reverse. * * @param source An `AsyncIterable` or `Iterable` object. * @param accumulator the callback used to compute the result. * @param seed An optional seed value. * @param resultSelector An optional callback used to compute the final result. * @category Scalar */ export function reduceRightAsync<T, U, R>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: U, element: T, offset: number) => PromiseLike<U> | U, seed: U, resultSelector: (result: U, count: number) => R | PromiseLike<R>): Promise<R>; export function reduceRightAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, seed?: T, resultSelector: (result: T, count: number) => PromiseLike<T> | T = identity): Promise<T> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(accumulator, "accumulator"); assert.mustBeFunction(resultSelector, "resultSelector"); return reduceRightAsyncCore(source, accumulator, arguments.length > 2, seed, resultSelector); } async function reduceRightAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, accumulator: (current: T, element: T, offset: number) => PromiseLike<T> | T, hasCurrent: boolean, current: T | undefined, resultSelector: (result: T, count: number) => PromiseLike<T> | T): Promise<T> { const sourceArray = await toArrayAsync(source); let count = 0; for (let offset = sourceArray.length - 1; offset >= 0; offset--) { const value = sourceArray[offset]; if (!hasCurrent) { current = value; hasCurrent = true; } else { current = await accumulator(current!, value, offset); } count++; } return resultSelector(current!, count); } /** * Counts the number of elements, optionally filtering elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function countAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T): Promise<number> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return countAsyncCore(source, predicate); } async function countAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<number> { if (predicate === T) { if (Array.isArray(source)) return source.length; if (source instanceof Set || source instanceof Map) return source.size; } let count = 0; for await (const element of source) { if (predicate === T || await predicate(element)) { count++; } } return count; } /** * Gets the first element, optionally filtering elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function firstAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the first element, optionally filtering elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function firstAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; export function firstAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T): Promise<T | undefined> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return firstAsyncCore(source, predicate); } async function firstAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); for await (const element of source) { const result = predicate(element); if (typeof result === "boolean" ? result : await result) { return element; } } return undefined; } /** * Gets the last element of an `AsyncIterable` or `Iterable`, optionally filtering elements using the supplied * callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function lastAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the last element of an `AsyncIterable` or `Iterable`, optionally filtering elements using the supplied * callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function lastAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; export function lastAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T): Promise<T | undefined> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return lastAsyncCore(source, predicate); } async function lastAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined> { let last: T | undefined; for await (const element of source) { const result = predicate(element); if (typeof result === "boolean" ? result : await result) { last = element; } } return last; } /** * Gets the only element, or returns `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function singleAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => element is U): Promise<U | undefined>; /** * Gets the only element, or returns `undefined`. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function singleAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate?: (element: T) => PromiseLike<boolean> | boolean): Promise<T | undefined>; export function singleAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T) { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return singleAsyncCore(source, predicate); } async function singleAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean) { let hasResult = false; let single: T | undefined; for await (const element of source) { const result = predicate(element); if (typeof result === "boolean" ? result : await result) { if (hasResult) { return undefined; } hasResult = true; single = element; } } return hasResult ? single : undefined; } /** * Gets the minimum element of an `AsyncIterable`, optionally comparing the keys of each element using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ export function minByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): Promise<T | undefined> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return minByAsyncCore(source, keySelector,keyComparer); } async function minByAsyncCore<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyComparer: Comparer<K>): Promise<T | undefined> { let hasResult = false; let result: T | undefined; let resultKey: K | undefined; for await (const element of source) { const key = keySelector(element); if (!hasResult) { result = element; resultKey = key; hasResult = true; } else if (keyComparer.compare(key, resultKey!) < 0) { result = element; resultKey = key; } } return result; } /** * Gets the minimum element of an `AsyncIterable`, optionally comparing elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param comparer An optional callback used to compare two elements. * @category Scalar */ export function minAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, comparer: Comparison<T> | Comparer<T> = Comparer.defaultComparer): Promise<T | undefined> { if (typeof comparer === "function") comparer = Comparer.create(comparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeType(Comparer.hasInstance, comparer, "comparer"); return minByAsyncCore(source, identity, comparer); } /** * Gets the maximum element of an `AsyncIterable`, optionally comparing the keys of each element using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to choose the key to compare. * @param keyComparer An optional callback used to compare the keys. * @category Scalar */ export function maxByAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyComparer: Comparison<K> | Comparer<K> = Comparer.defaultComparer): Promise<T | undefined> { if (typeof keyComparer === "function") keyComparer = Comparer.create(keyComparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeType(Comparer.hasInstance, keyComparer, "keyComparer"); return maxByAsyncCore(source, keySelector, keyComparer); } async function maxByAsyncCore<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (value: T) => K, keyComparer: Comparer<K>): Promise<T | undefined> { let hasResult = false; let result: T | undefined; let resultKey: K | undefined; for await (const element of source) { const key = keySelector(element); if (!hasResult) { result = element; resultKey = key; hasResult = true; } else if (keyComparer.compare(key, resultKey!) > 0) { result = element; resultKey = key; } } return result; } /** * Gets the maximum element of an `AsyncIterable`, optionally comparing elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param comparer An optional callback used to compare two elements. * @category Scalar */ export function maxAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, comparer: Comparison<T> | Comparer<T> = Comparer.defaultComparer): Promise<T | undefined> { if (typeof comparer === "function") comparer = Comparer.create(comparer); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeType(Comparer.hasInstance, comparer, "comparer"); return maxByAsyncCore(source, identity, comparer); } /** * Computes a scalar value indicating whether `source` contains any elements, * optionally filtering the elements using the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate An optional callback used to match each element. * @category Scalar */ export function someAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean = T): Promise<boolean> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return someAsyncCore(source, predicate); } async function someAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean> { for await (const element of source) { const result = predicate(element); if (typeof result === "boolean" ? result : await result) { return true; } } return false; } /** * Computes a scalar value indicating whether all elements match the supplied callback. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate A callback used to match each element. * @category Scalar */ export function everyAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return everyAsyncCore(source, predicate); } async function everyAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T) => PromiseLike<boolean> | boolean): Promise<boolean> { let hasMatchingElements = false; for await (const element of source) { const result = predicate(element); if (!(typeof result === "boolean" ? result : await result)) { return false; } hasMatchingElements = true; } return hasMatchingElements; } /** * Unzips a sequence of tuples into a tuple of sequences. * @param source An `AsyncIterable` or `Iterable` * @category Scalar */ export function unzipAsync<T extends readonly any[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): Promise<{ -readonly [I in keyof T]: T[I][]; }>; /** * Unzips a sequence of tuples into a tuple of sequences. * @param source An `AsyncIterable` or `Iterable` * @param partSelector A callback that converts a result into a tuple. * @category Scalar */ export function unzipAsync<T, U extends readonly any[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, partSelector: (value: T) => PromiseLike<U> | U): Promise<{ -readonly [I in keyof U]: U[I][]; }> export function unzipAsync<T extends readonly any[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, partSelector: (value: T) => PromiseLike<T> | T = identity): Promise<any> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(partSelector, "partSelector"); return unzipAsyncCore(source, partSelector); } async function unzipAsyncCore<T extends readonly any[] | []>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, partSelector: (value: T) => PromiseLike<T> | T): Promise<any> { const result: any[][] = []; let length = -1; for await (const element of source) { const row = await partSelector(element); if (length === -1) { length = row.length; for (let i = 0; i < length; i++) { result.push([]); } } for (let i = 0; i < length; i++) { result[i].push(row[i]); } } return result; } /** * Invokes a callback for each element of `source`. * * @param source An `AsyncIterable` or `Iterable` object. * @param callback The callback to invoke. * @category Scalar */ export function forEachAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, callback: (element: T, offset: number) => void | PromiseLike<void>): Promise<void> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(callback, "callback"); return forEachAsyncCore(source, callback); } async function forEachAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, callback: (element: T, offset: number) => void | PromiseLike<void>): Promise<void> { let offset = 0; for await (const element of source) { const result = callback(element, offset++); if (typeof result !== "undefined") await result; } } /** * Creates a Map for the elements of the `AsyncIterable`. * * @param source An `Iterable` object. * @param keySelector A callback used to select a key for each element. * @category Scalar */ export function toMapAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K): Promise<Map<K, T>>; /** * Creates a Map for the elements of the `AsyncIterable`. * * @param source An `Iterable` object. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @category Scalar */ export function toMapAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V): Promise<Map<K, V>>; export function toMapAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<T | V> | T | V = identity) { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); return toMapAsyncCore(source, keySelector, elementSelector); } async function toMapAsyncCore<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<T | V> | T | V) { const map = new Map<K, T | V>(); for await (const item of source) { const key = keySelector(item); const element = await elementSelector(item); map.set(key, element); } return map; } /** * Creates a `HashMap` for the elements of the source. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ export function toHashMapAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Promise<HashMap<K, T>>; /** * Creates a `HashMap` for the elements of the source. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ export function toHashMapAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): Promise<HashMap<K, V>>; export function toHashMapAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K> = identity, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { keyEqualer = elementSelector; elementSelector = identity; } assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return toHashMapAsyncCore(source, keySelector, elementSelector); } async function toHashMapAsyncCore<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<T | V> | T | V, keyEqualer?: Equaler<K>) { const map = new HashMap<K, T | V>(keyEqualer); for await (const item of source) { const key = keySelector(item); const element = await elementSelector(item); map.set(key, element); } return map; } /** * Creates a Set for the elements of the Iterable. * * @param source An `Iterable` object. * @category Scalar */ export function toSetAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): Promise<Set<T>>; /** * Creates a Set for the elements of the Iterable. * * @param source An `Iterable` object. * @param elementSelector A callback that selects a value for each element. * @category Scalar */ export function toSetAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<V> | V): Promise<Set<V>>; export function toSetAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<T | V> | T | V = identity) { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(elementSelector, "elementSelector"); return toSetAsyncCore(source, elementSelector); } async function toSetAsyncCore<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<T | V> | T | V) { const set = new Set<T | V>(); for await (const item of source) { const element = await elementSelector(item); set.add(element); } return set; } /** * Creates a `HashSet` for the elements of the `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ export function toHashSetAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: Equaler<T>): Promise<HashSet<T>>; /** * Creates a `HashSet` for the elements of the `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @param elementSelector A callback that selects a value for each element. * @param equaler An `Equaler` object used to compare equality. * @category Scalar */ export function toHashSetAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<V> | V, equaler?: Equaler<V>): Promise<HashSet<V>>; export function toHashSetAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: ((element: T) => PromiseLike<T> | T) | Equaler<T> = identity, equaler?: Equaler<T>): Promise<Set<T> | HashSet<T>> { if (typeof elementSelector !== "function") { equaler = elementSelector; elementSelector = identity; } assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, equaler, "equaler"); return toHashSetAsyncCore(source, elementSelector, equaler); } async function toHashSetAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<T> | T = identity, equaler?: Equaler<T>): Promise<Set<T> | HashSet<T>> { const set = new HashSet<T>(equaler); for await (const item of source) { const element = await elementSelector(item); set.add(element); } return set; } /** * Creates an Array for the elements of the `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @category Scalar */ export function toArrayAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>): Promise<T[]>; /** * Creates an Array for the elements of the `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @param elementSelector A callback that selects a value for each element. * @category Scalar */ export function toArrayAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<V> | V): Promise<V[]>; export function toArrayAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<T> | T = identity): Promise<T[]> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(elementSelector, "elementSelector"); return toArrayAsyncCore(source, elementSelector); } async function toArrayAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<T> | T): Promise<T[]> { const result: T[] = []; for await (const item of source) { result.push(elementSelector === identity ? item : await elementSelector(item)); } return result; } /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ export function toObjectAsync<T, TProto extends object, K extends PropertyKey>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: TProto, keySelector: (element: T) => K): Promise<TProto & Record<K, T>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ export function toObjectAsync<T, TProto extends object>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: TProto, keySelector: (element: T) => PropertyKey): Promise<TProto & Record<PropertyKey, T>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ export function toObjectAsync<T, K extends PropertyKey>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null | undefined, keySelector: (element: T) => K): Promise<Record<K, T>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // function * obj.toString(); // "x",1:"y",2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0]); * obj.x; // ["x", 1] * obj.y; // ["y", 2] * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @category Scalar */ export function toObjectAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null | undefined, keySelector: (element: T) => PropertyKey): Promise<Record<PropertyKey, T>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ export function toObjectAsync<T, TProto extends object, K extends PropertyKey, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: TProto, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: K, value: V) => TypedPropertyDescriptor<V>): Promise<TProto & Record<K, V>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ export function toObjectAsync<T, TProto extends object, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: TProto, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, value: V) => TypedPropertyDescriptor<V>): Promise<TProto & Record<PropertyKey, V>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ export function toObjectAsync<T, K extends PropertyKey, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null | undefined, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: K, value: V) => TypedPropertyDescriptor<V>): Promise<Record<K, V>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ export function toObjectAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, value: V) => TypedPropertyDescriptor<V>): Promise<Record<PropertyKey, V>>; /** * Creates an Object for the elements of `source`. Properties are added via `Object.defineProperty`. * * ```ts * // As a regular object * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], undefined, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * * // with a custom prototype * const baseObject = { toString() { return `${this.x}:${this.y}` } }; * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], baseObject, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // function * obj.toString(); // 1:2 * * // with a null prototype * const obj = await toObjectAsync([Promise.resolve(["x", 1]), ["y", 2]], null, a => a[0], a => a[1]); * obj.x; // 1 * obj.y; // 2 * typeof obj.toString; // undefined * ``` * * @param source An `AsyncIterable` or `Iterable` object. * @param prototype The prototype for the object. If `prototype` is `null`, an object with a `null` * prototype is created. If `prototype` is `undefined`, the default `Object.prototype` is used. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param descriptorSelector A callback that defines the `PropertyDescriptor` for each property. * @category Scalar */ export function toObjectAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null | undefined, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector?: (key: PropertyKey, value: V) => PropertyDescriptor): Promise<object>; export function toObjectAsync<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null = Object.prototype, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<T | V> | T | V = identity, descriptorSelector: (key: PropertyKey, value: T | V) => PropertyDescriptor = makeDescriptor): Promise<object> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeObjectOrNull(prototype, "prototype"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeFunction(descriptorSelector, "descriptorSelector"); return toObjectAsyncCore(source, prototype, keySelector, elementSelector, descriptorSelector); } async function toObjectAsyncCore<T, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, prototype: object | null, keySelector: (element: T) => PropertyKey, elementSelector: (element: T) => PromiseLike<V> | V, descriptorSelector: (key: PropertyKey, value: V) => PropertyDescriptor): Promise<object> { const obj = prototype === Object.prototype ? {} : Object.create(prototype); for await (const item of source) { const key = keySelector(item); const element = await elementSelector(item); const descriptor = descriptorSelector(key, element); Object.defineProperty(obj, key, descriptor); } return obj; } function makeDescriptor<K, V>(_key: K, value: V) { return { enumerable: true, configurable: true, writable: true, value }; } /** * Creates a Lookup for the elements of the source. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select a key for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ export function toLookupAsync<T, K>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, keyEqualer?: Equaler<K>): Promise<Lookup<K, T>>; /** * Creates a Lookup for the elements of the source. * * @param source An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select a key for each element. * @param elementSelector A callback that selects a value for each element. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Scalar */ export function toLookupAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<V> | V, keyEqualer?: Equaler<K>): Promise<Lookup<K, V>>; export function toLookupAsync<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: ((element: T) => PromiseLike<T | V> | T | V) | Equaler<K> = identity, keyEqualer?: Equaler<K>) { if (typeof elementSelector === "object") { keyEqualer = elementSelector; elementSelector = identity; } assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(keySelector, "keySelector"); assert.mustBeFunction(elementSelector, "elementSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return toLookupAsyncCore(source, keySelector, elementSelector); } async function toLookupAsyncCore<T, K, V>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K, elementSelector: (element: T) => PromiseLike<T | V> | T | V, keyEqualer?: Equaler<K>) { return new Lookup(await createGroupingsAsync(source, keySelector, elementSelector, keyEqualer), keyEqualer); } /** * Pass the entire source to the provided callback, returning the result. * * @param source An `AsyncIterable` or `Iterable` object. * @param callback A callback function. * @category Sub`AsyncIterable` */ export function intoAsync<T, S extends AsyncIterable<T> | Iterable<PromiseLike<T> | T>, R>(source: S, callback: (source: S) => R): R { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(callback, "callback"); return callback(source); } /** * Computes the sum for a series of numbers. * NOTE: If any element is not a `number`, this overload will throw. * * @param source An `AsyncIterable` or `Iterable` object. * @category Scalar */ export function sumAsync(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>): Promise<number>; /** * Computes the sum for a series of numbers. * * @param source An `AsyncIterable` or `Iterable` object. * @param elementSelector A callback used to convert a value in `source` to a number. * @category Scalar */ export function sumAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<number> | number): Promise<number>; export function sumAsync(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>, elementSelector: (element: number) => PromiseLike<number> | number = identity): Promise<number> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(elementSelector, "elementSelector"); return sumAsyncCore(source, elementSelector); } async function sumAsyncCore(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>, elementSelector: (element: number) => PromiseLike<number> | number): Promise<number> { let sum = 0; for await (const element of source) { const value = elementSelector(element); const result = typeof value === "number" ? value : await value; assert.mustBeNumber(result); sum += result; } return sum; } /** * Computes the average for a series of numbers. * NOTE: If any element is not a `number`, this overload will throw. * * @param source An `AsyncIterable` or `Iterable` object. * @category Scalar */ export function averageAsync(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>): Promise<number>; /** * Computes the average for a series of numbers. * * @param source An `AsyncIterable` or `Iterable` object. * @param elementSelector A callback used to convert a value in `source` to a number. * @category Scalar */ export function averageAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, elementSelector: (element: T) => PromiseLike<number> | number): Promise<number>; export function averageAsync(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>, elementSelector: (element: number) => PromiseLike<number> | number = identity): Promise<number> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(elementSelector, "elementSelector"); return averageAsyncCore(source, elementSelector); } async function averageAsyncCore(source: AsyncIterable<number> | Iterable<PromiseLike<number> | number>, elementSelector: (element: number) => PromiseLike<number> | number): Promise<number> { let sum = 0; let count = 0; for await (const element of source) { const value = elementSelector(element); const result = typeof value === "number" ? value : await value; assert.mustBeNumber(result); sum += result; count++; } return count > 0 ? sum / count : 0; } const noCacheAndLeaveOpen: ConsumeAsyncOptions = { cacheElements: false, leaveOpen: true }; const cacheAndClose: ConsumeAsyncOptions = { cacheElements: true, leaveOpen: false }; /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that match the supplied predicate, and whose second element is an `AsyncIterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanAsync<TNode, T extends TNode, U extends T>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => element is U): Promise<[HierarchyIterable<TNode, U>, AsyncHierarchyIterable<TNode, T>]>; /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that match the supplied predicate, and whose second element is an `AsyncIterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[HierarchyIterable<TNode, T>, AsyncHierarchyIterable<TNode, T>]>; /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that match the supplied predicate, and whose second element is an `AsyncIterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanAsync<T, U extends T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => element is U): Promise<[Iterable<U>, AsyncIterable<T>]>; /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that match the supplied predicate, and whose second element is an `AsyncIterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]>; export function spanAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return spanAsyncCore(source, predicate); } async function spanAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]> { const prefix: T[] = []; const iterator = toAsyncIterable(source)[Symbol.asyncIterator](); let offset = 0; for await (const value of consumeAsync(iterator, noCacheAndLeaveOpen)) { const result = predicate(value, offset++); if (!(typeof result === "boolean" ? result : await result)) { const remaining = prependAsync(consumeAsync(iterator, cacheAndClose), value); return [ flowHierarchy({ [Symbol.iterator]() { return prefix[Symbol.iterator](); } }, source), flowHierarchy(remaining, source), ]; } prefix.push(value); } return [ flowHierarchy({ [Symbol.iterator]() { return prefix[Symbol.iterator](); } }, source), flowHierarchy(emptyAsync<T>(), source), ]; } /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that do not match the supplied predicate, and whose second element is an `AsyncIterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanUntilAsync<TNode, T extends TNode>(source: AsyncHierarchyIterable<TNode, T> | HierarchyIterable<TNode, T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[HierarchyIterable<T>, AsyncHierarchyIterable<T>]>; /** * Creates a tuple whose first element is an `Iterable` containing the first span of * elements that do not match the supplied predicate, and whose second element is an `Iterable` * containing the remaining elements. * * The first `Iterable` is eagerly evaluated, while the second `AsyncIterable` is lazily * evaluated. * * @param source An `AsyncIterable` or `Iterable` object. * @param predicate The predicate used to match elements. * @category Scalar */ export function spanUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]>; export function spanUntilAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]> { assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeFunction(predicate, "predicate"); return spanUntilAsyncCore(source, predicate); } async function spanUntilAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, predicate: (element: T, offset: number) => PromiseLike<boolean> | boolean): Promise<[Iterable<T>, AsyncIterable<T>]> { const prefix: T[] = []; const iterator = toAsyncIterable(source)[Symbol.asyncIterator](); let offset = 0; for await (const value of consumeAsync(iterator, noCacheAndLeaveOpen)) { const result = predicate(value, offset++); if (typeof result === "boolean" ? result : await result) { const remaining = prependAsync(consumeAsync(iterator, cacheAndClose), value); return [ flowHierarchy({ [Symbol.iterator]() { return prefix[Symbol.iterator](); } }, source), flowHierarchy(remaining, source), ]; } prefix.push(value); } return [ flowHierarchy({ [Symbol.iterator]() { return prefix[Symbol.iterator](); } }, source), flowHierarchy(emptyAsync<T>(), source), ]; } /** * Computes a scalar value indicating whether the key for every element in `left` corresponds to a matching key * in `right` at the same position. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param keySelector A callback used to select the key for each element. * @category Scalar */ export function correspondsByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, keySelector: (element: T) => K): Promise<boolean>; /** * Computes a scalar value indicating whether the key for every element in `left` corresponds to a matching key * in `right` at the same position. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param leftKeySelector A callback used to select the key for each element in `left`. * @param rightKeySelector A callback used to select the key for each element in `right`. * @param keyEqualer An optional callback used to compare the equality of two keys. * @category Scalar */ export function correspondsByAsync<T, U, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, leftKeySelector: (element: T) => K, rightKeySelector: (element: U) => K, keyEqualer?: EqualityComparison<K> | Equaler<K>): Promise<boolean>; export function correspondsByAsync<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, leftKeySelector: (element: T) => K, rightKeySelector: (element: T) => K = leftKeySelector, keyEqualer: EqualityComparison<K> | Equaler<K> = Equaler.defaultEqualer): Promise<boolean> { if (typeof keyEqualer === "function") keyEqualer = Equaler.create(keyEqualer); assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeFunction(leftKeySelector, "leftKeySelector"); assert.mustBeFunction(rightKeySelector, "rightKeySelector"); assert.mustBeType(Equaler.hasInstance, keyEqualer, "keyEqualer"); return correspondsByAsyncCore(left, right, leftKeySelector, rightKeySelector, keyEqualer); } async function correspondsByAsyncCore<T, K>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, leftKeySelector: (element: T) => K, rightKeySelector: (element: T) => K, keyEqualer: Equaler<K>): Promise<boolean> { const leftIterator = toAsyncIterable(left)[Symbol.asyncIterator](); let leftDone: boolean | undefined = false; let leftValue: T; try { const rightIterator = toAsyncIterable(right)[Symbol.asyncIterator](); let rightDone: boolean | undefined = false; let rightValue: T; try { for (;;) { ({ done: leftDone = false, value: leftValue } = await leftIterator.next()); ({ done: rightDone = false, value: rightValue } = await rightIterator.next()); if (leftDone && rightDone) return true; if (Boolean(leftDone) !== Boolean(rightDone) || !keyEqualer.equals(leftKeySelector(leftValue), rightKeySelector(rightValue))) return false; } } finally { if (!rightDone) await rightIterator?.return?.(); } } finally { if (!leftDone) await leftIterator?.return?.(); } } /** * Computes a scalar value indicating whether every element in `left` corresponds to a matching element * in `right` at the same position. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function correspondsAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether every element in `left` corresponds to a matching element * in `right` at the same position. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function correspondsAsync<T, U>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; export function correspondsAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: EqualityComparison<T> | Equaler<T> = Equaler.defaultEqualer): Promise<boolean> { if (typeof equaler === "function") equaler = Equaler.create(equaler); assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeType(Equaler.hasInstance, equaler, "equality"); return correspondsByAsyncCore(left, right, identity, identity, equaler); } /** * Finds the value at the provided offset. A negative offset starts from the * last element. * * @param source An `AsyncIterable` or `Iterable` object. * @param offset An offset from the start of the iterable. * @category Scalar */ export function elementAtAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, offset: number | Index): Promise<T | undefined> { assert.mustBeAsyncOrSyncIterableObject(source, "source") let isFromEnd = false; if (typeof offset === "number") { assert.mustBeInteger(offset, "offset"); isFromEnd = offset < 0; if (isFromEnd) offset = -offset; } else { assert.mustBeInstanceOf(Index, offset, "offset"); isFromEnd = offset.isFromEnd; offset = offset.value; } return elementAtAsyncCore(source, offset, isFromEnd); } async function elementAtAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, offset: number, isFromEnd: boolean): Promise<T | undefined> { if (isFromEnd) { if (offset === 0) { return undefined; } if (offset === 1) { return lastAsync(source); } const array: T[] = []; for await (const element of source) { if (array.length >= offset) { array.shift(); } array.push(element); } return array.length - offset >= 0 ? array[array.length - offset] : undefined; } for await (const element of source) { if (offset === 0) { return element; } offset--; } return undefined; } export { elementAtAsync as nthAsync }; /** * Computes a scalar value indicating whether the elements of this `AsyncIterable` start * with the same sequence of elements in another `AsyncIterable`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback or `Equaler` object used to compare the equality of two elements. * @category Scalar */ export function startsWithAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of this `AsyncIterable` start * with the same sequence of elements in another `AsyncIterable`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback or `Equaler` object used to compare the equality of two elements. * @category Scalar */ export function startsWithAsync<T, U>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; export function startsWithAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: EqualityComparison<T> | Equaler<T> = Equaler.defaultEqualer): Promise<boolean> { if (typeof equaler === "function") equaler = Equaler.create(equaler); assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return startsWithAsyncCore(left, right, equaler); } async function startsWithAsyncCore<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: Equaler<T>): Promise<boolean> { const leftIterator = toAsyncIterable(left)[Symbol.asyncIterator](); let leftDone: boolean | undefined = false; let leftValue: T; try { const rightIterator = toAsyncIterable(right)[Symbol.asyncIterator](); let rightDone: boolean | undefined = false; let rightValue: T; try { for (;;) { ({ done: leftDone, value: leftValue } = await leftIterator.next()); ({ done: rightDone, value: rightValue } = await rightIterator.next()); if (rightDone) return true; if (leftDone || !equaler.equals(leftValue, rightValue)) return false; } } finally { if (!rightDone) await rightIterator.return?.(); } } finally { if (!leftDone) await leftIterator.return?.(); } } /** * Computes a scalar value indicating whether the elements of `left` end * with the same sequence of elements in `right`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function endsWithAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of `left` end * with the same sequence of elements in `right`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function endsWithAsync<T, U>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; export function endsWithAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: EqualityComparison<T> | Equaler<T> = Equaler.defaultEqualer): Promise<boolean> { if (typeof equaler === "function") equaler = Equaler.create(equaler); assert.mustBeAsyncOrSyncIterableObject(left, "left"); assert.mustBeAsyncOrSyncIterableObject(right, "right"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return endsWithAsyncCore(left, right, equaler); } async function endsWithAsyncCore<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: Equaler<T>): Promise<boolean> { const rightArray = await toArrayAsync(right); const numElements = rightArray.length; if (numElements <= 0) { return true; } const leftArray = await toArrayAsync(takeRightAsync(left, numElements)); if (leftArray.length < numElements) { return false; } for (let i = 0; i < numElements; i++) { if (!equaler.equals(leftArray[i], rightArray[i])) { return false; } } return true; } /** * Computes a scalar value indicating whether the provided value is included in an `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function includesAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: T, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the provided value is included in an `AsyncIterable`. * * @param source An `AsyncIterable` or `Iterable` object. * @param value A value. * @param equaler An optional callback used to compare the equality of two elements. * @category Scalar */ export function includesAsync<T, U>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: U, equaler: (left: T, right: U) => boolean): Promise<boolean>; export function includesAsync<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: T, equaler: EqualityComparison<T> | Equaler<T> = Equaler.defaultEqualer): Promise<boolean> { if (typeof equaler === "function") equaler = Equaler.create(equaler); assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return includesAsyncCore(source, value, equaler); } async function includesAsyncCore<T>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, value: T, equaler: Equaler<T>): Promise<boolean> { for await (const element of source) { if (equaler.equals(value, element)) { return true; } } return false; } /** * Computes a scalar value indicating whether the elements of `left` include * an exact sequence of elements from `right`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ export function includesSequenceAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler?: EqualityComparison<T> | Equaler<T>): Promise<boolean>; /** * Computes a scalar value indicating whether the elements of `left` include * an exact sequence of elements from `right`. * * @param left An `AsyncIterable` or `Iterable` object. * @param right An `AsyncIterable` or `Iterable` object. * @param equaler A callback used to compare the equality of two elements. * @category Scalar */ export function includesSequenceAsync<T, U>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<U> | Iterable<PromiseLike<U> | U>, equaler: (left: T, right: U) => boolean): Promise<boolean>; export function includesSequenceAsync<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: EqualityComparison<T> | Equaler<T> = Equaler.defaultEqualer): Promise<boolean> { if (typeof equaler === "function") equaler = Equaler.create(equaler); assert.mustBeAsyncOrSyncIterableObject(left, "source"); assert.mustBeAsyncOrSyncIterableObject(right, "other"); assert.mustBeType(Equaler.hasInstance, equaler, "equaler"); return includesSequenceAsyncCore(left, right, equaler); } async function includesSequenceAsyncCore<T>(left: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, right: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, equaler: Equaler<T>): Promise<boolean> { const rightArray = await toArrayAsync(right); const numRightElements = rightArray.length; if (numRightElements <= 0) { return true; } const span: T[] = []; for await (const leftValue of toAsyncIterable(left)) { for (;;) { const rightValue = rightArray[span.length]; if (equaler.equals(leftValue, rightValue)) { if (span.length + 1 >= numRightElements) { return true; } span.push(leftValue); } else if (span.length > 0) { span.shift(); continue; } break; } } return false; } class ArrayWrapper<T> { constructor(private array: T[]) { } get [IndexedCollection.size](): number { return this.array.length; } [IndexedCollection.setAt](index: number, value: T): boolean { this.array[index] = value; return true; } } /** * Writes each element of a source iterable to a destination array. * * @param source An `AsyncIterable` or `Iterable` object. * @param collection The destination array or `IndexedCollection`. * @param start The offset into the array at which to start writing. * @param count The number of elements to write to the array. * @category Scalar */ export function copyToAsync<T, U extends IndexedCollection<T> | T[]>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, collection: U, start: number = 0, count?: number): Promise<U> { const target = IndexedCollection.hasInstance(collection) ? collection : Array.isArray(collection) ? new ArrayWrapper<T>(collection) : undefined; assert.mustBeAsyncOrSyncIterableObject(source, "source"); assert.assertType(target !== undefined, "dest"); assert.mustBePositiveInteger(start, "start"); const size = target[IndexedCollection.size]; if (count !== undefined) { assert.mustBePositiveInteger(count, "count"); } else { count = size - start; } assert.assertRange(start + count <= size, "count"); return copyToAsyncCore(source, collection, target, start, count); } async function copyToAsyncCore<T, U extends IndexedCollection<T> | T[]>(source: AsyncIterable<T> | Iterable<PromiseLike<T> | T>, collection: U, target: Pick<IndexedCollection<T>, typeof IndexedCollection.size | typeof IndexedCollection.setAt>, start: number, count: number): Promise<U> { if (count > 0) { for await (const element of source) { if (count > 0) { target[IndexedCollection.setAt](start++, element); count--; } else { break; } } } return collection; }
the_stack
import { CommonConstructorOptions } from "../index"; /** * Microsoft Translator APIs can be seamlessly integrated into your applications, websites, tools, or other solutions to provide multi-language user experiences. * Leveraging industry standards, it can be used on any hardware platform and with any operating system to perform language translation and other language-related operations such as text language detection or text to speech */ export class textTranslator { constructor(options: CommonConstructorOptions); /** * Adds a translation to the translation memory. */ addTranslation(options: AddTranslationOptions): Promise<void>; /** * Adds an array of translations to add translation memory. This is an array version of AddTranslation. */ addTranslationArray(options: AddTranslationArrayOptions): Promise<void>; /** * Breaks a piece of text into sentences and returns an array containing the lengths in each sentence. * The return value: An array of integers representing the lengths of the sentences. The length of the array is the number of sentences, and the values are the length of each sentence. */ breakSentences(options: BreakSentencesOptions): Promise<void>; /** * Use the Detect method to identify the language of a selected piece of text. * The return value: A string containing a two-character Language code for the given text. */ detect(options: DetectTextTranslatorOptions): Promise<void>; /** * Use the DetectArray method to identify the language of an array of string at once. * Performs independent detection of each individual array element and returns a result for each row of the array. */ detectArray(options: DetectArrayOptions): Promise<DetectArrayReturnValue>; /** * Retrieves friendly names for the languages passed in as the parameter languageCodes, and localized using the passed locale language. */ getLanguageNames(options: GetLanguageNamesOptions): Promise<void>; /** * Retrieves the languages available for speech synthesis. * A return value: A string array containing the language codes supported for speech synthesis by the Translator Service. */ getLanguagesForSpeak(): Promise<void>; /** * Obtain a list of language codes representing languages that are supported by the Translation Service. * Translate and TranslateArray can translate between any two of these languages. * A return value: A string array containing the language codes supported by the Translator Services. */ getLanguagesForTranslate(): Promise<void>; /** * Retrieves an array of translations for a given language pair from the store and the MT engine. * GetTranslations differs from Translate as it returns all available translations. */ getTranslations(options: GetTranslationsOptions): Promise<GetTranslationsReturnValue>; /** * Retrieve multiple translation candidates for multiple source texts. */ getTranslationsArray(options: GetTranslationsArrayOptions): Promise<GetTranslationsArrayReturnValue>; /** * Returns a wave or mp3 stream of the passed-in text being spoken in the desired language. */ speak(options: SpeakOptions): Promise<void>; /** * Translates a text string from one language to another. */ translate(options: TranslateOptions): Promise<void>; /** * Use the TranslateArray method to retrieve translations for multiple source texts. */ translateArray(options: TranslateArrayOptions): Promise<TranslateArrayReturnValue>; } export interface AddTranslationOptions { parameters: AddTranslationParameters } export interface AddTranslationParameters { /** * A string containing the text to translate from. * The string has a maximum length of 1000 characters. */ originalText: string, /** * A string containing translated text in the target language. * The string has a maximum length of 2000 characters. */ translatedText: string, /** * A string representing the language code of the translation text. * en = english, de = german etc... */ from: string, /** * A string representing the language code to translate the text into. */ to: string, /** * An integer representing the quality rating for this string. * Value between -10 and 10. Defaults to 1. */ rating?: number, /** * The format of the text being translated. The supported formats are "text/plain" and "text/html". * Any HTML needs to be a well-formed, complete element. */ contentType?: string, /** * A string containing the category (domain) of the translation. Defaults to "general". */ category?: string, /** * A string used to track the originator of the submission. */ user: string, /** * A string containing the content location of this translation. */ uri?: string } export interface AddTranslationArrayOptions { body: AddTranslationArrayBody } export interface AddTranslationArrayBody { /** * A string containing the language code of the source language. * Must be one of the languages returned by theGetLanguagesForTranslate method. */ from: string, /** * A string containing the language code of the target language. * Must be one of the languages returned by the GetLanguagesForTranslate method. */ to: string, /** * An array of translations to add to translation memory. Each translation must contain: originalText, translatedText and rating. * The size of each originalText and translatedText is limited to 1000 chars. The total of all the originalText(s) and translatedText(s) must not exceed 10000 characters. * The maximum number of array elements is 100. */ translations: { originalText: string, rating: number, sequence?: number, translatedText: string }[], /** * A set of options, including Category, ContentType, Uri, and User. * Specified elements must be listed in alphabetical order. */ category?: string, uri?: string, user: string, contentType: string } export interface BreakSentencesOptions { parameters: BreakSentencesParameters } export interface BreakSentencesParameters { /** * A string representing the text to split into sentences. * The size of the text must not exceed 10000 characters. */ text: string, /** * A string representing the language code of input text. */ language: string } export interface DetectTextTranslatorOptions { parameters: DetectTextTranslatorParameters } export interface DetectTextTranslatorParameters { /** * A string representing the text to split into sentences. * The size of the text must not exceed 10000 characters. */ text: string, } export interface DetectArrayOptions { /** * The size of the text must not exceed 10000 characters. */ body: DetectArrayBody } export interface DetectArrayBody { texts: string[] } /** * A string array containing a two-character Language codes for each row of the input array. */ export interface DetectArrayReturnValue { ArrayOfstring: string[] } export interface GetLanguageNamesOptions { parameters: GetLanguageNamesParameters body: GetLanguageNamesBody } export interface GetLanguageNamesParameters { /** * A string representing a combination of an ISO 639 two-letter lowercase culture code associated with * a language and an ISO 3166 two-letter uppercase subculture code to localize the language names or a ISO 639 lowercase culture code by itself. */ locale: string } export interface GetLanguageNamesBody { /** * A string array representing the ISO 639-1 language codes to retrieve the friendly name for. */ languageCodes: string[] } export interface GetTranslationsOptions { parameters: GetTranslationsParameters } export interface GetTranslationsParameters { /** * A string representing the text to translate. * The size of the text must not exceed 10000 characters. */ text: string, /** * A string representing the language code of the translation text. */ from: string, /** * A string representing the language code to translate the text into. */ to: string, /** * An integer representing the maximum number of translations to return. */ maxTranslations: number, /** * object contains the values listed below. They are all optional and default to the most common settings. Specified elements must be listed in alphabetical order. */ translateOptions?: { /** * A string containing the category (domain) of the translation. Defaults to "general". */ category?: string, /** * The only supported, and the default, option is "text/plain". */ contentType?: "text/plain", /** * boolean flag to determine whether more than one alternatives should be returned from the MT engine. * Valid values are true and false (case-sensitive). Default is false and includes only 1 alternative. * Setting the flag to true allows for generating artificial alternatives in translation, fully integrated with the collaborative translations framework (CTF). * The feature allows for returning alternatives for sentences that have no alternatives in CTF, by adding artificial alternatives from the n-best list of the decoder. */ includeMultipleMTAlternatives: boolean, /** * User state to help correlate request and response. The same contents will be returned in the response. */ state?: number, /** * Filter results by this URI. If no value is set, the default is all. */ uri?: string, /** * Filter results by this user. If no value is set, the default is all. */ user?: string } } export interface GetTranslationsReturnValue { /** * An array of matches found, stored in TranslationMatch objects. The translations may include slight variants of the original text (fuzzy matching). * The translations will be sorted: 100% matches first, fuzzy matches below. */ Translations: { /** * If the method did not specify a From language, this will be the result of auto language detection. * Otherwise it will be the given From language. */ from: string, /** * User state to help correlate request and response. Contains the same value as given in the TranslateOptions parameter. */ state: string, translationMatch: { /** * If an error has occurred for a specific input string, the error code is stored. Otherwise the field is empty. */ error: string, /** * The system matches input sentences against the store, including inexact matches. MatchDegree indicates how closely the input text matches the original text found in the store. * The value returned ranges from 0 to 100, where 0 is no similarity and 100 is an exact case sensitive match. */ matchDegree: number, /** * Original text that was matched for this result. Only returned if the matched original text was different than the input text. * Used to return the source text of a fuzzy match. Not returned for Microsoft Translator results. */ matchedOriginalText: string, /** * Indicates the authority of the person making the quality decision. * Machine Translation results will have a rating of 5. Anonymously provided translations will generally have a rating of 1 to 4, whilst authoritatively provided translations will generally have a rating of 6 to 10. */ rating: number, /** * The number of times this translation with this rating has been selected. * The value will be 0 for the automatically translated response. */ count: number, /** * The translated text. */ translatedText: string } }[] } export interface GetTranslationsArrayOptions { body: GetTranslationsArrayBody } export interface GetTranslationsArrayBody { /** * A string representing the language code of the translation text. */ from: string, /** * An integer representing the maximum number of translations to return. */ maxTranslations: number, /** * They are all optional and default to the most common settings. Specified elements must be listed in alphabetical order. */ options?: { /** * A string containing the category (domain) of the translation. Defaults to general. */ category?: string, /** * lag to determine whether more than one alternatives should be returned from the MT engine. Valid values are true and false (case-sensitive). Default is false and includes only 1 alternative. * Setting the flag to true allows for generating artificial alternatives in translation, fully integrated with the collaborative translations framework (CTF). * The feature allows for returning alternatives for sentences that have no alternatives in CTF, by adding artificial alternatives from the n-best list of the decoder. */ includeMultipleMTAlternatives?: boolean, /** * User state to help correlate request and response. The same contents will be returned in the response. */ state?: number, /** * Filter results by this URI. If no value is set, the default is all. */ uri?: string, /** * Filter results by this user. If no value is set, the default is all. */ user?: string }, /** * An array containing the texts for translation. All strings must be of the same language. * The total of all texts to be translated must not exceed 10000 characters. The maximum number of array elements is 10. */ texts: string[], /** * A string representing the language code to translate the text into. */ to: string } export interface GetTranslationsArrayReturnValue { /** * An array of matches found, stored in TranslationMatch objects. The translations may include slight variants of the original text (fuzzy matching). * The translations will be sorted: 100% matches first, fuzzy matches below. */ translations: { /** * If the method did not specify a From language, this will be the result of auto language detection. * Otherwise it will be the given From language. */ from: string, /** * User state to help correlate request and response. Contains the same value as given in the TranslateOptions parameter. */ state: string, translationMatch: { /** * If an error has occurred for a specific input string, the error code is stored. Otherwise the field is empty. */ error: string, /** * The system matches input sentences against the store, including inexact matches. MatchDegree indicates how closely the input text matches the original text found in the store. * The value returned ranges from 0 to 100, where 0 is no similarity and 100 is an exact case sensitive match. */ matchDegree: number, /** * Original text that was matched for this result. Only returned if the matched original text was different than the input text. * Used to return the source text of a fuzzy match. Not returned for Microsoft Translator results. */ matchedOriginalText: string, /** * Indicates the authority of the person making the quality decision. * Machine Translation results will have a rating of 5. Anonymously provided translations will generally have a rating of 1 to 4, whilst authoritatively provided translations will generally have a rating of 6 to 10. */ rating: number, /** * The number of times this translation with this rating has been selected. * The value will be 0 for the automatically translated response. */ count: number, /** * The translated text. */ translatedText: string } }[] } export interface SpeakOptions { parameters: SpeakParameters } export interface SpeakParameters { /** * A string containing a sentence or sentences of the specified language to be spoken for the wave stream. * The size of the text to speak must not exceed 2000 characters. */ text: string, /** * A string representing the supported language code to speak the text in. * The code must be present in the list of codes returned from the method GetLanguagesForSpeak. */ language: string, /** * A string specifying the content-type ID. Currently, audio/wav and audio/mp3 are available. The default value is audio/wav. */ format: string, /** * A string specifying properties of the synthesized speech: * - MaxQuality and MinSize are available to specify the quality of the audio signals. With MaxQuality, you can get voices with the highest quality, and with MinSize, you can get the voices with the smallest size. Default is MinSize. * - female and male are available to specify the desired gender of the voice. Default is female. Use the vertical bar | to include multiple options. For example MaxQuality|Male. */ options?: string, } export interface TranslateOptions { parameters: TranslateParameters } export interface TranslateParameters { /** * A string containing a sentence or sentences of the specified language to be spoken for the wave stream. * The size of the text to speak must not exceed 2000 characters. */ text: string, /** * A string representing the language code of the translation text. For example, en for English. */ from?: string, /** * A string representing the language code to translate the text into. */ to: string, /** * A string containing the category (domain) of the translation. Defaults to general. */ category?: string, /** * The only supported, and the default, option is text/plain. */ contentType: "text/plain" } export interface TranslateArrayOptions { body: TranslateArrayBody } export interface TranslateArrayBody { /** * A string representing the language code to translate the text from. * If left empty the response will include the result of language auto-detection. */ from?: string, /** * An array containing the texts for translation. All strings must be of the same language. * The total of all texts to be translated must not exceed 10000 characters. * The maximum number of array elements is 2000. */ to: string, options?: { /** * A string containing the category (domain) of the translation. Defaults to general. */ category?: string, /** * Specifies how profanities are handled as explained above. * Accepted values of ProfanityAction are NoAction (default), Marked and Deleted. */ profanityAction?: string, /** * User state to help correlate request and response. The same contents will be returned in the response. */ state?: string, /** * Filter results by this URI. If no value is set, the default is all. */ uri?: string, /** * Filter results by this user. If no value is set, the default is all. */ user?: string }, /** * The only supported, and the default, option is text/plain. */ contentType?: string, /** * An array containing the texts for translation. All strings must be of the same language. * The total of all texts to be translated must not exceed 10000 characters. * The maximum number of array elements is 2000. */ sourceTexts: string[] } export interface TranslateArrayReturnValue { translateArrayResponse: { translateArrayResponse: { /** * Indicates an error if one has occurred. Otherwise set to null. */ error: string, /** * An array of integers indicating the length of each sentence in the original source text. * The length of the array indicates the number of sentences. */ originalSentenceLengths: number[], /** * The translated text. */ translatedText: string, /** * An array of integers indicating the length of each sentence in the translated text. * The length of the array indicates the number of sentences. */ translatedSentenceLengths: number[], /** * User state to help correlate request and response. Returns the same content as in the request. */ state: string } }[] }
the_stack
import { should } from 'chai'; import { LinkedListInstance } from '../../types/truffle-contracts'; import { TestLinkedListInstance } from '../../types/truffle-contracts'; const LinkedList = artifacts.require('LinkedList') as Truffle.Contract<LinkedListInstance>; const TestLinkedList = artifacts.require('TestLinkedList') as Truffle.Contract<TestLinkedListInstance>; should(); const emptyData = '0x0000000000000000000000000000000000000000'; const headData = '0x0000000000000000000000000000000000000001'; const middleData = '0x0000000000000000000000000000000000000002'; const tailData = '0x0000000000000000000000000000000000000003'; /** @test {LinkedList} contract */ contract('LinkedList - add', (accounts) => { let linkedList: LinkedListInstance; beforeEach(async () => { linkedList = await LinkedList.new(); }); /** * Test the two contract methods * @test {LinkedList#set} and {LinkedList#get} */ it('Constructor variables.', async () => { ((await linkedList.idCounter()).toNumber()).should.be.equal(1); }); it('get on a non existing object returns (0,0,0).', async () => { const result = (await linkedList.get(0)); result[0].toNumber().should.be.equal(0); result[1].toNumber().should.be.equal(0); result[2].should.be.equal(emptyData); }); it('adds an object at the head - event emission.', async () => { const objectEvent = ( await linkedList.addHead(headData) ).logs[0]; objectEvent.args.id.toNumber().should.be.equal(1); objectEvent.args.data.should.be.equal(headData); }); it('adds an object at the head - data storage.', async () => { const objectId = ( await linkedList.addHead(headData) ).logs[0].args.id.toNumber(); const result = (await linkedList.get(objectId)); result[0].toNumber().should.be.equal(objectId); result[1].toNumber().should.be.equal(0); result[2].should.be.equal(headData); }); it('adds two objects from the head.', async () => { const objectOneId = ( await linkedList.addHead(headData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await linkedList.addHead(middleData) ).logs[0].args.id.toNumber(); const objectOne = (await linkedList.get(objectOneId)); objectOne[0].toNumber().should.be.equal(objectOneId); objectOne[1].toNumber().should.be.equal(0); objectOne[2].should.be.equal(headData); const objectTwo = (await linkedList.get(objectTwoId)); objectTwo[0].toNumber().should.be.equal(objectTwoId); objectTwo[1].toNumber().should.be.equal(objectOneId); objectTwo[2].should.be.equal(middleData); ((await linkedList.head()).toNumber()).should.be.equal(objectTwoId); }); it('adds an object at the tail - event emission.', async () => { const objectEvent = ( await linkedList.addTail(headData) ).logs[0]; objectEvent.args.id.toNumber().should.be.equal(1); objectEvent.args.data.should.be.equal(headData); }); it('adds an object at the tail - data storage.', async () => { const objectId = ( await linkedList.addTail(headData) ).logs[0].args.id.toNumber(); const result = (await linkedList.get(objectId)); result[0].toNumber().should.be.equal(objectId); result[1].toNumber().should.be.equal(0); result[2].should.be.equal(headData); }); it('adds two objects from the tail.', async () => { const objectOneId = ( await linkedList.addTail(headData) ).logs[0].args.id.toNumber(); const objectTwoId = ( await linkedList.addTail(middleData) ).logs[0].args.id.toNumber(); const objectOne = (await linkedList.get(objectOneId)); objectOne[0].toNumber().should.be.equal(objectOneId); objectOne[1].toNumber().should.be.equal(objectTwoId); objectOne[2].should.be.equal(headData); const objectTwo = (await linkedList.get(objectTwoId)); objectTwo[0].toNumber().should.be.equal(objectTwoId); objectTwo[1].toNumber().should.be.equal(0); objectTwo[2].should.be.equal(middleData); ((await linkedList.head()).toNumber()).should.be.equal(objectOneId); }); }); contract('LinkedList - find', (accounts) => { let linkedList: LinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { linkedList = await LinkedList.new(); tailId = ( await linkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await linkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await linkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('finds an id for given data.', async () => { let resultId = (await linkedList.findIdForData(headData)); resultId.toNumber().should.be.equal(headId); resultId = (await linkedList.findIdForData(middleData)); resultId.toNumber().should.be.equal(middleId); resultId = (await linkedList.findIdForData(tailData)); resultId.toNumber().should.be.equal(tailId); }); it('finds the tail id.', async () => { (await linkedList.findTailId()).toNumber().should.be.equal(tailId); }); }); /** @test {LinkedList} contract */ contract('LinkedList - remove', (accounts) => { let linkedList: LinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { linkedList = await LinkedList.new(); tailId = ( await linkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await linkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await linkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('removes the head.', async () => { const removedId = ( await linkedList.remove(headId) ).logs[1].args.id.toNumber(); removedId.should.be.equal(headId); ((await linkedList.head()).toNumber()).should.be.equal(middleId); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].should.be.equal(middleData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('removes the tail.', async () => { const removedId = ( await linkedList.remove(tailId) ).logs[1].args.id.toNumber(); removedId.should.be.equal(tailId); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].should.be.equal(headData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(0); middleObject[2].should.be.equal(middleData); }); it('removes the middle.', async () => { const removedId = ( await linkedList.remove(middleId) ).logs[1].args.id.toNumber(); removedId.should.be.equal(middleId); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(tailId); headObject[2].should.be.equal(headData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('removes all.', async () => { (await linkedList.remove(headId)).logs[1].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(middleId); (await linkedList.remove(tailId)).logs[1].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(middleId); (await linkedList.remove(middleId)).logs[1].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(0); }); }); /** @test {LinkedList} contract */ contract('LinkedList - insert', (accounts) => { const insertedData = '0x0000000000000000000000000000000000000004'; let linkedList: LinkedListInstance; let headId: number; let middleId: number; let tailId: number; beforeEach(async () => { linkedList = await LinkedList.new(); tailId = ( await linkedList.addHead(tailData) ).logs[0].args.id.toNumber(); middleId = ( await linkedList.addHead(middleData) ).logs[0].args.id.toNumber(); headId = ( await linkedList.addHead(headData) ).logs[0].args.id.toNumber(); }); it('inserts after the head.', async () => { const insertedId = ( await linkedList.insertAfter(headId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(insertedId); headObject[2].should.be.equal(headData); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(middleId); insertedObject[2].should.be.equal(insertedData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].should.be.equal(middleData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('inserts after the tail.', async () => { const insertedId = ( await linkedList.insertAfter(tailId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].should.be.equal(headData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].should.be.equal(middleData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(insertedId); tailObject[2].should.be.equal(tailData); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(0); insertedObject[2].should.be.equal(insertedData); }); it('inserts after the middle.', async () => { const insertedId = ( await linkedList.insertAfter(middleId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].should.be.equal(headData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(insertedId); middleObject[2].should.be.equal(middleData); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(tailId); insertedObject[2].should.be.equal(insertedData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('inserts before the head.', async () => { const insertedId = ( await linkedList.insertBefore(headId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(insertedId); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(headId); insertedObject[2].should.be.equal(insertedData); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].should.be.equal(headData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].should.be.equal(middleData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('inserts before the tail.', async () => { const insertedId = ( await linkedList.insertBefore(tailId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(middleId); headObject[2].should.be.equal(headData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(insertedId); middleObject[2].should.be.equal(middleData); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(tailId); insertedObject[2].should.be.equal(insertedData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); it('inserts before the middle.', async () => { const insertedId = ( await linkedList.insertBefore(middleId, insertedData) ).logs[0].args.id.toNumber(); ((await linkedList.head()).toNumber()).should.be.equal(headId); const headObject = (await linkedList.get(headId)); headObject[0].toNumber().should.be.equal(headId); headObject[1].toNumber().should.be.equal(insertedId); headObject[2].should.be.equal(headData); const insertedObject = (await linkedList.get(insertedId)); insertedObject[0].toNumber().should.be.equal(insertedId); insertedObject[1].toNumber().should.be.equal(middleId); insertedObject[2].should.be.equal(insertedData); const middleObject = (await linkedList.get(middleId)); middleObject[0].toNumber().should.be.equal(middleId); middleObject[1].toNumber().should.be.equal(tailId); middleObject[2].should.be.equal(middleData); const tailObject = (await linkedList.get(tailId)); tailObject[0].toNumber().should.be.equal(tailId); tailObject[1].toNumber().should.be.equal(0); tailObject[2].should.be.equal(tailData); }); }); /* contract('LinkedList - gas tests', (accounts) => { let linkedList: TestLinkedListInstance; const dummyData = '0x0000000000000000000000000000000000000001'; beforeEach(async () => { linkedList = await TestLinkedList.new(); for (let i = 0; i < 100; i++) { await linkedList.addHead(dummyData); } }); it('Find Tail as a transaction.', async () => { await linkedList.findTailIdWithGas(); }); it('Add Head.', async () => { await linkedList.addHead(dummyData); }); it('Add Tail.', async () => { await linkedList.addTail(dummyData); }); it('Insert After.', async () => { const tailId = await linkedList.findTailId(); await linkedList.insertAfter(tailId, dummyData); }); it('Insert Before.', async () => { const tailId = await linkedList.findTailId(); await linkedList.insertBefore(tailId, dummyData); }); it('Remove.', async () => { const tailId = await linkedList.findTailId(); await linkedList.remove(tailId); }); }); */
the_stack
import * as React from 'react'; import { createPopper, Instance, ModifierArguments } from '@popperjs/core'; import is from 'is-lite'; import useTreeChanges from 'tree-changes-hook'; import Floater from './components/Floater'; import Portal from './components/Portal'; import Wrapper from './components/Wrapper'; import { POSITIONING_PROPS, STATUS } from './literals'; import { canUseDOM, enhanceProps, getFallbackPlacements, getModifiers, isFixed, isMobile, log, mergeModifier, once, randomId, } from './modules/helpers'; import { useMount, useSetState, useSingleton, useUnmount, useUpdateEffect } from './modules/hooks'; import getStyles from './modules/styles'; import { PlainObject, Props, State, Statuses, Styles } from './types'; export default function ReactFloater(props: Props): JSX.Element { const { autoOpen, callback, children, component, content, debug, disableFlip, disableHoverToClick, event, eventDelay, footer, getPopper, hideArrow, id, modifiers, offset, open, placement, portalElement, showCloseButton, style, styles, target, title, wrapperOptions, } = enhanceProps(props); const [state, setState] = useSetState<State>({ currentPlacement: placement || 'bottom', positionWrapper: !!wrapperOptions?.position && !!target, status: STATUS.INIT, statusWrapper: STATUS.INIT, }); const arrowRef = React.useRef<HTMLSpanElement>(null); const childRef = React.useRef<HTMLElement>(null); const eventDelayTimer = React.useRef<number>(); const floaterRef = React.useRef<HTMLDivElement>(null); const internalId = React.useRef(randomId()); const isMounted = React.useRef(false); const popperRef = React.useRef<Instance>(); const stateRef = React.useRef<State>(state); const wrapperPopper = React.useRef<Instance>(); const wrapperRef = React.useRef<HTMLSpanElement>(null); const wrapperStyles = React.useRef<React.CSSProperties>({}); const { currentPlacement, positionWrapper, status, statusWrapper } = state; const { changed } = useTreeChanges(state); const { changed: changedProps } = useTreeChanges(props); const updateState = React.useCallback( (nextState: Partial<State>, callback_?: () => void) => { if (isMounted.current) { setState(nextState); stateRef.current = { ...state, ...nextState }; if (callback_) { callback_(); } } }, [setState, state], ); const toggle = React.useCallback( (forceStatus?: Statuses) => { let nextStatus: Statuses = stateRef.current.status === STATUS.OPEN ? STATUS.CLOSING : STATUS.RENDER; if (!is.undefined(forceStatus)) { nextStatus = forceStatus; } updateState({ status: nextStatus, statusWrapper: nextStatus === STATUS.CLOSING ? STATUS.RENDER : STATUS.IDLE, }); }, [updateState], ); const targetElement = React.useRef(() => { if (!canUseDOM) { return null; } if (target) { if (is.domElement(target)) { return target; } return document.querySelector(target) as HTMLElement; } return childRef.current || wrapperRef.current; }); const currentDebug = React.useMemo(() => { return debug || canUseDOM ? !!window.ReactFloaterDebug : false; }, [debug]); const currentEvent = React.useMemo(() => { if (event === 'hover' && isMobile() && !disableHoverToClick) { return 'click'; } return event; }, [disableHoverToClick, event]); const currentStyles = React.useMemo(() => { const nextStyles: Styles = getStyles(styles); const element = targetElement.current(); if (positionWrapper) { let wrapperCurrentStyles: PlainObject | undefined; if (status !== STATUS.IDLE) { wrapperCurrentStyles = nextStyles.wrapperPosition; } else if (statusWrapper === STATUS.RENDER) { wrapperCurrentStyles = wrapperPopper.current?.state.styles; } nextStyles.wrapper = { ...nextStyles.wrapper, ...wrapperCurrentStyles, }; } /* istanbul ignore else */ if (element) { const targetStyles = window.getComputedStyle(element); /* istanbul ignore else */ if (wrapperStyles.current) { nextStyles.wrapper = { ...nextStyles.wrapper, ...wrapperStyles.current, }; } else if (!['relative', 'static'].includes(targetStyles.position)) { wrapperStyles.current = {}; if (!positionWrapper) { POSITIONING_PROPS.forEach(d => { if (d === 'position') { wrapperStyles.current[d] = targetStyles[d] as React.CSSProperties['position']; } else { wrapperStyles.current[d] = targetStyles[d]; } }); nextStyles.wrapper = { ...nextStyles.wrapper, ...wrapperStyles.current, }; } } } return nextStyles as Styles; }, [positionWrapper, status, statusWrapper, styles]); const cleanUp = React.useRef(() => { if (popperRef.current) { popperRef.current.destroy(); } if (wrapperPopper.current) { wrapperPopper.current.destroy(); } }); const initPopper = React.useRef(() => { const nextStatus = stateRef.current.status === STATUS.RENDER ? STATUS.OPENING : STATUS.IDLE; const element = targetElement.current(); /* istanbul ignore else */ if (placement === 'center') { setTimeout(() => { updateState({ status: nextStatus }); }, 100); } else if (element) { if (floaterRef.current) { const { arrow, flip, offset: offsetModifier, ...rest } = getModifiers(modifiers); popperRef.current = createPopper(element, floaterRef.current, { placement, strategy: isFixed(childRef.current) ? 'fixed' : 'absolute', modifiers: [ mergeModifier( { name: 'arrow', enabled: !hideArrow, options: { element: arrowRef.current, padding: 8, }, }, arrow, ), mergeModifier( { name: 'flip', enabled: !disableFlip, options: { altAxis: false, fallbackPlacements: getFallbackPlacements(placement || 'bottom'), }, }, flip, ), mergeModifier( { name: 'offset', options: { offset: [0, offset], }, }, offsetModifier, ), { name: 'updatePlacement', enabled: true, phase: 'afterWrite', fn: ({ instance, state: popperState }: ModifierArguments<PlainObject>) => { if (popperState.placement !== stateRef.current.currentPlacement) { popperRef.current = instance; updateState({ currentPlacement: popperState.placement }); } }, }, { name: 'applyArrowStyle', enabled: true, phase: 'write', fn: ({ state: popperState }: ModifierArguments<PlainObject>) => { const { elements: { arrow: stateArrow }, placement: statePlacement, } = popperState; if (stateArrow) { if (statePlacement.startsWith('top')) { stateArrow.style.bottom = '0px'; stateArrow.style.right = ''; } else if (statePlacement.startsWith('bottom')) { stateArrow.style.top = '0px'; stateArrow.style.right = ''; } else if (statePlacement.startsWith('left')) { stateArrow.style.right = '0px'; stateArrow.style.bottom = ''; } else if (statePlacement.startsWith('right')) { stateArrow.style.left = '0px'; stateArrow.style.bottom = ''; } } }, }, ...Object.values(rest), ], onFirstUpdate: popperState => { updateState({ currentPlacement: popperState.placement, status: nextStatus, }); if (placement !== popperState.placement) { setTimeout(() => { popperRef.current?.forceUpdate(); }); } }, }); if (getPopper && popperRef.current) { getPopper(popperRef.current, 'floater'); } } else { updateState({ status: STATUS.IDLE, }); } } if ( !wrapperPopper.current && stateRef.current.positionWrapper && element && wrapperRef.current && placement !== 'center' ) { const wrapperOffset = wrapperOptions?.offset ? wrapperOptions.offset : 0; wrapperPopper.current = createPopper(element, wrapperRef.current, { placement: wrapperOptions?.placement || placement, modifiers: [ { name: 'arrow', enabled: false, }, { name: 'offset', options: { offset: [0, wrapperOffset], }, }, { name: 'flip', enabled: false, }, ], onFirstUpdate: popperState => { updateState({ statusWrapper: STATUS.RENDER }); if (placement !== popperState.placement) { setTimeout(() => { wrapperPopper.current?.forceUpdate(); }); } }, }); if (getPopper) { getPopper(wrapperPopper.current, 'wrapper'); } } }); const handleLoad = React.useRef(() => { if (popperRef.current) { popperRef.current.forceUpdate(); } if (wrapperPopper.current) { wrapperPopper.current.forceUpdate(); } }); const handleTransitionEnd = React.useRef(() => { /* istanbul ignore else */ if (wrapperPopper.current) { wrapperPopper.current.forceUpdate(); } updateState( { status: stateRef.current.status === STATUS.OPENING ? STATUS.OPEN : STATUS.IDLE, }, () => { if (callback) { callback(stateRef.current.status === STATUS.OPEN ? 'open' : 'close', enhanceProps(props)); } }, ); }); const handleClick = React.useCallback(() => { if (is.boolean(open)) { return; } /* istanbul ignore else */ if (currentEvent === 'click' || (currentEvent === 'hover' && positionWrapper)) { log({ title: 'click', data: [{ event, status: status === STATUS.OPEN ? 'closing' : 'opening' }], debug: currentDebug, }); toggle(status === 'idle' ? STATUS.RENDER : undefined); } }, [currentDebug, currentEvent, event, open, positionWrapper, status, toggle]); const handleMouseEnter = React.useCallback(() => { if (is.boolean(open) || isMobile() || currentEvent !== 'hover') { return; } log({ title: 'mouseEnter', data: [{ key: 'originalEvent', value: event }], debug: currentDebug, }); if (status === STATUS.IDLE) { clearTimeout(eventDelayTimer.current); eventDelayTimer.current = undefined; toggle(STATUS.RENDER); } }, [currentDebug, currentEvent, event, open, status, toggle]); const handleMouseLeave = React.useCallback(() => { if (is.boolean(open) || isMobile()) { return; } /* istanbul ignore else */ if (currentEvent === 'hover') { log({ title: 'mouseLeave', data: [{ key: 'originalEvent', value: event }], debug: currentDebug, }); const hasOpenStatus = ([STATUS.OPENING, STATUS.OPEN] as Statuses[]).includes(status); if (!eventDelay) { toggle(status === STATUS.CLOSING ? STATUS.IDLE : STATUS.CLOSING); } else if (!positionWrapper) { if (hasOpenStatus) { clearTimeout(eventDelayTimer.current); eventDelayTimer.current = window.setTimeout(() => { toggle(); eventDelayTimer.current = undefined; }, eventDelay * 1000); } } } }, [currentDebug, currentEvent, event, eventDelay, open, positionWrapper, status, toggle]); useSingleton(() => { if (canUseDOM) { window.addEventListener('load', handleLoad.current); } }); useMount(() => { isMounted.current = true; log({ title: 'init', data: { hasChildren: !!children, hasTarget: !!target, isControlled: is.boolean(open), positionWrapper, target: targetElement.current(), floater: floaterRef.current, }, debug: currentDebug, }); initPopper.current(); }); useUnmount(() => { isMounted.current = false; cleanUp.current(); window.removeEventListener('load', handleLoad.current); }); // handle changes useUpdateEffect(() => { if (!canUseDOM) { return; } if (changedProps('open')) { let forceStatus; // always follow `open` in controlled mode if (is.boolean(open)) { forceStatus = open ? STATUS.RENDER : STATUS.CLOSING; } toggle(forceStatus); } if (changedProps('wrapperOptions.position') || changedProps('target')) { updateState({ positionWrapper: !!wrapperOptions?.position && !!target, }); } if ( (changed('status', STATUS.IDLE) && open) || (changed('status', STATUS.IDLE, STATUS.INIT) && autoOpen) ) { toggle(STATUS.RENDER); } if (changed('status', STATUS.RENDER)) { if (popperRef.current) { popperRef.current.destroy(); } initPopper.current(); } if (floaterRef.current && changed('status', [STATUS.RENDER, STATUS.CLOSING])) { once(floaterRef.current, 'transitionend', handleTransitionEnd.current); } if (changed('status', STATUS.IDLE, STATUS.CLOSING) && popperRef.current) { popperRef.current.destroy(); popperRef.current = undefined; if (wrapperPopper.current) { wrapperPopper.current.forceUpdate(); } } }); const wrapper = ( <Wrapper childRef={childRef} id={id || internalId.current} isControlled={is.boolean(open)} onClick={handleClick} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} status={status} style={style} styles={currentStyles.wrapper} wrapperRef={wrapperRef} > {children} </Wrapper> ); return ( <> <Portal hasChildren={!!children} placement={currentPlacement} portalElement={portalElement} target={target} zIndex={currentStyles.options.zIndex} > <Floater arrowRef={arrowRef} component={component} content={content} floaterRef={floaterRef} footer={footer} hideArrow={hideArrow || currentPlacement === 'center'} id={id || internalId.current} onClick={handleClick} placement={currentPlacement} positionWrapper={positionWrapper} showCloseButton={showCloseButton} status={status} styles={currentStyles} title={title} /> {positionWrapper && wrapper} </Portal> {!positionWrapper && wrapper} </> ); }
the_stack
import * as t from '@/lib/io'; import * as oly from '@/lib/olyger'; import uuid from 'uuid'; import { SynthType, SoundfontType, Soundfont, Synth, PatternType, Score, Pattern, Instrument, Sample, SampleType, PlaylistType, AutomationClip, AutomationType, TrackType, Channel, Track, ChannelType, createAutomationPrototype, createPatternPrototype, createSamplePrototype, Playlist, PlaylistElementLookup, PlaylistElementType, Automatable, ClipContext, PlaylistElements, } from '@/models'; import Tone from 'tone'; import * as Audio from '@/lib/audio'; import { makeLookup, reverse, range } from '@/lib/std'; import fs from '@/lib/fs'; import { loadBufferSync } from '@/lib/wav'; import { notify } from '@/core/notify'; import { getLogger } from '@/lib/log'; import tmp from 'tmp'; import { GraphNode, masterNode } from '@/lib/audio/node'; import * as framework from '@/lib/framework'; import { remote } from 'electron'; import { emitter, addEventListener } from '@/lib/events'; import { createExtension } from '@/lib/framework'; import { commands } from '@/core/commands'; import { computed } from '@vue/composition-api'; const logger = getLogger('project'); const DG = 'dg'; const FILTERS = [{ name: 'DAWG Files', extensions: [DG] }]; const DG_EXTENSION = `.${DG}`; // Chaining Examples // If I delete an instrument, I need to delete the scores // If I delete a pattern, I need to delete the pattern elements // If I delete a sample, I need to delete the sample elements // If I delete an automation clip, I need to delete the automation clip elements // Chaining Principles // 1. I only need to worry about my action (ie. how to execute AND undo my action) // 2. Chains define dependencies and work off a simple API (ie. changed, added, removed) // 3. Any chain reactions will be encompassed into a single action (ie. only a single undo/redo for the whole chain) export const ProjectType = t.type({ id: t.string, stepsPerBeat: t.number, beatsPerMeasure: t.number, bpm: t.number, name: t.string, instruments: t.array(t.union([SynthType, SoundfontType])), patterns: t.array(PatternType), samples: t.array(SampleType), master: PlaylistType, automationClips: t.array(AutomationType), channels: t.array(ChannelType), tracks: t.array(TrackType), }); export type IProject = t.TypeOf<typeof ProjectType>; interface LoadedProject { bpm: number; stepsPerBeat: number; beatsPerMeasure: number; name: string; id: string; patterns: oly.OlyArr<Pattern>; instruments: oly.OlyArr<Synth | Soundfont>; channels: oly.OlyArr<Channel>; tracks: oly.OlyArr<Track>; master: Playlist; samples: oly.OlyArr<Sample>; automationClips: oly.OlyArr<AutomationClip>; } export interface InitializationError { type: 'error'; message: string; project: LoadedProject; } export interface InitializationSuccess { type: 'success'; project: LoadedProject; } const load = (iProject: IProject): InitializationSuccess | InitializationError => { // FIXME what happens when we can add and delete channels? // What should be the chain reaction? const channels = oly.olyArr(iProject.channels.map((iChannel) => { return new Channel(iChannel); }), 'Channel'); const instruments = oly.olyArr(iProject.instruments.map((iInstrument) => { switch (iInstrument.instrument) { case 'soundfont': return new Soundfont(new Audio.Soundfont(iInstrument.soundfont), iInstrument); case 'synth': return new Synth(iInstrument); } }), 'Instrument'); const instrumentLookup = makeLookup(instruments); const channelLookup = makeLookup(channels); const tracks = oly.olyArr(iProject.tracks.map((iTrack) => new Track(iTrack)), 'Track'); // First, check that all the IDs exist in the lookup for (const iPattern of iProject.patterns) { for (const iScore of iPattern.scores) { if (!(iScore.instrumentId in instrumentLookup)) { return { type: 'error', message: `Instrument from score ${iScore.id} was not found in instrument list.`, project: emptyProject(), }; } } } const patterns = oly.olyArr(iProject.patterns.map((iPattern) => { const transport = new Audio.Transport(); // Then create the scores now that we know the instruments all exist const scores = iPattern.scores.map((iScore) => { return new Score(transport, instrumentLookup[iScore.instrumentId], iScore); }); return new Pattern(iPattern, transport, scores); }), 'Pattern'); const notFound: string[] = []; const samples = oly.olyArr(iProject.samples.map((iSample) => { let buffer: AudioBuffer | null = null; if (fs.existsSync(iSample.path)) { buffer = loadBufferSync(iSample.path); } else { notFound.push(iSample.path); } return new Sample(buffer, iSample); }), 'Sample'); if (notFound.length !== 0) { notify.warning(`Audio files not found`, { detail: `${notFound.join('\n')}`, }); } const automationClips = oly.olyArr(iProject.automationClips.map((iAutomationClip) => { let signal: Audio.Signal; if (iAutomationClip.context === 'channel') { // FIXME remove this signal = (channelLookup[iAutomationClip.contextId] as any)[iAutomationClip.attr]; } else { signal = (instrumentLookup[iAutomationClip.contextId] as any)[iAutomationClip.attr]; } if (!signal) { // FIXME remove this error and instead return error throw Error('Unable to parse automation clip'); } return new AutomationClip(signal, iAutomationClip); }), 'Automation Clip'); const clipLookup = makeLookup(automationClips); const patternLookup = makeLookup(patterns); const sampleLookup = makeLookup(samples); const mTransport = new Audio.Transport(); // master transport const elements: PlaylistElements[] = []; for (const iElement of iProject.master.elements) { switch (iElement.type) { case 'automation': if (!(iElement.id in clipLookup)) { return { type: 'error', message: `An Automation clip from the Playlist was not found (${iElement.id}).`, project: emptyProject(), }; } const clip = clipLookup[iElement.id]; elements.push(createAutomationPrototype(iElement, clip, {})(mTransport).copy()); break; case 'pattern': if (!(iElement.id in patternLookup)) { return { type: 'error', message: `A Pattern from the Playlist was not found (${iElement.id}).`, project: emptyProject(), }; } const pattern = patternLookup[iElement.id]; elements.push(createPatternPrototype(iElement, pattern, {})(mTransport).copy()); break; case 'sample': if (!(iElement.id in sampleLookup)) { return { type: 'error', message: `A sample from the Playlist was not found (${iElement.id}).`, project: emptyProject(), }; } const sample = sampleLookup[iElement.id]; elements.push(createSamplePrototype(iElement, sample, {})(mTransport).copy()); break; } } const master = new Playlist(mTransport, elements); return { type: 'success', project: { bpm: iProject.bpm, stepsPerBeat: iProject.stepsPerBeat, beatsPerMeasure: iProject.beatsPerMeasure, name: iProject.name, id: iProject.id, patterns, instruments, channels, tracks, master, samples, automationClips, }, }; }; function emptyProject(): LoadedProject { return { id: uuid.v4(), bpm: 120, stepsPerBeat: 4, beatsPerMeasure: 4, name: '', master: new Playlist(new Audio.Transport(), []), patterns: oly.olyArr([Pattern.create('Pattern 0')], 'Pattern'), instruments: oly.olyArr([Synth.create('Synth 0')], 'Instrument'), channels: oly.olyArr(range(10).map((index) => Channel.create(index)), 'Channel'), tracks: oly.olyArr(range(21).map((index) => Track.create(index)), 'Track'), samples: oly.olyArr([], 'Sample'), automationClips: oly.olyArr([], 'Automation Clip'), }; } function loadProject(): InitializationError | InitializationSuccess { logger.debug('Initiate loading of the project!'); const projectJSON = framework.manager.getProjectJSON(); if (!projectJSON) { return { type: 'success', project: emptyProject(), }; } const result = t.decodeItem(ProjectType, projectJSON); if (result.type === 'error') { return { type: 'error', message: result.message, project: emptyProject(), }; } return load(result.decoded); } export const defineAPI = (i: LoadedProject) => { const { master, patterns, instruments, channels, tracks, samples, automationClips, } = i; const mutedTracks = computed(() => { // 1. Get the track and the index in a tuple // 2. Filter to only the muted tracks // 3. Map so that you only have the indices // 4. Create a set with the indices return new Set(tracks .map((tr, ind) => [tr, ind] as const) .filter(([tr]) => tr.mute.value) .map(([_, ind]) => ind), ); }); // Ok this this solution kinda works but isn't complete // I honestly don't know how to go about fixing this issue but here is a description: // When a track is unmuted, everything in that track needs to be checked for onMidStart, onTick, and onEnd // Right now, we do nothing so for e.g. if a sample is halfway finish in a muted track which is subsequently // unmuted then we don't trigger the onMidStart or onEnd events // IMO this isn't a very simple problem to solve because the transport which handles all playback doesn't // have the concept on a track so how do we tell it to check all previous events which were previously filtered // out?? This isn't a huge issue though so I'm not fixing it ATM master.transport.addFilter((event) => { return !mutedTracks.value.has(event.row); }); instruments.onDidRemove(({ items: deletedInstruments }) => { logger.debug('instruments onDidRemove with ' + deletedInstruments.length + ' elements!'); const instrumentSet = new Set<Instrument>(deletedInstruments); patterns.forEach((pattern) => { const toRemove: number[] = []; pattern.scores.forEach((score, ind) => { if (instrumentSet.has(score.instrument)) { toRemove.push(ind); } }); logger.debug(`Removing ${toRemove.length} scores from "${pattern.name}"`); for (const ind of reverse(toRemove)) { pattern.scores.splice(ind, 1); } }); }); // FIXME move to instrument?? This is kinda tough though as the instruments would need references // to the channels. const setChannel = (instrument: Soundfont | Synth, channel: number | undefined) => { let destination: GraphNode; const destinationName = channel !== undefined ? `Channel ${channel}` : 'Master'; if (channel === undefined) { destination = masterNode; } else { const c = channels[channel]; destination = c.effects[0]?.effect ?? c.input; } return { execute: () => { logger.debug(`Connecting "${instrument.name.value}" to ${destinationName}`); const dispose = instrument.output.connect(destination); return { undo: () => { logger.debug(`Undoing connecting of "${instrument.name.value}" to ${destinationName}`); dispose.dispose(); }, }; }, }; }; const watchInstruments = ({ items }: { items: Array<Soundfont | Synth> }) => { items.forEach((instrument) => { instrument.channel.onDidChange(({ newValue: channel, subscriptions }) => { subscriptions.push(setChannel(instrument, channel)); }); }); }; instruments.onDidAdd(watchInstruments); // Do the initial connection instruments.forEach((instrument) => setChannel(instrument, instrument.channel.value).execute()); watchInstruments({ items: instruments }); const removeElements = <T extends PlaylistElementType>( type: T, removed: Array<PlaylistElementLookup[T]['element']>, ) => { const set = new Set(removed); const toRemove: number[] = []; master.elements.forEach((el, ind) => { if (el.type === type && set.has(el.element)) { toRemove.push(ind); } }); for (const ind of reverse(toRemove)) { master.elements.splice(ind, 1); } }; samples.onDidRemove(({ items: removedSamples }) => { removeElements('sample', removedSamples); }); patterns.onDidRemove(({ items: removedPatterns }) => { removeElements('pattern', removedPatterns); }); automationClips.onDidRemove(({ items: removedAutomation }) => { removeElements('automation', removedAutomation); }); const serialize = (): IProject => { return { id: project.id, bpm: project.bpm.value, name: project.name.value, stepsPerBeat: project.stepsPerBeat, beatsPerMeasure: project.beatsPerMeasure, patterns: patterns.map((pattern) => pattern.serialize()), instruments: instruments.map((instrument) => instrument.serialize()), channels: channels.map((channel) => channel.serialize()), tracks: tracks.map((track) => track.serialize()), samples: samples.map((sample) => sample.serialize()), automationClips: automationClips.map((clip) => clip.serialize()), master: master.serialize(), }; }; async function save(path: string) { const encoded = serialize(); await fs.writeFile(path, JSON.stringify(encoded, null, 4)); } // FIXME move this somewhere else function createAutomationClip<T extends Automatable>( payload: { automatable: T, key: keyof T & string, end: number, start: number }, ) { const { start, end, key, automatable } = payload; const signal = automatable[key] as any as Audio.Signal; const available: boolean[] = Array(tracks.length).fill(true); master.elements.forEach((element) => { if ( start > element.time.value && start < element.time.value + element.duration.value || end > element.time.value && end < element.time.value + element.duration.value ) { available[element.row.value] = false; } }); let row: number | null = null; for (const [ind, isAvailable] of available.entries()) { if (isAvailable) { row = ind; break; } } if (row === null) { notify.warning('Unable to create automation clip', { detail: 'There are no free tracks. Move elements and try again.', }); return; } let context: ClipContext; if (automatable instanceof Channel) { context = 'channel'; } else { context = 'instrument'; } const length = payload.end - payload.start; const clip = AutomationClip.create(length, signal, context, automatable.id, key); const placed = createAutomationPrototype( { time: payload.start, row, duration: clip.duration }, clip, {}, )(master.transport).copy(); automationClips.push(clip); master.elements.push(placed); } async function openTempProject(p: IProject) { const { name: path } = tmp.fileSync({ keep: true }); await fs.writeFile(path, JSON.stringify(p, null, 4)); logger.info(`Writing ${path} as backup`); framework.manager.setOpenedFile(path, { isTemp: true }); const window = remote.getCurrentWindow(); window.reload(); } const events = emitter<{ save: [IProject] }>(); function onDidSave(cb: (encoded: IProject) => void) { events.addListener('save', cb); return { dispose() { events.removeListener('save', cb); }, }; } async function saveProject(opts: { forceDialog?: boolean }) { let projectPath = framework.manager.getOpenedFile(); if (!projectPath || opts.forceDialog) { const saveDialogReturn = await remote.dialog.showSaveDialog(remote.getCurrentWindow(), {}); projectPath = saveDialogReturn.filePath || null; // If the user cancels the dialog if (!projectPath) { return; } if (!projectPath.endsWith(DG_EXTENSION)) { logger.info(`Adding ${DG_EXTENSION} to project path`); projectPath = projectPath + DG_EXTENSION; } // Make sure we set the cache and the general // The cache is what is written to the filesystem // and the general is the file that is currently opened logger.info(`Setting opened project as ${projectPath}`); framework.manager.setOpenedFile(projectPath); } const encoded = serialize(); await fs.writeFile(projectPath, JSON.stringify(encoded, null, 4)); events.emit('save', encoded); oly.freezeReference(); } async function removeOpenedFile() { await framework.manager.setOpenedFile(); } async function setOpenedFile(path: string) { await framework.manager.setOpenedFile(path); } function getOpenedFile() { return framework.manager.getOpenedFile(); } Audio.Context.BPM = i.bpm; const bpm = oly.olyRef(i.bpm, 'BPM'); bpm.onDidChange(({ newValue, oldValue, subscriptions }) => { subscriptions.push({ execute: () => { Audio.Context.BPM = newValue; return { undo: () => { Audio.Context.BPM = oldValue; }, }; }, }); }); logger.info('Master node -> ', masterNode); return { id: i.id, bpm, name: oly.olyRef(i.name), stepsPerBeat: i.stepsPerBeat, beatsPerMeasure: i.beatsPerMeasure, instruments, patterns, serialize, master, samples, automationClips, tracks, channels, save, createAutomationClip, openTempProject, onDidSave, onDidSetOpenedFile: framework.manager.onDidSetOpenedFile, saveProject, removeOpenedFile, setOpenedFile, getOpenedFile, } as const; }; const extension = createExtension({ id: 'dawg.project', activate(context) { const result = loadProject(); if (result.type === 'error') { notify.warning('Unable to load project.', { detail: result.message, duration: Infinity }); } const api = defineAPI(result.project); context.subscriptions.push(addEventListener('online', () => { api.instruments.forEach((instrument) => { instrument.online(); }); })); const save = framework.defineMenuBarItem({ menu: 'File', section: '1_save', text: 'Save', shortcut: ['CmdOrCtrl', 'S'], callback: async () => { logger.debug('"Save" initiated!'); await api.saveProject({ forceDialog: false, }); }, }); const saveAs = framework.defineMenuBarItem({ menu: 'File', section: '1_save', text: 'Save As', shortcut: ['CmdOrCtrl', 'Shift', 'S'], callback: async () => { logger.debug('"Save As" initiated!'); await api.saveProject({ forceDialog: true, }); }, }); const open = framework.defineMenuBarItem({ menu: 'File', section: '0_newOpen', text: 'Open', shortcut: ['CmdOrCtrl', 'O'], callback: async () => { // files can be undefined. There is an issue with the .d.ts files. const files = await remote.dialog.showOpenDialog( remote.getCurrentWindow(), { filters: FILTERS, properties: ['openFile'] }, ); if (!files.filePaths || files.filePaths.length === 0) { return; } const filePath = files.filePaths[0]; await api.setOpenedFile(filePath); const window = remote.getCurrentWindow(); window.reload(); }, }); const newProject = framework.defineMenuBarItem({ menu: 'File', section: '0_newOpen', shortcut: ['CmdOrCtrl', 'N'], text: 'New Project', callback: async () => { await api.removeOpenedFile(); const window = remote.getCurrentWindow(); window.reload(); }, }); const undo = framework.defineMenuBarItem({ menu: 'Edit', section: '0_undoRedo', shortcut: ['CmdOrCtrl', 'Z'], text: 'Undo', callback: () => { oly.undo(); }, }); const redo = framework.defineMenuBarItem({ menu: 'Edit', section: '0_undoRedo', shortcut: ['CmdOrCtrl', 'Shift', 'Z'], text: 'Redo', callback: () => { oly.redo(); }, }); [save, saveAs, open, newProject].map((command) => { context.subscriptions.push(commands.registerCommand({ ...command, registerAccelerator: false })); context.subscriptions.push(framework.addToMenu(command)); }); ([undo, redo]).map((command) => { context.subscriptions.push(commands.registerCommand({ ...command, registerAccelerator: false })); context.subscriptions.push(framework.addToMenu(command)); }); context.settings.push({ type: 'string', label: 'Project Name', description: 'Give your project a better name to make it more identifiable.', value: api.name, }); return api; }, }); export const project = framework.manager.activate(extension); // tslint:disable-next-line:no-console console.log(project);
the_stack
import { fireSingleFieldValidations } from './single-field-dispatcher'; import { FieldValidatorArgs, FieldValidationFunctionAsync, InternalFieldValidation, } from '../model'; // Checking console log errors: https://stackoverflow.com/questions/44344801/how-to-use-jest-with-jsdom-to-test-console-log describe('single-field-dispatcher', () => { describe('fireSingleFieldValidations', () => { it(` Spec #1 When passing vm equals undefined, value equals undefined and internalFieldValidations equals undefined should return succeeded FieldValidationResult `, done => { //Arrange const values = undefined; const value = undefined; const internalFieldValidations: InternalFieldValidation[] = undefined; //Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); done(); }); }); it(` Spec #2 When passing vm equals undefined, value equals undefined and internalFieldValidations equals null should return succeeded FieldValidationResult `, done => { //Arrange const values = undefined; const value = undefined; const internalFieldValidations: InternalFieldValidation[] = null; //Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); done(); }); }); it(` Spec #2.1 When passing vm equals undefined, value equals undefined and internalFieldValidations is an empty array should return succeeded FieldValidationResult and calls to successful validation function `, done => { //Arrange const values = undefined; const value = undefined; const internalFieldValidations: InternalFieldValidation[] = null; //Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); done(); }); }); it(` Spec #6 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with one item equals failed validation function should return succeeded false FieldValidationResult and calls to successful validation function just passing full validation info async `, done => { //Arrange const values = undefined; const value = undefined; const validationFn = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const fullValidation: InternalFieldValidation = { validator: validationFn, customArgs: {}, message: 'myError', }; const internalFieldValidations: InternalFieldValidation[] = [ fullValidation, ]; //Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn).toBeCalled(); done(); }); }); it(` Spec #7 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals failed validation function second equals failed validation function should return failed FieldValidationResult and calls only to first validation function `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); expect(validationFn2).not.toBeCalled(); done(); }); }); it(` Spec #8 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals failed validation function second equals success validation function should return failed FieldValidationResult and calls only to first validation function `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); expect(validationFn2).not.toBeCalled(); done(); }); }); it(` Spec #9 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals success validation function second equals failed validation function should return failed FieldValidationResult and calls only to first validation function `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); expect(validationFn2).toBeCalled(); done(); }); }); it(` Spec #10 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals success validation function second equals success validation function should return success FieldValidationResult and calls only to first validation function `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(validationFn2).toBeCalled(); done(); }); }); // TODO: Review this, should just skip that faulty validator and just show warning/error in console? it(` Spec #11 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with one items but returning undefined in the validator (wrong behavior) should return succeeded FieldValidationResult and calls to validation functions console.error should be called `, done => { //Arrange const values = undefined; const value = undefined; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); const validationFn1 = jest.fn().mockResolvedValue(void 0); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); // TODO: Review this, should just skip that faulty validator and just show warning/error in console? it(` Spec #12 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with one item but returning null in the validator (wrong behavior) should return succeded FieldValidationResult and calls to validation functions `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue(null); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); // Original Spec 12 (lc-form) check if assert makes sense it(` Spec #13 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with one item equals validation function resolving a fieldValidationResult equals "" should return succeded FieldValidationResult and calls to validation functions and should display a console.error `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue(''); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); it(` Spec #13.1 When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with one item equals validation function resolving a fieldValidationResult equals "error" should return succeded FieldValidationResult and calls to validation functions, and it should display a console.error `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue('error'); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); it(` Spec #14. When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals validation function resolving a fieldValidationResult equals undefined second equals successful validation function should return succeded FieldValidationResult and calls to validation functions, and it should display a console.error `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue(void 0); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(validationFn2).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); it(` Spec #15. When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals validation function resolving a fieldValidationResult equals undefined second equals failed validation function should return failed FieldValidationResult and calls to validation functions, and it should display a console.error `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue(void 0); const validationFn2 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); expect(validationFn2).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); it(` Spec #16. When passing values equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals failed validation function second equals validation function resolving a fieldValidationResult equals undefined should return failed FieldValidationResult (no console error since faulty validation is not executed) `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: false, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue(void 0); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); expect(validationFn2).not.toBeCalled(); done(); }); }); it(` Spec #17. When passing vm equals undefined, value equals undefined and internalFieldValidations equals array with two items first equals successful validation function second equals validation function resolving a fieldValidationResult equals undefined should return succeeded FieldValidationResult and console error warning about faulty validator in form `, done => { //Arrange const values = undefined; const value = undefined; const validationFn1 = jest.fn().mockResolvedValue({ errorMessage: '', succeeded: true, type: '', key: '', }); const validationFn2 = jest.fn().mockResolvedValue(void 0); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, ]; const errorStub = jest .spyOn(global.console, 'error') .mockImplementation(() => {}); // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); expect(validationFn1).toBeCalled(); expect(validationFn2).toBeCalled(); expect(errorStub).toHaveBeenCalled(); done(); }); }); it(` Spec #18. should pass customArgs to its proper validationFunction and succeed `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const validationFn1: FieldValidationFunctionAsync = ({ customArgs }) => Promise.resolve({ message: '', succeeded: customArgs.myCheck === 1 ? true : false, type: '', key: 'test1', }); const customArgs1 = { myCheck: 1 }; const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, customArgs: customArgs1, message: 'my error message', }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeTruthy(); done(); }); }); it(` Spec #18.1 should pass customArgs to its proper validationFunction and failed `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const validationFn1: FieldValidationFunctionAsync = jest .fn() .mockImplementation(({ customArgs }) => Promise.resolve({ message: '', succeeded: customArgs.myCheck === 1 ? true : false, type: '', key: 'test1', }) ); const customArgs1 = { myCheck: 0 }; const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, customArgs: customArgs1, message: 'my error message', }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, ]; // Act const fieldValidationResultPromise = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert fieldValidationResultPromise.then(fieldValidationResult => { expect(fieldValidationResult.succeeded).toBeFalsy(); expect(validationFn1).toBeCalled(); const fieldValidatorArgs: FieldValidatorArgs = { value, values, customArgs: customArgs1, message: 'my error message', }; expect(validationFn1).toBeCalledWith(fieldValidatorArgs); done(); }); }); it(` Spec #19.1 should resolve first validation when it feeds 5 validations and first failed `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const createValidationFn = (key, succeeded, timeout) => jest.fn().mockImplementation( () => new Promise(resolve => setTimeout( () => resolve({ errorMessage: '', succeeded, type: '', key, }), timeout ) ) ); const validationFn1 = createValidationFn('key1', false, 100); const validationFn2 = createValidationFn('key2', true, 50); const validationFn3 = createValidationFn('key3', true, 25); const validationFn4 = createValidationFn('key4', true, 30); const validationFn5 = createValidationFn('key5', true, 50); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const fullFieldValidationAsync3: InternalFieldValidation = { validator: validationFn3, }; const fullFieldValidationAsync4: InternalFieldValidation = { validator: validationFn4, }; const fullFieldValidationAsync5: InternalFieldValidation = { validator: validationFn5, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, fullFieldValidationAsync3, fullFieldValidationAsync4, fullFieldValidationAsync5, ]; // Act const result = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert result.then(validationResult => { expect(validationResult.key).toEqual('key1'); expect(validationResult.succeeded).toBeFalsy(); expect(validationFn1).toHaveBeenCalled(); expect(validationFn2).not.toHaveBeenCalled(); expect(validationFn3).not.toHaveBeenCalled(); expect(validationFn4).not.toHaveBeenCalled(); expect(validationFn5).not.toHaveBeenCalled(); done(); }); }); it(` Spec #19.2 should resolve third validation when it feeds 5 validations and third, fourth and fifth failed `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const createValidationFn = (key, succeeded, timeout) => jest.fn().mockImplementation( () => new Promise(resolve => setTimeout( () => resolve({ errorMessage: '', succeeded, type: '', key, }), timeout ) ) ); const validationFn1 = createValidationFn('key1', true, 100); const validationFn2 = createValidationFn('key2', true, 50); const validationFn3 = createValidationFn('key3', false, 20); const validationFn4 = createValidationFn('key4', false, 30); const validationFn5 = createValidationFn('key5', false, 50); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const fullFieldValidationAsync3: InternalFieldValidation = { validator: validationFn3, }; const fullFieldValidationAsync4: InternalFieldValidation = { validator: validationFn4, }; const fullFieldValidationAsync5: InternalFieldValidation = { validator: validationFn5, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, fullFieldValidationAsync3, fullFieldValidationAsync4, fullFieldValidationAsync5, ]; // Act const result = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert result.then(validationResult => { expect(validationResult.key).toEqual('key3'); expect(validationResult.succeeded).toBeFalsy(); expect(validationFn1).toHaveBeenCalled(); expect(validationFn2).toHaveBeenCalled(); expect(validationFn3).toHaveBeenCalled(); expect(validationFn4).not.toHaveBeenCalled(); expect(validationFn5).not.toHaveBeenCalled(); done(); }); }); it(` Spec #19.3 should resolve fifth validation when it feeds 5 validations fifth failed `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const createValidationFn = (key, succeeded, timeout) => jest.fn().mockImplementation( () => new Promise(resolve => setTimeout( () => resolve({ errorMessage: '', succeeded, type: '', key, }), timeout ) ) ); const validationFn1 = createValidationFn('key1', true, 100); const validationFn2 = createValidationFn('key2', true, 50); const validationFn3 = createValidationFn('key3', true, 25); const validationFn4 = createValidationFn('key4', true, 30); const validationFn5 = createValidationFn('key5', false, 50); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const fullFieldValidationAsync3: InternalFieldValidation = { validator: validationFn3, }; const fullFieldValidationAsync4: InternalFieldValidation = { validator: validationFn4, }; const fullFieldValidationAsync5: InternalFieldValidation = { validator: validationFn5, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, fullFieldValidationAsync3, fullFieldValidationAsync4, fullFieldValidationAsync5, ]; // Act const result = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert result.then(validationResult => { expect(validationResult.key).toEqual('key5'); expect(validationResult.succeeded).toBeFalsy(); expect(validationFn1).toHaveBeenCalled(); expect(validationFn2).toHaveBeenCalled(); expect(validationFn3).toHaveBeenCalled(); expect(validationFn4).toHaveBeenCalled(); expect(validationFn5).toHaveBeenCalled(); done(); }); }); it(` Spec #19.4 should resolve fifth validation when it feeds 5 successfully validations `, done => { //Arrange const values = { a: 'foo', b: 'bar' }; const value = 'new value'; const createValidationFn = (key, succeeded, timeout) => jest.fn().mockImplementation( () => new Promise(resolve => setTimeout( () => resolve({ errorMessage: '', succeeded, type: '', key, }), timeout ) ) ); const validationFn1 = createValidationFn('key1', true, 100); const validationFn2 = createValidationFn('key2', true, 50); const validationFn3 = createValidationFn('key3', true, 25); const validationFn4 = createValidationFn('key4', true, 30); const validationFn5 = createValidationFn('key5', true, 50); const fullFieldValidationAsync1: InternalFieldValidation = { validator: validationFn1, }; const fullFieldValidationAsync2: InternalFieldValidation = { validator: validationFn2, }; const fullFieldValidationAsync3: InternalFieldValidation = { validator: validationFn3, }; const fullFieldValidationAsync4: InternalFieldValidation = { validator: validationFn4, }; const fullFieldValidationAsync5: InternalFieldValidation = { validator: validationFn5, }; const internalFieldValidations: InternalFieldValidation[] = [ fullFieldValidationAsync1, fullFieldValidationAsync2, fullFieldValidationAsync3, fullFieldValidationAsync4, fullFieldValidationAsync5, ]; // Act const result = fireSingleFieldValidations( value, values, internalFieldValidations ); // Assert result.then(validationResult => { expect(validationResult.key).toEqual('key5'); expect(validationResult.succeeded).toBeTruthy(); expect(validationFn1).toHaveBeenCalled(); expect(validationFn2).toHaveBeenCalled(); expect(validationFn3).toHaveBeenCalled(); expect(validationFn4).toHaveBeenCalled(); expect(validationFn5).toHaveBeenCalled(); done(); }); }); }); });
the_stack
import { NodesEvent, GraphEvent, NodeConnectEvent, NodeConnectEventArg, NodeEvent, GroupEvent } from './misc/Events'; import { NodeJSONType, NodeBase } from './nodes/NodeBase'; import { Nodes } from './nodes/NodeDictionary'; import { GroupJSONType, GroupElement } from './GroupElement'; import { Process } from './Process'; import { DirectedAcyclicGraph } from './DirectedAcyclicGraph'; import { KilledProcessError } from './misc/KilledProcessError'; import { IO } from './io/IO'; import { NodeConstructorType } from './NodeConstructorType'; import { GraphJSONTypeV0, migrate } from './Migration'; import { Unknown } from './nodes/Unknown'; import { IDisposable } from './misc/IDisposable'; import { getNodeConstructorNameOfInstance } from './nodes/NodeUtils'; export const GraphJSONVersion = 1; export type GraphJSONType = { version: number; nodes: NodeJSONType[], groups: GroupJSONType[], }; export class Graph implements IDisposable { public onAddNode: NodeEvent = new NodeEvent(); public onRemoveNode: NodeEvent = new NodeEvent(); public onConnectNode: NodeConnectEvent = new NodeConnectEvent(); public onDisconnectNode: NodeConnectEvent = new NodeConnectEvent(); public onAddGroup: GroupEvent = new GroupEvent(); public onRemoveGroup: GroupEvent = new GroupEvent(); public onStartProcess: GraphEvent = new GraphEvent(); public onFinishProcess: GraphEvent = new GraphEvent(); public onConstructed: NodesEvent = new NodesEvent(); private nodes: NodeBase[] = []; private groups: GroupElement[] = []; private processQueue: Process[] = []; constructor (nodes: NodeBase[] = [], groups: GroupElement[] = []) { this.nodes = nodes.slice(); this.groups = groups.slice(); this.onConnectNode.on(this.onConnectedNode.bind(this)); this.onDisconnectNode.on(this.onDisconnectedNode.bind(this)); } addNode (uuid: string, constructor: NodeConstructorType, x: number = 0, y: number = 0): NodeBase { const node = new constructor(uuid); this.nodes.push(node); node.onConnect.on(this.onConnectNode.emit); node.onDisconnect.on(this.onDisconnectNode.emit); node.onValueChanged.on((e) => { this.stepNode(e.node); }); // for SubGraphNode only // node.on(Events.EDIT_SUBGRAPH, this.onEditSubGraph.bind(this)) // node.on(Events.EXPAND_SUBGRAPH, this.onExpandSubGraph.bind(this)) this.onAddNode.emit({ node }); node.moveTo(x, y); this.stepNode(node); return node; } removeNode (node: NodeBase, fire = true) { node.disconnectAllIO(); node.dispose(); const idx = this.nodes.indexOf(node); this.nodes.splice(idx, 1); for (let i = this.groups.length - 1; i >= 0; i--) { const grp = this.groups[i]; grp.removeNode(node.uuid); if (grp.isEmpty()) { this.removeGroup(grp); } } this.onRemoveNode.emit({ node }); } public removeNodes (UUIDs: string[], fire = true): string[] { UUIDs.forEach((id) => { const node = this.nodes.find(n => n.uuid === id); if (node !== undefined) { this.removeNode(node, fire); } }); this.notifyGraphConstructed(); return UUIDs; } public addGroup (group: GroupElement): void { this.groups.push(group); this.onAddGroup.emit({ group }); } public removeGroup (group: GroupElement): void { group.dispose(); const idx = this.groups.indexOf(group); this.groups.splice(idx, 1); this.onRemoveGroup.emit({ group }); } public removeGroups (IDs: string[]): void { for (let i = IDs.length - 1; i >= 0; i--) { const group = this.groups.find(grp => grp.uuid === IDs[i]); if (group !== undefined) { this.removeGroup(group); } } } public stepNode (node: NodeBase): void { this.onStartProcess.emit({ graph: this }); this.resetNode(node); this.processNode(node); } private processNode (node: NodeBase): Promise<void> { const steppable = node.isSteppable(); if (!(steppable && node.enabled)) { this.resetNode(node); this.checkProcessesDone(); return Promise.resolve(); } // nodeを処理しているすべてのprocessをkillして削除 const others = this.findProcesses(node); others.forEach((other) => { this.removeProcess(other.pid); }); const proc = new Process(node); this.processQueue.push(proc); // いきなりstartでなく、tickを挟むことで連続的にstepNodeが呼び出された際に無駄な処理を省く(process.killがコールされるので) return proc.tick() .then(() => proc.execute()) .then((_) => { node.safe(); const nexts = node.getNexts(); nexts.forEach((next) => { this.processNode(next); }); }).catch((err: Error) => { // 途中でKillされた場合はResetしない & エラー扱いにしない if (!(err instanceof KilledProcessError)) { this.resetNode(node); node.error(err.toString()); if ((process.env.NODE_ENV === 'development') || process.env.TEST) { // console.warn(err); } } }).finally(() => { // nexts後にremoveProcessすることですべてのprocessの終わりを検知(processes.length <= 0)できる this.removeProcess(proc.pid); }); } private findProcesses (node: NodeBase): Process[] { return this.processQueue.filter(proc => proc.has(node)); } private removeProcess (pid: string): void { const idx = this.processQueue.findIndex(other => other.pid === pid); if (idx >= 0) { const proc = this.processQueue[idx]; proc.kill(); this.processQueue.splice(idx, 1); } this.checkProcessesDone(); } private removeAllProcesses (): void { this.processQueue.forEach((proc) => { proc.kill(); }); this.processQueue = []; this.checkProcessesDone(); } private checkProcessesDone (): void { if (this.processQueue.length <= 0) { this.onFinishProcess.emit({ graph: this }); this.notifyGraphConstructed(); } } protected resetNode (node: NodeBase): void { const next = node.reset(); next.forEach((n) => { n.reset(); this.resetNode(n); }); } public getParentNode (io: IO): NodeBase | undefined { return this.nodes.find(n => n.hasIO(io)); } public connectIO (srcN: NodeBase, srcO: number = 0, dstN: NodeBase, dstI: number = 0): void { if (srcN.existIO(srcO, dstN, dstI)) { return; } srcN.connectIO(srcO, dstN, dstI); } disconnectIO (srcN: NodeBase, srcO: number, dstN: NodeBase, dstI: number): void { if (!srcN.existIO(srcO, dstN, dstI)) { return; } srcN.disconnectIO(srcO, dstN, dstI); } protected onConnectedNode (e: NodeConnectEventArg) { this.stepNode(e.destination); } protected onDisconnectedNode (e: NodeConnectEventArg) { this.stepNode(e.destination); } public dispose (): void { this.removeNodes(this.nodes.map(n => n.uuid), false); this.removeGroups(this.groups.map(grp => grp.uuid)); this.removeAllProcesses(); // dispose listeners this.onAddNode.dispose(); this.onRemoveNode.dispose(); this.onConnectNode.dispose(); this.onDisconnectNode.dispose(); this.onAddGroup.dispose(); this.onRemoveGroup.dispose(); this.onStartProcess.dispose(); this.onFinishProcess.dispose(); this.onConnectNode.dispose(); } public createNodesJSON (jsons: NodeJSONType[]): NodeBase[] { return jsons.map((json, i) => { const map = Nodes as { [name: string]: NodeConstructorType }; let constructor = map[json.name] as NodeConstructorType; if (constructor === undefined) { constructor = Unknown; } const instance = this.addNode(json.uuid, constructor); instance.fromJSON(json); return instance; }); } public connectNodesJSON (jsons: NodeJSONType[], candidates: NodeBase[]): void { // Process nodes based on DAG order to resolve errors. const tree = new DirectedAcyclicGraph(jsons, candidates); const hierarchy = tree.hierarchy; const indices = Object.keys(hierarchy).map(s => Number(s)).sort((a, b) => { return (a - b); }); indices.forEach((idx) => { const layer = hierarchy[idx]; layer.forEach((target) => { const json = jsons.find(json => json.uuid === target.uuid); if (json === undefined) { return; } json.inputs.forEach((input, dstI) => { input.connections.forEach((con) => { // Connection from the node (which is not includeded in jsons) to `target` const found = jsons.find(json => json.uuid === con.uuid); if (found === undefined) { const srcNode = this.nodes.find(other => (other.uuid === con.uuid)); if (srcNode !== undefined && srcNode !== target) { this.connectIO(srcNode, con.index, target, dstI); } } }); }); json.outputs.forEach((output, srcO) => { output.connections.forEach((con) => { const dst = candidates.find(cand => cand.uuid === con.uuid); if (dst !== undefined && target !== dst) { this.connectIO(target, srcO, dst, con.index); } }); }); }); }); } public createGroupsJSON (json: GroupJSONType[]) : GroupElement[] { return json.map((el) => { const group = new GroupElement(el.uuid, el.nodes); this.addGroup(group); return group; }); } public notifyGraphConstructed (): void { this.onConstructed.emit({ nodes: this.nodes }); } public fromJSON (json: any): NodeBase[] { if (json.version === undefined) { const v0 = json as GraphJSONTypeV0; json = migrate(v0); } const nodes = this.createNodesJSON(json.nodes); this.connectNodesJSON(json.nodes, nodes); this.createGroupsJSON(json.groups); return nodes; } public toJSON (): GraphJSONType { return { version: GraphJSONVersion, nodes: this.nodes.map(n => n.toJSON(getNodeConstructorNameOfInstance(n)!)), groups: this.groups.map(g => g.toJSON()) }; } }
the_stack
import * as _ from "lodash"; import ASTNode from "./parsers/ASTNode"; import Position from "./parsers/Position"; import StaticContext from "./StaticContext"; import RootStaticContext from "./RootStaticContext"; import QName from "./QName"; import Variable from "./Variable"; import Marker from "./Marker"; import * as err from "./StaticErrors"; import * as war from "./StaticWarnings"; import Iterator from "../runtime/iterators/Iterator"; import ItemIterator from "../runtime/iterators/ItemIterator"; import AdditiveIterator from "../runtime/iterators/AdditiveIterator"; import RangeIterator from "../runtime/iterators/RangeIterator"; import SequenceIterator from "../runtime/iterators/SequenceIterator"; import MultiplicativeIterator from "../runtime/iterators/MultiplicativeIterator"; import VarRefIterator from "../runtime/iterators/VarRefIterator"; import ComparisonIterator from "../runtime/iterators/ComparisonIterator"; import ObjectIterator from "../runtime/iterators/ObjectIterator"; import PairIterator from "../runtime/iterators/PairIterator"; import ArrayIterator from "../runtime/iterators/ArrayIterator"; import SimpleMapExpr from "../runtime/iterators/SimpleMapExpr"; import UnaryExpr from "../runtime/iterators/UnaryExpr"; import ObjectLookupExpr from "../runtime/iterators/ObjectLookupExpr"; import FLWORIterator from "../runtime/iterators/flwor/FLWORIterator"; import ForIterator from "../runtime/iterators/flwor/ForIterator"; import LetIterator from "../runtime/iterators/flwor/LetIterator"; import WhereIterator from "../runtime/iterators/flwor/WhereIterator"; import OrderByIterator from "../runtime/iterators/flwor/OrderByIterator"; import ReturnIterator from "../runtime/iterators/flwor/ReturnIterator"; //TODO: remove this class import Item from "../runtime/items/Item"; export default class Translator { private ast: ASTNode; private markers: Marker[] = []; private iterators: Iterator[] = []; private rootSctx: RootStaticContext; private sctx: StaticContext; constructor(rootSctx: RootStaticContext, ast: ASTNode) { this.rootSctx = rootSctx; this.sctx = rootSctx; this.ast = ast; } resolveQName(value: string, pos: Position): QName { var idx; if (value.substring(0, 2) === "Q{") { idx = value.indexOf("}"); return new QName("", value.substring(2, idx), value.substring(idx + 1)); } else { idx = value.indexOf(":"); var prefix = value.substring(0, idx); var qname = this.sctx.getNamespaceByPrefix(prefix); if(!qname && prefix.length > 0) { this.markers.push(new err.XPST0081(pos, prefix)); } return new QName(prefix, qname ? qname.getURI() : "", value.substring(idx + 1)); } } private pushIt(it: Iterator): Translator { this.iterators.push(it); return this; } private popIt(): Iterator { if(this.iterators.length === 0) { throw new Error("Empty iterator statck."); } return this.iterators.pop(); } private pushCtx(pos: Position): Translator { this.sctx = this.sctx.createContext(pos); return this; } private popCtx(pos: Position): Translator { this.sctx.setPosition( new Position( this.sctx.getPosition().getStartLine(), this.sctx.getPosition().getStartColumn(), pos.getEndLine(), pos.getEndColumn(), pos.getFileName() ) ); this.sctx.getParent().addVarRefs(this.sctx.getUnusedVarRefs()); this.sctx.getUnusedVariables().forEach((v: Variable) => { if(v.getType() !== "GroupingVariable" && v.getType() !== "CatchVar") { this.markers.push(new war.UnusedVariable(v)); } }); this.sctx = this.sctx.getParent(); return this; } compile(): Iterator { this.visit(this.ast); //if iterators.lenght === 0 //TODO: [XPST0003] invalid expression: syntax error, unexpected end of file, the query body should not be empty if(this.iterators.length !== 1) { throw new Error("Invalid query plan."); } return this.iterators[0]; } getMarkers(): Marker[] { return this.markers; } VersionDecl(node: ASTNode): boolean { return true; } NamespaceDecl(node: ASTNode): boolean { var prefix = node.find(["NCName"]).toString(); var uri = node.find(["URILiteral"]).toString(); this.sctx.addNamespace(prefix, uri); return true; } // Expr ::= ExprSingle ("," ExprSingle)* Expr(node: ASTNode): boolean { var exprs = node.find(["ExprSingle"]); if(exprs.length > 1) { var its = []; exprs.forEach(expr => { this.visit(expr); its.push(this.popIt()); }); this.pushIt(new SequenceIterator(node.getPosition(), its)); return true; } return false; } //FLWORExpr ::= InitialClause IntermediateClause* ReturnClause FLWORExpr(node: ASTNode): boolean { //this.pushCtx(node.getPosition()); var clauses = []; var children = node.getChildren().filter(node => { return node.getName() !== "WS"; }); for(var i = 0; i < children.length; i++) { this.visit(children[i]); clauses.push(this.popIt()); } this.pushIt(new FLWORIterator(node.getPosition(), clauses)); for(var i = 0; i < children.length - 1; i++) { this.popCtx(node.getPosition()); } //this.popCtx(node.getPosition()); return true; } //ForBinding ::= "$" VarName TypeDeclaration? AllowingEmpty? PositionalVar? "in" ExprSingle ForBinding(node: ASTNode): boolean { this.visitChildren(node); this.pushCtx(node.getPosition()); var varName = node.find(["VarName"])[0].toString(); var allowingEmpty = node.find(["AllowingEmpty"])[0] !== undefined; var pos = node.find(["PositionalVar"])[0]; var posVarName; if(pos) { posVarName = pos.find(["VarName"])[0].toString(); } this.pushIt(new ForIterator(node.getPosition(), varName, allowingEmpty, posVarName, this.popIt())); return true; } //LetBinding ::= ( '$' VarName TypeDeclaration? | FTScoreVar ) ':=' ExprSingle LetBinding(node: ASTNode): boolean { this.visitChildren(node); this.pushCtx(node.getPosition()); var v = node.find(["VarName"])[0]; var qname = this.resolveQName(v.toString(), v.getPosition()); var variable = new Variable(v.getPosition(), "LetBinding", qname); var overrides = this.sctx.getVariable(variable) !== undefined; this.sctx.addVariable(variable); this.pushIt(new LetIterator(node.getPosition(), v.toString(), this.popIt(), overrides)); return true; } WhereClause(node: ASTNode): boolean { this.visitChildren(node); this.pushCtx(node.getPosition()); this.pushIt(new WhereIterator(node.getPosition(), this.popIt())); return true; } //OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList OrderByClause(node: ASTNode): boolean { this.pushCtx(node.getPosition()); var orderSpecs: { expr: Iterator; ascending: boolean; emptyGreatest: boolean }[] = []; var specs: ASTNode[] = node.find(["OrderSpecList"])[0].getChildren(); _.chain<ASTNode[]>(specs) .filter((spec: ASTNode) => { return spec.getName() === "OrderSpec"; }) .forEach((spec: ASTNode) => { this.visitChildren(spec); orderSpecs.push({ expr: this.popIt(), ascending: spec.find(["OrderModifier"])[0].toString().indexOf("ascending") !== -1, emptyGreatest: spec.find(["OrderModifier"])[0].toString().indexOf("empty greatest") !== -1 }); }); this.pushIt(new OrderByIterator(node.getPosition(), false, orderSpecs)); return true; } ReturnClause(node: ASTNode): boolean { this.visitChildren(node); this.pushIt(new ReturnIterator(node.getPosition(), this.popIt())); return true; } //PostfixExpr ::= PrimaryExpr ( Predicate | ArgumentList | ObjectLookup | ArrayLookup | ArrayUnboxing )* PostfixExpr(node: ASTNode): boolean { var primary = node.find(["PrimaryExpr"]); this.visit(primary[0]); var it = this.popIt(); var names = ["Predicate", "ArgumentList", "ObjectLookup", "ArrayLookup", "ArrayUnboxing"]; var exprs = []; names.forEach(name => { exprs = exprs.concat(node.find([name])); }); exprs.forEach(expr => { this.visit(expr); //ObjectLookup ::= "." ( StringLiteral | NCName | ParenthesizedExpr | VarRef | ContextItemExpr ) if(expr.getName() === "ObjectLookup") { var name = expr.find(["NCName"]); if(name.length > 0) { it = new ObjectLookupExpr(node.getPosition(), it, new ItemIterator(name[0].getPosition(), new Item(name[0].toString()))); } else { it = new ObjectLookupExpr(node.getPosition(), it, this.popIt()); } } }); this.pushIt(it); return true; } //ObjectLookup ::= "." ( StringLiteral | NCName | ParenthesizedExpr | VarRef | ContextItemExpr ) //ArrayLookup ::= '[' '[' Expr ']' ']' //ArrayUnboxing ::= '[' ']' //ArgumentList ::= '(' ( Argument ( ',' Argument )* )? ')' //Predicate ::= '[' Expr ']' //StringConcatExpr ::= RangeExpr ( '||' RangeExpr )* /* StringConcatExpr(node: ASTNode): boolean { var exprs = return false; } */ //ParenthesizedExpr ::= "(" Expr? ")" ParenthesizedExpr(node: ASTNode): boolean { if(node.find(["Expr"]).length === 0) { this.pushIt(new SequenceIterator(node.getPosition(), [])); return true; } return false; } VarRef(node: ASTNode): boolean { var varName = node.find(["VarName"])[0].toString(); this.sctx.addVarRef(this.resolveQName(varName, node.getPosition())); this.pushIt(new VarRefIterator(node.getPosition(), varName)); return true; } ContextItemExpr(node: ASTNode): boolean { this.sctx.addVarRef(this.resolveQName("$", node.getPosition())); this.pushIt(new VarRefIterator(node.getPosition(), "$")); return true; } //RangeExpr ::= AdditiveExpr ( "to" AdditiveExpr )? RangeExpr(node: ASTNode): boolean { var exprs = node.find(["AdditiveExpr"]); if(exprs.length > 1) { this.visitChildren(node); var to = this.popIt(); var from = this.popIt(); this.iterators.push(new RangeIterator(node.getPosition(), from, to)); return true; } return false; } //AdditiveExpr ::= MultiplicativeExpr ( ( '+' | '-' ) MultiplicativeExpr )* AdditiveExpr(node: ASTNode): boolean { var exprs = node.find(["MultiplicativeExpr"]); var ops = node.find(["TOKEN"]); if(exprs.length > 1) { this.visit(exprs[0]); var it = this.popIt(); for(var i = 1; i < exprs.length; i++) { this.visit(exprs[i]); it = new AdditiveIterator(node.getPosition(), it, this.popIt(), ops.splice(0, 1)[0].getValue() === "+"); } this.pushIt(it); return true; } return false; } //MultiplicativeExpr ::= UnionExpr ( ( '*' | 'div' | 'idiv' | 'mod' ) UnionExpr )* MultiplicativeExpr(node: ASTNode): boolean { var exprs = node.find(["UnionExpr"]); var ops = node.find(["TOKEN"]); if(exprs.length > 1) { this.visit(exprs[0]); var it = this.popIt(); for(var i = 1; i < exprs.length; i++) { this.visit(exprs[i]); it = new MultiplicativeIterator(node.getPosition(), it, this.popIt(), ops.splice(0, 1)[0].getValue()); } this.pushIt(it); return true; } return false; } // ComparisonExpr ::= FTContainsExpr ( (ValueComp | GeneralComp | NodeComp) FTContainsExpr )? ComparisonExpr(node: ASTNode): boolean { var exprs = node.find(["FTContainsExpr"]); if(exprs.length > 1) { this.visitChildren(node); var right = this.popIt(); var left = this.popIt(); var comp = node.find(["ValueComp"]).toString(); comp = comp === "" ? node.find(["GeneralComp"]).toString() : comp; comp = comp === "" ? node.find(["NodeComp"]).toString() : comp; this.pushIt(new ComparisonIterator(node.getPosition(), left, right, comp)); return true; } return false; } BlockExpr(node: ASTNode): boolean { var oldLength = this.iterators.length; this.visitChildren(node); if(this.iterators.length === oldLength) { this.pushIt(new ObjectIterator(node.getPosition(), [])); } return true; } //RelativePathExpr ::= PostfixExpr ( ( '/' | '//' | '!' ) StepExpr )* RelativePathExpr(node: ASTNode): boolean { var exprs = node.find(["PostfixExpr"]).concat(node.find(["StepExpr"])); if(exprs.length > 1) { this.visit(exprs[0]); var it = this.popIt(); for(var i = 1; i < exprs.length; i++) { this.visit(exprs[i]); it = new SimpleMapExpr(node.getPosition(), it, this.popIt()); } this.pushIt(it); return true; } return false; } //UnaryExpr ::= ( '-' | '+' )* ValueExpr UnaryExpr(node: ASTNode): boolean { var ops = node.find(["TOKEN"]); if(ops.length > 0) { this.visitChildren(node); this.pushIt(new UnaryExpr(node.getPosition(), ops.map(op => { return op.getValue(); }), this.popIt())); return true; } return false; } ObjectConstructor(node: ASTNode): boolean { var l = this.iterators.length; this.visitChildren(node); this.pushIt(new ObjectIterator(node.getPosition(), this.iterators.splice(l))); return true; } //ArrayConstructor ArrayConstructor(node: ASTNode): boolean { this.visitChildren(node); this.pushIt(new ArrayIterator(node.getPosition(), this.popIt())); return true; } PairConstructor(node: ASTNode): boolean { this.visitChildren(node); var value = this.popIt(); var key; if(node.find(["NCName"])[0]) { key = new ItemIterator(node.getPosition(), new Item(node.find(["NCName"])[0].toString())); } else { key = this.popIt(); } this.pushIt(new PairIterator(node.getPosition(), key, value)); return true; } DecimalLiteral(node: ASTNode): boolean { var item = new Item(parseFloat(node.toString())); this.pushIt(new ItemIterator(node.getPosition(), item)); return true; } DoubleLiteral(node: ASTNode): boolean { var item = new Item(parseFloat(node.toString())); this.pushIt(new ItemIterator(node.getPosition(), item)); return true; } IntegerLiteral(node: ASTNode): boolean { var item = new Item(parseInt(node.toString(), 10)); this.pushIt(new ItemIterator(node.getPosition(), item)); return true; } StringLiteral(node: ASTNode): boolean { var val = node.toString(); val = val.substring(1, val.length - 1); this.pushIt(new ItemIterator(node.getPosition(), new Item(val))); return true; } BooleanLiteral(node: ASTNode): boolean { this.pushIt(new ItemIterator(node.getPosition(), new Item(node.toString() === "true"))); return true; } NullLiteral(node: ASTNode): boolean { this.pushIt(new ItemIterator(node.getPosition(), new Item(null))); return true; } visit(node: ASTNode): Translator { var name = node.getName(); var skip = false; if (typeof this[name] === "function") { skip = this[name](node) === true; } if (!skip) { this.visitChildren(node); } return this; } visitChildren(node: ASTNode): Translator { node.getChildren().forEach(child => { this.visit(child); }); return this; } }
the_stack
require('module-alias/register'); import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import { BigNumber } from 'bignumber.js'; import * as setProtocolUtils from 'set-protocol-utils'; import { Address, Bytes, ExchangeIssuanceParams, KyberTrade, ZeroExSignedFillOrder } from 'set-protocol-utils'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { AddressToAddressWhiteListContract, CoreContract, CTokenExchangeIssuanceModuleContract, RebalancingSetCTokenExchangeIssuanceModuleContract, RebalancingSetTokenContract, RebalancingSetTokenFactoryContract, SetTokenContract, SetTokenFactoryContract, StandardTokenMockContract, TransferProxyContract, VaultContract, WethMockContract, } from '@utils/contracts'; import { Blockchain } from '@utils/blockchain'; import { ether } from '@utils/units'; import { LogPayableExchangeIssue, LogPayableExchangeRedeem, } from '@utils/contract_logs/rebalancingSetExchangeIssuanceModule'; import { expectRevertError } from '@utils/tokenAssertions'; import { getWeb3, getGasUsageInEth } from '@utils/web3Helper'; import { DEFAULT_GAS, DEFAULT_REBALANCING_NATURAL_UNIT, DEFAULT_UNIT_SHARES, DEPLOYED_TOKEN_QUANTITY, ONE_DAY_IN_SECONDS, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, } from '@utils/constants'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { CompoundHelper } from '@utils/helpers/compoundHelper'; import { ExchangeHelper } from '@utils/helpers/exchangeHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { RebalancingHelper } from '@utils/helpers/rebalancingHelper'; import { KyberNetworkHelper } from '@utils/helpers/kyberNetworkHelper'; import { UtilsHelper } from '@utils/helpers/utilsHelper'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const { expect } = chai; const blockchain = new Blockchain(web3); const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils; const setTestUtils = new SetTestUtils(web3); const setUtils = new SetUtils(web3); const { NULL_ADDRESS, ZERO } = SetUtils.CONSTANTS; contract('RebalancingSetExchangeIssuanceModule', accounts => { const [ ownerAccount, kyberReserveOperator, tokenPurchaser, zeroExOrderMaker, whitelist, ] = accounts; let core: CoreContract; let cTokenExchangeIssuanceModule: CTokenExchangeIssuanceModuleContract; let cTokenWhiteList: AddressToAddressWhiteListContract; let transferProxy: TransferProxyContract; let vault: VaultContract; let rebalancingSetTokenFactory: RebalancingSetTokenFactoryContract; let setTokenFactory: SetTokenFactoryContract; let rebalancingSetCTokenExchangeIssuanceModule: RebalancingSetCTokenExchangeIssuanceModuleContract; let cUSDCInstance: StandardTokenMockContract; let usdcInstance: StandardTokenMockContract; let cDAIInstance: StandardTokenMockContract; let daiInstance: StandardTokenMockContract; let weth: WethMockContract; const coreHelper = new CoreHelper(ownerAccount, ownerAccount); const compoundHelper = new CompoundHelper(ownerAccount); const erc20Helper = new ERC20Helper(ownerAccount); const exchangeHelper = new ExchangeHelper(ownerAccount); const rebalancingHelper = new RebalancingHelper( ownerAccount, coreHelper, erc20Helper, blockchain ); const kyberNetworkHelper = new KyberNetworkHelper(); const utilsHelper = new UtilsHelper(ownerAccount); before(async () => { ABIDecoder.addABI(CoreContract.getAbi()); ABIDecoder.addABI(RebalancingSetCTokenExchangeIssuanceModuleContract.getAbi()); transferProxy = await coreHelper.deployTransferProxyAsync(); vault = await coreHelper.deployVaultAsync(); core = await coreHelper.deployCoreAsync(transferProxy, vault); setTokenFactory = await coreHelper.deploySetTokenFactoryAsync(core.address); await coreHelper.setDefaultStateAndAuthorizationsAsync(core, vault, transferProxy, setTokenFactory); rebalancingSetTokenFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync(core.address, whitelist); await coreHelper.addFactoryAsync(core, rebalancingSetTokenFactory); // Set up Compound USDC token usdcInstance = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const cUSDCAddress = await compoundHelper.deployMockCUSDC(usdcInstance.address, ownerAccount); await compoundHelper.enableCToken(cUSDCAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cUSDCAddress, new BigNumber('43084603999')); cUSDCInstance = await erc20Helper.getTokenInstanceAsync(cUSDCAddress); // Set up Compound DAI token daiInstance = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const cDAIAddress = await compoundHelper.deployMockCDAI(daiInstance.address, ownerAccount); await compoundHelper.enableCToken(cDAIAddress); // Set the Borrow Rate await compoundHelper.setBorrowRate(cDAIAddress, new BigNumber('29313252165')); cDAIInstance = await erc20Helper.getTokenInstanceAsync(cDAIAddress); cTokenWhiteList = await utilsHelper.deployAddressToAddressWhiteListAsync( [cUSDCInstance.address, cDAIInstance.address], [usdcInstance.address, daiInstance.address] ); cTokenExchangeIssuanceModule = await coreHelper.deployCTokenExchangeIssuanceModuleAsync( core.address, vault.address, transferProxy.address, cTokenWhiteList.address ); await coreHelper.addModuleAsync(core, cTokenExchangeIssuanceModule.address); weth = await erc20Helper.deployWrappedEtherAsync(ownerAccount); rebalancingSetCTokenExchangeIssuanceModule = await coreHelper.deployRebalancingSetCTokenExchangeIssuanceModuleAsync( core.address, transferProxy.address, cTokenExchangeIssuanceModule.address, weth.address, vault.address, cTokenWhiteList.address, ); await coreHelper.addModuleAsync(core, rebalancingSetCTokenExchangeIssuanceModule.address); await exchangeHelper.deployAndAuthorizeZeroExExchangeWrapper( core, SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, SetTestUtils.ZERO_EX_TOKEN_ADDRESS, transferProxy ); await exchangeHelper.deployAndAuthorizeKyberNetworkWrapper( core, kyberNetworkHelper.kyberNetworkProxy, transferProxy ); }); after(async () => { ABIDecoder.removeABI(CoreContract.getAbi()); ABIDecoder.removeABI(RebalancingSetCTokenExchangeIssuanceModuleContract.getAbi()); }); beforeEach(async () => { await blockchain.saveSnapshotAsync(); await kyberNetworkHelper.setup(); await kyberNetworkHelper.fundReserveWithEth( whitelist, ether(90), ); }); afterEach(async () => { await blockchain.revertAsync(); }); describe('#constructor', async () => { async function subject(): Promise<RebalancingSetCTokenExchangeIssuanceModuleContract> { return await coreHelper.deployRebalancingSetCTokenExchangeIssuanceModuleAsync( core.address, transferProxy.address, cTokenExchangeIssuanceModule.address, weth.address, vault.address, cTokenWhiteList.address, ); } it('should contain the correct address of the transfer proxy', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const proxyAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.transferProxyInstance.callAsync(); expect(proxyAddress).to.equal(transferProxy.address); }); it('should contain the correct address of Core', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const coreAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.coreInstance.callAsync(); expect(coreAddress).to.equal(core.address); }); it('should contain the correct address of Vault', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const vaultAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.vaultInstance.callAsync(); expect(vaultAddress).to.equal(vault.address); }); it('should contain the correct address of Wrapped Ether', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const wethAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.wethInstance.callAsync(); expect(wethAddress).to.equal(weth.address); }); it('should contain the correct address of the cTokenExchangeIssuanceModule', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const cTokenExchangeIssuanceModuleAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.exchangeIssuanceModuleInstance.callAsync(); expect(cTokenExchangeIssuanceModuleAddress).to.equal(cTokenExchangeIssuanceModule.address); }); it('should contain the correct address of the cToken WhiteList', async () => { const rebalancingSetCTokenExchangeIssuanceModuleContract = await subject(); const cTokenWhiteListAddress = await rebalancingSetCTokenExchangeIssuanceModuleContract.cTokenWhiteList.callAsync(); expect(cTokenWhiteListAddress).to.equal(cTokenWhiteList.address); }); }); describe('#issueRebalancingSetWithEther', async () => { let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectExchangeIssuanceParams: ExchangeIssuanceParams; let subjectExchangeOrdersData: Bytes; let subjectKeepChangeInVault: boolean; let subjectEtherValue: string; let subjectCaller: Address; // ---------------------------------------------------------------------- // Component and Rebalancing Set // ---------------------------------------------------------------------- let baseSetComponent: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetComponent3: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetUnderlyingComponent2: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customComponents: Address[]; let customComponentUnits: BigNumber[]; let customBaseSetComponent: StandardTokenMockContract; let customBaseSetComponent2: StandardTokenMockContract; let customBaseSetComponent3: StandardTokenMockContract; let customBaseSetUnderlying: StandardTokenMockContract; let customBaseSetUnderlying2: StandardTokenMockContract; // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- let rebalancingSetIssueQuantity: BigNumber; let baseSetIssueQuantity: BigNumber; let wethRequiredToIssueBaseSet: BigNumber; let customWethRequiredToIssueBaseSet: BigNumber; let customRebalancingSetIssueQuantity: BigNumber; // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- let totalEther: BigNumber; let zeroExSendTokenQuantity: BigNumber; let kyberSendTokenQuantity: BigNumber; let exchangeIssuanceSendTokenQuantity: BigNumber; let customExchangeIssuanceSendTokenQuantity: BigNumber; let customWethUsedInZeroExTrade: BigNumber; let customZeroExSendTokenQuantity: BigNumber; // ---------------------------------------------------------------------- // Exchange Issuance Variables // ---------------------------------------------------------------------- let exchangeIssueSetAddress: Address; let exchangeIssueQuantity: BigNumber; let exchangeIssueSendTokenExchangeIds: BigNumber[]; let exchangeIssueSendTokens: Address[]; let exchangeIssueSendTokenAmounts: BigNumber[]; let exchangeIssueReceiveTokens: Address[]; let exchangeIssueReceiveTokenAmounts: BigNumber[]; let customExchangeIssuanceBaseSetIssueQuantity: BigNumber; // ---------------------------------------------------------------------- // 0x Order Variables // ---------------------------------------------------------------------- let zeroExOrder: ZeroExSignedFillOrder; let zeroExMakerAssetAmount: BigNumber; let zeroExTakerAssetAmount: BigNumber; let customZeroExReceiveTokenAmount: BigNumber; // ---------------------------------------------------------------------- // Kyber Trade Variables // ---------------------------------------------------------------------- let kyberTrade: KyberTrade; let kyberConversionRatePower: BigNumber; beforeEach(async () => { // ---------------------------------------------------------------------- // Component and Rebalancing Set Deployment // ---------------------------------------------------------------------- // Create non-wrapped Ether component tokens baseSetComponent = customBaseSetComponent || cUSDCInstance; baseSetUnderlyingComponent = customBaseSetUnderlying || usdcInstance; baseSetComponent2 = customBaseSetComponent2 || cDAIInstance; baseSetUnderlyingComponent2 = customBaseSetUnderlying2 || daiInstance; baseSetComponent3 = customBaseSetComponent3 || await erc20Helper.deployTokenAsync(ownerAccount); // Create the Set (default is 4 components) const componentAddresses = customComponents || [ baseSetComponent.address, baseSetComponent2.address, baseSetComponent3.address, weth.address, ]; const componentUnits = customComponentUnits || [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; baseSetNaturalUnit = new BigNumber(10 ** 17); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = new BigNumber(10 ** 18); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- baseSetIssueQuantity = new BigNumber(10 ** 18); const impliedRebalancingSetQuantityFromBaseSet = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); rebalancingSetIssueQuantity = customRebalancingSetIssueQuantity || impliedRebalancingSetQuantityFromBaseSet; wethRequiredToIssueBaseSet = customWethRequiredToIssueBaseSet || baseSetIssueQuantity.mul(componentUnits[3]).div(baseSetNaturalUnit); // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- kyberSendTokenQuantity = new BigNumber(10 ** 18); zeroExSendTokenQuantity = customZeroExSendTokenQuantity || new BigNumber(10 ** 18); // 2 0x orders and 1 Kyber order exchangeIssuanceSendTokenQuantity = customExchangeIssuanceSendTokenQuantity || kyberSendTokenQuantity.plus(zeroExSendTokenQuantity).plus(zeroExSendTokenQuantity); totalEther = exchangeIssuanceSendTokenQuantity.plus(wethRequiredToIssueBaseSet); // ---------------------------------------------------------------------- // Exchange Issuance Set up // ---------------------------------------------------------------------- // Generate exchange issue data exchangeIssueSetAddress = baseSetToken.address; exchangeIssueQuantity = customExchangeIssuanceBaseSetIssueQuantity || baseSetIssueQuantity; exchangeIssueSendTokenExchangeIds = [SetUtils.EXCHANGES.ZERO_EX, SetUtils.EXCHANGES.KYBER, SetUtils.EXCHANGES.ZERO_EX]; exchangeIssueSendTokens = [weth.address, weth.address, weth.address]; exchangeIssueSendTokenAmounts = [zeroExSendTokenQuantity, kyberSendTokenQuantity, zeroExSendTokenQuantity]; const zeroExReceiveTokenAmount = componentUnits[0].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); const kyberReceiveTokenAmount = componentUnits[1].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); const nonCTokenZeroExReceiveTokenAmount = componentUnits[2].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); exchangeIssueReceiveTokens = [ componentAddresses[0], componentAddresses[1], componentAddresses[2], ]; exchangeIssueReceiveTokenAmounts = [ zeroExReceiveTokenAmount, kyberReceiveTokenAmount, nonCTokenZeroExReceiveTokenAmount, ]; const exchangeIssuanceParams = { setAddress: exchangeIssueSetAddress, sendTokenExchangeIds: exchangeIssueSendTokenExchangeIds, sendTokens: exchangeIssueSendTokens, sendTokenAmounts: exchangeIssueSendTokenAmounts, quantity: exchangeIssueQuantity, receiveTokens: exchangeIssueReceiveTokens, receiveTokenAmounts: exchangeIssueReceiveTokenAmounts, }; // ---------------------------------------------------------------------- // cToken 0x Order Set up // ---------------------------------------------------------------------- const makerAsset = baseSetUnderlyingComponent.address; const takerAsset = exchangeIssueSendTokens[0]; zeroExMakerAssetAmount = customZeroExReceiveTokenAmount || await compoundHelper.cTokenToUnderlying( exchangeIssueReceiveTokens[0], exchangeIssueReceiveTokenAmounts[0] ); zeroExTakerAssetAmount = customWethUsedInZeroExTrade || exchangeIssueSendTokenAmounts[0]; zeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee zeroExMakerAssetAmount, // makerAssetAmount zeroExTakerAssetAmount, // takerAssetAmount makerAsset, // makerAssetAddress takerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds zeroExTakerAssetAmount, // amount of zeroExOrder to fill ); await erc20Helper.approveTransfersAsync( [baseSetUnderlyingComponent], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent, zeroExOrderMaker, zeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Kyber Trade Set up // ---------------------------------------------------------------------- const maxDestinationQuantity = await compoundHelper.cTokenToUnderlying( exchangeIssueReceiveTokens[1], exchangeIssueReceiveTokenAmounts[1] ); const componentTokenDecimals = (await baseSetUnderlyingComponent2.decimals.callAsync()).toNumber(); const sourceTokenDecimals = (await weth.decimals.callAsync()).toNumber(); kyberConversionRatePower = new BigNumber(10).pow(18 + sourceTokenDecimals - componentTokenDecimals); const minimumConversionRate = maxDestinationQuantity.div(kyberSendTokenQuantity) .mul(kyberConversionRatePower) .round(); kyberTrade = { sourceToken: weth.address, destinationToken: baseSetUnderlyingComponent2.address, sourceTokenQuantity: kyberSendTokenQuantity, minimumConversionRate: minimumConversionRate, maxDestinationQuantity: maxDestinationQuantity, } as KyberTrade; await kyberNetworkHelper.approveToReserve( baseSetUnderlyingComponent2, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, kyberReserveOperator, ); await kyberNetworkHelper.setConversionRates( weth.address, baseSetUnderlyingComponent2.address, kyberSendTokenQuantity, maxDestinationQuantity, ); // Fund Kyber Reserve Operator await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent2, kyberReserveOperator, kyberTrade.maxDestinationQuantity, ownerAccount, ); // ---------------------------------------------------------------------- // Non cToken 0x Order Set up // ---------------------------------------------------------------------- const nonCTokenMakerAsset = exchangeIssueReceiveTokens[2]; const nonCTokenTakerAsset = exchangeIssueSendTokens[2]; const nonCTokenZeroExMakerAssetAmount = customZeroExReceiveTokenAmount || exchangeIssueReceiveTokenAmounts[2]; const nonCTokenZeroExTakerAssetAmount = exchangeIssueSendTokenAmounts[2]; const nonCTokenZeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee nonCTokenZeroExMakerAssetAmount, // makerAssetAmount nonCTokenZeroExTakerAssetAmount, // takerAssetAmount nonCTokenMakerAsset, // makerAssetAddress nonCTokenTakerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds nonCTokenZeroExTakerAssetAmount, // amount of zeroExOrder to fill ); await erc20Helper.approveTransfersAsync( [baseSetComponent3], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( baseSetComponent3, zeroExOrderMaker, nonCTokenZeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Subject Parameter Definitions // ---------------------------------------------------------------------- subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = rebalancingSetIssueQuantity; subjectExchangeIssuanceParams = exchangeIssuanceParams; subjectExchangeOrdersData = setUtils.generateSerializedOrders([zeroExOrder, kyberTrade, nonCTokenZeroExOrder]); subjectKeepChangeInVault = false; subjectCaller = tokenPurchaser; subjectEtherValue = totalEther.toString(); }); afterEach(async () => { customExchangeIssuanceSendTokenQuantity = undefined; customExchangeIssuanceBaseSetIssueQuantity = undefined; customComponents = undefined; customComponentUnits = undefined; }); async function subject(): Promise<string> { return rebalancingSetCTokenExchangeIssuanceModule.issueRebalancingSetWithEther.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectExchangeIssuanceParams, subjectExchangeOrdersData, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS, value: subjectEtherValue }, ); } it('issues the rebalancing Set to the caller', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(rebalancingSetIssueQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('reduces the callers Ether balance by the expected amount', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .sub(exchangeIssuanceSendTokenQuantity) .sub(wethRequiredToIssueBaseSet) .sub(totalGasInEth); const currentEthBalance = await web3.eth.getBalance(subjectCaller); expect(expectedEthBalance).to.bignumber.equal(currentEthBalance); }); it('emits correct LogPayableExchangeIssue event', async () => { const expectedReturnedEth = new BigNumber(0); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeIssue( subjectRebalancingSetAddress, subjectCaller, weth.address, subjectRebalancingSetQuantity, expectedReturnedEth, rebalancingSetCTokenExchangeIssuanceModule.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when more exchangeIssuance send token is sent than required by trades', async () => { const excessEth = new BigNumber(10 ** 10); describe('', async () => { before(async () => { customExchangeIssuanceSendTokenQuantity = new BigNumber(3).mul(10 ** 18).plus(excessEth); }); it('refunds the caller the appropriate amount of eth', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .sub(exchangeIssuanceSendTokenQuantity) .add(excessEth) .sub(wethRequiredToIssueBaseSet) .sub(totalGasInEth); const currentEthBalance = await web3.eth.getBalance(subjectCaller); expect(currentEthBalance).to.bignumber.equal(expectedEthBalance); }); }); describe('', async () => { before(async () => { customExchangeIssuanceSendTokenQuantity = new BigNumber(3).mul(10 ** 18).plus(excessEth); }); it('emits log with correct refund quantity', async () => { const txHash = await subject(); const expectedEthBalance = excessEth; const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeIssue( subjectRebalancingSetAddress, subjectCaller, weth.address, subjectRebalancingSetQuantity, expectedEthBalance, rebalancingSetCTokenExchangeIssuanceModule.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); }); describe('when zeroEx sendToken amount is greater than amount needed to execute 0x trade', async () => { before(async () => { customWethUsedInZeroExTrade = new BigNumber(10 ** 18); customZeroExSendTokenQuantity = new BigNumber(10 ** 18).times(3); }); it('refunds the unused Ether from the 0x trade', async () => { const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .sub(customWethUsedInZeroExTrade) .sub(kyberSendTokenQuantity) .sub(zeroExSendTokenQuantity) .sub(wethRequiredToIssueBaseSet) .sub(totalGasInEth); const currentEthBalance = await web3.eth.getBalance(subjectCaller); expect(currentEthBalance).to.bignumber.equal(expectedEthBalance); }); }); describe('when the base Set quantity minted is greater than required for Rebalancing Set issuance', async () => { const excessBaseSetIssued = new BigNumber(10 ** 17); describe('and keepChangeInVault is false', async () => { before(async () => { customRebalancingSetIssueQuantity = DEFAULT_REBALANCING_NATURAL_UNIT; customExchangeIssuanceBaseSetIssueQuantity = new BigNumber(10 ** 18).plus(excessBaseSetIssued); }); it('refunds the caller the excess base Set', async () => { await subject(); const ownerBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(excessBaseSetIssued); }); }); describe('and keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); before(async () => { customRebalancingSetIssueQuantity = DEFAULT_REBALANCING_NATURAL_UNIT; customExchangeIssuanceBaseSetIssueQuantity = new BigNumber(10 ** 18).plus(excessBaseSetIssued); }); it('sends to the Vault the excess base Set with ownership attributed to the caller', async () => { await subject(); const ownerBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); expect(ownerBalance).to.bignumber.equal(excessBaseSetIssued); }); }); }); describe('when the amount of receive token from trade exceeds receive token amount', async () => { before(async () => { // Amount exceeds any calculable quantity of component token customZeroExReceiveTokenAmount = ether(11); }); it('returns the user the leftover underlying token amount', async () => { const previousBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); await subject(); const underlyingMakerAssetAmount = await compoundHelper.cTokenToUnderlying( baseSetComponent.address, exchangeIssueReceiveTokenAmounts[0] ); const expectedOwnerBalance = previousBalance .add(customZeroExReceiveTokenAmount) .sub(underlyingMakerAssetAmount); const ownerBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(expectedOwnerBalance); }); it('returns the user the leftover base component token amount', async () => { const previousBalance = await baseSetComponent3.balanceOf.callAsync(subjectCaller); await subject(); const expectedOwnerBalance = previousBalance .add(customZeroExReceiveTokenAmount) .sub(exchangeIssueReceiveTokenAmounts[2]); const ownerBalance = await baseSetComponent3.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(expectedOwnerBalance); }); }); describe('when the wrapper does not have enough allowance to transfer weth', async () => { beforeEach(async () => { await weth.changeAllowanceProxy.sendTransactionAsync( rebalancingSetCTokenExchangeIssuanceModule.address, transferProxy.address, new BigNumber(0), { gas: DEFAULT_GAS } ); }); it('resets the transferProxy allowance', async () => { const wethAllowance = await weth.allowance.callAsync( rebalancingSetCTokenExchangeIssuanceModule.address, transferProxy.address ); expect(wethAllowance).to.bignumber.equal(ZERO); await subject(); const expectedWethAllowance = UNLIMITED_ALLOWANCE_IN_BASE_UNITS; const newWethAllowance = await weth.allowance.callAsync( rebalancingSetCTokenExchangeIssuanceModule.address, transferProxy.address ); expect(newWethAllowance).to.bignumber.equal(expectedWethAllowance); }); }); describe('when a send token address is not wrapped ether', async () => { beforeEach(async () => { const baseSetComponent = await erc20Helper.deployTokenAsync(zeroExOrderMaker); subjectExchangeIssuanceParams.sendTokens = [baseSetComponent.address, weth.address]; subjectExchangeIssuanceParams.sendTokenAmounts = [new BigNumber(1), new BigNumber(1)]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the exchangeIssuanceParams setAddress is not the Rebalancing Sets currentSet', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.setAddress = weth.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the eth sent is insufficient', async () => { before(async () => { customWethRequiredToIssueBaseSet = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is zero', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = DEFAULT_REBALANCING_NATURAL_UNIT.mul(1.5); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetAddress is not tracked by Core', async () => { beforeEach(async () => { const proposalPeriod = ONE_DAY_IN_SECONDS; const rebalanceInterval = ONE_DAY_IN_SECONDS; const unTrackedSetToken = await rebalancingHelper.deployRebalancingSetTokenAsync( rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, DEFAULT_UNIT_SHARES, DEFAULT_REBALANCING_NATURAL_UNIT, proposalPeriod, rebalanceInterval, whitelist, ); subjectRebalancingSetAddress = unTrackedSetToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the Set is only made of three components', async () => { before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount, 18); customComponents = [customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address]; customComponentUnits = [new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18)]; customWethRequiredToIssueBaseSet = new BigNumber(0); }); it('issues the rebalancing Set to the caller', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(rebalancingSetIssueQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); }); }); describe('#issueRebalancingSetWithERC20', async () => { let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectPaymentTokenAddress: Address; let subjectPaymentTokenQuantity: BigNumber; let subjectExchangeIssuanceParams: ExchangeIssuanceParams; let subjectExchangeOrdersData: Bytes; let subjectKeepChangeInVault: boolean; let subjectCaller: Address; // ---------------------------------------------------------------------- // Component and Rebalancing Set // ---------------------------------------------------------------------- let baseSetComponent: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetComponent3: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetUnderlyingComponent2: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customComponents: Address[]; let customComponentUnits: BigNumber[]; let customBaseSetComponent: StandardTokenMockContract; let customBaseSetComponent2: StandardTokenMockContract; let customBaseSetComponent3: StandardTokenMockContract; let customBaseSetUnderlying: StandardTokenMockContract; let customBaseSetUnderlying2: StandardTokenMockContract; // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- let rebalancingSetIssueQuantity: BigNumber; let baseSetIssueQuantity: BigNumber; let sendTokenRequiredToIssueBaseSet: BigNumber; let customSendTokenRequiredToIssueBaseSet: BigNumber; let customRebalancingSetIssueQuantity: BigNumber; // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- let totalSendToken: BigNumber; let zeroExSendTokenQuantity: BigNumber; let kyberSendTokenQuantity: BigNumber; let exchangeIssuanceSendTokenQuantity: BigNumber; let sendToken: StandardTokenMockContract; let customExchangeIssuanceSendTokenQuantity: BigNumber; let customSendTokenUsedInZeroExTrade: BigNumber; let customZeroExSendTokenQuantity: BigNumber; let customSendToken: StandardTokenMockContract; // ---------------------------------------------------------------------- // Exchange Issuance Variables // ---------------------------------------------------------------------- let exchangeIssueSetAddress: Address; let exchangeIssueQuantity: BigNumber; let exchangeIssueSendTokenExchangeIds: BigNumber[]; let exchangeIssueSendTokens: Address[]; let exchangeIssueSendTokenAmounts: BigNumber[]; let exchangeIssueReceiveTokens: Address[]; let exchangeIssueReceiveTokenAmounts: BigNumber[]; let customExchangeIssuanceBaseSetIssueQuantity: BigNumber; // ---------------------------------------------------------------------- // 0x Order Variables // ---------------------------------------------------------------------- let zeroExOrder: ZeroExSignedFillOrder; let zeroExMakerAssetAmount: BigNumber; let zeroExTakerAssetAmount: BigNumber; let customZeroExReceiveTokenAmount: BigNumber; // ---------------------------------------------------------------------- // Kyber Trade Variables // ---------------------------------------------------------------------- let kyberTrade: KyberTrade; let kyberConversionRatePower: BigNumber; beforeEach(async () => { // ---------------------------------------------------------------------- // Component and Rebalancing Set Deployment // ---------------------------------------------------------------------- // Create non-wrapped Ether component tokens baseSetComponent = customBaseSetComponent || cUSDCInstance; baseSetUnderlyingComponent = customBaseSetUnderlying || usdcInstance; baseSetComponent2 = customBaseSetComponent2 || cDAIInstance; baseSetUnderlyingComponent2 = customBaseSetUnderlying2 || daiInstance; baseSetComponent3 = customBaseSetComponent3 || await erc20Helper.deployTokenAsync(ownerAccount); // Create cToken underlying send token sendToken = customSendToken || await erc20Helper.deployTokenAsync(tokenPurchaser, 18); const nonExchangedComponentAddress = await compoundHelper.deployMockCDAI(sendToken.address, ownerAccount); await compoundHelper.enableCToken(nonExchangedComponentAddress); await compoundHelper.setBorrowRate(nonExchangedComponentAddress, new BigNumber('29313252165')); const sendTokenComponent = await erc20Helper.getTokenInstanceAsync(nonExchangedComponentAddress); await cTokenWhiteList.addPair.sendTransactionAsync( sendTokenComponent.address, sendToken.address, { gas: DEFAULT_GAS } ); // Create the Set (default is 4 components) const componentAddresses = customComponents || [ baseSetComponent.address, baseSetComponent2.address, baseSetComponent3.address, sendTokenComponent.address, ]; const componentUnits = customComponentUnits || [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; baseSetNaturalUnit = new BigNumber(10 ** 17); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = new BigNumber(10 ** 18); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- baseSetIssueQuantity = new BigNumber(10 ** 18); const impliedRebalancingSetQuantityFromBaseSet = baseSetIssueQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); rebalancingSetIssueQuantity = customRebalancingSetIssueQuantity || impliedRebalancingSetQuantityFromBaseSet; sendTokenRequiredToIssueBaseSet = customSendTokenRequiredToIssueBaseSet || baseSetIssueQuantity .mul(await compoundHelper.cTokenToUnderlying(componentAddresses[3], componentUnits[3])) .div(baseSetNaturalUnit); // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- kyberSendTokenQuantity = new BigNumber(10 ** 18); zeroExSendTokenQuantity = customZeroExSendTokenQuantity || new BigNumber(10 ** 18); // 2 0x order 1 Kyber order exchangeIssuanceSendTokenQuantity = customExchangeIssuanceSendTokenQuantity || kyberSendTokenQuantity.plus(zeroExSendTokenQuantity).plus(zeroExSendTokenQuantity); totalSendToken = exchangeIssuanceSendTokenQuantity.plus(sendTokenRequiredToIssueBaseSet); await erc20Helper.approveTransfersAsync( [sendToken], transferProxy.address, tokenPurchaser ); // ---------------------------------------------------------------------- // Exchange Issuance Set up // ---------------------------------------------------------------------- // Generate exchange issue data exchangeIssueSetAddress = baseSetToken.address; exchangeIssueQuantity = customExchangeIssuanceBaseSetIssueQuantity || baseSetIssueQuantity; exchangeIssueSendTokenExchangeIds = [SetUtils.EXCHANGES.ZERO_EX, SetUtils.EXCHANGES.KYBER, SetUtils.EXCHANGES.ZERO_EX]; exchangeIssueSendTokens = [sendToken.address, sendToken.address, sendToken.address]; exchangeIssueSendTokenAmounts = [zeroExSendTokenQuantity, kyberSendTokenQuantity, zeroExSendTokenQuantity]; const zeroExReceiveTokenAmount = componentUnits[0].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); const kyberReceiveTokenAmount = componentUnits[1].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); const nonCTokenZeroExReceiveTokenAmount = componentUnits[2].mul(exchangeIssueQuantity).div(baseSetNaturalUnit); exchangeIssueReceiveTokens = [ componentAddresses[0], componentAddresses[1], componentAddresses[2], ]; exchangeIssueReceiveTokenAmounts = [ zeroExReceiveTokenAmount, kyberReceiveTokenAmount, nonCTokenZeroExReceiveTokenAmount, ]; const exchangeIssuanceParams = { setAddress: exchangeIssueSetAddress, sendTokenExchangeIds: exchangeIssueSendTokenExchangeIds, sendTokens: exchangeIssueSendTokens, sendTokenAmounts: exchangeIssueSendTokenAmounts, quantity: exchangeIssueQuantity, receiveTokens: exchangeIssueReceiveTokens, receiveTokenAmounts: exchangeIssueReceiveTokenAmounts, }; // ---------------------------------------------------------------------- // cToken 0x Order Set up // ---------------------------------------------------------------------- const makerAsset = baseSetUnderlyingComponent.address; const takerAsset = exchangeIssueSendTokens[0]; zeroExMakerAssetAmount = customZeroExReceiveTokenAmount || await compoundHelper.cTokenToUnderlying( exchangeIssueReceiveTokens[0], exchangeIssueReceiveTokenAmounts[0] ); zeroExTakerAssetAmount = customSendTokenUsedInZeroExTrade || exchangeIssueSendTokenAmounts[0]; zeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee zeroExMakerAssetAmount, // makerAssetAmount zeroExTakerAssetAmount, // takerAssetAmount makerAsset, // makerAssetAddress takerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds zeroExTakerAssetAmount, // amount of zeroExOrder to fill ); await erc20Helper.approveTransfersAsync( [baseSetUnderlyingComponent], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent, zeroExOrderMaker, zeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Kyber Trade Set up // ---------------------------------------------------------------------- const maxDestinationQuantity = await compoundHelper.cTokenToUnderlying( exchangeIssueReceiveTokens[1], exchangeIssueReceiveTokenAmounts[1] ); const componentTokenDecimals = (await baseSetUnderlyingComponent2.decimals.callAsync()).toNumber(); const sourceTokenDecimals = (await sendToken.decimals.callAsync()).toNumber(); kyberConversionRatePower = new BigNumber(10).pow(18 + sourceTokenDecimals - componentTokenDecimals); const minimumConversionRate = maxDestinationQuantity.div(kyberSendTokenQuantity) .mul(kyberConversionRatePower) .round(); kyberTrade = { sourceToken: sendToken.address, destinationToken: baseSetUnderlyingComponent2.address, sourceTokenQuantity: kyberSendTokenQuantity, minimumConversionRate: minimumConversionRate, maxDestinationQuantity: maxDestinationQuantity, } as KyberTrade; await kyberNetworkHelper.approveToReserve( baseSetUnderlyingComponent2, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, kyberReserveOperator, ); await kyberNetworkHelper.setConversionRates( sendToken.address, baseSetUnderlyingComponent2.address, kyberSendTokenQuantity, maxDestinationQuantity, ); // Fund Kyber Reserve Operator await erc20Helper.transferTokenAsync( baseSetUnderlyingComponent2, kyberReserveOperator, kyberTrade.maxDestinationQuantity, ownerAccount, ); // ---------------------------------------------------------------------- // Non cToken 0x Order Set up // ---------------------------------------------------------------------- const nonCTokenMakerAsset = exchangeIssueReceiveTokens[2]; const nonCTokenTakerAsset = exchangeIssueSendTokens[2]; const nonCTokenZeroExMakerAssetAmount = customZeroExReceiveTokenAmount || exchangeIssueReceiveTokenAmounts[2]; const nonCTokenZeroExTakerAssetAmount = exchangeIssueSendTokenAmounts[2]; const nonCTokenZeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee nonCTokenZeroExMakerAssetAmount, // makerAssetAmount nonCTokenZeroExTakerAssetAmount, // takerAssetAmount nonCTokenMakerAsset, // makerAssetAddress nonCTokenTakerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds nonCTokenZeroExTakerAssetAmount, // amount of zeroExOrder to fill ); await erc20Helper.approveTransfersAsync( [baseSetComponent3], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( baseSetComponent3, zeroExOrderMaker, nonCTokenZeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Subject Parameter Definitions // ---------------------------------------------------------------------- subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = rebalancingSetIssueQuantity; subjectPaymentTokenAddress = sendToken.address; subjectPaymentTokenQuantity = totalSendToken; subjectExchangeIssuanceParams = exchangeIssuanceParams; subjectExchangeOrdersData = setUtils.generateSerializedOrders([zeroExOrder, kyberTrade, nonCTokenZeroExOrder]); subjectKeepChangeInVault = false; subjectCaller = tokenPurchaser; }); afterEach(async () => { customExchangeIssuanceSendTokenQuantity = undefined; customExchangeIssuanceBaseSetIssueQuantity = undefined; customComponents = undefined; customComponentUnits = undefined; customSendTokenRequiredToIssueBaseSet = undefined; customSendToken = undefined; customRebalancingSetIssueQuantity = undefined; }); async function subject(): Promise<string> { return rebalancingSetCTokenExchangeIssuanceModule.issueRebalancingSetWithERC20.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectPaymentTokenAddress, subjectPaymentTokenQuantity, subjectExchangeIssuanceParams, subjectExchangeOrdersData, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS }, ); } it('issues the rebalancing Set to the caller', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(rebalancingSetIssueQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('uses an expected amount of send token', async () => { const previousSendTokenBalance: BigNumber = await sendToken.balanceOf.callAsync(subjectCaller); await subject(); const expectedSendTokenBalance = previousSendTokenBalance.sub(subjectPaymentTokenQuantity); const currentSendTokenBalance = await sendToken.balanceOf.callAsync(subjectCaller); expect(expectedSendTokenBalance).to.bignumber.equal(currentSendTokenBalance); }); it('emits correct LogPayableExchangeIssue event', async () => { const expectedReturnedToken = new BigNumber(0); const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeIssue( subjectRebalancingSetAddress, subjectCaller, sendToken.address, subjectRebalancingSetQuantity, expectedReturnedToken, rebalancingSetCTokenExchangeIssuanceModule.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when more exchangeIssuance send token is sent than required by trades', async () => { const excessSendToken = new BigNumber(10 ** 10); describe('', async () => { before(async () => { customExchangeIssuanceSendTokenQuantity = new BigNumber(3).mul(10 ** 18).plus(excessSendToken); }); it('refunds the caller the appropriate amount of send token', async () => { const previousSendTokenBalance: BigNumber = await sendToken.balanceOf.callAsync(subjectCaller); await subject(); const expectedSentTokenBalance = previousSendTokenBalance .sub(subjectPaymentTokenQuantity) .add(excessSendToken); const currentSendTokenBalance: BigNumber = await sendToken.balanceOf.callAsync(subjectCaller); expect(currentSendTokenBalance).to.bignumber.equal(expectedSentTokenBalance); }); }); describe('', async () => { before(async () => { customExchangeIssuanceSendTokenQuantity = new BigNumber(3).mul(10 ** 18).plus(excessSendToken); }); it('emits log with correct refund quantity', async () => { const txHash = await subject(); const expectedSendTokenBalance = excessSendToken; const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeIssue( subjectRebalancingSetAddress, subjectCaller, sendToken.address, subjectRebalancingSetQuantity, expectedSendTokenBalance, rebalancingSetCTokenExchangeIssuanceModule.address, ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); }); }); describe('when zeroEx sendToken amount is greater than amount needed to execute 0x trade', async () => { before(async () => { customSendTokenUsedInZeroExTrade = new BigNumber(10 ** 18); customZeroExSendTokenQuantity = new BigNumber(10 ** 18).times(3); }); it('refunds the unused send token from the 0x trade', async () => { const previousSendTokenBalance: BigNumber = await sendToken.balanceOf.callAsync(subjectCaller); await subject(); const expectedEthBalance = previousSendTokenBalance .sub(customSendTokenUsedInZeroExTrade) .sub(kyberSendTokenQuantity) .sub(zeroExSendTokenQuantity) .sub(sendTokenRequiredToIssueBaseSet); const currentEthBalance = await sendToken.balanceOf.callAsync(subjectCaller); expect(currentEthBalance).to.bignumber.equal(expectedEthBalance); }); }); describe('when the base Set quantity minted is greater than required for Rebalancing Set issuance', async () => { const excessBaseSetIssued = new BigNumber(10 ** 17); describe('and keepChangeInVault is false', async () => { before(async () => { customRebalancingSetIssueQuantity = DEFAULT_REBALANCING_NATURAL_UNIT; customExchangeIssuanceBaseSetIssueQuantity = new BigNumber(10 ** 18).plus(excessBaseSetIssued); }); it('refunds the caller the excess base Set', async () => { await subject(); const ownerBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(excessBaseSetIssued); }); }); describe('and keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); before(async () => { customRebalancingSetIssueQuantity = DEFAULT_REBALANCING_NATURAL_UNIT; customExchangeIssuanceBaseSetIssueQuantity = new BigNumber(10 ** 18).plus(excessBaseSetIssued); }); it('sends to the Vault the excess base Set with ownership attributed to the caller', async () => { await subject(); const ownerBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); expect(ownerBalance).to.bignumber.equal(excessBaseSetIssued); }); }); }); describe('when the amount of receive token from trade exceeds receive token amount', async () => { before(async () => { // Amount exceeds any calculable quantity of component token customZeroExReceiveTokenAmount = ether(11); }); it('returns the user the leftover underlying token amount', async () => { const previousBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); await subject(); const underlyingMakerAssetAmount = await compoundHelper.cTokenToUnderlying( baseSetComponent.address, exchangeIssueReceiveTokenAmounts[0] ); const expectedOwnerBalance = previousBalance .add(customZeroExReceiveTokenAmount) .sub(underlyingMakerAssetAmount); const ownerBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(expectedOwnerBalance); }); it('returns the user the leftover base component token amount', async () => { const previousBalance = await baseSetComponent3.balanceOf.callAsync(subjectCaller); await subject(); const expectedOwnerBalance = previousBalance .add(customZeroExReceiveTokenAmount) .sub(exchangeIssueReceiveTokenAmounts[2]); const ownerBalance = await baseSetComponent3.balanceOf.callAsync(subjectCaller); expect(ownerBalance).to.bignumber.equal(expectedOwnerBalance); }); }); describe('when a send token address is not the payment token', async () => { beforeEach(async () => { const baseSetComponent = await erc20Helper.deployTokenAsync(zeroExOrderMaker); subjectExchangeIssuanceParams.sendTokens = [baseSetComponent.address, sendToken.address]; subjectExchangeIssuanceParams.sendTokenAmounts = [new BigNumber(1), new BigNumber(1)]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the exchangeIssuanceParams setAddress is not the Rebalancing Sets currentSet', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.setAddress = sendToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the send token is insufficient', async () => { before(async () => { customSendTokenRequiredToIssueBaseSet = new BigNumber(0); customExchangeIssuanceSendTokenQuantity = new BigNumber(0); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is zero', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is not a multiple of the natural unit', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = DEFAULT_REBALANCING_NATURAL_UNIT.mul(1.5); }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetAddress is not tracked by Core', async () => { beforeEach(async () => { const proposalPeriod = ONE_DAY_IN_SECONDS; const rebalanceInterval = ONE_DAY_IN_SECONDS; const unTrackedSetToken = await rebalancingHelper.deployRebalancingSetTokenAsync( rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, DEFAULT_UNIT_SHARES, DEFAULT_REBALANCING_NATURAL_UNIT, proposalPeriod, rebalanceInterval, whitelist, ); subjectRebalancingSetAddress = unTrackedSetToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the Set is only made of three components', async () => { before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customSendToken = await erc20Helper.deployTokenAsync( tokenPurchaser, 18, ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount, 18); customComponents = [ customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address, ]; customComponentUnits = [new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18)]; customSendTokenRequiredToIssueBaseSet = new BigNumber(0); }); it('issues the rebalancing Set to the caller', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(rebalancingSetIssueQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); }); }); describe('#redeemRebalancingSetIntoEther', async () => { let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectExchangeIssuanceParams: ExchangeIssuanceParams; let subjectExchangeOrdersData: Bytes; let subjectKeepChangeInVault: boolean; let subjectCaller: Address; // ---------------------------------------------------------------------- // Component and Rebalancing Set // ---------------------------------------------------------------------- let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetUnderlyingComponent2: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetComponent3: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customExchangeRedeemQuantity: BigNumber; let customComponentAddresses: Address[]; let customComponentUnits: BigNumber[]; let customBaseSetComponent: StandardTokenMockContract; let customBaseSetComponent2: StandardTokenMockContract; let customBaseSetComponent3: StandardTokenMockContract; let customBaseSetUnderlying: StandardTokenMockContract; let customBaseSetUnderlying2: StandardTokenMockContract; // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- let rebalancingSetRedeemQuantity: BigNumber; let baseSetRedeemQuantity: BigNumber; let customWethRequiredToIssueBaseSet: BigNumber; // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- let wethRequiredToIssueBaseSet: BigNumber; let zeroExReceiveTokenQuantity: BigNumber; let kyberReceiveTokenQuantity: BigNumber; let nonCTokenZeroExReceiveTokenQuantity: BigNumber; let exchangeIssuanceReceiveTokenQuantity: BigNumber; let zeroExSendTokenQuantity: BigNumber; let kyberSendTokenQuantity: BigNumber; let totalEtherToReceive: BigNumber; let customZeroExSendTokenQuantity: BigNumber; // ---------------------------------------------------------------------- // Exchange Issuance Variables // ---------------------------------------------------------------------- let exchangeRedeemSetAddress: Address; let exchangeRedeemQuantity: BigNumber; let exchangeRedeemSendTokenExchangeIds: BigNumber[]; let exchangeRedeemSendTokens: Address[]; let exchangeRedeemSendTokenAmounts: BigNumber[]; let exchangeRedeemReceiveTokens: Address[]; let exchangeRedeemReceiveTokenAmounts: BigNumber[]; // ---------------------------------------------------------------------- // 0x Order Variables // ---------------------------------------------------------------------- let zeroExOrder: ZeroExSignedFillOrder; let zeroExMakerAssetAmount: BigNumber; let zeroExTakerAssetAmount: BigNumber; let customZeroExReceiveTokenAmount: BigNumber; // ---------------------------------------------------------------------- // Kyber Trade Variables // ---------------------------------------------------------------------- let kyberTrade: KyberTrade; let kyberConversionRatePower: BigNumber; beforeEach(async () => { // ---------------------------------------------------------------------- // Component and Rebalancing Set Deployment // ---------------------------------------------------------------------- // Create non-wrapped Ether component tokens baseSetComponent = customBaseSetComponent || cUSDCInstance; baseSetUnderlyingComponent = customBaseSetUnderlying || usdcInstance; baseSetComponent2 = customBaseSetComponent2 || cDAIInstance; baseSetUnderlyingComponent2 = customBaseSetUnderlying2 || daiInstance; baseSetComponent3 = customBaseSetComponent3 || await erc20Helper.deployTokenAsync(ownerAccount); // Create the Set (default is 4 components) const componentAddresses = customComponentAddresses || [ baseSetComponent.address, baseSetComponent2.address, baseSetComponent3.address, weth.address, ]; const componentUnits = customComponentUnits || [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; baseSetNaturalUnit = new BigNumber(10 ** 17); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = new BigNumber(10 ** 18); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- baseSetRedeemQuantity = new BigNumber(10 ** 18); rebalancingSetRedeemQuantity = baseSetRedeemQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); wethRequiredToIssueBaseSet = customWethRequiredToIssueBaseSet || componentUnits[3].mul(baseSetRedeemQuantity).div(baseSetNaturalUnit); // ---------------------------------------------------------------------- // Payment / Send and Receive Token Details // ---------------------------------------------------------------------- kyberReceiveTokenQuantity = ether(1); zeroExReceiveTokenQuantity = customZeroExSendTokenQuantity || ether(1); nonCTokenZeroExReceiveTokenQuantity = ether(1); exchangeIssuanceReceiveTokenQuantity = zeroExReceiveTokenQuantity.plus(nonCTokenZeroExReceiveTokenQuantity).plus(kyberReceiveTokenQuantity); totalEtherToReceive = exchangeIssuanceReceiveTokenQuantity.plus(wethRequiredToIssueBaseSet); // ---------------------------------------------------------------------- // Exchange Issuance Set up // ---------------------------------------------------------------------- // Generate exchangeRedeem data exchangeRedeemSetAddress = baseSetToken.address; exchangeRedeemQuantity = customExchangeRedeemQuantity || baseSetRedeemQuantity; exchangeRedeemSendTokenExchangeIds = [SetUtils.EXCHANGES.ZERO_EX, SetUtils.EXCHANGES.KYBER, SetUtils.EXCHANGES.ZERO_EX]; exchangeRedeemSendTokens = [componentAddresses[0], componentAddresses[1], componentAddresses[2]]; zeroExSendTokenQuantity = customZeroExSendTokenQuantity || componentUnits[0].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); kyberSendTokenQuantity = componentUnits[1].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); const nonCTokenZeroExSendTokenQuantity = componentUnits[2].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); exchangeRedeemSendTokenAmounts = [zeroExSendTokenQuantity, kyberSendTokenQuantity, nonCTokenZeroExSendTokenQuantity]; exchangeRedeemReceiveTokens = [weth.address]; exchangeRedeemReceiveTokenAmounts = [exchangeIssuanceReceiveTokenQuantity]; const exchangeIssuanceParams = { setAddress: exchangeRedeemSetAddress, sendTokenExchangeIds: exchangeRedeemSendTokenExchangeIds, sendTokens: exchangeRedeemSendTokens, sendTokenAmounts: exchangeRedeemSendTokenAmounts, quantity: exchangeRedeemQuantity, receiveTokens: exchangeRedeemReceiveTokens, receiveTokenAmounts: exchangeRedeemReceiveTokenAmounts, }; // ---------------------------------------------------------------------- // 0x Order Set up // ---------------------------------------------------------------------- const makerAsset = exchangeRedeemReceiveTokens[0]; const takerAsset = baseSetUnderlyingComponent.address; zeroExMakerAssetAmount = customZeroExReceiveTokenAmount || zeroExReceiveTokenQuantity; // Taker is transacting in cToken underlying zeroExTakerAssetAmount = await compoundHelper.cTokenToUnderlying( exchangeRedeemSendTokens[0], exchangeRedeemSendTokenAmounts[0] ); zeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee zeroExMakerAssetAmount, // makerAssetAmount zeroExTakerAssetAmount, // takerAssetAmount makerAsset, // makerAssetAddress takerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds zeroExTakerAssetAmount, // amount of zeroExOrder to fill ); // Approve weth to the transfer proxy await weth.approve.sendTransactionAsync( SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, { from: zeroExOrderMaker, gas: DEFAULT_GAS } ); // Deposit weth await weth.deposit.sendTransactionAsync( { from: zeroExOrderMaker, value: zeroExMakerAssetAmount.toString(), gas: DEFAULT_GAS } ); // ---------------------------------------------------------------------- // Kyber Trade Set up // ---------------------------------------------------------------------- const maxDestinationQuantity = kyberReceiveTokenQuantity; const sourceTokenQuantity = await compoundHelper.cTokenToUnderlying(exchangeRedeemSendTokens[1], exchangeRedeemSendTokenAmounts[1]); const destinationTokenDecimals = (await weth.decimals.callAsync()).toNumber(); const sourceTokenDecimals = (await baseSetUnderlyingComponent2.decimals.callAsync()).toNumber(); kyberConversionRatePower = new BigNumber(10).pow(18 + sourceTokenDecimals - destinationTokenDecimals); const minimumConversionRate = maxDestinationQuantity.div(sourceTokenQuantity) .mul(kyberConversionRatePower) .round(); kyberTrade = { sourceToken: baseSetUnderlyingComponent2.address, destinationToken: weth.address, sourceTokenQuantity: sourceTokenQuantity, minimumConversionRate: minimumConversionRate, maxDestinationQuantity: maxDestinationQuantity, } as KyberTrade; await weth.approve.sendTransactionAsync( kyberNetworkHelper.kyberReserve, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, { from: kyberReserveOperator, gas: DEFAULT_GAS } ); // Deposit weth await weth.deposit.sendTransactionAsync( { from: kyberReserveOperator, value: maxDestinationQuantity.toString(), gas: DEFAULT_GAS } ); await kyberNetworkHelper.setConversionRates( baseSetUnderlyingComponent2.address, weth.address, sourceTokenQuantity, maxDestinationQuantity, ); // ---------------------------------------------------------------------- // Non cToken 0x Order Set up // ---------------------------------------------------------------------- const nonCTokenMakerAsset = exchangeRedeemReceiveTokens[0]; const nonCTokenTakerAsset = baseSetComponent3.address; const nonCTokenZeroExMakerAssetAmount = nonCTokenZeroExReceiveTokenQuantity; // Taker is transacting in cToken underlying const nonCTokenZeroExTakerAssetAmount = exchangeRedeemSendTokenAmounts[2]; const nonZeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee nonCTokenZeroExMakerAssetAmount, // makerAssetAmount nonCTokenZeroExTakerAssetAmount, // takerAssetAmount nonCTokenMakerAsset, // makerAssetAddress nonCTokenTakerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds nonCTokenZeroExTakerAssetAmount, // amount of zeroExOrder to fill ); // Deposit weth for nonCToken 0x order await weth.deposit.sendTransactionAsync( { from: zeroExOrderMaker, value: nonCTokenZeroExMakerAssetAmount.toString(), gas: DEFAULT_GAS } ); // ---------------------------------------------------------------------- // Rebalancing Set Issuance // ---------------------------------------------------------------------- // Mint cTokens from underlying for the send tokens await erc20Helper.approveTransfersAsync([baseSetUnderlyingComponent], baseSetComponent.address); await erc20Helper.approveTransfersAsync([baseSetUnderlyingComponent2], baseSetComponent2.address); await compoundHelper.mintCToken( baseSetComponent.address, DEPLOYED_TOKEN_QUANTITY ); await compoundHelper.mintCToken( baseSetComponent2.address, DEPLOYED_TOKEN_QUANTITY ); // Approve base components to transfer proxy await erc20Helper.approveTransfersAsync( [baseSetComponent, baseSetComponent2, baseSetComponent3], transferProxy.address, ownerAccount ); if (wethRequiredToIssueBaseSet.gt(0)) { // Approve Weth to the transferProxy await weth.approve.sendTransactionAsync( transferProxy.address, wethRequiredToIssueBaseSet, { gas: DEFAULT_GAS } ); // Generate wrapped Ether for the caller await weth.deposit.sendTransactionAsync( { value: wethRequiredToIssueBaseSet.toString(), gas: DEFAULT_GAS } ); } // Issue the Base Set to the vault under ownerAccount await core.issueInVault.sendTransactionAsync( baseSetToken.address, baseSetRedeemQuantity, { gas: DEFAULT_GAS } ); // Issue the RB Set under ownerAccount await core.issue.sendTransactionAsync( rebalancingSetToken.address, rebalancingSetRedeemQuantity, { gas: DEFAULT_GAS } ); // Transfer RB Set to tokenPurchaser await erc20Helper.transferTokenAsync( rebalancingSetToken, tokenPurchaser, rebalancingSetRedeemQuantity ); // ---------------------------------------------------------------------- // Subject Parameter Definitions // ---------------------------------------------------------------------- subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = rebalancingSetRedeemQuantity; subjectExchangeIssuanceParams = exchangeIssuanceParams; subjectExchangeOrdersData = setUtils.generateSerializedOrders([zeroExOrder, kyberTrade, nonZeroExOrder]); subjectKeepChangeInVault = false; subjectCaller = tokenPurchaser; }); afterEach(async () => { customExchangeRedeemQuantity = undefined; }); async function subject(): Promise<string> { return rebalancingSetCTokenExchangeIssuanceModule.redeemRebalancingSetIntoEther.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectExchangeIssuanceParams, subjectExchangeOrdersData, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS }, ); } it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('should increment the users eth balance by the correct quantity', async () => { const previousEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .add(totalEtherToReceive) .sub(totalGasInEth); const currentEthBalance = await web3.eth.getBalance(subjectCaller); expect(currentEthBalance).to.bignumber.equal(expectedEthBalance); }); it('increases the 0x makers underlying send token quantity properly', async () => { const previousTakerTokenBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(zeroExOrderMaker); const underlyingSendTokenAmount = await compoundHelper.cTokenToUnderlying( exchangeRedeemSendTokens[0], exchangeRedeemSendTokenAmounts[0] ); const expectedTakerTokenBalance = previousTakerTokenBalance.add(underlyingSendTokenAmount); await subject(); const currentTakerTokenBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(zeroExOrderMaker); expect(expectedTakerTokenBalance).to.bignumber.equal(currentTakerTokenBalance); }); it('increases the 0x makers non cToken send token quantity properly', async () => { const previousTakerTokenBalance = await baseSetComponent3.balanceOf.callAsync(zeroExOrderMaker); const underlyingSendTokenAmount = exchangeRedeemSendTokenAmounts[2]; const expectedTakerTokenBalance = previousTakerTokenBalance.add(underlyingSendTokenAmount); await subject(); const currentTakerTokenBalance = await baseSetComponent3.balanceOf.callAsync(zeroExOrderMaker); expect(expectedTakerTokenBalance).to.bignumber.equal(currentTakerTokenBalance); }); it('emits correct LogPayableExchangeRedeem event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeRedeem( subjectRebalancingSetAddress, subjectCaller, weth.address, subjectRebalancingSetQuantity, totalEtherToReceive, rebalancingSetCTokenExchangeIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the Set has a component that has not been exchanged', async () => { let nonExchangedNonWethComponent: StandardTokenMockContract; before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount); nonExchangedNonWethComponent = await erc20Helper.deployTokenAsync(ownerAccount); customComponentAddresses = [ customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address, weth.address, nonExchangedNonWethComponent.address, ]; customComponentUnits = [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; await erc20Helper.approveTransfersAsync( [nonExchangedNonWethComponent], transferProxy.address, ownerAccount ); }); after(async () => { customBaseSetComponent = undefined; customBaseSetComponent2 = undefined; customBaseSetComponent3 = undefined; customBaseSetUnderlying = undefined; customBaseSetUnderlying2 = undefined; customComponentAddresses = undefined; customComponentUnits = undefined; }); it('should send the extra asset to the caller', async () => { const previousReturnedAssetBalance = await nonExchangedNonWethComponent.balanceOf.callAsync(subjectCaller); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add( customComponentUnits[3].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit) ); await subject(); const currentReturnedAssetBalance = await nonExchangedNonWethComponent.balanceOf.callAsync(subjectCaller); expect(expectedReturnedAssetBalance).to.bignumber.equal(currentReturnedAssetBalance); }); }); describe('when the 0x order receiveToken quantity is greater than specified', async () => { before(async () => { customZeroExReceiveTokenAmount = ether(2); }); after(async () => { customZeroExReceiveTokenAmount = undefined; }); it('should increment the users eth balance by the correct quantity', async () => { const previousEthBalance = new BigNumber(await web3.eth.getBalance(subjectCaller)); const txHash = await subject(); const totalGasInEth = await getGasUsageInEth(txHash); const expectedEthBalance = previousEthBalance .add(totalEtherToReceive) .add(customZeroExReceiveTokenAmount) .sub(zeroExReceiveTokenQuantity) .sub(totalGasInEth); const currentEthBalance = await web3.eth.getBalance(subjectCaller); expect(currentEthBalance).to.bignumber.equal(expectedEthBalance); }); }); describe('when the quantity of underlying send token is less than the components redeemed', async () => { let halfBaseComponentQuantity: BigNumber; before(async () => { const componentUnit = new BigNumber(10 ** 18); const naturalUnit = new BigNumber(10 ** 17); const redeemQuantity = new BigNumber(10 ** 18); halfBaseComponentQuantity = componentUnit.mul(redeemQuantity).div(naturalUnit).div(2); customZeroExSendTokenQuantity = halfBaseComponentQuantity; }); after(async () => { customZeroExSendTokenQuantity = undefined; }); it('should send the unsold components to the caller', async () => { const previousReturnedAssetBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); const halfBaseUnderlyingQuantity = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, halfBaseComponentQuantity); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(halfBaseUnderlyingQuantity); await subject(); const currentReturnedAssetBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(expectedReturnedAssetBalance).to.bignumber.equal(currentReturnedAssetBalance); }); }); describe('when the implied base Set quantity is greater than the issuance params base Set quantity', async () => { let excessBaseSetQuantity: BigNumber; beforeEach(async () => { const excessNonExchangedWethQuantity = wethRequiredToIssueBaseSet.mul(2); excessBaseSetQuantity = exchangeRedeemQuantity.mul(2); // Generate wrapped Ether for the caller await weth.deposit.sendTransactionAsync( { from: ownerAccount, value: excessNonExchangedWethQuantity.toString(), gas: DEFAULT_GAS } ); // Approve Weth to the transferProxy await weth.approve.sendTransactionAsync( transferProxy.address, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, { from: ownerAccount, gas: DEFAULT_GAS } ); // Issue the Base Set to the vault await core.issueInVault.sendTransactionAsync( baseSetToken.address, excessBaseSetQuantity, { from: ownerAccount, gas: DEFAULT_GAS } ); // Issue the Rebalancing Set const excessRebalancingSetQuantity = excessBaseSetQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await core.issue.sendTransactionAsync( rebalancingSetToken.address, excessRebalancingSetQuantity, { from: ownerAccount, gas: DEFAULT_GAS } ); // Transfer RB Set to tokenPurchaser await erc20Helper.transferTokenAsync( rebalancingSetToken, tokenPurchaser, excessRebalancingSetQuantity ); subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.add(excessRebalancingSetQuantity); }); it('should return the excess base Set to the caller', async () => { const previousReturnedAssetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(excessBaseSetQuantity); await subject(); const currentReturnedAssetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentReturnedAssetBalance).to.bignumber.equal(expectedReturnedAssetBalance); }); describe('and keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); it('refunds the user the appropriate amount of base Set to the Vault', async () => { const previousReturnedAssetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(excessBaseSetQuantity); await subject(); const currentReturnedAssetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); expect(currentReturnedAssetBalance).to.bignumber.equal(expectedReturnedAssetBalance); }); }); }); describe('when the receive tokens length is greater than 1 and there are duplicates', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.receiveTokens = [weth.address, weth.address]; subjectExchangeIssuanceParams.receiveTokenAmounts = [new BigNumber(1), new BigNumber(1)]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the receive token is not wrapped ether', async () => { beforeEach(async () => { const baseSetComponent = await erc20Helper.deployTokenAsync(zeroExOrderMaker); subjectExchangeIssuanceParams.receiveTokens = [baseSetComponent.address]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the base Set of the rebalancing Set is not the issuance params Set', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.setAddress = weth.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is zero', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetAddress is not tracked by Core', async () => { beforeEach(async () => { const proposalPeriod = ONE_DAY_IN_SECONDS; const rebalanceInterval = ONE_DAY_IN_SECONDS; const unTrackedSetToken = await rebalancingHelper.deployRebalancingSetTokenAsync( rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, DEFAULT_UNIT_SHARES, DEFAULT_REBALANCING_NATURAL_UNIT, proposalPeriod, rebalanceInterval, whitelist, ); subjectRebalancingSetAddress = unTrackedSetToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the Set is only made of three components', async () => { before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount, 18); customComponentAddresses = [customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address]; customComponentUnits = [new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18)]; customWethRequiredToIssueBaseSet = new BigNumber(0); }); it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); }); }); describe('#redeemRebalancingSetIntoERC20', async () => { let subjectRebalancingSetAddress: Address; let subjectRebalancingSetQuantity: BigNumber; let subjectReceiveTokenAddress: Address; let subjectExchangeIssuanceParams: ExchangeIssuanceParams; let subjectExchangeOrdersData: Bytes; let subjectKeepChangeInVault: boolean; let subjectCaller: Address; // ---------------------------------------------------------------------- // Component and Rebalancing Set // ---------------------------------------------------------------------- let baseSetComponent: StandardTokenMockContract; let baseSetUnderlyingComponent: StandardTokenMockContract; let baseSetUnderlyingComponent2: StandardTokenMockContract; let baseSetComponent2: StandardTokenMockContract; let baseSetComponent3: StandardTokenMockContract; let baseSetToken: SetTokenContract; let baseSetNaturalUnit: BigNumber; let rebalancingSetToken: RebalancingSetTokenContract; let rebalancingUnitShares: BigNumber; let customExchangeRedeemQuantity: BigNumber; let customComponentAddresses: Address[]; let customComponentUnits: BigNumber[]; let customBaseSetComponent: StandardTokenMockContract; let customBaseSetComponent2: StandardTokenMockContract; let customBaseSetComponent3: StandardTokenMockContract; let customBaseSetUnderlying: StandardTokenMockContract; let customBaseSetUnderlying2: StandardTokenMockContract; // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- let rebalancingSetRedeemQuantity: BigNumber; let baseSetRedeemQuantity: BigNumber; let customReceiveTokenRequiredToIssueBaseSet: BigNumber; // ---------------------------------------------------------------------- // Payment / Send Token Details // ---------------------------------------------------------------------- let receiveTokenRequiredToIssueBaseSet: BigNumber; let zeroExReceiveTokenQuantity: BigNumber; let kyberReceiveTokenQuantity: BigNumber; let nonCTokenZeroExReceiveTokenQuantity: BigNumber; let exchangeIssuanceReceiveTokenQuantity: BigNumber; let zeroExSendTokenQuantity: BigNumber; let kyberSendTokenQuantity: BigNumber; let totalReceiveAmount: BigNumber; let receiveToken: StandardTokenMockContract; let receiveTokenComponent: StandardTokenMockContract; let customZeroExSendTokenQuantity: BigNumber; // ---------------------------------------------------------------------- // Exchange Issuance Variables // ---------------------------------------------------------------------- let exchangeRedeemSetAddress: Address; let exchangeRedeemQuantity: BigNumber; let exchangeRedeemSendTokenExchangeIds: BigNumber[]; let exchangeRedeemSendTokens: Address[]; let exchangeRedeemSendTokenAmounts: BigNumber[]; let exchangeRedeemReceiveTokens: Address[]; let exchangeRedeemReceiveTokenAmounts: BigNumber[]; // ---------------------------------------------------------------------- // 0x Order Variables // ---------------------------------------------------------------------- let zeroExOrder: ZeroExSignedFillOrder; let zeroExMakerAssetAmount: BigNumber; let zeroExTakerAssetAmount: BigNumber; let customZeroExReceiveTokenAmount: BigNumber; // ---------------------------------------------------------------------- // Kyber Trade Variables // ---------------------------------------------------------------------- let kyberTrade: KyberTrade; let kyberConversionRatePower: BigNumber; beforeEach(async () => { // ---------------------------------------------------------------------- // Component and Rebalancing Set Deployment // ---------------------------------------------------------------------- // Create non-wrapped Ether component tokens baseSetComponent = customBaseSetComponent || cUSDCInstance; baseSetUnderlyingComponent = customBaseSetUnderlying || usdcInstance; baseSetComponent2 = customBaseSetComponent2 || cDAIInstance; baseSetUnderlyingComponent2 = customBaseSetUnderlying2 || daiInstance; baseSetComponent3 = customBaseSetComponent3 || await erc20Helper.deployTokenAsync(ownerAccount); receiveToken = await erc20Helper.deployTokenAsync(ownerAccount, 18); const nonExchangedComponentAddress = await compoundHelper.deployMockCDAI(receiveToken.address, ownerAccount); await compoundHelper.enableCToken(nonExchangedComponentAddress); await compoundHelper.setBorrowRate(nonExchangedComponentAddress, new BigNumber('29313252165')); receiveTokenComponent = await erc20Helper.getTokenInstanceAsync(nonExchangedComponentAddress); await cTokenWhiteList.addPair.sendTransactionAsync( receiveTokenComponent.address, receiveToken.address, { gas: DEFAULT_GAS } ); // Create the Set (default is 4 components) const componentAddresses = customComponentAddresses || [ baseSetComponent.address, baseSetComponent2.address, baseSetComponent3.address, receiveTokenComponent.address, ]; const componentUnits = customComponentUnits || [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; baseSetNaturalUnit = new BigNumber(10 ** 17); baseSetToken = await coreHelper.createSetTokenAsync( core, setTokenFactory.address, componentAddresses, componentUnits, baseSetNaturalUnit, ); // Create the Rebalancing Set rebalancingUnitShares = new BigNumber(10 ** 18); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync( core, rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, ONE_DAY_IN_SECONDS, rebalancingUnitShares, ); // ---------------------------------------------------------------------- // Issuance Details // ---------------------------------------------------------------------- baseSetRedeemQuantity = new BigNumber(10 ** 18); rebalancingSetRedeemQuantity = baseSetRedeemQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); const receiveTokenBaseComponent = customReceiveTokenRequiredToIssueBaseSet || componentUnits[3].mul(baseSetRedeemQuantity).div(baseSetNaturalUnit); receiveTokenRequiredToIssueBaseSet = await compoundHelper.cTokenToUnderlying( receiveTokenComponent.address, receiveTokenBaseComponent ); // ---------------------------------------------------------------------- // Payment / Send and Receive Token Details // ---------------------------------------------------------------------- kyberReceiveTokenQuantity = ether(1); zeroExReceiveTokenQuantity = customZeroExSendTokenQuantity || ether(1); nonCTokenZeroExReceiveTokenQuantity = ether(1); exchangeIssuanceReceiveTokenQuantity = zeroExReceiveTokenQuantity.plus(nonCTokenZeroExReceiveTokenQuantity).plus(kyberReceiveTokenQuantity); totalReceiveAmount = exchangeIssuanceReceiveTokenQuantity.plus(receiveTokenRequiredToIssueBaseSet); // ---------------------------------------------------------------------- // Exchange Issuance Set up // ---------------------------------------------------------------------- // Generate exchangeRedeem data exchangeRedeemSetAddress = baseSetToken.address; exchangeRedeemQuantity = customExchangeRedeemQuantity || baseSetRedeemQuantity; exchangeRedeemSendTokenExchangeIds = [SetUtils.EXCHANGES.ZERO_EX, SetUtils.EXCHANGES.KYBER, SetUtils.EXCHANGES.ZERO_EX]; exchangeRedeemSendTokens = [componentAddresses[0], componentAddresses[1], componentAddresses[2]]; zeroExSendTokenQuantity = customZeroExSendTokenQuantity || componentUnits[0].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); kyberSendTokenQuantity = componentUnits[1].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); const nonCTokenZeroExSendTokenQuantity = componentUnits[2].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit); exchangeRedeemSendTokenAmounts = [zeroExSendTokenQuantity, kyberSendTokenQuantity, nonCTokenZeroExSendTokenQuantity]; exchangeRedeemReceiveTokens = [receiveToken.address]; exchangeRedeemReceiveTokenAmounts = [exchangeIssuanceReceiveTokenQuantity]; const exchangeIssuanceParams = { setAddress: exchangeRedeemSetAddress, sendTokenExchangeIds: exchangeRedeemSendTokenExchangeIds, sendTokens: exchangeRedeemSendTokens, sendTokenAmounts: exchangeRedeemSendTokenAmounts, quantity: exchangeRedeemQuantity, receiveTokens: exchangeRedeemReceiveTokens, receiveTokenAmounts: exchangeRedeemReceiveTokenAmounts, }; // ---------------------------------------------------------------------- // 0x Order Set up // ---------------------------------------------------------------------- const makerAsset = exchangeRedeemReceiveTokens[0]; const takerAsset = baseSetUnderlyingComponent.address; zeroExMakerAssetAmount = customZeroExReceiveTokenAmount || zeroExReceiveTokenQuantity; // Taker is transacting in cToken underlying zeroExTakerAssetAmount = await compoundHelper.cTokenToUnderlying( exchangeRedeemSendTokens[0], exchangeRedeemSendTokenAmounts[0] ); zeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee zeroExMakerAssetAmount, // makerAssetAmount zeroExTakerAssetAmount, // takerAssetAmount makerAsset, // makerAssetAddress takerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds zeroExTakerAssetAmount, // amount of zeroExOrder to fill ); // Approve weth to the transfer proxy await erc20Helper.approveTransfersAsync( [receiveToken], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( receiveToken, zeroExOrderMaker, zeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Kyber Trade Set up // ---------------------------------------------------------------------- const maxDestinationQuantity = kyberReceiveTokenQuantity; const sourceTokenQuantity = await compoundHelper.cTokenToUnderlying(exchangeRedeemSendTokens[1], exchangeRedeemSendTokenAmounts[1]); const destinationTokenDecimals = (await weth.decimals.callAsync()).toNumber(); const sourceTokenDecimals = (await baseSetUnderlyingComponent2.decimals.callAsync()).toNumber(); kyberConversionRatePower = new BigNumber(10).pow(18 + sourceTokenDecimals - destinationTokenDecimals); const minimumConversionRate = maxDestinationQuantity.div(sourceTokenQuantity) .mul(kyberConversionRatePower) .round(); kyberTrade = { sourceToken: baseSetUnderlyingComponent2.address, destinationToken: receiveToken.address, sourceTokenQuantity: sourceTokenQuantity, minimumConversionRate: minimumConversionRate, maxDestinationQuantity: maxDestinationQuantity, } as KyberTrade; await kyberNetworkHelper.approveToReserve( receiveToken, UNLIMITED_ALLOWANCE_IN_BASE_UNITS, kyberReserveOperator, ); await kyberNetworkHelper.setConversionRates( baseSetUnderlyingComponent2.address, receiveToken.address, sourceTokenQuantity, maxDestinationQuantity, ); // Fund Kyber Reserve Operator await erc20Helper.transferTokenAsync( receiveToken, kyberReserveOperator, kyberTrade.maxDestinationQuantity, ownerAccount, ); // ---------------------------------------------------------------------- // Non cToken 0x Order Set up // ---------------------------------------------------------------------- const nonCTokenMakerAsset = exchangeRedeemReceiveTokens[0]; const nonCTokenTakerAsset = baseSetComponent3.address; const nonCTokenZeroExMakerAssetAmount = nonCTokenZeroExReceiveTokenQuantity; // Taker is transacting in cToken underlying const nonCTokenZeroExTakerAssetAmount = exchangeRedeemSendTokenAmounts[2]; const nonZeroExOrder = await setUtils.generateZeroExSignedFillOrder( NULL_ADDRESS, // senderAddress zeroExOrderMaker, // makerAddress NULL_ADDRESS, // takerAddress ZERO, // makerFee ZERO, // takerFee nonCTokenZeroExMakerAssetAmount, // makerAssetAmount nonCTokenZeroExTakerAssetAmount, // takerAssetAmount nonCTokenMakerAsset, // makerAssetAddress nonCTokenTakerAsset, // takerAssetAddress SetUtils.generateSalt(), // salt SetTestUtils.ZERO_EX_EXCHANGE_ADDRESS, // exchangeAddress NULL_ADDRESS, // feeRecipientAddress SetTestUtils.generateTimestamp(10000), // expirationTimeSeconds nonCTokenZeroExTakerAssetAmount, // amount of zeroExOrder to fill ); // Approve receive token await erc20Helper.approveTransfersAsync( [receiveToken], SetTestUtils.ZERO_EX_ERC20_PROXY_ADDRESS, zeroExOrderMaker ); // Fund zero Ex Order Maker await erc20Helper.transferTokenAsync( receiveToken, zeroExOrderMaker, nonCTokenZeroExMakerAssetAmount, ownerAccount, ); // ---------------------------------------------------------------------- // Rebalancing Set Issuance // ---------------------------------------------------------------------- // Mint cTokens from underlying for the send tokens await erc20Helper.approveTransfersAsync([baseSetUnderlyingComponent], baseSetComponent.address); await erc20Helper.approveTransfersAsync([baseSetUnderlyingComponent2], baseSetComponent2.address); await erc20Helper.approveTransfersAsync([receiveToken], receiveTokenComponent.address); await compoundHelper.mintCToken( baseSetComponent.address, DEPLOYED_TOKEN_QUANTITY ); await compoundHelper.mintCToken( baseSetComponent2.address, DEPLOYED_TOKEN_QUANTITY ); await compoundHelper.mintCToken( receiveTokenComponent.address, receiveTokenRequiredToIssueBaseSet ); // Approve base components to transfer proxy await erc20Helper.approveTransfersAsync( [baseSetComponent, baseSetComponent2, baseSetComponent3, receiveTokenComponent], transferProxy.address, ownerAccount ); // Issue the Base Set to the vault under ownerAccount await core.issueInVault.sendTransactionAsync( baseSetToken.address, baseSetRedeemQuantity, { gas: DEFAULT_GAS } ); // Issue the RB Set under ownerAccount await core.issue.sendTransactionAsync( rebalancingSetToken.address, rebalancingSetRedeemQuantity, { gas: DEFAULT_GAS } ); // Transfer RB Set to tokenPurchaser await erc20Helper.transferTokenAsync( rebalancingSetToken, tokenPurchaser, rebalancingSetRedeemQuantity ); // ---------------------------------------------------------------------- // Subject Parameter Definitions // ---------------------------------------------------------------------- subjectRebalancingSetAddress = rebalancingSetToken.address; subjectRebalancingSetQuantity = rebalancingSetRedeemQuantity; subjectReceiveTokenAddress = receiveToken.address; subjectExchangeIssuanceParams = exchangeIssuanceParams; subjectExchangeOrdersData = setUtils.generateSerializedOrders([zeroExOrder, kyberTrade, nonZeroExOrder]); subjectKeepChangeInVault = false; subjectCaller = tokenPurchaser; }); afterEach(async () => { customExchangeRedeemQuantity = undefined; }); async function subject(): Promise<string> { return rebalancingSetCTokenExchangeIssuanceModule.redeemRebalancingSetIntoERC20.sendTransactionAsync( subjectRebalancingSetAddress, subjectRebalancingSetQuantity, subjectReceiveTokenAddress, subjectExchangeIssuanceParams, subjectExchangeOrdersData, subjectKeepChangeInVault, { from: subjectCaller, gas: DEFAULT_GAS }, ); } it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); it('should increment the users receive balance by the correct quantity', async () => { const previousReceiveBalance = await receiveToken.balanceOf.callAsync(subjectCaller); await subject(); const expectedReceiveBalance = previousReceiveBalance.add(totalReceiveAmount); const currentReceiveBalance = await receiveToken.balanceOf.callAsync(subjectCaller); expect(currentReceiveBalance).to.bignumber.equal(expectedReceiveBalance); }); it('increases the 0x makers send token quantity properly', async () => { const previousTakerTokenBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(zeroExOrderMaker); const underlyingReceiveTokenAmount = await compoundHelper.cTokenToUnderlying( exchangeRedeemSendTokens[0], exchangeRedeemSendTokenAmounts[0] ); const expectedTakerTokenBalance = previousTakerTokenBalance.add(underlyingReceiveTokenAmount); await subject(); const currentTakerTokenBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(zeroExOrderMaker); expect(expectedTakerTokenBalance).to.bignumber.equal(currentTakerTokenBalance); }); it('emits correct LogPayableExchangeRedeem event', async () => { const txHash = await subject(); const formattedLogs = await setTestUtils.getLogsFromTxHash(txHash); const expectedLogs = LogPayableExchangeRedeem( subjectRebalancingSetAddress, subjectCaller, receiveToken.address, subjectRebalancingSetQuantity, totalReceiveAmount, rebalancingSetCTokenExchangeIssuanceModule.address ); await SetTestUtils.assertLogEquivalence(formattedLogs, expectedLogs); }); describe('when the Set has a component that has not been exchanged', async () => { let nonExchangedNonWethComponent: StandardTokenMockContract; before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount); nonExchangedNonWethComponent = await erc20Helper.deployTokenAsync(ownerAccount); customComponentAddresses = [ customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address, nonExchangedNonWethComponent.address, ]; customComponentUnits = [ new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18), ]; await erc20Helper.approveTransfersAsync( [nonExchangedNonWethComponent], transferProxy.address, ownerAccount ); }); after(async () => { customBaseSetComponent = undefined; customBaseSetComponent2 = undefined; customBaseSetComponent3 = undefined; customBaseSetUnderlying = undefined; customBaseSetUnderlying2 = undefined; customComponentAddresses = undefined; customComponentUnits = undefined; }); it('should send the extra asset to the caller', async () => { const previousReturnedAssetBalance = await nonExchangedNonWethComponent.balanceOf.callAsync(subjectCaller); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add( customComponentUnits[3].mul(exchangeRedeemQuantity).div(baseSetNaturalUnit) ); await subject(); const currentReturnedAssetBalance = await nonExchangedNonWethComponent.balanceOf.callAsync(subjectCaller); expect(expectedReturnedAssetBalance).to.bignumber.equal(currentReturnedAssetBalance); }); }); describe('when the 0x order receiveToken quantity is greater than specified', async () => { before(async () => { customZeroExReceiveTokenAmount = ether(2); }); after(async () => { customZeroExReceiveTokenAmount = undefined; }); it('should increment the users eth balance by the correct quantity', async () => { const previousReceiveBalance = await receiveToken.balanceOf.callAsync(subjectCaller); await subject(); const expectedReceiveBalance = previousReceiveBalance .add(totalReceiveAmount) .add(customZeroExReceiveTokenAmount) .sub(zeroExReceiveTokenQuantity); const currentReceiveBalance = await receiveToken.balanceOf.callAsync(subjectCaller); expect(currentReceiveBalance).to.bignumber.equal(expectedReceiveBalance); }); }); describe('when the quantity of underlying send token is less than the components redeemed', async () => { let halfBaseComponentQuantity: BigNumber; before(async () => { const componentUnit = new BigNumber(10 ** 18); const naturalUnit = new BigNumber(10 ** 17); const redeemQuantity = new BigNumber(10 ** 18); halfBaseComponentQuantity = componentUnit.mul(redeemQuantity).div(naturalUnit).div(2); customZeroExSendTokenQuantity = halfBaseComponentQuantity; }); after(async () => { customZeroExSendTokenQuantity = undefined; }); it('should send the unsold components to the caller', async () => { const previousReturnedAssetBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); const halfBaseUnderlyingQuantity = await compoundHelper.cTokenToUnderlying(baseSetComponent.address, halfBaseComponentQuantity); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(halfBaseUnderlyingQuantity); await subject(); const currentReturnedAssetBalance = await baseSetUnderlyingComponent.balanceOf.callAsync(subjectCaller); expect(expectedReturnedAssetBalance).to.bignumber.equal(currentReturnedAssetBalance); }); }); describe('when the implied base Set quantity is greater than the issuance params base Set quantity', async () => { let excessBaseSetQuantity: BigNumber; beforeEach(async () => { const excessNonExchangedQuantity = receiveTokenRequiredToIssueBaseSet.mul(2); excessBaseSetQuantity = exchangeRedeemQuantity.mul(2); // Approve and mint cToken from receive token underlying await compoundHelper.mintCToken( receiveTokenComponent.address, excessNonExchangedQuantity, ); // Issue the Base Set to the vault await core.issueInVault.sendTransactionAsync( baseSetToken.address, excessBaseSetQuantity, { from: ownerAccount, gas: DEFAULT_GAS } ); // Issue the Rebalancing Set const excessRebalancingSetQuantity = excessBaseSetQuantity .mul(DEFAULT_REBALANCING_NATURAL_UNIT) .div(rebalancingUnitShares); await core.issue.sendTransactionAsync( rebalancingSetToken.address, excessRebalancingSetQuantity, { from: ownerAccount, gas: DEFAULT_GAS } ); // Transfer RB Set to caller await erc20Helper.transferTokenAsync( rebalancingSetToken, tokenPurchaser, excessRebalancingSetQuantity, ownerAccount, ); subjectRebalancingSetQuantity = subjectRebalancingSetQuantity.add(excessRebalancingSetQuantity); }); it('should return the excess base Set to the caller', async () => { const previousReturnedAssetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(excessBaseSetQuantity); await subject(); const currentReturnedAssetBalance = await baseSetToken.balanceOf.callAsync(subjectCaller); expect(currentReturnedAssetBalance).to.bignumber.equal(expectedReturnedAssetBalance); }); describe('and keepChangeInVault is true', async () => { beforeEach(async () => { subjectKeepChangeInVault = true; }); it('refunds the user the appropriate amount of base Set to the Vault', async () => { const previousReturnedAssetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); const expectedReturnedAssetBalance = previousReturnedAssetBalance.add(excessBaseSetQuantity); await subject(); const currentReturnedAssetBalance = await vault.getOwnerBalance.callAsync( baseSetToken.address, subjectCaller ); expect(currentReturnedAssetBalance).to.bignumber.equal(expectedReturnedAssetBalance); }); }); }); describe('when the receive tokens length is greater than 1 and there are duplicates', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.receiveTokens = [receiveToken.address, receiveToken.address]; subjectExchangeIssuanceParams.receiveTokenAmounts = [new BigNumber(1), new BigNumber(1)]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the receive token is not correct', async () => { beforeEach(async () => { const baseSetComponent = await erc20Helper.deployTokenAsync(zeroExOrderMaker); subjectExchangeIssuanceParams.receiveTokens = [baseSetComponent.address]; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the base Set of the rebalancing Set is not the issuance params Set', async () => { beforeEach(async () => { subjectExchangeIssuanceParams.setAddress = receiveToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetQuantity is zero', async () => { beforeEach(async () => { subjectRebalancingSetQuantity = ZERO; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the rebalancingSetAddress is not tracked by Core', async () => { beforeEach(async () => { const proposalPeriod = ONE_DAY_IN_SECONDS; const rebalanceInterval = ONE_DAY_IN_SECONDS; const unTrackedSetToken = await rebalancingHelper.deployRebalancingSetTokenAsync( rebalancingSetTokenFactory.address, ownerAccount, baseSetToken.address, DEFAULT_UNIT_SHARES, DEFAULT_REBALANCING_NATURAL_UNIT, proposalPeriod, rebalanceInterval, whitelist, ); subjectRebalancingSetAddress = unTrackedSetToken.address; }); it('should revert', async () => { await expectRevertError(subject()); }); }); describe('when the Set is only made of three components', async () => { before(async () => { customBaseSetUnderlying = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress = await compoundHelper.deployMockCUSDC(customBaseSetUnderlying.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress); customBaseSetComponent = await erc20Helper.getTokenInstanceAsync(customComponentAddress); customBaseSetUnderlying2 = await erc20Helper.deployTokenAsync( ownerAccount, 18, ); const customComponentAddress2 = await compoundHelper.deployMockCDAI(customBaseSetUnderlying2.address, ownerAccount); await compoundHelper.enableCToken(customComponentAddress2); customBaseSetComponent2 = await erc20Helper.getTokenInstanceAsync(customComponentAddress2); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent.address, customBaseSetUnderlying.address, { gas: DEFAULT_GAS } ); await cTokenWhiteList.addPair.sendTransactionAsync( customBaseSetComponent2.address, customBaseSetUnderlying2.address, { gas: DEFAULT_GAS } ); customBaseSetComponent3 = await erc20Helper.deployTokenAsync(ownerAccount, 18); customComponentAddresses = [customBaseSetComponent.address, customBaseSetComponent2.address, customBaseSetComponent3.address]; customComponentUnits = [new BigNumber(10 ** 18), new BigNumber(10 ** 18), new BigNumber(10 ** 18)]; customReceiveTokenRequiredToIssueBaseSet = new BigNumber(0); }); it('redeems the rebalancing Set', async () => { const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity); await subject(); const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller); expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance); }); }); }); });
the_stack
import { ChildProcess, spawn } from "child_process"; import { AgentInitializeResult, BaseAgentOptions, DidChangeApiVersionCompatibilityNotification, DidChangeApiVersionCompatibilityNotificationType, DidChangeConnectionStatusNotification, DidChangeConnectionStatusNotificationType, DidChangeDataNotification, DidChangeDataNotificationType, DidChangeDocumentMarkersNotification, DidChangeDocumentMarkersNotificationType, DidChangeServerUrlNotification, DidChangeServerUrlNotificationType, DidChangeVersionCompatibilityNotification, DidChangeVersionCompatibilityNotificationType, DidEncounterMaintenanceModeNotification, DidEncounterMaintenanceModeNotificationType, DidFailLoginNotificationType, DidLoginNotification, DidLoginNotificationType, DidStartLoginNotificationType, RestartRequiredNotificationType, TelemetryRequest, TelemetryRequestType, AgentOpenUrlRequestType, AgentOpenUrlRequest } from "@codestream/protocols/agent"; import { CompositeDisposable, Disposable } from "atom"; import { Convert, LanguageClientConnection } from "atom-languageclient"; import { EnvironmentConfig } from "env-utils"; import { FileLogger } from "logger"; import { asAbsolutePath, Debug, Echo, Editor, getAgentSource, getPluginVersion } from "utils"; import { createMessageConnection, IPCMessageReader, IPCMessageWriter, MessageConnection, NotificationType, RequestType } from "vscode-jsonrpc"; import { ConfigurationParams, DidChangeWorkspaceFoldersNotification, DidChangeWorkspaceFoldersParams, MessageType, RegistrationParams, WorkspaceFoldersChangeEvent } from "vscode-languageserver-protocol"; import { Container } from "workspace/container"; import { shell } from "electron"; import { LSP_CLIENT_CAPABILITIES } from "./lsp-client-capabilities"; /* Create a reverse mapping of the MessageType enum so that given an integer, we know the type. The result will be something like { 0: 'log', 1: 'error' } */ const reverseMessageType = function() { const result = {}; Object.entries(MessageType).forEach(([type, int]) => { result[int] = type.toLowerCase(); }); return result; }; const ReversedMessageType = reverseMessageType(); type RequestOrNotificationType<P, R> = RequestType<P, R, any, any> | NotificationType<P, R>; export type RequestOf<RT> = RT extends RequestOrNotificationType<infer RQ, any> ? RQ : never; export type ResponseOf<RT> = RT extends RequestOrNotificationType<any, infer R> ? R : never; const normalizeProxyUrl = (url: string) => { const protocol = "http://"; if (!url.startsWith(protocol)) { return `${protocol}${url}`; } return url; }; export class AgentConnection implements Disposable { private _connection: LanguageClientConnection | undefined; private _agentProcess: ChildProcess | undefined; private _initializedEvent = new Echo(); private _crashEmitter = new Echo(); private _didChangeDataEvent = new Echo<DidChangeDataNotification>(); private _didChangeDocumentMarkersEvent = new Echo<DidChangeDocumentMarkersNotification>(); private _didChangeConnectionStatusEvent = new Echo<DidChangeConnectionStatusNotification>(); private _didStartLoginEvent = new Echo(); private _didFailLoginEvent = new Echo(); private _didLoginEvent = new Echo<DidLoginNotification>(); private _didChangeVersionCompatibility = new Echo<DidChangeVersionCompatibilityNotification>(); private _didChangeApiVersionCompatibility = new Echo< DidChangeApiVersionCompatibilityNotification >(); private _didChangeServerUrl = new Echo<DidChangeServerUrlNotification>(); private _didEncounterMaintenanceMode = new Echo<DidEncounterMaintenanceModeNotification>(); private _restartNeededEmitter = new Echo(); private _initialized = false; private _subscriptions = new CompositeDisposable(); private logger = new FileLogger("agent"); get initialized() { return this._initialized; } get connection() { return this._connection; } constructor(private _environment: EnvironmentConfig) {} @started request<RT extends RequestType<any, any, any, any>>( requestType: RT, params: RequestOf<RT> ): Promise<ResponseOf<RT>> { return this.connection!.sendCustomRequest(requestType.method, params); } // for when typing can't be inferred @started sendRequest<R>(name: string, params?: any): Promise<R> { return this.connection!.sendCustomRequest(name, params); } @started telemetry(data: TelemetryRequest) { this.request(TelemetryRequestType, data); } onDidInitialize(cb: () => void) { return this._initializedEvent.add(cb); } onDidStartLogin(cb: () => void) { return this._didStartLoginEvent.add(cb); } onDidFailLogin(cb: () => void) { return this._didFailLoginEvent.add(cb); } onDidLogin(cb: (event: DidLoginNotification) => void) { return this._didLoginEvent.add(cb); } onDidChangeData(cb: (event: DidChangeDataNotification) => void) { return this._didChangeDataEvent.add(cb); } onDidChangeDocumentMarkers(cb: (event: DidChangeDocumentMarkersNotification) => void) { return this._didChangeDocumentMarkersEvent.add(cb); } onDidChangeConnectionStatus(cb: (event: DidChangeConnectionStatusNotification) => void) { return this._didChangeConnectionStatusEvent.add(cb); } onDidChangeVersionCompatibility(cb: (event: DidChangeVersionCompatibilityNotification) => void) { return this._didChangeVersionCompatibility.add(cb); } onDidChangeApiVersionCompatibility( cb: (event: DidChangeApiVersionCompatibilityNotification) => void ) { return this._didChangeApiVersionCompatibility.add(cb); } onDidChangeServerUrl(cb: (event: DidChangeServerUrlNotification) => void) { return this._didChangeServerUrl.add(cb); } onDidEncounterMaintenanceMode(cb: (event: DidEncounterMaintenanceModeNotification) => void) { return this._didEncounterMaintenanceMode.add(cb); } onDidCrash(cb: () => void) { return this._crashEmitter.add(cb); } onDidRequireRestart(cb: () => void) { return this._restartNeededEmitter.add(cb); } dispose() { this.stop(); this.logger.dispose(); this._initializedEvent.dispose(); this._crashEmitter.dispose(); this._didLoginEvent.dispose(); this._didChangeDataEvent.dispose(); this._didChangeDocumentMarkersEvent.dispose(); this._didChangeConnectionStatusEvent.dispose(); this._didStartLoginEvent.dispose(); this._didFailLoginEvent.dispose(); } async start() { this._agentProcess = this._startServer(); const rpc = createMessageConnection( new IPCMessageReader(this._agentProcess as ChildProcess), new IPCMessageWriter(this._agentProcess as ChildProcess) ); this._connection = new LanguageClientConnection(rpc); this._connection.onCustom(RestartRequiredNotificationType.method, () => { this._restartNeededEmitter.push(); }); this._preInitialization(this._connection, rpc); const firstProject = atom.project.getPaths()[0]; // TODO: what if there are no projects const response = await this._connection.initialize({ processId: this._agentProcess.pid, workspaceFolders: [], rootUri: firstProject ? Convert.pathToUri(firstProject) : null, capabilities: LSP_CLIENT_CAPABILITIES, initializationOptions: this._getInitializationOptions() }); if (response.result.error) { this.stop(); } else { this._connection.initialized(); this._initialized = true; this._initializedEvent.push(); } return (response as AgentInitializeResult).result; } private _getInitializationOptions(): BaseAgentOptions { const initializationOptions: Partial<BaseAgentOptions> = { extension: { build: "", buildEnv: "dev", version: getPluginVersion(), versionFormatted: `${getPluginVersion()}${atom.inDevMode() ? "(dev)" : ""}` }, ide: { name: "Atom", version: atom.getVersion(), detail: `Atom (${atom.getReleaseChannel()})` }, disableStrictSSL: Container.configs.get("disableStrictSSL"), isDebugging: atom.inDevMode(), traceLevel: Container.configs.get("traceLevel"), gitPath: "git", serverUrl: this._environment.serverUrl }; const configs = Container.configs; const proxySupport = configs.get("proxySupport"); if (proxySupport === "on") { const proxy = configs.get("proxyUrl"); if (proxy !== "") { initializationOptions.proxySupport = "override"; initializationOptions.proxy = { url: normalizeProxyUrl(proxy), strictSSL: configs.get("proxyStrictSSL") }; } else { initializationOptions.proxySupport = "on"; } } else { initializationOptions.proxySupport = proxySupport; } return initializationOptions as BaseAgentOptions; } private _preInitialization(connection: LanguageClientConnection, rpc: MessageConnection) { rpc.onRequest("client/registerCapability", (params: RegistrationParams) => { params.registrations.forEach(registration => { // TODO: register workspace/didChangeConfiguration if (registration.method === DidChangeWorkspaceFoldersNotification.type.method) { this._subscriptions.add( atom.project.onDidChangePaths(() => { connection.sendCustomNotification(DidChangeWorkspaceFoldersNotification.type.method, { event: { added: atom.project.getDirectories().map(dir => ({ uri: Convert.pathToUri(dir.getPath()), name: dir.getBaseName() })), removed: [] } as WorkspaceFoldersChangeEvent } as DidChangeWorkspaceFoldersParams); }) ); } }); }); rpc.onRequest("workspace/configuration", (params: ConfigurationParams) => params.items.map(({ section }) => { const result = {}; if (section === "files.exclude" || section === "search.exclude") { const ignoredPaths = atom.config.get("core.ignoredNames") as string[]; for (const path of ignoredPaths) { result[path] = true; } return result; } }) ); rpc.onRequest("workspace/workspaceFolders", () => atom.project .getDirectories() .map(dir => ({ uri: Convert.pathToUri(dir.getPath()), name: dir.getBaseName() })) ); rpc.onRequest(AgentOpenUrlRequestType.method, (params: AgentOpenUrlRequest) => { shell.openExternal(params.url); }); this._subscriptions.add( atom.workspace.observeTextEditors(editor => { const filePath = editor.getPath(); if (!filePath) return; connection.didOpenTextDocument({ textDocument: { uri: Editor.getUri(editor), languageId: "", version: editor.getBuffer().createCheckpoint(), text: editor.getText() } }); this._subscriptions.add( editor.onDidDestroy(() => connection.didCloseTextDocument({ textDocument: { uri: Editor.getUri(editor) } }) ), editor.onDidChange(() => { connection.didChangeTextDocument({ textDocument: { uri: Editor.getUri(editor), version: editor.createCheckpoint() }, contentChanges: [{ text: editor.getText() }] }); }), editor.onDidChangePath(path => { connection.didCloseTextDocument({ textDocument: { uri: Convert.pathToUri(filePath) } }); connection.didOpenTextDocument({ textDocument: { uri: Convert.pathToUri(path), languageId: "", version: editor.getBuffer().createCheckpoint(), text: editor.getText() } }); }) ); }) ); connection.onLogMessage(params => { this.logger.log(ReversedMessageType[params.type], params.message); }); connection.onCustom(DidChangeDataNotificationType.method, event => { this._didChangeDataEvent.push(event as DidChangeDataNotification); }); connection.onCustom(DidChangeDocumentMarkersNotificationType.method, notification => { this._didChangeDocumentMarkersEvent.push( notification as DidChangeDocumentMarkersNotification ); }); connection.onCustom(DidChangeConnectionStatusNotificationType.method, notification => this._didChangeConnectionStatusEvent.push( notification as DidChangeConnectionStatusNotification ) ); connection.onCustom(DidStartLoginNotificationType.method, () => this._didStartLoginEvent.push() ); connection.onCustom(DidFailLoginNotificationType.method, () => this._didFailLoginEvent.push()); connection.onCustom(DidLoginNotificationType.method, notification => this._didLoginEvent.push(notification as DidLoginNotification) ); connection.onCustom(DidChangeVersionCompatibilityNotificationType.method, notification => this._didChangeVersionCompatibility.push( notification as DidChangeVersionCompatibilityNotification ) ); connection.onCustom(DidChangeApiVersionCompatibilityNotificationType.method, notification => this._didChangeApiVersionCompatibility.push( notification as DidChangeApiVersionCompatibilityNotification ) ); connection.onCustom(DidChangeServerUrlNotificationType.method, notification => { this._didChangeServerUrl.push(notification as DidChangeServerUrlNotification); }); connection.onCustom(DidEncounterMaintenanceModeNotificationType.method, notification => this._didEncounterMaintenanceMode.push( notification as DidEncounterMaintenanceModeNotification ) ); } private _getAgentSourceArgs(): string[] { if (Debug.isDebugging()) { return ["--inspect=6012", getAgentSource()]; } return [asAbsolutePath("dist/agent/agent.js")]; } private _startServer(): ChildProcess { const options: { [k: string]: any } = {}; options.env = Object.create(process.env); options.env.ELECTRON_RUN_AS_NODE = "1"; options.env.ELECTRON_NO_ATTACH_CONSOLE = "1"; options.stdio = [null, null, null, "ipc"]; const agentProcess = spawn( process.execPath, ["--no-lazy", ...this._getAgentSourceArgs(), "--node-ipc"], options ); if (Debug.isDebugging()) { console.debug("CodeStream agent pid", agentProcess.pid); } agentProcess.on("error", error => { console.error(error); }); /* I'm not sure handling `disconnect` is necessary - akonwi */ // agentProcess.on("disconnect", () => { // // this._connection will be unset if this instance was stopped properly // if (this._connection) { // atom.notifications.addWarning("The CodeStream agent process unexpectedly crashed.", { // description: "Please open the dev tools and share the error with us.", // }); // this._crashEmitter.push(); // } // this.stop(); // }); agentProcess.on("exit", code => { if (Number(code) !== 0) { if (code === 12) { atom.notifications.addError("Port 6012 for debugging is already in use"); } else console.error(`CodeStream agent process exited with non-zero exit code ${code}`); } this.stop(); }); return agentProcess; } stop() { if (!this.initialized) return; try { this._connection!.dispose(); } catch (error) { this.logger.log("error", `Error disposing LanguageClientConnection - ${error}`); } finally { this._connection = undefined; } try { this._agentProcess!.kill(); } catch (error) { this.logger.log("error", `Error killing agent process - ${error}`); } finally { this._agentProcess = undefined; } this._subscriptions.dispose(); this._subscriptions = new CompositeDisposable(); this._initialized = false; } async reset(newEnvironmentConfig?: EnvironmentConfig) { if (newEnvironmentConfig != null) this._environment = newEnvironmentConfig; this.stop(); await this.start(); } } function started(_target: AgentConnection, _key: string, descriptor: PropertyDescriptor) { const fn = descriptor.value; descriptor.value = async function(this: AgentConnection, ...args: any[]) { if (!this.initialized) { await this.start(); } return fn.apply(this, args); }; return descriptor; }
the_stack