text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { useApolloClient } from "@apollo/client" import { StackNavigationProp } from "@react-navigation/stack" import i18n from "i18n-js" import * as React from "react" import { StatusBar, StyleSheet, Text, View } from "react-native" import { ScrollView, TouchableOpacity } from "react-native-gesture-handler" import { SvgProps } from "react-native-svg" import { MountainHeader } from "../../components/mountain-header" import { Screen } from "../../components/screen" import { getQuizQuestions } from "../../graphql/query" import { translate, translateQuizSections } from "../../i18n" import { PrimaryStackParamList } from "../../navigation/stack-param-lists" import { color } from "../../theme" import { palette } from "../../theme/palette" import { ComponentType, ScreenType } from "../../types/jsx" import useToken from "../../utils/use-token" import { sectionCompletedPct } from "../earns-screen" import BitcoinCircle from "./bitcoin-circle-01.svg" import BottomOngoing from "./bottom-ongoing-01.svg" import BottomStart from "./bottom-start-01.svg" import LeftFinish from "./left-finished-01.svg" import LeftLastOngoing from "./left-last-section-ongoing-01.svg" import LeftLastTodo from "./left-last-section-to-do-01.svg" import LeftComplete from "./left-section-completed-01.svg" import LeftOngoing from "./left-section-ongoing-01.svg" import LeftTodo from "./left-section-to-do-01.svg" import RightFinish from "./right-finished-01.svg" import RightFirst from "./right-first-section-to-do-01.svg" import RightLastOngoing from "./right-last-section-ongoing-01.svg" import RightLastTodo from "./right-last-section-to-do-01.svg" import RightComplete from "./right-section-completed-01.svg" import RightOngoing from "./right-section-ongoing-01.svg" import RightTodo from "./right-section-to-do-01.svg" import TextBlock from "./text-block-medium.svg" const BottomOngoingEN = React.lazy(() => import("./bottom-ongoing-01.en.svg")) const BottomOngoingES = React.lazy(() => import("./bottom-ongoing-01.es.svg")) const BottomStartEN = React.lazy(() => import("./bottom-start-01.en.svg")) const BottomStartES = React.lazy(() => import("./bottom-start-01.es.svg")) const styles = StyleSheet.create({ contentContainer: { backgroundColor: palette.lightBlue, flexGrow: 1, }, finishText: { color: palette.white, fontSize: 18, position: "absolute", right: 30, textAlign: "center", top: 30, width: 160, }, icon: { marginBottom: 6, marginHorizontal: 10, }, mainView: { alignSelf: "center", }, textStyleBox: { color: palette.white, fontSize: 16, fontWeight: "bold", marginHorizontal: 10, }, progressContainer: { backgroundColor: palette.darkGrey, margin: 10 }, position: { height: 40 }, }) type SideType = "left" | "right" interface IInBetweenTile { side: SideType position: number length: number } interface IBoxAdding { text: string Icon: React.FunctionComponent<SvgProps> side: SideType position: number length: number onPress: () => void } interface ISectionData { text: string index: string icon: React.FunctionComponent<SvgProps> onPress: () => void } interface IEarnMapScreen { currSection: number progress: number sectionsData: ISectionData[] earned: number } type ProgressProps = { progress: number } export const ProgressBar: ComponentType = ({ progress }: ProgressProps) => { const balanceWidth = `${progress * 100}%` return ( <View style={styles.progressContainer}> {/* pass props to style object to remove inline style */} {/* eslint-disable-next-line react-native/no-inline-styles */} <View style={{ width: balanceWidth, height: 3, backgroundColor: palette.white }} /> </View> ) } type EarnMapDataProps = { navigation: StackNavigationProp<PrimaryStackParamList, "Earn"> } export const EarnMapDataInjected: ScreenType = ({ navigation }: EarnMapDataProps) => { const { hasToken } = useToken() const client = useApolloClient() const quizQuestions = getQuizQuestions(client, { hasToken }) React.useEffect(() => { const unsubscribe = navigation?.addListener("focus", () => { StatusBar.setBackgroundColor(color.transparent) StatusBar.setBarStyle("light-content") StatusBar.setTranslucent(true) }) return unsubscribe }, [navigation]) React.useEffect(() => { const unsubscribe = navigation?.addListener("blur", () => { StatusBar.setTranslucent(false) StatusBar.setBarStyle("dark-content") StatusBar.setBackgroundColor(palette.lighterGrey) }) return unsubscribe }, [navigation]) if (!quizQuestions.allQuestions) { return null } const sectionIndexs = Object.keys(translateQuizSections("EarnScreen.earns")) const sectionsData = [] let currSection = 0 let progress = NaN for (const sectionIndex of sectionIndexs) { sectionsData.push({ index: sectionIndex, text: translate(`EarnScreen.earns.${sectionIndex}.meta.title`), icon: BitcoinCircle, onPress: navigation.navigate.bind(navigation.navigate, "earnsSection", { section: sectionIndex, }), }) const sectionCompletion = sectionCompletedPct({ quizQuestions, sectionIndex }) if (sectionCompletion === 1) { currSection += 1 } else if (isNaN(progress)) { // only do it once for the first uncompleted section progress = sectionCompletion } } const earnedSat = quizQuestions.myCompletedQuestions ? Object.values(quizQuestions.myCompletedQuestions).reduce((a, b) => a + b, 0) : 0 return ( <EarnMapScreen sectionsData={sectionsData} currSection={currSection} progress={progress} earned={earnedSat} /> ) } type FinishProps = { currSection: number length: number } export const EarnMapScreen: React.FC<IEarnMapScreen> = ({ sectionsData, currSection, progress, earned, }: IEarnMapScreen) => { const Finish = ({ currSection, length }: FinishProps) => { if (currSection !== sectionsData.length) return null return ( <> <Text style={styles.finishText}>{translate("EarnScreen.finishText")}</Text> {/* TODO FIXME for even section # */} {length % 2 ? <LeftFinish /> : <RightFinish />} </> ) } const InBetweenTile: React.FC<IInBetweenTile> = ({ side, position, length, }: IInBetweenTile) => { if (currSection < position) { if (position === length - 1) { return side === "left" ? <LeftLastTodo /> : <RightLastTodo /> } return side === "left" ? <LeftTodo /> : <RightTodo /> } if (currSection === position) { if (position === length - 1) { return ( <> <View style={styles.position} /> {side === "left" ? <LeftLastOngoing /> : <RightLastOngoing />} </> ) } if (position === 0 && progress === 0) { return <RightFirst /> } return side === "left" ? <LeftOngoing /> : <RightOngoing /> } return side === "left" ? <LeftComplete /> : <RightComplete /> } const BoxAdding: React.FC<IBoxAdding> = ({ text, Icon, side, position, length, onPress, }: IBoxAdding) => { const disabled = currSection < position const progressSection = disabled ? 0 : currSection > position ? 1 : progress // rework this to pass props into the style object const boxStyle = StyleSheet.create({ container: { position: "absolute", bottom: currSection === position ? (currSection === 0 && progress === 0 ? 30 : 80) : 30, left: side === "left" ? 35 : 200, opacity: disabled ? 0.5 : 1, }, }) return ( <View> <InBetweenTile side={side} position={position} length={length} /> <View style={boxStyle.container}> <View> <TouchableOpacity disabled={disabled} onPress={onPress}> <TextBlock /> {/* eslint-disable-next-line react-native/no-inline-styles */} <View style={{ position: "absolute", width: "100%" }}> <ProgressBar progress={progressSection} /> <Icon style={styles.icon} width={50} height={50} /> <Text style={styles.textStyleBox}>{text}</Text> </View> </TouchableOpacity> </View> </View> </View> ) } const sectionsComp = [] sectionsData.forEach((item, index) => { sectionsComp.unshift( <BoxAdding key={item.index} text={item.text} Icon={item.icon} side={index % 2 ? "left" : "right"} position={index} length={sectionsData.length} onPress={item.onPress} />, ) }) const scrollViewRef: React.MutableRefObject<ScrollView> = React.useRef() React.useEffect(() => { scrollViewRef.current.scrollToEnd() }, []) const backgroundColor = currSection < sectionsData.length ? palette.sky : palette.orange const translatedBottomOngoing = () => { switch (i18n.locale) { case "es": return <BottomOngoingES /> default: return <BottomOngoingEN /> } } const translatedBottomStart = () => { switch (i18n.locale) { case "es": return <BottomStartES /> default: return <BottomStartEN /> } } return ( <Screen unsafe statusBar="light-content"> <ScrollView // removeClippedSubviews={true} style={{ backgroundColor }} contentContainerStyle={styles.contentContainer} ref={scrollViewRef} onContentSizeChange={() => { scrollViewRef.current.scrollToEnd() }} > <MountainHeader amount={earned.toString()} color={backgroundColor} /> {/* <View style={{backgroundColor: palette.sky}}> <Top width={screenWidth} /> </View> */} <View style={styles.mainView}> <Finish currSection={currSection} length={sectionsData.length} /> {sectionsComp} {currSection === 0 ? ( progress === 0 ? ( <React.Suspense fallback={<BottomStart />}> {translatedBottomStart()} </React.Suspense> ) : ( <React.Suspense fallback={<BottomOngoing />}> {translatedBottomOngoing()} </React.Suspense> ) ) : ( <View style={styles.position} /> )} </View> </ScrollView> </Screen> ) }
the_stack
import mock, { mockClear, mockDeep, mockReset, mockFn, JestMockExtended } from './Mock'; import { anyNumber } from './Matchers'; import calledWithFn from './CalledWithFn'; import { MockProxy } from './Mock'; interface MockInt { id: number; someValue?: boolean | null; getNumber: () => number; getNumberWithMockArg: (mock: any) => number; getSomethingWithArgs: (arg1: number, arg2: number) => number; getSomethingWithMoreArgs: (arg1: number, arg2: number, arg3: number) => number; } class Test1 implements MockInt { readonly id: number; public deepProp: Test2 = new Test2(); private readonly anotherPart: number; constructor(id: number) { this.id = id; this.anotherPart = id; } public ofAnother(test: Test1) { return test.getNumber(); } public getNumber() { return this.id; } public getNumberWithMockArg(mock: any) { return this.id; } public getSomethingWithArgs(arg1: number, arg2: number) { return this.id; } public getSomethingWithMoreArgs(arg1: number, arg2: number, arg3: number) { return this.id; } } class Test2 { public deeperProp: Test3 = new Test3(); getNumber(num: number) { return num * 2; } getAnotherString(str: string) { return `${str} another string`; } } class Test3 { getNumber(num: number) { return num ^ 2; } } class Test4 { constructor(test1: Test1, int: MockInt) {} } describe('jest-mock-extended', () => { test('Can be assigned back to itself even when there are private parts', () => { // No TS errors here const mockObj: Test1 = mock<Test1>(); // No error here. new Test1(1).ofAnother(mockObj); expect(mockObj.getNumber).toHaveBeenCalledTimes(1); }); test('Check that a jest.fn() is created without any invocation to the mock method', () => { const mockObj = mock<MockInt>(); expect(mockObj.getNumber).toHaveBeenCalledTimes(0); }); test('Check that invocations are registered', () => { const mockObj: MockInt = mock<MockInt>(); mockObj.getNumber(); mockObj.getNumber(); expect(mockObj.getNumber).toHaveBeenCalledTimes(2); }); test('Can mock a return value', () => { const mockObj = mock<MockInt>(); mockObj.getNumber.mockReturnValue(12); expect(mockObj.getNumber()).toBe(12); }); test('Can specify args', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs(1, 2); expect(mockObj.getSomethingWithArgs).toBeCalledWith(1, 2); }); test('Can specify calledWith', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(1); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(1); }); test('Can specify multiple calledWith', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(3); mockObj.getSomethingWithArgs.calledWith(6, 7).mockReturnValue(13); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); expect(mockObj.getSomethingWithArgs(6, 7)).toBe(13); }); test('Can set props', () => { const mockObj = mock<MockInt>(); mockObj.id = 17; expect(mockObj.id).toBe(17); }); test('Can set false and null boolean props', () => { const mockObj = mock<MockInt>({ someValue: false, }); const mockObj2 = mock<MockInt>({ someValue: null, }); expect(mockObj.someValue).toBe(false); expect(mockObj2.someValue).toBe(null); }); test('can set undefined explicitly', () => { const mockObj = mock<MockInt>({ someValue: undefined, // this is intentionally set to undefined }); expect(mockObj.someValue).toBe(undefined); }); test('Equals self', () => { const mockObj = mock<MockInt>(); expect(mockObj).toBe(mockObj); expect(mockObj).toEqual(mockObj); const spy = jest.fn(); spy(mockObj); expect(spy).toHaveBeenCalledWith(mockObj); }); describe('Mimic Type', () => { test('can use MockProxy in place of Mock Type', () => { const t1: MockProxy<Test1> = mock<Test1>(); const i1: MockProxy<MockInt> = mock<MockInt>(); // no TS error const f = new Test4(t1, i1); }); }); describe('calledWith', () => { test('can use calledWith without mock', () => { const mockFunc = calledWithFn(); mockFunc.calledWith(anyNumber(), anyNumber()).mockReturnValue(3); expect(mockFunc(1, 2)).toBe(3); }); test('Can specify matchers', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(anyNumber(), anyNumber()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('does not match when one arg does not match Matcher', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(anyNumber(), anyNumber()).mockReturnValue(3); // @ts-ignore expect(mockObj.getSomethingWithArgs('1', 2)).toBe(undefined); }); test('can use literals', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('can mix Matchers with literals', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('supports multiple calledWith', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(2, anyNumber()).mockReturnValue(4); mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3); mockObj.getSomethingWithArgs.calledWith(6, anyNumber()).mockReturnValue(7); expect(mockObj.getSomethingWithArgs(2, 2)).toBe(4); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); expect(mockObj.getSomethingWithArgs(6, 2)).toBe(7); expect(mockObj.getSomethingWithArgs(7, 2)).toBe(undefined); }); test('Support jest matcher', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(expect.anything(), expect.anything()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('Suport mix Matchers with literals and with jest matcher', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithMoreArgs.calledWith(anyNumber(), expect.anything(), 3).mockReturnValue(4); expect(mockObj.getSomethingWithMoreArgs(1, 2, 3)).toBe(4); expect(mockObj.getSomethingWithMoreArgs(1, 2, 4)).toBeUndefined; }); test('Can use calledWith with an other mock', () => { const mockObj = mock<MockInt>(); const mockArg = mock(); mockObj.getNumberWithMockArg.calledWith(mockArg).mockReturnValue(4); expect(mockObj.getNumberWithMockArg(mockArg)).toBe(4); }) }); describe('Matchers with toHaveBeenCalledWith', () => { test('matchers allow all args to be Matcher based', () => { const mockObj: MockInt = mock<MockInt>(); mockObj.getSomethingWithArgs(2, 4); expect(mockObj.getSomethingWithArgs).toHaveBeenCalledWith(anyNumber(), anyNumber()); }); test('matchers allow for a mix of Matcher and literal', () => { const mockObj: MockInt = mock<MockInt>(); mockObj.getSomethingWithArgs(2, 4); expect(mockObj.getSomethingWithArgs).toHaveBeenCalledWith(anyNumber(), 4); }); test('matchers allow for not.toHaveBeenCalledWith', () => { const mockObj: MockInt = mock<MockInt>(); mockObj.getSomethingWithArgs(2, 4); expect(mockObj.getSomethingWithArgs).not.toHaveBeenCalledWith(anyNumber(), 5); }); }); describe('Deep mock support', () => { test('can deep mock members', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); expect(mockObj.deepProp.getNumber(1)).toBe(4); }); test('three level deep mock', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.deeperProp.getNumber.calledWith(1).mockReturnValue(4); expect(mockObj.deepProp.deeperProp.getNumber(1)).toBe(4); }); test('maintains API for deep mocks', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.getNumber(100); expect(mockObj.deepProp.getNumber.mock.calls[0][0]).toBe(100); }); test('non deep expectation work as expected', () => { const mockObj = mockDeep<Test1>(); new Test1(1).ofAnother(mockObj); expect(mockObj.getNumber).toHaveBeenCalledTimes(1); }); test('deep expectation work as expected', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.getNumber(2); expect(mockObj.deepProp.getNumber).toHaveBeenCalledTimes(1); }); }); describe('mock implementation support', () => { test('can provide mock implementation for props', () => { const mockObj = mock<Test1>({ id: 61, }); expect(mockObj.id).toBe(61); }); test('can provide mock implementation for functions', () => { const mockObj = mock<Test1>({ getNumber: () => { return 150; }, }); expect(mockObj.getNumber()).toBe(150); }); test('Partially mocked implementations can have non-mocked function expectations', () => { const mockObj = mock<Test1>({ getNumber: () => { return 150; }, }); mockObj.getSomethingWithArgs.calledWith(1, 2).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('can provide deep mock implementations', () => { const mockObj = mockDeep<Test1>({ deepProp: { getNumber: (num: number) => { return 76; }, }, }); expect(mockObj.deepProp.getNumber(123)).toBe(76); }); test('Partially mocked implementations of deep mocks can have non-mocked function expectations', () => { const mockObj = mockDeep<Test1>({ deepProp: { getNumber: (num: number) => { return 76; }, }, }); mockObj.deepProp.getAnotherString.calledWith('abc').mockReturnValue('this string'); expect(mockObj.deepProp.getAnotherString('abc')).toBe('this string'); }); }); describe('Promise', () => { test('Can return as Promise.resolve', async () => { const mockObj = mock<MockInt>(); mockObj.id = 17; const promiseMockObj = Promise.resolve(mockObj); await expect(promiseMockObj).resolves.toBeDefined(); await expect(promiseMockObj).resolves.toMatchObject({ id: 17 }); }); test('Can return as Promise.reject', async () => { const mockError = mock<Error>(); mockError.message = '17'; const promiseMockObj = Promise.reject(mockError); try { await promiseMockObj; fail('Promise must be rejected'); } catch (e) { await expect(e).toBeDefined(); await expect(e).toBe(mockError); await expect(e).toHaveProperty('message', '17'); } await expect(promiseMockObj).rejects.toBeDefined(); await expect(promiseMockObj).rejects.toBe(mockError); await expect(promiseMockObj).rejects.toHaveProperty('message', '17'); }); test('Can mock a then function', async () => { const mockPromiseObj = Promise.resolve(42); const mockObj = mock<MockInt>(); mockObj.id = 17; // @ts-ignore mockObj.then = mockPromiseObj.then.bind(mockPromiseObj); const promiseMockObj = Promise.resolve(mockObj); await promiseMockObj; await expect(promiseMockObj).resolves.toBeDefined(); await expect(promiseMockObj).resolves.toEqual(42); }); }); describe('clearing / resetting', () => { test('mockReset supports jest.fn()', () => { const fn = jest.fn().mockImplementation(() => true); expect(fn()).toBe(true); mockReset(fn); expect(fn()).toBe(undefined); }); test('mockClear supports jest.fn()', () => { const fn = jest.fn().mockImplementation(() => true); fn(); expect(fn.mock.calls.length).toBe(1); mockClear(fn); expect(fn.mock.calls.length).toBe(0); }); test('mockReset object', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); mockReset(mockObj); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(undefined); mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('mockClear object', () => { const mockObj = mock<MockInt>(); mockObj.getSomethingWithArgs.calledWith(1, anyNumber()).mockReturnValue(3); expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); expect(mockObj.getSomethingWithArgs.mock.calls.length).toBe(1); mockClear(mockObj); expect(mockObj.getSomethingWithArgs.mock.calls.length).toBe(0); // Does not clear mock implementations of calledWith expect(mockObj.getSomethingWithArgs(1, 2)).toBe(3); }); test('mockReset deep', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); expect(mockObj.deepProp.getNumber(1)).toBe(4); mockReset(mockObj); expect(mockObj.deepProp.getNumber(1)).toBe(undefined); }); test('mockClear deep', () => { const mockObj = mockDeep<Test1>(); mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4); expect(mockObj.deepProp.getNumber(1)).toBe(4); expect(mockObj.deepProp.getNumber.mock.calls.length).toBe(1); mockClear(mockObj); expect(mockObj.deepProp.getNumber.mock.calls.length).toBe(0); // Does not clear mock implementations of calledWith expect(mockObj.deepProp.getNumber(1)).toBe(4); }); }); describe('function mock', () => { test('should mock function', async () => { type MyFn = (x: number, y: number) => Promise<string>; const mockFunc = mockFn<MyFn>(); mockFunc.mockResolvedValue(`str`); const result: string = await mockFunc(1, 2); expect(result).toBe(`str`); }); test('should mock function and use calledWith', async () => { type MyFn = (x: number, y: number) => Promise<string>; const mockFunc = mockFn<MyFn>(); mockFunc.calledWith(1, 2).mockResolvedValue(`str`); const result: string = await mockFunc(1, 2); expect(result).toBe(`str`); }); }); describe('ignoreProps', () => { test('can configure ignoreProps', async () => { JestMockExtended.configure({ ignoreProps: ['ignoreMe'] }); const mockObj = mock<{ ignoreMe: string; dontIgnoreMe: string }>(); expect(mockObj.ignoreMe).toBeUndefined(); expect(mockObj.dontIgnoreMe).toBeDefined(); }); }); describe('JestMockExtended config', () => { test('can mock then', async () => { JestMockExtended.configure({ ignoreProps: [] }); const mockObj = mock<{ then: () => void }>(); mockObj.then(); expect(mockObj.then).toHaveBeenCalled(); }); test('can reset config', async () => { JestMockExtended.configure({ ignoreProps: [] }); JestMockExtended.resetConfig(); const mockObj = mock<{ then: () => void }>(); expect(mockObj.then).toBeUndefined(); }); }); describe('mock Date', () => { test('should call built-in date functions', () => { type objWithDate = { date: Date }; const mockObj = mock<objWithDate>({ date: new Date('2000-01-15') }); expect(mockObj.date.getFullYear()).toBe(2000); expect(mockObj.date.getMonth()).toBe(0); expect(mockObj.date.getDate()).toBe(15); }); }); });
the_stack
import 'reflect-metadata' import test from 'japa' import { join } from 'path' import { fs } from '../test-helpers' import { ManifestLoader } from '../src/Manifest/Loader' import { ManifestGenerator } from '../src/Manifest/Generator' test.group('Manifest Generator', (group) => { group.before(async () => { await fs.ensureRoot() }) group.afterEach(async () => { await fs.cleanup() }) test('read manifest file', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' @args.string() public name: string @flags.boolean() public adult: boolean public async handle () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, ]) await manifestLoader.boot() assert.deepEqual(manifestLoader.getCommands(), { commands: [ { settings: {}, commandPath: './Commands/Greet', commandName: 'greet', description: 'Greet a user', aliases: [], args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [ { name: 'adult', type: 'boolean', propertyName: 'adult', }, ], }, ], aliases: {}, }) }) test('read more than one manifest files', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' @args.string() public name: string @flags.boolean() public adult: boolean public async run () {} }` ) await fs.add( './sub-app/MyCommands/Run.ts', ` import { args, flags } from '../../../../index' import { BaseCommand } from '../../../../src/BaseCommand' export default class Run extends BaseCommand { public static commandName = 'run' public static description = 'Run another command' @args.string() public name: string public async run () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() await new ManifestGenerator(join(fs.basePath, 'sub-app'), ['./MyCommands/Run']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, { basePath: join(fs.basePath, 'sub-app'), manifestAbsPath: join(fs.basePath, 'sub-app', 'ace-manifest.json'), }, ]) await manifestLoader.boot() assert.deepEqual(manifestLoader.getCommands(), { commands: [ { settings: {}, commandPath: './Commands/Greet', commandName: 'greet', description: 'Greet a user', aliases: [], args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [ { name: 'adult', type: 'boolean', propertyName: 'adult', }, ], }, { settings: {}, commandPath: './MyCommands/Run', commandName: 'run', description: 'Run another command', aliases: [], args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [], }, ], aliases: {}, }) }) test('merge aliases of more than one command', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' public static aliases = ['sayhi'] @args.string() public name: string @flags.boolean() public adult: boolean public async run () {} }` ) await fs.add( './sub-app/MyCommands/Run.ts', ` import { args, flags } from '../../../../index' import { BaseCommand } from '../../../../src/BaseCommand' export default class Run extends BaseCommand { public static commandName = 'run' public static description = 'Run another command' public static aliases = ['fire'] @args.string() public name: string public async run () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() await new ManifestGenerator(join(fs.basePath, 'sub-app'), ['./MyCommands/Run']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, { basePath: join(fs.basePath, 'sub-app'), manifestAbsPath: join(fs.basePath, 'sub-app', 'ace-manifest.json'), }, ]) await manifestLoader.boot() assert.deepEqual(manifestLoader.getCommands(), { commands: [ { settings: {}, commandPath: './Commands/Greet', commandName: 'greet', description: 'Greet a user', aliases: ['sayhi'], args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [ { name: 'adult', type: 'boolean', propertyName: 'adult', }, ], }, { settings: {}, commandPath: './MyCommands/Run', commandName: 'run', description: 'Run another command', aliases: ['fire'], args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [], }, ], aliases: { sayhi: 'greet', fire: 'run', }, }) }) test('find if a command exists', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' @args.string() public name: string @flags.boolean() public adult: boolean public async run () {} }` ) await fs.add( './sub-app/MyCommands/Run.ts', ` import { args, flags } from '../../../../index' import { BaseCommand } from '../../../../src/BaseCommand' export default class Run extends BaseCommand { public static commandName = 'run' public static description = 'Run another command' @args.string() public name: string public async run () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() await new ManifestGenerator(join(fs.basePath, 'sub-app'), ['./MyCommands/Run']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, { basePath: join(fs.basePath, 'sub-app'), manifestAbsPath: join(fs.basePath, 'sub-app', 'ace-manifest.json'), }, ]) await manifestLoader.boot() assert.isTrue(manifestLoader.hasCommand('greet')) assert.isTrue(manifestLoader.hasCommand('run')) assert.isFalse(manifestLoader.hasCommand('make')) }) test('get command manifest node', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' @args.string() public name: string @flags.boolean() public adult: boolean public async run () {} }` ) await fs.add( './sub-app/MyCommands/Run.ts', ` import { args, flags } from '../../../../index' import { BaseCommand } from '../../../../src/BaseCommand' export default class Run extends BaseCommand { public static commandName = 'run' public static description = 'Run another command' @args.string() public name: string public async run () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() await new ManifestGenerator(join(fs.basePath, 'sub-app'), ['./MyCommands/Run']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, { basePath: join(fs.basePath, 'sub-app'), manifestAbsPath: join(fs.basePath, 'sub-app', 'ace-manifest.json'), }, ]) await manifestLoader.boot() assert.deepEqual(manifestLoader.getCommand('greet'), { basePath: fs.basePath, command: { settings: {}, commandPath: './Commands/Greet', commandName: 'greet', aliases: [], description: 'Greet a user', args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [ { name: 'adult', type: 'boolean', propertyName: 'adult', }, ], }, }) assert.deepEqual(manifestLoader.getCommand('run'), { basePath: join(fs.basePath, 'sub-app'), command: { settings: {}, aliases: [], commandPath: './MyCommands/Run', commandName: 'run', description: 'Run another command', args: [ { name: 'name', propertyName: 'name', type: 'string', required: true, }, ], flags: [], }, }) assert.isUndefined(manifestLoader.getCommand('make')) }) test('load command', async (assert) => { await fs.add( './Commands/Greet.ts', ` import { args, flags } from '../../../index' import { BaseCommand } from '../../../src/BaseCommand' export default class Greet extends BaseCommand { public static commandName = 'greet' public static description = 'Greet a user' @args.string() public name: string @flags.boolean() public adult: boolean public async run () {} }` ) await fs.add( './sub-app/MyCommands/Run.ts', ` import { args, flags } from '../../../../index' import { BaseCommand } from '../../../../src/BaseCommand' export default class Run extends BaseCommand { public static commandName = 'run' public static description = 'Run another command' @args.string() public name: string public async run () {} }` ) await new ManifestGenerator(fs.basePath, ['./Commands/Greet']).generate() await new ManifestGenerator(join(fs.basePath, 'sub-app'), ['./MyCommands/Run']).generate() const manifestLoader = new ManifestLoader([ { basePath: fs.basePath, manifestAbsPath: join(fs.basePath, 'ace-manifest.json'), }, { basePath: join(fs.basePath, 'sub-app'), manifestAbsPath: join(fs.basePath, 'sub-app', 'ace-manifest.json'), }, ]) await manifestLoader.boot() const command = await manifestLoader.loadCommand('greet') assert.deepEqual(command.commandName, 'greet') assert.isTrue(command.booted) }) })
the_stack
import { CSSLength, CSSPercentage, CSSTransformFunction } from './types'; import { createFunction } from './utils/formatting'; /** * The CSS transform property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. * Returns the transforms as a delimited string by space or returns 'none' if no arguments are provided * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform */ export function transform(...transforms: CSSTransformFunction[]): CSSTransformFunction { return transforms.length ? transforms.join(' ') : 'none'; } export const matrix = createFunction<{ /** * The matrix() CSS function specifies a homogeneous 2D transformation matrix comprised of the specified six values. The constant values of such matrices are implied and not passed as parameters; the other parameters are described in the column-major order. * * matrix(a, b, c, d, tx, ty) is a shorthand for matrix3d(a, b, 0, 0, c, d, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix */ (a: number, b: number, c: number, d: number, tx: number, ty: number): CSSTransformFunction; }>('matrix'); export const matrix3d = createFunction<{ /** * The matrix3d() CSS function describes a 3D transform as a 4x4 homogeneous matrix. The 16 parameters are described in the column-major order. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/matrix3d */ ( a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number ): CSSTransformFunction; }>('matrix3d'); export const perspective = createFunction<{ /** * The perspective() CSS function defines the distance between the z=0 plane and the user in order to give to the 3D-positioned element some perspective. Each 3D element with z>0 becomes larger; each 3D-element with z<0 becomes smaller. The strength of the effect is determined by the value of this property. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/perspective */ (value: CSSLength): CSSTransformFunction; }>('perspective'); export const rotate = createFunction<{ /** * The rotate() CSS function defines a transformation that moves the element around a fixed point (as specified by the transform-origin property) without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise. A rotation by 180° is called point reflection. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate */ (z: CSSPercentage): CSSTransformFunction; }>('rotate'); export const rotate3d = createFunction<{ /** * The rotate3d()CSS function defines a transformation that moves the element around a fixed axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.In opposition to rotations in the plane, the composition of 3D rotations is usually not commutative; it means that the order in which the rotations are applied is crucial. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d */ (x: CSSPercentage, y: CSSPercentage, z: CSSPercentage): CSSTransformFunction; }>('rotate3d'); export const rotateX = createFunction<{ /** * The rotateX()CSS function defines a transformation that moves the element around the abscissa without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise. The axis of rotation passes by the origin, defined by transform-origin CSS property. * * rotateX(a)is a shorthand for rotate3d(1, 0, 0, a). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotateX */ (x: CSSPercentage): CSSTransformFunction; }>('rotateX'); export const rotateY = createFunction<{ /** * The rotateY()CSS function defines a transformation that moves the element around the ordinate without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise. The axis of rotation passes by the origin, defined by transform-origin CSS property. * * rotateY(a)is a shorthand for rotate3d(0, 1, 0, a). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotateY */ (y: CSSPercentage): CSSTransformFunction; }>('rotateY'); export const rotateZ = createFunction<{ /** * The rotateZ()CSS function defines a transformation that moves the element around the z-axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise. The axis of rotation passes by the origin, defined by transform-origin CSS property. * * rotateZ(a)is a shorthand for rotate3d(0, 0, 1, a). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotateZ */ (z: CSSPercentage): CSSTransformFunction; }>('rotateZ'); export const scale = createFunction<{ /** * The scale() CSS function modifies the size of the element. It can either augment or decrease its size and as the amount of scaling is defined by a vector, it can do so more in one direction than in another one. This transformation is characterized by a vector whose coordinates define how much scaling is done in each direction. If both coordinates of the vector are equal, the scaling is uniform, or isotropic, and the shape of the element is preserved. In that case, the scaling function defines a homothetic transformation. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale */ (x: number, y?: number): CSSTransformFunction; }>('scale'); export const scale3d = createFunction<{ /** * The scale3d() CSS function modifies the size of an element. Because the amount of scaling is defined by a vector, it can resize different dimensions at different scales. This transformation is characterized by a vector whose coordinates define how much scaling is done in each direction. If all three coordinates of the vector are equal, the scaling is uniform, or isotropic, and the shape of the element is preserved. In that case, the scaling function defines a homothetic transformation. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale3d */ (x: number, y: number, z: number): CSSTransformFunction; }>('scale3d'); export const scaleX = createFunction<{ /** * The scaleX() CSS function modifies the abscissa of each element point by a constant factor, except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved. scaleX(-1) defines an axial symmetry with a vertical axis passing by the origin (as specified by the transform-origin property). * * scaleX(sx) is a shorthand for scale(sx, 1) or for scale3d(sx, 1, 1). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleX */ (x: number): CSSTransformFunction; }>('scaleX'); export const scaleY = createFunction<{ /** * The scaleY() CSS function modifies the ordinate of each element point by a constant factor except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved. scaleY(-1) defines an axial symmetry with a horizontal axis passing by the origin (as specified by the transform-origin property). * * scaleY(sy) is a shorthand for scale(1, sy) or for scale3d(1, sy, 1). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleY */ (y: number): CSSTransformFunction; }>('scaleY'); export const scaleZ = createFunction<{ /** * The scaleZ() CSS function modifies the z-coordinate of each element point by a constant factor, except if this scale factor is 1, in which case the function is the identity transform. The scaling is not isotropic and the angles of the element are not conserved. scaleZ(-1) defines an axial symmetry along the z-axis passing by the origin (as specified by the transform-origin property). * * scaleZ(sz) is a shorthand for scale3d(1, 1, sz). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scaleZ */ (z: number): CSSTransformFunction; }>('scaleZ'); export const skew = createFunction<{ /** * The skew() CSS function is a shear mapping, or transvection, distorting each point of an element by a certain angle in each direction. It is done by increasing each coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skew */ (x: CSSPercentage, y?: CSSPercentage): CSSTransformFunction; }>('skew'); export const skewX = createFunction<{ /** * The skewX() CSS function is a horizontal shear mapping distorting each point of an element by a certain angle in the horizontal direction. It is done by increasing the abscissa coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewX */ (x: CSSPercentage): CSSTransformFunction; }>('skewX'); export const skewY = createFunction<{ /** * The skewY() CSS function is a vertical shear mapping distorting each point of an element by a certain angle in the vertical direction. It is done by increasing the ordinate coordinate by a value proportionate to the specified angle and to the distance to the origin. The more far from the origin, the more away the point is, the greater will be the value added to it. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewY */ (y: CSSPercentage): CSSTransformFunction; }>('skewY'); export const translate = createFunction<{ /** * The translate() CSS function moves the position of the element on the plane. This transformation is characterized by a vector whose coordinates define how much it moves in each direction. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate */ (x: CSSLength | CSSPercentage, y?: CSSLength | CSSPercentage): CSSTransformFunction; }>('translate'); export const translate3d = createFunction<{ /** * The translate3d() CSS function moves the position of the element in the 3D space. This transformation is characterized by a 3-dimension vector whose coordinates define how much it moves in each direction. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate3d */ (x: CSSLength | CSSPercentage, y: CSSLength | CSSPercentage, z: CSSLength | CSSPercentage): CSSTransformFunction; }>('translate3d'); export const translateX = createFunction<{ /** * The translateX() CSS function moves the element horizontally on the plane. This transformation is characterized by a <length> defining how much it moves horizontally. * * translateX(tx) is a shortcut for translate(tx, 0). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateX */ (x: CSSLength | CSSPercentage): CSSTransformFunction; }>('translateX'); export const translateY = createFunction<{ /** * The translateY() CSS function moves the element vertically on the plane. This transformation is characterized by a <length> defining how much it moves vertically. * * translateY(ty) is a shortcut for translate(0, ty). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateY */ (y: CSSLength | CSSPercentage): CSSTransformFunction; }>('translateY'); export const translateZ = createFunction<{ /** * The translateZ() CSS function moves the element along the z-axis of the 3D space. This transformation is characterized by a <length> defining how much it moves. * * translateZ(tz) is a shorthand for translate3d(0, 0, tz). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translateZ */ (z: CSSLength | CSSPercentage): CSSTransformFunction; }>('translateZ');
the_stack
import React from "react"; import { GridSheet, Renderer, aa2oa, MatrixType, Parser } from "./src"; import { defaultParser } from "./src/parsers/core"; import { defaultRenderer } from "./src/renderers/core"; // import { GridSheet, Renderer, aa2oa } from "../dist"; type Obj = {v: any}; class ObjectRenderer extends Renderer { object(value: Obj): any { return value.v; } stringify(value: Obj): string { return "" + value.v; } } class ObjectParser<T extends Obj> extends Parser { callback(value: any, old: T): T { console.log("callback", old, value, "=>", {...old, v: value}); return {...old, v: value}; } }; class KanjiRenderer extends Renderer { protected kanjiMap: { [s: string]: string } = { "0": "〇", "1": "一", "2": "二", "3": "三", "4": "四", "5": "五", "6": "六", "7": "七", "8": "八", "9": "九", ".": ".", }; number(value: number): string { let kanji = ""; let [int, fraction] = String(value).split("."); for (let i = 0; i < int.length; i++) { const j = int.length - i; if (j % 3 === 0 && i !== 0) { kanji += ","; } kanji += this.kanjiMap[int[i]]; } if (fraction == null) { return kanji; } kanji += "."; for (let i = 0; i < fraction.length; i++) { kanji += this.kanjiMap[fraction[i]]; } return kanji; } } export default { title: "grid sheet", }; const initialData = [ [123456, "b", "c", "d", "e", "aa", "bb", "cc", [1, 2, 3], "ee"], ["a", "b", 789, "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [true, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [false, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [123456, "b", "c", "d", "e", "aa", "bb", "cc", [1, 2, 3], "ee"], ["a", "b", 789, "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [true, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [false, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [123456, "b", "c", "d", "e", "aa", "bb", "cc", [1, 2, 3], "ee"], ["a", "b", 789, "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [true, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [false, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [123456, "b", "c", "d", "e", "aa", "bb", "cc", [1, 2, 3], "ee"], ["a", "b", 789, "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [true, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [false, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [123456, "b", "c", "d", "e", "aa", "bb", "cc", [1, 2, 3], "ee"], ["a", "b", 789, "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ["a", "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [true, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], [false, "b", "c", "d", "e", "aa", "bb", "cc", "dd", "ee"], ]; export const showIndex = () => { const [data, setData] = React.useState<MatrixType>(initialData); React.useEffect(() => { setData([...initialData]); }, []); return ( <> <div>aaaaa</div> <GridSheet data={data} options={{ // cellLabel: false, // headerWidth: 50, headerHeight: 40, historySize: 100, mode: "dark", //stickyHeaders: "horizontal", cells: { default: { style: { fontStyle: "italic" } }, A1: { style: { color: "#008888" } }, B: { fixed: true, label: "ビー" }, D: { width: 300, style: { textAlign: "right" } }, "2": { label: "二", style: { borderBottom: "double 4px #000000" }, renderer: "kanji", }, "3": { height: 100, style: { fontWeight: "bold", color: "#ff0000", backgroundColor: "rgba(255, 200, 200, 0.5)", }, }, "4": { fixed: true, label: "よん", height: 50, verticalAlign: "bottom", }, "5": { height: 100, style: { fontWeight: "bold", color: "#000fff", backgroundColor: "rgba(0, 200, 200, 0.5)", }, }, "6": { height: 100, style: { fontWeight: "bold", color: "#ff0000", backgroundColor: "rgba(255, 200, 200, 0.5)", }, }, }, onSave: (matrix, options, positions) => { console.log( "matrix on save:", aa2oa(matrix || [], ["A", "B", "C", "D", "E", "F"]) ); console.log("positions on save", positions); }, onChange: (matrix, options, positions) => { if (typeof matrix !== "undefined") { console.log("matrix on change:", matrix); } if (typeof options !== "undefined") { console.log("options on change", options); } if (typeof positions !== "undefined") { console.log("positions on change", positions); } }, onSelect: (matrix, options, positions) => { console.log("positions on select", positions) }, renderers: { kanji: new KanjiRenderer(), }, }} /> <br /> <br /> <hr /> {true && ( <table style={{ width: "100%", tableLayout: "fixed" }}> <tbody> <tr> <td> {" "} <GridSheet style={{ maxWidth: "100%", maxHeight: "150px" }} data={[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, "both"], ]} options={{ sheetResize: "both" }} /> </td> <td> {" "} <GridSheet style={{ maxWidth: "100%", maxHeight: "150px" }} data={[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, "vertical"], ]} options={{ sheetResize: "vertical" }} /> </td> </tr> <tr> <td> {" "} <GridSheet style={{ maxWidth: "100%", maxHeight: "150px" }} data={[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, "horizontal"], ]} options={{ sheetResize: "horizontal" }} /> </td> <td> {" "} <GridSheet style={{ maxWidth: "100%", maxHeight: "150px" }} data={[ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, "none"], ]} options={{ sheetResize: "none" }} /> </td> </tr> </tbody> </table> )} <div>object value</div> <GridSheet data={[ [{v: 1}, {v: 2}], [{v: 3}, {v: 4}], [{v: 5}, {v: 6}], [{v: 7}, 8], ]} options={{ cells: { default: { renderer: "obj", parser: "obj", }, B4: { renderer: "default", parser: "default", }, }, renderers: { obj: new ObjectRenderer(), default: defaultRenderer, }, parsers: { obj: new ObjectParser(), default: defaultParser, }, onChange: (matrix, options, positions) => { if (typeof matrix !== "undefined") { console.log("matrix on change:", matrix); } if (typeof options !== "undefined") { console.log("options on change", options); } if (typeof positions !== "undefined") { console.log("positions on change", positions); } }, }} /> </> ); };
the_stack
export declare type TypeAnimationTarget = string | Node | NodeList | HTMLCollection | HTMLElement[] | TypeAnimationTarget[]; export declare type TypeCallbackArgs = [number, number, HTMLElement]; export declare type TypeGeneric = boolean | object | string | number; export declare type TypeCSSLikeKeyframe = { [key: string]: Keyframe & ICSSComputedTransformableProperties; }; export declare type TypeKeyFrameOptionsType = TypeCSSLikeKeyframe | Keyframe[] | PropertyIndexedKeyframes; export declare type TypeCSSPropertyValue = (string | number)[]; export declare type TypeComputedAnimationOptions = TypeGeneric | TypeGeneric[] | TypeKeyFrameOptionsType | KeyframeEffectOptions | ICSSComputedTransformableProperties; export declare type TypeCallback = (index?: number, total?: number, element?: HTMLElement) => TypeComputedAnimationOptions; export declare type TypeAnimationOptionTypes = TypeCallback | TypeComputedAnimationOptions; export declare type TypeComputedOptions = { [key: string]: TypeComputedAnimationOptions; }; export declare type TypeSingleValueCSSProperty = string | number | TypeCSSPropertyValue; /** * CSS properties the `ParseTransformableCSSProperties` can parse */ export interface ICSSTransformableProperties { perspective?: TypeSingleValueCSSProperty | TypeCallback; rotate?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; rotate3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; rotateX?: TypeSingleValueCSSProperty | TypeCallback; rotateY?: TypeSingleValueCSSProperty | TypeCallback; rotateZ?: TypeSingleValueCSSProperty | TypeCallback; translate?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; translate3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; translateX?: TypeSingleValueCSSProperty | TypeCallback; translateY?: TypeSingleValueCSSProperty | TypeCallback; translateZ?: TypeSingleValueCSSProperty | TypeCallback; scale?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; scale3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; scaleX?: TypeSingleValueCSSProperty | TypeCallback; scaleY?: TypeSingleValueCSSProperty | TypeCallback; scaleZ?: TypeSingleValueCSSProperty | TypeCallback; skew?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty> | TypeCallback; skewX?: TypeSingleValueCSSProperty | TypeCallback; skewY?: TypeSingleValueCSSProperty | TypeCallback; opacity?: TypeSingleValueCSSProperty | TypeCallback; } /** * Animation options control how an animation is produced, it shouldn't be too different for those who have used `animejs`, or `jquery`'s animate method. * * @remark * An animation option is an object with keys and values that are computed and passed to the `Animate` class to create animations that match the specified options. */ export interface IAnimationOptions extends ICSSTransformableProperties { /** * Determines the DOM elements to animate. You can pass it a CSS selector, DOM elements, or an Array of DOM Elements and/or CSS Selectors. */ target?: TypeAnimationTarget; /** * Alias of `target` * {@link AnimationOptions.target | target } */ targets?: TypeAnimationTarget; /** * Determines the acceleration curve of your animation. Based on the easings of [easings.net](https://easings.net) * * Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing) * * * | constant | accelerate | decelerate | accelerate-decelerate | * | :--------- | :----------- | :------------- | :-------------------- | * | linear | ease-in / in | ease-out / out | ease-in-out / in-out | * | ease | in-sine | out-sine | in-out-sine | * | steps | in-quad | out-quad | in-out-quad | * | step-start | in-cubic | out-cubic | in-out-cubic | * | step-end | in-quart | out-quart | in-out-quart | * | | in-quint | out-quint | in-out-quint | * | | in-expo | out-expo | in-out-expo | * | | in-circ | out-circ | in-out-circ | * | | in-back | out-back | in-out-back | * * You can create your own custom cubic-bezier easing curves. Similar to css you type `cubic-bezier(...)` with 4 numbers representing the shape of the bezier curve, for example, `cubic-bezier(0.47, 0, 0.745, 0.715)` this is the bezier curve for `in-sine`. * * *Note: the `easing` property supports the original values and functions for easing as well, for example, `steps(1)`, and etc... are supported.* * * *Note: you can also use camelCase when defining easing functions, e.g. `inOutCubic` to represent `in-out-cubic`* * * @example * ```ts * // cubic-bezier easing * animate({ * target: ".div", * easing: "cubic-bezier(0.47, 0, 0.745, 0.715)", * * // or * easing: "in-sine", * * // or * easing: "inSine", * * transform: ["translate(0px)", "translate(500px)"], * }); * ``` */ easing?: TypeCallback | string | string[]; /** * Determines the duration of your animation in milliseconds. By passing it a callback, you can define a different duration for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. * * @example * ```ts * // First element fades out in 1s, second element in 2s, etc. * animate({ * target: ".div", * easing: "linear", * duration: 1000, * // or * duration: (index) => (index + 1) * 1000, * opacity: [1, 0], * }); * ``` */ duration?: number | string | TypeCallback; /** * Determines the delay of your animation in milliseconds. By passing it a callback, you can define a different delay for each element. The callback takes the index of each element, the target dom element, and the total number of target elements as its argument and returns a number. * * @example * ```ts * // First element starts fading out after 1s, second element after 2s, etc. * animate({ * target: ".div", * easing: "linear", * delay: 5, * // or * delay: (index) => (index + 1) * 1000, * opacity: [1, 0], * }); * ``` */ delay?: number | TypeCallback; /** * Adds an offset ammount to the `delay`, for creating a timeline similar to `animejs` */ timelineOffset?: number | TypeCallback; /** * Similar to delay but it indicates the number of milliseconds to delay **after** the full animation has played **not before**. * * _**Note**: `endDelay` will delay the `onfinish` method and event, but will not reserve the current state of the CSS animation, if you need to use endDelay you may need to use the `fillMode` property to reserve the changes to the animation target._ * @example * ```ts * // First element fades out but then after 1s finishes, the second element after 2s, etc. * animate({ * target: ".div", * easing: "linear", * endDelay: 1000, * // or * endDelay: (index) => (index + 1) * 1000, * opacity: [1, 0], * }); * ``` */ endDelay?: number | TypeCallback; /** * * This ensures all `animations` match up to the total duration, and don't finish too early, if animations finish too early when the `.play()` method is called specific animations that are finished will restart while the rest of the animations will continue playing. * * _**Note**: you cannot use the `padEndDelay` option and set a value for `endDelay`, the `endDelay` value will replace the padded endDelay_ */ padEndDelay?: Boolean; /** * Determines if the animation should repeat, and how many times it should repeat. * * @example * ```ts * // Loop forever * animate({ * target: ".div", * easing: "linear", * loop: true, // If you want it to continously loop * // or * // loop: 5, // If you want the animation to loop 5 times * opacity: [1, 0], * }); * ``` */ loop?: number | boolean | TypeCallback; /** * Occurs when the animation for one of the targets completes, meaning when animating many targets that finish at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. * * The animation argument represents the animation for the current target. * * @param element - the current target element * @param index - the index of the current target element in `Animate.prototype.targets` * @param total - the total number of target elements * @param animation - the animation of the current target element * * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. */ onfinish?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void; /** * Occurs when the animation for one of the targets is cancelled, meaning when animating many targets that are cancelled at different times this will run multiple times. The arguments it takes is slightly different from the rest of the animation options. * * The animation argument represents the animation for the current target. * * @param element - the current target element * @param index - the index of the current target element in `Animate.prototype.targets` * @param total - the total number of target elements * @param animation - the animation of the current target element * * * **Warning**: the order of the callback's arguments are in a different order, with the target element first, and the index second. */ oncancel?: (element?: HTMLElement, index?: number, total?: number, animation?: Animation) => void; /** * * Determines if the animation should automatically play immediately after being instantiated. */ autoplay?: boolean; /** * Determines the direction of the animation; * - `reverse` runs the animation backwards, * - `alternate` switches direction after each iteration if the animation loops. * - `alternate-reverse` starts the animation at what would be the end of the animation if the direction were * - `normal` but then when the animation reaches the beginning of the animation it alternates going back to the position it started at. */ direction?: PlaybackDirection; /** * Determines the animation playback rate. Useful in the authoring process to speed up some parts of a long sequence (value above 1) or slow down a specific animation to observe it (value between 0 to 1). * * _**Note**: negative numbers reverse the animation._ */ speed?: number | TypeCallback; /** * Defines how an element should look after the animation. * * @remark * fillMode of: * - `none` means the animation's effects are only visible while the animation is playing. * - `forwards` the affected element will continue to be rendered in the state of the final animation frame. * - `backwards` the animation's effects should be reflected by the element(s) state prior to playing. * - `both` combining the effects of both forwards and backwards; The animation's effects should be reflected by the element(s) state prior to playing and retained after the animation has completed playing. * - `auto` if the animation effect fill mode is being applied to is a keyframe effect. "auto" is equivalent to "none". Otherwise, the result is "both". * * You can learn more here on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill). * _Be careful when using fillMode, it has some problems when it comes to concurrency of animations read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill), if browser support were better I would remove fillMode and use Animation.commitStyles, I'll have to change the way `fillMode` functions later. Use the onfinish method to commit styles [onfinish](#onfinish)._ */ fillMode?: FillMode; /** * Another way to input options for an animation, it's also used to chain animations. * * @remarks * The `options` animation option is another way to declare options, it can take an instance of `Animate`, a single `Animate` instance in an Array, e.g. `[Animate]` or an object containing animation options. * * * `options` extends the animation properties of an animation, but more importance is given to the actual animation options object, so, the properties from `options` will be ignored if there is already an animation option with the same name declared. * * * _**Note**: you can't use this property as a method._ * * @example * ```ts * (async () => { * // animate is Promise-like, as in it has a then() method like a Promise but it isn't a Promise. * // animate resolves to an Array that contains the Animate instance, e.g. [Animate] * let [options] = await animate({ * target: ".div", * opacity: [0, 1], * }); * * animate({ * options, * * // opacity overrides the opacity property from `options` * opacity: [1, 0], * }); * * console.log(options); //= Animate * })(); * * // or * (async () => { * let options = await animate({ * target: ".div", * opacity: [0, 1], * duration: 2000, * * }); * * // Remeber, the `options` animation option can handle Arrays with an Animate instance, e.g. [Animate] * // Also, remeber that Animate resolves to an Arrays with an Animate instance, e.g. [Animate] * // Note: the `options` animation option can only handle one Animate instance in an Array and that is alway the first element in the Array * animate({ * options, * opacity: [1, 0], * }); * * console.log(options); //= [Animate] * })(); * * // or * (async () => { * let options = { * target: ".div", * opacity: [0, 1], * }; * * await animate(options); * animate({ * options, * opacity: [1, 0], * }); * * console.log(options); //= { ... } * })(); * ``` */ options?: IAnimationOptions; /** * Contols the starting point of certain parts of an animation * * @remark * The offset of the keyframe specified as a number between `0.0` and `1.0` inclusive or null. This is equivalent to specifying start and end states in percentages in CSS stylesheets using @keyframes. If this value is null or missing, the keyframe will be evenly spaced between adjacent keyframes. * * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats) * * @example * ```ts * animate({ * duration: 2000, * opacity: [ 0, 0.9, 1 ], * easing: [ 'ease-in', 'ease-out' ], * * offset: [ "from", 0.8 ], // Shorthand for [ 0, 0.8, 1 ] * // or * offset: [ 0, "80%", "to" ], // Shorthand for [ 0, 0.8, 1 ] * // or * offset: [ "0", "0.8", "to" ], // Shorthand for [ 0, 0.8, 1 ] * }); * ``` */ offset?: (number | string)[] | TypeCallback; /** * Represents the timeline of animation. It exists to pass timeline features to Animations (default is [DocumentTimeline](https://developer.mozilla.org/en-US/docs/Web/API/DocumentTimeline)). * * As of right now it doesn't contain any features but in the future when other timelines like the [ScrollTimeline](https://drafts.csswg.org/scroll-animations-1/#scrolltimeline), read the Google Developer article for [examples and demos of ScrollTimeLine](https://developers.google.com/web/updates/2018/10/animation-worklet#hooking_into_the_space-time_continuum_scrolltimeline) */ timeline?: AnimationTimeline; /** * Allows you to manually set keyframes using a `keyframe` array * * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) * * @remark * An `array` of objects (keyframes) consisting of properties and values to iterate over. This is the canonical format returned by the [getKeyframes()](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/getKeyframes) method. * * @example * ```ts * element.animate([ * { // from * opacity: 0, * color: "#fff" * }, * { // to * opacity: 1, * color: "#000" * } * ], 2000); * ``` * * Offsets for each keyframe can be specified by providing an `offset` value. * @example * ```ts * element.animate([ { opacity: 1 }, * { opacity: 0.1, offset: 0.7 }, * { opacity: 0 } ], * 2000); * ``` * * _**Note**: `offset` values, if provided, must be between 0.0 and 1.0 (inclusive) and arranged in ascending order._ * * It is not necessary to specify an offset for every keyframe. Keyframes without a specified offset will be evenly spaced between adjacent keyframes. * * --- * * The easing to apply between keyframes can be specified by providing an easing `value` as illustrated below. * * _**Note**: the values for easing in keyframes are limited to "ease", "ease-in", "ease-out", "ease-in-out", "linear", "steps(...)", and "cubic-bezier(...)", to get access to the predefined {@link EASINGS | easings}, you will need to use the function {@link GetEase}._ * @example * ```ts * element.animate([ { opacity: 1, easing: 'ease-out' }, * { opacity: 0.1, easing: 'ease-in' }, * { opacity: 0 } ], * 2000); * ``` * * In this example, the specified easing only applies from the keyframe where it is specified until the next keyframe. Any easing value specified on the options argument, however, applies across a single iteration of the animation — for the entire duration. * * * `@okikio/animate` also offers another format called `CSSLikeKeyframe`, * it basically functions the same way CSS `@keyframe` functions * * @example * ```ts * animate({ * keyframes: { * "from, 50%, to": { * opacity: 1 * }, * * "25%, 0.7": { * opacity: 0 * } * } * }) * // Results in a keyframe array like this * //= [ * //= { opacity: 1, offset: 0 }, * //= { opacity: 0, offset: 0.25 }, * //= { opacity: 1, offset: 0.5 }, * //= { opacity: 0, offset: 0.7 }, * //= { opacity: 1, offset: 1 } * //= ] * ``` */ keyframes?: TypeCSSLikeKeyframe | ICSSComputedTransformableProperties[] & Keyframe[] | object[] | TypeCallback; /** * The `composite` property of a `KeyframeEffect` resolves how an element's animation impacts its underlying property values. * * To understand these values, take the example of a `keyframeEffect` value of `blur(2)` working on an underlying property value of `blur(3)`. * - `replace` - The keyframeEffect overrides the underlying value it is combined with: `blur(2)` replaces `blur(3)`. * - `add` - The keyframeEffect is added to the underlying value with which it is combined (aka additive): `blur(2) blur(3)`. * - `accumulate` - The keyframeEffect is accumulated on to the underlying value: `blur(5)`. * * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite) * * I recommend reading [web.dev](https://web.dev)'s article on [web-animations](https://web.dev/web-animations/#smoother-animations-with-composite-modes). */ composite?: TypeCallback | string; /** * The properties of the `extend` animation option are not interperted or computed, they are given directly to the `Web Animation API`, as way to access features that haven't been implemented in `@okikio/animate`, for example, `iterationStart`. * * `extend` is supposed to future proof the library if new features are added to the `Web Animation API` that you want to use, but that has not been implemented yet. * * _**Note**: it doesn't allow for declaring actual animation keyframes; it's just for animation timing options, and it overrides all other animation timing options that accomplish the same goal, e.g. `loop` & `iterations`, if `iterations` is a property of `extend` then `iterations` will override `loop`._ * * @example * ```ts * animate({ * target: ".div", * opacity: [0, 1], * loop: 5, * extend: { * iterationStart: 0.5, * // etc... * fill: "both", // This overrides fillMode * iteration: 2, // This overrides loop * } * }); * ``` */ extend?: KeyframeEffectOptions | TypeCallback; /** * Theses are the CSS properties to be animated as Keyframes * * Read more on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/setKeyframes) * * @remark * An `object` containing key-value pairs consisting of the property to animate and an `array` of values to iterate over. * * @example * ```ts * element.animate({ * opacity: [ 0, 1 ], // [ from, to ] * color: [ "#fff", "#000" ] // [ from, to ] * }, 2000); * ``` * * Using this format, the number of elements in each array does not need to be equal. The provided values will be spaced out independently. * @example * ```ts * element.animate({ * opacity: [ 0, 1 ], // offset: 0, 1 * backgroundColor: [ "red", "yellow", "green" ], // offset: 0, 0.5, 1 * }, 2000); * ``` * * The special keys `offset`, `easing`, and `composite` (described below) may be specified alongside the property values. * @example * ```ts * element.animate({ * opacity: [ 0, 0.9, 1 ], * offset: [ 0, 0.8 ], // Shorthand for [ 0, 0.8, 1 ] * easing: [ 'ease-in', 'ease-out' ], * }, 2000); * ``` * * After generating a suitable set of keyframes from the property value lists, each supplied offset is applied to the corresponding keyframe. If there are insufficient values, or if the list contains `null` values, the keyframes without specified offsets will be evenly spaced as with the array format described above. * * If there are too few `easing` or `composite` values, the corresponding list will be repeated as needed. * * _**Note**: to use `composite` you will need to add it to the {@link AnimationOptions.extend | extend} object as an option_ */ [property: string]: TypeAnimationOptionTypes; } export declare type TypeAnimationEvents = "update" | "play" | "pause" | "begin" | "cancel" | "finish" | "error" | "stop" | "playstate-change"; export declare type TypePlayStates = "idle" | "running" | "paused" | "finished"; /** * CSS properties */ export interface ICSSProperties { [key: string]: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; } /** * After being computed as an animation option */ export interface ICSSComputedTransformableProperties extends ICSSProperties { perspective?: TypeSingleValueCSSProperty; rotate?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; rotate3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; rotateX?: TypeSingleValueCSSProperty; rotateY?: TypeSingleValueCSSProperty; rotateZ?: TypeSingleValueCSSProperty; translate?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; translate3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; translateX?: TypeSingleValueCSSProperty; translateY?: TypeSingleValueCSSProperty; translateZ?: TypeSingleValueCSSProperty; scale?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; scale3d?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; scaleX?: TypeSingleValueCSSProperty; scaleY?: TypeSingleValueCSSProperty; scaleZ?: TypeSingleValueCSSProperty; skew?: TypeSingleValueCSSProperty | Array<TypeSingleValueCSSProperty>; skewX?: TypeSingleValueCSSProperty; skewY?: TypeSingleValueCSSProperty; }
the_stack
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { InputDialog } from '@jupyterlab/apputils'; import { CodeMirrorEditor } from '@jupyterlab/codemirror'; import { URLExt } from '@jupyterlab/coreutils'; import { IDocumentManager } from '@jupyterlab/docmanager'; import { IEditorTracker } from '@jupyterlab/fileeditor'; import { INotebookTracker } from '@jupyterlab/notebook'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; import { ITranslator, TranslationBundle } from '@jupyterlab/translation'; import { LabIcon } from '@jupyterlab/ui-components'; import { CodeJumper, FileEditorJumper, NotebookJumper } from '@krassowski/code-jumpers'; import { AnyLocation } from 'lsp-ws-connection/lib/types'; import type * as lsp from 'vscode-languageserver-protocol'; import jumpToSvg from '../../style/icons/jump-to.svg'; import { CodeJump as LSPJumpSettings, ModifierKey } from '../_jump_to'; import { CommandEntryPoint } from '../command_manager'; import { PositionConverter } from '../converter'; import { CodeMirrorIntegration } from '../editor_integration/codemirror'; import { FeatureSettings, IFeatureCommand, IFeatureLabIntegration } from '../feature'; import { IVirtualPosition, ProtocolCoordinates } from '../positioning'; import { ILSPAdapterManager, ILSPFeatureManager, PLUGIN_ID } from '../tokens'; import { getModifierState, uri_to_contents_path, uris_equal } from '../utils'; import { CodeMirrorVirtualEditor } from '../virtual/codemirror_editor'; export const jumpToIcon = new LabIcon({ name: 'lsp:jump-to', svgstr: jumpToSvg }); const jumpBackIcon = new LabIcon({ name: 'lsp:jump-back', svgstr: jumpToSvg.replace('jp-icon3', 'lsp-icon-flip-x jp-icon3') }); const FEATURE_ID = PLUGIN_ID + ':jump_to'; let trans: TranslationBundle; const enum JumpResult { NoTargetsFound = 1, PositioningFailure = 2, PathResolutionFailure = 3, AssumeSuccess = 4, UnspecifiedFailure = 5, AlreadyAtTarget = 6 } export class CMJumpToDefinition extends CodeMirrorIntegration { get jumper() { return (this.feature.labIntegration as JumperLabIntegration).jumper; } get settings() { return super.settings as FeatureSettings<LSPJumpSettings>; } protected get modifierKey(): ModifierKey { return this.settings.composite.modifierKey; } register() { this.editor_handlers.set( 'mousedown', this._jumpToDefinitionOrRefernce.bind(this) ); super.register(); } private _jumpToDefinitionOrRefernce( virtual_editor: CodeMirrorVirtualEditor, event: MouseEvent ) { const { button } = event; const shouldJump = button === 0 && getModifierState(event, this.modifierKey); if (!shouldJump) { return; } let root_position = this.position_from_mouse(event); if (root_position == null) { this.console.warn( 'Could not retrieve root position from mouse event to jump to definition/reference' ); return; } let document = virtual_editor.document_at_root_position(root_position); let virtual_position = virtual_editor.root_position_to_virtual_position(root_position); const positionParams: lsp.TextDocumentPositionParams = { textDocument: { uri: document.document_info.uri }, position: { line: virtual_position.line, character: virtual_position.ch } }; this.connection.clientRequests['textDocument/definition'] .request(positionParams) .then(targets => { this.handleJump(targets, positionParams) .then((result: JumpResult | undefined) => { if ( result === JumpResult.NoTargetsFound || result === JumpResult.AlreadyAtTarget ) { // definition was not found, or we are in definition already, suggest references this.connection.clientRequests['textDocument/references'] .request({ ...positionParams, context: { includeDeclaration: false } }) .then(targets => // TODO: explain that we are now presenting references? this.handleJump(targets, positionParams) ) .catch(this.console.warn); } }) .catch(this.console.warn); }) .catch(this.console.warn); event.preventDefault(); event.stopPropagation(); } private _harmonizeLocations(locationData: AnyLocation): lsp.Location[] { if (locationData == null) { return []; } const locationsList = Array.isArray(locationData) ? locationData : [locationData]; return (locationsList as (lsp.Location | lsp.LocationLink)[]) .map((locationOrLink): lsp.Location | undefined => { if ('targetUri' in locationOrLink) { return { uri: locationOrLink.targetUri, range: locationOrLink.targetRange }; } else if ('uri' in locationOrLink) { return { uri: locationOrLink.uri, range: locationOrLink.range }; } else { this.console.warn( 'Returned jump location is incorrect (no uri or targetUri):', locationOrLink ); return undefined; } }) .filter((location): location is lsp.Location => location != null); } private async _chooseTarget(locations: lsp.Location[]) { if (locations.length > 1) { const choices = locations.map(location => { // TODO: extract the line, the line above and below, and show it const path = this._resolvePath(location.uri) || location.uri; return path + ', line: ' + location.range.start.line; }); // TODO: use selector with preview, basically needes the ui-component // from jupyterlab-citation-manager; let's try to move it to JupyterLab core // (and re-implement command palette with it) // the preview should use this.jumper.document_manager.services.contents let getItemOptions = { title: trans.__('Choose the jump target'), okLabel: trans.__('Jump'), items: choices }; // TODO: use showHints() or completion-like widget instead? const choice = await InputDialog.getItem(getItemOptions).catch( this.console.warn ); if (!choice || choice.value == null) { this.console.warn('No choice selected for jump location selection'); return; } const choiceIndex = choices.indexOf(choice.value); if (choiceIndex === -1) { this.console.error( 'Choice selection error: please report this as a bug:', choices, choice ); return; } return locations[choiceIndex]; } else { return locations[0]; } } private _resolvePath(uri: string): string | null { let contentsPath = uri_to_contents_path(uri); if (contentsPath == null) { if (uri.startsWith('file://')) { contentsPath = decodeURIComponent(uri.slice(7)); } else { contentsPath = decodeURIComponent(uri); } } return contentsPath; } async handleJump( locationData: AnyLocation, positionParams: lsp.TextDocumentPositionParams ) { const locations = this._harmonizeLocations(locationData); const targetInfo = await this._chooseTarget(locations); if (!targetInfo) { this.setStatusMessage(trans.__('No jump targets found'), 2 * 1000); return JumpResult.NoTargetsFound; } let { uri, range } = targetInfo; let virtual_position = PositionConverter.lsp_to_cm( range.start ) as IVirtualPosition; if (uris_equal(uri, positionParams.textDocument.uri)) { let editor_index = this.adapter.get_editor_index_at(virtual_position); // if in current file, transform from the position within virtual document to the editor position: let editor_position = this.virtual_editor.transform_virtual_to_editor(virtual_position); if (editor_position === null) { this.console.warn( 'Could not jump: conversion from virtual position to editor position failed', virtual_position ); return JumpResult.PositioningFailure; } let editor_position_ce = PositionConverter.cm_to_ce(editor_position); this.console.log(`Jumping to ${editor_index}th editor of ${uri}`); this.console.log('Jump target within editor:', editor_position_ce); let contentsPath = this.adapter.widget.context.path; const didUserChooseThis = locations.length > 1; // note: we already know that URIs are equal, so just check the position range if ( !didUserChooseThis && ProtocolCoordinates.isWithinRange(positionParams.position, range) ) { return JumpResult.AlreadyAtTarget; } this.jumper.global_jump({ line: editor_position_ce.line, column: editor_position.ch, editor_index: editor_index, is_symlink: false, contents_path: contentsPath }); return JumpResult.AssumeSuccess; } else { // otherwise there is no virtual document and we expect the returned position to be source position: let source_position_ce = PositionConverter.cm_to_ce(virtual_position); this.console.log(`Jumping to external file: ${uri}`); this.console.log('Jump target (source location):', source_position_ce); let jump_data = { editor_index: 0, line: source_position_ce.line, column: source_position_ce.column }; // assume that we got a relative path to a file within the project // TODO use is_relative() or something? It would need to be not only compatible // with different OSes but also with JupyterHub and other platforms. // can it be resolved vs our guessed server root? const contentsPath = this._resolvePath(uri); if (contentsPath === null) { this.console.warn('contents_path could not be resolved'); return JumpResult.PathResolutionFailure; } try { await this.jumper.document_manager.services.contents.get(contentsPath, { content: false }); this.jumper.global_jump({ contents_path: contentsPath, ...jump_data, is_symlink: false }); return JumpResult.AssumeSuccess; } catch (err) { this.console.warn(err); } this.jumper.global_jump({ contents_path: URLExt.join('.lsp_symlink', contentsPath), ...jump_data, is_symlink: true }); return JumpResult.AssumeSuccess; } } } class JumperLabIntegration implements IFeatureLabIntegration { private adapterManager: ILSPAdapterManager; private jumpers: Map<string, CodeJumper>; settings: FeatureSettings<any>; constructor( settings: FeatureSettings<any>, adapterManager: ILSPAdapterManager, notebookTracker: INotebookTracker, documentManager: IDocumentManager, fileEditorTracker: IEditorTracker | null ) { this.settings = settings; this.adapterManager = adapterManager; this.jumpers = new Map(); if (fileEditorTracker !== null) { fileEditorTracker.widgetAdded.connect((sender, widget) => { let fileEditor = widget.content; if (fileEditor.editor instanceof CodeMirrorEditor) { let jumper = new FileEditorJumper(widget, documentManager); this.jumpers.set(widget.id, jumper); } }); } notebookTracker.widgetAdded.connect(async (sender, widget) => { // NOTE: assuming that the default cells content factory produces CodeMirror editors(!) let jumper = new NotebookJumper(widget, documentManager); this.jumpers.set(widget.id, jumper); }); } get jumper(): CodeJumper { let current = this.adapterManager.currentAdapter.widget.id; return this.jumpers.get(current)!; } } const COMMANDS = (trans: TranslationBundle): IFeatureCommand[] => [ { id: 'jump-to-definition', execute: async ({ connection, virtual_position, document, features }) => { const jumpFeature = features.get(FEATURE_ID) as CMJumpToDefinition; if (!connection) { jumpFeature.setStatusMessage( trans.__('Connection not found for jump'), 2 * 1000 ); return; } const positionParams: lsp.TextDocumentPositionParams = { textDocument: { uri: document.document_info.uri }, position: { line: virtual_position.line, character: virtual_position.ch } }; const targets = await connection.clientRequests[ 'textDocument/definition' ].request(positionParams); await jumpFeature.handleJump(targets, positionParams); }, is_enabled: ({ connection }) => connection ? connection.provides('definitionProvider') : false, label: trans.__('Jump to definition'), icon: jumpToIcon }, { id: 'jump-to-reference', execute: async ({ connection, virtual_position, document, features }) => { const jumpFeature = features.get(FEATURE_ID) as CMJumpToDefinition; if (!connection) { jumpFeature.setStatusMessage( trans.__('Connection not found for jump'), 2 * 1000 ); return; } const positionParams: lsp.TextDocumentPositionParams = { textDocument: { uri: document.document_info.uri }, position: { line: virtual_position.line, character: virtual_position.ch } }; const targets = await connection.clientRequests[ 'textDocument/references' ].request({ ...positionParams, context: { includeDeclaration: false } }); await jumpFeature.handleJump(targets, positionParams); }, is_enabled: ({ connection }) => connection ? connection.provides('referencesProvider') : false, label: trans.__('Jump to references'), icon: jumpToIcon }, { id: 'jump-back', execute: async ({ connection, virtual_position, document, features }) => { const jump_feature = features.get(FEATURE_ID) as CMJumpToDefinition; jump_feature.jumper.global_jump_back(); }, is_enabled: ({ connection }) => connection ? connection.provides('definitionProvider') || connection.provides('referencesProvider') : false, label: trans.__('Jump back'), icon: jumpBackIcon, // do not attach to any of the context menus attach_to: new Set<CommandEntryPoint>() } ]; export const JUMP_PLUGIN: JupyterFrontEndPlugin<void> = { id: FEATURE_ID, requires: [ ILSPFeatureManager, ISettingRegistry, ILSPAdapterManager, INotebookTracker, IDocumentManager, ITranslator ], optional: [IEditorTracker], autoStart: true, activate: ( app: JupyterFrontEnd, featureManager: ILSPFeatureManager, settingRegistry: ISettingRegistry, adapterManager: ILSPAdapterManager, notebookTracker: INotebookTracker, documentManager: IDocumentManager, translator: ITranslator, fileEditorTracker: IEditorTracker | null ) => { const settings = new FeatureSettings(settingRegistry, FEATURE_ID); trans = translator.load('jupyterlab-lsp'); let labIntegration = new JumperLabIntegration( settings, adapterManager, notebookTracker, documentManager, fileEditorTracker ); featureManager.register({ feature: { editorIntegrationFactory: new Map([ ['CodeMirrorEditor', CMJumpToDefinition] ]), commands: COMMANDS(trans), id: FEATURE_ID, name: 'Jump to definition', labIntegration: labIntegration, settings: settings, capabilities: { textDocument: { declaration: { dynamicRegistration: true, linkSupport: true }, definition: { dynamicRegistration: true, linkSupport: true }, typeDefinition: { dynamicRegistration: true, linkSupport: true }, implementation: { dynamicRegistration: true, linkSupport: true } } } } }); } };
the_stack
import { flags } from "@oclif/command"; import { table } from "table"; import { GraphQLSchema, introspectionFromSchema, printSchema } from "graphql"; import chalk from "chalk"; import envCi from "env-ci"; import { gitInfo } from "../../git"; import { ProjectCommand } from "../../Command"; import { CompactRenderer, pluralize, validateHistoricParams } from "../../utils"; import { ChangeSeverity, CheckPartialSchema_service_checkPartialSchema_checkSchemaResult, CheckSchema_service_checkSchema, CheckSchema_service_checkSchema_diffToPrevious_changes as Change, CheckSchemaVariables, IntrospectionSchemaInput } from "apollo-language-server/lib/graphqlTypes"; import { ApolloConfig } from "apollo-language-server"; import moment from "moment"; import sortBy from "lodash.sortby"; import { graphUndefinedError } from "../../utils/sharedMessages"; const formatChange = (change: Change) => { let color = (x: string): string => x; if (change.severity === ChangeSeverity.FAILURE) { color = chalk.red; } const changeDictionary: Record<ChangeSeverity, string> = { [ChangeSeverity.FAILURE]: "FAIL", [ChangeSeverity.NOTICE]: "PASS" }; return { severity: color(changeDictionary[change.severity]), code: color(change.code), description: color(change.description) }; }; export function formatTimePeriod(hours: number): string { if (hours <= 24) { return pluralize(hours, "hour"); } return pluralize(Math.floor(hours / 24), "day"); } type CompositionErrors = Array<{ service?: string; field?: string; message: string; }>; interface TasksOutput { config: ApolloConfig; checkSchemaResult: | CheckSchema_service_checkSchema | CheckPartialSchema_service_checkPartialSchema_checkSchemaResult; shouldOutputJson: boolean; shouldOutputMarkdown: boolean; shouldAlwaysExit0: boolean; federationSchemaHash?: string; serviceName: string | undefined; compositionErrors?: CompositionErrors; graphCompositionID?: string; } export function formatMarkdown({ checkSchemaResult, graphName, serviceName, tag, graphCompositionID }: { checkSchemaResult: CheckSchema_service_checkSchema; graphName: string; serviceName?: string | undefined; tag: string; // this will only exist for federated schema check graphCompositionID: string | undefined; }): string { const { diffToPrevious } = checkSchemaResult; if (!diffToPrevious) { throw new Error("checkSchemaResult.diffToPrevious missing"); } const { validationConfig } = diffToPrevious; let validationText = ""; if (validationConfig) { // The validationConfig will always return a negative number. Use Math.abs to make it positive. const hours = Math.abs( moment() .add(validationConfig.from, "second") .diff(moment().add(validationConfig.to, "second"), "hours") ); validationText = `🔢 Compared **${pluralize( diffToPrevious.changes.length, "schema change" )}** against **${pluralize( diffToPrevious.numberOfCheckedOperations, "operation" )}** seen over the **last ${formatTimePeriod(hours)}**.`; } const breakingChanges = diffToPrevious.changes.filter( change => change.severity === "FAILURE" ); const affectedQueryCount = diffToPrevious.affectedQueries ? diffToPrevious.affectedQueries.length : 0; return ` ### Apollo Service Check 🔄 Validated your local schema against metrics from variant \`${tag}\` ${ serviceName ? `for graph \`${serviceName}\` ` : "" }on graph \`${graphName}@${tag}\`. ${validationText} ${ breakingChanges.length > 0 ? `❌ Found **${pluralize( diffToPrevious.changes.filter(change => change.severity === "FAILURE") .length, "breaking change" )}** that would affect **${pluralize( affectedQueryCount, "operation" )}** across **${pluralize( diffToPrevious.affectedClients && diffToPrevious.affectedClients.length, "client" )}**` : diffToPrevious.changes.length === 0 ? `✅ Found **no changes**.` : `✅ Found **no breaking changes**.` } 🔗 [View your service check details](${checkSchemaResult.targetUrl + (graphCompositionID ? `?graphCompositionId=${graphCompositionID})` : `)`)}. `; } export function formatCompositionErrorsMarkdown({ compositionErrors, graphName, serviceName, tag }: { compositionErrors: CompositionErrors; graphName: string; serviceName: string; tag: string; }): string { return ` ### Apollo Service Check 🔄 Validated graph composition for service \`${serviceName}\` on graph \`${graphName}@${tag}\`. ❌ Found **${compositionErrors.length} composition errors** | Service | Field | Message | | --------- | --------- | --------- | ${compositionErrors .map( ({ service, field, message }) => `| ${service} | ${field} | ${message} |` ) .join("\n")} `; } export function formatHumanReadable({ checkSchemaResult, graphCompositionID }: { checkSchemaResult: CheckSchema_service_checkSchema; // this will only exist for federated schema check graphCompositionID: string | undefined; }): string { const { targetUrl, diffToPrevious: { changes } } = checkSchemaResult; let result = ""; if (changes.length === 0) { result = "\nNo changes present between schemas"; } else { // Create a sorted list of the changes. We'll then filter values from the sorted list, resulting in sorted // filtered lists. const sortedChanges = sortBy<typeof changes[0]>(changes, [ change => change.code, change => change.description ]); const breakingChanges = sortedChanges.filter( change => change.severity === ChangeSeverity.FAILURE ); sortBy(breakingChanges, change => change.severity); const nonBreakingChanges = sortedChanges.filter( change => change.severity !== ChangeSeverity.FAILURE ); result += table([ ["Change", "Code", "Description"], ...[ ...breakingChanges.map(formatChange).map(Object.values), // Add an empty line between, but only if there are both breaking changes and non-breaking changes. // nonBreakingChanges.length && breakingChanges.length ? {} : null, ...nonBreakingChanges.map(formatChange).map(Object.values) ].filter(Boolean) ]); } if (targetUrl) { result += `\n\nView full details at: ${targetUrl}${ graphCompositionID ? `?graphCompositionId=${graphCompositionID}` : `` }`; } return result; } export default class ServiceCheck extends ProjectCommand { static aliases = ["schema:check"]; static description = "[DEPRECATED] Check a service against known operation workloads to find breaking changes" + ProjectCommand.DEPRECATION_MSG; static flags = { ...ProjectCommand.flags, tag: flags.string({ char: "t", description: "[Deprecated: please use --variant instead] The tag (AKA variant) to check the proposed schema against", hidden: true, exclusive: ["variant"] }), variant: flags.string({ char: "v", description: "The variant to check the proposed schema against", exclusive: ["tag"] }), graph: flags.string({ char: "g", description: "The ID of the graph in Apollo to check your proposed schema changes against. Overrides config file if set." }), branch: flags.string({ description: "The branch name to associate with this check" }), commitId: flags.string({ description: "The SHA-1 hash of the commit to associate with this check" }), author: flags.string({ description: "The author to associate with this proposed schema" }), validationPeriod: flags.string({ description: "The size of the time window with which to validate the schema against. You may provide a number (in seconds), or an ISO8601 format duration for more granularity (see: https://en.wikipedia.org/wiki/ISO_8601#Durations)" }), queryCountThreshold: flags.integer({ description: "Minimum number of requests within the requested time window for a query to be considered." }), queryCountThresholdPercentage: flags.integer({ description: "Number of requests within the requested time window for a query to be considered, relative to total request count. Expected values are between 0 and 0.05 (minimum 5% of total request volume)" }), json: flags.boolean({ description: "Output result in json, which can then be parsed by CLI tools such as jq.", exclusive: ["markdown"] }), localSchemaFile: flags.string({ description: "Path to one or more local GraphQL schema file(s), as introspection result or SDL. Supports comma-separated list of paths (ex. `--localSchemaFile=schema.graphql,extensions.graphql`)" }), markdown: flags.boolean({ description: "Output result in markdown.", exclusive: ["json"] }), serviceName: flags.string({ description: "Provides the name of the implementing service for a federated graph. This flag will indicate that the schema is a partial schema from a federated service" }), ignoreFailures: flags.boolean({ description: "Exit with status 0 when the check completes, even if errors are found" }) }; async run() { this.printDeprecationWarning(); // @ts-ignore we're going to populate `taskOutput` later const taskOutput: TasksOutput = {}; // Define this constant so we can throw it and compare against the same value. const breakingChangesErrorMessage = "breaking changes found"; const federatedServiceCompositionUnsuccessfulErrorMessage = "Federated service composition was unsuccessful. Please see the reasons below."; const { isCi } = envCi(); let schema: GraphQLSchema | undefined; let graphID: string | undefined; let graphVariant: string | undefined; try { await this.runTasks<TasksOutput>( ({ config, flags, project }) => { /** * Name of the graph being checked. `engine` is an example of a graph. * * A graph can be either a monolithic schema or the result of composition a federated schema. */ graphID = config.graph; graphVariant = config.variant; /** * Name of the implementing service being checked. * * This is optional because this check can be run on a graph or on an implementing service. */ const serviceName: string | undefined = flags.serviceName; if (!graphID) { throw graphUndefinedError; } const graphSpecifier = `${graphID}@${graphVariant}`; // Add some fields to output that are required for post-processing taskOutput.shouldOutputJson = !!flags.json; taskOutput.shouldOutputMarkdown = !!flags.markdown; taskOutput.shouldAlwaysExit0 = !!flags.ignoreFailures; taskOutput.serviceName = flags.serviceName; taskOutput.config = config; return [ { enabled: () => !!serviceName, title: `Validate graph composition for service ${chalk.cyan( serviceName || "" )} on graph ${chalk.cyan(graphSpecifier)}`, task: async (ctx: TasksOutput, task) => { if (!serviceName) { throw new Error( "This task should not be run without a `serviceName`. Check the `enabled` function." ); } task.output = "Fetching local service's partial schema"; const sdl = await project.resolveFederatedServiceSDL(); if (!sdl) { throw new Error("No SDL found for federated service"); } task.output = `Attempting to compose graph with ${chalk.cyan( serviceName )} service's partial schema`; const historicParameters = validateHistoricParams({ validationPeriod: flags.validationPeriod, queryCountThreshold: flags.queryCountThreshold, queryCountThresholdPercentage: flags.queryCountThresholdPercentage }); const gitInfoFromEnv = await gitInfo(this.log); const { compositionValidationResult, checkSchemaResult } = await project.engine.checkPartialSchema({ id: graphID!, graphVariant: graphVariant!, implementingServiceName: serviceName, partialSchema: { sdl }, ...(historicParameters && { historicParameters }), gitContext: { ...gitInfoFromEnv, ...(flags.author ? { committer: flags.author } : undefined), ...(flags.branch ? { branch: flags.branch } : undefined), ...(flags.commitId ? { commit: flags.commitId } : undefined) } }); task.title = `Found ${pluralize( compositionValidationResult.errors.length, "graph composition error" )} for service ${chalk.cyan(serviceName)} on graph ${chalk.cyan( graphSpecifier )}`; if (compositionValidationResult.errors.length > 0) { taskOutput.compositionErrors = compositionValidationResult.errors .filter(isNotNullOrUndefined) .map(error => { // checks for format: [serviceName] Location -> Error Message const match = error.message.match( /^\[([^\[]+)\]\s+(\S+)\ ->\ (.+)/ ); if (!match) { // If we can't match the errors, that means they're in a format we don't recognize. // Report the entire string as the user will see the raw message. return { message: error.message }; } // Regular expression matches return `[entireStringMatched, ...eachGroup]`; we don't // care about the entire string match, only the groups, so ignore the first value in the // tuple. const [, service, field, message] = match; return { service, field, message }; }); taskOutput.graphCompositionID = compositionValidationResult.graphCompositionID; this.error( federatedServiceCompositionUnsuccessfulErrorMessage ); } else { if (!checkSchemaResult) { throw new Error( "Violated invariant. Schema should have been validated against operations if" + "there were no composition errors" ); } // this is used for the printing taskOutput.checkSchemaResult = checkSchemaResult; // this is used for the next step in the `run` command (comparing schema changes) ctx.checkSchemaResult = checkSchemaResult; } } }, { title: `Validating ${ serviceName ? "composed " : "" }schema against metrics from variant ${chalk.cyan( graphVariant! )} on graph ${chalk.cyan(graphSpecifier)}`, // We have already performed validation per operation above if the service is federated enabled: () => !serviceName, task: async (ctx: TasksOutput, task) => { let schemaCheckSchemaVariables: | { schemaHash: string } | { schema: IntrospectionSchemaInput } | undefined; // This is _not_ a `federated` schema. Resolve the schema given `config.variant`. task.output = "Resolving schema"; schema = await project.resolveSchema({ tag: config.variant }); if (!schema) { throw new Error("Failed to resolve schema"); } schemaCheckSchemaVariables = { schema: introspectionFromSchema(schema) .__schema as IntrospectionSchemaInput }; const historicParameters = validateHistoricParams({ validationPeriod: flags.validationPeriod, queryCountThreshold: flags.queryCountThreshold, queryCountThresholdPercentage: flags.queryCountThresholdPercentage }); task.output = "Validating schema"; const gitInfoFromEnv = await gitInfo(this.log); const variables: CheckSchemaVariables = { id: graphID!, tag: config.variant, gitContext: { ...gitInfoFromEnv, ...(flags.committer ? { committer: flags.committer } : undefined), ...(flags.branch ? { branch: flags.branch } : undefined) }, ...(historicParameters && { historicParameters }), ...schemaCheckSchemaVariables }; const { schema: _, ...restVariables } = variables; this.debug("Variables sent to Apollo:"); this.debug(restVariables); if (schema) { this.debug("SDL of introspection sent to Apollo:"); this.debug(printSchema(schema)); } else { this.debug("Schema hash generated:"); this.debug(schemaCheckSchemaVariables); } const checkSchemaResult = await project.engine.checkSchema( variables ); // Attach to ctx as this will be used in later steps. ctx.checkSchemaResult = checkSchemaResult; // Save the output because we're going to use it even if we throw. `runTasks` won't return // anything if we throw. taskOutput.checkSchemaResult = checkSchemaResult; task.title = task.title.replace("Validating", "Validated"); } }, { title: "Comparing schema changes", task: async (ctx: TasksOutput, task) => { const schemaChanges = ctx.checkSchemaResult.diffToPrevious.changes; const numberOfCheckedOperations = ctx.checkSchemaResult.diffToPrevious .numberOfCheckedOperations || 0; const validationConfig = ctx.checkSchemaResult.diffToPrevious.validationConfig; const hours = validationConfig ? Math.abs( moment() .add(validationConfig.from, "second") .diff( moment().add(validationConfig.to, "second"), "hours" ) ) : null; task.title = `Compared ${pluralize( chalk.cyan(schemaChanges.length.toString()), "schema change" )} against ${pluralize( chalk.cyan(numberOfCheckedOperations.toString()), "operation" )}${ hours ? ` over the last ${chalk.cyan(formatTimePeriod(hours))}` : "" }`; } }, { title: "Reporting result", task: async (ctx: TasksOutput, task) => { const breakingSchemaChangeCount = ctx.checkSchemaResult.diffToPrevious.changes.filter( change => change.severity === ChangeSeverity.FAILURE ).length; const nonBreakingSchemaChangeCount = ctx.checkSchemaResult.diffToPrevious.changes.length - breakingSchemaChangeCount; task.title = `Found ${pluralize( chalk.cyan(breakingSchemaChangeCount.toString()), "breaking change" )} and ${pluralize( chalk.cyan(nonBreakingSchemaChangeCount.toString()), "compatible change" )}`; if (breakingSchemaChangeCount) { // Throw an error here to produce a red X in the list of steps being taken. We're going to // `catch` this error below and proceed with the reporting. throw new Error(breakingChangesErrorMessage); } } } ]; }, context => ({ // It would be better here to use a custom renderer that will output the `Listr` output to stderr and // the `this.log` output to `stdout`. // // @see https://github.com/SamVerschueren/listr#renderer renderer: isCi ? CompactRenderer : context.flags.markdown || context.flags.json ? "silent" : "default" }) ); } catch (error) { if (error.message.includes("/upgrade")) { this.exit(1); return; } if ( error.message !== breakingChangesErrorMessage && error.message !== federatedServiceCompositionUnsuccessfulErrorMessage ) { throw error; } } const { checkSchemaResult, config, shouldOutputJson, shouldOutputMarkdown, serviceName, compositionErrors, graphCompositionID, shouldAlwaysExit0 } = taskOutput; if (shouldOutputJson) { if (compositionErrors) { return this.log(JSON.stringify({ errors: compositionErrors }, null, 2)); } return this.log( JSON.stringify( { targetUrl: checkSchemaResult.targetUrl + (graphCompositionID ? `?graphCompositionId=${graphCompositionID}` : ``), changes: checkSchemaResult.diffToPrevious.changes, validationConfig: checkSchemaResult.diffToPrevious.validationConfig }, null, 2 ) ); } else if (shouldOutputMarkdown) { if (!graphID) { throw new Error( "The graph name should have been defined in the Apollo config and validated when the config was loaded. Please file an issue if you're seeing this error." ); } if (compositionErrors) { if (!serviceName) { throw new Error( "Composition errors should only occur when `serviceName` is present. Please file an issue if you're seeing this error." ); } return this.log( formatCompositionErrorsMarkdown({ compositionErrors, graphName: graphID, serviceName, tag: config.variant }) ); } return this.log( formatMarkdown({ checkSchemaResult, graphName: graphID, serviceName, tag: config.variant, graphCompositionID }) ); } if (compositionErrors) { // Add a cosmetic line break console.log(""); // errors that DONT match the expected format: [service] field -> message const unformattedErrors = compositionErrors.filter( e => !e.field && !e.service ); // errors that match the expected format: [service] field -> message const formattedErrors = compositionErrors.filter( e => e.field || e.service ); if (formattedErrors.length) this.log( table( [ ["Service", "Field", "Message"], ...formattedErrors.map(Object.values) ], { columns: { 2: { width: 50, wrapWord: true } } } ) ); // list out errors which we couldn't determine Service name and/or location names if (unformattedErrors.length) this.log( table([["Message"], ...unformattedErrors.map(e => [e.message])]) ); // Return a non-zero error code if (shouldAlwaysExit0) { return; } this.exit(1); } else { this.log(formatHumanReadable({ checkSchemaResult, graphCompositionID })); // exit with failing status if we have failures if ( checkSchemaResult.diffToPrevious.changes.find( ({ severity }) => severity === ChangeSeverity.FAILURE ) ) { if (shouldAlwaysExit0) { return; } this.exit(1); } } } } function isNotNullOrUndefined<T>(value: T | null | undefined): value is T { return value !== null && typeof value !== "undefined"; }
the_stack
import { Combat, Mechanics, Item, state, ActionChart, ActionChartItem, mechanicsEngine } from ".."; /** * Stores information about an object available to pick on a section */ export interface SectionItem { /** The object id */ id: string; /** The object price. If its zero or null, the object is free */ price: number; /** True if there are an infinite number of this kind of object on the section */ unlimited: boolean; /** * Only applies if id = 'quiver' (number of arrows on the quiver) * or id = 'money' (number of Gold Crowns) */ count: number; /** * Object is allowed to be used from the section (not picked object)? */ useOnSection: boolean; /** * Number of allowed uses of the item. * Added in v1.12. It can be null after installation of this version. In this case, asume is 1 */ usageCount: number; } /** * Stores a section state (combats, objects, etc) */ export class SectionState { /** * Objects on the section */ public objects: SectionItem[] = []; /** * Sell prices on the section. Applies only on sections where you can * sell inventory objects. */ public sellPrices: SectionItem[] = []; /** Combats on the section */ public combats: Combat[] = []; /** The combat has been eluded? */ public combatEluded = false; /** Paths of mechanics rules already executed * The key is the rule path, and the value is true bool value, or info about the * rule execution */ public executedRules = {}; /** Healing discipline has been executed on this section? */ public healingExecuted = false; /** * Number picker states for this section. * See numberPicker.js and numberPickerMechanics.ts */ public numberPickersState = { actionFired: null }; /** * Mark a rule as executed * @param rule The executed rule * @param executionState The state to associate with the execution. If it's null, * if will be set to true */ public markRuleAsExecuted( rule: Element, executionState: any = true ) { if ( !executionState ) { executionState = true; } this.executedRules[ Mechanics.getRuleSelector(rule) ] = executionState; } /** * Check if a rule for this section has been executed * @param rule Rule to check * @return The object associated with the execution. true if there was no result stored */ public ruleHasBeenExecuted(rule: Element): any { // TODO: This will fail if the XML changes. The rule should be searched // TODO: with all selectors on the sectionState.executedRules keys // TODO: If it's found, it's executed return this.executedRules[ Mechanics.getRuleSelector(rule) ]; } /** * Return the count of items on the current section of a given type * @param type The object type to count ('weapon', 'object' or 'special'). * null to return all * @return The objects on this section */ public getSectionObjects(type: string = null): Item[] { const items: Item[] = []; for ( const sectionItem of this.objects) { if ( sectionItem.id === Item.MONEY ) { // Money if not really an object. It's stored like one for mechanics needs continue; } const i = state.mechanics.getObject( sectionItem.id ); if ( !type || i.type === type ) { items.push(i); } } return items; } /** * Return the count of objects on the current section of a given type * @param type The object type to count ('weapon', 'object' or 'special'). * null to return all * @return The count of objects on this section */ public getCntSectionObjects(type: string): number { return this.getSectionObjects(type).length; } /** * Return the weapons and weapon special object on the section */ public getWeaponObjects(): Item[] { const weapons: Item[] = []; for ( const i of this.getSectionObjects() ) { if ( i.isWeapon() ) { weapons.push( i ); } } return weapons; } /** * Returns 'finished' if all combats are finished, and Lone Wolf is not death. * Returns 'eluded' if all combats are eluded, and Lone Wolf is not death. * Returns false if there are pending combats, or Lone Wolf is death */ public areAllCombatsFinished(actionChart: ActionChart): string|boolean { if ( actionChart.currentEndurance <= 0 ) { // LW death return false; } if ( this.combats.length === 0 ) { return "finished"; } if ( this.combatEluded ) { return "eluded"; } for (const combat of this.combats) { if ( !combat.isFinished() ) { return false; } } return "finished"; } /** * Returns true if all combats are won */ public areAllCombatsWon(): boolean { for (const combat of this.combats) { if ( combat.endurance > 0 ) { return false; } } return true; } /** * Returns true if there is some combat active */ public someCombatActive(): boolean { if ( this.combatEluded ) { return false; } for (const combat of this.combats) { if ( !combat.isFinished() ) { return true; } } return false; } /** * Returns the number on endurance points lost by somebody on section combats * @param {string} who If is 'enemy' we will calculate the enemy loss. Otherwise, we will * calculate the player loss */ public combatsEnduranceLost( who: string ): number { let lost = 0; for ( let i = 0, len = this.combats.length; i < len; i++) { if ( who === "enemy") { lost += this.combats[i].enemyEnduranceLost(); } else { lost += this.combats[i].playerEnduranceLost(); } } return lost; } /** * Returns the number of turns used on all combats on the section */ public combatsDuration(): number { let duration = 0; for ( let i = 0, len = this.combats.length; i < len; i++) { duration += this.combats[i].turns.length; } return duration; } /** * Set combats as enabled / disabled * @param enabled True to enable combats. False to disable them */ public setCombatsEnabled(enabled: boolean) { for ( let i = 0, len = this.combats.length; i < len; i++) { this.combats[i].disabled = !enabled; } } /** * Add an object from the Action Chart to the section available objects * @param aChartItem Action Chart item information * @param arrowCount Only applies if id = Item.QUIVER (number of arrows on the quiver) */ public addActionChartItemToSection(aChartItem: ActionChartItem, arrowCount: number = 0) { this.addObjectToSection(aChartItem.id, 0, false, arrowCount, false, aChartItem.usageCount); } /** * Add an object to the section * @param objectId Object id to add * @param price The object price. 0 === no buy (free) * @param unlimited True if there are an infinite number of this kind of object on the section * @param count Only applies if id = Item.QUIVER (number of arrows on the quiver), Item.ARROW (number of arrows), or Item.MONEY * (number of Gold Crowns), or if price is is not zero (-> you buy "count" items for one "price") * @param useOnSection The object is allowed to be used on the section (not picked object)? * @param usageCount Number of remaining object uses. If no specified or < 0, the default Item usageCount will be used */ public addObjectToSection(objectId: string , price: number = 0, unlimited: boolean = false, count: number = 0 , useOnSection: boolean = false, usageCount: number = -1) { // Special cases: if ( objectId === Item.MONEY ) { // Try to increase the current money amount / arrows on the section: const moneyIndex = this.getObjectIndex(objectId); if (moneyIndex >= 0) { this.objects[moneyIndex].count += count; return; } } // Usages count if (usageCount < 0) { // Default usage count const item = state.mechanics.getObject(objectId); usageCount = item && item.usageCount ? item.usageCount : 1; } if (!usageCount) { // Do not store nulls usageCount = 0; } this.objects.push({ id: objectId, price, unlimited, count: (objectId === Item.QUIVER || objectId === Item.ARROW || objectId === Item.MONEY || price > 0 ? count : 0 ), useOnSection, usageCount }); } /** * Remove an object from the section * @param objectId Object id to remove * @param price Price of the object to remove. If index is specified, this will be ignored * @param count Count to decrease. Only applies if the object is 'money' * @param index Object index to remove. If not specified or < 0, the first object with the gived id will be removed */ public removeObjectFromSection(objectId: string, price: number, count: number = -1, index: number = -1) { // Be sure price is not null if ( !price ) { price = 0; } if (index < 0) { // Find the first one with the gived id and price index = this.getObjectIndex(objectId, price); } if (index >= 0 && index < this.objects.length) { let removeObject = true; if ( ( objectId === Item.MONEY || objectId === Item.ARROW ) && count >= 0 && this.objects[index].count > count ) { // Still money / arrows available: this.objects[index].count -= count; removeObject = false; } if ( removeObject ) { this.objects.splice(index, 1); } return; } mechanicsEngine.debugWarning( "Object to remove from section not found :" + objectId + " " + price ); } /** * Returns the last random value picked on the first combat of this section. * Returns -1 if there are no combats or not turns yet */ public getLastRandomCombatTurn(): number { if ( this.combats.length === 0 ) { return -1; } const combat = this.combats[0]; if ( combat.turns.length === 0 ) { return -1; } return combat.turns[ combat.turns.length - 1].randomValue; } /** * Returns the enemy current endurance of the first combat on the section. * It returns zero if there are no combats on the section */ public getEnemyEndurance(): number { if ( this.combats.length === 0 ) { return 0; } return this.combats[0].endurance; } /** * Get the available amount of money on the section */ public getAvailableMoney(): number { let moneyCount = 0; for ( const o of this.objects ) { if (o.id === Item.MONEY) { moneyCount += o.count; } } return moneyCount; } /** * Add a combat skill bonus to the current section combats by an object usage. * @param combatSkillModifier The combat skill increase */ public combatSkillUsageModifier( combatSkillModifier: number ) { // Apply the modifier to current combats: for ( const combat of this.combats ) { combat.objectsUsageModifier += combatSkillModifier; } } /** Return true if the object is on the section */ public containsObject( objectId: string ): boolean { return this.getObjectIndex(objectId) >= 0; } /** * Get an object index in this.objects * @param objectId The object id * @param price If specified and >= 0, the object price to search. If it's not specified the price will not be checked * @returns The object index in this.objects. -1 if the object was not found. */ private getObjectIndex(objectId: string, price: number = -1): number { for (let i = 0; i < this.objects.length; i++) { // Be sure price is not null let currentPrice = this.objects[i].price; if ( !currentPrice ) { currentPrice = 0; } if ( this.objects[i].id === objectId && ( price < 0 || currentPrice === price ) ) { return i; } } return -1; } }
the_stack
'use strict'; import {IDiffChange, ISequence, LcsDiff} from 'vs/base/common/diff/diff'; import * as strings from 'vs/base/common/strings'; import {ICharChange, ILineChange} from 'vs/editor/common/editorCommon'; var MAXIMUM_RUN_TIME = 5000; // 5 seconds var MINIMUM_MATCHING_CHARACTER_LENGTH = 3; interface IMarker { lineNumber: number; column: number; offset: number; } function computeDiff(originalSequence:ISequence, modifiedSequence:ISequence, continueProcessingPredicate:()=>boolean): IDiffChange[] { var diffAlgo = new LcsDiff(originalSequence, modifiedSequence, continueProcessingPredicate); return diffAlgo.ComputeDiff(); } class MarkerSequence implements ISequence { public buffer:string; public startMarkers:IMarker[]; public endMarkers:IMarker[]; constructor(buffer:string, startMarkers:IMarker[], endMarkers:IMarker[]) { this.buffer = buffer; this.startMarkers = startMarkers; this.endMarkers = endMarkers; } public equals(other:any): boolean { if (!(other instanceof MarkerSequence)) { return false; } var otherMarkerSequence = <MarkerSequence>other; if (this.getLength() !== otherMarkerSequence.getLength()) { return false; } for (var i = 0, len = this.getLength(); i < len; i++) { var myElement = this.getElementHash(i); var otherElement = otherMarkerSequence.getElementHash(i); if (myElement !== otherElement) { return false; } } return true; } public getLength(): number { return this.startMarkers.length; } public getElementHash(i:number): string { return this.buffer.substring(this.startMarkers[i].offset, this.endMarkers[i].offset); } public getStartLineNumber(i:number): number { if (i === this.startMarkers.length) { // This is the special case where a change happened after the last marker return this.startMarkers[i - 1].lineNumber + 1; } return this.startMarkers[i].lineNumber; } public getStartColumn(i:number): number { return this.startMarkers[i].column; } public getEndLineNumber(i:number): number { return this.endMarkers[i].lineNumber; } public getEndColumn(i:number): number { return this.endMarkers[i].column; } } class LineMarkerSequence extends MarkerSequence { constructor(lines:string[], shouldIgnoreTrimWhitespace:boolean) { var i:number, length:number, pos:number; var buffer = ''; var startMarkers:IMarker[] = [], endMarkers:IMarker[] = [], startColumn:number, endColumn:number; for (pos = 0, i = 0, length = lines.length; i < length; i++) { buffer += lines[i]; startColumn = 1; endColumn = lines[i].length + 1; if (shouldIgnoreTrimWhitespace) { startColumn = LineMarkerSequence._getFirstNonBlankColumn(lines[i], 1); endColumn = LineMarkerSequence._getLastNonBlankColumn(lines[i], 1); } startMarkers.push({ offset: pos + startColumn - 1, lineNumber: i + 1, column: startColumn }); endMarkers.push({ offset: pos + endColumn - 1, lineNumber: i+1, column: endColumn }); pos += lines[i].length; } super(buffer, startMarkers, endMarkers); } private static _getFirstNonBlankColumn(txt:string, defaultValue:number): number { var r = strings.firstNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 1; } private static _getLastNonBlankColumn(txt:string, defaultValue:number): number { var r = strings.lastNonWhitespaceIndex(txt); if (r === -1) { return defaultValue; } return r + 2; } public getCharSequence(startIndex:number, endIndex:number):MarkerSequence { var startMarkers:IMarker[] = [], endMarkers:IMarker[] = [], index:number, i:number, startMarker:IMarker, endMarker:IMarker; for (index = startIndex; index <= endIndex; index++) { startMarker = this.startMarkers[index]; endMarker = this.endMarkers[index]; for (i = startMarker.offset; i < endMarker.offset; i++) { startMarkers.push({ offset: i, lineNumber: startMarker.lineNumber, column: startMarker.column + (i - startMarker.offset) }); endMarkers.push({ offset: i + 1, lineNumber: startMarker.lineNumber, column: startMarker.column + (i - startMarker.offset) + 1 }); } } return new MarkerSequence(this.buffer, startMarkers, endMarkers); } } class CharChange implements ICharChange { public originalStartLineNumber:number; public originalStartColumn:number; public originalEndLineNumber:number; public originalEndColumn:number; public modifiedStartLineNumber:number; public modifiedStartColumn:number; public modifiedEndLineNumber:number; public modifiedEndColumn:number; constructor(diffChange:IDiffChange, originalCharSequence:MarkerSequence, modifiedCharSequence:MarkerSequence) { if (diffChange.originalLength === 0) { this.originalStartLineNumber = 0; this.originalStartColumn = 0; this.originalEndLineNumber = 0; this.originalEndColumn = 0; } else { this.originalStartLineNumber = originalCharSequence.getStartLineNumber(diffChange.originalStart); this.originalStartColumn = originalCharSequence.getStartColumn(diffChange.originalStart); this.originalEndLineNumber = originalCharSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1); this.originalEndColumn = originalCharSequence.getEndColumn(diffChange.originalStart + diffChange.originalLength - 1); } if (diffChange.modifiedLength === 0) { this.modifiedStartLineNumber = 0; this.modifiedStartColumn = 0; this.modifiedEndLineNumber = 0; this.modifiedEndColumn = 0; } else { this.modifiedStartLineNumber = modifiedCharSequence.getStartLineNumber(diffChange.modifiedStart); this.modifiedStartColumn = modifiedCharSequence.getStartColumn(diffChange.modifiedStart); this.modifiedEndLineNumber = modifiedCharSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1); this.modifiedEndColumn = modifiedCharSequence.getEndColumn(diffChange.modifiedStart + diffChange.modifiedLength - 1); } } } function postProcessCharChanges(rawChanges:IDiffChange[]): IDiffChange[] { if (rawChanges.length <= 1) { return rawChanges; } var result = [ rawChanges[0] ]; var i:number, len:number, originalMatchingLength:number, modifiedMatchingLength:number, matchingLength:number, prevChange = result[0], currChange:IDiffChange; for (i = 1, len = rawChanges.length; i < len; i++) { currChange = rawChanges[i]; originalMatchingLength = currChange.originalStart - (prevChange.originalStart + prevChange.originalLength); modifiedMatchingLength = currChange.modifiedStart - (prevChange.modifiedStart + prevChange.modifiedLength); // Both of the above should be equal, but the continueProcessingPredicate may prevent this from being true matchingLength = Math.min(originalMatchingLength, modifiedMatchingLength); if (matchingLength < MINIMUM_MATCHING_CHARACTER_LENGTH) { // Merge the current change into the previous one prevChange.originalLength = (currChange.originalStart + currChange.originalLength) - prevChange.originalStart; prevChange.modifiedLength = (currChange.modifiedStart + currChange.modifiedLength) - prevChange.modifiedStart; } else { // Add the current change result.push(currChange); prevChange = currChange; } } return result; } class LineChange implements ILineChange { public originalStartLineNumber:number; public originalEndLineNumber:number; public modifiedStartLineNumber:number; public modifiedEndLineNumber:number; public charChanges:CharChange[]; constructor(diffChange:IDiffChange, originalLineSequence:LineMarkerSequence, modifiedLineSequence:LineMarkerSequence, continueProcessingPredicate:()=>boolean, shouldPostProcessCharChanges:boolean) { if (diffChange.originalLength === 0) { this.originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart) - 1; this.originalEndLineNumber = 0; } else { this.originalStartLineNumber = originalLineSequence.getStartLineNumber(diffChange.originalStart); this.originalEndLineNumber = originalLineSequence.getEndLineNumber(diffChange.originalStart + diffChange.originalLength - 1); } if (diffChange.modifiedLength === 0) { this.modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart) - 1; this.modifiedEndLineNumber = 0; } else { this.modifiedStartLineNumber = modifiedLineSequence.getStartLineNumber(diffChange.modifiedStart); this.modifiedEndLineNumber = modifiedLineSequence.getEndLineNumber(diffChange.modifiedStart + diffChange.modifiedLength - 1); } if (diffChange.originalLength !== 0 && diffChange.modifiedLength !== 0 && continueProcessingPredicate()) { var originalCharSequence = originalLineSequence.getCharSequence(diffChange.originalStart, diffChange.originalStart + diffChange.originalLength - 1); var modifiedCharSequence = modifiedLineSequence.getCharSequence(diffChange.modifiedStart, diffChange.modifiedStart + diffChange.modifiedLength - 1); var rawChanges = computeDiff(originalCharSequence, modifiedCharSequence, continueProcessingPredicate); if (shouldPostProcessCharChanges) { rawChanges = postProcessCharChanges(rawChanges); } this.charChanges = []; for (var i = 0, length = rawChanges.length; i < length; i++) { this.charChanges.push(new CharChange(rawChanges[i], originalCharSequence, modifiedCharSequence)); } } } } export interface IDiffComputerOpts { shouldPostProcessCharChanges: boolean; shouldIgnoreTrimWhitespace: boolean; shouldConsiderTrimWhitespaceInEmptyCase: boolean; } export class DiffComputer { private shouldPostProcessCharChanges:boolean; private shouldIgnoreTrimWhitespace:boolean; private maximumRunTimeMs:number; private original:LineMarkerSequence; private modified:LineMarkerSequence; private computationStartTime:number; constructor(originalLines:string[], modifiedLines:string[], opts:IDiffComputerOpts) { this.shouldPostProcessCharChanges = opts.shouldPostProcessCharChanges; this.shouldIgnoreTrimWhitespace = opts.shouldIgnoreTrimWhitespace; this.maximumRunTimeMs = MAXIMUM_RUN_TIME; this.original = new LineMarkerSequence(originalLines, this.shouldIgnoreTrimWhitespace); this.modified = new LineMarkerSequence(modifiedLines, this.shouldIgnoreTrimWhitespace); if (opts.shouldConsiderTrimWhitespaceInEmptyCase && this.shouldIgnoreTrimWhitespace && this.original.equals(this.modified)) { // Diff would be empty with `shouldIgnoreTrimWhitespace` this.shouldIgnoreTrimWhitespace = false; this.original = new LineMarkerSequence(originalLines, this.shouldIgnoreTrimWhitespace); this.modified = new LineMarkerSequence(modifiedLines, this.shouldIgnoreTrimWhitespace); } } public computeDiff():ILineChange[] { this.computationStartTime = (new Date()).getTime(); var rawChanges = computeDiff(this.original, this.modified, this._continueProcessingPredicate.bind(this)); var lineChanges: ILineChange[] = []; for (var i = 0, length = rawChanges.length; i < length; i++) { lineChanges.push(new LineChange(rawChanges[i], this.original, this.modified, this._continueProcessingPredicate.bind(this), this.shouldPostProcessCharChanges)); } return lineChanges; } private _continueProcessingPredicate(): boolean { if (this.maximumRunTimeMs === 0) { return true; } var now = (new Date()).getTime(); return now - this.computationStartTime < this.maximumRunTimeMs; } }
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ComponentRef, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'; import { FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, UrlSegment } from '@angular/router'; import { ChildItemRef, CmsObject, CmsPropertyFactoryResolver, CmsTab, Content, ContentTypeEnum, ContentTypeProperty, InsertPointDirective, sortByString, TypeOfContent } from '@typijs/core'; import { combineLatest, merge, Observable, of } from 'rxjs'; import { auditTime, catchError, concatMap, debounceTime, distinctUntilChanged, filter, map, mapTo, switchMap, takeUntil, tap, withLatestFrom } from 'rxjs/operators'; import { DynamicFormService } from '../../shared/form/dynamic-form.service'; import { SubjectService } from '../../shared/services/subject.service'; import { SubscriptionDestroy } from '../../shared/subscription-destroy'; import { ContentCrudService, ContentCrudServiceResolver, ContentExt, ContentInfo } from '../content-crud.service'; @Component({ templateUrl: './content-update.component.html', styleUrls: ['./content-update.scss'] }) export class ContentUpdateComponent extends SubscriptionDestroy implements OnInit, OnDestroy, AfterViewInit { @ViewChildren(InsertPointDirective) insertPoints: QueryList<InsertPointDirective>; contentFormGroup: FormGroup = new FormGroup({}); formTabs: Partial<CmsTab>[] = []; currentContent: ContentExt; editMode: 'AllProperties' | 'OnPageEdit' = 'AllProperties'; typeOfContent: TypeOfContent; previewUrl: string; showIframeHider = false; saveMessage: string = ''; isPublishing = false; readonly settingsGroup: string = 'Settings'; readonly defaultGroup: string = 'Content'; private contentService: ContentCrudService; private contentTypeProperties: ContentTypeProperty[] = []; private componentRefs: ComponentRef<any>[] = []; constructor( private contentServiceResolver: ContentCrudServiceResolver, private propertyFactoryResolver: CmsPropertyFactoryResolver, private dynamicFormService: DynamicFormService, private subjectService: SubjectService, private route: ActivatedRoute, private changeDetectionRef: ChangeDetectorRef ) { super(); } ngOnInit() { combineLatest([this.route.paramMap, this.route.queryParamMap]) .pipe( switchMap(([params, query]) => { const contentId = params.get('id'); const versionId = query.get('versionId'); const language = query.get('language'); this.typeOfContent = this.getTypeContentFromUrl(this.route.snapshot.url); this.contentService = this.contentServiceResolver.resolveCrudFormService(this.typeOfContent); return this.contentService.getContentVersion(contentId, versionId, language).pipe( catchError(error => { return of({}); }) ); }), tap((result: ContentInfo) => { this.previewUrl = result.previewUrl; this.contentTypeProperties = result.contentTypeProperties; // Extract the tab from property information of content type this.formTabs = this.extractFormTabsFromProperties(result.contentTypeProperties); // Populate the properties for content data this.currentContent = this.getContentWithPopulatedProperties(result.contentData, result.contentTypeProperties); // Binds data for content form and create the form group controls this.contentFormGroup = this.createFormGroup(this.currentContent, result.contentTypeProperties); }), takeUntil(this.unsubscribe$)) .subscribe(() => { this.subjectService.fireContentSelected(this.typeOfContent, this.currentContent); this.handleFormChangesToAutoSave(this.contentFormGroup); }); this.subjectService.portalLayoutChanged$ .pipe( distinctUntilChanged(), tap((showIframeHider: boolean) => this.showIframeHider = showIframeHider), takeUntil(this.unsubscribe$) ) .subscribe(); } ngAfterViewInit() { this.insertPoints.changes.subscribe((newValue: QueryList<InsertPointDirective>) => { if (newValue.length > 0) { this.componentRefs = this.createPropertyComponents(this.contentTypeProperties); this.changeDetectionRef.detectChanges(); } }); } publishContent(formId: any) { if (this.contentFormGroup.valid && this.currentContent && this.currentContent.status === 2) { this.saveMessage = ''; this.isPublishing = true; const { _id, versionId } = this.currentContent; this.contentService.publishContentVersion(_id, versionId).pipe( catchError(error => { return of(undefined); }) ).subscribe((publishedContent: ContentExt) => { this.isPublishing = false; formId.control.markAsPristine(); if (publishedContent) { this.saveMessage = 'Published'; if (publishedContent.status !== this.currentContent.status) { Object.assign(this.currentContent, publishedContent); this.subjectService.fireContentStatusChanged(this.typeOfContent, publishedContent); } } else { this.saveMessage = 'Publish Error'; } }); } } private getTypeContentFromUrl(url: UrlSegment[]): TypeOfContent { return url.length >= 2 && url[0].path === 'content' ? url[1].path : ''; } /** * Subscribe the form value changes to trigger the save action * * https://stackoverflow.com/questions/45777683/rxjs-debounce-with-regular-sampling */ private handleFormChangesToAutoSave(formGroup: FormGroup) { // implement the auto save function this.saveMessage = ''; const formChanges$ = formGroup.valueChanges; // If nothing change for 1 second, trigger save action const debounceSave$ = formChanges$.pipe(debounceTime(1200)); // A signal to indicate whether or not the form changing const valueChanging$ = merge( formChanges$.pipe(mapTo(true)), debounceSave$.pipe(mapTo(false)) ).pipe(distinctUntilChanged()); // Every 5 seconds in while form changing, trigger save action const auditSave$ = formChanges$.pipe( auditTime(5000), withLatestFrom(valueChanging$), filter(([values, changing]) => changing), map(([values]) => values) ); merge(debounceSave$, auditSave$).pipe( tap(() => this.saveMessage = 'Saving...'), concatMap(formValues => this.updateContent(formValues)), takeUntil(this.unsubscribe$) ).subscribe((savedContent: Content) => { if (savedContent) { // update current content this.saveMessage = 'Saved'; const { versionId, status } = this.currentContent; Object.assign(this.currentContent, savedContent); if (versionId !== savedContent.versionId || status !== savedContent.status) { this.subjectService.fireContentStatusChanged(this.typeOfContent, savedContent); } } else { this.saveMessage = 'Save Error'; } }); } private getContentWithPopulatedProperties(content: Content, propertiesMetadata: ContentTypeProperty[]): ContentExt { propertiesMetadata.forEach(propertyMeta => { if (content.properties) { const propertyFactory = this.propertyFactoryResolver.resolvePropertyFactory(propertyMeta.metadata.displayType); content.properties[propertyMeta.name] = propertyFactory.getPopulatedReferenceProperty(content, propertyMeta); } }); return content; } private extractFormTabsFromProperties(properties: ContentTypeProperty[]): Partial<CmsTab>[] { const tabs: Partial<CmsTab>[] = []; properties.forEach((property: ContentTypeProperty) => { const groupName = property.metadata.groupName; if (!this.isNil(groupName)) { if (tabs.findIndex(x => x.title === groupName) === -1) { tabs.push({ title: groupName, name: groupName }); } } }); if (properties.findIndex((property: ContentTypeProperty) => this.isNil(property.metadata.groupName)) !== -1) { if (tabs.findIndex(x => x.name === this.defaultGroup) === -1) { tabs.push({ title: this.defaultGroup, name: this.defaultGroup }); } } if (tabs.findIndex(x => x.name === this.settingsGroup) === -1) { tabs.push({ title: this.settingsGroup, name: this.settingsGroup }); } return tabs.sort(sortByString('title', 'asc')); } private isNil(value): boolean { if (value === null || value === undefined) { return true; } return false; } /** * Creates Reactive Form from the properties of content * @param properties * @returns FormGroup instance */ private createFormGroup(content: ContentExt, properties: ContentTypeProperty[]): FormGroup { const formControls: { [key: string]: any } = this.createDefaultFormControls(content); const formModel = content.properties ? content.properties : {}; return this.dynamicFormService.createFormGroup(properties, formModel, formControls); } /** * Create the default form controls such as content name, page url segment */ private createDefaultFormControls(content: ContentExt): { [key: string]: any } { const formControls: { [key: string]: any } = {}; formControls.name = [content.name, Validators.required]; formControls.startPublish = [content.startPublish]; formControls.createdAt = [content.createdAt]; formControls.updatedAt = [content.updatedAt]; formControls.childOrderRule = [content.childOrderRule]; formControls.peerOrder = [content.peerOrder]; if (this.typeOfContent === ContentTypeEnum.Page) { formControls.urlSegment = [content.urlSegment, Validators.required]; formControls.visibleInMenu = [content.visibleInMenu]; formControls.simpleAddress = [content.simpleAddress]; } return formControls; } /** * Creates the form controls corresponding to the properties of content type * @param properties * @returns property components */ private createPropertyComponents(properties: ContentTypeProperty[]): ComponentRef<any>[] { const propertyControls: ComponentRef<any>[] = []; if (!this.formTabs || this.formTabs.length === 0) { return propertyControls; } this.formTabs.forEach(tab => { const viewContainerRef = this.insertPoints.find(x => x.name === tab.name).viewContainerRef; viewContainerRef.clear(); const propertiesInTab = properties.filter(x => (x.metadata.groupName === tab.title || (!x.metadata.groupName && tab.title === this.defaultGroup))); const fieldComponentsInTab = this.dynamicFormService.createFormFieldComponents(propertiesInTab, this.contentFormGroup); fieldComponentsInTab.forEach(fieldCmp => { viewContainerRef.insert(fieldCmp.hostView); propertyControls.push(fieldCmp); }); }); return propertyControls; } private updateContent(formValue: any): Observable<Content> { if (formValue) { // Extract the field's values such as name, url segment. These fields don't belong properties const contentDto: Partial<Content> = this.extractOwnPropertyValuesOfContent(formValue); Object.assign(this.currentContent, contentDto); // Extract the properties's values this.currentContent.properties = this.extractPropertiesPropertyOfContent(formValue); this.currentContent.childItems = this.extractChildItemsRefs(); const { _id, versionId, properties, childItems } = this.currentContent; Object.assign(contentDto, { properties, childItems }); return this.contentService.editContentVersion(_id, versionId, contentDto).pipe(catchError(error => { return of(undefined); })); } } private extractOwnPropertyValuesOfContent(formValue: any): CmsObject { const properties = {}; Object.keys(formValue).forEach(key => { // check current content object own the key if (this.currentContent.hasOwnProperty(key)) { properties[key] = formValue[key]; } }); return properties; } private extractPropertiesPropertyOfContent(formValue: any): CmsObject { const properties = {}; Object.keys(formValue).forEach(key => { // check current content object don't own key if (!this.currentContent.hasOwnProperty(key)) { properties[key] = formValue[key]; } }); return properties; } // get all reference id of blocks in all content area private extractChildItemsRefs(): ChildItemRef[] { const childItems: ChildItemRef[] = []; Object.keys(this.currentContent.properties).forEach(propertyName => { const property = this.contentTypeProperties.find(x => x.name === propertyName); if (property) { const propertyType = property.metadata.displayType; const propertyFactory = this.propertyFactoryResolver.resolvePropertyFactory(propertyType); const propertyChildItems = propertyFactory.getChildItemsRef(this.currentContent, property); if (propertyChildItems.length > 0) { childItems.push(...propertyChildItems); } } }); return childItems; } ngOnDestroy() { super.ngOnDestroy(); if (this.insertPoints) { this.insertPoints.map(x => x.viewContainerRef).forEach(containerRef => containerRef.clear()); } if (this.componentRefs) { this.componentRefs.forEach(cmpRef => { cmpRef.destroy(); }); this.componentRefs = []; } } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CreateApplicationCommand, CreateApplicationCommandInput, CreateApplicationCommandOutput, } from "./commands/CreateApplicationCommand"; import { CreateApplicationVersionCommand, CreateApplicationVersionCommandInput, CreateApplicationVersionCommandOutput, } from "./commands/CreateApplicationVersionCommand"; import { CreateCloudFormationChangeSetCommand, CreateCloudFormationChangeSetCommandInput, CreateCloudFormationChangeSetCommandOutput, } from "./commands/CreateCloudFormationChangeSetCommand"; import { CreateCloudFormationTemplateCommand, CreateCloudFormationTemplateCommandInput, CreateCloudFormationTemplateCommandOutput, } from "./commands/CreateCloudFormationTemplateCommand"; import { DeleteApplicationCommand, DeleteApplicationCommandInput, DeleteApplicationCommandOutput, } from "./commands/DeleteApplicationCommand"; import { GetApplicationCommand, GetApplicationCommandInput, GetApplicationCommandOutput, } from "./commands/GetApplicationCommand"; import { GetApplicationPolicyCommand, GetApplicationPolicyCommandInput, GetApplicationPolicyCommandOutput, } from "./commands/GetApplicationPolicyCommand"; import { GetCloudFormationTemplateCommand, GetCloudFormationTemplateCommandInput, GetCloudFormationTemplateCommandOutput, } from "./commands/GetCloudFormationTemplateCommand"; import { ListApplicationDependenciesCommand, ListApplicationDependenciesCommandInput, ListApplicationDependenciesCommandOutput, } from "./commands/ListApplicationDependenciesCommand"; import { ListApplicationsCommand, ListApplicationsCommandInput, ListApplicationsCommandOutput, } from "./commands/ListApplicationsCommand"; import { ListApplicationVersionsCommand, ListApplicationVersionsCommandInput, ListApplicationVersionsCommandOutput, } from "./commands/ListApplicationVersionsCommand"; import { PutApplicationPolicyCommand, PutApplicationPolicyCommandInput, PutApplicationPolicyCommandOutput, } from "./commands/PutApplicationPolicyCommand"; import { UnshareApplicationCommand, UnshareApplicationCommandInput, UnshareApplicationCommandOutput, } from "./commands/UnshareApplicationCommand"; import { UpdateApplicationCommand, UpdateApplicationCommandInput, UpdateApplicationCommandOutput, } from "./commands/UpdateApplicationCommand"; import { ServerlessApplicationRepositoryClient } from "./ServerlessApplicationRepositoryClient"; /** * <p>The AWS Serverless Application Repository makes it easy for developers and enterprises to quickly find * and deploy serverless applications in the AWS Cloud. For more information about serverless applications, * see Serverless Computing and Applications on the AWS website.</p><p>The AWS Serverless Application Repository is deeply integrated with the AWS Lambda console, so that developers of * all levels can get started with serverless computing without needing to learn anything new. You can use category * keywords to browse for applications such as web and mobile backends, data processing applications, or chatbots. * You can also search for applications by name, publisher, or event source. To use an application, you simply choose it, * configure any required fields, and deploy it with a few clicks. </p><p>You can also easily publish applications, sharing them publicly with the community at large, or privately * within your team or across your organization. To publish a serverless application (or app), you can use the * AWS Management Console, AWS Command Line Interface (AWS CLI), or AWS SDKs to upload the code. Along with the * code, you upload a simple manifest file, also known as the AWS Serverless Application Model (AWS SAM) template. * For more information about AWS SAM, see AWS Serverless Application Model (AWS SAM) on the AWS Labs * GitHub repository.</p><p>The AWS Serverless Application Repository Developer Guide contains more information about the two developer * experiences available:</p><ul> * <li> * <p>Consuming Applications – Browse for applications and view information about them, including * source code and readme files. Also install, configure, and deploy applications of your choosing. </p> * <p>Publishing Applications – Configure and upload applications to make them available to other * developers, and publish new versions of applications. </p> * </li> * </ul> */ export class ServerlessApplicationRepository extends ServerlessApplicationRepositoryClient { /** * <p>Creates an application, optionally including an AWS SAM file to create the first application version in the same call.</p> */ public createApplication( args: CreateApplicationCommandInput, options?: __HttpHandlerOptions ): Promise<CreateApplicationCommandOutput>; public createApplication( args: CreateApplicationCommandInput, cb: (err: any, data?: CreateApplicationCommandOutput) => void ): void; public createApplication( args: CreateApplicationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateApplicationCommandOutput) => void ): void; public createApplication( args: CreateApplicationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateApplicationCommandOutput) => void), cb?: (err: any, data?: CreateApplicationCommandOutput) => void ): Promise<CreateApplicationCommandOutput> | void { const command = new CreateApplicationCommand(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 application version.</p> */ public createApplicationVersion( args: CreateApplicationVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateApplicationVersionCommandOutput>; public createApplicationVersion( args: CreateApplicationVersionCommandInput, cb: (err: any, data?: CreateApplicationVersionCommandOutput) => void ): void; public createApplicationVersion( args: CreateApplicationVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateApplicationVersionCommandOutput) => void ): void; public createApplicationVersion( args: CreateApplicationVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateApplicationVersionCommandOutput) => void), cb?: (err: any, data?: CreateApplicationVersionCommandOutput) => void ): Promise<CreateApplicationVersionCommandOutput> | void { const command = new CreateApplicationVersionCommand(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 AWS CloudFormation change set for the given application.</p> */ public createCloudFormationChangeSet( args: CreateCloudFormationChangeSetCommandInput, options?: __HttpHandlerOptions ): Promise<CreateCloudFormationChangeSetCommandOutput>; public createCloudFormationChangeSet( args: CreateCloudFormationChangeSetCommandInput, cb: (err: any, data?: CreateCloudFormationChangeSetCommandOutput) => void ): void; public createCloudFormationChangeSet( args: CreateCloudFormationChangeSetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateCloudFormationChangeSetCommandOutput) => void ): void; public createCloudFormationChangeSet( args: CreateCloudFormationChangeSetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCloudFormationChangeSetCommandOutput) => void), cb?: (err: any, data?: CreateCloudFormationChangeSetCommandOutput) => void ): Promise<CreateCloudFormationChangeSetCommandOutput> | void { const command = new CreateCloudFormationChangeSetCommand(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 AWS CloudFormation template.</p> */ public createCloudFormationTemplate( args: CreateCloudFormationTemplateCommandInput, options?: __HttpHandlerOptions ): Promise<CreateCloudFormationTemplateCommandOutput>; public createCloudFormationTemplate( args: CreateCloudFormationTemplateCommandInput, cb: (err: any, data?: CreateCloudFormationTemplateCommandOutput) => void ): void; public createCloudFormationTemplate( args: CreateCloudFormationTemplateCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateCloudFormationTemplateCommandOutput) => void ): void; public createCloudFormationTemplate( args: CreateCloudFormationTemplateCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCloudFormationTemplateCommandOutput) => void), cb?: (err: any, data?: CreateCloudFormationTemplateCommandOutput) => void ): Promise<CreateCloudFormationTemplateCommandOutput> | void { const command = new CreateCloudFormationTemplateCommand(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 application.</p> */ public deleteApplication( args: DeleteApplicationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteApplicationCommandOutput>; public deleteApplication( args: DeleteApplicationCommandInput, cb: (err: any, data?: DeleteApplicationCommandOutput) => void ): void; public deleteApplication( args: DeleteApplicationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteApplicationCommandOutput) => void ): void; public deleteApplication( args: DeleteApplicationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteApplicationCommandOutput) => void), cb?: (err: any, data?: DeleteApplicationCommandOutput) => void ): Promise<DeleteApplicationCommandOutput> | void { const command = new DeleteApplicationCommand(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>Gets the specified application.</p> */ public getApplication( args: GetApplicationCommandInput, options?: __HttpHandlerOptions ): Promise<GetApplicationCommandOutput>; public getApplication( args: GetApplicationCommandInput, cb: (err: any, data?: GetApplicationCommandOutput) => void ): void; public getApplication( args: GetApplicationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetApplicationCommandOutput) => void ): void; public getApplication( args: GetApplicationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetApplicationCommandOutput) => void), cb?: (err: any, data?: GetApplicationCommandOutput) => void ): Promise<GetApplicationCommandOutput> | void { const command = new GetApplicationCommand(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>Retrieves the policy for the application.</p> */ public getApplicationPolicy( args: GetApplicationPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<GetApplicationPolicyCommandOutput>; public getApplicationPolicy( args: GetApplicationPolicyCommandInput, cb: (err: any, data?: GetApplicationPolicyCommandOutput) => void ): void; public getApplicationPolicy( args: GetApplicationPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetApplicationPolicyCommandOutput) => void ): void; public getApplicationPolicy( args: GetApplicationPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetApplicationPolicyCommandOutput) => void), cb?: (err: any, data?: GetApplicationPolicyCommandOutput) => void ): Promise<GetApplicationPolicyCommandOutput> | void { const command = new GetApplicationPolicyCommand(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>Gets the specified AWS CloudFormation template.</p> */ public getCloudFormationTemplate( args: GetCloudFormationTemplateCommandInput, options?: __HttpHandlerOptions ): Promise<GetCloudFormationTemplateCommandOutput>; public getCloudFormationTemplate( args: GetCloudFormationTemplateCommandInput, cb: (err: any, data?: GetCloudFormationTemplateCommandOutput) => void ): void; public getCloudFormationTemplate( args: GetCloudFormationTemplateCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetCloudFormationTemplateCommandOutput) => void ): void; public getCloudFormationTemplate( args: GetCloudFormationTemplateCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetCloudFormationTemplateCommandOutput) => void), cb?: (err: any, data?: GetCloudFormationTemplateCommandOutput) => void ): Promise<GetCloudFormationTemplateCommandOutput> | void { const command = new GetCloudFormationTemplateCommand(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>Retrieves the list of applications nested in the containing application.</p> */ public listApplicationDependencies( args: ListApplicationDependenciesCommandInput, options?: __HttpHandlerOptions ): Promise<ListApplicationDependenciesCommandOutput>; public listApplicationDependencies( args: ListApplicationDependenciesCommandInput, cb: (err: any, data?: ListApplicationDependenciesCommandOutput) => void ): void; public listApplicationDependencies( args: ListApplicationDependenciesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListApplicationDependenciesCommandOutput) => void ): void; public listApplicationDependencies( args: ListApplicationDependenciesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApplicationDependenciesCommandOutput) => void), cb?: (err: any, data?: ListApplicationDependenciesCommandOutput) => void ): Promise<ListApplicationDependenciesCommandOutput> | void { const command = new ListApplicationDependenciesCommand(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 applications owned by the requester.</p> */ public listApplications( args: ListApplicationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListApplicationsCommandOutput>; public listApplications( args: ListApplicationsCommandInput, cb: (err: any, data?: ListApplicationsCommandOutput) => void ): void; public listApplications( args: ListApplicationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListApplicationsCommandOutput) => void ): void; public listApplications( args: ListApplicationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApplicationsCommandOutput) => void), cb?: (err: any, data?: ListApplicationsCommandOutput) => void ): Promise<ListApplicationsCommandOutput> | void { const command = new ListApplicationsCommand(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 versions for the specified application.</p> */ public listApplicationVersions( args: ListApplicationVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<ListApplicationVersionsCommandOutput>; public listApplicationVersions( args: ListApplicationVersionsCommandInput, cb: (err: any, data?: ListApplicationVersionsCommandOutput) => void ): void; public listApplicationVersions( args: ListApplicationVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListApplicationVersionsCommandOutput) => void ): void; public listApplicationVersions( args: ListApplicationVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListApplicationVersionsCommandOutput) => void), cb?: (err: any, data?: ListApplicationVersionsCommandOutput) => void ): Promise<ListApplicationVersionsCommandOutput> | void { const command = new ListApplicationVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Sets the permission policy for an application. For the list of actions supported for this operation, see * <a href="https://docs.aws.amazon.com/serverlessrepo/latest/devguide/access-control-resource-based.html#application-permissions">Application * Permissions</a> * .</p> */ public putApplicationPolicy( args: PutApplicationPolicyCommandInput, options?: __HttpHandlerOptions ): Promise<PutApplicationPolicyCommandOutput>; public putApplicationPolicy( args: PutApplicationPolicyCommandInput, cb: (err: any, data?: PutApplicationPolicyCommandOutput) => void ): void; public putApplicationPolicy( args: PutApplicationPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutApplicationPolicyCommandOutput) => void ): void; public putApplicationPolicy( args: PutApplicationPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutApplicationPolicyCommandOutput) => void), cb?: (err: any, data?: PutApplicationPolicyCommandOutput) => void ): Promise<PutApplicationPolicyCommandOutput> | void { const command = new PutApplicationPolicyCommand(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>Unshares an application from an AWS Organization.</p><p>This operation can be called only from the organization's master account.</p> */ public unshareApplication( args: UnshareApplicationCommandInput, options?: __HttpHandlerOptions ): Promise<UnshareApplicationCommandOutput>; public unshareApplication( args: UnshareApplicationCommandInput, cb: (err: any, data?: UnshareApplicationCommandOutput) => void ): void; public unshareApplication( args: UnshareApplicationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UnshareApplicationCommandOutput) => void ): void; public unshareApplication( args: UnshareApplicationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UnshareApplicationCommandOutput) => void), cb?: (err: any, data?: UnshareApplicationCommandOutput) => void ): Promise<UnshareApplicationCommandOutput> | void { const command = new UnshareApplicationCommand(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 specified application.</p> */ public updateApplication( args: UpdateApplicationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateApplicationCommandOutput>; public updateApplication( args: UpdateApplicationCommandInput, cb: (err: any, data?: UpdateApplicationCommandOutput) => void ): void; public updateApplication( args: UpdateApplicationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateApplicationCommandOutput) => void ): void; public updateApplication( args: UpdateApplicationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateApplicationCommandOutput) => void), cb?: (err: any, data?: UpdateApplicationCommandOutput) => void ): Promise<UpdateApplicationCommandOutput> | void { const command = new UpdateApplicationCommand(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 React, { useMemo, useCallback } from 'react'; import { useIntl } from 'react-intl'; import { useSwipeable } from 'react-swipeable'; import { Line, Bar, LinePath } from '@visx/shape'; import { GridRows } from '@visx/grid'; import { Group } from '@visx/group'; import { scaleTime, scaleLinear } from '@visx/scale'; import { withTooltip, TooltipWithBounds } from '@visx/tooltip'; import { WithTooltipProvidedProps } from '@visx/tooltip/lib/enhancers/withTooltip'; import { localPoint } from '@visx/event'; import { AxisBottom, AxisLeft } from '@visx/axis'; import { max, min, extent, bisector } from 'd3-array'; import dayjs from 'dayjs'; import { useThemeContext } from '@aave/aave-ui-kit'; import ValuePercent from '../../basic/ValuePercent'; import staticStyles from './style'; import { GraphPoint } from '../types'; interface AreaProps { width: number; height: number; margin?: { top: number; right: number; bottom: number; left: number }; graphHeight: number; data: GraphPoint[]; secondData?: GraphPoint[]; colors: string[]; tooltipName: string[]; withAxisLeft?: boolean; withAxisBottom?: boolean; maxYaxis?: number; } interface TooltipData { date: number; values: { name: string; value: number }[]; } export default withTooltip<AreaProps, TooltipData>( ({ width, margin = { top: 0, right: 0, bottom: 0, left: 0 }, graphHeight, data, secondData, showTooltip, hideTooltip, tooltipData, tooltipTop = 0, tooltipLeft = 0, colors, tooltipName, withAxisLeft, withAxisBottom, maxYaxis, }: AreaProps & WithTooltipProvidedProps<TooltipData>) => { const intl = useIntl(); const { currentTheme, sm } = useThemeContext(); const getSeriesDate = (d: GraphPoint) => new Date(dayjs.unix(+d[0]).format()); const getSeriesValue = (d: GraphPoint) => d[1]; const bisectDate = bisector<GraphPoint, Date>((d) => new Date(dayjs.unix(+d[0]).format())).left; // bounds const formatWidth = width - margin.left - margin.right - 20; const innerWidth = formatWidth > 0 ? formatWidth : 0; const axisLeftPosition = withAxisLeft ? 40 : 20; const formattedWidth = withAxisLeft ? innerWidth - axisLeftPosition - 5 : innerWidth - 5; const finalWidth = formattedWidth > 0 ? formattedWidth : 0; const axisBottomPosition = 20; const innerHeight = graphHeight - margin.top - margin.bottom; const formattedHeight = withAxisBottom ? innerHeight - axisBottomPosition : innerHeight; // scales const dateScale = useMemo( () => scaleTime({ range: [margin.left, finalWidth + margin.left], domain: !!data.length ? (extent(data, getSeriesDate) as [Date, Date]) : [], }), // eslint-disable-next-line react-hooks/exhaustive-deps [finalWidth, margin.left] ); const valueScale = useMemo( () => scaleLinear({ range: [formattedHeight + margin.top, margin.top], domain: !!data.length ? [ (min(data, getSeriesValue) || 0) - formattedHeight / 2.5 < 0 ? 0 : (min(data, getSeriesValue) || 0) - formattedHeight / 2.5, ((max(data, getSeriesValue) || 0) === 0 ? 1 : max(data, getSeriesValue) || 0) * 1.05, ] : [], nice: true, }), // eslint-disable-next-line react-hooks/exhaustive-deps [margin.top, formattedHeight] ); const valueScaleWithMax = useMemo( () => scaleLinear({ range: [formattedHeight + margin.top, margin.top], domain: !!data.length ? [ (min(data, getSeriesValue) || 0) - formattedHeight / 2.5 < 0 ? 0 : (min(data, getSeriesValue) || 0) - formattedHeight / 2.5, (max(data, getSeriesValue) || 0) > (maxYaxis || 0) ? maxYaxis || 0 : (max(data, getSeriesValue) || 0) === 0 ? 1 : max(data, getSeriesValue) || 0, ] : [], nice: true, }), // eslint-disable-next-line react-hooks/exhaustive-deps [margin.top, formattedHeight] ); const axisBottomScale = useMemo( () => scaleTime({ range: [margin.left, (withAxisLeft ? finalWidth : finalWidth - 40) + margin.left], domain: !!data.length ? (extent(data, getSeriesDate) as [Date, Date]) : [], }), // eslint-disable-next-line react-hooks/exhaustive-deps [finalWidth, margin.left] ); // tooltip handler const tooltipDataCalculation = ( event: React.TouchEvent<SVGRectElement> | React.MouseEvent<SVGRectElement>, data: GraphPoint[], secondData?: GraphPoint[], second?: boolean ) => { const { x } = localPoint(event) || { x: 0 }; const x0 = dateScale.invert(withAxisLeft ? x - axisLeftPosition : x); const index = bisectDate(data, x0, 1); const d = data[index - 1]; const d1 = secondData ? secondData[index - 1] : []; showTooltip({ tooltipData: { date: +d[0], values: second ? [ { name: tooltipName[0], value: +d[1] }, { name: tooltipName[1], value: +d1[1] }, ] : [{ name: tooltipName[0], value: +d[1] }], }, tooltipLeft: x, tooltipTop: maxYaxis ? valueScaleWithMax(getSeriesValue(d)) : valueScale(getSeriesValue(d)), }); }; const handleTooltip = useCallback( (event: React.TouchEvent<SVGRectElement> | React.MouseEvent<SVGRectElement>) => { tooltipDataCalculation(event, data); if (secondData) { tooltipDataCalculation(event, data, secondData, true); } }, // eslint-disable-next-line react-hooks/exhaustive-deps [showTooltip, valueScale, valueScaleWithMax, dateScale] ); const yScale = maxYaxis ? valueScaleWithMax : valueScale; const handlers = useSwipeable({ onSwipedLeft: (e) => e.event.stopPropagation(), }); return ( <div {...handlers} className="VisxHistoricalRatesGraph"> <svg width={width} height={innerHeight + 8}> {withAxisLeft && ( <AxisLeft left={axisLeftPosition} stroke={currentTheme.white.hex} tickStroke={currentTheme.white.hex} scale={maxYaxis ? valueScaleWithMax : valueScale} hideTicks={true} tickComponent={(tickRendererProps) => ( <text x={tickRendererProps.x - 20} y={tickRendererProps.y} className="VisxHistoricalRatesGraph__axisLeft--tick" > {intl.formatNumber(+(tickRendererProps.formattedValue || 0), { maximumFractionDigits: 2, })} % </text> )} tickLabelProps={() => ({ fontFamily: 'roboto-font', })} numTicks={5} /> )} {withAxisBottom && ( <AxisBottom top={formattedHeight} left={axisLeftPosition} scale={axisBottomScale} stroke={currentTheme.white.hex} tickStroke={currentTheme.white.hex} tickLabelProps={() => ({ fontFamily: 'roboto-font', fill: currentTheme.white.hex, fontSize: 10, textAnchor: 'middle', })} hideZero={true} numTicks={sm ? 3 : 4} /> )} <Group left={withAxisLeft ? axisLeftPosition : 0}> <GridRows left={margin.left} scale={maxYaxis ? valueScaleWithMax : valueScale} width={formattedWidth} stroke={currentTheme.white.hex} strokeOpacity={0.2} pointerEvents="none" /> <LinePath stroke={colors[0]} strokeWidth={2} data={data} x={(d) => dateScale(getSeriesDate(d)) ?? 0} y={(d) => yScale(getSeriesValue(d)) ?? 0} /> {secondData && ( <LinePath stroke={colors[1]} strokeWidth={2} data={secondData} x={(d) => dateScale(getSeriesDate(d)) ?? 0} y={(d) => yScale(getSeriesValue(d)) ?? 0} /> )} <Bar x={margin.left} y={margin.top} width={finalWidth} height={formattedHeight} fill="transparent" onTouchStart={handleTooltip} onTouchMove={handleTooltip} onMouseMove={handleTooltip} onMouseLeave={() => hideTooltip()} /> </Group> {tooltipData && ( <g> <Line from={{ x: tooltipLeft, y: margin.top }} to={{ x: tooltipLeft, y: withAxisLeft ? formattedHeight + margin.top + 5 : formattedHeight + margin.top, }} stroke={currentTheme.white.hex} strokeWidth={1} strokeOpacity={0.5} pointerEvents="none" strokeDasharray="4" /> {tooltipData.values.map((value, index) => ( <React.Fragment key={index}> <circle cx={tooltipLeft} cy={yScale(value.value)} r={3} fill="black" fillOpacity={0.1} stroke="black" strokeOpacity={0.1} strokeWidth={2} pointerEvents="none" /> <circle cx={tooltipLeft} cy={yScale(value.value)} r={3} fill={colors[index]} stroke="white" strokeWidth={1} pointerEvents="none" /> </React.Fragment> ))} </g> )} </svg> {tooltipData && ( <> <TooltipWithBounds className="VisxHistoricalRatesGraph__valueTooltipInner" key={Math.random()} top={tooltipTop - 12} left={tooltipLeft + 12} > <div className="VisxHistoricalRatesGraph__tooltipDate"> {dayjs.unix(tooltipData.date).format('DD MMM')} </div> <div className="VisxHistoricalRatesGraph__tooltipValues"> {tooltipData.values.map((value, index) => ( <div className="VisxHistoricalRatesGraph__tooltipValue" key={index}> <div className="VisxHistoricalRatesGraph__tooltipValue--text"> <div className="VisxHistoricalRatesGraph__tooltipValue-dot" style={{ background: `${colors[index]}`, }} /> <p className="VisxHistoricalRatesGraph__tooltipValue-name">{value.name}:</p> </div> <ValuePercent value={value.value / 100} color="secondary" /> </div> ))} </div> </TooltipWithBounds> </> )} <style jsx={true} global={true}> {staticStyles} </style> <style jsx={true} global={true}>{` .VisxHistoricalRatesGraph { &__axisLeft--tick { fill: ${currentTheme.white.hex}; } &__valueTooltipInner { color: ${currentTheme.darkBlue.hex}; } &__tooltipDate { border-bottom: 1px solid ${currentTheme.lightBlue.hex}; } &__tooltipValues { .ValuePercent .ValuePercent__value { color: ${currentTheme.darkBlue.hex} !important; span { color: ${currentTheme.darkBlue.hex} !important; } } } } `}</style> </div> ); } );
the_stack
import { Diagram } from '../diagram'; import { DiagramModel } from '../diagram-model'; import { HistoryEntry, History } from '../diagram/history'; import { SelectorModel } from '../objects/node-model'; import { NodeModel, PhaseModel, LaneModel } from '../objects/node-model'; import { SwimLane, Selector } from '../objects/node'; import { Node, BpmnAnnotation } from './node'; import { Connector } from './connector'; import { ConnectorModel } from '../objects/connector-model'; import { DiagramAction, HistoryEntryType } from '../enum/enum'; import { removeItem, getObjectType } from '../utility/diagram-util'; import { cloneObject, getFunction } from '../utility/base-util'; import { IElement, StackEntryObject, IBlazorCustomHistoryChangeArgs, HistoryChangeEventObject } from '../objects/interface/IElement'; import { ShapeAnnotationModel, PathAnnotationModel } from '../objects/annotation-model'; import { PointPortModel, PortModel } from '../objects/port-model'; import { ShapeAnnotation, PathAnnotation } from '../objects/annotation'; import { findAnnotation, findPort } from '../utility/diagram-util'; import { PointPort } from './port'; import { Size, GridPanel, addChildToContainer } from '../index'; import { swimLaneMeasureAndArrange, laneInterChanged, findLaneIndex, updateSwimLaneObject, pasteSwimLane } from '../utility/swim-lane-util'; import { ICustomHistoryChangeArgs } from '../objects/interface/IElement'; import { DiagramEvent, BlazorAction } from '../enum/enum'; import { isBlazor } from '@syncfusion/ej2-base'; /** * Undo redo function used for revert and restore the changes */ export class UndoRedo { private groupUndo: boolean = false; private childTable: NodeModel[] = []; private historyCount: number = 0; private hasGroup: boolean = false; private groupCount: number = 0; /** * initHistory method \ * * @returns { void } initHistory method .\ * @param {Diagram} diagram - provide the points value. * * @private */ public initHistory(diagram: Diagram): void { diagram.historyManager = { canRedo: false, canUndo: false, currentEntry: null, push: diagram.addHistoryEntry.bind(diagram), undo: Function, redo: Function, startGroupAction: diagram.startGroupAction.bind(diagram), endGroupAction: diagram.endGroupAction.bind(diagram), canLog: null, undoStack: [], redoStack: [], stackLimit: diagram.historyManager ? diagram.historyManager.stackLimit : undefined }; } /** * addHistoryEntry method \ * * @returns { void } addHistoryEntry method .\ * @param {HistoryEntry} entry - provide the points value. * @param {Diagram} diagram - provide the points value. * * @private */ public addHistoryEntry(entry: HistoryEntry, diagram: Diagram): void { let entryObject: HistoryEntry = null; let nextEntry: HistoryEntry = null; if (diagram.historyManager.canLog) { const hEntry: HistoryEntry = diagram.historyManager.canLog(entry); if (hEntry.cancel === true) { return; } } if (diagram.historyManager && diagram.historyManager.canUndo && diagram.historyManager.currentEntry) { entryObject = diagram.historyManager.currentEntry; if (entryObject.next) { if (entryObject.previous) { nextEntry = entryObject.next; nextEntry.previous = null; entryObject.next = entry; entry.previous = entryObject; } } else { entryObject.next = entry; entry.previous = entryObject; } } diagram.historyManager.currentEntry = entry; if (diagram.historyManager.stackLimit) { if (entry.type === 'StartGroup' || entry.type === 'EndGroup') { const value: boolean = entry.type === 'EndGroup' ? true : false; this.setEntryLimit(value); } if (!this.hasGroup && this.groupCount === 0) { if (this.historyCount < diagram.historyManager.stackLimit) { this.historyCount++; } else { this.applyLimit(diagram.historyManager.currentEntry, diagram.historyManager.stackLimit, diagram); } } } this.getHistoryList(diagram); diagram.historyManager.canUndo = true; diagram.historyManager.canRedo = false; } /** * applyLimit method \ * * @returns { void } applyLimit method .\ * @param {HistoryEntry} list - provide the list value. * @param {number} stackLimit - provide the list value. * @param {Diagram} diagram - provide the list value. * @param {boolean} limitHistory - provide the list value. * * @private */ public applyLimit(list: HistoryEntry, stackLimit: number, diagram: Diagram, limitHistory?: boolean): void { if (list && list.previous) { if (list.type === 'StartGroup' || list.type === 'EndGroup') { const value: boolean = list.type === 'StartGroup' ? true : false; this.setEntryLimit(value); } if (!this.hasGroup && this.groupCount === 0) { stackLimit--; } if (stackLimit === 0) { if (limitHistory) { this.limitHistoryStack(list.previous, diagram); } if (diagram.historyManager.stackLimit < this.historyCount) { this.historyCount = diagram.historyManager.stackLimit; } delete list.previous; } else if (list.previous) { this.applyLimit(list.previous, stackLimit, diagram, limitHistory); } } this.groupCount = 0; } /** * clearHistory method \ * * @returns { void } clearHistory method .\ * @param {Diagram} diagram - provide the points value. * * @private */ public clearHistory(diagram: Diagram): void { const hList: History = diagram.historyManager; hList.currentEntry = undefined; hList.canUndo = false; hList.canRedo = false; this.historyCount = 0; this.groupCount = 0; diagram.historyManager.undoStack = []; diagram.historyManager.redoStack = []; } private setEntryLimit(value: boolean): void { // eslint-disable-next-line @typescript-eslint/no-unused-expressions value ? this.groupCount-- : this.groupCount++; // eslint-disable-next-line @typescript-eslint/no-unused-expressions value ? this.hasGroup = !value : this.hasGroup = value; } private limitHistoryStack(list: HistoryEntry, diagram: Diagram): void { if (list.type !== 'StartGroup' && list.type !== 'EndGroup') { this.removeFromStack(diagram.historyManager.undoStack, list); this.removeFromStack(diagram.historyManager.redoStack, list); } if (list.previous) { this.limitHistoryStack(list.previous, diagram); } } private removeFromStack(entyList: HistoryEntry[], list: HistoryEntry): void { if (entyList.length) { for (let i: number = 0; i <= entyList.length; i++) { if (entyList[i].undoObject === list.undoObject && entyList[i].redoObject === list.redoObject) { entyList.splice(i, 1); break; } } } } /** * undo method \ * * @returns { void } undo method .\ * @param {Diagram} diagram - provide the diagram value. * * @private */ public undo(diagram: Diagram): void { const entry: HistoryEntry = this.getUndoEntry(diagram); let endGroupActionCount: number = 0; if (entry) { if (entry.category === 'Internal') { if (entry.type === 'EndGroup') { endGroupActionCount++; this.groupUndo = true; if (isBlazor()) { diagram.blazorActions |= BlazorAction.GroupingInProgress; } } else { this.undoEntry(entry, diagram); } if (this.groupUndo) { this.undoGroupAction(entry, diagram, endGroupActionCount); this.groupUndo = false; } } else { if (!isBlazor()) { diagram.historyManager.undo(entry); } let arg: ICustomHistoryChangeArgs | IBlazorCustomHistoryChangeArgs = { entryType: 'undo', oldValue: entry.undoObject, newValue: entry.redoObject }; if (isBlazor()) { arg = { entryType: 'undo', oldValue: this.getHistoryChangeEvent(entry.undoObject, entry.blazorHistoryEntryType), newValue: this.getHistoryChangeEvent(entry.redoObject, entry.blazorHistoryEntryType) }; } diagram.triggerEvent(DiagramEvent.historyStateChange, arg); } } } private getHistoryChangeEvent( object: NodeModel | ConnectorModel | SelectorModel | DiagramModel | ShapeAnnotation | PathAnnotation | PointPortModel, prop: HistoryEntryType): HistoryChangeEventObject { const value: HistoryChangeEventObject = {}; switch (prop) { case 'Node': value.node = object as Node; break; case 'Connector': value.connector = object as Connector; break; case 'Selector': value.selector = object as Selector; break; case 'Diagram': value.diagram = object as Diagram; break; case 'ShapeAnnotation': value.shapeAnnotation = object as ShapeAnnotation; break; case 'PathAnnotation': value.pathAnnotation = object as PathAnnotation; break; case 'PortObject': value.pointPortModel = object as PortModel; break; case 'Object': value.object = object; } return value; } private getHistoryList(diagram: Diagram): void { const undoStack: HistoryEntry[] = []; const redoStack: HistoryEntry[] = []; let currEntry: HistoryEntry = diagram.historyManager.currentEntry; let undoObj: HistoryEntry; let redoObj: HistoryEntry; currEntry = diagram.historyManager.currentEntry; if (diagram.historyManager.canUndo || diagram.historyManager.undoStack.length === 0) { this.getHistroyObject(undoStack, currEntry); } else { this.getHistroyObject(redoStack, currEntry); } while (currEntry && currEntry.previous) { undoObj = currEntry.previous; this.getHistroyObject(undoStack, undoObj); currEntry = currEntry.previous; } currEntry = diagram.historyManager.currentEntry; while (currEntry && currEntry.next) { redoObj = currEntry.next; this.getHistroyObject(redoStack, redoObj); currEntry = currEntry.next; } diagram.historyManager.undoStack = undoStack; diagram.historyManager.redoStack = redoStack; } private getHistroyObject(list: HistoryEntry[], obj: HistoryEntry): void { if (obj && obj.type !== 'StartGroup' && obj.type !== 'EndGroup') { list.push({ redoObject: obj.redoObject ? obj.redoObject : null, undoObject: obj.undoObject ? obj.undoObject : null, type: obj.type ? obj.type : null, category: obj.category ? obj.category : null }); } } private undoGroupAction(entry: HistoryEntry, diagram: Diagram, endGroupActionCount: number): void { while (endGroupActionCount !== 0) { this.undoEntry(entry, diagram); entry = this.getUndoEntry(diagram); if (entry.type === 'StartGroup') { endGroupActionCount--; } else if (entry.type === 'EndGroup') { endGroupActionCount++; } } endGroupActionCount = 0; } private undoEntry(entry: HistoryEntry, diagram: Diagram): void { let obj: SelectorModel; let nodeObject: SelectorModel | Node; if (entry.type !== 'PropertyChanged' && entry.type !== 'CollectionChanged' && entry.type !== 'LabelCollectionChanged') { obj = (entry.undoObject) as SelectorModel; nodeObject = (entry.undoObject) as SelectorModel; } if (entry.type !== 'StartGroup' && entry.type !== 'EndGroup') { if (diagram.historyManager.undoStack.length > 0) { const addObject: HistoryEntry[] = diagram.historyManager.undoStack.splice(0, 1); diagram.historyManager.redoStack.splice(0, 0, addObject[0]); nodeObject = (entry.undoObject) as SelectorModel; } } diagram.protectPropertyChange(true); diagram.diagramActions |= DiagramAction.UndoRedo; if (isBlazor() && entry.previous && entry.previous.type === 'StartGroup') { diagram.blazorActions &= ~BlazorAction.GroupingInProgress; } switch (entry.type) { case 'PositionChanged': case 'Align': case 'Distribute': this.recordPositionChanged(obj, diagram); break; case 'SizeChanged': case 'Sizing': this.recordSizeChanged(obj, diagram, entry); break; case 'RotationChanged': this.recordRotationChanged(obj, diagram, entry); break; case 'ConnectionChanged': this.recordConnectionChanged(obj, diagram); break; case 'PropertyChanged': this.recordPropertyChanged(entry, diagram, false); break; case 'CollectionChanged': if (entry && entry.next && entry.next.type === 'AddChildToGroupNode' && entry.next.changeType === 'Insert') { const group: NodeModel = diagram.getObject((entry.next.undoObject as NodeModel).id); diagram.insertValue(cloneObject(group), true); } entry.isUndo = true; this.recordCollectionChanged(entry, diagram); entry.isUndo = false; if (entry && entry.next && entry.next.type === 'AddChildToGroupNode' && entry.next.changeType === 'Insert') { const group: NodeModel = diagram.getObject((entry.next.undoObject as NodeModel).id); group.wrapper.measure(new Size()); group.wrapper.arrange(group.wrapper.desiredSize); diagram.updateDiagramObject(group); } break; case 'LabelCollectionChanged': entry.isUndo = true; this.recordLabelCollectionChanged(entry, diagram); entry.isUndo = false; break; case 'PortCollectionChanged': entry.isUndo = true; this.recordPortCollectionChanged(entry, diagram); entry.isUndo = false; break; case 'Group': this.unGroup(entry, diagram); break; case 'UnGroup': this.group(entry, diagram); break; case 'SegmentChanged': this.recordSegmentChanged(obj, diagram); break; case 'PortPositionChanged': this.recordPortChanged(entry, diagram, false); break; case 'AnnotationPropertyChanged': this.recordAnnotationChanged(entry, diagram, false); break; case 'ChildCollectionChanged': this.recordChildCollectionChanged(entry, diagram, false); break; case 'StackChildPositionChanged': this.recordStackPositionChanged(entry, diagram, false); break; case 'RowHeightChanged': this.recordGridSizeChanged(entry, diagram, false, true); break; case 'ColumnWidthChanged': this.recordGridSizeChanged(entry, diagram, false, false); break; case 'LanePositionChanged': this.recordLanePositionChanged(entry, diagram, false); break; case 'LaneCollectionChanged': case 'PhaseCollectionChanged': entry.isUndo = true; this.recordLaneOrPhaseCollectionChanged(entry, diagram, false); entry.isUndo = false; break; case 'SendToBack': case 'SendForward': case 'SendBackward': case 'BringToFront': this.recordOrderCommandChanged(entry, diagram, false); break; case 'AddChildToGroupNode': this.recordAddChildToGroupNode(entry, diagram, false); break; } diagram.diagramActions &= ~DiagramAction.UndoRedo; diagram.protectPropertyChange(false); diagram.historyChangeTrigger(entry, 'Undo'); if (nodeObject) { const object: NodeModel | ConnectorModel = this.checkNodeObject(nodeObject, diagram); if (object) { const getnodeDefaults: Function = getFunction(diagram.updateSelection); if (getnodeDefaults) { getnodeDefaults(object, diagram); } } } } private checkNodeObject(value: SelectorModel | Node, diagram: Diagram): NodeModel | ConnectorModel { let object: NodeModel | ConnectorModel; if (!(value as Node).id) { if (((value as SelectorModel).nodes && (value as SelectorModel).nodes.length > 0) || ((value as SelectorModel).connectors && (value as SelectorModel).connectors.length > 0)) { const undoNode: NodeModel[] | ConnectorModel[] = (value as SelectorModel).nodes.length > 0 ? (value as SelectorModel).nodes : (value as SelectorModel).connectors; for (object of undoNode) { object = diagram.nameTable[object.id]; } } else { const knownNode: NodeModel[] | ConnectorModel[] = (value as SelectorModel).nodes ? (value as SelectorModel).nodes : (value as SelectorModel).connectors; if (knownNode) { for (const key of Object.keys(knownNode)) { const index: number = Number(key); object = (value as SelectorModel).nodes ? diagram.nodes[index] as Node : diagram.connectors[index]; } } } } else { object = diagram.nameTable[(value as Node).id]; } return object; } private group(historyEntry: HistoryEntry, diagram: Diagram): void { diagram.add(historyEntry.undoObject as IElement); } private unGroup(entry: HistoryEntry, diagram: Diagram): void { //const i: number = 0; entry.redoObject = cloneObject(entry.undoObject); const node: NodeModel = entry.undoObject as Node; diagram.commandHandler.unGroup(node); } private ignoreProperty(key: string): boolean { if (key === 'zIndex' || key === 'wrapper' || key === 'parentObj' || key === 'controlParent') { return true; } return false; } private getProperty(collection: Object, property: Object): void { for (const key of Object.keys(property)) { if (collection) { if (!this.ignoreProperty(key)) { if (property[key] instanceof Object) { this.getProperty(collection[key] as Object, property[key] as Object); } else { collection[key] = property[key]; } } } } } // eslint-disable-next-line @typescript-eslint/no-unused-vars private recordLaneOrPhaseCollectionChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const node: NodeModel = entry.redoObject as NodeModel; const obj: LaneModel | PhaseModel = entry.undoObject as LaneModel | PhaseModel; let changeType: string; if (entry.isUndo) { if (entry.changeType === 'Insert') { changeType = 'Remove'; } else { changeType = 'Insert'; } } else { changeType = entry.changeType; } if (changeType === 'Remove') { diagram.remove(node); } else { if ((node as Node).isPhase) { const swimlane: NodeModel = diagram.nameTable[(node as Node).parentId]; diagram.addPhases(swimlane, [obj]); } else { const swimlane: NodeModel = diagram.nameTable[(node as Node).parentId]; const laneIndex: number = findLaneIndex(swimlane, node); diagram.addLanes(swimlane, [obj], laneIndex); } } diagram.clearSelection(); } private recordAnnotationChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const entryObject: NodeModel | ConnectorModel = ((isRedo) ? entry.redoObject : entry.undoObject) as NodeModel | ConnectorModel; if (diagram.canEnableBlazorObject) { const node: object = cloneObject(diagram.nameTable[entryObject.id]); diagram.insertValue(node, node instanceof Node ? true : false); } const oldElement: ShapeAnnotation | PathAnnotation = findAnnotation( entryObject, entry.objectId) as ShapeAnnotation | PathAnnotation; const undoChanges: Object = diagram.commandHandler.getAnnotationChanges(diagram.nameTable[entryObject.id], oldElement); const currentObject: NodeModel | ConnectorModel = diagram.nameTable[entryObject.id]; const currentElement: ShapeAnnotation | PathAnnotation = findAnnotation( currentObject, entry.objectId) as ShapeAnnotation | PathAnnotation; currentElement.offset = oldElement.offset; currentElement.margin = oldElement.margin; currentElement.width = oldElement.width; currentElement.height = oldElement.height; currentElement.rotateAngle = oldElement.rotateAngle; currentElement.margin = oldElement.margin; if (currentObject instanceof Node) { diagram.nodePropertyChange(currentObject as Node, {} as Node, undoChanges as Node); } else { diagram.connectorPropertyChange(currentObject as Connector, {} as Connector, undoChanges as Connector); } } private recordChildCollectionChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const entryObject: NodeModel | ConnectorModel = ((isRedo) ? entry.redoObject : entry.undoObject) as NodeModel | ConnectorModel; let parentNode: NodeModel = diagram.nameTable[(entryObject as Node).parentId]; const actualObject: Node = diagram.nameTable[(entryObject as Node).id]; if (parentNode) { addChildToContainer(diagram, parentNode, actualObject, !isRedo, entry.historyAction === 'AddNodeToLane'); } else { if (actualObject.parentId) { parentNode = diagram.nameTable[actualObject.parentId]; parentNode.children.splice(parentNode.children.indexOf(actualObject.id), 1); parentNode.wrapper.children.splice(parentNode.wrapper.children.indexOf(actualObject.wrapper), 1); } if ((entryObject as Node).parentId && (entryObject as Node).parentId !== '') { parentNode = diagram.nameTable[(entryObject as Node).parentId]; parentNode.children.push((entryObject as Node).id); parentNode.wrapper.children.push(actualObject.wrapper); } actualObject.parentId = (entryObject as Node).parentId; diagram.removeElements(actualObject); diagram.updateDiagramObject(actualObject); } } private recordStackPositionChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const entryObject: StackEntryObject = ((isRedo) ? entry.redoObject : entry.undoObject) as StackEntryObject; if (entryObject.source) { const parent: Node = diagram.nameTable[(entryObject.source as Node).parentId]; if (parent) { if (entryObject.target) { parent.wrapper.children.splice(entryObject.targetIndex, 1); parent.wrapper.children.splice(entryObject.sourceIndex, 0, entryObject.source.wrapper); } else { if (entryObject.sourceIndex !== undefined) { if (!diagram.nameTable[entryObject.source.id]) { diagram.add(entryObject.source); } parent.wrapper.children.splice(entryObject.sourceIndex, 0, diagram.nameTable[entryObject.source.id].wrapper); diagram.nameTable[entryObject.source.id].parentId = parent.id; } else { parent.wrapper.children.splice( parent.wrapper.children.indexOf(diagram.nameTable[entryObject.source.id].wrapper), 1); diagram.nameTable[entryObject.source.id].parentId = ''; } } if (isRedo && parent.shape.type === 'UmlClassifier') { diagram.remove(entryObject.source); } parent.wrapper.measure(new Size()); parent.wrapper.arrange(parent.wrapper.desiredSize); diagram.updateDiagramObject(parent); diagram.updateSelector(); } } } private recordGridSizeChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean, isRow: boolean): void { const obj: Node = (isRedo) ? entry.redoObject as Node : entry.undoObject as Node; const node: Node = (!isRedo) ? entry.redoObject as Node : entry.undoObject as Node; if (obj.parentId) { const swimlane: NodeModel = diagram.nameTable[obj.parentId]; const actualObject: NodeModel = diagram.nameTable[obj.id]; const x: number = swimlane.wrapper.bounds.x; const y: number = swimlane.wrapper.bounds.y; if (swimlane.shape.type === 'SwimLane') { const grid: GridPanel = swimlane.wrapper.children[0] as GridPanel; const padding: number = (swimlane.shape as SwimLane).padding; updateSwimLaneObject(diagram, node, swimlane, obj); if (isRow) { grid.updateRowHeight(obj.rowIndex, obj.wrapper.actualSize.height, true, padding); swimlane.height = swimlane.wrapper.height = grid.height; } else { grid.updateColumnWidth(obj.columnIndex, obj.wrapper.actualSize.width, true, padding); swimlane.width = swimlane.wrapper.width = grid.width; if (obj.isPhase) { actualObject.maxWidth = actualObject.wrapper.maxWidth = obj.wrapper.actualSize.width; } } swimLaneMeasureAndArrange(swimlane); const tx: number = x - swimlane.wrapper.bounds.x; const ty: number = y - swimlane.wrapper.bounds.y; diagram.drag(swimlane, tx, ty); diagram.clearSelection(); diagram.updateDiagramObject(swimlane); } } } private recordLanePositionChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const entryObject: StackEntryObject = ((isRedo) ? entry.redoObject : entry.undoObject) as StackEntryObject; if (entryObject.source) { const parent: Node = diagram.nameTable[(entryObject.source as Node).parentId]; if (parent && parent.shape.type === 'SwimLane') { laneInterChanged(diagram, entryObject.target, entryObject.source); diagram.clearSelection(); } } } private recordPortChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const entryObject: NodeModel = ((isRedo) ? (entry.redoObject as SelectorModel).nodes[0] : (entry.undoObject as SelectorModel).nodes[0]); if (diagram.canEnableBlazorObject) { const node: object = cloneObject(diagram.nameTable[entryObject.id]); diagram.insertValue(node, true); } const oldElement: PointPort = findPort(entryObject, entry.objectId) as PointPort; const undoChanges: Object = diagram.commandHandler.getPortChanges(diagram.nameTable[entryObject.id], oldElement); const currentObject: NodeModel | ConnectorModel = diagram.nameTable[entryObject.id]; const currentElement: PointPort = findPort(currentObject, entry.objectId) as PointPort; currentElement.offset = oldElement.offset; diagram.nodePropertyChange(currentObject as Node, {} as Node, undoChanges as Node); if ((currentObject as Node).parentId) { diagram.updateConnectorEdges(diagram.nameTable[(currentObject as Node).parentId]); } } private recordPropertyChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const redoObject: DiagramModel = entry.redoObject as DiagramModel; const undoObject: DiagramModel = entry.undoObject as DiagramModel; if (isBlazor()) { for (const prop of Object.keys(undoObject)) { let obj: object; switch (prop) { case 'nodes': for (const key of Object.keys(undoObject.nodes)) { if (diagram.canEnableBlazorObject) { obj = cloneObject(diagram.nodes[Number(key)]); diagram.insertValue(obj, true); } } break; case 'connectors': for (const key of Object.keys(undoObject.connectors)) { if (diagram.canEnableBlazorObject) { obj = cloneObject(diagram.connectors[Number(key)]); diagram.insertValue(obj, false); } } break; } } } this.getProperty(diagram as Object, (isRedo ? redoObject : undoObject) as Object); // eslint-disable-next-line @typescript-eslint/no-unused-expressions isRedo ? diagram.onPropertyChanged(redoObject, undoObject) : diagram.onPropertyChanged(undoObject, redoObject); diagram.diagramActions = diagram.diagramActions | DiagramAction.UndoRedo; } private recordOrderCommandChanged(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const redoObject: Selector = entry.redoObject as Selector; const undoObject: Selector = entry.undoObject as Selector; diagram.commandHandler.orderCommands(isRedo, (isRedo ? redoObject : undoObject), entry.type); diagram.diagramActions = diagram.diagramActions | DiagramAction.UndoRedo; } private recordAddChildToGroupNode(entry: HistoryEntry, diagram: Diagram, isRedo: boolean): void { const group: Node = diagram.nameTable[(entry.undoObject as NodeModel).id]; const child: Node = diagram.nameTable[entry.objectId]; if (isRedo && entry.changeType === 'Insert') { diagram.addChildToGroup(group, child.id); } } private recordSegmentChanged(obj: SelectorModel, diagram: Diagram): void { let i: number = 0; //let node: NodeModel; let connector: ConnectorModel; if (obj.connectors && obj.connectors.length > 0) { for (i = 0; i < obj.connectors.length; i++) { connector = obj.connectors[i]; this.segmentChanged(connector, diagram); } } } private segmentChanged(connector: ConnectorModel, diagram: Diagram): void { const conn: ConnectorModel = diagram.nameTable[connector.id]; conn.segments = connector.segments; diagram.commandHandler.updateEndPoint(conn as Connector); } private recordPositionChanged(obj: SelectorModel, diagram: Diagram): void { let i: number = 0; let node: NodeModel; let connector: ConnectorModel; if (obj.nodes && obj.nodes.length > 0) { for (i = 0; i < obj.nodes.length; i++) { node = obj.nodes[i]; this.positionChanged(node, diagram); } } if (obj.connectors && obj.connectors.length > 0) { for (i = 0; i < obj.connectors.length; i++) { connector = obj.connectors[i]; this.connectionChanged(connector, diagram); } } } private positionChanged(obj: NodeModel, diagram: Diagram): void { const node: NodeModel = diagram.nameTable[obj.id]; if ((obj as Node).processId && !(node as Node).processId) { diagram.addProcess(obj as Node, (obj as Node).processId); } if (!(obj as Node).processId && (node as Node).processId) { diagram.removeProcess(obj.id); } if ((node as Node).processId) { const tx: number = (obj as NodeModel).margin.left - node.margin.left; const ty: number = (obj as NodeModel).margin.top - node.margin.top; diagram.drag(node, tx, ty); } else { if ((node as Node).parentId) { const parent: Node = diagram.nameTable[(node as Node).parentId]; if (parent.isLane) { obj.wrapper.offsetX = (obj.width / 2) + (parent.wrapper.bounds.x + obj.margin.left); obj.wrapper.offsetY = (obj.height / 2) + (parent.wrapper.bounds.y + obj.margin.top); } } const tx: number = (obj as NodeModel).wrapper.offsetX - node.offsetX; const ty: number = (obj as NodeModel).wrapper.offsetY - node.offsetY; diagram.drag(node, tx, ty); } if (diagram.bpmnModule) { diagram.bpmnModule.updateDocks(node as Node, diagram); } } private recordSizeChanged(obj: SelectorModel, diagram: Diagram, entry?: HistoryEntry): void { let i: number = 0; let connector: ConnectorModel; let node: NodeModel; if (obj && obj.nodes && obj.nodes.length > 0) { for (i = 0; i < obj.nodes.length; i++) { node = obj.nodes[i]; if (node.children && !node.container) { const elements: (NodeModel | ConnectorModel)[] = []; const nodes: (NodeModel | ConnectorModel)[] = diagram.commandHandler.getAllDescendants(node, elements); for (let i: number = 0; i < nodes.length; i++) { const tempNode: NodeModel | ConnectorModel = entry.childTable[nodes[i].id]; if ((getObjectType(tempNode) === Node)) { this.sizeChanged(tempNode, diagram, entry); this.positionChanged(tempNode as NodeModel, diagram); } else { this.connectionChanged(tempNode as ConnectorModel, diagram, entry); } } } else { this.sizeChanged(node, diagram); this.positionChanged(node, diagram); } } } if (obj && obj.connectors && obj.connectors.length > 0) { const connectors: ConnectorModel[] = obj.connectors; for (i = 0; i < connectors.length; i++) { connector = connectors[i]; this.connectionChanged(connector, diagram); } } } private sizeChanged(obj: NodeModel | ConnectorModel, diagram: Diagram, entry?: HistoryEntry): void { const node: NodeModel | ConnectorModel = diagram.nameTable[obj.id]; const scaleWidth: number = obj.wrapper.actualSize.width / node.wrapper.actualSize.width; const scaleHeight: number = obj.wrapper.actualSize.height / node.wrapper.actualSize.height; if (entry && entry.childTable) { entry.childTable[obj.id] = cloneObject(node); } diagram.scale(node, scaleWidth, scaleHeight, { x: obj.wrapper.offsetX / node.wrapper.offsetX, y: obj.wrapper.offsetY / node.wrapper.offsetY }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars private recordRotationChanged(obj: SelectorModel, diagram: Diagram, entry: HistoryEntry): void { let i: number = 0; let node: NodeModel; let connector: ConnectorModel; const selectorObj: SelectorModel = diagram.selectedItems; selectorObj.rotateAngle = obj.rotateAngle; if (selectorObj && selectorObj.wrapper) { selectorObj.wrapper.rotateAngle = obj.rotateAngle; } if (obj && obj.nodes && obj.nodes.length > 0) { for (i = 0; i < obj.nodes.length; i++) { node = obj.nodes[i]; this.rotationChanged(node, diagram); this.positionChanged(node, diagram); } } if (obj && obj.connectors && obj.connectors.length > 0) { for (i = 0; i < obj.connectors.length; i++) { connector = obj.connectors[i]; this.connectionChanged(connector, diagram); } } } private rotationChanged(obj: NodeModel, diagram: Diagram): void { const node: NodeModel = diagram.nameTable[obj.id]; diagram.rotate(node, obj.rotateAngle - node.rotateAngle); } private recordConnectionChanged(obj: SelectorModel, diagram: Diagram): void { const connector: ConnectorModel = (obj as SelectorModel).connectors[0]; if (connector.sourceID && diagram.nameTable[connector.sourceID]) { diagram.insertValue(diagram.nameTable[connector.sourceID], true); } if (connector.targetID && diagram.nameTable[connector.targetID]) { diagram.insertValue(diagram.nameTable[connector.targetID], true); } this.connectionChanged(connector, diagram); } private connectionChanged(obj: ConnectorModel, diagram: Diagram, entry?: HistoryEntry): void { const connector: ConnectorModel = diagram.nameTable[obj.id]; let node: Node; if (obj.sourcePortID !== connector.sourcePortID) { diagram.removePortEdges(diagram.nameTable[connector.sourceID], connector.sourcePortID, connector.id, false); connector.sourcePortID = obj.sourcePortID; diagram.connectorPropertyChange(connector as Connector, {} as Connector, { sourcePortID: obj.sourcePortID } as Connector); } if (obj.targetPortID !== connector.targetPortID) { diagram.removePortEdges(diagram.nameTable[connector.targetID], connector.targetPortID, connector.id, true); connector.targetPortID = obj.targetPortID; diagram.connectorPropertyChange(connector as Connector, {} as Connector, { targetPortID: obj.targetPortID } as Connector); } if (obj.sourceID !== connector.sourceID) { if (obj.sourceID === '') { node = diagram.nameTable[connector.sourceID]; removeItem(node.outEdges, obj.id); } else { node = diagram.nameTable[obj.sourceID]; node.outEdges.push(obj.id); diagram.updatePortEdges(node, obj, false); } connector.sourceID = obj.sourceID; diagram.connectorPropertyChange(connector as Connector, {} as Connector, { sourceID: obj.sourceID } as Connector); } if (obj.targetID !== connector.targetID) { if (obj.targetID === '') { node = diagram.nameTable[connector.targetID]; removeItem(node.inEdges, obj.id); } else { node = diagram.nameTable[obj.targetID]; node.inEdges.push(obj.id); diagram.updatePortEdges(node, obj, true); } connector.targetID = obj.targetID; diagram.connectorPropertyChange(connector as Connector, {} as Connector, { targetID: obj.targetID } as Connector); } if (entry && entry.childTable) { entry.childTable[obj.id] = cloneObject(connector); } const sx: number = obj.sourcePoint.x - connector.sourcePoint.x; const sy: number = obj.sourcePoint.y - connector.sourcePoint.y; if (sx !== 0 || sy !== 0) { diagram.dragSourceEnd(connector, sx, sy); } const tx: number = obj.targetPoint.x - connector.targetPoint.x; const ty: number = obj.targetPoint.y - connector.targetPoint.y; if (tx !== 0 || ty !== 0) { diagram.dragTargetEnd(connector, tx, ty); } diagram.updateSelector(); if (diagram.mode !== 'SVG') { diagram.refreshDiagramLayer(); } } private recordCollectionChanged(entry: HistoryEntry, diagram: Diagram): void { const obj: NodeModel | ConnectorModel = entry.undoObject as NodeModel | ConnectorModel; if (entry && entry.changeType) { let changeType: string; if (entry.isUndo) { if (entry.changeType === 'Insert') { changeType = 'Remove'; } else { changeType = 'Insert'; } } else { changeType = entry.changeType; } if (changeType === 'Remove') { if ((obj as BpmnAnnotation).nodeId) { diagram.remove(diagram.nameTable[(obj as BpmnAnnotation).nodeId + '_textannotation_' + obj.id]); } else { diagram.remove(obj); diagram.clearSelectorLayer(); } } else { diagram.clearSelectorLayer(); if ((obj as Node | Connector).parentId) { const parentNode: NodeModel = diagram.nameTable[(obj as Node | Connector).parentId]; if (parentNode) { diagram.addChild(parentNode, obj); } else { diagram.add(obj); } } else if ((obj as BpmnAnnotation).nodeId) { diagram.addTextAnnotation(obj, diagram.nameTable[(obj as BpmnAnnotation).nodeId]); } else { if (!diagram.nameTable[obj.id]) { if (obj && obj.shape && (obj as Node).shape.type === 'SwimLane' && entry.isUndo) { pasteSwimLane(obj as NodeModel, undefined, undefined, undefined, undefined, true); } diagram.add(obj); } } if ((obj as Node).processId && diagram.nameTable[(obj as Node).processId]) { diagram.addProcess((obj as Node), (obj as Node).processId); } } if (diagram.mode !== 'SVG') { diagram.refreshDiagramLayer(); } } } private recordLabelCollectionChanged(entry: HistoryEntry, diagram: Diagram): void { const label: ShapeAnnotationModel | PathAnnotationModel = entry.undoObject as ShapeAnnotationModel | PathAnnotationModel; const obj: Node | Connector = entry.redoObject as Node | Connector; const node: Node | Connector = diagram.nameTable[obj.id]; if (entry && entry.changeType) { let changeType: string; if (entry.isUndo) { changeType = (entry.changeType === 'Insert') ? 'Remove' : 'Insert'; } else { changeType = entry.changeType; } if (changeType === 'Remove') { diagram.removeLabels(node, [label] as ShapeAnnotationModel[] | PathAnnotationModel[]); diagram.clearSelectorLayer(); } else { diagram.clearSelectorLayer(); diagram.addLabels(node, [label] as ShapeAnnotationModel[] | PathAnnotationModel[]); } if (diagram.mode !== 'SVG') { diagram.refreshDiagramLayer(); } } } private recordPortCollectionChanged(entry: HistoryEntry, diagram: Diagram): void { const port: PointPortModel = entry.undoObject as PointPortModel; const obj: Node | Connector = entry.redoObject as Node | Connector; const node: NodeModel = diagram.nameTable[obj.id]; if (entry && entry.changeType) { let changeType: string; if (entry.isUndo) { changeType = (entry.changeType === 'Insert') ? 'Remove' : 'Insert'; } else { changeType = entry.changeType; } if (changeType === 'Remove') { diagram.removePorts(node as Node, [port]); diagram.clearSelectorLayer(); } else { diagram.clearSelectorLayer(); diagram.addPorts(node, [port]); } if (diagram.mode !== 'SVG') { diagram.refreshDiagramLayer(); } } } /** * redo method \ * * @returns { void } redo method .\ * @param {Diagram} diagram - provide the diagram value. * * @private */ public redo(diagram: Diagram): void { const entry: HistoryEntry = this.getRedoEntry(diagram); let startGroupActionCount: number = 0; if (entry) { if (entry.category === 'Internal') { if (entry.type === 'StartGroup') { startGroupActionCount++; this.groupUndo = true; if (isBlazor()) { diagram.blazorActions |= BlazorAction.GroupingInProgress; } } else { this.redoEntry(entry, diagram); } if (this.groupUndo) { this.redoGroupAction(entry, diagram, startGroupActionCount); this.groupUndo = false; } } else { if (!isBlazor()) { diagram.historyManager.redo(entry); } let arg: ICustomHistoryChangeArgs | IBlazorCustomHistoryChangeArgs = { entryType: 'redo', oldValue: entry.redoObject, newValue: entry.undoObject }; if (isBlazor()) { arg = { entryType: 'redo', oldValue: this.getHistoryChangeEvent(entry.redoObject, entry.blazorHistoryEntryType), newValue: this.getHistoryChangeEvent(entry.undoObject, entry.blazorHistoryEntryType) }; } diagram.triggerEvent(DiagramEvent.historyStateChange, arg); } } } private redoGroupAction(entry: HistoryEntry, diagram: Diagram, startGroupActionCount: number): void { while (startGroupActionCount !== 0) { this.redoEntry(entry, diagram); entry = this.getRedoEntry(diagram); if (entry.type === 'EndGroup') { startGroupActionCount--; } else if (entry.type === 'StartGroup') { startGroupActionCount++; } } startGroupActionCount = 0; } private redoEntry(historyEntry: HistoryEntry, diagram: Diagram): void { let redoObject: SelectorModel; let redovalue: SelectorModel | Node; if (historyEntry.type !== 'PropertyChanged' && historyEntry.type !== 'CollectionChanged') { redoObject = (historyEntry.redoObject) as SelectorModel; redovalue = (historyEntry.redoObject) as SelectorModel; } diagram.diagramActions |= DiagramAction.UndoRedo; if (historyEntry.type !== 'StartGroup' && historyEntry.type !== 'EndGroup') { if (diagram.historyManager.redoStack.length > 0) { const addObject: HistoryEntry[] = diagram.historyManager.redoStack.splice(0, 1); diagram.historyManager.undoStack.splice(0, 0, addObject[0]); redovalue = (historyEntry.redoObject) as SelectorModel; } } diagram.protectPropertyChange(true); if (isBlazor() && historyEntry.next && historyEntry.next.type === 'EndGroup') { diagram.blazorActions &= ~BlazorAction.GroupingInProgress; } switch (historyEntry.type) { case 'PositionChanged': case 'Align': case 'Distribute': this.recordPositionChanged(redoObject, diagram); break; case 'SizeChanged': case 'Sizing': this.recordSizeChanged(redoObject, diagram, historyEntry); break; case 'RotationChanged': this.recordRotationChanged(redoObject, diagram, historyEntry); break; case 'ConnectionChanged': this.recordConnectionChanged(redoObject, diagram); break; case 'PropertyChanged': this.recordPropertyChanged(historyEntry, diagram, true); break; case 'CollectionChanged': this.recordCollectionChanged(historyEntry, diagram); break; case 'LabelCollectionChanged': this.recordLabelCollectionChanged(historyEntry, diagram); break; case 'PortCollectionChanged': this.recordPortCollectionChanged(historyEntry, diagram); break; case 'Group': this.group(historyEntry, diagram); break; case 'UnGroup': this.unGroup(historyEntry, diagram); break; case 'SegmentChanged': this.recordSegmentChanged(redoObject, diagram); break; case 'PortPositionChanged': this.recordPortChanged(historyEntry, diagram, true); break; case 'AnnotationPropertyChanged': this.recordAnnotationChanged(historyEntry, diagram, true); break; case 'ChildCollectionChanged': this.recordChildCollectionChanged(historyEntry, diagram, true); break; case 'StackChildPositionChanged': this.recordStackPositionChanged(historyEntry, diagram, true); break; case 'RowHeightChanged': this.recordGridSizeChanged(historyEntry, diagram, true, true); break; case 'ColumnWidthChanged': this.recordGridSizeChanged(historyEntry, diagram, true, false); break; case 'LanePositionChanged': this.recordLanePositionChanged(historyEntry, diagram, true); break; case 'LaneCollectionChanged': case 'PhaseCollectionChanged': this.recordLaneOrPhaseCollectionChanged(historyEntry, diagram, true); break; case 'SendToBack': case 'SendForward': case 'SendBackward': case 'BringToFront': this.recordOrderCommandChanged(historyEntry, diagram, true); break; case 'AddChildToGroupNode': this.recordAddChildToGroupNode(historyEntry, diagram, true); break; } diagram.protectPropertyChange(false); diagram.diagramActions &= ~DiagramAction.UndoRedo; diagram.historyChangeTrigger(historyEntry, 'Redo'); if (redovalue) { const value: NodeModel | ConnectorModel = this.checkNodeObject(redovalue, diagram); if (value) { const getnodeDefaults: Function = getFunction(diagram.updateSelection); if (getnodeDefaults) { getnodeDefaults(value, diagram); } } } } private getUndoEntry(diagram: Diagram): HistoryEntry { let undoEntry: HistoryEntry = null; let currentObject: HistoryEntry; const hList: History = diagram.historyManager; if (hList.canUndo) { undoEntry = hList.currentEntry; currentObject = hList.currentEntry.previous; if (currentObject) { hList.currentEntry = currentObject; if (!hList.canRedo) { hList.canRedo = true; } } else { hList.canRedo = true; hList.canUndo = false; } } return undoEntry; } private getRedoEntry(diagram: Diagram): HistoryEntry { let redoEntry: HistoryEntry = null; let entryCurrent: HistoryEntry; const hList: History = diagram.historyManager; if (hList.canRedo) { if (!hList.currentEntry.previous && !hList.canUndo) { entryCurrent = hList.currentEntry; } else { entryCurrent = hList.currentEntry.next; } if (entryCurrent) { hList.currentEntry = entryCurrent; if (!hList.canUndo) { hList.canUndo = true; } if (!entryCurrent.next) { hList.canRedo = false; hList.canUndo = true; } } redoEntry = hList.currentEntry; } return redoEntry; } /** * Constructor for the undo redo module * * @private */ constructor() { //constructs the undo redo module } /** * To destroy the undo redo module * * @returns {void} * @private */ public destroy(): void { /** * Destroys the undo redo module */ } /** * @returns { string } toBounds method .\ * Get getModuleName name. */ protected getModuleName(): string { /** * Returns the module name */ return 'UndoRedo'; } }
the_stack
import { blockchainTests, constants, expect, filterLogs, filterLogsToArguments, getRandomInteger, Numberish, randomAddress, } from '@0x/contracts-test-utils'; import { AssetProxyId } from '@0x/types'; import { BigNumber, hexUtils } from '@0x/utils'; import { DecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; import { artifacts } from './artifacts'; import { TestUniswapBridgeContract, TestUniswapBridgeEthToTokenTransferInputEventArgs as EthToTokenTransferInputArgs, TestUniswapBridgeEvents as ContractEvents, TestUniswapBridgeTokenApproveEventArgs as TokenApproveArgs, TestUniswapBridgeTokenToEthSwapInputEventArgs as TokenToEthSwapInputArgs, TestUniswapBridgeTokenToTokenTransferInputEventArgs as TokenToTokenTransferInputArgs, TestUniswapBridgeTokenTransferEventArgs as TokenTransferArgs, TestUniswapBridgeWethDepositEventArgs as WethDepositArgs, TestUniswapBridgeWethWithdrawEventArgs as WethWithdrawArgs, } from './wrappers'; blockchainTests.resets('UniswapBridge unit tests', env => { let testContract: TestUniswapBridgeContract; let wethTokenAddress: string; before(async () => { testContract = await TestUniswapBridgeContract.deployFrom0xArtifactAsync( artifacts.TestUniswapBridge, env.provider, env.txDefaults, artifacts, ); wethTokenAddress = await testContract.wethToken().callAsync(); }); describe('isValidSignature()', () => { it('returns success bytes', async () => { const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381'; const result = await testContract .isValidSignature(hexUtils.random(), hexUtils.random(_.random(0, 32))) .callAsync(); expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE); }); }); describe('bridgeTransferFrom()', () => { interface WithdrawToOpts { fromTokenAddress: string; toTokenAddress: string; fromTokenBalance: Numberish; toAddress: string; amount: Numberish; exchangeRevertReason: string; exchangeFillAmount: Numberish; toTokenRevertReason: string; fromTokenRevertReason: string; } function createWithdrawToOpts(opts?: Partial<WithdrawToOpts>): WithdrawToOpts { return { fromTokenAddress: constants.NULL_ADDRESS, toTokenAddress: constants.NULL_ADDRESS, fromTokenBalance: getRandomInteger(1, 1e18), toAddress: randomAddress(), amount: getRandomInteger(1, 1e18), exchangeRevertReason: '', exchangeFillAmount: getRandomInteger(1, 1e18), toTokenRevertReason: '', fromTokenRevertReason: '', ...opts, }; } interface WithdrawToResult { opts: WithdrawToOpts; result: string; logs: DecodedLogs; blockTime: number; } async function withdrawToAsync(opts?: Partial<WithdrawToOpts>): Promise<WithdrawToResult> { const _opts = createWithdrawToOpts(opts); const callData = { value: new BigNumber(_opts.exchangeFillAmount) }; // Create the "from" token and exchange. const createFromTokenFn = testContract.createTokenAndExchange( _opts.fromTokenAddress, _opts.exchangeRevertReason, ); [_opts.fromTokenAddress] = await createFromTokenFn.callAsync(callData); await createFromTokenFn.awaitTransactionSuccessAsync(callData); // Create the "to" token and exchange. const createToTokenFn = testContract.createTokenAndExchange( _opts.toTokenAddress, _opts.exchangeRevertReason, ); [_opts.toTokenAddress] = await createToTokenFn.callAsync(callData); await createToTokenFn.awaitTransactionSuccessAsync(callData); await testContract .setTokenRevertReason(_opts.toTokenAddress, _opts.toTokenRevertReason) .awaitTransactionSuccessAsync(); await testContract .setTokenRevertReason(_opts.fromTokenAddress, _opts.fromTokenRevertReason) .awaitTransactionSuccessAsync(); // Set the token balance for the token we're converting from. await testContract.setTokenBalance(_opts.fromTokenAddress).awaitTransactionSuccessAsync({ value: new BigNumber(_opts.fromTokenBalance), }); // Call bridgeTransferFrom(). const bridgeTransferFromFn = testContract.bridgeTransferFrom( // The "to" token address. _opts.toTokenAddress, // The "from" address. randomAddress(), // The "to" address. _opts.toAddress, // The amount to transfer to "to" new BigNumber(_opts.amount), // ABI-encoded "from" token address. hexUtils.leftPad(_opts.fromTokenAddress), ); const result = await bridgeTransferFromFn.callAsync(); const receipt = await bridgeTransferFromFn.awaitTransactionSuccessAsync(); return { opts: _opts, result, logs: (receipt.logs as any) as DecodedLogs, blockTime: await env.web3Wrapper.getBlockTimestampAsync(receipt.blockNumber), }; } async function getExchangeForTokenAsync(tokenAddress: string): Promise<string> { return testContract.getExchange(tokenAddress).callAsync(); } it('returns magic bytes on success', async () => { const { result } = await withdrawToAsync(); expect(result).to.eq(AssetProxyId.ERC20Bridge); }); it('just transfers tokens to `to` if the same tokens are in play', async () => { const createTokenFn = await testContract.createTokenAndExchange(constants.NULL_ADDRESS, ''); const [tokenAddress] = await createTokenFn.callAsync(); await createTokenFn.awaitTransactionSuccessAsync(); const { opts, result, logs } = await withdrawToAsync({ fromTokenAddress: tokenAddress, toTokenAddress: tokenAddress, }); expect(result).to.eq(AssetProxyId.ERC20Bridge); const transfers = filterLogsToArguments<TokenTransferArgs>(logs, ContractEvents.TokenTransfer); expect(transfers.length).to.eq(1); expect(transfers[0].token).to.eq(tokenAddress); expect(transfers[0].from).to.eq(testContract.address); expect(transfers[0].to).to.eq(opts.toAddress); expect(transfers[0].amount).to.bignumber.eq(opts.amount); }); describe('token -> token', () => { it('calls `IUniswapExchange.tokenToTokenTransferInput()', async () => { const { opts, logs, blockTime } = await withdrawToAsync(); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); const calls = filterLogsToArguments<TokenToTokenTransferInputArgs>( logs, ContractEvents.TokenToTokenTransferInput, ); expect(calls.length).to.eq(1); expect(calls[0].exchange).to.eq(exchangeAddress); expect(calls[0].tokensSold).to.bignumber.eq(opts.fromTokenBalance); expect(calls[0].minTokensBought).to.bignumber.eq(opts.amount); expect(calls[0].minEthBought).to.bignumber.eq(1); expect(calls[0].deadline).to.bignumber.eq(blockTime); expect(calls[0].recipient).to.eq(opts.toAddress); expect(calls[0].toTokenAddress).to.eq(opts.toTokenAddress); }); it('sets allowance for "from" token', async () => { const { opts, logs } = await withdrawToAsync(); const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); expect(approvals.length).to.eq(1); expect(approvals[0].spender).to.eq(exchangeAddress); expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256); }); it('sets allowance for "from" token on subsequent calls', async () => { const { opts } = await withdrawToAsync(); const { logs } = await withdrawToAsync(opts); const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); expect(approvals.length).to.eq(1); expect(approvals[0].spender).to.eq(exchangeAddress); expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256); }); it('fails if "from" token does not exist', async () => { const tx = testContract .bridgeTransferFrom( randomAddress(), randomAddress(), randomAddress(), getRandomInteger(1, 1e18), hexUtils.leftPad(randomAddress()), ) .awaitTransactionSuccessAsync(); return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if the exchange fails', async () => { const revertReason = 'FOOBAR'; const tx = withdrawToAsync({ exchangeRevertReason: revertReason, }); return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); describe('token -> ETH', () => { it('calls `IUniswapExchange.tokenToEthSwapInput()`, `WETH.deposit()`, then `transfer()`', async () => { const { opts, logs, blockTime } = await withdrawToAsync({ toTokenAddress: wethTokenAddress, }); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); let calls: any = filterLogs<TokenToEthSwapInputArgs>(logs, ContractEvents.TokenToEthSwapInput); expect(calls.length).to.eq(1); expect(calls[0].args.exchange).to.eq(exchangeAddress); expect(calls[0].args.tokensSold).to.bignumber.eq(opts.fromTokenBalance); expect(calls[0].args.minEthBought).to.bignumber.eq(opts.amount); expect(calls[0].args.deadline).to.bignumber.eq(blockTime); calls = filterLogs<WethDepositArgs>( logs.slice(calls[0].logIndex as number), ContractEvents.WethDeposit, ); expect(calls.length).to.eq(1); expect(calls[0].args.amount).to.bignumber.eq(opts.exchangeFillAmount); calls = filterLogs<TokenTransferArgs>( logs.slice(calls[0].logIndex as number), ContractEvents.TokenTransfer, ); expect(calls.length).to.eq(1); expect(calls[0].args.token).to.eq(opts.toTokenAddress); expect(calls[0].args.from).to.eq(testContract.address); expect(calls[0].args.to).to.eq(opts.toAddress); expect(calls[0].args.amount).to.bignumber.eq(opts.exchangeFillAmount); }); it('sets allowance for "from" token', async () => { const { opts, logs } = await withdrawToAsync({ toTokenAddress: wethTokenAddress, }); const transfers = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); expect(transfers.length).to.eq(1); expect(transfers[0].spender).to.eq(exchangeAddress); expect(transfers[0].allowance).to.bignumber.eq(constants.MAX_UINT256); }); it('sets allowance for "from" token on subsequent calls', async () => { const { opts } = await withdrawToAsync({ toTokenAddress: wethTokenAddress, }); const { logs } = await withdrawToAsync(opts); const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove); const exchangeAddress = await getExchangeForTokenAsync(opts.fromTokenAddress); expect(approvals.length).to.eq(1); expect(approvals[0].spender).to.eq(exchangeAddress); expect(approvals[0].allowance).to.bignumber.eq(constants.MAX_UINT256); }); it('fails if "from" token does not exist', async () => { const tx = testContract .bridgeTransferFrom( randomAddress(), randomAddress(), randomAddress(), getRandomInteger(1, 1e18), hexUtils.leftPad(wethTokenAddress), ) .awaitTransactionSuccessAsync(); return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if `WETH.deposit()` fails', async () => { const revertReason = 'FOOBAR'; const tx = withdrawToAsync({ toTokenAddress: wethTokenAddress, toTokenRevertReason: revertReason, }); return expect(tx).to.eventually.be.rejectedWith(revertReason); }); it('fails if the exchange fails', async () => { const revertReason = 'FOOBAR'; const tx = withdrawToAsync({ toTokenAddress: wethTokenAddress, exchangeRevertReason: revertReason, }); return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); describe('ETH -> token', () => { it('calls `WETH.withdraw()`, then `IUniswapExchange.ethToTokenTransferInput()`', async () => { const { opts, logs, blockTime } = await withdrawToAsync({ fromTokenAddress: wethTokenAddress, }); const exchangeAddress = await getExchangeForTokenAsync(opts.toTokenAddress); let calls: any = filterLogs<WethWithdrawArgs>(logs, ContractEvents.WethWithdraw); expect(calls.length).to.eq(1); expect(calls[0].args.amount).to.bignumber.eq(opts.fromTokenBalance); calls = filterLogs<EthToTokenTransferInputArgs>( logs.slice(calls[0].logIndex as number), ContractEvents.EthToTokenTransferInput, ); expect(calls.length).to.eq(1); expect(calls[0].args.exchange).to.eq(exchangeAddress); expect(calls[0].args.minTokensBought).to.bignumber.eq(opts.amount); expect(calls[0].args.deadline).to.bignumber.eq(blockTime); expect(calls[0].args.recipient).to.eq(opts.toAddress); }); it('does not set any allowance', async () => { const { logs } = await withdrawToAsync({ fromTokenAddress: wethTokenAddress, }); const approvals = filterLogsToArguments<TokenApproveArgs>(logs, ContractEvents.TokenApprove); expect(approvals).to.be.empty(''); }); it('fails if "to" token does not exist', async () => { const tx = testContract .bridgeTransferFrom( wethTokenAddress, randomAddress(), randomAddress(), getRandomInteger(1, 1e18), hexUtils.leftPad(randomAddress()), ) .awaitTransactionSuccessAsync(); return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if the `WETH.withdraw()` fails', async () => { const revertReason = 'FOOBAR'; const tx = withdrawToAsync({ fromTokenAddress: wethTokenAddress, fromTokenRevertReason: revertReason, }); return expect(tx).to.eventually.be.rejectedWith(revertReason); }); it('fails if the exchange fails', async () => { const revertReason = 'FOOBAR'; const tx = withdrawToAsync({ fromTokenAddress: wethTokenAddress, exchangeRevertReason: revertReason, }); return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); }); });
the_stack
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.1" language="ru"> <context> <name>LC::Poshuku::CleanWeb::CleanWeb</name> <message> <location filename="cleanweb.cpp" line="+89"/> <source>Blocks unwanted ads.</source> <translation type="unfinished">Bloku evitindan anoncon.</translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::Core</name> <message> <location filename="core.cpp" line="+271"/> <source>Blocked by Poshuku CleanWeb: %1</source> <translation type="unfinished"></translation> </message> <message> <location line="+39"/> <source>Block image...</source> <translation type="unfinished"></translation> </message> <message> <location line="+269"/> <source>The subscription %1 was successfully added.</source> <translation type="unfinished"></translation> </message> <message> <location line="+30"/> <source>The subscription %1 wasn&apos;t delegated.</source> <translation type="unfinished">La abono %1 ne estis delegita.</translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::RuleOptionDialog</name> <message> <location filename="ruleoptiondialog.cpp" line="+159"/> <location line="+26"/> <source>Enter domain</source> <translation type="unfinished"></translation> </message> <message> <location line="+25"/> <source>Are you sure you want to remove %1?</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::SubscriptionAddDialog</name> <message> <location filename="subscriptionadddialog.cpp" line="+98"/> <source>Name</source> <translation type="unfinished">Nomo</translation> </message> <message> <location line="+1"/> <source>Purpose</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>URL</source> <translation type="unfinished">URL</translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::SubscriptionsManagerWidget</name> <message> <location filename="subscriptionsmanagerwidget.cpp" line="+78"/> <location line="+10"/> <location line="+9"/> <location line="+9"/> <source>Error adding subscription</source> <translation type="unfinished"></translation> </message> <message> <location line="-27"/> <source>Invalid URL. Valid URL format is %1.</source> <translation type="unfinished"></translation> </message> <message> <location line="+10"/> <source>Can&apos;t add subscription without a title.</source> <translation type="unfinished"></translation> </message> <message> <location line="+9"/> <source>Subscription with this title already exists.</source> <translation type="unfinished"></translation> </message> <message> <location line="+9"/> <source>Subscription with this URL already exists.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::SubscriptionsModel</name> <message> <location filename="subscriptionsmodel.cpp" line="+47"/> <source>Name</source> <translation type="unfinished">Nomo</translation> </message> <message> <location line="+0"/> <source>Last updated</source> <translation type="unfinished">Laste ĝisdatigita</translation> </message> <message> <location line="+0"/> <source>URL</source> <translation type="unfinished">URL</translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::UserFilters</name> <message> <location filename="userfilters.cpp" line="+99"/> <source>Paste rules</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Paste your custom rules here:</source> <translation type="unfinished"></translation> </message> <message> <location line="+22"/> <source>Load rules</source> <translation type="unfinished"></translation> </message> <message> <location line="+14"/> <source>Error opening file %1: %2.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LC::Poshuku::CleanWeb::UserFiltersModel</name> <message> <location filename="userfiltersmodel.cpp" line="+62"/> <source>Filter</source> <translation type="unfinished">Filtrilo</translation> </message> <message> <location line="+1"/> <source>Policy</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished">Tipo</translation> </message> <message> <location line="+1"/> <source>Case sensitive</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Domains</source> <translation type="unfinished"></translation> </message> <message> <location line="+45"/> <source>Allowed</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Blocked</source> <translation type="unfinished"></translation> </message> <message> <location line="+8"/> <source>Wildcard</source> <translation type="unfinished"></translation> </message> <message> <location line="+2"/> <source>Regexp</source> <translation type="unfinished"></translation> </message> <message> <location line="+4"/> <source>True</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>False</source> <translation type="unfinished"></translation> </message> <message> <location line="+56"/> <source>Add a filter</source> <translation type="unfinished"></translation> </message> <message> <location line="+51"/> <source>Modify filter</source> <translation type="unfinished"></translation> </message> <message> <location line="+34"/> <source>Imported %1 user filters (%2 parsed successfully).</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RuleOptionDialog</name> <message> <location filename="ruleoptiondialog.ui" line="+25"/> <source>String:</source> <translation type="unfinished"></translation> </message> <message> <location line="+10"/> <source>Type:</source> <translation type="unfinished"></translation> </message> <message> <location line="+9"/> <source>Wildcard</source> <translation type="unfinished"></translation> </message> <message> <location line="+13"/> <source>Regexp</source> <translation type="unfinished"></translation> </message> <message> <location line="+12"/> <source>Policy:</source> <translation type="unfinished"></translation> </message> <message> <location line="+9"/> <source>Block</source> <translation type="unfinished"></translation> </message> <message> <location line="+13"/> <source>Allow</source> <translation type="unfinished"></translation> </message> <message> <location line="+14"/> <source>Case sensitive</source> <translation type="unfinished"></translation> </message> <message> <location line="+7"/> <source>Customize domains</source> <translation type="unfinished"></translation> </message> <message> <location line="+15"/> <source>Enable for:</source> <translation type="unfinished"></translation> </message> <message> <location line="+25"/> <location line="+48"/> <source>Add...</source> <translation>Aldoni...</translation> </message> <message> <location line="-41"/> <location line="+48"/> <source>Modify...</source> <translation>Ŝanĝi...</translation> </message> <message> <location line="-41"/> <location line="+48"/> <source>Remove</source> <translation type="unfinished">Forigi</translation> </message> <message> <location line="-39"/> <source>Disable for:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>StartupFirstPageWidget</name> <message> <location filename="startupfirstpage.ui" line="+17"/> <source>Select ad blocking lists</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Select ad blocking lists that you would like to add to the Poshuku CleanWeb plugin.</source> <translation type="unfinished"></translation> </message> <message> <location line="+6"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;DejaVu Sans&apos;; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;You may choose to add EasyList ad blocking subscription to Poshuku CleanWeb if you wish.&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;You may also add the required subscriptions later, either by directly entering their URL in CleanWeb&apos;s settings or by navigating to &lt;a href=&quot;http://adblockplus.org/en/subscriptions&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#1a619f;&quot;&gt;http://adblockplus.org/en/subscriptions&lt;/span&gt;&lt;/a&gt; for example and selecting the subscriptions you would like to be enabled there.&lt;/p&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;Please note that if you have enabled the &lt;span style=&quot; font-weight:600;&quot;&gt;LackMan &lt;/span&gt;plugin for LeechCraft and installed the &lt;span style=&quot; font-style:italic;&quot;&gt;Poshuku CleanWeb Subscriptions&lt;/span&gt; through it, you may also choose between various predefined subscriptions in the CleanWeb&apos;s settings.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <location line="+16"/> <source>Enable EasyList</source> <translation type="unfinished"></translation> </message> <message> <location line="+10"/> <source>abp:subscribe?location=https%3A%2F%2Feasylist%2Ddownloads%2Eadblockplus%2Eorg%2Feasylist%2Etxt&amp;title=EasyList</source> <translation type="unfinished"></translation> </message> <message> <location line="+22"/> <source>+ EasyPrivacy (privacy protection)</source> <translation type="unfinished"></translation> </message> <message> <location line="+4"/> <source>abp:subscribe?location=https%3A%2F%2Feasylist%2Ddownloads%2Eadblockplus%2Eorg%2Feasyprivacy%2Etxt&amp;title=EasyPrivacy&amp;requiresLocation=https%3A%2F%2Feasylist%2Ddownloads%2Eadblockplus%2Eorg%2Feasylist%2Etxt&amp;requiresTitle=EasyList</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SubscriptionAddDialog</name> <message> <location filename="subscriptionadddialog.ui" line="+14"/> <source>Add Subscription</source> <translation type="unfinished"></translation> </message> <message> <location line="+11"/> <source>Title:</source> <translation type="unfinished"></translation> </message> <message> <location line="+10"/> <source>URL:</source> <translation>URL:</translation> </message> <message> <location line="+7"/> <source>Should be in AdBlock format: abp://subscribe/?location=&lt;b&gt;URL&lt;/b&gt;</source> <translation type="unfinished"></translation> </message> <message> <location line="+9"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;DejaVu Sans&apos;; font-size:9pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;You may also select predefined subscriptions if you have LackMan plugin and have installed the &lt;span style=&quot; font-style:italic;&quot;&gt;Poshuku CleanWeb Subscriptions&lt;/span&gt; package.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SubscriptionsManagerWidget</name> <message> <location filename="subscriptionsmanagerwidget.ui" line="+32"/> <source>Add</source> <translation type="unfinished">Aldoni</translation> </message> <message> <location line="+7"/> <source>Remove</source> <translation type="unfinished">Forigi</translation> </message> </context> <context> <name>UserFilters</name> <message> <location filename="userfilters.ui" line="+35"/> <source>Add...</source> <translation>Aldoni...</translation> </message> <message> <location line="+7"/> <source>Modify...</source> <translation>Ŝanĝi...</translation> </message> <message> <location line="+7"/> <source>Remove</source> <translation>Forigi</translation> </message> <message> <location line="+14"/> <source>Allows one to paste several add blocking rules in AdBlock+ format.</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Paste...</source> <translation type="unfinished"></translation> </message> <message> <location line="+7"/> <source>Loads rules from a file, adding them to user rules.</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source>Load...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>poshukucleanwebsettings</name> <message> <location filename="dummy.cpp" line="+2"/> <location line="+1"/> <source>General</source> <translation type="unfinished"></translation> </message> <message> <location line="+7"/> <source>Update subscriptions</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Update interval:</source> <translation type="unfinished"></translation> </message> <message> <location line="-5"/> <source>Enable filtering</source> <oldsource>User filters</oldsource> <translation type="unfinished"></translation> </message> <message> <location line="-2"/> <source>Enable JIT for regexps</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>This option controls the usage of Just-In-Time compilation for regular expressions if CleanWeb was built with PCRE 8.20 and upper. JIT speeds up rules matching at the cost of higher memory usage. The speedup is somewhere between 25% and 50% depending on page being loaded, but this option uses about 2.1 KiB of RAM per regular expression.&lt;br/&gt;Disable this if you want to lower memory footprint.</source> <translation type="unfinished"></translation> </message> <message> <location line="+2"/> <source>Enable element hiding</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>User rules</source> <translation type="unfinished"></translation> </message> <message> <location line="+1"/> <source>Subscriptions</source> <translation type="unfinished"></translation> </message> <message> <location line="+3"/> <source> days</source> <translation type="unfinished"></translation> </message> </context> </TS>
the_stack
import { Any } from "../src/json2typescript/any"; import { JsonConvert } from "../src/json2typescript/json-convert"; import { OperationMode, PropertyConvertingMode, PropertyMatchingRule, ValueCheckingMode, } from "../src/json2typescript/json-convert-enums"; import { MappingOptions, Settings } from "../src/json2typescript/json-convert-options"; import { ICat } from "./model/json/i-cat"; import { IDog } from "./model/json/i-dog"; import { IHuman } from "./model/json/i-human"; import { Cat } from "./model/typescript/cat"; import { DateConverter } from "./model/typescript/date-converter"; import { Dog } from "./model/typescript/dog"; import { DuplicateCat } from "./model/typescript/duplicate-cat"; import { Human } from "./model/typescript/human"; import { OptionalCat } from "./model/typescript/optional-cat"; describe("JsonConvert unit tests", () => { const jsonConvert = new JsonConvert(); // JSON DATA let human1JsonObject: IHuman = { givenName: "Andreas", lastName: "Muster", }; let human2JsonObject: IHuman = { givenName: "Michael", name: "Meier", }; let cat1JsonObject: ICat = { catName: "Meowy", district: 100, owner: human1JsonObject, talky: true, other: "cute", friends: [], }; let cat2JsonObject: ICat = { catName: "Links", district: 50, talky: true, other: "sweet", birthdate: "2014-09-01", }; let dog1JsonObject: IDog = { name: "Barky", barking: true, other: 1.1, toys: [], }; // TYPESCRIPT INSTANCES let human1 = new Human(); human1.firstname = "Andreas"; human1.lastname = "Muster"; let human2 = new Human(); human2.firstname = "Michael"; human2.lastname = "Meier"; let cat1 = new Cat(); cat1.name = "Meowy"; cat1.district = 100; cat1.owner = human1; cat1.talky = true; cat1.other = "cute"; cat1.friends = []; let cat2 = new Cat(); cat2.name = "Links"; cat2.district = 50; cat2.other = "sweet"; cat2.birthdate = new Date("2014-09-01"); cat2.friends = null; cat2.talky = true; let dog1 = new Dog(); dog1.name = "Barky"; dog1.isBarking = true; dog1.owner = null; dog1.other = 1.1; let duplicateCat1 = new DuplicateCat(); duplicateCat1.name = "Duplicate"; duplicateCat1.district = new Date("2014-10-01"); duplicateCat1.talky = new Date("2015-02-03"); // TYPESCRIPT OPTIONAL INSTANCES let optionalCat1 = new OptionalCat(); optionalCat1.name = "MaybeMeowy"; // SETUP CHECKS describe("setup checks", () => { it("JsonConvert instance", () => { let jsonConvertTest: JsonConvert; jsonConvertTest = new JsonConvert(OperationMode.ENABLE, ValueCheckingMode.ALLOW_OBJECT_NULL, false); expect(jsonConvertTest.operationMode).toEqual(OperationMode.ENABLE); expect(jsonConvertTest.valueCheckingMode).toEqual(ValueCheckingMode.ALLOW_OBJECT_NULL); expect(jsonConvertTest.ignorePrimitiveChecks).toEqual(false); expect(jsonConvertTest.ignoreRequiredCheck).toEqual(false); jsonConvertTest = new JsonConvert(OperationMode.DISABLE, ValueCheckingMode.ALLOW_NULL, true); expect(jsonConvertTest.operationMode).toEqual(OperationMode.DISABLE); expect(jsonConvertTest.valueCheckingMode).toEqual(ValueCheckingMode.ALLOW_NULL); expect(jsonConvertTest.ignorePrimitiveChecks).toEqual(true); expect(jsonConvertTest.ignoreRequiredCheck).toEqual(false); jsonConvertTest = new JsonConvert(OperationMode.LOGGING, ValueCheckingMode.DISALLOW_NULL, false); expect(jsonConvertTest.operationMode).toEqual(OperationMode.LOGGING); expect(jsonConvertTest.valueCheckingMode).toEqual(ValueCheckingMode.DISALLOW_NULL); expect(jsonConvertTest.ignorePrimitiveChecks).toEqual(false); expect(jsonConvertTest.ignoreRequiredCheck).toEqual(false); jsonConvertTest = new JsonConvert(); expect(jsonConvertTest.operationMode).toEqual(OperationMode.ENABLE); expect(jsonConvertTest.valueCheckingMode).toEqual(ValueCheckingMode.ALLOW_OBJECT_NULL); expect(jsonConvertTest.ignorePrimitiveChecks).toEqual(false); expect(jsonConvertTest.ignoreRequiredCheck).toEqual(false); }); it("JsonObject decorator", () => { expect((<any>human1)[Settings.CLASS_IDENTIFIER]).toEqual("Human"); expect((<any>cat1)[Settings.CLASS_IDENTIFIER]).toEqual("Kitty"); expect((<any>dog1)[Settings.CLASS_IDENTIFIER]).toEqual("Doggy"); }); }); // DISCRIMINATOR FEATURE describe('discriminator checks', () => { it('registering classes', () => { let jsonConvertTest: JsonConvert; jsonConvertTest = new JsonConvert(); jsonConvertTest.registerClasses(Cat, Dog); expect((<any>jsonConvertTest).classes.has((<any>cat1)[Settings.CLASS_IDENTIFIER])).toBeTrue(); expect((<any>jsonConvertTest).classes.has((<any>dog1)[Settings.CLASS_IDENTIFIER])).toBeTrue(); expect((<any>jsonConvertTest).classes.has((<any>human1)[Settings.CLASS_IDENTIFIER])).toBeFalse(); }); it('unregistering classes', () => { let jsonConvertTest: JsonConvert; jsonConvertTest = new JsonConvert(); jsonConvertTest.registerClasses(Cat, Dog); jsonConvertTest.unregisterClasses(Cat); expect((<any>jsonConvertTest).classes.has((<any>cat1)[Settings.CLASS_IDENTIFIER])).toBeFalse(); expect((<any>jsonConvertTest).classes.has((<any>dog1)[Settings.CLASS_IDENTIFIER])).toBeTrue(); expect((<any>jsonConvertTest).classes.has((<any>human1)[Settings.CLASS_IDENTIFIER])).toBeFalse(); }); it('unregistering all classes', () => { let jsonConvertTest: JsonConvert; jsonConvertTest = new JsonConvert(); jsonConvertTest.registerClasses(Cat, Dog); jsonConvertTest.unregisterAllClasses(); expect((<any>jsonConvertTest).classes.size).toEqual(0); }); }); // NULL/UNDEFINED CHECKS describe("null/undefined checks", () => { it("serialize and deserialize null", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; let t_cat = (<any>jsonConvert).deserialize(null, Cat); expect(t_cat).toEqual(null); let t_catJsonObject = (<any>jsonConvert).serialize(null); expect(t_catJsonObject).toEqual(null); jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; expect(() => (<any>jsonConvert).deserialize(null, Cat)).toThrow(); expect(() => (<any>jsonConvert).serialize(null)).toThrow(); }); it("deserialize and serialize undefined", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; expect(() => (<any>jsonConvert).deserialize(undefined, Cat)).toThrowError(); expect(() => (<any>jsonConvert).serialize(undefined)).toThrowError(); }); }); // BASIC CHECKS describe("basic checks", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; it("serialize and deserialize same data", () => { let t_catJsonObject = (<any>jsonConvert).serialize(cat1); expect(t_catJsonObject).toEqual(cat1JsonObject); let t_cat = (<any>jsonConvert).deserialize(t_catJsonObject, Cat); expect(t_cat).toEqual(cat1); }); it("deserialize and serialize same data", () => { let t_cat = (<any>jsonConvert).deserialize(cat1JsonObject, Cat); expect(t_cat).toEqual(cat1); let t_catJsonObject = (<any>jsonConvert).serialize(t_cat); expect(t_catJsonObject).toEqual(cat1JsonObject); }); }); // PRIVATE METHODS describe("private methods", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; describe("serializeObject_loopProperty()", () => { let t_cat: any; beforeEach(() => { t_cat = {}; }); it("should serialize property with different class and JSON names", () => { (<any>jsonConvert).serializeObject_loopProperty(cat1, cat1, "name", t_cat); expect((<any>t_cat)["catName"]).toBe(cat1.name); }); it("should serialize property with no declared property name", () => { (<any>jsonConvert).serializeObject_loopProperty(cat1, cat1, "district", t_cat); expect((<any>t_cat)["district"]).toBe(100); }); it("should serialize a child object property", () => { (<any>jsonConvert).serializeObject_loopProperty(cat1, cat1, "owner", t_cat); expect((<any>t_cat)["owner"]["givenName"]).toBe("Andreas"); }); it("should throw an error if required property is missing", () => { expect(function () { (<any>jsonConvert).serializeObject_loopProperty(optionalCat1, optionalCat1, "district", t_cat); }).toThrowError(); }); it("should not throw an error if required property is missing but ignoreRequiredCheck flag set", () => { jsonConvert.ignoreRequiredCheck = true; (<any>jsonConvert).serializeObject_loopProperty(optionalCat1, optionalCat1, "district", t_cat); expect((<any>t_cat)["district"]).toBeUndefined("No value set, but no error thrown"); jsonConvert.ignoreRequiredCheck = false; }); }); describe("deserializeObject_loopProperty()", () => { let t_cat: Cat; beforeEach(() => { t_cat = new Cat(); }); it("should deserialize properties", () => { (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {"catName": "Meowy"}); expect(t_cat.name).toEqual("Meowy"); (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "district", {"district": 100}); expect(t_cat.district).toEqual(100); (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "owner", { "owner": { givenName: "Andreas", lastName: "Muster", }, }); expect(t_cat.owner!.lastname).toEqual("Muster"); let t_dog = new Dog(); (<any>jsonConvert).deserializeObject_loopProperty(t_dog, "name", {"name": "Barky"}); expect(t_dog.name).toEqual("Barky"); jsonConvert.propertyMatchingRule = PropertyMatchingRule.CASE_INSENSITIVE; (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {"catName": "Meowy"}); expect(t_cat.name).toEqual("Meowy"); (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {"catNAME": "Meowy"}); expect(t_cat.name).toEqual("Meowy"); expect(() => (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {"catNames": "Meowy"})).toThrow(); jsonConvert.propertyMatchingRule = PropertyMatchingRule.CASE_STRICT; }); it("should throw an error if required property is missing", () => { expect(function () { (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {}); }).toThrowError(); }); it("should not throw an error if required property is missing but ignoreRequiredCheck flag is set", () => { jsonConvert.ignoreRequiredCheck = true; (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "name", {}); expect(t_cat.name).toEqual("", "Value not set because not present, default value used"); jsonConvert.ignoreRequiredCheck = false; }); }); jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; it("serializeObject_loopProperty()", () => { let t_cat = {}; (<any>jsonConvert).serializeObject_loopProperty(cat2, cat2, "owner", t_cat); expect((<any>t_cat)["owner"]).toBe(undefined); }); it("deserializeObject_loopProperty()", () => { let t_cat = new Cat(); (<any>jsonConvert).deserializeObject_loopProperty(t_cat, "owner", {"owner": null}); expect(t_cat.owner).toBe(null); }); }); // HELPER METHODS describe("helper methods", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; it("getClassPropertyMappingOptions()", () => { /* The actual JSON types used are not strings, even though MappingOption.expectedJsonType is typed as string, * so obscure this by assigning the expected JSON type to an "any" variable. */ let jsonType: any = String; const catNameMapping = new MappingOptions(); catNameMapping.classPropertyName = "name"; catNameMapping.jsonPropertyName = "catName"; catNameMapping.expectedJsonType = jsonType; catNameMapping.convertingMode = PropertyConvertingMode.MAP_NULLABLE; catNameMapping.customConverter = null; expect((<any>jsonConvert).getClassPropertyMappingOptions(cat1, "name")).toEqual(catNameMapping); const dogNameMapping = new MappingOptions(); dogNameMapping.classPropertyName = "name"; dogNameMapping.jsonPropertyName = "name"; dogNameMapping.expectedJsonType = jsonType; dogNameMapping.convertingMode = PropertyConvertingMode.MAP_NULLABLE; dogNameMapping.customConverter = null; expect((<any>jsonConvert).getClassPropertyMappingOptions(dog1, "name")).toEqual(dogNameMapping); // Check that mapped property on "sibling" DuplicateCat class with same name as Cat property // but different type is handled correctly const duplicateCatTalkyMapping = new MappingOptions(); duplicateCatTalkyMapping.classPropertyName = "talky"; duplicateCatTalkyMapping.jsonPropertyName = "talky"; duplicateCatTalkyMapping.expectedJsonType = undefined; duplicateCatTalkyMapping.convertingMode = PropertyConvertingMode.MAP_NULLABLE; duplicateCatTalkyMapping.customConverter = new DateConverter(); expect((<any>jsonConvert).getClassPropertyMappingOptions(duplicateCat1, "talky")).toEqual(duplicateCatTalkyMapping); expect((<any>jsonConvert).getClassPropertyMappingOptions(human1, "name")).toBeNull(); // Unmapped property should not return mapping, even though property is the same name as a mapped property // on another class expect((<any>jsonConvert).getClassPropertyMappingOptions(duplicateCat1, "district")).toBeNull(); }); describe("convertProperty()", () => { let jsonConvert: JsonConvert; beforeEach(() => { jsonConvert = new JsonConvert(); jsonConvert.ignorePrimitiveChecks = false; jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; }); describe("expectedJsonType unmapped", () => { it("should return the value if expected type is Any, Object, or null", () => { expect((<any>jsonConvert).convertProperty(Any, cat1, true)).toBe(cat1); expect((<any>jsonConvert).convertProperty(Object, cat1, false)).toBe(cat1); expect((<any>jsonConvert).convertProperty(null, cat1, true)).toBe(cat1); }); it("should NOT throw an error even if null not allowed", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; expect((<any>jsonConvert).convertProperty(Any, null, true)).toBeNull("expected Any"); expect((<any>jsonConvert).convertProperty(Object, null, false)).toBeNull("expected Object"); expect((<any>jsonConvert).convertProperty(null, null, true)).toBeNull("expected null"); }); }); describe("expectedJsonType mapped class", () => { it("should correctly serialize/deserialize a mapped object property", () => { expect((<any>jsonConvert).convertProperty(Cat, cat2, PropertyConvertingMode.MAP_NULLABLE, true)).toEqual(cat2JsonObject); expect((<any>jsonConvert).convertProperty(Cat, cat1JsonObject, PropertyConvertingMode.MAP_NULLABLE, false)).toEqual(cat1); }); it("should return null if allowed", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_OBJECT_NULL; expect((<any>jsonConvert).convertProperty(Cat, null, PropertyConvertingMode.MAP_NULLABLE, true)).toEqual(null); expect((<any>jsonConvert).convertProperty(Cat, null, PropertyConvertingMode.MAP_NULLABLE, false)).toEqual(null); }); it("should throw an error if null not allowed", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; expect(() => (<any>jsonConvert).convertProperty(Cat, null, PropertyConvertingMode.MAP_NULLABLE, true)) .toThrowError(); expect(() => (<any>jsonConvert).convertProperty(Cat, null, PropertyConvertingMode.MAP_NULLABLE, false)) .toThrowError(); }); it("should throw an error if value is an array", () => { expect(() => (<any>jsonConvert).convertProperty(Cat, [cat1, cat2], true)) .toThrowError(); }); }); describe("expectedJsonType primitive", () => { it("should correctly serialize and deserialize expected primitive values", () => { expect((<any>jsonConvert).convertProperty(String, "Andreas", PropertyConvertingMode.MAP_NULLABLE, false)).toBe("Andreas"); expect((<any>jsonConvert).convertProperty(Number, 2.2, PropertyConvertingMode.MAP_NULLABLE, false)).toBe(2.2); expect((<any>jsonConvert).convertProperty(Boolean, true, PropertyConvertingMode.MAP_NULLABLE, true)).toBe(true); }); it("should error if expected JSON type doesn't match value type", () => { expect(() => (<any>jsonConvert).convertProperty(Number, "Andreas", PropertyConvertingMode.MAP_NULLABLE, false)).toThrowError(); expect(() => (<any>jsonConvert).convertProperty(String, true, PropertyConvertingMode.MAP_NULLABLE, true)).toThrowError(); expect(() => (<any>jsonConvert).convertProperty(Boolean, 54, PropertyConvertingMode.MAP_NULLABLE, true)).toThrowError(); }); it("should return value if expected JSON type doesn't match value type but flag set", () => { jsonConvert.ignorePrimitiveChecks = true; expect((<any>jsonConvert).convertProperty(Number, "Andreas", PropertyConvertingMode.MAP_NULLABLE, false)).toBe("Andreas"); expect((<any>jsonConvert).convertProperty(String, true, PropertyConvertingMode.MAP_NULLABLE, true)).toBe(true); expect((<any>jsonConvert).convertProperty(Boolean, 54, PropertyConvertingMode.MAP_NULLABLE, true)).toBe(54); }); it("should return null if nulls allowed", () => { expect((<any>jsonConvert).convertProperty(String, null, PropertyConvertingMode.MAP_NULLABLE, false)).toBeNull("expected string should be null"); expect((<any>jsonConvert).convertProperty(Number, null, PropertyConvertingMode.MAP_NULLABLE, false)).toBeNull("expected number should be null"); expect((<any>jsonConvert).convertProperty(Boolean, null, PropertyConvertingMode.MAP_NULLABLE, true)).toBeNull("expected boolean should be null"); }); it("should throw an error if only object nulls allowed", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_OBJECT_NULL; expect(() => (<any>jsonConvert).convertProperty(String, null, PropertyConvertingMode.MAP_NULLABLE, false)) .toThrowError(); expect(() => (<any>jsonConvert).convertProperty(Number, null, PropertyConvertingMode.MAP_NULLABLE, false)) .toThrowError(); expect(() => (<any>jsonConvert).convertProperty(Boolean, null, PropertyConvertingMode.MAP_NULLABLE, true)) .toThrowError(); }); it("should throw an error if value is an array", () => { expect(() => (<any>jsonConvert).convertProperty(String, ["Andreas", "Joseph"], PropertyConvertingMode.MAP_NULLABLE, true)) .toThrowError(); }); }); describe("expectedJsonType array", () => { it("should return value as-is if expected type is empty", () => { const pseudoArray = { "0": "Andreas", "1": {"0": true, "1": 2.2}, }; expect((<any>jsonConvert).convertProperty([], pseudoArray, PropertyConvertingMode.MAP_NULLABLE, true)).toBe(pseudoArray); expect((<any>jsonConvert).convertProperty([], cat1, PropertyConvertingMode.MAP_NULLABLE, false)).toBe(cat1); }); it("should return empty array if value is empty", () => { expect((<any>jsonConvert).convertProperty([String], [], PropertyConvertingMode.MAP_NULLABLE, true)).toEqual([]); expect((<any>jsonConvert).convertProperty([String, [Boolean, Number]], [], PropertyConvertingMode.PASS_NULLABLE, false)).toEqual([]); expect((<any>jsonConvert).convertProperty([Cat], [], PropertyConvertingMode.MAP_NULLABLE, false)).toEqual([]); }); it("should correctly handle array of object types", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; expect((<any>jsonConvert).convertProperty([Cat], [cat1, cat2], PropertyConvertingMode.PASS_NULLABLE, true)).toEqual([cat1JsonObject, cat2JsonObject]); expect((<any>jsonConvert).convertProperty([Cat], [cat1JsonObject, cat2JsonObject], PropertyConvertingMode.PASS_NULLABLE, false)).toEqual([cat1, cat2]); }); it("should correctly handle expected nested array types", () => { expect((<any>jsonConvert).convertProperty([String, [Boolean, Number]], ["Andreas", [true, 2.2]], false)) .toEqual(["Andreas", [true, 2.2]]); expect((<any>jsonConvert).convertProperty([String, [Boolean, Number]], { "0": "Andreas", "1": {"0": true, "1": 2.2}, }, true)).toEqual(["Andreas", [true, 2.2]]); }); it("should expand expected array type as needed without affecting original mapping", () => { const expectedJsonType = [String]; expect((<any>jsonConvert).convertProperty(expectedJsonType, ["Andreas", "Joseph", "Albert"], PropertyConvertingMode.MAP_NULLABLE, true)) .toEqual(["Andreas", "Joseph", "Albert"]); expect(expectedJsonType).toEqual([String]); expect((<any>jsonConvert).convertProperty(expectedJsonType, { "0": "Andreas", "1": "Joseph", "2": "Albert", }, PropertyConvertingMode.MAP_NULLABLE)) .toEqual(["Andreas", "Joseph", "Albert"]); expect(expectedJsonType).toEqual([String]); }); it("should throw an error if expected array and value is primitive", () => { expect(() => (<any>jsonConvert).convertProperty([String], "Andreas", PropertyConvertingMode.MAP_NULLABLE)) .toThrowError(); expect(() => (<any>jsonConvert).convertProperty([], "Andreas", PropertyConvertingMode.MAP_NULLABLE)) .toThrowError(); }); it("should return null if nulls allowed", () => { expect((<any>jsonConvert).convertProperty([String], null, PropertyConvertingMode.MAP_NULLABLE, true)).toEqual(null); expect((<any>jsonConvert).convertProperty([String, [Boolean, Number]], null, PropertyConvertingMode.MAP_NULLABLE, true)).toEqual(null); }); it("should throw an error if nulls disallowed", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; expect(() => (<any>jsonConvert).convertProperty([String], null, PropertyConvertingMode.MAP_NULLABLE, true)) .toThrowError(); expect(() => (<any>jsonConvert).convertProperty([String, [Boolean, Number]], null, PropertyConvertingMode.MAP_NULLABLE, true)) .toThrowError(); }); }); }); it("getObjectValue()", () => { expect((<any>jsonConvert).getObjectValue({"name": "Andreas"}, "name")).toBe("Andreas"); expect(() => (<any>jsonConvert).getObjectValue({"nAmE": "Andreas"}, "NaMe")).toThrow(); jsonConvert.propertyMatchingRule = PropertyMatchingRule.CASE_INSENSITIVE; expect((<any>jsonConvert).getObjectValue({"nAmE": "Andreas"}, "NaMe")).toBe("Andreas"); jsonConvert.propertyMatchingRule = PropertyMatchingRule.CASE_STRICT; }); }); // JSON2TYPESCRIPT TYPES describe("json2typescript types", () => { jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; it("getExpectedType()", () => { expect((<any>jsonConvert).getExpectedType(JsonConvert)).toBe("JsonConvert"); expect((<any>jsonConvert).getExpectedType([String, [Boolean, Number]])).toBe("[string,[boolean,number]]"); expect((<any>jsonConvert).getExpectedType([[null, Any], Object])).toBe("[[any,any],any]"); expect((<any>jsonConvert).getExpectedType(undefined)).toBe("undefined"); expect((<any>jsonConvert).getExpectedType("A")).toBe("A"); }); it("getJsonType()", () => { expect((<any>jsonConvert).getJsonType({name: "Andreas"})).toBe("object"); expect((<any>jsonConvert).getJsonType(["a", 0, [true, null]])).toBe("[string,number,[boolean,null]]"); }); it("getTrueType()", () => { expect((<any>jsonConvert).getTrueType(new JsonConvert())).toBe("object"); expect((<any>jsonConvert).getTrueType({name: "Andreas"})).toBe("object"); expect((<any>jsonConvert).getTrueType("Andreas")).toBe("string"); }); }); });
the_stack
import { Spreadsheet } from '../base/index'; import { getColIdxFromClientX, createImageElement, deleteImage, refreshImagePosition, completeAction } from '../common/event'; import { insertImage, refreshImgElem, refreshImgCellObj, getRowIdxFromClientY } from '../common/event'; import { Overlay, Dialog } from '../services/index'; import { OpenOptions, overlay, dialog, BeforeImageData, BeforeImageRefreshData } from '../common/index'; import { removeClass, L10n, isUndefined } from '@syncfusion/ej2-base'; import { ImageModel, CellModel, getCell, setCell, getSheetIndex, getRowsHeight, getColumnsWidth, Workbook, beginAction, getCellAddress } from '../../workbook/index'; import { getRangeIndexes, SheetModel, setImage } from '../../workbook/index'; export class SpreadsheetImage { private parent: Spreadsheet; private pictureCount: number = 1; constructor(parent: Spreadsheet) { this.parent = parent; this.addEventListener(); this.renderImageUpload(); } /** * Adding event listener for success and failure * * @returns {void} - Adding event listener for success and failure */ private addEventListener(): void { this.parent.on(insertImage, this.insertImage, this); this.parent.on(refreshImgElem, this.refreshImgElem, this); this.parent.on(refreshImgCellObj, this.refreshImgCellObj, this); this.parent.on(createImageElement, this.createImageElement, this); this.parent.on(deleteImage, this.deleteImage, this); this.parent.on(refreshImagePosition, this.refreshInsDelImagePosition, this); } /** * Rendering upload component for importing images. * * @returns {void} - Rendering upload component for importing images. */ private renderImageUpload(): void { const uploadBox: HTMLElement = this.parent.element.appendChild(this.parent.createElement('input', { id: this.parent.element.id + '_imageUpload', styles: 'display: none;', attrs: { type: 'file', accept: '.image, .jpg, .png, .gif ,jpeg', name: 'fileUpload' } })); uploadBox.onchange = this.imageSelect.bind(this); } /** * Process after select the excel and image file. * * @param {Event} args - File select native event. * @returns {void} - Process after select the excel and image file. */ private imageSelect(args: Event): void { const file: File = (<HTMLInputElement>args.target).files[0]; if (!file) { return; } if (file.type.includes('image')) { this.insertImage(<OpenOptions>{ file: file }); } else { (this.parent.serviceLocator.getService(dialog) as Dialog).show( { content: (this.parent.serviceLocator.getService('spreadsheetLocale') as L10n).getConstant('UnsupportedFile'), width: '300' }); } (<HTMLInputElement>args.target).value = ''; } /** * Removing event listener for success and failure * * @returns {void} - Removing event listener for success and failure */ private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(insertImage, this.insertImage); this.parent.off(refreshImgCellObj, this.refreshImgCellObj); this.parent.off(createImageElement, this.createImageElement); this.parent.off(deleteImage, this.deleteImage); this.parent.off(refreshImagePosition, this.refreshInsDelImagePosition); } } /* eslint-disable */ private insertImage(args: OpenOptions, range?: string): void { this.binaryStringVal(args).then( src => this.createImageElement({ options: { src: src as string }, range: range, isPublic: true }) ); } private binaryStringVal(args: any): Promise<string | ArrayBuffer> { return new Promise((resolve, reject) => { let reader: FileReader = new FileReader(); reader.readAsDataURL(args.file); reader.onload = () => resolve(reader.result); reader.onerror = error => reject(error); }); } /* eslint-enable */ private createImageElement(args: { options: { src: string, imageId?: string, height?: number, width?: number, top?: number, left?: number }, range?: string, isPublic?: boolean, isUndoRedo?: boolean }): void { const range: string = args.range ? (args.range.indexOf('!') > 0) ? args.range.split('!')[1] : args.range.split('!')[0] : this.parent.getActiveSheet().selectedRange; const sheetIndex: number = (args.range && args.range.indexOf('!') > 0) ? getSheetIndex(this.parent as Workbook, args.range.split('!')[0]) : this.parent.activeSheetIndex; const overlayObj: Overlay = this.parent.serviceLocator.getService(overlay) as Overlay; const id: string = args.options.imageId ? args.options.imageId : this.parent.element.id + '_overlay_picture_' + this.pictureCount; const indexes: number[] = getRangeIndexes(range); const sheet: SheetModel = isUndefined(sheetIndex) ? this.parent.getActiveSheet() : this.parent.sheets[sheetIndex]; if (document.getElementById(id)) { return; } let eventArgs: BeforeImageData = { requestType: 'beforeInsertImage', range: sheet.name + '!' + range, imageData: args.options.src, sheetIndex: sheetIndex }; if (args.isPublic) { this.parent.notify('actionBegin', { eventArgs: eventArgs, action: 'beforeInsertImage' }); } if (eventArgs.cancel) { return; } const element: HTMLElement = overlayObj.insertOverlayElement(id, range, sheetIndex); element.style.backgroundImage = 'url(\'' + args.options.src + '\')'; if (args.options.height || args.options.left) { element.style.height = args.options.height + 'px'; element.style.width = args.options.width + 'px'; element.style.top = args.options.top + 'px'; element.style.left = args.options.left + 'px'; } if (sheet.frozenRows || sheet.frozenColumns) { overlayObj.adjustFreezePaneSize(args.options, element, range); } if (!args.options.imageId) { this.pictureCount++; } const imgData: ImageModel = { src: args.options.src, id: id, height: parseFloat(element.style.height.replace('px', '')), width: parseFloat(element.style.width.replace('px', '')), top: sheet.frozenRows || sheet.frozenColumns ? (indexes[0] ? getRowsHeight(sheet, 0, indexes[0] - 1) : 0) : parseFloat(element.style.top.replace('px', '')), left: sheet.frozenRows || sheet.frozenColumns ? (indexes[1] ? getColumnsWidth(sheet, 0, indexes[1] - 1) : 0) : parseFloat(element.style.left.replace('px', '')) }; this.parent.setUsedRange(indexes[0], indexes[1]); if (args.isPublic || args.isUndoRedo) { this.parent.notify(setImage, { options: [imgData], range: sheet.name + '!' + range }); } const currCell: CellModel = getCell(indexes[0], indexes[1], sheet); if (!currCell.image[currCell.image.length - 1].id) { currCell.image[currCell.image.length - 1].id = imgData.id; } if (!args.isUndoRedo && args.isPublic) { eventArgs = { requestType: 'insertImage', range: sheet.name + '!' + range, imageHeight: args.options.height ? args.options.height : 300, imageWidth: args.options.width ? args.options.width : 400, imageData: args.options.src, id: id, sheetIndex: sheetIndex }; this.parent.notify('actionComplete', { eventArgs: eventArgs, action: 'insertImage' }); } } private refreshImgElem(): void { const overlayElem: HTMLElement = document.getElementsByClassName('e-ss-overlay-active')[0] as HTMLElement; if (overlayElem) { removeClass([overlayElem], 'e-ss-overlay-active'); } } private refreshInsDelImagePosition(args: { rowIdx: number, colIdx: number, sheetIdx: number, count: number, type: string, status: string }): void { const count: number = args.count; const sheetIdx: number = args.sheetIdx; const sheet: SheetModel = this.parent.sheets[sheetIdx]; let pictureElements: HTMLElement; const currCellObj: CellModel = getCell(args.rowIdx, args.colIdx, sheet); const imageLen: number = currCellObj.image.length; let top: number; let left: number; for (let i: number = 0; i < imageLen; i++) { pictureElements = document.getElementById(currCellObj.image[i].id); top = (args.type === 'Row') ? (args.status === 'insert') ? currCellObj.image[i].top + (count * 20) : currCellObj.image[i].top - (count * 20) : currCellObj.image[i].top; left = (args.type === 'Column') ? (args.status === 'insert') ? currCellObj.image[i].left + (count * 64) : currCellObj.image[i].left - (count * 64) : currCellObj.image[i].left; currCellObj.image[i].top = top; currCellObj.image[i].left = left; pictureElements.style.top = top + 'px'; pictureElements.style.left = left + 'px'; } } private refreshImgCellObj(args: BeforeImageRefreshData): void { const sheet: SheetModel = this.parent.getActiveSheet(); const prevCellObj: CellModel = getCell(args.prevRowIdx, args.prevColIdx, sheet); const currCellObj: CellModel = getCell(args.currentRowIdx, args.currentColIdx, sheet); const prevCellImg: object[] = prevCellObj ? prevCellObj.image : []; let prevImgObj: ImageModel; let currImgObj: ImageModel[]; const prevCellImgLen: number = (prevCellImg && prevCellImg.length) ? prevCellImg.length : 0; if (prevCellObj && prevCellObj.image && prevCellImg.length > 0) { for (let i: number = 0; i < prevCellImgLen; i++) { if (prevCellImg[i] && (prevCellImg[i] as ImageModel).id === args.id) { prevImgObj = prevCellImg[i]; prevImgObj.height = args.currentHeight; prevImgObj.width = args.currentWidth; prevImgObj.top = args.currentTop; prevImgObj.left = args.currentLeft; prevCellImg.splice(i, 1); } } if (currCellObj && currCellObj.image) { currImgObj = currCellObj.image; if (prevImgObj) { currImgObj.push(prevImgObj); } } if (currImgObj) { setCell(args.currentRowIdx, args.currentColIdx, sheet, { image: currImgObj }, true); } else { setCell(args.currentRowIdx, args.currentColIdx, sheet, { image: [prevImgObj] }, true); } if (args.requestType === 'imageRefresh' && !args.isUndoRedo) { const eventArgs: BeforeImageRefreshData = { requestType: 'imageRefresh', currentRowIdx: args.currentRowIdx, currentColIdx: args.currentColIdx, prevRowIdx: args.prevRowIdx, prevColIdx: args.prevColIdx, prevTop: args.prevTop, prevLeft: args.prevLeft, currentTop: args.currentTop, currentLeft: args.currentLeft, currentHeight: args.currentHeight, currentWidth: args.currentWidth, prevHeight: args.prevHeight, prevWidth: args.prevWidth, id: args.id, sheetIdx: this.parent.activeSheetIndex }; this.parent.notify('actionComplete', { eventArgs: eventArgs, action: 'imageRefresh' }); } } } public deleteImage(args: { id: string, range?: string, preventEventTrigger?:boolean }): void { let sheet: SheetModel = this.parent.getActiveSheet(); const pictureElements: HTMLElement = document.getElementById(args.id); let rowIdx: number; let colIdx: number; let address: string; if (pictureElements) { let imgTop: { clientY: number, isImage?: boolean, target?: Element }; let imgleft: { clientX: number, isImage?: boolean, target?: Element }; if (sheet.frozenRows || sheet.frozenColumns) { const clientRect: ClientRect = pictureElements.getBoundingClientRect(); imgTop = { clientY: clientRect.top }; imgleft = { clientX: clientRect.left }; if (clientRect.top < this.parent.getColumnHeaderContent().getBoundingClientRect().bottom) { imgTop.target = this.parent.getColumnHeaderContent(); } if (clientRect.left < this.parent.getRowHeaderContent().getBoundingClientRect().right) { imgleft.target = this.parent.getRowHeaderTable(); } } else { imgTop = { clientY: pictureElements.offsetTop, isImage: true }; imgleft = { clientX: pictureElements.offsetLeft, isImage: true }; } this.parent.notify(getRowIdxFromClientY, imgTop); this.parent.notify(getColIdxFromClientX, imgleft); rowIdx = imgTop.clientY; colIdx = imgleft.clientX; address = sheet.name + '!' + getCellAddress(rowIdx, colIdx); if (!args.preventEventTrigger) { const eventArgs: { address: string, cancel: boolean } = { address: address, cancel: false }; this.parent.notify(beginAction, { action: 'deleteImage', eventArgs: eventArgs }); if (eventArgs.cancel) { return; } } document.getElementById(args.id).remove(); } else { const rangeVal: string = args.range ? args.range.indexOf('!') > 0 ? args.range.split('!')[1] : args.range.split('!')[0] : this.parent.getActiveSheet().selectedRange; const sheetIndex: number = args.range && args.range.indexOf('!') > 0 ? getSheetIndex(this.parent as Workbook, args.range.split('!')[0]) : this.parent.activeSheetIndex; const index: number[] = getRangeIndexes(rangeVal); rowIdx = index[0]; colIdx = index[1]; sheet = this.parent.sheets[sheetIndex]; } const cellObj: CellModel = getCell(rowIdx, colIdx, sheet); const prevCellImg: ImageModel[] = cellObj.image; const imgLength: number = prevCellImg.length; let image: ImageModel = {}; for (let i: number = 0; i < imgLength; i++) { if (prevCellImg[i].id === args.id) { image = prevCellImg.splice(i, 1)[0]; } } setCell(rowIdx, colIdx, sheet, { image: prevCellImg }, true); if (!args.preventEventTrigger) { this.parent.notify(completeAction, { action: 'deleteImage', eventArgs: { address: address, id: image.id, imageData: image.src, cancel: false } }); } } /** * To Remove the event listeners. * * @returns {void} - To Remove the event listeners. */ public destroy(): void { this.removeEventListener(); this.parent = null; } /** * Get the sheet picture module name. * * @returns {string} - Get the sheet picture module name. */ public getModuleName(): string { return 'spreadsheetImage'; } }
the_stack
import type { TextOffset } from '@cspell/cspell-types'; import { PairingHeap } from './PairingHeap'; import { escapeRegEx } from './regexHelper'; import { regExDanglingQuote, regExEscapeCharacters, regExPossibleWordBreaks, regExSplitWords, regExSplitWords2, regExTrailingEndings, regExWordsAndDigits, } from './textRegex'; const ignoreBreak: readonly number[] = Object.freeze([] as number[]); export type IsValidWordFn = (word: TextOffset) => boolean; export interface SplitResult { /** Original line passed to the split function */ line: TextOffset; /** Starting point of processing - Original offset passed to the split function */ offset: number; /** The span of text that was split */ text: TextOffset; /** The collection of words that `text` was split into */ words: TextOffsetWithValid[]; /** the offset at which the split stopped */ endOffset: number; } export interface LineSegment { line: TextOffset; relStart: number; relEnd: number; } export interface TextOffsetWithValid extends TextOffset { isFound: boolean; } // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface SplitOptions extends WordBreakOptions {} export function split( line: TextOffset, offset: number, isValidWord: IsValidWordFn, options: SplitOptions = {} ): SplitResult { const relWordToSplit = findNextWordText({ text: line.text, offset: offset - line.offset }); const lineOffset = line.offset; const requested = new Map<number, boolean>(); if (!relWordToSplit.text) { const text = rebaseTextOffset(relWordToSplit); return { line, offset, text: text, words: [], endOffset: text.offset + text.text.length, }; } const lineSegment: LineSegment = { line, relStart: relWordToSplit.offset, relEnd: relWordToSplit.offset + relWordToSplit.text.length, }; const possibleBreaks = generateWordBreaks(lineSegment, options); if (!possibleBreaks.length) { const text = rebaseTextOffset(relWordToSplit); return { line, offset, text: text, words: [{ ...text, isFound: isValidWord(text) }], endOffset: text.offset + text.text.length, }; } function rebaseTextOffset<T extends TextOffset>(relText: T): T { return { ...relText, offset: relText.offset + lineOffset, }; } function has(word: TextOffset): boolean { const i = word.offset; const j = word.text.length; let v = i + (j << 20); if (i < 1 << 20 && j < 1 << 11) { const b = requested.get(v); if (b !== undefined) return b; } else { v = -1; } const r = isValidWord(rebaseTextOffset(word)); if (v >= 0) { requested.set(v, r); } return r; } // Add a dummy break at the end to avoid needing to check for last break. possibleBreaks.push({ offset: lineSegment.relEnd, breaks: [ignoreBreak], }); const result: SplitResult = { line, offset, text: rebaseTextOffset(relWordToSplit), words: splitIntoWords(lineSegment, possibleBreaks, has).map(rebaseTextOffset), endOffset: lineOffset + lineSegment.relEnd, }; return result; } function findNextWordText({ text, offset }: TextOffset): TextOffset { const reg = new RegExp(regExWordsAndDigits); reg.lastIndex = offset; const m = reg.exec(text); if (!m) { return { text: '', offset: offset + text.length, }; } return { text: m[0], offset: m.index, }; } type BreakPairs = readonly number[]; interface PossibleWordBreak { /** offset from the start of the string */ offset: number; /** * break pairs (start, end) * (the characters between the start and end are removed) * With a pure break, start === end. */ breaks: BreakPairs[]; } export type SortedBreaks = PossibleWordBreak[]; interface WordBreakOptions { optionalWordBreakCharacters?: string; } function generateWordBreaks(line: LineSegment, options: WordBreakOptions): SortedBreaks { const camelBreaks = genWordBreakCamel(line); const symbolBreaks = genSymbolBreaks(line); const optionalBreaks = genOptionalWordBreaks(line, options.optionalWordBreakCharacters); return mergeSortedBreaks(...camelBreaks, ...symbolBreaks, ...optionalBreaks); } function offsetRegEx(reg: RegExp, offset: number) { const r = new RegExp(reg); r.lastIndex = offset; return r; } function genWordBreakCamel(line: LineSegment): SortedBreaks[] { const breaksCamel1: SortedBreaks = []; const text = line.line.text.slice(0, line.relEnd); // lower,Upper: camelCase -> camel|Case for (const m of text.matchAll(offsetRegEx(regExSplitWords, line.relStart))) { if (m.index === undefined) break; const i = m.index + 1; breaksCamel1.push({ offset: m.index, breaks: [[i, i], ignoreBreak], }); } const breaksCamel2: SortedBreaks = []; // cspell:ignore ERRORC // Upper,Upper,lower: ERRORCodes -> ERROR|Codes, ERRORC|odes for (const m of text.matchAll(offsetRegEx(regExSplitWords2, line.relStart))) { if (m.index === undefined) break; const i = m.index + m[1].length; const j = i + 1; breaksCamel2.push({ offset: m.index, breaks: [[i, i], [j, j], ignoreBreak], }); } return [breaksCamel1, breaksCamel2]; } function calcBreaksForRegEx( line: LineSegment, reg: RegExp, calcBreak: (m: RegExpMatchArray) => PossibleWordBreak | undefined ): SortedBreaks { const sb: SortedBreaks = []; const text = line.line.text.slice(0, line.relEnd); for (const m of text.matchAll(offsetRegEx(reg, line.relStart))) { const b = calcBreak(m); if (b) { sb.push(b); } } return sb; } function genOptionalWordBreaks(line: LineSegment, optionalBreakCharacters: string | undefined): SortedBreaks[] { function calcBreaks(m: RegExpMatchArray): PossibleWordBreak | undefined { const i = m.index; if (i === undefined) return; const j = i + m[0].length; return { offset: i, breaks: [ [i, j], // Remove the characters ignoreBreak, ], }; } const breaks: SortedBreaks[] = [ calcBreaksForRegEx(line, regExDanglingQuote, calcBreaks), calcBreaksForRegEx(line, regExTrailingEndings, calcBreaks), ]; if (optionalBreakCharacters) { const regex = new RegExp(`[${escapeRegEx(optionalBreakCharacters)}]`, 'gu'); breaks.push(calcBreaksForRegEx(line, regex, calcBreaks)); } return breaks; } function genSymbolBreaks(line: LineSegment): SortedBreaks[] { function calcBreaks(m: RegExpMatchArray): PossibleWordBreak | undefined { const i = m.index; if (i === undefined) return; const j = i + m[0].length; return { offset: i, breaks: [ [i, j], // Remove the characters [i, i], // keep characters with word to right [j, j], // keep characters with word to left ignoreBreak, ], }; } return [ calcBreaksForRegEx(line, regExPossibleWordBreaks, calcBreaks), calcBreaksForRegEx(line, /\d+/g, calcBreaks), calcBreaksForRegEx(line, regExEscapeCharacters, calcBreaks), ]; } interface PathNode { /** Next Path Node or undefined if at the end */ n: PathNode | undefined; /** offset in text */ i: number; /** cost to the end of the path */ c: number; /** the extracted text */ text: TextOffsetWithValid | undefined; } interface Candidate { /** parent candidate in the chain */ p: Candidate | undefined; /** offset in text */ i: number; /** index within Possible Breaks */ bi: number; /** current break pair */ bp: BreakPairs; /** cost */ c: number; /** expected cost */ ec: number; /** the extracted text */ text: TextOffsetWithValid | undefined; } function splitIntoWords( lineSeg: LineSegment, breaks: SortedBreaks, has: (word: TextOffset) => boolean ): TextOffsetWithValid[] { const maxIndex = lineSeg.relEnd; const maxAttempts = 1000; const knownPathsByIndex = new Map<number, PathNode>(); /** * Create a set of possible candidate to consider * @param p - prev candidate that lead to this one * @param i - offset within the string * @param bi - current index into the set of breaks * @param currentCost - current cost accrued */ function makeCandidates(p: Candidate | undefined, i: number, bi: number, currentCost: number): Candidate[] { const len = maxIndex; while (bi < breaks.length && breaks[bi].offset < i) { bi += 1; } if (bi >= breaks.length) { return []; } const br = breaks[bi]; function c(bp: BreakPairs): Candidate { const d = bp.length < 2 ? len - i : (bp[0] - i) * 0.5 + len - bp[1]; const ec = currentCost + d; return { p, i, bi, bp, c: currentCost, ec, text: undefined, }; } return br.breaks.map(c); } function toTextOffset(text: string, offset: number): TextOffsetWithValid { const valid = has({ text, offset }); return { text, offset, isFound: valid, }; } function compare(a: Candidate, b: Candidate): number { return a.ec - b.ec || b.i - a.i; } function pathToWords(node: PathNode | undefined): TextOffsetWithValid[] { const results: TextOffsetWithValid[] = []; for (let p = node; p; p = p.n) { if (p.text) { results.push(p.text); } } return results; } function addToKnownPaths(candidate: Candidate, path: PathNode | undefined) { for (let can: Candidate | undefined = candidate; can !== undefined; can = can.p) { const t = can.text; const i = can.i; const cost = (!t || t.isFound ? 0 : t.text.length) + (path?.c ?? 0); const exitingPath = knownPathsByIndex.get(i); // Keep going only if this is a better candidate than the existing path if (exitingPath && exitingPath.c <= cost) { return undefined; } const node: PathNode = { n: path, i, c: cost, text: t, }; knownPathsByIndex.set(i, node); path = node; } return path; } let maxCost = lineSeg.relEnd - lineSeg.relStart; const candidates = new PairingHeap<Candidate>(compare); const text = lineSeg.line.text; candidates.concat(makeCandidates(undefined, lineSeg.relStart, 0, 0)); let attempts = 0; let bestPath: PathNode | undefined; while (maxCost && candidates.length && attempts++ < maxAttempts) { /** Best Candidate Index */ const best = candidates.dequeue(); if (!best || best.c >= maxCost) { continue; } // Does it have a split? if (best.bp.length) { // yes const i = best.bp[0]; const j = best.bp[1]; const t = i > best.i ? toTextOffset(text.slice(best.i, i), best.i) : undefined; const cost = !t || t.isFound ? 0 : t.text.length; const mc = maxIndex - j; best.c += cost; best.ec = best.c + mc; best.text = t; const possiblePath = knownPathsByIndex.get(j); if (possiblePath) { // We found a known apply to candidate const f = addToKnownPaths(best, possiblePath); bestPath = !bestPath || (f && f.c < bestPath.c) ? f : bestPath; } else if (best.c < maxCost) { const c = makeCandidates(t ? best : best.p, j, best.bi + 1, best.c); candidates.concat(c); } } else { // It is a pass through const c = makeCandidates(best.p, best.i, best.bi + 1, best.c); candidates.concat(c); if (!c.length) { const t = maxIndex > best.i ? toTextOffset(text.slice(best.i, maxIndex), best.i) : undefined; const cost = !t || t.isFound ? 0 : t.text.length; best.c += cost; best.ec = best.c; best.text = t; const segText = t || best.p?.text || toTextOffset('', best.i); const can = t ? { ...best, text: segText } : { ...best, ...best.p, text: segText }; const f = addToKnownPaths(can, undefined); bestPath = !bestPath || (f && f.c < bestPath.c) ? f : bestPath; } } if (bestPath && bestPath.c < maxCost) { maxCost = bestPath.c; } } return pathToWords(bestPath); } function mergeSortedBreaks(...maps: SortedBreaks[]): SortedBreaks { return ([] as SortedBreaks).concat(...maps).sort((a, b) => a.offset - b.offset); } export const __testing__ = { generateWordBreaks, };
the_stack
import { IonicNativePlugin } from '@ionic-native/core'; import { Observable } from 'rxjs'; export interface RequestPermissionReq { permissionList: Array<string>; } export interface CheckPermissionReq { permissionList: Array<string>; } export interface statisticsnReq { isAllowed: boolean; } export interface MLBounds { marginTop?: number; marginBottom?: number; marginLeft?: number; marginRight?: number; } export interface MLconfig { lensEngineReq: lensEngineReq; } export interface lensEngineReq { analyzerName: MLAnalyzerName; lensEngineSetting?: MLLensEngineSetting; grapgicSetting?: FaceGraphicSetting | sceneSettings | HandkeyGraphicSetting | SkeletonGraphicSetting | ObjectGraphicSetting | null; analyzerSetting?: mlFaceAnalyzerSetting | mlHandKeypointSetting | mlImageSegmentationSetting | mlObjectAnalyserSetting | null; } export interface MLconfigComposite { lensEngineReq: compositeAnalyser; } export interface compositeAnalyser { analyzerNames?: Array<MLAnalyzerName>; lensEngineSetting?: MLLensEngineSetting; grapgicSetting?: FaceGraphicSetting | sceneSettings | HandkeyGraphicSetting | SkeletonGraphicSetting | ObjectGraphicSetting | null; analyzerSetting?: mlFaceAnalyzerSetting | mlHandKeypointSetting | mlImageSegmentationSetting | mlObjectAnalyserSetting | null; } export interface MLLensEngineSetting { fps?: number | null; displayDimensionI?: number | null; displayDimensionI1?: number | null; lensType?: MLLensType | null; enableFocus?: boolean | null; flashMode?: MLFlashMode | null; } export declare enum MLFlashMode { AUTO = "auto", ON = "on", OFF = "off" } export declare enum MLLensType { BACK_LENS = 0, FRONT_LENS = 1 } export declare enum MLStillCompositerName { FACE = "FACE", HAND = "HAND", SKELETON = "SKELETON", OBJECT = "OBJECT", TEXT = "TEXT", CLASSIFICATION = "classification" } export declare enum MLAnalyzerName { LIVEFACE = "FACE", LIVEFACE3D = "FACE3D", LIVEFACEMAX = "FACEMAX", LIVEHAND = "HAND", LIVESKELETON = "SKELETON", LIVEOBJECT = "OBJECT", LIVECLASSIFICATION = "CLASSIFICATION", LIVESCENE = "SCENE", LIVETEXT = "TEXT" } export interface doZoomReq { scale?: number | null; } export interface mlFrameReq { actionName: MLFrame; filePath: any; } export declare enum MLFrame { getPreviewBitmap = "getPreviewBitmap", readBitmap = "readBitmap", rotate = "rotate" } export interface configReq { apiKey: string; } export interface appSettingReq { apiKey?: string | null; applicationId?: string | null; certFingerprint?: string | null; } export interface compositeAnalyserReq { compositeAnalyserConfig: compositeAnalyserConfig; } export interface compositeAnalyserConfig { filePath: any; analyzerNames?: Array<MLStillCompositerName>; analyzerSetting?: mlFaceAnalyzerSetting | mlHandKeypointSetting | mlImageSegmentationSetting | mlObjectAnalyserSetting | null; } export interface aftReq { audioPath: any; aftSetting?: (AftSetting); } export interface AftSetting { languageCode?: string | null; punctuationEnabled?: boolean | null; timeOffset?: boolean | null; wordTimeOffsetEnabled?: boolean | null; sentenceTimeOffsetEnabled?: boolean | null; } export interface asrReq { language?: LANGUAGE | null; feature?: FEATURE | null; } export declare enum FEATURE { FEATURE_ALLINONE = 12, FEATURE_WORDFLUX = 11 } export declare enum LANGUAGE { LAN_EN_US = "en-US", LAN_FR_FR = "fr-FR", LAN_ZH = "zh", LAN_ZH_CN = "zh-CN", LAN_ES_ES = "es-ES", LAN_DE_DE = "de-DE" } export interface bankCardSDKDetectorReq { filePath: any; detectType: 0; mLBcrAnalyzerSetting?: MLBcrAnalyzerSetting | null; } export interface MLBcrAnalyzerSetting { langType?: string | null; resultType?: MLBcrResultConfig | null; } export interface bankCardPluginDetectorReq { detectType: 1; mLBcrCaptureConfig?: mLBcrCaptureConfig | null; } export interface mLBcrCaptureConfig { orientation?: MLBcrCaptureConfig | null; resultType?: MLBcrResultConfig | null; } export declare enum MLBcrCaptureConfig { ORIENTATION_AUTO = 0, ORIENTATION_LANDSCAPE = 1, ORIENTATION_PORTRAIT = 2 } export declare enum MLBcrResultConfig { RESULT_NUM_ONLY = 0, RESULT_SIMPLE = 1, RESULT_ALL = 2 } export interface localImageClassificationReq { ocrType: MLImageClassificationConfig | null; analyseMode?: number | null; localClassificationAnalyzerSetting?: (LocalClassificationAnalyzerSetting) | null; filePath: any; } export interface LocalClassificationAnalyzerSetting { possibility?: number | null; } export interface remoteImageClassificationReq { ocrType: MLImageClassificationConfig; analyseMode?: number; remoteClassificationAnalyzerSetting?: (RemoteClassificationAnalyzerSetting) | null; filePath: any; } export interface RemoteClassificationAnalyzerSetting { maxResults?: number | null; possibility?: number | null; isEnableFingerprintVerification?: boolean | null; } export declare enum MLImageClassificationConfig { TYPE_LOCAL = 0, TYPE_REMOTE = 1 } export interface downloadModelReq { detectType: 1; filePath: any; downloadStrategySetting?: DownloadStrategySetting | null; } export interface DownloadStrategySetting { isChargingNeed: boolean | null; isWifiNeed: boolean | null; isDeviceIdleNeed: boolean | null; setRegion?: DownloadStrategyCustom | null; } export declare enum DownloadStrategyCustom { REGION_DR_CHINA = 1002, REGION_DR_AFILA = 1003, REGION_DR_EUROPE = 1004, REGION_DR_RUSSIA = 1005 } export interface ownCustomModelReq { detectType: number; filePath: any; modelFullName: string | null; modelName: string | null; labelFileName: string | null; bitmapHeight: number | null; bitmapWidth: number | null; outPutSize: number | null; } export interface documentImageAnalyserReq { documentSetting?: DocumentSetting | null; filePath: any; } export interface DocumentSetting { borderType?: MLRemoteTextSetting | null; LanguageList?: Array<string> | null; enableFingerprintVerification: boolean | null; } export declare enum MLRemoteTextSetting { OCR_LOOSE_SCENE = 1, OCR_COMPACT_SCENE = 2, NGON = "NGON", ARC = "ARC" } export interface formRecognizerAnalyserReq { filePath: any; syncType: MLFormRecogitionConfig; } export declare enum MLFormRecogitionConfig { SYNC_TYPE = 1, ASYNC_TYPE = 0 } export interface documentSkewCorrectionReq { filePath: any; syncMode?: MLFormRecogitionConfig | null; } export interface faceReq { mlFaceAnalyserSetting?: mlFaceAnalyzerSetting | null; analyseMode?: MLFaceConfigs | null; filePath: any; } export declare enum MLFaceConfigs { TYPE_2D_SYNC = 0, TYPE_2D_ASYNC = 1, TYPE_3D_SYNC = 2, TYPE_3D_ASYNC = 3 } export interface FaceGraphicSetting { facePositionPaintSetting?: FacePositionPaintSetting | null; textPaintSetting?: TextPaintSettingFace | null; faceFeaturePaintTextSetting?: FaceFeaturePaintTextSetting | null; keypointPaintSetting?: KeypointPaintSetting | null; boxPaintSetting?: BoxPaintSettingFace | null; facePaintSetting?: FacePaintSetting | null; eyePaintSetting?: EyePaintSetting | null; eyebrowPaintSetting?: EyebrowPaintSetting | null; nosePaintSetting?: NosePaintSetting | null; noseBasePaintSetting?: NoseBasePaintSetting | null; lipPaintSetting?: LipPaintSetting | null; } export interface LipPaintSetting { color?: String | Colors | null; style?: RectStyle | null; strokeWidth: Number | null; } export interface NosePaintSetting { color?: String | Colors | null; style?: RectStyle | null; strokeWidth?: Number; } export interface NoseBasePaintSetting { color?: String | Colors | null; style?: RectStyle | null; strokeWidth?: Number; } export interface EyebrowPaintSetting { color?: String | Colors | null; style?: RectStyle; strokeWidth?: Number; } export interface EyePaintSetting { color?: String | Colors; style?: RectStyle | Colors; strokeWidth: Number | null; } export interface FacePaintSetting { color?: String | Colors | null; style?: RectStyle | null; strokeWidth: Number | null; } export interface BoxPaintSettingFace { color?: String | Colors | null; style?: RectStyle | null; strokeWidth?: Number | null; } export interface KeypointPaintSetting { color?: Colors | Colors | null; style?: RectStyle | null; textSize: Number | null; } export interface FaceFeaturePaintTextSetting { color?: Colors | null; textSize: Number | null; } export interface FacePositionPaintSetting { color?: Colors | null; } export interface TextPaintSettingFace { color?: Colors | null; textSize?: Number | null; } export interface mlFaceAnalyzerSetting { featureType?: MLFaceSetting | null; keyPointType?: MLFaceSetting | null; maxSizeFaceOnly?: boolean | null; minFaceProportion?: number | null; performanceType?: MLFaceSetting | null; poseDisabled?: boolean | null; shapeType?: MLFaceSetting | null; tracingAllowed?: boolean | null; } export declare enum MLFaceSetting { TYPE_FEATURES = 1, TYPE_UNSUPPORT_FEATURES = 2, TYPE_KEYPOINTS = 0, TYPE_UNSUPPORT_KEYPOINTS = 2, TYPE_PRECISION = 1, TYPE_SPEED = 2, TYPE_SHAPES = 2, TYPE_UNSUPPORT_SHAPES = 3, TYPE_FEATURE_EMOTION = 4, TYPE_FEATURE_EYEGLASS = 8, TYPE_FEATURE_HAT = 16, TYPE_FEATURE_BEARD = 32, TYPE_FEATURE_OPENCLOSEEYE = 64, TYPE_FEATURE_GENDAR = 128, TYPE_FEATURE_AGE = 256, MODE_TRACING_FAST = 1, MODE_TRACING_ROBUST = 2 } export interface generalCardDetectorReq { gcrCaptureConfig?: gcrCaptureConfig; gcrCaptureUIConfig?: gcrCaptureUIConfig; captureType?: gcrCaptureType | null; } export interface gcrCaptureConfig { language: string; } export declare enum gcrCaptureType { CAPTURE_ACTIVITY = 0, CAPTURE_PHOTO = 1, CAPTURE_IMAGE = 2 } export interface gcrCaptureUIConfig { orientation?: MLGcrCaptureUIConfig | null; tipText?: string | null; tipTextColor?: number | null; photoButtonResId?: number | null; scanBoxCornerColor?: number | null; backButtonRedId?: number | null; torchRedId?: number | null; } export declare enum MLGcrCaptureUIConfig { ORIENTATION_AUTO = 0, ORIENTATION_LANDSCAPE = 1, ORIENTATION_PORTRAIT = 2 } export interface idCardAnalyserReqWithSDK { detectType: number; isRemote?: boolean | null; isFront?: boolean | null; countryCode?: string; filePath: any; } export interface idCardAnalyserReqWithPlugin { detectType: number; isRemote?: boolean | null; isFront?: boolean | null; countryCode?: string; } export interface stillHandKeypointReq { syncType?: syncType | null; filePath: any; handkeySetting?: mlHandKeypointSetting | null; } export declare enum syncType { SYNC_MODE = 0, ASYNC_MODE = 1 } export interface HandkeyGraphicSetting { idPaintnewSetting?: IdPaintnewSetting | null; rectPaintSetting?: RectPaintSetting | null; } export interface IdPaintnewSetting { color?: Colors | null; textSize?: Number | null; } export interface RectPaintSetting { color?: Colors | null; style?: RectStyle | null; boxStrokeWidth?: Number | null; } export interface mlHandKeypointSetting { sceneType?: HandkeyPointConfig | null; maxHandResults?: number | null; } export declare enum HandkeyPointConfig { TYPE_ALL = 0, TYPE_KEYPOINT_ONLY = 1, TYPE_RECT_ONLY = 2 } export interface imageSuperResolutionReq { filePath: any; imgSuperResolutionSetting?: (ImgSuperResolutionSetting) | null; syncType?: MLFormRecogitionConfig | null; } export interface ImgSuperResolutionSetting { scaleType?: ImgSuperResolutionConfig; } export declare enum ImgSuperResolutionConfig { ISR_SCALE_1X = 1, ISR_SCALE_3X = 3 } export interface productReq { filePath?: any | null; detectType?: number; mlProductSetting?: (mlProductSetting) | null; } export interface mlProductSetting { largestNumOfReturns?: number | null; productSetId?: string | null; region?: MLProductConfig | null; } export declare enum MLProductConfig { REGION_DR_CHINA = 1002, REGION_DR_AFILA = 1003, REGION_DR_EUROPE = 1004, REGION_DR_RUSSIA = 1005, REGION_DR_GERMAN = 1006, REGION_DR_SIANGAPORE = 1007 } export interface textImageSuperResolutionReq { filePath: any; analyseMode?: MLFormRecogitionConfig | null; } export interface imgSegmentationReq { imageSegmentationSetting?: (mlImageSegmentationSetting); filePath: any; analyseMode?: MLFormRecogitionConfig | null; } export interface mlImageSegmentationSetting { isExact: boolean | null; analyserType?: MLImageSegmentationSetting | null; scene?: MLImageSegmentationScene; } export declare enum MLImageSegmentationSetting { BODY_SEG = 0, IMAGE_SEG = 1 } export declare enum MLImageSegmentationScene { ALL = 0, MASK_ONLY = 1, FOREGROUND_ONLY = 2, GRAYSCALE_ONLY = 3 } export interface imgLandMarkReq { landmarkAnalyzerSetting?: landmarkAnalyzerSetting; filePath: any; } export interface landmarkAnalyzerSetting { maxResults?: number | null; modelType?: MLRemoteLandmarkSetting | null; } export declare enum MLRemoteLandmarkSetting { STEADY_PATTERN = 1, NEWEST_PATTERN = 2 } export interface remoteLangDetectionReq { sourceText: string; taskMode?: number; trustedThreshold?: number; } export interface localLangDetectionReq { sourceText: string; trustedThreshold?: number; } export interface livenessDetectionReq { analyserMode?: MLLivenessCaptureResult | null; } export declare enum MLLivenessConfig { DEFAULT = 0, CUSTOM = 1 } export interface objectReq { filePath: any; mlObjectAnalyserSetting?: mlObjectAnalyserSetting; syncType?: MLFormRecogitionConfig | null; } export interface ObjectGraphicSetting { boxPaintSetting?: BoxPaintSetting | null; textPaintSetting?: TextPaintSetting | null; } export interface BoxPaintSetting { color?: Colors | null; style?: RectStyle | null; boxStrokeWidth?: Number | null; } export interface TextPaintSetting { color?: Colors | null; textSize?: Number | null; } export interface mlObjectAnalyserSetting { isClassificationAllowed?: boolean | null; isMultipleResultsAllowed?: boolean | null; analyzerType: MlObjectAnalyserConfig; } export declare enum MlObjectAnalyserConfig { TYPE_VIDEO = 1, TYPE_PICTURE = 0 } export interface rttReq { mLSpeechRealTimeTranscriptionConfig: MLSpeechRealTimeTranscriptionConfig; } export interface MLSpeechRealTimeTranscriptionConfig { language: MLRttLanguages | null; punctuationEnable: boolean | null; wordTimeOffsetEnable: boolean | null; sentenceTimeOffsetEnable: boolean | null; scenes?: MLRttScenes | null; } export declare enum MLRttLanguages { LAN_ZH_CN = "zh-CN", LAN_EN_US = "en-US", LAN_FR_FR = "fr-FR", LAN_ES_ES = "es-ES", LAN_EN_IN = "en-IN", LAN_DE_DE = "de-DE" } export declare enum MLRttScenes { SCENES_SHOPPING = "shopping" } export interface stillSceneReq { filePath: any; analyseMode?: syncType | null; } export interface sceneSettings { color?: Colors | null; textSize?: Number | null; } export interface stillSkeletonReq { filePath: any; syncType: MLSkeletonConfig; analyzerType: MLSkeletonConfig; } export interface stillSkeletonSimilarityReq { filePath: any; filepath2: any; syncType: MLSkeletonConfig; analyzerType: MLSkeletonConfig; } export declare enum MLSkeletonConfig { SYNC_MODE = 0, ASYNC_MODE = 1, SIMILARITTY_MODE = 2, TYPE_YOGA = 1, TYPE_NORMAL = 0 } export interface SkeletonGraphicSetting { circlePaintSetting?: circlePaintSetting | null; linePaintSetting?: linePaintSetting | null; } export interface circlePaintSetting { color?: Colors | null; style?: RectStyle | null; antiAlias?: boolean | null; } export interface linePaintSetting { color?: Colors | null; style?: RectStyle | null; strokeWidth?: Number | null; antiAlias?: boolean | null; } export interface localImageTextReq { ocrType: MLTextConfig; analyseMode?: number; localTextSetting?: (localTextSetting) | null; filePath: any; } export interface localTextSetting { ocrMode?: MLLocalTextSetting; language?: string; } export declare enum MLLocalTextSetting { OCR_DETECT_MODE = 1, OCR_TRACKING_MODE = 2 } export declare enum MLTextConfig { OCR_LOCAL_TYPE = 0, OCR_REMOTE_TYPE = 1 } export interface remoteImageTextReq { ocrType: MLTextConfig; analyseMode?: number; remoteTextSetting?: (remoteTextSetting); filePath: any; } export interface remoteTextSetting { textDensityScene?: MLRemoteTextSetting; languageList?: Array<string>; borderType?: MLRemoteTextSetting; } export interface remotetranslateReq { USE_SYNC: boolean; targetLangCode: string; sourceLangCode?: string; sourceText: string; } export interface localtranslateReq { USE_SYNC: boolean; targetLangCode: string; sourceLangCode: string; sourceText: string; } export interface deleteTranslateReq { USE_SYNC: boolean; langcode: string; } export interface downloadTranslateReq { USE_SYNC: boolean; langcode: string; } export interface localAllLangReq { USE_SYNC: boolean; } export interface remoteAllLangReq { USE_SYNC: boolean; } export interface soundDectReq { startType: boolean | null; } export interface textEmbeddingDicInfoReq { textEmbeddingSetting: textEmbeddingSetting; } export interface textEmbeddingWordtoVectorReq { textEmbeddingSetting?: textEmbeddingSetting; wordText: string; } export interface textEmbeddingSentencetoVectorReq { textEmbeddingSetting?: textEmbeddingSetting; sentenceText: string; } export interface textEmbeddingWordSimilarityReq { textEmbeddingSetting?: textEmbeddingSetting; wordText1: string; wordText2: string; } export interface textEmbeddingSentenceSimilarityReq { textEmbeddingSetting?: textEmbeddingSetting; sentenceText1: string; sentenceText2: string; } export interface textEmbeddingSimilarWordsReq { textEmbeddingSetting?: textEmbeddingSetting; multipleText: string; similarityNumber: number; } export interface textEmbeddingWordBatchReq { textEmbeddingSetting?: textEmbeddingSetting; batchText: string; } export interface textEmbeddingSetting { language: string; } export interface ttsEngineReq { language?: string | null; } export interface ttsReq { text: string; mlConfigs: MLConfigs; queuingMode: MLTtsConstants; } export interface MLConfigs { language: MLTtsConstants; person: MLTtsConstants; speed: number; volume: number; synthesizeMode: MLTtsConstants; } export declare enum MLTtsConstants { TTS_EN_US = "en-US", TTS_LAN_ES_ES = "es-ES", TTS_LAN_FR_FR = "fr-FR", TTS_LAN_DE_DE = "de-DE", TTS_LAN_IT_IT = "it-IT", TTS_ZH_HANS = "zh-Hans", TTS_SPEAKER_FEMALE_EN = "Female-en", TTS_SPEAKER_FEMALE_ZH = "Female-zh", TTS_SPEAKER_MALE_EN = "Male-en", TTS_SPEAKER_MALE_ZH = "Male-zh", TTS_SPEAKER_FEMALE_DE = "de-DE-st-1", TTS_SPEAKER_FEMALE_ES = "it-IT-st-1", TTS_SPEAKER_FEMALE_IT = "es-ES-st-1", TTS_SPEAKER_FEMALE_FR = "fr-FR-st-1", TTS_SPEAKER_OFFLINE_EN_US_MALE_BOLT = "en-US-st-bolt-2", TTS_SPEAKER_OFFLINE_ZH_HANS_FEMALE_EAGLE = "zh-Hans-st-eagle-1", TTS_SPEAKER_OFFLINE_ZH_HANS_MALE_EAGLE = "zh-Hans-st-eagle-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_EAGLE = "en-US-st-eagle-1", TTS_SPEAKER_OFFLINE_EN_US_MALE_EAGLE = "en-US-st-eagle-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_BEE = "en-US-st-bee-1", TTS_SPEAKER_OFFLINE_FR_FR_FEMALE_BEE = "fr-FR-st-bee-1", TTS_SPEAKER_OFFLINE_ES_ES_FEMALE_BEE = "es-ES-st-bee-1", TTS_SPEAKER_OFFLINE_DE_DE_FEMALE_BEE = "de-DE-st-bee-1", TTS_SPEAKER_OFFLINE_IT_IT_FEMALE_BEE = "it-IT-st-bee-1", TTS_SPEAKER_OFFLINE_ZH_HANS_FEMALE_BOLT = "zh-Hans-st-bolt-1", TTS_SPEAKER_OFFLINE_ZH_HANS_MALE_BOLT = "zh-Hans-st-bolt-2", TTS_SPEAKER_OFFLINE_EN_US_FEMALE_BOLT = "en-US-st-bolt-1", TTS_ONLINE_MODE = "online", TTS_OFFLINE_MODE = "offline", QUEUE_APPEND = 0, QUEUE_FLUSH = 1, EXTERNAL_PLAYBACK = 2, OPEN_STREAM = 4 } export declare enum Colors { RED = -65536, DKGRAY = -12303292, GRAY = -7829368, WHITE = -1, BLUE = -16776961, BLACK = -16777216, LTGRAY = -3355444, MAGENTA = -65281, YELLOW = -256, CYAN = -16711681, GREEN = -16711936, TRANSPARENT = 0 } export declare enum RectStyle { STROKE = 1, FILL = 2, FILL_AND_STROKE = 3 } export interface MLAftResult { eventName: string; text: string; taskId: string; complete: boolean; } export interface MLAftErrorResult { eventName: string; taskId: string; errorCode: MLAftErrorCodes; message: string; } export declare enum MLAftErrorCodes { EROTSUPPORTED = 11101, LANGUAGE_CODE_NOTSUPPORTED = 11102, ERR_AUDIO_FILE_SIZE_OVERFLOW = 11103, ERR_AUDIO_LENGTH_OVERFLOW = 11104, ERR_FILE_NOT_FOUND = 11105, ERR_ILLEGAL_PARAMETER = 11106, ERR_ENGINE_BUSY = 11107, ERR_NETCONNECT_FAILED = 11108, ERR_RESULT_WHEN_UPLOADING = 11109, ERR_TASK_NOT_EXISTED = 11110, ERR_AUDIO_TRANSCRIPT_FAILED = 11111, ERR_AUDIO_INIT_FAILED = 11112, ERR_AUDIO_UPLOAD_FAILED = 11113, ERR_TASK_ALREADY_INPROGRESS = 11114, ERR_NO_ENOUGH_STORAGE = 11115, ERR_AUTHORIZE_FAILED = 11119, ERR_SERVICE_CREDIT = 11122, ERR_INTERNAL = 11198, ERR_UNKNOWN = 11199 } export interface MLAftEventResult { eventName: string; taskId: string; ext: string; eventId: string; } export declare enum MLAFTEventCodes { PAUSE_EVENT = 2, STOP_EVENT = 3, UPLOADED_EVENT = 1 } export interface MLBankCard { number: string; expire: string; issuer: string; type: string; organization: string; originalBitmap: any; numberBitmap: any; } export interface MLCustomBankCard { number: string; expire: string; issuer: string; type: string; organization: string; originalBitmap: any; numberBitmap: any; } export interface MLFace { Result?: (ResultEntity)[] | null; } export interface ResultEntity { opennessOfLeftEye: number; tracingIdentity: number; possibilityOfSmiling: number; opennessOfRightEye: number; rotationAngleX: number; rotationAngleY: number; rotationAngleZ: number; height: number; width: number; border: Border; features: Features; emotions: Emotions; allPoints?: (AllPointsEntity)[] | null; keyPoints?: (null)[] | null; faceShapeList?: (FaceShapeListEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Features { sunGlassProbability: number; sexProbability: number; rightEyeOpenProbability: number; moustacheProbability: number; leftEyeOpenProbability: number; age: number; hatProbability: number; } export interface Emotions { surpriseProbability: number; smilingProbability: number; sadProbability: number; neutralProbability: number; fearProbability: number; disgustProbability: number; angryProbability: number; } export interface AllPointsEntity { X: number; Y: number; } export interface FaceShapeListEntity { points?: (PointsEntity)[] | null; faceShapeType: number; } export interface PointsEntity { X: number; Y: number; Z: number; } export interface MLImageClassification { result?: (ResultEntity)[] | null; } export interface ResultEntity { identity: string; name: string; possibility: number; hashCode: number; } export interface MLDocument { stringValue: string; blocks?: (Blocks)[]; } export interface Blocks { stringValue: string; possibility: number; border: Border; interval: Interval; sections?: (Sections)[]; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Interval { intervalType: number; isTextFollowed: boolean; } export interface Sections { stringValue: string; border: Border; interval: Interval; possibility: number; languageList?: (LanguageList)[]; lineList?: (LineList)[]; } export interface LanguageList { language: string; } export interface LineList { stringValue: string; border: Border; possibility: number; languageList?: (LanguageList)[]; wordList?: (WordList)[]; } export interface WordList { stringValue: string; border: Border; characterList?: (CharacterList)[]; languageList?: (LanguageList)[]; possibility?: number; interval?: Interval; } export interface CharacterList { stringValue: string; possibility: number; border?: Border; languageList?: (LanguageList)[]; interval?: Interval; } export interface MLDocumentSkewDetectResult { resultCode: number; bitmap: any; } export interface MLGcrCaptureResult { text: string; cardBitmap: any; } export interface MLHandKeypoints { handkeyPoints: handkeyPoints; rect: Rect; score: number; } export interface handkeyPoints { x: number; y: number; score: number; type: number; } export interface Rect { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface MLImageSegmentation { bitmapForeground: any; bitmapGrayscale: any; masks: number; bitmapOriginal: any; } export interface MLRemoteLandmark { landmark: string; landmarkIdentity: string; possibility: number; border: Border; positionInfo?: (PositionInfoEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface PositionInfoEntity { lng: number; lat: number; } export interface MLRemoteLangDetection { langCode: string; probability: number; hashCode: number; } export interface MLlangDetectionWithFirstDetect { langCode: string; } export interface MLLivenessCaptureResult { bitmap: Bitmap; isLive: boolean; pitch: number; roll: number; score: number; yaw: number; } export interface Bitmap { mGalleryCached: boolean; mHeight: number; mNativePtr: number; mWidth: number; } export interface MLObject { typeIdentity: number; typePossibility: number; border: Border; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface MLSkeleton { joints: joints; } export interface joints { x: number; y: number; score: number; type: number; hashCode: number; } export interface MLText { stringValue: string; blocks?: (Blocks)[]; } export interface Blocks { contents?: (Contents)[]; } export interface Contents { stringValue: string; rotatingDegree: number; isVertical: boolean; language: string; border: Border; contents?: (Contents)[]; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface Contents { stringValue: string; border: Border; language: string; languageList?: (LanguageList)[]; vertexes?: (Vertexes)[]; } export interface LanguageList { language: string; } export interface Vertexes { x: number; y: number; describeContents: number; } export interface MLTtsResult { eventName: string; taskID: string; start: number; end: number; } export interface MLSceneDetectionResult { resultString: string; confidence: number; } export interface LiveScenAnalyser { analyseList: [AnalyseList]; frameProperty: FrameProperty; } export interface AnalyseList { 0: a; } export interface a { result: string; confidence: number; } export interface FrameProperty { ext: string; formatType: number; height: number; itemIdentity: number; quadrant: number; timestamp: number; width: number; } export interface MLSoundDectResult { soundType: MLSoundDectSoundTypeResult; eventName: string; } export declare enum MLSoundDectSoundTypeResult { SOUND_DECT_ERROR_NO_MEM = 12201, SOUND_DECT_ERROR_FATAL_ERROR = 12202, SOUND_DECT_ERROR_AUDIO = 12203, SOUND_DECT_ERROR_INTERNAL = 12298, SOUND_EVENT_TYPE_LAUGHTER = 0, SOUND_EVENT_TYPE_BABY_CRY = 1, SOUND_EVENT_TYPE_SNORING = 2, SOUND_EVENT_TYPE_SNEEZE = 3, SOUND_EVENT_TYPE_SCREAMING = 4, SOUND_EVENT_TYPE_MEOW = 5, SOUND_EVENT_TYPE_BARK = 6, SOUND_EVENT_TYPE_WATER = 7, SOUND_EVENT_TYPE_CAR_ALARM = 8, SOUND_EVENT_TYPE_DOOR_BELL = 9, SOUND_EVENT_TYPE_KNOCK = 10, SOUND_EVENT_TYPE_ALARM = 11, SOUND_EVENT_TYPE_STEAM_WHISTLE = 12 } export interface MLVocabularyVersion { dictionaryDimension: string; dictionarySize: string; versionNo: string; } export interface MLWordtoVectorResult { result: Result; } export interface Result { wordText: string; vector: string; } export interface MlSentencetoVectorResult { sentence: string; vector: string; } export interface MLWordSimilarityResult { wordSimilarity: number; } export interface MLSentenceSimilarityResult { sentenceSimilarity: number; } export interface MLSimilarWordsResult { result?: (string)[] | null; } export interface MLFormRecogitionResult { retCode: number; tableContent: TableContent; } export interface TableContent { tableCount: number; tables?: (TablesEntity)[] | null; } export interface TablesEntity { tableID: number; headerInfo: string; footerInfo: string; tableBody?: (TableBodyEntity)[] | null; } export interface TableBodyEntity { startRow: number; endRow: number; startCol: number; endCol: number; cellCoordinate: CellCoordinate; textInfo: string; } export interface CellCoordinate { topLeft_x: number; topLeft_y: number; topRight_x: number; topRight_y: number; bottomLeft_x: number; bottomLeft_y: number; bottomRight_x: number; bottomRight_y: number; } export interface MLProductVisionResult { type: string; border: Border; list?: (ListEntity)[] | null; } export interface Border { bottom: number; top: number; left: number; right: number; exactCenterX: number; centerY: number; centerX: number; describeContents: number; height: number; width: number; } export interface ListEntity { customcontent: string; imagelist?: (ImagelistEntity)[] | null; possibility: number; productURL: string; } export interface ImagelistEntity { imageId: string; possibility: number; productId: string; } export declare class HMSMLKit extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; /** * Adjusts the focal length of the camera based on the scaling coefficient (digital zoom). * @param {doZoomReq} doZoomReq Reperesents the necessary parameters. * @returns Promise<any> */ doZoom(doZoomReq: doZoomReq): Promise<any>; /** * Monitors photographing. * @returns Promise<any> */ photograph(): Promise<any>; /** * Close lens engine. * @returns Promise<any> */ destroy(): Promise<any>; /** * Obtains the size of the preview image of a camera. * @returns Promise<any> */ getDisplayDimension(): Promise<any>; /** * Obtains the selected camera type. * @returns Promise<any> */ getLensType(): Promise<any>; /** * It checks the permissions required to use this Kit. * @param {CheckPermissionReq} permissionListInput Represents the list in which permission names are kept. * @returns Promise<any> */ hasPermissions(permissionListReq: CheckPermissionReq): Promise<any>; /** * It gets the necessary permissions. * @param {RequestPermissionReq} permissionListInput Represents the list in which permission names are kept. * @returns Promise<any> */ requestPermissions(permissionListInput: RequestPermissionReq): Promise<any>; /** * It sets Api Key or access token for application. * @param {configReq} params Represents your API_KEY. * @returns Promise<any> */ serviceInitializer(params: configReq): Promise<any>; /** * This service recognize the image from the picture and return what the picture can be with the percentages. Use ML Libraries. * @param {ownCustomModelReq | downloadModelReq} customModelReq Represents the parameter required for custom model analyser. * @returns Promise<any> */ customModelAnalyser(customModelReq: ownCustomModelReq | downloadModelReq): Promise<any>; /** * Obtains Frame. * @param {mlFrameReq} mlFrameReq Represents the parameter required. * @returns Promise<any> */ mlFrame(mlFrameReq: mlFrameReq): Promise<any>; /** * An app information class used to store basic information about apps with the HMS Core ML SDK integrated and complete the initialization of ML Kit. When using cloud services of the ML Kit, you need to set the apiKey of your app. * @param {appSettingReq} appSettingReq Represents the parameter required. * @returns Promise<any> */ appSetting(appSettingReq: appSettingReq): Promise<any>; /** * Determines whether to collect statistics on the current app. * @param {any} any * @returns Promise<any> */ setStatistic(any: any): Promise<any>; /** * Determines whether to collect statistics on the current app. ** @param {any} any * @returns Promise<any> */ getStatistic(any: any): Promise<any>; /** * This service enable logger service. * @returns Promise<any> */ enableLogger(): Promise<any>; /** * This service disable logger service. * @returns Promise<any> */ disableLogger(): Promise<any>; } export declare abstract class MLLive { private arScene; constructor(scene: string, divId: string); on(call: (value: any) => void): Promise<void>; startARScene(config?: MLconfig, bounds?: MLBounds): Promise<void>; destroy(): Promise<void>; setConfig(config: MLconfig): Promise<void>; scroll(): Promise<void>; } export declare class liveEngineAnalyser extends MLLive { constructor(divId: string); } export declare class HMSFaceBodyProvider extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; /** * The face detection service can detect the face contour, recognize facial features, and determine facial expressions for a person. * @param {faceReq} faceReq Represents the parameter required for face detection. * @returns Promise<StillFaceAnalyser> */ stillFaceAnalyser(faceReq: faceReq): Promise<MLFace>; /** * This method gives the information of the face recognition service. * @returns Promise<any> */ stilFaceAnalyserInfo(): Promise<any>; /** * This method stop face recognition service. * @returns Promise<any> */ stopStillFaceAnalyser(): Promise<any>; /** The skeleton detection service detects and locates key points of the human body, such as the top of the head, neck, shoulder, elbow, wrist, hip, knee, and ankle. * @param {stillSkeletonReq |stillSkeletonSimilarityReq} stillSkeletonReq Represents the parameter required for still skeleton detection. * @returns Promise<StillSkeletonAnalyser> */ stillSkeletonAnalyser(stillSkeletonReq: stillSkeletonReq | stillSkeletonSimilarityReq): Promise<MLSkeleton>; /** * The liveness detection service supports silent liveness detection and captures faces in real time. It can determine whether a face is of a real user or is a face attack * (for example, face recapture image, face recapture video, or face mask) without requiring the user to follow specific instructions. * @param {livenessDetectionReq} livenessDetectionReq Represents the parameter required. * @returns Promise<LiveLivenessAnalyser> */ liveLivenessAnalyser(livenessDetectionReq: livenessDetectionReq): Promise<MLLivenessCaptureResult>; /** * This service can detects 21 hand keypoints (including fingertips, knuckles, and wrists) and return positions of the keypoints. * @param {stillHandKeypointReq } stillHandKeypointReq Represents the parameter required for still handkey analyser. * @returns Promise<StillHandKeyAnalyser> */ stillHandkeyAnalyser(stillHandKeypointReq: stillHandKeypointReq): Promise<MLHandKeypoints>; /** * This method stop hand analyzer service. * @returns Promise<any> */ stopStillHandKeyAnalyser(): Promise<any>; /** * This method returns face analyzer settings. * @returns Promise<any> */ getFaceAnalyserSetting(): Promise<any>; /** * This method returns hand analyzer settings. * @returns Promise<any> */ getHandKeyAnalyserSetting(): Promise<any>; /** * This method stop skeleton analyzer service. * @returns Promise<any> */ stopStillSkeletonAnalyser(): Promise<any>; } export declare class HMSImageServiceProvider extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; /** * This method represents the image classification SDK. * @param {localImageClassificationReq|remoteImageClassificationReq} imageClassificationInput Represents the parameter required for classify objects. * @returns Promise<ImageClassificationAnalyser> */ imageClassificationAnalyser(imageClassificationInput: localImageClassificationReq | remoteImageClassificationReq): Promise<MLImageClassification>; /** * This method stop image classification analyser. * @returns Promise<string> */ stopImageClassificationAnalyser(): Promise<string>; /** * The image segmentation service segments same elements (such as human body, plant, and sky) from an image. The elements supported include human body, sky, plant, food and others. * @param {imgSegmentationReq} imgSegmentationReq Represents the parameter required for image segmentation. * @returns Promise<SegmentationAnalyser> */ imgSegmentation(imgSegmentationReq: imgSegmentationReq): Promise<MLImageSegmentation>; /** * This method stop image segmentation service. * @returns Promise<any> */ stopImgSegmentation(): Promise<any>; /** * The landmark recognition service enables you to obtain the landmark name, landmark longitude and latitude, and confidence of the input image. * @param {imgLandMarkReq} imgLandMarkReq Represents the parameter required for image landmark analyser. * @returns Promise<ImageLandmarkAnalyser> */ imgLandMarkAnalyser(imgLandMarkReq: imgLandMarkReq): Promise<MLRemoteLandmark>; /** * This method stop image landmark analyser service. * @returns Promise<any> */ imgLandMarkAnalyserStop(): Promise<any>; /** * The object detection service can detect and track multiple objects in an image. * @param {objectReq} objectReq Represents the parameter required for object detection. * @returns Promise<ImageObjectAnalyser> */ objectAnalyser(objectReq: objectReq): Promise<MLObject>; /** * The scene detection service can classify the scenario content of images and add labels, such as outdoor scenery, indoor places, and buildings, to help understand the image content. * @param {stillSceneReq} stillSceneReq Represents the parameter required for Scene analyser. * @returns Promise <any> */ stillSceneAnalyser(stillSceneReq: stillSceneReq): Promise<MLSceneDetectionResult>; /** This service can automatically identify the location of a document in an image and adjust the shooting angle to the angle facing the document, even if the document is tilted. * @param {documentSkewCorrectionReq} documentSkewCorrectionReq Represents the parameter required for document skew correction. * @returns Promise<DocumentSkewAnalyser> */ documentSkewCorrectionAnalyser(documentSkewCorrectionReq: documentSkewCorrectionReq): Promise<MLDocumentSkewDetectResult>; /** * This service can zoom in an image that contains text and significantly improve the definition of text in the image. * @param {textImageSuperResolutionReq} textImageSuperResolutionReq Represents the parameter required for Text Image Super Resolution. * @returns Promise<any> */ textImageSuperResolution(textImageSuperResolutionReq: textImageSuperResolutionReq): Promise<any>; /** * This service provides the 1x super-resolution capabilities. 1x super-resolution removes the compression noise. * @param {imageSuperResolutionReq} imageSuperResolutionReq Represents the parameter required for Image Super Resolution. * @returns Promise<any> */ imageSuperResolution(imageSuperResolutionReq: imageSuperResolutionReq): Promise<any>; /** * Represents the image-based product detection API of HUAWEI ML Kit. * @param {productReq} productReq Represents the parameter required. * @returns Promise<any> */ productVisionAnalyser(productReq: productReq): Promise<any>; /** * This method stop object analyser service. * @returns Promise<any> */ objectAnalyserStop(): Promise<any>; /** * This method stop product analyser service. * @returns Promise<any> */ productAnalyserStop(): Promise<any>; /** * This method stop document skew analyser service. * @returns Promise<any> */ docSkewAnalyserStop(): Promise<any>; /** * This method stop TISR analyser service. * @returns Promise<any> */ TISRAnalyserStop(): Promise<any>; /** * This method stop ISR analyser service. * @returns Promise<any> */ ISRAnalyserStop(): Promise<any>; /** * This method stop scene analyser service. * @returns Promise<any> */ stillSceneAnalyserStop(): Promise<any>; /** * This method returns image classification settings. * @returns Promise<any> */ getImageClassificationAnalyserSetting(): Promise<any>; /** * This method returns ISR settings. * @returns Promise<any> */ getISRSetting(): Promise<any>; /** * This method returns segmentation settings. * @returns Promise<any> */ getSegmentationSetting(): Promise<any>; /** * This method returns landmark settings. * @returns Promise<any> */ getLandmarkSetting(): Promise<any>; /** * This method returns object settings. * @returns Promise<any> */ getObjectSetting(): Promise<any>; } export declare class HMSLanguageServiceProvider extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingDicInfoReq} textEmbeddingDicInfoReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingDictionaryInfo(textEmbeddingDicInfoReq: textEmbeddingDicInfoReq): Promise<MLVocabularyVersion>; /** * Asynchronously queries word vectors in batches. (The number of words ranges from 1 to 500.) * @param {textEmbeddingWordBatchReq} textEmbeddingWordBatchReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingWordBatchVector(textEmbeddingWordBatchReq: textEmbeddingWordBatchReq): Promise<any>; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingWordtoVectorReq} textEmbeddingWordtoVectorReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingWordtoVector(textEmbeddingWordtoVectorReq: textEmbeddingWordtoVectorReq): Promise<MLWordtoVectorResult>; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingSentencetoVectorReq} textEmbeddingSentencetoVectorReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingSentencetoVector(textEmbeddingSentencetoVectorReq: textEmbeddingSentencetoVectorReq): Promise<MlSentencetoVectorResult>; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingWordSimilarityReq} textEmbeddingWordSimilarityReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingWordSimilarty(textEmbeddingWordSimilarityReq: textEmbeddingWordSimilarityReq): Promise<MLWordSimilarityResult>; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingSentenceSimilarityReq} textEmbeddingSentenceSimilarityReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingSentenceSimilarty(textEmbeddingSentenceSimilarityReq: textEmbeddingSentenceSimilarityReq): Promise<MLSentenceSimilarityResult>; /** * The text embedding service allows you to enter Chinese and English words or sentences to query matching vector values, and perform further research based on the query result. * @param {textEmbeddingSimilarWordsReq} textEmbeddingSimilarWordsReq Represents the parameter required for Text Embedding. * @returns Promise<any> */ textEmbeddingSimilarWords(textEmbeddingSimilarWordsReq: textEmbeddingSimilarWordsReq): Promise<MLSimilarWordsResult>; /** * This method returns textembedding settings. * @returns Promise<any> */ getTextEmbeddingSetting(): Promise<any>; } export declare class HMSTextServiceProvider extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; /** * This method start the Text analyzer. * @param {localImageTextReq|remoteImageTextReq} ImageTextAnalyserInput Reperesents the necessary parameters to convert images to text format. * @returns Promise <TextAnalyser> */ imageTextAnalyser(ImageTextAnalyserInput: localImageTextReq | remoteImageTextReq): Promise<MLText>; /** * This method stop the Text analyzer. * @returns Promise<any> */ stopTextAnalyser(): Promise<any>; /** * This method gives Text Analyser information. * @returns Promise<any> */ getTextAnalyserInfo(): Promise<any>; /** * This method provides a document recognition component that recognizes text from images of documents. * @param {documentImageAnalyserReq} documentImageAnalyserReq Reperesents the necessary parameter to convert document images to text format. * @returns Promise<DocumentAnalyser> */ documentImageAnalyser(documentImageAnalyserReq: documentImageAnalyserReq): Promise<MLDocument>; /** * This method stop the Document analyzer. * @returns Promise<any> */ stopDocumentImageAnalyser(): Promise<any>; /** * This method close the Document analyzer. * @returns Promise<any> */ closeDocumentImageAnalyser(): Promise<any>; /** * This method returns the Document analyzer setting. * @returns Promise<any> */ getDocumentImageAnalyserSetting(): Promise<any>; /** * This method returns the Image analyzer setting. * @returns Promise<any> */ getTextAnalyserSetting(): Promise<any>; /** * This method returns the GCR setting. * @returns Promise<any> */ getGCRSetting(): Promise<any>; /** * This method stop the Form Recognition Analyzer. * @returns Promise<any> */ stopFormRecognitionAnalyser(): Promise<any>; /** * The bank card recognition service recognizes bank cards in camera streams within angle offset of 15 degrees and extracts key information such as card number and validity period. * @param {bankCardSDKDetectorReq|bankCardPluginDetectorReq} bankCardDetecterInput Represents the parameter required for bank card recognition. * @returns Promise<BankCardAnalyser> | Promise<BankCardAnalyser> */ bankCardDetector(bankCardDetecterInput: bankCardSDKDetectorReq | bankCardPluginDetectorReq): Promise<MLBankCard>; /** * This method stop bankcard recognition service. * @returns Promise<any> */ stopBankCardDetector(): Promise<any>; /** * This method returns the BCR setting. * @returns Promise<any> */ getBankCardDetectorSetting(): Promise<any>; /** * The general card recognition service provides a universal development framework based on the text recognition technology. * @param {generalCardDetectorReq} generalCardDetectorReq Represents the parameter required for general card recognition plug-in. * @returns Promise<GeneralCardAnalyser> */ generalCardDetector(generalCardDetectorReq: generalCardDetectorReq): Promise<MLGcrCaptureResult>; /** * The form recognition service uses AI technologies to recognize and return form structure information (including rows, columns, and coordinates of cells) and form text in Chinese and English (including punctuation) from input images. * @param {formRecognizerAnalyserReq} formRecognizerAnalyserReq Represents the parameter required for general card recognition plug-in. * @returns Promise<GeneralCardAnalyser> */ formRecognitionAnalyser(formRecognizerAnalyserReq: formRecognizerAnalyserReq): Promise<MLGcrCaptureResult>; } export declare class HMSVoiceServiceProvider extends IonicNativePlugin { MLFaceSetting: typeof MLFaceSetting; MLLocalTextSetting: typeof MLLocalTextSetting; MLTextConfig: typeof MLTextConfig; MLRemoteTextSetting: typeof MLRemoteTextSetting; MLImageClassificationConfig: typeof MLImageClassificationConfig; MLImageSegmentationSetting: typeof MLImageSegmentationSetting; MLImageSegmentationScene: typeof MLImageSegmentationScene; MLRemoteLandmarkSetting: typeof MLRemoteLandmarkSetting; MLBcrCaptureConfig: typeof MLBcrCaptureConfig; MLGcrCaptureUIConfig: typeof MLGcrCaptureUIConfig; MLBcrResultConfig: typeof MLBcrResultConfig; HandkeyPointConfig: typeof HandkeyPointConfig; ImgSuperResolutionConfig: typeof ImgSuperResolutionConfig; MlObjectAnalyserConfig: typeof MlObjectAnalyserConfig; DownloadStrategyCustom: typeof DownloadStrategyCustom; FEATURE: typeof FEATURE; LANGUAGE: typeof LANGUAGE; MLTtsConstants: typeof MLTtsConstants; Colors: typeof Colors; RectStyle: typeof RectStyle; MLSkeletonConfig: typeof MLSkeletonConfig; MLFlashMode: typeof MLFlashMode; MLLensType: typeof MLLensType; MLAnalyzerName: typeof MLAnalyzerName; MLFrame: typeof MLFrame; MLFormRecogitionConfig: typeof MLFormRecogitionConfig; MLFaceConfigs: typeof MLFaceConfigs; MLProductConfig: typeof MLProductConfig; MLLivenessConfig: typeof MLLivenessConfig; MLRttLanguages: typeof MLRttLanguages; MLRttScenes: typeof MLRttScenes; gcrCaptureType: typeof gcrCaptureType; syncType: typeof syncType; /** * Implements on-cloud text translation. * @param {remotetranslateReq} remotetranslateReq Represents the parameter required for translate. * @returns Promise<any> */ remoteTranslator(remotetranslateReq: remotetranslateReq): Promise<any>; /** * Implements on-cloud text translation. * @param {localtranslateReq} localtranslateReq Represents the parameter required for translate. * @returns Promise<any> */ localTranslator(localtranslateReq: localtranslateReq): Promise<any>; /** * Obtains all languages supported for local translation. * @param {localAllLangReq} localAllLangReq Represents the parameter required for translate. * @returns Promise<any> */ translatorLocalAllLang(localAllLangReq: localAllLangReq): Promise<any>; /** * Obtains all languages supported for on-cloud translation. * @param {remoteAllLangReq} remoteAllLangReq Represents the parameter required for translate. * @returns Promise<any> */ translatorRemoteAllLang(remoteAllLangReq: remoteAllLangReq): Promise<any>; /** * Detects languages on the cloud. * @param {remoteLangDetectionReq} remoteLangDetectionReq Represents the parameter required for lang detection. * @returns Promise<RemoteLangDetectionAnalyser> | Promise<langDetectionWithFirstDetect> */ remoteLangDetection(remoteLangDetectionReq: remoteLangDetectionReq): Promise<MLRemoteLangDetection | MLlangDetectionWithFirstDetect>; /** * Detects languages on local. * @param {localLangDetectionReq} localLangDetectionReq Represents the parameter required for lang detection. * @returns Promise<any> | Promise<any> */ localLangDetection(localLangDetectionReq: localLangDetectionReq): Promise<any>; /** * Download language model. * @param {downloadTranslateReq} downloadTranslateReq Represents the parameter required for download model. * @returns Promise<any> */ translatorDownloadModel(downloadTranslateReq: downloadTranslateReq): Promise<any>; /** * For delete language model. * @param {deleteTranslateReq} deleteTranslateReq Represents the parameter required for delete model. * @returns Promise<any> */ translatorDeleteModel(deleteTranslateReq: deleteTranslateReq): Promise<any>; /** * This method stop translator service. * @returns Promise<any> */ stopTranslatorService(): Promise<any>; /** * This method return RTT setting. * @returns Promise<any> */ getRTTSetting(): Promise<any>; /** * This method returns TTS setting. * @returns Promise<any> */ getTTSSetting(): Promise<any>; /** * This method returns AFT setting. * @returns Promise<any> */ getAFTSetting(): Promise<any>; /** * This method returns Lang Detection setting. * @returns Promise<any> */ getLangDetectionSetting(): Promise<any>; /** * This method stop lang detection service. * @returns Promise<any> */ stopLangDetectionService(): Promise<any>; /** * The sound detection service can detect sound events in online (real-time recording) mode. The detected sound events can help you perform subsequent actions. * @param {soundDectReq} soundDectReq Represents the parameter required for Sound Detection analyser. * @returns Promise<any> */ soundDectAnalyser(soundDectReq: soundDectReq): Promise<MLSoundDectResult>; /** * TTS can convert text information into audio output. Rich timbres, and volume and speed options are supported to produce more natural sounds. * @param {ttsReq} ttsReq Represents the parameter required for text to speech. * @returns Promise<TtsAnalyser> */ ttsAnalyser(ttsReq: ttsReq): Promise<MLTtsResult>; /** * TTS can convert text information into audio output offline. Rich timbres, and volume and speed options are supported to produce more natural sounds. * @param {ttsReq} ttsReq Represents the parameter required for text to speech. * @returns Promise<TtsAnalyser> */ ttsOfflineAnalyser(ttsReq: ttsReq): Promise<MLTtsResult>; /** * This service stop text to speech (TTS) service. * @returns Promise<any> */ ttsAnalyserStop(): Promise<any>; /** * This service pauses text to speech (TTS) analyser. * @returns Promise<any> */ ttsAnalyserPause(): Promise<any>; /** * This service continues text to speech (TTS) analyser. * @returns Promise<any> */ ttsAnalyserResume(): Promise<any>; /** * This service shutdown text to speech (TTS) analyser. * @returns Promise<any> */ ttsAnalysershutDown(): Promise<any>; /** * This method returns TTS Download setting. * @returns Promise<any> */ ttsAnalyserDownloadSetting(): Promise<any>; /** * This service close AFT analyser. * @returns Promise<any> */ aftAnalyserClose(): Promise<any>; /** * This service stop AFT analyser. * @returns Promise<any> */ asrAnalyserStop(): Promise<any>; /** * This service destroy AFT analyser. * @returns Promise<any> */ aftAnalyserDestroy(): Promise<any>; /** * This service pause AFT analyser. * @returns Promise<any> */ aftAnalyserPause(): Promise<any>; /** * This service destroy Sound Detection analyser. * @returns Promise<any> */ soundDectAnalyserDestroy(): Promise<any>; /** * The audio file transcription service can convert an audio file less than or equal to 60 seconds into a text file. Currently, Chinese and English are supported. * @param {aftReq} aftReq Represents the parameter required for aft analyser. * @returns Promise<AftAnalyser> */ aftAnalyser(aftReq: aftReq): Promise<MLAftResult>; /** * ASR can recognize speech not longer than 60s and convert the input speech into text in real time. * @param {asrReq} asrReq Represents the parameter required for asr analyser. * @param {any} success A callback function. It is called when function is executed successfully. It returns the results of text. * @param {any} error A callback function. It is called when function is failed. * @returns callback */ asrAnalyser(asrReq: asrReq): Observable<any>; /** * Real-time transcription enables your app to convert long speech (no longer than 5 hours) into text in real time. The generated text contains punctuation marks and timestamps. * @param {rttReq} rttReq Represents the parameter required for rtt analyser. * @param {any} success A callback function. It is called when function is executed successfully. It returns the results of text. * @param {any} error A callback function. It is called when function is failed. * @returns callback */ rttAnalyserStart(rttReq: rttReq): Observable<any>; /** * This method stop RTT analyser * @param {any} success A callback function. It is called when function is executed successfully. It returns the results of text. * @param {any} error A callback function. It is called when function is failed. * @returns callback */ rttAnalyserStop(): Observable<any>; }
the_stack
import { number as assertNumber } from './_assert'; import { Input, toBytes, wrapConstructorWithOpts, u32, Hash, HashXOF } from './utils.js'; import { Keccak, ShakeOpts } from './sha3.js'; // cSHAKE && KMAC (NIST SP800-185) function leftEncode(n: number): Uint8Array { const res = [n & 0xff]; n >>= 8; for (; n > 0; n >>= 8) res.unshift(n & 0xff); res.unshift(res.length); return new Uint8Array(res); } function rightEncode(n: number): Uint8Array { const res = [n & 0xff]; n >>= 8; for (; n > 0; n >>= 8) res.unshift(n & 0xff); res.push(res.length); return new Uint8Array(res); } function chooseLen(opts: ShakeOpts, outputLen: number): number { return opts.dkLen === undefined ? outputLen : opts.dkLen; } const toBytesOptional = (buf?: Input) => (buf !== undefined ? toBytes(buf) : new Uint8Array([])); // NOTE: second modulo is necessary since we don't need to add padding if current element takes whole block const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); export type cShakeOpts = ShakeOpts & { personalization?: Input; NISTfn?: Input }; // Personalization function cshakePers(hash: Keccak, opts: cShakeOpts = {}): Keccak { if (!opts || (!opts.personalization && !opts.NISTfn)) return hash; // Encode and pad inplace to avoid unneccesary memory copies/slices (so we don't need to zero them later) // bytepad(encode_string(N) || encode_string(S), 168) const blockLenBytes = leftEncode(hash.blockLen); const fn = toBytesOptional(opts.NISTfn); const fnLen = leftEncode(8 * fn.length); // length in bits const pers = toBytesOptional(opts.personalization); const persLen = leftEncode(8 * pers.length); // length in bits if (!fn.length && !pers.length) return hash; hash.suffix = 0x04; hash.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; hash.update(getPadding(totalLen, hash.blockLen)); return hash; } const gencShake = (suffix: number, blockLen: number, outputLen: number) => wrapConstructorWithOpts<Keccak, cShakeOpts>((opts: cShakeOpts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts) ); export const cshake128 = gencShake(0x1f, 168, 128 / 8); export const cshake256 = gencShake(0x1f, 136, 256 / 8); class KMAC extends Keccak implements HashXOF<KMAC> { constructor( blockLen: number, outputLen: number, enableXOF: boolean, key: Input, opts: cShakeOpts = {} ) { super(blockLen, 0x1f, outputLen, enableXOF); cshakePers(this, { NISTfn: 'KMAC', personalization: opts.personalization }); key = toBytes(key); // 1. newX = bytepad(encode_string(K), 168) || X || right_encode(L). const blockLenBytes = leftEncode(this.blockLen); const keyLen = leftEncode(8 * key.length); this.update(blockLenBytes).update(keyLen).update(key); const totalLen = blockLenBytes.length + keyLen.length + key.length; this.update(getPadding(totalLen, this.blockLen)); } protected finish() { if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits super.finish(); } _cloneInto(to?: KMAC): KMAC { // Create new instance without calling constructor since key already in state and we don't know it. // Force "to" to be instance of KMAC instead of Sha3. if (!to) { to = Object.create(Object.getPrototypeOf(this), {}) as KMAC; to.state = this.state.slice(); to.blockLen = this.blockLen; to.state32 = u32(to.state); } return super._cloneInto(to) as KMAC; } clone(): KMAC { return this._cloneInto(); } } function genKmac(blockLen: number, outputLen: number, xof = false) { const kmac = (key: Input, message: Input, opts?: cShakeOpts): Uint8Array => kmac.create(key, opts).update(message).digest(); kmac.create = (key: Input, opts: cShakeOpts = {}) => new KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); return kmac; } export const kmac128 = genKmac(168, 128 / 8); export const kmac256 = genKmac(136, 256 / 8); export const kmac128xof = genKmac(168, 128 / 8, true); export const kmac256xof = genKmac(136, 256 / 8, true); // TupleHash // Usage: tuple(['ab', 'cd']) != tuple(['a', 'bcd']) class TupleHash extends Keccak implements HashXOF<TupleHash> { constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts: cShakeOpts = {}) { super(blockLen, 0x1f, outputLen, enableXOF); cshakePers(this, { NISTfn: 'TupleHash', personalization: opts.personalization }); // Change update after cshake processed this.update = (data: Input) => { data = toBytes(data); super.update(leftEncode(data.length * 8)); super.update(data); return this; }; } protected finish() { if (!this.finished) super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits super.finish(); } _cloneInto(to?: TupleHash): TupleHash { to ||= new TupleHash(this.blockLen, this.outputLen, this.enableXOF); return super._cloneInto(to) as TupleHash; } clone(): TupleHash { return this._cloneInto(); } } function genTuple(blockLen: number, outputLen: number, xof = false) { const tuple = (messages: Input[], opts?: cShakeOpts): Uint8Array => { const h = tuple.create(opts); for (const msg of messages) h.update(msg); return h.digest(); }; tuple.create = (opts: cShakeOpts = {}) => new TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); return tuple; } export const tuplehash128 = genTuple(168, 128 / 8); export const tuplehash256 = genTuple(136, 256 / 8); export const tuplehash128xof = genTuple(168, 128 / 8, true); export const tuplehash256xof = genTuple(136, 256 / 8, true); // ParallelHash (same as K12/M14, but without speedup for inputs less 8kb, reduced number of rounds and more simple) type ParallelOpts = cShakeOpts & { blockLen?: number }; class ParallelHash extends Keccak implements HashXOF<ParallelHash> { private leafHash?: Hash<Keccak>; private chunkPos = 0; // Position of current block in chunk private chunksDone = 0; // How many chunks we already have private chunkLen: number; constructor( blockLen: number, outputLen: number, protected leafCons: () => Hash<Keccak>, enableXOF: boolean, opts: ParallelOpts = {} ) { super(blockLen, 0x1f, outputLen, enableXOF); cshakePers(this, { NISTfn: 'ParallelHash', personalization: opts.personalization }); let { blockLen: B } = opts; B ||= 8; assertNumber(B); this.chunkLen = B; super.update(leftEncode(B)); // Change update after cshake processed this.update = (data: Input) => { data = toBytes(data); const { chunkLen, leafCons } = this; for (let pos = 0, len = data.length; pos < len; ) { if (this.chunkPos == chunkLen || !this.leafHash) { if (this.leafHash) { super.update(this.leafHash.digest()); this.chunksDone++; } this.leafHash = leafCons(); this.chunkPos = 0; } const take = Math.min(chunkLen - this.chunkPos, len - pos); this.leafHash.update(data.subarray(pos, pos + take)); this.chunkPos += take; pos += take; } return this; }; } protected finish() { if (this.finished) return; if (this.leafHash) { super.update(this.leafHash.digest()); this.chunksDone++; } super.update(rightEncode(this.chunksDone)); super.update(rightEncode(this.enableXOF ? 0 : this.outputLen * 8)); // outputLen in bits super.finish(); } _cloneInto(to?: ParallelHash): ParallelHash { to ||= new ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); to.chunkPos = this.chunkPos; to.chunkLen = this.chunkLen; to.chunksDone = this.chunksDone; return super._cloneInto(to) as ParallelHash; } destroy() { super.destroy.call(this); if (this.leafHash) this.leafHash.destroy(); } clone(): ParallelHash { return this._cloneInto(); } } function genParallel( blockLen: number, outputLen: number, leaf: ReturnType<typeof gencShake>, xof = false ) { const parallel = (message: Input, opts?: ParallelOpts): Uint8Array => parallel.create(opts).update(message).digest(); parallel.create = (opts: ParallelOpts = {}) => new ParallelHash( blockLen, chooseLen(opts, outputLen), () => leaf.create({ dkLen: 2 * outputLen }), xof, opts ); return parallel; } export const parallelhash128 = genParallel(168, 128 / 8, cshake128); export const parallelhash256 = genParallel(136, 256 / 8, cshake256); export const parallelhash128xof = genParallel(168, 128 / 8, cshake128, true); export const parallelhash256xof = genParallel(136, 256 / 8, cshake256, true); // Kangaroo // Same as NIST rightEncode, but returns [0] for zero string function rightEncodeK12(n: number): Uint8Array { const res = []; for (; n > 0; n >>= 8) res.unshift(n & 0xff); res.push(res.length); return new Uint8Array(res); } export type KangarooOpts = { dkLen?: number; personalization?: Input }; const EMPTY = new Uint8Array([]); class KangarooTwelve extends Keccak implements HashXOF<KangarooTwelve> { readonly chunkLen = 8192; private leafHash?: Keccak; private personalization: Uint8Array; private chunkPos = 0; // Position of current block in chunk private chunksDone = 0; // How many chunks we already have constructor( blockLen: number, protected leafLen: number, outputLen: number, rounds: number, opts: KangarooOpts ) { super(blockLen, 0x07, outputLen, true, rounds); const { personalization } = opts; this.personalization = toBytesOptional(personalization); } update(data: Input) { data = toBytes(data); const { chunkLen, blockLen, leafLen, rounds } = this; for (let pos = 0, len = data.length; pos < len; ) { if (this.chunkPos == chunkLen) { if (this.leafHash) super.update(this.leafHash.digest()); else { this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() super.update(new Uint8Array([3, 0, 0, 0, 0, 0, 0, 0])); } this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); this.chunksDone++; this.chunkPos = 0; } const take = Math.min(chunkLen - this.chunkPos, len - pos); const chunk = data.subarray(pos, pos + take); if (this.leafHash) this.leafHash.update(chunk); else super.update(chunk); this.chunkPos += take; pos += take; } return this; } protected finish() { if (this.finished) return; const { personalization } = this; this.update(personalization).update(rightEncodeK12(personalization.length)); // Leaf hash if (this.leafHash) { super.update(this.leafHash.digest()); super.update(rightEncodeK12(this.chunksDone)); super.update(new Uint8Array([0xff, 0xff])); } super.finish.call(this); } destroy() { super.destroy.call(this); if (this.leafHash) this.leafHash.destroy(); // We cannot zero personalization buffer since it is user provided and we don't want to mutate user input this.personalization = EMPTY; } _cloneInto(to?: KangarooTwelve): KangarooTwelve { const { blockLen, leafLen, leafHash, outputLen, rounds } = this; to ||= new KangarooTwelve(blockLen, leafLen, outputLen, rounds, {}); super._cloneInto(to); if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); to.personalization.set(this.personalization); to.leafLen = this.leafLen; to.chunkPos = this.chunkPos; to.chunksDone = this.chunksDone; return to; } clone(): KangarooTwelve { return this._cloneInto(); } } // Default to 32 bytes, so it can be used without opts export const k12 = wrapConstructorWithOpts<KangarooTwelve, KangarooOpts>( (opts: KangarooOpts = {}) => new KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) ); // MarsupilamiFourteen export const m14 = wrapConstructorWithOpts<KangarooTwelve, KangarooOpts>( (opts: KangarooOpts = {}) => new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts) ); // https://keccak.team/files/CSF-0.1.pdf // + https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG class KeccakPRG extends Keccak { protected rate: number; constructor(capacity: number) { assertNumber(capacity); // Rho should be full bytes if (capacity < 0 || capacity > 1600 - 10 || (1600 - capacity - 2) % 8) throw new Error('KeccakPRG: Invalid capacity'); // blockLen = rho in bytes super((1600 - capacity - 2) / 8, 0, 0, true); this.rate = 1600 - capacity; this.posOut = Math.floor((this.rate + 7) / 8); } keccak() { // Duplex padding this.state[this.pos] ^= 0x01; this.state[this.blockLen] ^= 0x02; // Rho is full bytes super.keccak(); this.pos = 0; this.posOut = 0; } update(data: Input) { super.update(data); this.posOut = this.blockLen; return this; } feed(data: Input) { return this.update(data); } protected finish() {} digestInto(out: Uint8Array): Uint8Array { throw new Error('KeccakPRG: digest is not allowed, please use .fetch instead.'); } fetch(bytes: number): Uint8Array { return this.xof(bytes); } // Ensure irreversibility (even if state leaked previous outputs cannot be computed) forget() { if (this.rate < 1600 / 2 + 1) throw new Error('KeccakPRG: rate too low to use forget'); this.keccak(); for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; this.pos = this.blockLen; this.keccak(); this.posOut = this.blockLen; } _cloneInto(to?: KeccakPRG): KeccakPRG { const { rate } = this; to ||= new KeccakPRG(1600 - rate); super._cloneInto(to); to.rate = rate; return to; } clone(): KeccakPRG { return this._cloneInto(); } } export const keccakprg = (capacity = 254) => new KeccakPRG(capacity);
the_stack
import {EventEmitter} from 'events'; import * as util from 'util'; import {ProtractorBrowser} from './browser'; import {Config} from './config'; import {buildDriverProvider, DriverProvider} from './driverProviders'; import {Logger} from './logger'; import {Plugins} from './plugins'; import {protractor} from './ptor'; import {joinTestLogs, runFilenameOrFn_} from './util'; declare let global: any; declare let process: any; let logger = new Logger('runner'); /* * Runner is responsible for starting the execution of a test run and triggering * setup, teardown, managing config, etc through its various dependencies. * * The Protractor Runner is a node EventEmitter with the following events: * - testPass * - testFail * - testsDone * * @param {Object} config * @constructor */ export class Runner extends EventEmitter { config_: Config; preparer_: any; driverprovider_: DriverProvider; o: any; plugins_: Plugins; restartPromise: Promise<any>; frameworkUsesAfterEach: boolean; ready_?: Promise<void>; constructor(config: Config) { super(); this.config_ = config; if (config.v8Debug) { // Call this private function instead of sending SIGUSR1 because Windows. process['_debugProcess'](process.pid); } if (config.nodeDebug) { process['_debugProcess'](process.pid); const nodedebug = require('child_process').fork('debug', ['localhost:5858']); process.on('exit', () => { nodedebug.kill('SIGTERM'); }); nodedebug.on('exit', () => { process.exit(1); }); } if (config.capabilities && config.capabilities.seleniumAddress) { config.seleniumAddress = config.capabilities.seleniumAddress; } this.loadDriverProvider_(config); this.setTestPreparer(config.onPrepare); } /** * Registrar for testPreparers - executed right before tests run. * @public * @param {string/Fn} filenameOrFn */ setTestPreparer(filenameOrFn: string|Function): void { this.preparer_ = filenameOrFn; } /** * Executor of testPreparer * @public * @param {string[]=} An optional list of command line arguments the framework will accept. * @return {Promise} A promise that will resolve when the test preparers * are finished. */ runTestPreparer(extraFlags?: string[]): Promise<any> { let unknownFlags = this.config_.unknownFlags_ || []; if (extraFlags) { unknownFlags = unknownFlags.filter((f) => extraFlags.indexOf(f) === -1); } if (unknownFlags.length > 0 && !this.config_.disableChecks) { // TODO: Make this throw a ConfigError in Protractor 6. logger.warn( 'Ignoring unknown extra flags: ' + unknownFlags.join(', ') + '. This will be' + ' an error in future versions, please use --disableChecks flag to disable the ' + ' Protractor CLI flag checks. '); } return this.plugins_.onPrepare().then(() => { return runFilenameOrFn_(this.config_.configDir, this.preparer_); }); } /** * Called after each test finishes. * * Responsible for `restartBrowserBetweenTests` * * @public * @return {Promise} A promise that will resolve when the work here is done */ afterEach(): Promise<void> { let ret: Promise<void>; this.frameworkUsesAfterEach = true; if (this.config_.restartBrowserBetweenTests) { this.restartPromise = this.restartPromise || Promise.resolve(protractor.browser.restart()); ret = this.restartPromise; this.restartPromise = undefined; } return ret || Promise.resolve(); } /** * Grab driver provider based on type * @private * * Priority * 1) if directConnect is true, use that * 2) if seleniumAddress is given, use that * 3) if a Sauce Labs account is given, use that * 4) if a seleniumServerJar is specified, use that * 5) try to find the seleniumServerJar in protractor/selenium */ loadDriverProvider_(config: Config) { this.config_ = config; this.driverprovider_ = buildDriverProvider(this.config_); } /** * Responsible for cleaning up test run and exiting the process. * @private * @param {int} Standard unix exit code */ async exit_(exitCode: number): Promise<number> { const returned = await runFilenameOrFn_(this.config_.configDir, this.config_.onCleanUp, [exitCode]); if (typeof returned === 'number') { return returned; } else { return exitCode; } } /** * Getter for the Runner config object * @public * @return {Object} config */ getConfig(): Config { return this.config_; } /** * Sets up convenience globals for test specs * @private */ setupGlobals_(browser_: ProtractorBrowser) { // Keep $, $$, element, and by/By under the global protractor namespace protractor.browser = browser_; protractor.$ = browser_.$; protractor.$$ = browser_.$$; protractor.element = browser_.element; protractor.by = protractor.By = ProtractorBrowser.By; protractor.ExpectedConditions = browser_.ExpectedConditions; if (!this.config_.noGlobals) { // Export protractor to the global namespace to be used in tests. global.browser = browser_; global.$ = browser_.$; global.$$ = browser_.$$; global.element = browser_.element; global.by = global.By = protractor.By; global.ExpectedConditions = protractor.ExpectedConditions; } global.protractor = protractor; if (!this.config_.skipSourceMapSupport) { // Enable sourcemap support for stack traces. require('source-map-support').install(); } // Required by dart2js machinery. // https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/sdk/lib/js/dart2js/js_dart2js.dart?spec=svn32943&r=32943#487 global.DartObject = function(o: any) { this.o = o; }; } /** * Create a new driver from a driverProvider. Then set up a * new protractor instance using this driver. * This is used to set up the initial protractor instances and any * future ones. * * @param {Plugin} plugins The plugin functions * @param {ProtractorBrowser=} parentBrowser The browser which spawned this one * * @return {Protractor} a protractor instance. * @public */ async createBrowser(plugins: any, parentBrowser?: ProtractorBrowser): Promise<any> { let config = this.config_; let driver = await this.driverprovider_.getNewDriver(); let blockingProxyUrl: string; if (config.useBlockingProxy) { blockingProxyUrl = this.driverprovider_.getBPUrl(); } let initProperties = { baseUrl: config.baseUrl, rootElement: config.rootElement as string | Promise<string>, untrackOutstandingTimeouts: config.untrackOutstandingTimeouts, params: config.params, getPageTimeout: config.getPageTimeout, allScriptsTimeout: config.allScriptsTimeout, debuggerServerPort: config.debuggerServerPort, ng12Hybrid: config.ng12Hybrid, waitForAngularEnabled: true as boolean | Promise<boolean> }; if (parentBrowser) { initProperties.baseUrl = parentBrowser.baseUrl; initProperties.rootElement = parentBrowser.angularAppRoot(); initProperties.untrackOutstandingTimeouts = !parentBrowser.trackOutstandingTimeouts_; initProperties.params = parentBrowser.params; initProperties.getPageTimeout = parentBrowser.getPageTimeout; initProperties.allScriptsTimeout = parentBrowser.allScriptsTimeout; initProperties.debuggerServerPort = parentBrowser.debuggerServerPort; initProperties.ng12Hybrid = parentBrowser.ng12Hybrid; initProperties.waitForAngularEnabled = parentBrowser.waitForAngularEnabled(); } let browser_ = new ProtractorBrowser( driver, initProperties.baseUrl, initProperties.rootElement, initProperties.untrackOutstandingTimeouts, blockingProxyUrl); browser_.params = initProperties.params; browser_.plugins_ = plugins || new Plugins({}); if (initProperties.getPageTimeout) { browser_.getPageTimeout = initProperties.getPageTimeout; } if (initProperties.allScriptsTimeout) { browser_.allScriptsTimeout = initProperties.allScriptsTimeout; } if (initProperties.debuggerServerPort) { browser_.debuggerServerPort = initProperties.debuggerServerPort; } if (initProperties.ng12Hybrid) { browser_.ng12Hybrid = initProperties.ng12Hybrid; } await browser_.waitForAngularEnabled(initProperties.waitForAngularEnabled); // TODO(selenium4): Options does not have a setScriptTimeout method. await(driver.manage() as any).setTimeouts({script: initProperties.allScriptsTimeout || 0}); browser_.getProcessedConfig = () => { return Promise.resolve(config); }; browser_.forkNewDriverInstance = async( useSameUrl: boolean, copyMockModules: boolean, copyConfigUpdates = true): Promise<any> => { let newBrowser = await this.createBrowser(plugins); if (copyMockModules) { newBrowser.mockModules_ = browser_.mockModules_; } if (useSameUrl) { const currentUrl = await browser_.driver.getCurrentUrl(); await newBrowser.get(currentUrl); } return newBrowser; }; let replaceBrowser = async () => { let newBrowser = await browser_.forkNewDriverInstance(false, true); if (browser_ === protractor.browser) { this.setupGlobals_(newBrowser); } return newBrowser; }; browser_.restart = async () => { // Note: because tests are not paused at this point, any async // calls here are not guaranteed to complete before the tests resume. const restartedBrowser = await replaceBrowser(); await this.driverprovider_.quitDriver(browser_.driver); return restartedBrowser; }; return browser_; } /** * Final cleanup on exiting the runner. * * @return {Promise} A promise which resolves on finish. * @private */ shutdown_(): Promise<void> { return DriverProvider.quitDrivers( this.driverprovider_, this.driverprovider_.getExistingDrivers()); } /** * The primary workhorse interface. Kicks off the test running process. * * @return {Promise} A promise which resolves to the exit code of the tests. * @public */ async run(): Promise<number> { let testPassed: boolean; let plugins = this.plugins_ = new Plugins(this.config_); let pluginPostTestPromises: any; let browser_: any; let results: any; if (this.config_.framework !== 'explorer' && !this.config_.specs.length) { throw new Error('Spec patterns did not match any files.'); } if (this.config_.webDriverLogDir || this.config_.highlightDelay) { this.config_.useBlockingProxy = true; } // 1) Setup environment // noinspection JSValidateTypes await this.driverprovider_.setupEnv(); // 2) Create a browser and setup globals browser_ = await this.createBrowser(plugins); this.setupGlobals_(browser_); try { const session = await browser_.getSession(); logger.debug( 'WebDriver session successfully started with capabilities ' + util.inspect(session.getCapabilities())); } catch (err) { logger.error('Unable to start a WebDriver session.'); throw err; } // 3) Setup plugins await plugins.setup(); // 4) Execute test cases // Do the framework setup here so that jasmine and mocha globals are // available to the onPrepare function. let frameworkPath = ''; if (this.config_.framework === 'jasmine' || this.config_.framework === 'jasmine2') { frameworkPath = './frameworks/jasmine.js'; } else if (this.config_.framework === 'mocha') { frameworkPath = './frameworks/mocha.js'; } else if (this.config_.framework === 'debugprint') { // Private framework. Do not use. frameworkPath = './frameworks/debugprint.js'; } else if (this.config_.framework === 'explorer') { // Private framework. Do not use. frameworkPath = './frameworks/explorer.js'; } else if (this.config_.framework === 'custom') { if (!this.config_.frameworkPath) { throw new Error( 'When config.framework is custom, ' + 'config.frameworkPath is required.'); } frameworkPath = this.config_.frameworkPath; } else { throw new Error( 'config.framework (' + this.config_.framework + ') is not a valid framework.'); } if (this.config_.restartBrowserBetweenTests) { // TODO(sjelin): replace with warnings once `afterEach` support is required let restartDriver = async () => { if (!this.frameworkUsesAfterEach) { this.restartPromise = await browser_.restart(); } }; this.on('testPass', restartDriver); this.on('testFail', restartDriver); } // We need to save these promises to make sure they're run, but we // don't // want to delay starting the next test (because we can't, it's just // an event emitter). pluginPostTestPromises = []; this.on('testPass', (testInfo: any) => { pluginPostTestPromises.push(plugins.postTest(true, testInfo)); }); this.on('testFail', (testInfo: any) => { pluginPostTestPromises.push(plugins.postTest(false, testInfo)); }); logger.debug('Running with spec files ' + this.config_.specs); let testResults = await require(frameworkPath).run(this, this.config_.specs); // 5) Wait for postTest plugins to finish results = testResults; await Promise.all(pluginPostTestPromises); // 6) Teardown plugins await plugins.teardown(); // 7) Teardown results = joinTestLogs(results, plugins.getResults()); this.emit('testsDone', results); testPassed = results.failedCount === 0; if (this.driverprovider_.updateJob) { await this.driverprovider_.updateJob({'passed': testPassed}); } await this.driverprovider_.teardownEnv(); // 8) Let plugins do final cleanup await plugins.postResults(); // 9) Exit process const exitCode = testPassed ? 0 : 1; await this.shutdown_(); return this.exit_(exitCode); } }
the_stack
import { Vulcan } from '../../lib/vulcan-lib'; import { Posts } from '../../lib/collections/posts'; import Users from '../../lib/collections/users/collection'; import { createDummyMessage, createDummyConversation, createDummyPost, createDummyComment } from '../../testing/utils'; import { performSubscriptionAction } from '../../lib/collections/subscriptions/mutations'; import moment from 'moment'; import * as _ from 'underscore'; Vulcan.populateNotifications = async ({username, messageNotifications = 3, postNotifications = 3, commentNotifications = 3, replyNotifications = 3}: { username: string, messageNotifications?: number, postNotifications?: number, commentNotifications?: number, replyNotifications?: number }) => { const user = await Users.findOne({username}); if (!user) throw Error(`Can't find user with username: ${username}`) const randomUser = await Users.findOne({_id: {$ne: user._id}}); if (!randomUser) throw Error("No users available in database to populate notifications") if (messageNotifications > 0) { //eslint-disable-next-line no-console console.log("generating new messages...") const conversation = await createDummyConversation(randomUser, {participantIds: [randomUser._id, user._id]}); _.times(messageNotifications, () => createDummyMessage(randomUser, {conversationId: conversation._id})) } if (postNotifications > 0) { //eslint-disable-next-line no-console console.log("generating new posts...") try { await performSubscriptionAction('subscribe', Users, randomUser._id, user) } catch(err) { //eslint-disable-next-line no-console console.log("User already subscribed, continuing"); } _.times(postNotifications, () => createDummyPost(randomUser)) } if (commentNotifications > 0) { const post = await Posts.findOneArbitrary(); // Grab random post //eslint-disable-next-line no-console console.log("generating new comments...") try { await performSubscriptionAction('subscribe', Posts, post?._id, user) } catch(err) { //eslint-disable-next-line no-console console.log("User already subscribed, continuing"); } _.times(commentNotifications, () => createDummyComment(randomUser, {postId: post?._id})); } if (replyNotifications > 0) { const post = await Posts.findOneArbitrary(); //eslint-disable-next-line no-console console.log("generating new replies...") try { await performSubscriptionAction('subscribe', Users, randomUser._id, user); } catch(err) { //eslint-disable-next-line no-console console.log("User already subscribed, continuing"); } const comment: any = await createDummyComment(user, {postId: post?._id}); _.times(replyNotifications, () => createDummyComment(randomUser, {postId: post?._id, parentCommentId: comment._id})); } } let loremIpsumTokens = [ "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et" ]; function getLoremIpsumToken() { let index = Math.floor(Math.random() * loremIpsumTokens.length); return loremIpsumTokens[index]; } // Generate a given number of characters of lorem ipsum. function makeLoremIpsum(length: number) { let result: Array<string> = []; let lengthSoFar = 0; result.push("Lorem "); lengthSoFar = "Lorem ".length; while(lengthSoFar < length) { let token = getLoremIpsumToken()+" "; lengthSoFar += token.length; result.push(token) } return result.join("").substr(0,length); } // Create a given number of paragraphs of a given length (in characters) // of lorem ipsum, formatted like: // <p>Lorem ipsum dolor sit ame</p> // This is strictly for making big/slow posts for test purposes. function makeLoremIpsumBody(numParagraphs: number, paragraphLength: number) { let result: Array<string> = []; for(var ii=0; ii<numParagraphs; ii++) { result.push('<p>'); result.push(makeLoremIpsum(paragraphLength)); result.push('</p>'); } return result.join(""); } function makeStyledBody() { let result: Array<string> = []; result.push('<h1>Post Title</h1>') result.push('<p><a>Test Link</a> '); result.push(makeLoremIpsum(500)); result.push('</p>'); result.push('<p>'); result.push(makeLoremIpsum(200)); result.push('</p>'); result.push('<ul><li>Option 1</li><li>Option 2</li><li>Option 3</li></ul>'); result.push('<p>'); result.push(makeLoremIpsum(200)); result.push('</p>'); result.push('<blockquote><a>Test Link</a> '); result.push(makeLoremIpsum(300)); result.push('</blockquote>'); result.push('<blockquote>'); result.push(makeLoremIpsum(100)); result.push('</blockquote>'); result.push('<pre><code><a>Test Link</a> '); result.push(makeLoremIpsum(100)); result.push('</code></pre>'); result.push('<p>'); result.push(makeLoremIpsum(250)); result.push('</p>'); result.push('<blockquote><a>Test Link</a> '); result.push(makeLoremIpsum(300)); result.push('</blockquote>'); result.push('<p>'); result.push(makeLoremIpsum(250)); result.push('</p>'); result.push('<pre><code><a>Test Link</a> '); result.push(makeLoremIpsum(100)); result.push('</code></pre>'); result.push('<h2>Post Title</h2>') result.push('<p>'); result.push(makeLoremIpsum(200)); result.push('</p>'); return result.join(""); } Vulcan.createStyledPost = async () => { const user = await Users.findOneArbitrary(); // Create a post const post = await createDummyPost(user, { title: "Styled Post", slug: "styled-post", contents: { originalContents: { data: makeStyledBody(), type: "html" } }, frontpageDate: new Date(), curatedDate: new Date(), }) await createDummyComment(user, { postId: post._id, contents: { originalContents: { data: makeStyledBody(), type: "html" } }, }) } Vulcan.createStyledAFPost = async () => { const user = await Users.findOneArbitrary(); // Create a post const post = await createDummyPost(user, { title: "Styled Post", slug: "styled-post", contents: { originalContents: { data: makeStyledBody(), type: "html" } }, af: true, frontpageDate: new Date(), curatedDate: new Date(), }) await createDummyComment(user, { postId: post._id, contents: { originalContents: { data: makeStyledBody(), type: "html" } }, }) } Vulcan.createStyledQuestion = async () => { const user = await Users.findOneArbitrary(); // Create a post const post = await createDummyPost(user, { title: "Styled Post", slug: "styled-post", contents: { originalContents: { data: makeStyledBody(), type: "html" } }, question: true, frontpageDate: new Date(), curatedDate: new Date(), }) await createDummyComment(user, { postId: post._id, contents: { originalContents: { data: makeStyledBody(), type: "html" } }, }) } // Create a set of bulky test posts, used for checking for load time // problems. This is meant to be invoked from 'meteor shell'. It is // slow. Vulcan.createTestPostSet = async () => { //eslint-disable-next-line no-console console.log("Creating a set of bulky posts to test for load-time problems. This may take awhile..."); await Vulcan.createStyledPost() await Vulcan.createStyledAFPost() await Vulcan.createStyledQuestion() await Vulcan.createBulkyTestPost({ postTitle: "Test post with 100 flat comments", numRootComments: 100 }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with 1000 flat comments", numRootComments: 1000 }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with multiple 50-deep comments", numRootComments: 3, commentDepth: 50 }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with 1000-deep comments", numRootComments: 1, commentDepth: 1000 }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with a 500-paragraph long post body", postParagraphCount: 500, numRootComments: 1, }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with a 500-paragraph long comment body", commentParagraphCount: 500, numRootComments: 1, }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with a 100kb-long single paragraph body", postParagraphCount: 1, postParagraphLength: 100000, numRootComments: 1, }); await Vulcan.createBulkyTestPost({ postTitle: "Test post with a 100kb-long single comment body", commentParagraphCount: 1, commentParagraphLength: 100000, numRootComments: 1, }); //eslint-disable-next-line no-console console.log("Finished creating bulky test posts."); } // Create a single test post, which is bulky in one or more of a // number of different ways, controlled by arguments. Used for testing // for loading time problems. Vulcan.createTestPostSet() will invoke // this in different ways with pretty good coverage of the problems // it's capable uncovering. Vulcan.createBulkyTestPost = async ({ username = null, postTitle = "Test Post With Many Comments", postParagraphCount = 3, postParagraphLength = 1000, commentParagraphCount = 2, commentParagraphLength = 800, numRootComments = 100, commentDepth = 1, backDate = null}) => { var user; if(username) user = await Users.findOne({username}); else user = await Users.findOneArbitrary(); // Create a post const body = "<p>This is a programmatically generated test post.</p>" + makeLoremIpsumBody(postParagraphCount, postParagraphLength); let dummyPostFields: any = { title: postTitle, contents: { originalContents: { data: body, type: "html" } }, }; if (backDate) { dummyPostFields.createdAt = backDate; dummyPostFields.postedAt = backDate; } const post = await createDummyPost(user, dummyPostFields) // Create some comments for(var ii=0; ii<numRootComments; ii++) { //eslint-disable-next-line no-await-in-loop var rootComment = await createDummyComment(user, { postId: post._id, contents: { originalContents: { data: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength), type: "html" } }, }) // If commentDepth>1, create a series of replies-to-replies under the top-level replies var parentCommentId = rootComment._id for(var jj=0; jj<commentDepth-1; jj++) { var childComment = await createDummyComment(user, { postId: post._id, parentCommentId: parentCommentId, contents: { originalContents: { data: makeLoremIpsumBody(commentParagraphCount, commentParagraphLength), type: "html" } }, }); parentCommentId = childComment._id } } } // Create a set of test posts that are back-dated, one per hour for the past // ten days. Primarily for testing time-zone handling on /allPosts (in daily mode). Vulcan.createBackdatedPosts = async () => { //eslint-disable-next-line no-console console.log("Creating back-dated test post set"); for(let i=0; i<24*10; i++) { const backdateTime = moment().subtract(i, 'hours').toDate(); await Vulcan.createBulkyTestPost({ postTitle: "Test post backdated by "+i+" hours", numRootComments: 0, backDate: backdateTime, }); } //eslint-disable-next-line no-console console.log("Done"); }
the_stack
import { PdfTextAlignment, PdfVerticalAlignment, PdfTextDirection } from './../../graphics/enum'; import { PdfSubSuperScript, PdfWordWrapType } from './../../graphics/fonts/enum'; /** * `PdfStringFormat` class represents the text layout information on PDF. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set the text alignment * stringFormat.alignment = PdfTextAlignment.Center; * // set the vertical alignment * stringFormat.lineAlignment = PdfVerticalAlignment.Middle; * // * // draw the text * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ export class PdfStringFormat { // Fields /** * `Horizontal text alignment`. * @private */ private textAlignment : PdfTextAlignment; /** * `Vertical text alignment`. * @private */ private verticalAlignment : PdfVerticalAlignment; /** * Indicates whether `RTL` should be checked. * @private */ private isRightToLeft : boolean; /** * `Character spacing` value. * @private */ private internalCharacterSpacing : number; /** * `Word spacing` value. * @private */ private internalWordSpacing : number; /** * Text `leading`. * @private */ private leading : number; /** * Shows if the text should be a part of the current `clipping` path. * @private */ private clip : boolean; /** * Indicates whether the text is in `subscript or superscript` mode. * @private */ private pdfSubSuperScript : PdfSubSuperScript; /** * The `scaling factor` of the text being drawn. * @private */ private scalingFactor : number = 100.0; /** * Indent of the `first line` in the text. * @private */ private initialLineIndent : number; /** * Indent of the `first line` in the paragraph. * @private */ private internalParagraphIndent : number; /** * Indicates whether entire lines are laid out in the formatting rectangle only or not[`line limit`]. * @private */ private internalLineLimit : boolean; /** * Indicates whether spaces at the end of the line should be left or removed[`measure trailing spaces`]. * @private */ private trailingSpaces : boolean; /** * Indicates whether the text region should be `clipped` or not. * @private */ private isNoClip : boolean; /** * Indicates text `wrapping` type. * @private */ public wordWrapType : PdfWordWrapType = PdfWordWrapType.Word; private direction : PdfTextDirection ; //Constructors /** * Initializes a new instance of the `PdfStringFormat` class. * @private */ public constructor() /** * Initializes a new instance of the `PdfStringFormat` class with horizontal alignment of a text. * @private */ public constructor(alignment : PdfTextAlignment) /** * Initializes a new instance of the `PdfStringFormat` class with column format. * @private */ public constructor(columnFormat : string) /** * Initializes a new instance of the `PdfStringFormat` class with horizontal and vertical alignment. * @private */ public constructor(alignment : PdfTextAlignment, lineAlignment : PdfVerticalAlignment) public constructor(arg1? : PdfTextAlignment|string, arg2? : PdfVerticalAlignment) { this.internalLineLimit = true; this.wordWrapType = PdfWordWrapType.Word; if ((typeof arg1 !== 'undefined') && (typeof arg1 !== 'string') ) { this.textAlignment = arg1; } if (typeof arg2 !== 'undefined') { this.verticalAlignment = arg2; } } //Properties /** * Gets or sets the `horizontal` text alignment * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set the text alignment * stringFormat.alignment = PdfTextAlignment.Center; * // * // draw the text * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get alignment() : PdfTextAlignment { return this.textAlignment; } public set alignment(value : PdfTextAlignment) { this.textAlignment = value; } public get textDirection() : PdfTextDirection { return this.direction; } public set textDirection(value : PdfTextDirection) { this.direction = value; } /** * Gets or sets the `vertical` text alignment. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set the vertical alignment * stringFormat.lineAlignment = PdfVerticalAlignment.Middle; * // * // draw the text * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get lineAlignment() : PdfVerticalAlignment { if (typeof this.verticalAlignment === 'undefined' || this.verticalAlignment == null) { return PdfVerticalAlignment.Top; } else { return this.verticalAlignment; } } public set lineAlignment(value : PdfVerticalAlignment) { this.verticalAlignment = value; } /** * Gets or sets the value that indicates text `direction` mode. * @private */ public get rightToLeft() : boolean { if (typeof this.isRightToLeft === 'undefined' || this.isRightToLeft == null) { return false; } else { return this.isRightToLeft; } } public set rightToLeft(value : boolean) { this.isRightToLeft = value; } /** * Gets or sets value that indicates a `size` among the characters in the text. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set character spacing * stringFormat.characterSpacing = 10; * // * // draw the text * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get characterSpacing() : number { if (typeof this.internalCharacterSpacing === 'undefined' || this.internalCharacterSpacing == null) { return 0; } else { return this.internalCharacterSpacing; } } public set characterSpacing(value : number) { this.internalCharacterSpacing = value; } /** * Gets or sets value that indicates a `size` among the words in the text. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set word spacing * stringFormat.wordSpacing = 10; * // * // draw the text * page1.graphics.drawString('Hello World', font, blackBrush, new PointF(10, 10), stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get wordSpacing() : number { if (typeof this.internalWordSpacing === 'undefined' || this.internalWordSpacing == null) { return 0; } else { return this.internalWordSpacing; } } public set wordSpacing(value : number) { this.internalWordSpacing = value; } /** * Gets or sets value that indicates the `vertical distance` between the baselines of adjacent lines of text. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // add a pages to the document * let page1 : PdfPage = document.pages.add(); * // set font * let font : PdfStandardFont = new PdfStandardFont(PdfFontFamily.Helvetica, 20); * // set brush * let blackBrush : PdfSolidBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); * // set string * let text : string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor * incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitati'; * // set rectangle bounds * let rectangle : RectangleF = new RectangleF({x : 0, y : 0}, {width : 300, height : 100}) * // * // set the format for string * let stringFormat : PdfStringFormat = new PdfStringFormat(); * // set line spacing * stringFormat.lineSpacing = 10; * // * // draw the text * page1.graphics.drawString(text, font, blackBrush, rectangle, stringFormat); * // save the document * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get lineSpacing() : number { if (typeof this.leading === 'undefined' || this.leading == null) { return 0; } else { return this.leading; } } public set lineSpacing(value : number) { this.leading = value; } /** * Gets or sets a value indicating whether the text is `clipped` or not. * @private */ public get clipPath() : boolean { if (typeof this.clip === 'undefined' || this.clip == null) { return false; } else { return this.clip; } } public set clipPath(value : boolean) { this.clip = value; } /** * Gets or sets value indicating whether the text is in `subscript or superscript` mode. * @private */ public get subSuperScript() : PdfSubSuperScript { if (typeof this.pdfSubSuperScript === 'undefined' || this.pdfSubSuperScript == null) { return PdfSubSuperScript.None; } else { return this.pdfSubSuperScript; } } public set subSuperScript(value : PdfSubSuperScript) { this.pdfSubSuperScript = value; } /** * Gets or sets the `indent` of the first line in the paragraph. * @private */ public get paragraphIndent() : number { if (typeof this.internalParagraphIndent === 'undefined' || this.internalParagraphIndent == null) { return 0; } else { return this.internalParagraphIndent; } } public set paragraphIndent(value : number) { this.internalParagraphIndent = value; this.firstLineIndent = value; } /** * Gets or sets a value indicating whether [`line limit`]. * @private */ public get lineLimit() : boolean { return this.internalLineLimit; } public set lineLimit(value : boolean) { this.internalLineLimit = value; } /** * Gets or sets a value indicating whether [`measure trailing spaces`]. * @private */ public get measureTrailingSpaces() : boolean { if (typeof this.trailingSpaces === 'undefined' || this.trailingSpaces == null) { return false; } else { return this.trailingSpaces; } } public set measureTrailingSpaces(value : boolean) { this.trailingSpaces = value; } /** * Gets or sets a value indicating whether [`no clip`]. * @private */ public get noClip() : boolean { if (typeof this.isNoClip === 'undefined' || this.isNoClip == null) { return false; } else { return this.isNoClip; } } public set noClip(value : boolean) { this.isNoClip = value; } /** * Gets or sets value indicating type of the text `wrapping`. * @private */ public get wordWrap() : PdfWordWrapType { // if (typeof this.wrapType === 'undefined' || this.wrapType == null) { // return PdfWordWrapType.Word; // } else { return this.wordWrapType; // } } public set wordWrap(value : PdfWordWrapType) { this.wordWrapType = value; } /** * Gets or sets the `scaling factor`. * @private */ public get horizontalScalingFactor() : number { // if (typeof this.scalingFactor === 'undefined' || this.scalingFactor == null) { // return 100; // } else { return this.scalingFactor; // } } public set horizontalScalingFactor(value : number) { if (value <= 0) { throw new Error('ArgumentOutOfRangeException:The scaling factor cant be less of equal to zero, ScalingFactor'); } this.scalingFactor = value; } /** * Gets or sets the `indent` of the first line in the text. * @private */ public get firstLineIndent() : number { if (typeof this.initialLineIndent === 'undefined' || this.initialLineIndent == null) { return 0; } else { return this.initialLineIndent; } } public set firstLineIndent(value : number) { this.initialLineIndent = value; } /** * `Clones` the object. * @private */ //IClonable implementation public clone() : Object { let format : PdfStringFormat = this; return format; } }
the_stack
import * as React from 'react'; import * as ReactDom from 'react-dom'; import { Version, DisplayMode } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneDropdown, PropertyPaneChoiceGroup, PropertyPaneCheckbox, PropertyPaneTextField } from '@microsoft/sp-webpart-base'; //import { SPComponentLoader } from '@microsoft/sp-loader'; import * as strings from 'PageSectionsNavigationStrings'; import { PageSectionsNavigation, IPageSectionsNavigationProps } from './components/PageSectionsNavigation'; import { IDynamicDataSource, IDynamicDataCallables, IDynamicDataPropertyDefinition } from '@microsoft/sp-dynamic-data'; import { IAnchorItem } from '../../common/model'; import { NavPosition, NavAlign, NavTheme } from '../../common/types'; export interface IPageSectionsNavigationWebPartProps { scrollBehavior: ScrollBehavior; position: NavPosition; isDark?: boolean; theme: NavTheme; align: NavAlign; showHomeItem: boolean; homeItemText: string; customCssUrl: string; } export default class PageSectionsNavigationWebPart extends BaseClientSideWebPart<IPageSectionsNavigationWebPartProps> implements IDynamicDataCallables { // "Anchor" data sources private _dataSources: IDynamicDataSource[] = []; protected onInit(): Promise<void> { const { customCssUrl } = this.properties; this._onAnchorChanged = this._onAnchorChanged.bind(this); this._availableSourcesChanged = this._availableSourcesChanged.bind(this); // getting data sources that have already been added on the page this._initDataSources(); // registering for changes in available datasources this.context.dynamicDataProvider.registerAvailableSourcesChanged(this._availableSourcesChanged); this._addCustomCss(customCssUrl); // registering current web part as a data source this.context.dynamicDataSourceManager.initializeSource(this); return super.onInit(); } public render(): void { const anchors = this._dataSources && this._dataSources.map(ds => ds.getPropertyValue('anchor') as IAnchorItem); const { scrollBehavior, position, isDark, theme, align, showHomeItem, homeItemText } = this.properties; const element: React.ReactElement<IPageSectionsNavigationProps> = React.createElement( PageSectionsNavigation, { anchors: anchors, scrollBehavior: scrollBehavior, position: position, theme: theme ? theme : (isDark ? 'dark' : 'light'), align: align, isEditMode: this.displayMode === DisplayMode.Edit, homeItem: showHomeItem ? homeItemText : '' } ); ReactDom.render(element, this.domElement); } /** * implementation of getPropertyDefinitions from IDynamicDataCallables */ public getPropertyDefinitions(): ReadonlyArray<IDynamicDataPropertyDefinition> { return [{ id: 'position', title: 'position' }]; } /** * implementation of getPropertyValue from IDynamicDataCallables * @param propertyId property Id */ public getPropertyValue(propertyId: string): NavPosition { switch (propertyId) { case 'position': return this.properties.position; } throw new Error('Bad property id'); } protected onDispose(): void { this.context.dynamicDataProvider.unregisterAvailableSourcesChanged(this._availableSourcesChanged); if (this._dataSources) { this._dataSources.forEach(ds => { this.context.dynamicDataProvider.unregisterPropertyChanged(ds.id, 'anchor', this._onAnchorChanged); }); delete this._dataSources; } ReactDom.unmountComponentAtNode(this.domElement); super.onDispose(); } protected get dataVersion(): Version { return Version.parse('1.0'); } /** * Manual handling of changed properties. * If position has been changed we need to notify subscribers * If custom css has been changed we need to add new CSS to the page * @param propertyPath * @param oldValue * @param newValue */ protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any) { if (propertyPath === 'position') { this.context.dynamicDataSourceManager.notifyPropertyChanged('position'); } else if (propertyPath === 'customCssUrl') { // // removing prev css // if (oldValue) { const oldCssLink = this._getCssLink(oldValue); if (oldCssLink) { oldCssLink.parentElement!.removeChild(oldCssLink); } } this._addCustomCss(newValue); } } protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { const align = this.properties.align || 'left'; const { scrollBehavior, position, theme, isDark, showHomeItem, homeItemText, customCssUrl } = this.properties; return { pages: [ { header: { description: '' }, groups: [ { groupName: strings.NavGroupName, groupFields: [ PropertyPaneDropdown('scrollBehavior', { label: strings.ScrollBehaviorFieldLabel, options: [{ key: 'auto', text: strings.AutoScrollBehavior }, { key: 'smooth', text: strings.SmoothScrollBehavior }], selectedKey: scrollBehavior || 'auto' }), PropertyPaneDropdown('position', { label: strings.PositionLabel, options: [{ key: 'section', text: strings.PositionSection }, { key: 'top', text: strings.PositionTop }], selectedKey: position || 'top' }), PropertyPaneDropdown('theme', { label: strings.ThemeLabel, options: [{ key: 'light', text: strings.ThemeLight }, { key: 'theme', text: strings.ThemeTheme }, { key: 'dark', text: strings.ThemeDark }], selectedKey: theme ? theme : isDark ? 'dark' : 'light' }), PropertyPaneChoiceGroup('align', { label: strings.AlignLabel, options: [{ key: 'flex-start', text: strings.AlignLeft, checked: align === 'flex-start', iconProps: { officeFabricIconFontName: 'AlignLeft' } }, { key: 'center', text: strings.AlignCenter, checked: align === 'center', iconProps: { officeFabricIconFontName: 'AlignCenter' } }, { key: 'flex-end', text: strings.AlignRight, checked: align === 'flex-end', iconProps: { officeFabricIconFontName: 'AlignRight' } }] }), PropertyPaneCheckbox('showHomeItem', { text: strings.HomeNavItemCbxLabel, checked: showHomeItem }), PropertyPaneTextField('homeItemText', { label: strings.HomeNavItemTextLabel, value: homeItemText || strings.HomeNavItemDefaultText }), PropertyPaneTextField('customCssUrl', { label: strings.CustomCSSLabel, value: customCssUrl }) ] } ] } ] }; } private _availableSourcesChanged() { this._initDataSources(true); } /** * Initializes collection of "Anchor" data soures based on collection of existing page's data sources * @param reRender specifies if the web part should be rerendered */ private _initDataSources(reRender?: boolean) { // all data sources on the page const availableDataSources = this.context.dynamicDataProvider.getAvailableSources(); if (availableDataSources && availableDataSources.length) { // "Ahchor" data sources cached in the web part from prev call const dataSources = this._dataSources; // // removing deleted data sources if any // const availableDataSourcesIds = availableDataSources.map(ds => ds.id); for (let i = 0, len = dataSources.length; i < len; i++) { let dataSource = dataSources[i]; if (availableDataSourcesIds.indexOf(dataSource.id) == -1) { dataSources.splice(i, 1); try { this.context.dynamicDataProvider.unregisterPropertyChanged(dataSource.id, 'anchor', this._onAnchorChanged); } catch (err) { } i--; len--; } } // // adding new data sources // for (let i = 0, len = availableDataSources.length; i < len; i++) { let dataSource = availableDataSources[i]; if (!dataSource.getPropertyDefinitions().filter(pd => pd.id === 'anchor').length) { continue; // we don't need data sources other than anchors } if (!dataSources || !dataSources.filter(ds => ds.id === dataSource.id).length) { dataSources.push(dataSource); this.context.dynamicDataProvider.registerPropertyChanged(dataSource.id, 'anchor', this._onAnchorChanged); } } } if (reRender) { this.render(); } } /** * Fired when any of anchors has been changed */ private _onAnchorChanged() { this.render(); } private _addCustomCss(customCssUrl: string) { if (customCssUrl) { //SPComponentLoader doesn't work on Comm Sites: https://github.com/SharePoint/sp-dev-docs/issues/3503 //SPComponentLoader.loadCss(this.properties.customCssUrl); const head = document.head; let styleEl = this._getCssLink(customCssUrl); if (!styleEl) { styleEl = document.createElement('link'); styleEl.setAttribute('rel', 'stylesheet'); styleEl.setAttribute('href', customCssUrl); head.appendChild(styleEl); } } } private _getCssLink(customCssUrl: string): Element | null { const head = document.head; return head.querySelector(`link[href="${customCssUrl}"]`); } }
the_stack
import * as ts from 'typescript' import { FieldDefinition, InterfaceWithFields, } from '@creditkarma/thrift-parser' import { IRenderState } from '../../../types' import { renderAnnotations, renderFieldAnnotations } from '../annotations' import { COMMON_IDENTIFIERS, THRIFT_IDENTIFIERS } from '../identifiers' import { createClassConstructor, createFunctionParameter, createNotNullCheck, hasRequiredField, } from '../utils' import { renderValue } from '../initializers' import { createVoidType, typeNodeForFieldType } from '../types' import { assignmentForField } from './reader' import { classNameForStruct, createSuperCall, extendsAbstract, implementsInterface, looseNameForStruct, throwForField, tokens, toolkitNameForStruct, } from './utils' export function renderClass( node: InterfaceWithFields, state: IRenderState, isExported: boolean, ): ts.ClassDeclaration { const fields: Array<ts.PropertyDeclaration> = [ ...createFieldsForStruct(node, state), renderAnnotations(node.annotations), renderFieldAnnotations(node.fields), ] if (state.options.withNameField) { const nameField: ts.PropertyDeclaration = ts.createProperty( undefined, [ ts.createToken(ts.SyntaxKind.PublicKeyword), ts.createToken(ts.SyntaxKind.ReadonlyKeyword), ], COMMON_IDENTIFIERS.__name, undefined, undefined, ts.createLiteral(node.name.value), ) fields.splice(-2, 0, nameField) } /** * After creating the properties on our class for the struct fields we must create * a constructor that knows how to assign these values based on a passed args. * * The constructor will take one arguments 'args'. This argument will be an object * of an interface matching the struct definition. This interface is built by another * function in src/render/interface * * The interface follows the naming convention of 'I<struct name>' * * If a required argument is not on the passed 'args' argument we need to throw on error. * Optional fields we must allow to be null or undefined. */ const fieldAssignments: Array<ts.IfStatement> = node.fields.map( (field: FieldDefinition) => { return createFieldAssignment(field, state) }, ) const argsParameter: ts.ParameterDeclaration = createArgsParameterForStruct( node, state, ) // Build the constructor body const ctor: ts.ConstructorDeclaration = createClassConstructor( [argsParameter], [createSuperCall(), ...fieldAssignments], ) // export class <node.name> { ... } return ts.createClassDeclaration( undefined, tokens(isExported), classNameForStruct(node, state).replace('__NAMESPACE__', ''), [], [extendsAbstract(), implementsInterface(node, state)], // heritage [ ...fields, ctor, createStaticReadMethod(node, state), createStaticWriteMethod(node, state), createWriteMethod(node, state), ], ) } export function createWriteMethod( node: InterfaceWithFields, state: IRenderState, ): ts.MethodDeclaration { return ts.createMethod( undefined, [ts.createToken(ts.SyntaxKind.PublicKeyword)], undefined, COMMON_IDENTIFIERS.write, undefined, undefined, [createOutputParameter()], createVoidType(), ts.createBlock( [ ts.createReturn( ts.createCall( ts.createPropertyAccess( ts.createIdentifier( toolkitNameForStruct(node, state), ), COMMON_IDENTIFIERS.encode, ), undefined, [COMMON_IDENTIFIERS.this, COMMON_IDENTIFIERS.output], ), ), ], true, ), ) } export function createStaticWriteMethod( node: InterfaceWithFields, state: IRenderState, ): ts.MethodDeclaration { return ts.createMethod( undefined, [ ts.createToken(ts.SyntaxKind.PublicKeyword), ts.createToken(ts.SyntaxKind.StaticKeyword), ], undefined, COMMON_IDENTIFIERS.write, undefined, undefined, [ createFunctionParameter( COMMON_IDENTIFIERS.args, ts.createTypeReferenceNode( ts.createIdentifier(looseNameForStruct(node, state)), undefined, ), ), createOutputParameter(), ], createVoidType(), ts.createBlock( [ ts.createReturn( ts.createCall( ts.createPropertyAccess( ts.createIdentifier( toolkitNameForStruct(node, state), ), COMMON_IDENTIFIERS.encode, ), undefined, [COMMON_IDENTIFIERS.args, COMMON_IDENTIFIERS.output], ), ), ], true, ), ) } export function createStaticReadMethod( node: InterfaceWithFields, state: IRenderState, ): ts.MethodDeclaration { return ts.createMethod( undefined, [ ts.createToken(ts.SyntaxKind.PublicKeyword), ts.createToken(ts.SyntaxKind.StaticKeyword), ], undefined, COMMON_IDENTIFIERS.read, undefined, undefined, [createInputParameter()], ts.createTypeReferenceNode( ts.createIdentifier(classNameForStruct(node, state)), undefined, ), ts.createBlock( [ ts.createReturn( ts.createNew( ts.createIdentifier(classNameForStruct(node, state)), undefined, [ ts.createCall( ts.createPropertyAccess( ts.createIdentifier( toolkitNameForStruct(node, state), ), COMMON_IDENTIFIERS.decode, ), undefined, [COMMON_IDENTIFIERS.input], ), ], ), ), ], true, ), ) } export function createOutputParameter(): ts.ParameterDeclaration { return createFunctionParameter( COMMON_IDENTIFIERS.output, // param name ts.createTypeReferenceNode(THRIFT_IDENTIFIERS.TProtocol, undefined), // param type ) } export function createInputParameter(): ts.ParameterDeclaration { return createFunctionParameter( COMMON_IDENTIFIERS.input, // param name ts.createTypeReferenceNode(THRIFT_IDENTIFIERS.TProtocol, undefined), // param type ) } export function createFieldsForStruct( node: InterfaceWithFields, state: IRenderState, ): Array<ts.PropertyDeclaration> { return node.fields.map((field: FieldDefinition) => { return renderFieldDeclarations(field, state, true) }) } /** * Render properties for struct class based on values thrift file * * EXAMPLE: * * // thrift * stuct MyStruct { * 1: required i32 id, * 2: optional bool field1, * } * * // typescript * export class MyStruct { * public id: number = null; * public field1?: boolean = null; * * ... * } */ export function renderFieldDeclarations( field: FieldDefinition, state: IRenderState, withDefaults: boolean, ): ts.PropertyDeclaration { const defaultValue: ts.Expression | undefined = withDefaults && field.defaultValue !== null ? renderValue(field.fieldType, field.defaultValue, state) : undefined return ts.createProperty( undefined, [ts.createToken(ts.SyntaxKind.PublicKeyword)], ts.createIdentifier(field.name.value), field.requiredness === 'required' ? undefined : ts.createToken(ts.SyntaxKind.QuestionToken), typeNodeForFieldType(field.fieldType, state), defaultValue, ) } /** * Assign field if contained in args: * * if (args && args.<field.name> != null) { * this.<field.name> = args.<field.name> * } * * If field is required throw an error: * * else { * throw new Thrift.TProtocolException(Thrift.TProtocolExceptionType.UNKNOWN, 'Required field {{fieldName}} is unset!') * } */ export function createFieldAssignment( field: FieldDefinition, state: IRenderState, ): ts.IfStatement { const hasValue: ts.BinaryExpression = createNotNullCheck( ts.createPropertyAccess(COMMON_IDENTIFIERS.args, `${field.name.value}`), ) const thenAssign: Array<ts.Statement> = assignmentForField(field, state) const elseThrow: ts.Statement | undefined = throwForField(field) return ts.createIf( hasValue, ts.createBlock([...thenAssign], true), elseThrow === undefined ? undefined : ts.createBlock([elseThrow], true), ) } function createDefaultInitializer( node: InterfaceWithFields, ): ts.Expression | undefined { if (hasRequiredField(node)) { return undefined } else { return ts.createObjectLiteral([]) } } export function createArgsParameterForStruct( node: InterfaceWithFields, state: IRenderState, ): ts.ParameterDeclaration { return createFunctionParameter( COMMON_IDENTIFIERS.args, // param name createArgsTypeForStruct(node, state), // param type createDefaultInitializer(node), ) } function createArgsTypeForStruct( node: InterfaceWithFields, state: IRenderState, ): ts.TypeNode { // return ts.createTypeLiteralNode( // node.fields.map((field: FieldDefinition): ts.TypeElement => { // return ts.createPropertySignature( // undefined, // field.name.value, // renderOptional(field.requiredness), // typeNodeForFieldType(field.fieldType, identifiers, true), // undefined, // ) // }) // ) return ts.createTypeReferenceNode( ts.createIdentifier(looseNameForStruct(node, state)), undefined, ) }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [kafka](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmanagedstreamingforapachekafka.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Kafka extends PolicyStatement { public servicePrefix = 'kafka'; /** * Statement provider for service [kafka](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonmanagedstreamingforapachekafka.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to associate one or more Scram Secrets with an Amazon MSK cluster * * Access Level: Write * * Dependent actions: * - kms:CreateGrant * - kms:RetireGrant * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-scram-secrets.html#BatchAssociateScramSecret */ public toBatchAssociateScramSecret() { return this.to('BatchAssociateScramSecret'); } /** * Grants permission to disassociate one or more Scram Secrets from an Amazon MSK cluster * * Access Level: Write * * Dependent actions: * - kms:RetireGrant * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-scram-secrets.html#BatchDisassociateScramSecret */ public toBatchDisassociateScramSecret() { return this.to('BatchDisassociateScramSecret'); } /** * Grants permission to create an MSK cluster * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:DescribeSecurityGroups * - ec2:DescribeSubnets * - ec2:DescribeVpcs * - iam:AttachRolePolicy * - iam:CreateServiceLinkedRole * - iam:PutRolePolicy * - kms:CreateGrant * - kms:DescribeKey * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters.html#CreateCluster */ public toCreateCluster() { return this.to('CreateCluster'); } /** * Grants permission to create an MSK configuration * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations.html#CreateConfiguration */ public toCreateConfiguration() { return this.to('CreateConfiguration'); } /** * Grants permission to delete an MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn.html#DeleteCluster */ public toDeleteCluster() { return this.to('DeleteCluster'); } /** * Grants permission to delete the specified MSK configuration * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations-arn.html#DeleteConfiguration */ public toDeleteConfiguration() { return this.to('DeleteConfiguration'); } /** * Grants permission to describe an MSK cluster * * Access Level: Read * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn.html#DescribeCluster */ public toDescribeCluster() { return this.to('DescribeCluster'); } /** * Grants permission to describe the cluster operation that is specified by the given ARN * * Access Level: Read * * https://docs.aws.amazon.com/msk/1.0/apireference/operations-clusteroperationarn.html#DescribeClusterOperation */ public toDescribeClusterOperation() { return this.to('DescribeClusterOperation'); } /** * Grants permission to describe an MSK configuration * * Access Level: Read * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations-configurationarn.html#DescribeConfiguration */ public toDescribeConfiguration() { return this.to('DescribeConfiguration'); } /** * Grants permission to describe an MSK configuration revision * * Access Level: Read * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations-configurationarn-revision.html#DescribeConfigurationRevision */ public toDescribeConfigurationRevision() { return this.to('DescribeConfigurationRevision'); } /** * Grants permission to get connection details for the brokers in an MSK cluster * * Access Level: Read * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-bootstrap-brokers.html#GetBootstrapBrokers */ public toGetBootstrapBrokers() { return this.to('GetBootstrapBrokers'); } /** * Grants permission to get a list of the Apache Kafka versions to which you can update an MSK cluster * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/compatible-kafka-versions.html#GetCompatibleKafkaVersions */ public toGetCompatibleKafkaVersions() { return this.to('GetCompatibleKafkaVersions'); } /** * Grants permission to return a list of all the operations that have been performed on the specified MSK cluster * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-operations.html#ListClusterOperations */ public toListClusterOperations() { return this.to('ListClusterOperations'); } /** * Grants permission to list all MSK clusters in this account * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters.html#ListClusters */ public toListClusters() { return this.to('ListClusters'); } /** * Grants permission to list all revisions for an MSK configuration in this account * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations-arn-revisions.html#ListConfigurationRevisions */ public toListConfigurationRevisions() { return this.to('ListConfigurationRevisions'); } /** * Grants permission to list all MSK configurations in this account * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations.html#CreateConfiguration */ public toListConfigurations() { return this.to('ListConfigurations'); } /** * Grants permission to list all Apache Kafka versions supported by Amazon MSK * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/kafka-versions.html#ListKafkaVersions */ public toListKafkaVersions() { return this.to('ListKafkaVersions'); } /** * Grants permission to list brokers in an MSK cluster * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-nodes.html#ListNodes */ public toListNodes() { return this.to('ListNodes'); } /** * Grants permission to list the Scram Secrets associated with an Amazon MSK cluster * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-scram-secrets.html#ListScramSecrets */ public toListScramSecrets() { return this.to('ListScramSecrets'); } /** * Grants permission to list tags of an MSK resource * * Access Level: List * * https://docs.aws.amazon.com/msk/1.0/apireference/tags-resourcearn.html#ListTagsForResource */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to reboot broker * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-reboot-broker.html#RebootBroker */ public toRebootBroker() { return this.to('RebootBroker'); } /** * Grants permission to tag an MSK resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/msk/1.0/apireference/tags-resourcearn.html#TagResource */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from an MSK resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/msk/1.0/apireference/tags-resourcearn.html#UntagResource */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the number of brokers of the MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-nodes-count.html#UpdateBrokerCount */ public toUpdateBrokerCount() { return this.to('UpdateBrokerCount'); } /** * Grants permission to update the storage size of the brokers of the MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-nodes-storage.html#UpdateBrokerStorage */ public toUpdateBrokerStorage() { return this.to('UpdateBrokerStorage'); } /** * Grants permission to update the broker type of an Amazon MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-nodes-type.html#UpdateBrokerType */ public toUpdateBrokerType() { return this.to('UpdateBrokerType'); } /** * Grants permission to update the configuration of the MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-configuration.html#UpdateClusterConfiguration */ public toUpdateClusterConfiguration() { return this.to('UpdateClusterConfiguration'); } /** * Grants permission to update the MSK cluster to the specified Apache Kafka version * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-version.html#UpdateClusterKafkaVersion */ public toUpdateClusterKafkaVersion() { return this.to('UpdateClusterKafkaVersion'); } /** * Grants permission to create a new revision of the MSK configuration * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/configurations-arn.html#updateconfiguration */ public toUpdateConfiguration() { return this.to('UpdateConfiguration'); } /** * Grants permission to update the monitoring settings for the MSK cluster * * Access Level: Write * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-monitoring.html#UpdateMonitoring */ public toUpdateMonitoring() { return this.to('UpdateMonitoring'); } /** * Grants permission to update the security settings for the MSK cluster * * Access Level: Write * * Dependent actions: * - kms:RetireGrant * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn-security.html#UpdateSecurity */ public toUpdateSecurity() { return this.to('UpdateSecurity'); } protected accessLevelList: AccessLevelList = { "Write": [ "BatchAssociateScramSecret", "BatchDisassociateScramSecret", "CreateCluster", "CreateConfiguration", "DeleteCluster", "DeleteConfiguration", "RebootBroker", "UpdateBrokerCount", "UpdateBrokerStorage", "UpdateBrokerType", "UpdateClusterConfiguration", "UpdateClusterKafkaVersion", "UpdateConfiguration", "UpdateMonitoring", "UpdateSecurity" ], "Read": [ "DescribeCluster", "DescribeClusterOperation", "DescribeConfiguration", "DescribeConfigurationRevision", "GetBootstrapBrokers" ], "List": [ "GetCompatibleKafkaVersions", "ListClusterOperations", "ListClusters", "ListConfigurationRevisions", "ListConfigurations", "ListKafkaVersions", "ListNodes", "ListScramSecrets", "ListTagsForResource" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type cluster to the statement * * https://docs.aws.amazon.com/msk/1.0/apireference/clusters-clusterarn.html * * @param clusterName - Identifier for the clusterName. * @param uUID - Identifier for the uUID. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onCluster(clusterName: string, uUID: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:kafka:${Region}:${Account}:cluster/${ClusterName}/${UUID}'; arn = arn.replace('${ClusterName}', clusterName); arn = arn.replace('${UUID}', uUID); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
'use strict'; import { remote } from 'electron'; import * as stdFs from 'fs'; import * as stdPath from 'path'; import { CHORD_DIR } from 'chord/preference/common/chord'; import { isEmptyObject } from 'chord/base/common/objects'; import { ok } from 'chord/base/common/assert'; import { sleep } from 'chord/base/common/time'; import { getRandom } from 'chord/base/node/random'; import { decodeHtml } from 'chord/base/browser/htmlContent'; import { decodeBase64 } from 'chord/base/node/crypto'; import { ORIGIN } from 'chord/music/common/origin'; import { NoLoginError, LoginTimeoutError } from 'chord/music/common/errors'; import { IAudio } from 'chord/music/api/audio'; import { ISong } from 'chord/music/api/song'; import { ILyric } from 'chord/music/api/lyric'; import { IAlbum } from 'chord/music/api/album'; import { IArtist } from 'chord/music/api/artist'; import { ICollection } from 'chord/music/api/collection'; import { IListOption } from 'chord/music/api/listOption'; import { TMusicItems } from 'chord/music/api/items'; import { IUserProfile, IAccount } from 'chord/music/api/user'; import { ESize, resizeImageUrl } from 'chord/music/common/size'; import { makeCookie, makeCookieJar } from 'chord/base/node/cookies'; import { querystringify } from 'chord/base/node/url'; import { request, htmlGet, IRequestOptions } from 'chord/base/node/_request'; import { makeSong, makeSongs, makeLyric, makeAlbum, makeAlbums, makeCollection, makeEmptyCollection, makeCollections, makeArtist, makeArtists, makeUserProfile, makeUserProfiles, } from 'chord/music/qq/parser'; import { getACSRFToken } from 'chord/music/qq/util'; import { getSecuritySign } from 'chord/music/qq/crypto'; import { AUDIO_FORMAT_MAP } from 'chord/music/qq/parser'; import { ARTIST_LIST_OPTIONS } from 'chord/music/qq/common'; const ALBUM_OPTION_NAME_MAP = { area: '地区', genre: '流派', type: '类别', year: '年代', company: '唱片公司', }; export class QQMusicApi { static readonly HEADERS = { 'accept-encoding': 'gzip, deflate', 'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,ja;q=0.6,zh-TW;q=0.5', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36', 'accept': '*/*', }; // static readonly AUDIO_URI = 'http://mobileoc.music.tc.qq.com/'; // static readonly AUDIO_URI = 'http://streamoc.music.tc.qq.com/'; // static readonly AUDIO_URI = 'http://223.111.154.151/amobile.music.tc.qq.com/'; // static readonly AUDIO_URI = 'http://dl.stream.qqmusic.qq.com/'; static readonly AUDIO_URI = 'http://isure.stream.qqmusic.qq.com/'; static readonly NODE_MAP = { // qqKey: 'https://c.y.qq.com/base/fcgi-bin/fcg_musicexpress.fcg', qqKey: 'https://c.y.qq.com/base/fcgi-bin/fcg_music_express_mobile3.fcg', audio: 'https://u.y.qq.com/cgi-bin/musicu.fcg', song: 'https://u.y.qq.com/cgi-bin/musicu.fcg', // lyric: 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_yqq.fcg', lyric: 'https://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg', album: 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_album_info_cp.fcg', artist: 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg', artistLikeCount: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_order_singer_getnum.fcg', artistSongs: 'https://c.y.qq.com/v8/fcg-bin/fcg_v8_singer_track_cp.fcg', artistAlbums: 'https://u.y.qq.com/cgi-bin/musicu.fcg', collection: 'https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg', collectionAddons: 'https://c.y.qq.com/3gmusic/fcgi-bin/3g_dir_order_uinlist', searchSongs: 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp', searchAlbums: 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp', searchCollections: 'https://c.y.qq.com/soso/fcgi-bin/client_music_search_songlist', songList: 'https://u.y.qq.com/cgi-bin/musicu.fcg', albumList: 'https://u.y.qq.com/cgi-bin/musicu.fcg', collectionList: 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg', artistList: 'https://u.y.qq.com/cgi-bin/musicu.fcg', collectionListOptions: 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_tag_conf.fcg', userProfile: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_get_profile_homepage.fcg', userFavoriteSongs: 'https://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg', userFavoriteAlbums: 'https://c.y.qq.com/fav/fcgi-bin/fcg_get_profile_order_asset.fcg', userFavoriteArtists: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_order_singer_getlist.fcg', userFavoriteCollections: 'https://c.y.qq.com/fav/fcgi-bin/fcg_get_profile_order_asset.fcg', userCreatedCollections: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_user_created_diss', userFollow: 'https://c.y.qq.com/rsc/fcgi-bin/friend_follow_or_listen_list.fcg', myCreatedCollections: 'https://c.y.qq.com/splcloud/fcgi-bin/songlist_list.fcg', userLikeSong: 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_music_add2songdir.fcg', userLikeArtist: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_order_singer_add.fcg', userLikeAlbum: 'https://c.y.qq.com/folder/fcgi-bin/fcg_qm_order_diss.fcg', userLikeCollection: 'https://c.y.qq.com/folder/fcgi-bin/fcg_qm_order_diss.fcg', userLikeUserProfile: 'https://c.y.qq.com/rsc/fcgi-bin/add_attention_status.fcg', userDislikeSong: 'https://c.y.qq.com/qzone/fcg-bin/fcg_music_delbatchsong.fcg', userDislikeArtist: 'https://c.y.qq.com/rsc/fcgi-bin/fcg_order_singer_del.fcg', userDislikeAlbum: 'https://c.y.qq.com/folder/fcgi-bin/fcg_qm_order_diss.fcg', userDislikeCollection: 'https://c.y.qq.com/folder/fcgi-bin/fcg_qm_order_diss.fcg', userDislikeUserProfile: 'https://c.y.qq.com/rsc/fcgi-bin/add_attention_status.fcg', recommendCollections: 'https://u.y.qq.com/cgi-bin/musicu.fcg', newSongs: 'https://u.y.qq.com/cgi-bin/musicu.fcg', newAlbums: 'https://u.y.qq.com/cgi-bin/musicu.fcg', newCollections: 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg', playLog: 'https://c.y.qq.com/tplcloud/fcgi-bin/fcg_reportlsting_web.fcg', }; private account: IAccount; private cookies: Object; // The cookies are for getting audio url. // They can be these cookies of a vip user. private cookiesForAudio: Object; private ip_index: number; private ips: Array<string>; constructor() { this.cookies = {}; this.ip_index = -1; this.ips = []; try { let cookiesForAudioPath = stdPath.join(CHORD_DIR, 'cookies-for-audio.json'); let cookiesForAudio = JSON.parse(stdFs.readFileSync(cookiesForAudioPath).toString()); this.cookiesForAudio = cookiesForAudio[ORIGIN.qq] || this.cookies; } catch { this.cookiesForAudio = this.cookies; } } private getACSRFToken(): string { return this.account ? getACSRFToken(this.account.cookies) : null; } public async request( method: string, url: string, params?: any, data?: any, referer?: string, cookies: Object = {}): Promise<any> { if (params) { url = url + '?' + querystringify(params); } referer = referer || 'https://y.qq.com'; let headers = { ...QQMusicApi.HEADERS, referer }; // Here, domains are different. Make a new CookieJar for a request. if (isEmptyObject(cookies)) { cookies = this.cookies; } let jar = makeCookieJar(); for (let k of Object.keys(cookies)) { let cookie = makeCookie(k, cookies[k]); jar.setCookie(cookie, url); } let options: IRequestOptions = { method, url, jar, headers: headers, body: data, gzip: true, }; let body: any = await request(options); return body.trim().startsWith('<') || body == '' ? body : JSON.parse(body); } public makeguid(): string { // return '0'; return Math.floor(Math.random() * 1000000000).toString(); } // Deprecated. Do not use it // This api has been blocked. public async qqKey2(guid: string, songMid: string, songMediaMid: string): Promise<string> { let params = { cid: '205361747', guid: guid, songmid: songMid, filename: 'M500' + songMediaMid + '.mp3', format: 'json', '_': Date.now(), }; let url = QQMusicApi.NODE_MAP.qqKey; let json = await this.request('GET', url, params); return json['data']['items'][0]['vkey']; } // Deprecated. Do not use it public async qqKey(guid: string, songMid: string, songMediaMid: string): Promise<string> { let data = JSON.stringify({ 'req': { 'module': 'vkey.GetVkeyServer', 'method': 'CgiGetVkey', 'param': { guid, 'songmid': [songMid], 'songtype': [0], 'uin': '0', 'loginflag': 1, 'platform': '20' } }, 'comm': { 'uin': 0, 'format': 'json', 'ct': 24, 'cv': 0 } }); let sign = getSecuritySign(data); let params = { g_tk: '5381', sign, loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq.json', needNewCode: '0', data, }; let url = QQMusicApi.NODE_MAP.qqKey; let json = await this.request('GET', url, params); return json.req.data.midurlinfo[0].vkey; } /** * Uin is important for get audio url */ private getUinForAudio(): string { let uin = this.cookiesForAudio['uin'] || (this.account && this.account.user && this.account.user.userOriginalId); return uin || ''; } // Deprecated private getAudioServerIP(): string { this.ip_index = (this.ip_index + 1) % this.ips.length; return this.ips[this.ip_index]; } // Deprecated private getAudioURI(): string { let ip = this.getAudioServerIP(); return 'http://' + ip + '/amobile.music.tc.qq.com/'; } // Deprecated public makeAudios(song: ISong, qqKey: string, guid: string): Array<IAudio> { if (!qqKey) return []; let uri = QQMusicApi.AUDIO_URI; return song.audios.filter(audio => !!AUDIO_FORMAT_MAP[`${audio.kbps || ''}${audio.format}`]) .map(audio => { audio.url = uri + AUDIO_FORMAT_MAP[`${audio.kbps || ''}${audio.format}`] + song.songMediaMid + '.' + audio.format + '?guid=' + guid + '&vkey=' + qqKey + '&uin=0' + '&fromtag=66'; return audio; }); } // Deprecated /** * Get available qq music server ips */ public async getIPs(): Promise<Array<string>> { let url = 'https://raw.githubusercontent.com/PeterDing/chord-data/master/qq-ip-checker/qq-ips.txt'; let cn = await htmlGet(url); let ips = (cn as any).split('\n').map(ip => ip.trim() || null).filter(ip => ip); return ips; } /** * Get audio url */ async getAudioUrl(songMid: string, songMediaMid: string, kbps: number, format: string): Promise<string> { let guid = this.makeguid(); let uin = this.getUinForAudio(); if (!(AUDIO_FORMAT_MAP[`${kbps || ''}${format}`])) { return null; } let filename = AUDIO_FORMAT_MAP[`${kbps || ''}${format}`] + songMediaMid + '.' + format; let data = JSON.stringify({ 'req_0': { 'module': 'vkey.GetVkeyServer', 'method': 'CgiGetVkey', 'param': { 'filename': [filename], guid, 'songmid': [songMid], 'songtype': [0], uin, 'loginflag': 1, 'platform': '20', } }, 'comm': { uin, 'format': 'json', 'ct': 19, 'cv': 0 } }); let sign = getSecuritySign(data); let params = { sign, g_tk: 5381, loginUin: '', hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8¬ice=0', platform: 'yqq.json', needNewCode: 0, data, }; let url = QQMusicApi.NODE_MAP.audio; let json = await this.request('GET', url, params, null, null, this.cookiesForAudio); let audioUri = json.req_0.data.midurlinfo[0].purl; if (audioUri) { return QQMusicApi.AUDIO_URI + audioUri; } else { return null; } } public async audios(songId: string, supKbps?: number): Promise<Array<IAudio>> { let song = await this.song(songId); let { songMid, songMediaMid } = song; let audios = song.audios; for (let audio of audios) { let { kbps, format } = audio; if (audio.kbps <= supKbps) { let audioUrl = await this.getAudioUrl(songMid, songMediaMid, kbps, format); if (audioUrl) { audio.url = audioUrl; break; } } } return audios; } public async song(songId: string, songMid?: string): Promise<ISong> { let data = { "comm": { "uin": 0, "format": "json", "inCharset": "utf-8", "outCharset": "utf-8", "notice": 0, "platform": "h5", "needNewCode": 1 }, "detail": { "module": "music.pf_song_detail_svr", "method": "get_song_detail", "param": { "song_id": songId ? parseInt(songId) : undefined, "song_mid": songMid || undefined, } }, // "simsongs": { // "module": "rcmusic.similarSongRadioServer", // "method": "get_simsongs", // "param": { // "songid": 307012 // } // }, // "gedan": { // "module": "music.mb_gedan_recommend_svr", // "method": "get_related_gedan", // "param": { // "sin": 0, // "last_id": 0, // "song_type": 1, // "song_id": 307012 // } // } }; let url = QQMusicApi.NODE_MAP.song; let json = await this.request('POST', url, null, JSON.stringify(data)); return makeSong(json['detail']['data']); } public async lyric(songId: string, songMid: string): Promise<ILyric> { let params = { '-': 'MusicJsonCallback_lrc', pcachetime: Date.now(), songmid: songMid, g_tk: 5381, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, }; let url = QQMusicApi.NODE_MAP.lyric; let referer = 'https://y.qq.com/portal/player.html'; let json = await this.request('GET', url, params, null, referer); let lyricInfo = decodeHtml(decodeBase64(json['lyric'])); let transInfo = decodeHtml(decodeBase64(json['trans'])); return makeLyric(songId, lyricInfo, transInfo); } public async album(albumId: string, albumMid?: string): Promise<IAlbum> { let params = { albumid: albumId || undefined, albummid: albumMid || undefined, uin: '0', format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: '0', platform: 'h5', needNewCode: '1', '_': Date.now(), }; let url = QQMusicApi.NODE_MAP.album; let json = await this.request('GET', url, params); return makeAlbum(json['data']); } public async artistLikeCount(artistMid: string): Promise<number> { let params = { loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', singermid: artistMid, utf8: '1', } let url = QQMusicApi.NODE_MAP.artistLikeCount; let json = await this.request('GET', url, params); return json.num; } public async artist(artistId: string, artistMid?: string): Promise<IArtist> { let params = { singerid: artistId || undefined, singermid: artistMid || undefined, uin: '0', format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: '0', platform: 'h5page', needNewCode: '1', order: 'listen', from: 'h5', num: 1, begin: 0, '_': Date.now(), }; let url = QQMusicApi.NODE_MAP.artist; let json = await this.request('GET', url, params); let artist = makeArtist(json['data']); let likeCount = await this.artistLikeCount(artist.artistMid); artist.likeCount = likeCount; return artist; } public async artistSongs(artistId: string, offset: number = 0, limit: number = 10): Promise<Array<ISong>> { let params = { singerid: artistId, uin: '0', format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: '0', platform: 'h5page', needNewCode: '1', order: 'listen', from: 'h5', num: limit, begin: offset, '_': Date.now(), }; let url = QQMusicApi.NODE_MAP.artistSongs; let json = await this.request('GET', url, params); return makeSongs(json['data']['list'].map(info => info['musicData'])); } /** * WARN: `artistMid` */ public async artistAlbums(artistMid: string, offset: number = 0, limit: number = 10): Promise<Array<IAlbum>> { let data = JSON.stringify({ "singerAlbum": { "method": "get_singer_album", "param": { "singermid": artistMid, "order": "time", "begin": offset, "num": limit, "exstatus": 1 }, "module": "music.web_singer_info_svr" } }); let params = { loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', data, }; let url = QQMusicApi.NODE_MAP.artistAlbums; let json = await this.request('GET', url, params); return makeAlbums(json['singerAlbum']['data']['list']); } public async collectionAddons(collectionId: string): Promise<any> { let params = { loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', cid: '322', nocompress: '1', disstid: collectionId, }; let url = QQMusicApi.NODE_MAP.collectionAddons; let referer = `https://y.qq.com/n/yqq/playlist/${collectionId}.html`; let json = await this.request('GET', url, params, null, referer); return json; } public async collection(collectionId: string, offset: number = 0, limit: number = 1000): Promise<ICollection> { let params = { uin: '0', format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: '0', platform: 'h5', needNewCode: '1', new_format: '1', pic: '500', disstid: collectionId, type: '1', json: '1', utf8: '1', onlysong: '0', picmid: '1', nosign: '1', song_begin: offset, song_num: limit, '_': Date.now(), }; let url = QQMusicApi.NODE_MAP.collection; let referer = 'https://y.qq.com/w/taoge.html?ADTAG=newyqq.taoge&id=' + collectionId; let json = await this.request('GET', url, params, null, referer); if (!json['cdlist'] || !json['cdlist'].length) { return makeEmptyCollection(collectionId); } let collection = makeCollection(json['cdlist'][0]); let addons = await this.collectionAddons(collection.collectionOriginalId); collection.userId = addons['diruin'] ? `qq|collection|${addons['diruin']}` : collection.userId; collection.likeCount = addons['totalnum']; return collection; } public async searchSongs(keyword: string, offset: number = 0, limit: number = 10): Promise<Array<ISong>> { let params = { remoteplace: 'txt.yqq.song', format: 'json', p: offset, n: limit, w: keyword, aggr: 1, cr: 1, lossless: 1, flag_qc: 1, new_json: 1, }; let url = QQMusicApi.NODE_MAP.searchSongs; let json = await this.request('GET', url, params); if (!json['data']) { return []; } return makeSongs(json['data']['song']['list']); } public async searchAlbums(keyword: string, offset: number = 0, limit: number = 10): Promise<Array<IAlbum>> { let params = { platform: 'yqq', ct: 24, qqmusic_ver: 1298, remoteplace: 'txt.yqq.album', format: 'json', p: offset, n: limit, w: keyword, lossless: 0, aggr: 0, sem: 10, t: 8, catZhida: 1, }; let url = QQMusicApi.NODE_MAP.searchAlbums; let json = await this.request('GET', url, params); if (!json['data']) { return []; } return makeAlbums(json['data']['album']['list']); } public async searchCollections(keyword: string, offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { let params = { remoteplace: 'txt.yqq.playlist', flag_qc: '0', page_no: offset, num_per_page: limit, query: keyword, loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', }; let url = QQMusicApi.NODE_MAP.searchCollections; let json = await this.request('GET', url, params); if (!json['data']) { return []; } return makeCollections(json['data']['list']); } /** * Get new songs * * languageId: * 1: 内地 * 2: 港台 * 3: 欧美 * 4: 日本 * 5: 韩国 */ public async songList(languageId: number = 1, offset: number = 0, limit: number = 10): Promise<Array<ISong>> { let params = { g_tk: 0, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, data: JSON.stringify({ comm: { ct: 24 }, new_song: { method: "GetNewSong", module: "QQMusic.MusichallServer", param: { type: languageId, } }, }), }; let url = QQMusicApi.NODE_MAP.songList; let json = await this.request('GET', url, params); return makeSongs(json['new_song']['data']['song_list']); } public async albumListOptions(): Promise<Array<IListOption>> { let params = { g_tk: 0, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, data: JSON.stringify({ comm: { ct: 24 }, albumlib: { param: { get_tags: 1, click_albumid: 0, year: -1, genre: -1, area: 1, sort: 2, type: -1, sin: 0, num: 1, company: -1 }, method: 'get_album_by_tags', module: 'music.web_album_library', }, }), }; let url = QQMusicApi.NODE_MAP.songList; let json = await this.request('GET', url, params); let tags = json['albumlib']['data']['tags']; let options = Object.keys(tags).map(key => ({ name: ALBUM_OPTION_NAME_MAP[key], type: key, items: tags[key].map(info => ({ id: info['id'], name: info['name'], })), })); let sortOption = { name: '排序', type: 'sort', items: [ { id: 2, name: '最新' }, { id: 5, name: '最热' }, ], }; options.push(sortOption); return options; } /** * sort: * 2: 最新 * 5: 最热 * * area: 地区 // 同 xiami 的语种 * genre: 流派 // 同 xiami 的曲风 * type: 类别 // album 类别 * year: 年代 * company: 唱片公司 */ public async albumList( sort: number = 5, areaId: number = 0, genreId: number = -1, typeId: number = -1, yearId: number = -1, companyId: number = -1, offset: number = 0, limit: number = 10): Promise<Array<IAlbum>> { let params = { g_tk: 0, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, data: JSON.stringify({ comm: { ct: 24 }, albumlib: { param: { get_tags: 0, click_albumid: 0, sort: sort, area: areaId, genre: genreId, type: typeId, year: yearId, company: companyId, sin: offset, num: limit, }, method: 'get_album_by_tags', module: 'music.web_album_library', }, }), }; let url = QQMusicApi.NODE_MAP.albumList; let json = await this.request('GET', url, params); return makeAlbums(json['albumlib']['data']['list']); } public collectionListOrders(): Array<{ name: string, id: string }> { return [ { id: '3', name: '最热' }, { id: '2', name: '最新' }, { id: '4', name: '评分' }, ]; } public async collectionListOptions(): Promise<Array<IListOption>> { let params = { g_tk: 0, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, }; let url = QQMusicApi.NODE_MAP.collectionListOptions; let json = await this.request('GET', url, params); let options = json['data']['categories'].map(info => ({ name: info['categoryGroupName'], type: 'category', items: info['items'].map(item => ({ id: item['categoryId'], name: item['categoryName'], })), })); return options; } /** * sort: * 2: 最新 * 3: 最热 * 4: 评分 * * categoryId sees this.collectionListOptions */ public async collectionList(sort: number | string = 3, categoryId: number | string = 10000000, offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { let params = { picmid: 1, rnd: getRandom(), g_tk: 0, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, categoryId: categoryId, sortId: sort, sin: offset, ein: limit, }; let url = QQMusicApi.NODE_MAP.collectionList; let json = await this.request('GET', url, params); return makeCollections(json['data']['list']); } public async artistListOptions(): Promise<Array<IListOption>> { return ARTIST_LIST_OPTIONS; } /** * Get artists by options * * return 80 artists, default * * @param offset is just offset * @param limit is page number */ public async artistList( area: string = '-100', genre: string = '-100', sex: string = '-100', index: string = '-100', offset: number = 0, limit: number = 1): Promise<Array<IArtist>> { let data = JSON.stringify({ comm: { ct: 24, cv: 0, }, singerList: { module: "Music.SingerListServer", method: "get_singer_list", param: { area: Number.parseInt(area), genre: Number.parseInt(genre), sex: Number.parseInt(sex), index: Number.parseInt(index), sin: offset, cur_page: 1, } } }); let params = { g_tk: 5381, loginUin: 0, hostUin: 0, format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: 0, platform: 'yqq.json', needNewCode: 0, data, }; let url = QQMusicApi.NODE_MAP.artistList; let json = await this.request('GET', url, params); return makeArtists(json['singerList']['data']['singerlist']); } public async newSongs(offset: number = 0, limit: number = 10): Promise<Array<ISong>> { let songLists = await Promise.all([ this.songList(1), this.songList(2), this.songList(3), this.songList(4), this.songList(5), ]); let songs = []; for (let i of Array(10).keys()) { for (let j of Array(5).keys()) { let song = songLists[j][i]; if (song) songs.push(song); } } return songs; } public async newAlbums(offset: number = 0, limit: number = 10): Promise<Array<IAlbum>> { let albumLists = await Promise.all([ this.albumList(2, 1, -1, -1, -1, -1, 0, 5), this.albumList(2, 0, -1, -1, -1, -1, 0, 5), this.albumList(2, 3, -1, -1, -1, -1, 0, 5), this.albumList(2, 15, -1, -1, -1, -1, 0, 5), this.albumList(2, 14, -1, -1, -1, -1, 0, 5), ]); let albums = []; for (let i of Array(5).keys()) { for (let j of Array(5).keys()) { let album = albumLists[j][i]; if (album) albums.push(album); } } return albums; } public async newCollections(offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { return this.collectionList(2, 10000000, offset, limit); } /** * TODO: use qr code login */ public async login(): Promise<IAccount> { let url = 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=1006102&daid=384&low_login=1&pt_no_auth=1&s_url=https://y.qq.com/vip/daren_recruit/apply.html&style=40'; // let url = 'https://y.qq.com' let win = new remote.BrowserWindow( { width: 800, height: 600, webPreferences: { webSecurity: true, nodeIntegration: false, allowRunningInsecureContent: true }, }); // win.webContents.openDevTools(); win.on('close', () => { win = null; }); win.loadURL(url); // clear cache win.webContents.session.clearStorageData(); win.show(); // timeout is 2 min // await sleep(5000); for (let timeout = 0; timeout < 12000000; timeout += 1000) { // waiting to login await sleep(1000); let cookiesStr = await win.webContents.executeJavaScript('Promise.resolve(document.cookie)', true); if (cookiesStr.includes('pt4_token')) { await sleep(2000); let cookies = {}; cookiesStr.split('; ').forEach(chunk => { let index = chunk.indexOf('='); cookies[chunk.slice(0, index)] = chunk.slice(index + 1); }); // get user profile let userOriginalId = cookies['ptui_loginuin'] || cookies['uin']; let tmpApi = new QQMusicApi(); tmpApi.cookies = cookies; let userProfile = await tmpApi.userProfile(userOriginalId); let account: IAccount = { user: userProfile, type: 'account', cookies, } // close window win.close(); return account; } } // Handle timeout win.close(); throw new LoginTimeoutError('Timeout !!!'); } public setAccount(account: IAccount): void { ok(account.user.origin == ORIGIN.qq, `[QQMusicApi.setAccount]: this account is not a qq account`); this.cookies = { ...account.cookies }; this.account = account; } public getAccount(): IAccount { return this.account; } public logined(): boolean { return !!this.account && !!this.account.cookies && !!this.account.cookies['pt4_token']; } public async userProfile(userMid: string): Promise<IUserProfile> { let params = { hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', cid: '205360838', ct: '20', userid: userMid, reqfrom: '1', reqtype: '0', }; let url = QQMusicApi.NODE_MAP.userProfile; let json = await this.request('GET', url, params); return makeUserProfile(json.data); } /** * No need to login */ public async userFavoriteSongs(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<ISong>> { let collections = await this.userCreatedCollections(userMid, 0, 2); let collectionOriginalId = collections[0].collectionOriginalId; let collection = await this.collection(collectionOriginalId, offset, limit); return collection.songs; } /** * No need to login */ public async userFavoriteAlbums(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<IAlbum>> { let account = this.getAccount(); let params = { loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', ct: '20', cid: '205360956', userid: userMid, reqtype: '2', sin: offset, ein: limit, }; let url = QQMusicApi.NODE_MAP.userFavoriteAlbums; let json = await this.request('GET', url, params); if (!json.data) { return []; } return makeAlbums(json.data.albumlist); } /** * TODO: Need to logined */ public async userFavoriteArtists(userMid: string, offset: number = 1, limit: number = 10): Promise<Array<IArtist>> { if (!this.logined()) { throw new NoLoginError("[QQMusicApi] Geting user's favorite artists needs to login"); } let account = this.getAccount(); let params = { utf8: '1', page: offset, perpage: limit, uin: userMid, g_tk: this.getACSRFToken(), loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'GB2312', notice: '0', platform: 'yqq', needNewCode: '0', }; let referer = `https://y.qq.com/portal/profile.html?uin=${userMid}`; let url = QQMusicApi.NODE_MAP.userFavoriteArtists; let json = await this.request('GET', url, params, null, referer); return makeArtists(json.list); } public async userFavoriteCollections(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { if (!this.logined()) { throw new NoLoginError("[QQMusicApi] Geting user's favorite collections needs to login"); } let account = this.getAccount(); let params = { loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', ct: '20', cid: '205360956', userid: userMid, reqtype: '3', sin: offset, ein: limit, }; let url = QQMusicApi.NODE_MAP.userFavoriteCollections; let json = await this.request('GET', url, params); if (!json.data) { return []; } return makeCollections(json.data.cdlist); } public async userCreatedCollections(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { if (!this.logined()) { throw new NoLoginError("[QQMusicApi] Geting user's created collections needs to login"); } let account = this.getAccount(); let params = { hostuin: userMid, sin: offset, size: limit, loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', }; let url = QQMusicApi.NODE_MAP.userCreatedCollections; let json = await this.request('GET', url, params); if (!json.data) { return []; } let userId = 'qq|user|' + json.data['hostuin'].toString(); userMid = json.data['encrypt_uin']; let userName = json.data['hostname']; let collections = makeCollections( (offset == 0 ? json.data.disslist.slice(1) : json.data.disslist) .filter(info => info.tid != 0) ); collections.filter(collection => { collection.userId = userId; collection.userMid = userMid; collection.userName = userName; }); return collections; } /** * TODO: Need to logined * * offset begins from 0 * * followings: `is_listen = 0` * followers: `is_listen = 1` */ protected async userFollows(userMid: string, offset: number = 0, limit: number = 10, ing: boolean = true): Promise<Array<IUserProfile>> { if (!this.logined()) { throw new NoLoginError("[QQMusicApi] Geting user's followings list needs to login"); } let account = this.getAccount(); let params = { utf8: '1', start: offset, num: limit, is_listen: ing ? '0' : '1', uin: userMid, loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), }; let url = QQMusicApi.NODE_MAP.userFollow; let json = await this.request('GET', url, params); return makeUserProfiles(json.list); } public async userFollowings(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<IUserProfile>> { return this.userFollows(userMid, offset, limit, true); } public async userFollowers(userMid: string, offset: number = 0, limit: number = 10): Promise<Array<IUserProfile>> { return this.userFollows(userMid, offset, limit, false); } public async myCreatedCollections(): Promise<Array<{ id: string; name: string }>> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Saving one song to favorite songs list needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), utf8: '1', uin: account.user.userOriginalId, loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', }; let url = QQMusicApi.NODE_MAP.myCreatedCollections; let json = await this.request('GET', url, params); return json.list.map(item => { return { id: item['dirid'].toString(), name: item['dirname'].trim() }; }); } public async userLikeSong(songId: string, songMid: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Saving one song to favorite songs list needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq.post', needNewCode: '0', uin: account.user.userOriginalId, midlist: songMid, typelist: '13', dirid: '201', addtype: '', formsender: '4', source: '153', r2: '0', r3: '1', utf8: '1', g_tk: this.getACSRFToken(), }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userLikeSong; let json = await this.request('POST', url, params, data, referer); return json.code == 0; } public async userLikeArtist(artistId: string, artistMid: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Saving one artist needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'gb2312', notice: '0', platform: 'yqq', needNewCode: '0', singermid: artistMid, rnd: Date.now(), }; let referer = `https://y.qq.com/n/yqq/singer/${artistMid}.html`; let url = QQMusicApi.NODE_MAP.userLikeArtist; let json = await this.request('GET', url, params, null, referer); return json['code'] == 0; } public async userLikeAlbum(albumId: string, albumMid: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Saving one album needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), uin: account.user.userOriginalId, ordertype: '1', albumid: albumId, albummid: albumMid, from: '1', optype: '1', utf8: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userLikeAlbum; let body = await this.request('POST', url, params, data, referer); return body.includes('"code":0'); } public async userLikeCollection(collectionId: string, collectionMid?: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Saving one collection needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), uin: account.user.userOriginalId, dissid: collectionId, from: '1', optype: '1', utf8: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userLikeCollection; let body = await this.request('POST', url, params, data, referer); return body.includes('"code":0'); } public async userLikeUserProfile(userId: string, userMid?: string, dislike: boolean = false): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] following/unfollowing one user needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), my_uin: account.user.userOriginalId, friend_uin: userId, status: dislike ? '0' : '1', formsender: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_gbk.html'; let url = QQMusicApi.NODE_MAP.userLikeUserProfile; let body = await this.request('POST', url, params, data, referer); return body.includes('"code":0'); } public async userDislikeSong(songId: string, songMid?: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Deleting one song from favorite songs list needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), uin: account.user.userOriginalId, dirid: '201', ids: songId, source: '103', types: '3', formsender: '1', flag: '2', from: '3', utf8: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userDislikeSong; let body = await this.request('POST', url, params, data, referer); return body.includes('删除成功'); } public async userDislikeArtist(artist: string, artistMid: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Deleting one artist needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), loginUin: account.user.userOriginalId, hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'gb2312', notice: '0', platform: 'yqq', needNewCode: '0', singermid: artistMid, rnd: Date.now(), }; let referer = `https://y.qq.com/n/yqq/singer/${artistMid}.html`; let url = QQMusicApi.NODE_MAP.userDislikeArtist; let json = await this.request('GET', url, params, null, referer); return json['code'] == 0; } public async userDislikeAlbum(albumId: string, albumMid: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Deleting one album needs to login'); } let account = this.getAccount(); let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: account.user.userOriginalId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), uin: account.user.userOriginalId, ordertype: '1', albumid: albumId, albummid: albumMid, from: '1', optype: '2', utf8: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userDislikeAlbum; let body = await this.request('POST', url, params, data, referer); return body.includes('"code":0'); } public async userDislikeCollection(collectionId: string, collectionMid?: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] Deleting one collection needs to login'); } let userId = this.account.user.userOriginalId; let params = { g_tk: this.getACSRFToken(), }; let data = querystringify({ loginUin: userId, hostUin: '0', format: 'fs', inCharset: 'GB2312', outCharset: 'utf8', notice: '0', platform: 'yqq', needNewCode: '0', g_tk: this.getACSRFToken(), uin: userId, dissid: collectionId, from: '1', optype: '2', utf8: '1', }); let referer = 'https://imgcache.qq.com/music/miniportal_v4/tool/html/fp_utf8.html'; let url = QQMusicApi.NODE_MAP.userDislikeCollection; let body = await this.request('POST', url, params, data, referer); return body.includes('"code":0'); } public async userDislikeUserProfile(userId: string, userMid?: string): Promise<boolean> { return this.userLikeUserProfile(userId, userMid, true); } /** * QQ has not recommended songs */ public async recommendSongs(offset: number = 0, limit: number = 10): Promise<Array<ISong>> { return []; } public async recommendCollections(offset: number = 0, limit: number = 10): Promise<Array<ICollection>> { let data = JSON.stringify( { recomPlaylist: { module: "playlist.HotRecommendServer", method: "get_hot_recommend", param: { cmd: 2, async: 1 } }, } ); let params = { g_tk: this.getACSRFToken(), loginUin: '0', hostUin: '0', format: 'json', inCharset: 'utf8', outCharset: 'utf-8', notice: '0', platform: 'yqq', needNewCode: '0', data, }; let url = QQMusicApi.NODE_MAP.recommendCollections; let json = await this.request('GET', url, params); return makeCollections(json['recomPlaylist']['data']['v_hot'] || []); } /** * QQ seems has not the api */ public async playLog(songId: string, seek: number, songMid?: string): Promise<boolean> { if (!this.logined()) { throw new NoLoginError('[QQMusicApi] recording one played song needs to login'); } let params = { musicid: songId, isexit: 'false', _r: Date.now(), g_tk: this.getACSRFToken(), }; let referer = 'https://y.qq.com/portal/player.html'; let url = QQMusicApi.NODE_MAP.playLog; // return nothing; await this.request('GET', url, params, null, referer); return true; } public resizeImageUrl(url: string, size: ESize | number): string { return resizeImageUrl(url, size, (url, size) => { if (size <= 300) { return url; } else if (size > 300 && size <= 500) { return url.replace('300x300', '500x500'); } else if (size > 500 && size <= 800) { return url.replace('300x300', '800x800'); } else { return url.replace('300x300', '800x800'); } }); } public changeIP(audioUrl: string): string { let re = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/; let mod = re.exec(audioUrl); if (!!!mod) { let newURI = this.getAudioURI(); return audioUrl.replace(QQMusicApi.AUDIO_URI, newURI); } let ip = mod[0]; // remove invalid ip this.ips = [ ...this.ips.slice(0, this.ip_index), ...this.ips.slice(this.ip_index + 1) ]; this.ip_index -= 1; let newIP = this.getAudioServerIP(); return audioUrl.replace(ip, newIP); } public async fromURL(input: string): Promise<Array<TMusicItems>> { let chunks = input.split(' '); let items = []; for (let chunk of chunks) { let m; let mid; let originId; let type; let matchList = [ // song [/songmid=([^/#&.]+)/, 'song', 'mid'], [/songid=(\d+)/, 'song', 'originId'], [/song\/(\d+)_num/, 'song', 'originId'], [/song\/([^/#&.]+)/, 'song', 'mid'], // singer [/singerid=(\d+)/, 'artist', 'originId'], [/singermid=([^/#&.]+)/, 'artist', 'mid'], [/singer\/([^/#&.]+)/, 'artist', 'mid'], // album [/album\/(\d+)_num/, 'album', 'originId'], [/albumId=(\d+)/, 'album', 'originId'], [/album\/([^/#&.]+)/, 'album', 'mid'], // collection [/taoge\/.+?&id=(\d+)/, 'collection', 'originId'], [/playlist\/(\d+)/, 'collection', 'originId'], [/playsquare\/([^/#&.]+)/, 'collection', 'originId'], // user [/profile\.html\?uin=([^/#&.]+)/, 'user', 'originId'], ]; for (let [re, tp, idType] of matchList) { m = (re as RegExp).exec(chunk); if (m) { if (idType == 'mid') { mid = m[1]; originId = null; type = tp; } else { mid = null; originId = m[1]; type = tp; } break; } } if (mid || originId) { let item; switch (type) { case 'song': item = await this.song(originId, mid); items.push(item); break; case 'artist': item = await this.artist(originId, mid); items.push(item); break; case 'album': item = await this.album(originId, mid); items.push(item); break; case 'collection': item = await this.collection(originId); items.push(item); break; case 'user': item = await this.userProfile(originId); items.push(item); break; default: break; } } } return items; } }
the_stack
/* * Copyright(c) 2017 Microsoft Corporation. All rights reserved. * * This code is licensed under the MIT License (MIT). * * 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. */ /// <reference path="../Microsoft.Maps.d.ts"/> declare module Microsoft.Maps { /** An object that contains the event arguments for when the drawing mode changes in the drawing tools. **/ export interface IDrawingModeChangedData { /** The shape being modified by the drawing tools. **/ shape: IPrimitive; /** The new drawing mode. **/ mode: DrawingTools.DrawingMode; } /** * Collection of options for the various DrawingTool methods */ export interface IDrawingToolOptions { /** Set of buttons to show in the drawing bar */ drawingBarActions?: DrawingTools.DrawingBarAction; } /** An object that contains options to change the settings of the drawing manager. */ export interface IDrawingManagerOptions extends IDrawingToolOptions { /** Set of buttons to show in the drawing bar. */ drawingBarActions?: DrawingTools.DrawingBarAction; /** The fill color used for pushpins and polygons. */ fillColor?: string | Color; /** The stroke color used for polylines and polygons. */ strokeColor?: string | Color; } /** * The DrawingManager class manages the ability to draw and edit multiple shapes on the map. Shapes managed by this class are rendered on a separate drawing layer. * User can use a mouse or a touch screen to draw on the map. When they are done, pressing the escape button or any button on the toolbar will exit the current drawing mode. * This class does not have a publicly accessible constructor and can only be accessed using the showDrawingManager of the DrawingTools class. */ export interface DrawingManager { /** * Adds a shapes to the layer, at the specified index if specified. • @param data The shape(s) to be added to the layer. • @param index The index at which to insert the shape into the layer. */ add(data: IPrimitive | IPrimitive[], index?: number): void; /** * Disposes the drawing manager instance. */ dispose(): void; /** * Resets the drawing manager and clears all shapes in the drawing layer. */ clear(): void; /** * Gets the current drawing mode of the drawing manager. * @returns The current drawing mode of the drawing manager. */ getDrawingMode(): DrawingTools.DrawingMode; /** * Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes. * @returns An array of shapes that are in the layer. This can be used to iterate over the individual shapes. */ getPrimitives(): IPrimitive[]; /** * Returns the index of the shape in the drawing layer. * @param primitive The shape to find the index of. * @param fromIndex The index to start the search from. * @returns The index of the shape in the drawing layer. Returns -1 if shape is not found. */ indexOf(primitive: IPrimitive, fromIndex?: number): number; /** * Removes a shape from the layer and returns it. * @param primitive The shape to remove from the layer. * @returns The shape that was removed from the layer. */ remove(primitive: IPrimitive): IPrimitive; /** * Removes a shape from the layer at the specified index. * @param index The index of the shape to remove from the layer. * @returns The shape that was removed from the layer. */ removeAt(index: number): IPrimitive; /** * Sets the drawing mode of the drawing manager. * @param mode The drawing mode to set the DrawingManager to. */ setDrawingMode(mode: DrawingTools.DrawingMode): void; /** * Sets the drawing tool options. * @param options The options to use with the drawing manager. */ setOptions(options: IDrawingManagerOptions): void; /** * Replaces all shapes in the layer with the new array of shapes that have been provided. * @param primitives An array of shapes to add to the drawing layer. */ setPrimitives(primitives: IPrimitive[]): void; } /** * Provides a set of tools for drawing and editing shapes on top of the map. * @requires The Microsoft.Maps.DrawingTools module. */ export class DrawingTools { /** * @constructor * @requires The Microsoft.Maps.DrawingTools module. * @param map A map instanct to attach the drawing tools to. */ constructor(map: Map); /** * Initializes the drawing layer and instructs it to create a new shape of a given type. * @param shapeType The type of new shape to create. * @param created A callback function that is fired after the initial shape is created. */ public create(shapeType: DrawingTools.ShapeType, created?: (shape: IPrimitive) => void): void; /** Disposes the instance of the DrawingTools class. */ public dispose(): void; /** * Adds a shape to the drawing layer and puts it into edit mode. * @param shape A shape to put into editting mode. */ public edit(shape: IPrimitive): void; /** * Finishes any shape create / edit operation currently in progress, and returns the shape that was created or editted through a specified callback function. * @param finished A callback function to return the completed shape with. */ public finish(finished?: (shape: IPrimitive) => void): void; /** * Shows the drawing toolbar, if it isn't already visible. * @param options - Options for this DrawingTool operation. Specifically, * the drawingBarActions property is used to customize the drawing bar view. */ public showDrawingBar(options?: IDrawingToolOptions): void; /** * Creates a drawing manager which allows multi-shape editing and displays the toolbar. * @param callback A callback function that is triggered after the DrawingTools have loaded. */ public showDrawingManager(callback?: (manager: DrawingManager) => void): void; } export module Events { ///////////////////////////////////// /// addHandler Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): IHandlerId; ///////////////////////////////////// /// addOne Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. */ export function addOne(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): void; /** * Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. */ export function addOne(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): void; ///////////////////////////////////// /// addThrottledHandler Definitions //////////////////////////////////// /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. * @returns The handler id. */ export function addThrottledHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId; /** * Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter. * @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc. * @param eventName The type of event to attach. Supported Events: * disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted * @param handler The callback function to handle the event when triggered. * @param throttleInterval throttle interval (in ms) * @returns The handler id. */ export function addThrottledHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void, throttleInterval: number): IHandlerId; } } declare module Microsoft.Maps.DrawingTools { /** * The different drawing modes that the drawing manager can be set to. * @requires The Microsoft.Maps.DrawingTools module. */ export enum DrawingMode { /** Edit an existing shape. Click on a shape to edit it. */ edit, /** Erase and existing shape. Click on the shapes to erase them. */ erase, /** Sets the drawing manager into an idle mode. */ none, /** Allow the user to draw a polygon. */ polygon, /** Allow the user to draw a polyline. */ polyline, /** Allow the user to draw a pushpin. */ pushpin } /** * The different types of shapes that are created or edited by the drawing tools. * @requires The Microsoft.Maps.DrawingTools module. */ export enum ShapeType { /** A polygon shape type. */ polygon, /** A polyline shape type. */ polyline } /** * Values used to identify and enable the items shown in the drawing bar. */ export enum DrawingBarAction { /** Create point primitive */ point, /** Create polyline primitive */ polyline, /** Create polygon primitive */ polygon, /** Erase existing primitive */ erase, /** Edit existing primitive */ edit, /** Change stroke style */ strokeStyle, /** Change fill style */ fillStyle, /** All items */ all, /** All shape creation items */ createShapes, /** All shape editing items */ editShapes, /** All shape styling items */ styleShapes } }
the_stack
import * as highlightjs from "highlightjs"; import * as marked from "marked"; import { toArray } from "react-emoji-render"; import { dispatch } from "./AppRedux"; import { AppState } from "./AppState"; import { NodeCompTableRowLayout } from "./comps/NodeCompTableRowLayout"; import { NodeCompVerticalRowLayout } from "./comps/NodeCompVerticalRowLayout"; import { Constants as C } from "./Constants"; import { MessageDlg } from "./dlg/MessageDlg"; import { UserProfileDlg } from "./dlg/UserProfileDlg"; import { NodeActionType } from "./enums/NodeActionType"; import { RenderIntf } from "./intf/RenderIntf"; import { TypeHandlerIntf } from "./intf/TypeHandlerIntf"; import * as J from "./JavaIntf"; import { PubSub } from "./PubSub"; import { Singletons } from "./Singletons"; import { Comp } from "./widget/base/Comp"; import { Div } from "./widget/Div"; import { Heading } from "./widget/Heading"; import { HorizontalLayout } from "./widget/HorizontalLayout"; import { Img } from "./widget/Img"; import { Span } from "./widget/Span"; let S: Singletons; PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => { S = s; }); function imageErrorFunc(evt: any) { console.log("remove broken img"); evt.target.hidden = true; evt.target.onerror = null; return true; } export class Render implements RenderIntf { private debug: boolean = false; private markedRenderer = null; CHAR_CHECKMARK = "&#10004;"; // After adding the breadcrumb query it's a real challenge to get this fading to work right, so for now // I'm disabling it entirely with this flag. enableRowFading: boolean = true; fadeInId: string; allowFadeInId: boolean = false; injectSubstitutions = (node: J.NodeInfo, val: string): string => { val = S.util.replaceAll(val, "{{locationOrigin}}", window.location.origin); /* These allow us to enter into the markdown things like this: [My Link Test]({{url}}?id=:my-test-name) [My Other Link Test]({{byName}}my-test-name) to be able to have a link to a node of a specific name However, this also works and may be the more 'clear' way: [Link Test App](/app?id=:my-test-name) */ val = S.util.replaceAll(val, "{{byName}}", window.location.origin + window.location.pathname + "?id=:"); val = S.util.replaceAll(val, "{{url}}", window.location.origin + window.location.pathname); let upperLeftImg = "<img class=\"img-upper-left\" width=\"{{imgSize}}\" src=\"{{imgUrl}}\"><div class=\"clearfix\"/>"; val = S.util.replaceAll(val, "{{imgUpperLeft}}", upperLeftImg); let upperRightImg = "<img class=\"img-upper-right\" width=\"{{imgSize}}\" src=\"{{imgUrl}}\"><div class=\"clearfix\"/>"; val = S.util.replaceAll(val, "{{imgUpperRight}}", upperRightImg); let imgInline = "<img class=\"img-block\" width=\"{{imgSize}}\" src=\"{{imgUrl}}\">"; val = S.util.replaceAll(val, "{{img}}", imgInline); if (val.indexOf("{{paypal-button}}") !== -1) { val = S.util.replaceAll(val, "{{paypal-button}}", C.PAY_PAL_BUTTON); } let imgSize = S.props.getNodePropVal(J.NodeProp.IMG_SIZE, node); // actual size prop is saved as "0" if (imgSize && imgSize !== "0") { val = S.util.replaceAll(val, "{{imgSize}}", imgSize); } else { val = S.util.replaceAll(val, "{{imgSize}}", ""); } /* Allow the <img> tag to be supported inside the markdown for any node and let {{imgUrl}}, be able to be used in that to reference the url of any attached image. This allows the following type of thing to be put inside the markdown at the beginning of the text:, whenever you want to make the text flow around an image. This text currently has to be entered manually but in the future we'll have a way to generate this more 'automatically' based on editor options. <img class="img-upper-left" width="100px" src="{{imgUrl}}"> <div class="clearfix"/> */ if (val.indexOf("{{imgUrl}}")) { let src: string = S.render.getUrlForNodeAttachment(node, false); val = val.replace("{{imgUrl}}", src); } return val; } /** * See: https://github.com/highlightjs/highlight.js */ initMarkdown = (): void => { if (this.markedRenderer) return; this.markedRenderer = new marked.Renderer(); this.markedRenderer.code = (code, language) => { // Check whether the given language is valid for highlight.js. const validLang = !!(language && highlightjs.getLanguage(language)); // Highlight only if the language is valid. const highlighted = validLang ? highlightjs.highlight(language, code).value : code; // Render the highlighted code with `hljs` class. return `<pre><code class="hljs ${language}">${highlighted}</code></pre>`; }; marked.setOptions({ renderer: this.markedRenderer, // This appears to be working just fine, but i don't have the CSS styles added into the distro yet // so none of the actual highlighting works yet, so i'm just commenting out for now, until i add classes. // // Note: using the 'markedRenderer.code' set above do we still need this highlight call here? I have no idea. Need to check/test highlight: function (code) { return highlightjs.highlightAuto(code).value; }, gfm: true, breaks: false, pedantic: false, smartLists: true, smartypants: false }); } setNodeDropHandler = (attribs: any, node: J.NodeInfo, isFirst: boolean, state: AppState): void => { if (!node) return; // console.log("Setting drop handler: nodeId=" + node.id + " attribs.id=" + attribs.id); S.util.setDropHandler(attribs, (evt: DragEvent) => { const data = evt.dataTransfer.items; // todo-2: right now we only actually support one file being dragged? Would be nice to support multiples for (let i = 0; i < data.length; i++) { const d = data[i]; // console.log("DROP[" + i + "] kind=" + d.kind + " type=" + d.type); if (d.kind === "string") { d.getAsString((s) => { if (d.type.match("^text/uri-list")) { /* Disallow dropping from our app onto our app */ if (s.startsWith(location.protocol + "//" + location.hostname)) { return; } S.attachment.openUploadFromUrlDlg(node ? node.id : null, s, null, state); } /* this is the case where a user is moving a node by dragging it over another node */ else if (s.startsWith(S.nav._UID_ROWID_PREFIX)) { S.edit.moveNodeByDrop(node.id, s.substring(4), isFirst); } }); return; } else if (d.kind === "string" && d.type.match("^text/html")) { } else if (d.kind === "file" /* && d.type.match('^image/') */) { const file: File = data[i].getAsFile(); // if (file.size > Constants.MAX_UPLOAD_MB * Constants.ONE_MB) { // S.util.showMessage("That file is too large to upload. Max file size is "+Constants.MAX_UPLOAD_MB+" MB"); // return; // } S.attachment.openUploadFromFileDlg(false, node, file, state); return; } } }); } /* nodeId is parent node to query for calendar content */ showCalendar = (nodeId: string, allNodes: boolean, state: AppState): void => { if (!nodeId) { let node = S.quanta.getHighlightedNode(state); if (node) { nodeId = node.id; } } if (!nodeId) { S.util.showMessage("You must first click on a node.", "Warning"); return; } S.util.ajax<J.RenderCalendarRequest, J.RenderCalendarResponse>("renderCalendar", { allNodes, nodeId }, (res: J.RenderCalendarResponse) => { dispatch("Action_ShowCalendar", (s: AppState): AppState => { s.fullScreenCalendarId = nodeId; s.fullScreenCalendarAllNodes = allNodes; s.calendarData = S.util.buildCalendarData(res.items); return s; }); }); } showNodeUrl = (node: J.NodeInfo, state: AppState): void => { if (!node) { node = S.quanta.getHighlightedNode(state); } if (!node) { S.util.showMessage("You must first click on a node.", "Warning"); return; } const children = []; /* we need this holder object because we don't have the dialog until it's created */ const dlgHolder: any = {}; let byIdUrl = window.location.origin + "/app?id=" + node.id; children.push(new Heading(5, "By ID"), // new Div(byIdUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(byIdUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); let markdownIdUrl = "[link](/app?id=" + node.id + ")"; children.push(new Heading(5, "Markdown Link"), // new Div(markdownIdUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(markdownIdUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); if (node.name) { let byNameUrl = window.location.origin + S.util.getPathPartForNamedNode(node); children.push(new Heading(5, "By Name"), // new Div(byNameUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(byNameUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); } let rssFeed = window.location.origin + "/rss?id=" + node.id; children.push(new Heading(5, "Node RSS Feed"), // new Div(rssFeed, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(rssFeed); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); let bin = S.props.getNodePropVal(J.NodeProp.BIN, node); if (bin) { let attByIdUrl = window.location.origin + "/f/id/" + node.id; children.push(new Heading(5, "View Attachment By Id"), // new Div(attByIdUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(attByIdUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); let downloadttByIdUrl = attByIdUrl + "?download=y"; children.push(new Heading(5, "Download Attachment By Id"), // new Div(downloadttByIdUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(downloadttByIdUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); } if (node.name) { if (bin) { let attByNameUrl = window.location.origin + S.util.getPathPartForNamedNodeAttachment(node); children.push(new Heading(5, "View Attachment By Name"), // new Div(attByNameUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(attByNameUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); let downloadAttByNameUrl = attByNameUrl + "?download=y"; children.push(new Heading(5, "Download Attachment By Name"), // new Div(downloadAttByNameUrl, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(downloadAttByNameUrl); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); } } let ipfsLink = S.props.getNodePropVal(J.NodeProp.IPFS_LINK, node); if (ipfsLink) { children.push(new Heading(5, "IPFS CID"), // new Div(ipfsLink, { className: "anchorBigMarginBottom", title: "Click -> Copy to clipboard", onClick: () => { S.util.copyToClipboard(ipfsLink); S.util.flashMessage("Copied link to Clipboard", "Clipboard", true); dlgHolder.dlg.close(); } })); } dlgHolder.dlg = new MessageDlg(null, "URLs", null, new Div(null, null, children), false, 0, null); dlgHolder.dlg.open(); } allowAction = (typeHandler: TypeHandlerIntf, action: NodeActionType, node: J.NodeInfo, appState: AppState): boolean => { return typeHandler == null || typeHandler.allowAction(action, node, appState); } renderPageFromData = (res: J.RenderNodeResponse, scrollToTop: boolean, targetNodeId: string, clickTab: boolean = true, allowScroll: boolean = true): void => { if (res && res.noDataResponse) { S.util.showMessage(res.noDataResponse, "Note"); return; } try { // console.log("renderPageFromData: " + S.util.prettyPrint(res)); dispatch("Action_RenderPage", (s: AppState): AppState => { // if (allowScroll) { // S.quanta.tabScrollTop(C.TAB_MAIN); // } // console.log("update state in Action_RenderPage"); if (!s.activeTab || clickTab) { S.quanta.tabChanging(s.activeTab, C.TAB_MAIN, s); s.activeTab = S.quanta.activeTab = C.TAB_MAIN; } s.guiReady = true; s.pageMessage = null; /* Note: This try block is solely to enforce the finally block to happen to guarantee setting s.rendering back to false, no matter what */ try { if (res) { s.node = res.node; s.endReached = res.endReached; s.breadcrumbs = res.breadcrumbs; /* Slight hack to make viewing 'posts' or chat rooms nodes turn on metaData */ if (s.node.type === J.NodeType.POSTS || s.node.type === J.NodeType.ROOM) { S.edit.setMetadataOption(true); } } s.idToNodeMap = new Map<string, J.NodeInfo>(); if (res) { S.quanta.updateNodeMap(res.node, s); } let targetNode: J.NodeInfo = null; if (targetNodeId) { // If you access /n/myNodeName we get here with targetNodeId being the name (and not the ID) // so we have to call getNodeByName() to get the 'id' that goes with that node name. if (targetNodeId.startsWith(":")) { targetNodeId = targetNodeId.substring(1); targetNode = S.quanta.getNodeByName(res.node, targetNodeId, s); if (targetNode) { targetNodeId = targetNode.id; } } S.render.fadeInId = targetNodeId; s.pendingLocationHash = null; } else { if (!S.render.fadeInId) { S.render.fadeInId = s.node.id; } } if (s.node && !s.isAnonUser) { // do this async just for performance setTimeout(() => { S.util.updateHistory(s.node, targetNode, s); }, 10); } if (this.debug && s.node) { console.log("RENDER NODE: " + s.node.id); } if (s.activeTab !== C.TAB_MAIN) { allowScroll = false; } // NOTE: In these blocks we set rendering=true only if we're scrolling so that the user doesn't see // a jump in position during scroll, but a smooth reveal of the post-scroll location/rendering. if (s.pendingLocationHash) { // console.log("highlight: pendingLocationHash"); window.location.hash = s.pendingLocationHash; // Note: the substring(1) trims the "#" character off. if (allowScroll) { // console.log("highlight: pendingLocationHash (allowScroll)"); S.quanta.highlightRowById(s.pendingLocationHash.substring(1), true, s); if (S.quanta.hiddenRenderingEnabled) { s.rendering = true; } } s.pendingLocationHash = null; } else if (allowScroll && targetNodeId) { // console.log("highlight: byId"); if (!S.quanta.highlightRowById(targetNodeId, true, s)) { // anything to do here? didn't find node. } if (S.quanta.hiddenRenderingEnabled) { s.rendering = true; } } // else if (allowScroll && (scrollToTop || !S.quanta.getHighlightedNode(s))) { // console.log("highlight: scrollTop"); S.view.scrollToTop(); if (S.quanta.hiddenRenderingEnabled) { s.rendering = true; } } // else if (allowScroll) { // console.log("highlight: scrollToSelected"); S.view.scrollToSelectedNode(s); if (S.quanta.hiddenRenderingEnabled) { s.rendering = true; } } } finally { if (s.rendering) { /* This is a tiny timeout yes, but don't remove this timer. We need it or else this won't work. */ PubSub.subSingleOnce(C.PUBSUB_postMainWindowScroll, () => { setTimeout(() => { dispatch("Action_settingVisible", (s: AppState): AppState => { s.rendering = false; this.allowFadeInId = true; return s; }); }, /* This delay has to be long enough to be sure scrolling has taken place already I'm pretty sure this might work even at 100ms or less on most machines, but I'm leaving room for slower browsers, because it's critical that this be long enough, but not long enough to be noticeable. */ 300); }); } else { this.allowFadeInId = true; } // see also: tag #getNodeMetaInfo this.getNodeMetaInfo(res.node); // only focus the TAB if we're not editing, because if editing the edit field will be focused. In other words, // if we're about to initiate editing a TextArea field will be getting focus // so we don't want to set the MAIN tab as the focus and mess that up. // console.log("focus MAIN_TAB during render."); if (!s.editNode) { S.util.focusId(C.TAB_MAIN); } } return s; }); } catch (err) { console.error("render failed."); } } /* Get information for each node. Namely for now just the 'hasChildren' state because it takes a actual query per node to find that out. Note: Users will be able to see the fading in fadeInRowBkgClz class for the length of time it takes the getNodeMetaInfo, this is ok and is the current design. The fading now works kind of like a progress indicator by keeping user busy watching something. This function will perform well even if called repeatedly. Only does the work once as neccessary so we can call this safely after every time we get new data from the server, with no unnecessarey performance hit. */ getNodeMetaInfo = (node: J.NodeInfo) => { if (node && node.children) { // Holds the list of IDs we will query for. Only those with "metainfDone==false", meaning we // haven't yet pulled the metadata yet. let ids: string[] = []; for (let child of node.children) { if (!(child as any).metaInfDone) { ids.push(child.id); } } if (ids.length > 0) { // console.log("MetaQuery idCount=" + ids.length); S.util.ajax<J.GetNodeMetaInfoRequest, J.GetNodeMetaInfoResponse>("getNodeMetaInfo", { ids }, (res: J.GetNodeMetaInfoResponse) => { dispatch("Action_updateNodeMetaInfo", (s: AppState): AppState => { if (s.node && s.node.children) { s.node.hasChildren = true; // iterate all children for (let child of s.node.children) { // if this is a child we will have just pulled down if (!(child as any).metaInfDone) { // find the child in what we just pulled down. let inf: J.NodeMetaIntf = res.nodeIntf.find(v => v.id === child.id); // set the hasChildren to the value we just pulled down. if (inf) { child.hasChildren = inf.hasChildren; } (child as any).metaInfDone = true; } } } return s; }); }, null, true); } } } renderChildren = (node: J.NodeInfo, level: number, allowNodeMove: boolean, state: AppState): Comp => { if (!node || !node.children) return null; let allowAvatars = true; /* * Number of rows that have actually made it onto the page to far. Note: some nodes get filtered out on * the client side for various reasons. */ const layout = S.props.getNodePropVal(J.NodeProp.LAYOUT, node); /* Note: for edit mode, or on mobile devices, always use vertical layout. */ if (state.userPreferences.editMode || state.mobileMode || !layout || layout === "v") { return new NodeCompVerticalRowLayout(node, level, allowNodeMove, true); } else if (layout.indexOf("c") === 0) { return new NodeCompTableRowLayout(node, level, layout, allowNodeMove, true); } else { // of no layout is valid, fall back on vertical. return new NodeCompVerticalRowLayout(node, level, allowNodeMove, true); } } getAttachmentUrl = (urlPart: string, node: J.NodeInfo, downloadLink: boolean): string => { /* If this node attachment points to external URL return that url */ let imgUrl = S.props.getNodePropVal(J.NodeProp.BIN_URL, node); if (imgUrl) { return imgUrl; } const ipfsLink = S.props.getNodePropVal(J.NodeProp.IPFS_LINK, node); let bin = S.props.getNodePropVal(J.NodeProp.BIN, node); if (bin || ipfsLink) { if (ipfsLink) { bin = "ipfs"; } let ret: string = S.util.getRpcPath() + urlPart + "/" + bin + "?nodeId=" + node.id; if (downloadLink) { ret += "&download=true"; } return ret; } return null; } getUrlForNodeAttachment = (node: J.NodeInfo, downloadLink: boolean): string => { let ret = null; if (node.dataUrl) { ret = node.dataUrl; // console.log("getUrlForNodeAttachment: id="+node.id+" url="+ret+" from dataUrl"); } else { ret = this.getAttachmentUrl("bin", node, downloadLink); // console.log("getUrlForNodeAttachment: id=" + node.id + " url=" + ret + " from bin"); } return ret; } getStreamUrlForNodeAttachment = (node: J.NodeInfo): string => { return this.getAttachmentUrl("stream", node, false); } getAvatarImgUrl = (ownerId: string, avatarVer: string) => { if (!avatarVer) return null; return S.util.getRpcPath() + "bin/avatar" + "?nodeId=" + ownerId + "&v=" + avatarVer; } getProfileHeaderImgUrl = (ownerId: string, avatarVer: string) => { if (!avatarVer) return null; return S.util.getRpcPath() + "bin/profileHeader" + "?nodeId=" + ownerId + "&v=" + avatarVer; } makeAvatarImage = (node: J.NodeInfo, state: AppState) => { let src: string = node.apAvatar || this.getAvatarImgUrl(node.ownerId, node.avatarVer); if (!src) { return null; } const key = "avatar-" + node.id; // Note: we DO have the image width/height set on the node object (node.width, node.hight) but we don't need it for anything currently return new Img(key, { src, className: "avatarImage", onError: imageErrorFunc, title: "User: @" + node.owner + "\n\nShow Profile", // align: "left", // causes text to flow around onClick: (evt: any) => { new UserProfileDlg(node.ownerId, state).open(); } }); } /* Returns true if the logged in user and the type of node allow the property to be edited by the user */ allowPropertyEdit = (node: J.NodeInfo, propName: string, state: AppState): boolean => { const typeHandler: TypeHandlerIntf = S.plugin.getTypeHandler(node.type); return typeHandler ? typeHandler.allowPropertyEdit(propName, state) : true; } isReadOnlyProperty = (propName: string): boolean => { return S.props.readOnlyPropertyList.has(propName); } showGraph = (node: J.NodeInfo, searchText: string, state: AppState): void => { if (!node) { node = S.quanta.getHighlightedNode(state); } dispatch("Action_ShowGraph", (s: AppState): AppState => { s.fullScreenGraphId = node.id; s.graphSearchText = searchText; return s; }); } parseEmojis = (value: any): any => { if (!value) return value; const emojisArray = toArray(value); if (!emojisArray) return value; const newValue = emojisArray.reduce((previous: any, current: any) => { if (typeof current === "string") { return previous + current; } if (current && current.props) { return previous + current.props.children; } else { return previous; } }, ""); return newValue; }; renderUser(nodeId: string, user: string, userBio: string, imgSrc: string, actorUrl: string, displayName: string, className: string, iconClass: string, showMessageButton: boolean, onClick: Function): Comp { let img: Img = imgSrc ? new Img(null, { className: iconClass, src: imgSrc, onClick }) : null; let attribs: any = {}; if (className) attribs.className = className; return new Div(null, attribs, [ new HorizontalLayout([ new Div(null, { className: "friendLhs" }, [ img ]), new Div(null, { className: "friendRhs" }, [ // I'm removing this becasue we can click on the image and to these thru the Profile Dialog of the user. // new ButtonBar([ // // todo-1: need to make ALL calls be able to do a newSubNode here without so we don't need // // the showMessagesButton flag. // showMessageButton ? new Button("Message", S.edit.newSubNode, { // title: "Send Private Message", // nid: nodeId // }) : null, // actorUrl ? new Button("Go to User Page", () => { // window.open(actorUrl, "_blank"); // }) : null // ], null, "float-right"), // new Clearfix(), new Div(displayName, { className: "userName" }), new Div(null, null, [ // we use a span because the div stretches across empty space and does a mouse click // when you didn't intend to click the actual name sometimes. new Span("@" + user, { className: (displayName ? "" : "userName ") + "clickable", onClick }) ]) // The page just looks cleaner with the username only. We can click them to see their bio text. // userBio ? new Html(userBio, { // className: "userBio" // }) : null ]) ], "displayTable userInfo", null) ]); } }
the_stack
import EyeglassCompiler = require('broccoli-eyeglass'); import Eyeglass = require('eyeglass'); import findHost from "./findHost"; import funnel = require('broccoli-funnel'); import MergeTrees = require('broccoli-merge-trees'); import * as path from 'path'; import * as url from 'url'; import cloneDeep = require('lodash.clonedeep'); import defaultsDeep = require('lodash.defaultsdeep'); import {BroccoliSymbolicLinker} from "./broccoli-ln-s"; import debugGenerator = require("debug"); import BroccoliDebug = require("broccoli-debug"); import { URL } from 'url'; const debug = debugGenerator("ember-cli-eyeglass"); const debugSetup = debug.extend("setup"); const debugBuild = debug.extend("build"); const debugCache = debug.extend("cache"); const debugAssets = debug.extend("assets"); interface EyeglassProjectInfo { apps: Array<any>; } interface EyeglassAddonInfo { name: string; parentPath: string; isApp: boolean; app: any; assets?: BroccoliSymbolicLinker; } interface EyeglassAppInfo { assets?: BroccoliSymbolicLinker; sessionCache: Map<string, string | number>; } interface GlobalEyeglassData { infoPerAddon: WeakMap<object, EyeglassAddonInfo>; infoPerApp: WeakMap<object, EyeglassAppInfo>; projectInfo: EyeglassProjectInfo; } const g: typeof global & {EYEGLASS?: GlobalEyeglassData} = global; if (!g.EYEGLASS) { g.EYEGLASS = { infoPerAddon: new WeakMap(), infoPerApp: new WeakMap(), projectInfo: { apps: [], } } } const EYEGLASS_INFO_PER_ADDON = g.EYEGLASS.infoPerAddon; const EYEGLASS_INFO_PER_APP = g.EYEGLASS.infoPerApp; const APPS = g.EYEGLASS.projectInfo.apps; //eslint-disable-next-line @typescript-eslint/no-explicit-any function isLazyEngine(addon: any): boolean { if (addon.lazyLoading === true) { // pre-ember-engines 0.5.6 lazyLoading flag return true; } if (addon.lazyLoading && addon.lazyLoading.enabled === true) { return true; } return false; } //eslint-disable-next-line @typescript-eslint/no-explicit-any function embroiderEnabled(config: any): boolean { return config.embroiderEnabled ?? false; } //eslint-disable-next-line @typescript-eslint/no-explicit-any function getDefaultAssetHttpPrefix(parent: any, config: any): string { // the default http prefix differs between Ember app and lazy Ember engine // iterate over the parent's chain and look for a lazy engine or there are // no more parents, which means we've reached the Ember app project let current = parent; while (current.parent) { if (isLazyEngine(current) && !embroiderEnabled(config)) { // only lazy engines will inline their assets in the engines-dist folder return `engines-dist/${current.name}/assets`; } else if (isEngine(current)) { return `${current.name}/assets`; } current = current.parent; } // at this point, the highlevel container is Ember app and we should use the default 'assets' prefix return 'assets'; } /* addon.addons forms a tree(graph?) of addon objects that allow us to traverse the * ember addon dependencies. However there's no path information in the addon object, * but each addon object has some disconnected metadata in addon.addonPackages * with the path info. Unfortunately there's no shared information that would * allow us to connect which addon packages are actually which addon objects. * It would be great if ember-cli didn't throw that information on the ground * while building these objects. It would also be marvelous if we knew which * addons came from a local addon declaration and which ones came from node * modules. **/ function localEyeglassAddons(addon): Array<{path: string}> { let paths = new Array<{path: string}>(); if (typeof addon.addons !== 'object' || typeof addon.addonPackages !== 'object') { return paths; } let packages = Object.keys(addon.addonPackages); for (let i = 0; i < packages.length; i++) { let p = addon.addonPackages[packages[i]]; // Note: this will end up creating manual addons for things in node modules // that are actually auto discovered, these manual modules will get deduped // out. but we need to add all of them because the some eyeglass modules // for addons & engines won't get autodiscovered otherwise unless the // addons/engines are themselves eyeglass modules (which we don't want to require). if (p.pkg.keywords.some(kw => kw == 'eyeglass-module')) { paths.push({ path: p.path }) } } // TODO: if there's a cycle in the addon graph don't recurse. for (let i = 0; i < addon.addons.length; i++) { paths = paths.concat(localEyeglassAddons(addon.addons[i])); } return paths; } const EMBER_CLI_EYEGLASS = { name: require("../package.json").name, included(parent) { this._super.included.apply(this, arguments); this.initSelf(); }, initSelf() { if (EYEGLASS_INFO_PER_ADDON.has(this)) return; let app = findHost(this); if (!app) return; let isApp = (this.app === app); let name = app.name; if (!isApp) { let thisName = typeof this.parent.name === "function" ? this.parent.name() : this.parent.name; name = `${name}/${thisName}` } let parentPath = this.parent.root; debugSetup("Initializing %s with eyeglass support for %s at %s", isApp ? "app" : "addon", name, parentPath); if (isApp) { APPS.push(app); // we create the symlinker in persistent mode because there's not a good // way yet to recreate the symlinks when sass files are cached. I would // worry about it more but it seems like the dist directory is cumulative // across builds anyway. EYEGLASS_INFO_PER_APP.set(app, { sessionCache: new Map(), assets: new BroccoliSymbolicLinker({}, {annotation: app.name, persistentOutput: true}) }); } let addonInfo = { isApp, name, parentPath, app, isEngine: isEngine(this.parent), assets: new BroccoliSymbolicLinker({}, { annotation: `Eyeglass Assets for ${app.name}/${name}`, persistentOutput: true, }), }; EYEGLASS_INFO_PER_ADDON.set(this, addonInfo); }, postBuild(_result) { debugBuild("Build Succeeded."); this._resetCaches(); }, _resetCaches() { debugCache("clearing eyeglass global cache"); Eyeglass.resetGlobalCaches(); for (let app of APPS) { let appInfo = EYEGLASS_INFO_PER_APP.get(app); let addonInfo = EYEGLASS_INFO_PER_ADDON.get(this); let extracted = this.extractConfig(addonInfo.app, this); if (!embroiderEnabled(extracted)) { appInfo.assets.reset(); } debugCache("clearing %d cached items from the eyeglass build cache for %s", appInfo.sessionCache.size, app.name); appInfo.sessionCache.clear(); } }, buildError(_error) { debugBuild("Build Failed."); this._resetCaches(); }, postprocessTree(type, tree) { let addon = this; let addonInfo = EYEGLASS_INFO_PER_ADDON.get(this); let extracted = this.extractConfig(addonInfo.app, addon); // This code is intended only for classic ember builds. // (There's no "all" postprocess tree in embroider.) // Skip this entirely for embroider builds (we'll include // assets on a per-addon basis in the CSS tree). if (embroiderEnabled(extracted)) { return tree; } if (type === "all" && addonInfo.isApp) { debugBuild("Merging eyeglass asset tree with the '%s' tree", type); let appInfo = EYEGLASS_INFO_PER_APP.get(addonInfo.app); return new MergeTrees([tree, appInfo.assets], {overwrite: true}); } else { return tree; } }, setupPreprocessorRegistry(type, registry) { let addon = this; registry.add('css', { name: 'eyeglass', ext: 'scss', toTree: (tree, inputPath, outputPath) => { // These start with a slash and that messes things up. let cssDir = outputPath.slice(1) || './'; let sassDir = inputPath.slice(1) || './'; let {app, name, isApp} = EYEGLASS_INFO_PER_ADDON.get(this); tree = new BroccoliDebug(tree, `ember-cli-eyeglass:${name}:input`); let extracted = this.extractConfig(app, addon); extracted.cssDir = cssDir; extracted.sassDir = sassDir; const config = this.setupConfig(extracted); debugSetup("Broccoli Configuration for %s: %O", name, config) let httpRoot = config.eyeglass && config.eyeglass.httpRoot || "/"; let addonInfo = EYEGLASS_INFO_PER_ADDON.get(this); let compiler = new EyeglassCompiler(tree, config); compiler.events.on("cached-asset", (absolutePathToSource, httpPathToOutput) => { debugBuild("will symlink %s to %s", absolutePathToSource, httpPathToOutput); try { this.linkAsset(absolutePathToSource, httpRoot, httpPathToOutput); } catch (e) { // pass this only happens with a cache after downgrading ember-cli. } }); if (embroiderEnabled(config)) { compiler.events.on("build", () => { addonInfo.assets.reset(); }); } let withoutSassFiles = funnel(tree, { srcDir: (isApp && !embroiderEnabled(config)) ? 'app/styles' : undefined, destDir: isApp ? 'assets' : undefined, exclude: ['**/*.s{a,c}ss'], allowEmpty: true, }); let trees: Array<ReturnType<typeof funnel> | EyeglassCompiler | BroccoliSymbolicLinker> = [withoutSassFiles, compiler]; if (embroiderEnabled(config)) { // Push the addon assets tree on to this build only if we're using embroider. // (For classic builds, the postprocess tree will handle this.) trees.push(addonInfo.assets); } let result = new MergeTrees(trees, { overwrite: true }); return new BroccoliDebug(result, `ember-cli-eyeglass:${name}:output`); } }); }, extractConfig(host, addon) { const isNestedAddon = typeof addon.parent.parent === 'object'; // setup eyeglass for this project's configuration const hostConfig = cloneDeep(host.options.eyeglass || {}); const addonConfig = isNestedAddon ? cloneDeep(addon.parent.options.eyeglass || {}) : {}; return defaultsDeep(addonConfig, hostConfig); }, linkAsset(srcFile: string, httpRoot: string, destUri: string, config: any): string { let rootPath = httpRoot.startsWith("/") ? httpRoot.substring(1) : httpRoot; let destPath = destUri.startsWith("/") ? destUri.substring(1) : destUri; if (process.platform === "win32") { destPath = convertURLToPath(destPath); rootPath = convertURLToPath(rootPath); } if (destPath.startsWith(rootPath)) { destPath = path.relative(rootPath, destPath); } let assets; if (embroiderEnabled(config)) { assets = EYEGLASS_INFO_PER_ADDON.get(this).assets; } else { let {app} = EYEGLASS_INFO_PER_ADDON.get(this); assets = EYEGLASS_INFO_PER_APP.get(app).assets; } debugAssets("Will link asset %s to %s to expose it at %s relative to %s", srcFile, destPath, destUri, httpRoot); return assets.ln_s(srcFile, destPath); }, setupConfig(config: ConstructorParameters<typeof EyeglassCompiler>[1], options) { let {isApp, app, parentPath} = EYEGLASS_INFO_PER_ADDON.get(this); let {sessionCache} = EYEGLASS_INFO_PER_APP.get(app); config.sessionCache = sessionCache; config.annotation = `EyeglassCompiler(${parentPath})`; if (!config.sourceFiles && !config.discover) { config.sourceFiles = [isApp ? 'app.scss' : 'addon.scss']; } config.assets = ['public', 'app'].concat(config.assets || []); config.eyeglass = config.eyeglass || {} // XXX We don't set the root anywhere but I'm not sure what might break if we do. // config.eyeglass.root = parentPath; config.eyeglass.httpRoot = config.eyeglass.httpRoot || config["httpRoot"]; if (config.persistentCache) { let cacheDir = parentPath.replace(/\//g, "$"); config.persistentCache += `/${cacheDir}`; } config.assetsHttpPrefix = config.assetsHttpPrefix || getDefaultAssetHttpPrefix(this.parent, config); if (config.eyeglass.modules) { config.eyeglass.modules = config.eyeglass.modules.concat(localEyeglassAddons(this.parent)); } else { config.eyeglass.modules = localEyeglassAddons(this.parent); } let originalConfigureEyeglass = config.configureEyeglass; config.configureEyeglass = (eyeglass, sass, details) => { eyeglass.assets.installer((file, uri, fallbackInstaller, cb) => { try { cb(null, this.linkAsset(file, eyeglass.options.eyeglass.httpRoot || "/", uri, config)) } catch (e) { cb(e); } }); if (originalConfigureEyeglass) { originalConfigureEyeglass(eyeglass, sass, details); } }; // If building an app, rename app.css to <project>.css per Ember conventions. // Otherwise, we're building an addon, so rename addon.css to <name-of-addon>.css. let originalGenerator = config.optionsGenerator; config.optionsGenerator = (sassFile, cssFile, sassOptions, compilationCallback) => { if (isApp) { cssFile = cssFile.replace(/app\.css$/, `${this.app.name}.css`); } else { cssFile = cssFile.replace(/addon\.css$/, `${this.parent.name}.css`); } if (originalGenerator) { originalGenerator(sassFile, cssFile, sassOptions, compilationCallback); } else { compilationCallback(cssFile, sassOptions); } }; return config; } }; function isEngine(appOrAddon: any): boolean { let keywords: Array<string> = appOrAddon._packageInfo.pkg.keywords || new Array<string>(); return keywords.includes("ember-engine"); } function convertURLToPath(fragment: string): string { return (new URL(`file://${fragment}`)).pathname; } export = EMBER_CLI_EYEGLASS;
the_stack
// tslint:disable:max-func-body-length no-non-null-assertion import * as assert from "assert"; import { AzureRMAssets, BuiltinFunctionMetadata, FunctionsMetadata } from "../extension.bundle"; import { networkTest } from "./networkTest.test"; suite("AzureRMAssets", () => { networkTest("getFunctionMetadata()", async () => { const functionMetadataArray = AzureRMAssets.getFunctionsMetadata().functionMetadata; assert(functionMetadataArray); assert(functionMetadataArray.length > 0, `Expected to get at least 1 function metadata, but got ${functionMetadataArray.length} instead.`); }); suite("FunctionMetadata", () => { test("constructor(string,string,string)", () => { const metadata = new BuiltinFunctionMetadata("a", "b", "c", 1, 2, [], undefined); assert.deepStrictEqual(metadata.fullName, "a"); assert.deepStrictEqual(metadata.usage, "b"); assert.deepStrictEqual(metadata.description, "c"); assert.deepStrictEqual(metadata.minimumArguments, 1); assert.deepStrictEqual(metadata.maximumArguments, 2); assert.deepStrictEqual(metadata.returnValueMembers, []); }); test("findByName", () => { const metadata = new FunctionsMetadata( [new BuiltinFunctionMetadata("hi", "", "", 0, 0, [], undefined), new BuiltinFunctionMetadata("MyFunction", "", "", 0, 0, [], undefined)]); assert.equal(metadata.findbyName("MyFunction")!.fullName, "MyFunction"); assert.equal(metadata.findbyName("myfunction")!.fullName, "MyFunction"); assert.equal(metadata.findbyName("MYFUNCTION")!.fullName, "MyFunction"); assert.equal(metadata.findbyName("MyFunction2"), undefined); }); test("findByPrefix", () => { const metadata = new FunctionsMetadata([ new BuiltinFunctionMetadata("One", "", "", 0, 0, [], undefined), new BuiltinFunctionMetadata("Onerous", "", "", 0, 0, [], undefined), new BuiltinFunctionMetadata("Two", "", "", 0, 0, [], undefined) ]); assert.deepStrictEqual(metadata.filterByPrefix("MyFunction"), []); assert.deepStrictEqual(metadata.filterByPrefix("On").map(meta => meta.fullName), ["One", "Onerous"]); assert.deepStrictEqual(metadata.filterByPrefix("on").map(meta => meta.fullName), ["One", "Onerous"]); assert.deepStrictEqual(metadata.filterByPrefix("ONE").map(meta => meta.fullName), ["One", "Onerous"]); assert.deepStrictEqual(metadata.filterByPrefix("Oner").map(meta => meta.fullName), ["Onerous"]); assert.deepStrictEqual(metadata.filterByPrefix("Onerous").map(meta => meta.fullName), ["Onerous"]); assert.deepStrictEqual(metadata.filterByPrefix("Onerousy"), []); }); suite("parameters", () => { test("with no parameters in usage", () => { const metadata = new BuiltinFunctionMetadata("a", "a()", "description", 1, 2, [], []); assert.deepStrictEqual(metadata.parameters, []); }); test("with one parameter in usage", () => { const metadata = new BuiltinFunctionMetadata("a", "a(b)", "description", 1, 2, [], undefined); assert.deepStrictEqual(metadata.parameters, [{ name: "b", type: undefined }]); }); test("with two parameters in usage", () => { const metadata = new BuiltinFunctionMetadata("a", "a(b, c )", "description", 1, 2, [], undefined); assert.deepStrictEqual(metadata.parameters, [{ name: "b", type: undefined }, { name: "c", type: undefined }]); }); }); suite("fromString(string)", () => { test("with null", () => { // tslint:disable-next-line:no-any assert.deepStrictEqual(BuiltinFunctionMetadata.fromString(<any>null), []); }); test("with undefined", () => { // tslint:disable-next-line:no-any assert.deepStrictEqual(BuiltinFunctionMetadata.fromString(<any>undefined), []); }); test("with empty string", () => { assert.deepStrictEqual(BuiltinFunctionMetadata.fromString(""), []); }); test("with non-JSON string", () => { assert.deepStrictEqual(BuiltinFunctionMetadata.fromString("hello there"), []); }); test("with empty object", () => { assert.deepStrictEqual(BuiltinFunctionMetadata.fromString("{}"), []); }); test("with empty functionSignatures property", () => { assert.deepStrictEqual(BuiltinFunctionMetadata.fromString("{ 'functionSignatures': [] }"), []); }); test("with one function signature with only name property", () => { assert.deepStrictEqual( BuiltinFunctionMetadata.fromString(`{ "functionSignatures": [ { "name": "a", "expectedUsage": "z", "description": "1" } ] }`), [ // tslint:disable-next-line:no-any new BuiltinFunctionMetadata("a", "z", "1", <any>undefined, <any>undefined, [], undefined) ]); }); test("with two function signatures with only name property", () => { assert.deepStrictEqual( // tslint:disable-next-line:max-line-length BuiltinFunctionMetadata.fromString(`{ "functionSignatures": [ { "name": "a", "expectedUsage": "z" }, { "name": "b", "expectedUsage": "y", "description": "7" } ] }`), [ // tslint:disable-next-line:no-any new BuiltinFunctionMetadata("a", "z", <any>undefined, <any>undefined, <any>undefined, [], undefined), // tslint:disable-next-line:no-any new BuiltinFunctionMetadata("b", "y", "7", <any>undefined, <any>undefined, [], undefined) ]); }); test("with actual ExpressionMetadata.json file contents", () => { const fileContents: string = `{ "$schema": "expressionMetadata.schema.json", "functionSignatures": [ { "name": "add", "expectedUsage": "add(operand1, operand2)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "base64", "expectedUsage": "base64(inputString)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "concat", "expectedUsage": "concat(arg1, arg2, arg3, ...)", "minimumArguments": 0, "maximumArguments": null }, { "name": "copyIndex", "expectedUsage": "copyIndex([offset])", "minimumArguments": 0, "maximumArguments": 1 }, { "name": "deployment", "expectedUsage": "deployment()", "minimumArguments": 0, "maximumArguments": 0 }, { "name": "div", "expectedUsage": "div(operand1, operand2)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "int", "expectedUsage": "int(valueToConvert)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "length", "expectedUsage": "length(array\/string)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "listKeys", "expectedUsage": "listKeys(resourceName\/resourceIdentifier, apiVersion)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "listPackage", "expectedUsage": "listPackage(resourceName\/resourceIdentifier, apiVersion)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "mod", "expectedUsage": "mod(operand1, operand2)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "mul", "expectedUsage": "mul(operand1, operand2)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "padLeft", "expectedUsage": "padLeft(stringToPad, totalLength, paddingCharacter)", "minimumArguments": 3, "maximumArguments": 3 }, { "name": "parameters", "expectedUsage": "parameters(parameterName)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "providers", "expectedUsage": "providers(providerNamespace, [resourceType])", "minimumArguments": 1, "maximumArguments": 2 }, { "name": "reference", "expectedUsage": "reference(resourceName\/resourceIdentifier, [apiVersion])", "minimumArguments": 1, "maximumArguments": 2 }, { "name": "replace", "expectedUsage": "replace(originalString, oldCharacter, newCharacter)", "minimumArguments": 3, "maximumArguments": 3 }, { "name": "resourceGroup", "expectedUsage": "resourceGroup()", "minimumArguments": 0, "maximumArguments": 0, "returnValueMembers": [ { "name": "id" }, { "name": "name" }, { "name": "location" }, { "name": "properties" }, { "name": "tags" } ] }, { "name": "resourceId", "expectedUsage": "resourceId([subscriptionId], [resourceGroupName], resourceType, resourceName1, [resourceName2]...)", "minimumArguments": 2, "maximumArguments": null }, { "name": "split", "expectedUsage": "split(inputString, delimiter)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "string", "expectedUsage": "string(valueToConvert)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "sub", "expectedUsage": "sub(operand1, operand2)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "subscription", "expectedUsage": "subscription()", "minimumArguments": 0, "maximumArguments": 0, "returnValueMembers": [ { "name": "id" }, { "name": "subscriptionId" } ] }, { "name": "substring", "expectedUsage": "substring(stringToParse, startIndex, length)", "minimumArguments": 1, "maximumArguments": 3 }, { "name": "toLower", "expectedUsage": "toLower(string)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "toUpper", "expectedUsage": "toUpper(string)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "trim", "expectedUsage": "trim(stringToTrim)", "minimumArguments": 1, "maximumArguments": 1 }, { "name": "uniqueString", "expectedUsage": "uniqueString(stringForCreatingUniqueString, ...)", "minimumArguments": 1, "maximumArguments": null }, { "name": "uri", "expectedUsage": "uri(baseUri, relativeUri)", "minimumArguments": 2, "maximumArguments": 2 }, { "name": "variables", "expectedUsage": "variables(variableName)", "minimumArguments": 1, "maximumArguments": 1 } ] }`; const functionMetadata: BuiltinFunctionMetadata[] = BuiltinFunctionMetadata.fromString(fileContents); assert(functionMetadata); assert(functionMetadata.length > 0); }); }); }); });
the_stack
import { Injectable, InternalServerErrorException, NotFoundException, ConflictException, Scope, Inject, } from '@nestjs/common'; import { Model, Schema } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { UserDocument as User } from './schema/user.schema'; import { CreateUserDTO } from './dto/create-user.dto'; import { UpdateUserDTO } from './dto/update-user.dto'; import { CourseDocument as Course } from '../course/schema/course.schema'; import { EnrolledCourseDocument as Enrolled } from '../course/schema/enrolledCourse.schema'; import { CreateEnrolledDTO } from './dto/create-enrolled.dto'; import { UpdateEnrolledDTO } from './dto/update-enrolled.dto'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; @Injectable({ scope: Scope.REQUEST }) export class UserService { constructor( @InjectModel('User') private readonly userModel: Model<User>, @InjectModel('Course') private readonly courseModel: Model<Course>, @InjectModel('Enrolled') private readonly enrolledModel: Model<Enrolled>, @Inject(REQUEST) private readonly request: Request, ) {} // fetch all Users async getAllUser(): Promise<User[]> { try { const users = await this.userModel.find().exec(); return users; } catch (e) { throw new InternalServerErrorException(e); } } // fetch all gamification data async getAllGamified(skip: string): Promise<User[]> { try { const skipNum = parseInt(skip, 10); const users = await this.userModel .find({}, { _id: false }, { skip: skipNum, limit: 10 }) .select('first_name last_name score photoUrl') .sort({ score: -1 }) .exec(); return users; } catch (e) { throw new InternalServerErrorException(e); } } // Get a single User async findUserByEmail(query): Promise<User> { try { const { email } = query; const user = await this.userModel.findOne({ email }); if (user) { return user; } else { throw new NotFoundException(`user with email ${email} not Found`); } } catch (e) { throw new InternalServerErrorException(e); } } // Get a single User async getMe(): Promise<User> { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { return user; } else { throw new NotFoundException("Your email doesn't Exist in database"); } } catch (e) { throw new InternalServerErrorException(e); } } // post a single User async addUser(request, CreateUserDTO: CreateUserDTO): Promise<User> { try { const { email, fId, role } = request['user']; const userExists = await this.userModel.findOne({ email: email }).lean(); if (userExists) { throw new ConflictException(`User with email ${email} already exists`); } const userToBeCreated = { ...CreateUserDTO, email, fId, role }; const newUser = await new this.userModel(userToBeCreated); return newUser.save(); } catch (e) { throw new InternalServerErrorException(e); } } // Edit User details async updateUser(UpdateUserDTO: UpdateUserDTO): Promise<User> { let updatedUser; const filter = { email: this.request['user']['email'] }; try { updatedUser = await this.userModel.findOneAndUpdate( filter, UpdateUserDTO, { new: true, useFindAndModify: false }, ); } catch (e) { throw new InternalServerErrorException(e); } finally { return updatedUser; } } // Delete a User async deleteUser(query: any): Promise<any> { try { const deletedUser = await this.userModel.findOneAndDelete(query); if (deletedUser) { return deletedUser; } else { throw new NotFoundException('User not Found or query not correct!'); } } catch (e) { throw new InternalServerErrorException(e); } } // gets all Enrolled courses async getEnrolledCoursesById(courseId: Schema.Types.ObjectId) { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const userId = user.id; const enrolledCourses = await this.enrolledModel.findOne({ studentId: userId, courseId: courseId, }); return enrolledCourses; } else { throw new NotFoundException('User not found'); } } catch (e) { throw new InternalServerErrorException(e); } } // gets all Enrolled courses async getEnrolledCourses() { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const userId = user.id; const enrolledCourses = await this.enrolledModel.find({ studentId: userId, }); return enrolledCourses; } else { throw new NotFoundException('User not found'); } } catch (e) { throw new InternalServerErrorException(e); } } // adds Enrolled Course async addCourse(createEnrolledDTO: CreateEnrolledDTO) { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const courseIdSearch = await this.enrolledModel .find({ studentId: user.id }) .lean(); courseIdSearch.forEach((singleEnrolled) => { if (singleEnrolled.courseId == createEnrolledDTO['courseId']) { throw new ConflictException('Course Already Enrolled by user'); } }); const newEnrolled = await new this.enrolledModel(createEnrolledDTO); const course = await this.courseModel.findById( createEnrolledDTO.courseId, ); if (course) { newEnrolled['videosWatched'] = new Array(course.video_num).fill( false, ); await newEnrolled.save(); return newEnrolled; } else { throw new NotFoundException('course not found!'); } // a test line to see the populated sets of data /*const newF = await this.enrolledModel.find({}).populate('students'); return newF;*/ } else { throw new NotFoundException('user not found!'); } } catch (e) { throw new InternalServerErrorException(e); } } // gets all wishlisted courses async getWishList(): Promise<any> { try { const userWishList = await this.userModel .findOne({ email: this.request['user']['email'], }) .lean(); return userWishList.wishlist; } catch (e) { throw new InternalServerErrorException(e); } } // adds wishlisted course async addWishlist(cId: Schema.Types.ObjectId) { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const doesWishlistExists = await this.courseModel.exists({ _id: cId['cId'], }); if (doesWishlistExists) { const doesUserExistInWishList = user.wishlist.includes(cId['cId']); if (!doesUserExistInWishList) { user.wishlist.push(cId['cId']); await user.save(); return user; } else { throw new ConflictException('Course Already Exists In WishList'); } } else { throw new NotFoundException("Wishlisted Course doesn't exist"); } } else { throw new NotFoundException('User Not Found'); } } catch (e) { throw new InternalServerErrorException(e); } } // Delete a wishList of User async deleteWishList(wishId: Schema.Types.ObjectId): Promise<any> { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { user.wishlist = user.wishlist.filter((wishlist) => wishlist != wishId); await user.save(); return user; } else { throw new NotFoundException('not found'); } } catch (e) { throw new InternalServerErrorException(e); } } // gets all courses on cartList async getCartList(): Promise<any> { try { const userCartList = await this.userModel .findOne({ email: this.request['user']['email'], }) .lean(); return userCartList.cartList; } catch (e) { throw new InternalServerErrorException(e); } } // adds a course to Cart async addCartList(cId: Schema.Types.ObjectId) { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const doesCartListExists = await this.courseModel.exists({ _id: cId['cId'], }); if (doesCartListExists) { const doesUserExistInCartList = user.cartList.includes(cId['cId']); if (!doesUserExistInCartList) { user.cartList.push(cId['cId']); await user.save(); return user; } else { throw new ConflictException('Course Already Exists In Cart'); } } else { throw new NotFoundException("Course doesn't exist"); } } else { throw new NotFoundException('User Not Found'); } } catch (e) { throw new InternalServerErrorException(e); } } // Delete a course from cart of user async deleteCardList(cartId: Schema.Types.ObjectId): Promise<any> { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { user.cartList = user.cartList.filter((cartList) => cartList != cartId); await user.save(); return user; } else { throw new NotFoundException('User not found'); } } catch (e) { throw new InternalServerErrorException(e); } } // update Enrolled Course async updateCourse( updateEnrolledDto: UpdateEnrolledDTO, courseId: Schema.Types.ObjectId, ): Promise<any> { try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const userId = user.id; const updatedCourse = await this.enrolledModel.findOneAndUpdate( { studentId: userId, courseId: courseId, }, updateEnrolledDto, { new: true, useFindAndModify: false }, ); return updatedCourse; } else { throw new NotFoundException('User not found'); } } catch (e) { throw new InternalServerErrorException(e); } } // Delete Enrolled Course of User async deleteEnrolledCourse(courseId: Schema.Types.ObjectId): Promise<any> { let deletedFrom; try { const user = await this.userModel.findOne({ email: this.request['user']['email'], }); if (user) { const userId = user.id; deletedFrom = await this.enrolledModel.findOneAndRemove({ studentId: userId, courseId: courseId, }); if (deletedFrom) { return deletedFrom; } else { throw new NotFoundException('not found'); } } else { throw new NotFoundException('User not found'); } } catch (e) { throw new InternalServerErrorException(e); } } }
the_stack
import { AffectedTaskOccurrence } from '../../../Enumerations/AffectedTaskOccurrence'; import { ConflictResolutionMode } from '../../../Enumerations/ConflictResolutionMode'; import { DateTime } from '../../../DateTime'; import { DeleteMode } from '../../../Enumerations/DeleteMode'; import { ExchangeService } from '../../ExchangeService'; import { ExchangeVersion } from '../../../Enumerations/ExchangeVersion'; import { ItemAttachment } from "../../../ComplexProperties/ItemAttachment"; import { ItemId } from '../../../ComplexProperties/ItemId'; import { MessageDisposition } from '../../../Enumerations/MessageDisposition'; import { Promise } from './../../../Promise'; import { PropertySet } from '../../PropertySet'; import { Recurrence } from '../../../ComplexProperties/Recurrence/Patterns/Recurrence'; import { Schemas } from "../Schemas/Schemas"; import { ServiceObjectSchema } from '../Schemas/ServiceObjectSchema'; import { StringList } from '../../../ComplexProperties/StringList'; import { TaskDelegationState } from '../../../Enumerations/TaskDelegationState'; import { TaskMode } from '../../../Enumerations/TaskMode'; import { TaskStatus } from '../../../Enumerations/TaskStatus'; import { XmlElementNames } from '../../XmlElementNames'; import { Item } from './Item'; /** * Represents a Task item. Properties available on tasks are defined in the TaskSchema class. */ export class Task extends Item { /** required to check [Attachable] attribute, AttachmentCollection.AddItemAttachment<TItem>() checks for non inherited [Attachable] attribute. */ public static get Attachable(): boolean { return (<any>this).name === "Task"; }; /** * @nullable Gets or sets the actual amount of time that is spent on the task. */ get ActualWork(): number { return <number>this.PropertyBag._getItem(Schemas.TaskSchema.ActualWork); } set ActualWork(value: number) { this.PropertyBag._setItem(Schemas.TaskSchema.ActualWork, value); } /** * @nullable Gets the date and time the task was assigned. */ get AssignedTime(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.TaskSchema.AssignedTime); } /** * Gets or sets the billing information of the task. */ get BillingInformation(): string { return <string>this.PropertyBag._getItem(Schemas.TaskSchema.BillingInformation); } set BillingInformation(value: string) { this.PropertyBag._setItem(Schemas.TaskSchema.BillingInformation, value); } /** * Gets the number of times the task has changed since it was created. */ get ChangeCount(): number { return <number>this.PropertyBag._getItem(Schemas.TaskSchema.ChangeCount); } /** * Gets or sets a list of companies associated with the task. */ get Companies(): StringList { return <StringList>this.PropertyBag._getItem(Schemas.TaskSchema.Companies); } set Companies(value: StringList) { this.PropertyBag._setItem(Schemas.TaskSchema.Companies, value); } /** * @nullable Gets or sets the date and time on which the task was completed. */ get CompleteDate(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.TaskSchema.CompleteDate); } set CompleteDate(value: DateTime) { this.PropertyBag._setItem(Schemas.TaskSchema.CompleteDate, value); } /** * Gets or sets a list of contacts associated with the task. */ get Contacts(): StringList { return <StringList>this.PropertyBag._getItem(Schemas.TaskSchema.Contacts); } set Contacts(value: StringList) { this.PropertyBag._setItem(Schemas.TaskSchema.Contacts, value); } /** * Gets the current delegation state of the task. */ get DelegationState(): TaskDelegationState { return <TaskDelegationState>this.PropertyBag._getItem(Schemas.TaskSchema.DelegationState); } /** * Gets the name of the delegator of this task. */ get Delegator(): string { return <string>this.PropertyBag._getItem(Schemas.TaskSchema.Delegator); } /** * @nullable Gets or sets the date and time on which the task is due. */ get DueDate(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.TaskSchema.DueDate); } set DueDate(value: DateTime) { this.PropertyBag._setItem(Schemas.TaskSchema.DueDate, value); } /** * Gets a value indicating the mode of the task. */ get Mode(): TaskMode { return <TaskMode>this.PropertyBag._getItem(Schemas.TaskSchema.Mode); } /** * Gets a value indicating whether the task is complete. */ get IsComplete(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.TaskSchema.IsComplete); } /** * Gets a value indicating whether the task is recurring. */ get IsRecurring(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.TaskSchema.IsRecurring); } /** * Gets a value indicating whether the task is a team task. */ get IsTeamTask(): boolean { return <boolean>this.PropertyBag._getItem(Schemas.TaskSchema.IsTeamTask); } /** * Gets or sets the mileage of the task. */ get Mileage(): string { return <string>this.PropertyBag._getItem(Schemas.TaskSchema.Mileage); } set Mileage(value: string) { this.PropertyBag._setItem(Schemas.TaskSchema.Mileage, value); } /** * Gets the name of the owner of the task. */ get Owner(): string { return <string>this.PropertyBag._getItem(Schemas.TaskSchema.Owner); } /** * Gets or sets the completeion percentage of the task. PercentComplete must be between 0 and 100. */ get PercentComplete(): number { return <number>this.PropertyBag._getItem(Schemas.TaskSchema.PercentComplete); } set PercentComplete(value: number) { this.PropertyBag._setItem(Schemas.TaskSchema.PercentComplete, value); } /** * Gets or sets the recurrence pattern for this task. Available recurrence pattern classes include Recurrence. * DailyPattern, Recurrence.MonthlyPattern and Recurrence.YearlyPattern. */ get Recurrence(): Recurrence { return <Recurrence>this.PropertyBag._getItem(Schemas.TaskSchema.Recurrence); } set Recurrence(value: Recurrence) { this.PropertyBag._setItem(Schemas.TaskSchema.Recurrence, value); } /** * @nullable Gets or sets the date and time on which the task starts. */ get StartDate(): DateTime { return <DateTime>this.PropertyBag._getItem(Schemas.TaskSchema.StartDate); } set StartDate(value: DateTime) { this.PropertyBag._setItem(Schemas.TaskSchema.StartDate, value); } /** * Gets or sets the status of the task. */ get Status(): TaskStatus { return <TaskStatus>this.PropertyBag._getItem(Schemas.TaskSchema.Status); } set Status(value: TaskStatus) { this.PropertyBag._setItem(Schemas.TaskSchema.Status, value); } /** * Gets a string representing the status of the task, localized according to the PreferredCulture property of the ExchangeService object the task is bound to. */ get StatusDescription(): string { return <string>this.PropertyBag._getItem(Schemas.TaskSchema.StatusDescription); } /** * @nullable Gets or sets the total amount of work spent on the task. */ get TotalWork(): number { return <number>this.PropertyBag._getItem(Schemas.TaskSchema.TotalWork); } set TotalWork(value: number) { this.PropertyBag._setItem(Schemas.TaskSchema.TotalWork, value); } /** * @internal @nullable Gets the default setting for how to treat affected task occurrences on Delete. */ get DefaultAffectedTaskOccurrences(): AffectedTaskOccurrence { return AffectedTaskOccurrence.AllOccurrences; } /** * Initializes an unsaved local instance of **Task**. To bind to an existing task, use Task.Bind() instead. * * @param {ExchangeService} service The ExchangeService instance to which this task is bound. */ constructor(service: ExchangeService); /** * @internal Initializes a new instance of the **Task** class. * * @param {ItemAttachment} parentAttachment The parent attachment. */ constructor(parentAttachment: ItemAttachment); constructor(serviceOrParentAttachment: ExchangeService | ItemAttachment) { super(serviceOrParentAttachment); } /** * Binds to an existing task and loads the specified set of properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the task. * @param {ItemId} id The Id of the task to bind to. * @param {PropertySet} propertySet The set of properties to load. * @return {Promise<Task>} A Task instance representing the task corresponding to the specified Id :Promise. */ public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet): Promise<Task>; /** * Binds to an existing task and loads its first class properties. * Calling this method results in a call to EWS. * * @param {ExchangeService} service The service to use to bind to the task. * @param {ItemId} id The Id of the task to bind to. * @return {Promise<Task>} A Task instance representing the task corresponding to the specified Id :Promise. */ public static Bind(service: ExchangeService, id: ItemId): Promise<Task>; public static Bind(service: ExchangeService, id: ItemId, propertySet: PropertySet = PropertySet.FirstClassProperties): Promise<Task> { return service.BindToItem<Task>(id, propertySet, Task); } /** * Deletes the current occurrence of a recurring task. After the current occurrence isdeleted, the task represents the next occurrence. * Developers should call Load to retrieve the new property values of the task. * Calling this method results in a call to EWS. * * @param {DeleteMode} deleteMode The deletion mode. * @return {Promise<void>} :Promise. */ DeleteCurrentOccurrence(deleteMode: DeleteMode): Promise<void> { return this.InternalDelete( deleteMode, null, AffectedTaskOccurrence.SpecifiedOccurrenceOnly); } /** * @internal Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem or UpdateItem request so this item can be property saved or updated. * * @param {boolean} isUpdateOperation Indicates whether the operation being petrformed is an update operation. * @return {boolean} *true* if a time zone SOAP header should be emitted; otherwise, *false*. */ GetIsTimeZoneHeaderRequired(isUpdateOperation: boolean): boolean { return true; } /** * @internal Gets the minimum required server version. * * @return {ExchangeVersion} Earliest Exchange version in which this service object type is supported. */ GetMinimumRequiredServerVersion(): ExchangeVersion { return ExchangeVersion.Exchange2007_SP1; } /** * @internal Internal method to return the schema associated with this type of object. * * @return {ServiceObjectSchema} The schema associated with this type of object. */ GetSchema(): ServiceObjectSchema { return Schemas.TaskSchema.Instance; } /** * @internal Gets the element name of item in XML * * @return {string} name of elelment */ GetXmlElementName(): string { return XmlElementNames.Task; } /** * Applies the local changes that have been made to this task. Calling this method results in at least one call to EWS. * Mutliple calls to EWS might be made if attachments have been added or removed. * * @param {ConflictResolutionMode} conflictResolutionMode Specifies how conflicts should be resolved. * @return {Promise<Task>} A Task object representing the completed occurrence if the task is recurring and the update marks it as completed; or a Task object representing the current occurrence if the task is recurring and the uypdate changed its recurrence pattern; or null in every other case :Promise. */ Update(conflictResolutionMode: ConflictResolutionMode): Promise<Task>; /** ##internal ~~ workaround GitHub #52 */ Update(conflictResolutionMode: ConflictResolutionMode): Promise<any>; Update(conflictResolutionMode: ConflictResolutionMode): Promise<Task> { return <Promise<Task>>this.InternalUpdate( null /* parentFolder */, conflictResolutionMode, MessageDisposition.SaveOnly, null); } }
the_stack
declare var WorkerGlobalScope: any; var _self: any = (typeof window !== 'undefined') ? window // if in browser : ( (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self // if in worker : {} // if in node js ); /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * author Lea Verou http://lea.verou.me */ export var Prism = (function () { // Private helper vars var lang = /\blang(?:uage)?-(\w+)\b/i; var uniqueId = 0; var _ = _self.Prism = { util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token((tokens as any).type, _.util.encode((tokens as any).content), (tokens as any).alias); } else if (_.util.type(tokens) === 'Array') { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]; }, objId: function (obj) { if (!obj['__id']) { Object.defineProperty(obj, '__id', {value: ++uniqueId}); } return obj['__id']; }, // Deep clone a language definition (e.g. to extend it) clone: function (o) { var type = _.util.type(o); switch (type) { case 'Object': var clone = {}; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = _.util.clone(o[key]); } } return clone; case 'Array': // Check for existence for IE8 return o.map && o.map(function (v) { return _.util.clone(v); }); } return o; } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need anobject and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. If not provided, the function appends instead. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function (key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; }, // Traverse a language definition with Depth First Search DFS: function (o, callback, type?, visited?) { visited = visited || {}; for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); if (_.util.type(o[i]) === 'Object' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, null, visited); } else if (_.util.type(o[i]) === 'Array' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, i, visited); } } } } }, plugins: {}, highlightAll: function (async, callback) { var env = { callback: callback, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code', elements: undefined }; _.hooks.run("before-highlightall", env); var elements = env.elements || document.querySelectorAll(env.selector); for (var i = 0, element; element = elements[i++];) { _.highlightElement(element, async === true, env.callback); } }, highlightElement: function (element, async, callback) { // Find language var language, grammar, parent = element; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (parent.className.match(lang) || [, ''])[1].toLowerCase(); grammar = _.languages[language]; } // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; // Set language on the parent, for styling parent = element.parentNode; if (/pre/i.test(parent.nodeName)) { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } var code = element.textContent; var env = { element: element, language: language, grammar: grammar, code: code }; _.hooks.run('before-sanity-check', env); if (!env.code || !env.grammar) { _.hooks.run('complete', env); return; } _.hooks.run('before-highlight', env); if (async && _self.Worker) { var worker = new Worker(_['filename']); worker.onmessage = function (evt) { env['highlightedCode'] = evt.data; _.hooks.run('before-insert', env); env.element.innerHTML = env['highlightedCode']; callback && callback.call(env.element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code, immediateClose: true })); } else { env['highlightedCode'] = _.highlight(env.code, env.grammar, env.language); _.hooks.run('before-insert', env); env.element.innerHTML = env['highlightedCode']; callback && callback.call(element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); } }, highlight: function (text, grammar, language) { var tokens = _.tokenize(text, grammar); return Token['stringify'](_.util.encode(tokens), language); }, tokenize: function (text, grammar, language?) { var Token = _['Token']; var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } tokenloop: for (var token in grammar) { if (!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } var patterns = grammar[token]; patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, greedy = !!pattern.greedy, lookbehindLength = 0, alias = pattern.alias; pattern = pattern.pattern || pattern; for (var i = 0; i < strarr.length; i++) { // Don’t cache length as it changes during the loop var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! break tokenloop; } if (str instanceof Token) { continue; } pattern.lastIndex = 0; var match = pattern.exec(str), delNum = 1; // Greedy patterns can override/remove up to two previously matched tokens if (!match && greedy && i != strarr.length - 1) { // Reconstruct the original text using the next two tokens var nextToken = strarr[i + 1].matchedStr || strarr[i + 1], combStr = str + nextToken; if (i < strarr.length - 2) { combStr += strarr[i + 2].matchedStr || strarr[i + 2]; } // Try the pattern again on the reconstructed text pattern.lastIndex = 0; match = pattern.exec(combStr); if (!match) { continue; } var from = match.index + (lookbehind ? match[1].length : 0); // To be a valid candidate, the new match has to start inside of str if (from >= str.length) { continue; } var to = match.index + match[0].length, len = str.length + nextToken.length; // Number of tokens to delete and replace with the new match delNum = 3; if (to <= len) { if (strarr[i + 1].greedy) { continue; } delNum = 2; combStr = combStr.slice(0, len); } str = combStr; } if (!match) { continue; } if (lookbehind) { lookbehindLength = match[1].length; } var from = match.index + lookbehindLength, match = match[0].slice(lookbehindLength), to = from + match.length, before = str.slice(0, from), after = str.slice(to); var args = [i, delNum]; if (before) { args.push(before); } var wrapped = new Token(token, inside ? _.tokenize(match, inside) : match, alias, match, greedy); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); } } } return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i = 0, callback; callback = callbacks[i++];) { callback(env); } } } }; var Token = _['Token'] = function (type, content, alias?, matchedStr?, greedy?) { this.type = type; this.content = content; this.alias = alias; // Copy of the full string this token was created from this.matchedStr = matchedStr || null; this.greedy = !!greedy; }; Token['stringify'] = function (o, language, parent) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function (element) { return Token['stringify'](element, language, o); }).join(''); } var env = { type: o.type, content: Token['stringify'](o.content, language, parent), tag: 'span', classes: ['token', o.type], attributes: {}, language: language, parent: parent }; if (env.type == 'comment') { env.attributes['spellcheck'] = 'true'; } if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = ''; for (var name in env.attributes) { attributes += (attributes ? ' ' : '') + name + '="' + (env.attributes[name] || '') + '"'; } return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>'; }; if (!_self.document) { if (!_self.addEventListener) { // in Node.js return _self.Prism; } // In worker _self.addEventListener('message', function (evt) { var message = JSON.parse(evt.data), lang = message.language, code = message.code, immediateClose = message.immediateClose; _self.postMessage(_.highlight(code, _.languages[lang], lang)); if (immediateClose) { _self.close(); } }, false); return _self.Prism; } //Get current script and highlight var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop(); if (script) { _['filename'] = script.src; if (document.addEventListener && !script.hasAttribute('data-manual')) { if (document.readyState !== "loading") { requestAnimationFrame(<FrameRequestCallback>_.highlightAll); } else { document.addEventListener('DOMContentLoaded', <any>_['highlightAll']); } } } return _self.Prism; })(); // if (typeof module !== 'undefined' && module.exports) { // module.exports = Prism; // } // // // hack for components to work correctly in node.js // if (typeof global !== 'undefined') { // global.Prism = Prism; // } ; Prism.languages.markup = { 'comment': /<!--[\w\W]*?-->/, 'prolog': /<\?[\w\W]+?\?>/, 'doctype': /<!DOCTYPE[\w\W]+?>/, 'cdata': /<!\[CDATA\[[\w\W]*?]]>/i, 'tag': { pattern: /<\/?(?!\d)[^\s>\/=.$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i, inside: { 'tag': { pattern: /^<\/?[^\s>\/]+/i, inside: { 'punctuation': /^<\/?/, 'namespace': /^[^\s>\/:]+:/ } }, 'attr-value': { pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i, inside: { 'punctuation': /[=>"']/ } }, 'punctuation': /\/?>/, 'attr-name': { pattern: /[^\s>\/]+/, inside: { 'namespace': /^[^\s>\/:]+:/ } } } }, 'entity': /&#?[\da-z]{1,8};/i }; // Plugin to make entity title show the real entity, idea by Roman Komarov Prism.hooks.add('wrap', function (env) { if (env.type === 'entity') { env.attributes['title'] = env.content.replace(/&amp;/, '&'); } }); Prism.languages.xml = Prism.languages.markup; Prism.languages.html = Prism.languages.markup; Prism.languages.mathml = Prism.languages.markup; Prism.languages.svg = Prism.languages.markup; Prism.languages.css = { 'comment': /\/\*[\w\W]*?\*\//, 'atrule': { pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i, inside: { 'rule': /@[\w-]+/ // See rest below } }, 'url': /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, 'selector': /[^\{\}\s][^\{\};]*?(?=\s*\{)/, 'string': /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/, 'property': /(\b|\B)[\w-]+(?=\s*:)/i, 'important': /\B!important\b/i, 'function': /[-a-z0-9]+(?=\()/i, 'punctuation': /[(){};:]/ }; Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css); if (Prism.languages.markup) { Prism.languages.insertBefore('markup', 'tag', { 'style': { pattern: /(<style[\w\W]*?>)[\w\W]*?(?=<\/style>)/i, lookbehind: true, inside: Prism.languages.css, alias: 'language-css' } }); Prism.languages.insertBefore('inside', 'attr-value', { 'style-attr': { pattern: /\s*style=("|').*?\1/i, inside: { 'attr-name': { pattern: /^\s*style/i, inside: Prism.languages.markup.tag.inside }, 'punctuation': /^\s*=\s*['"]|['"]\s*$/, 'attr-value': { pattern: /.+/i, inside: Prism.languages.css } }, alias: 'language-css' } }, Prism.languages.markup.tag); } ; Prism.languages.clike = { 'comment': [ { pattern: /(^|[^\\])\/\*[\w\W]*?\*\//, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true } ], 'string': { pattern: /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, 'class-name': { pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i, lookbehind: true, inside: { punctuation: /(\.|\\)/ } }, 'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, 'boolean': /\b(true|false)\b/, 'function': /[a-z0-9_]+(?=\()/i, 'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i, 'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, 'punctuation': /[{}[\];(),.:]/ }; Prism.languages.javascript = Prism.languages.extend('clike', { 'keyword': /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/, 'number': /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/, // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444) 'function': /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i }); Prism.languages.insertBefore('javascript', 'keyword', { 'regex': { pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/, lookbehind: true, greedy: true } }); Prism.languages.insertBefore('javascript', 'string', { 'template-string': { pattern: /`(?:\\\\|\\?[^\\])*?`/, greedy: true, inside: { 'interpolation': { pattern: /\$\{[^}]+\}/, inside: { 'interpolation-punctuation': { pattern: /^\$\{|\}$/, alias: 'punctuation' }, rest: Prism.languages.javascript } }, 'string': /[\s\S]+/ } } }); if (Prism.languages.markup) { Prism.languages.insertBefore('markup', 'tag', { 'script': { pattern: /(<script[\w\W]*?>)[\w\W]*?(?=<\/script>)/i, lookbehind: true, inside: Prism.languages.javascript, alias: 'language-javascript' } }); } Prism.languages.js = Prism.languages.javascript;
the_stack
import { path, homeDir, crypto, fs, readFileUtf8Sync, tls, } from "./adapter.node"; import * as errors from "./errors"; import {getCredentialsPath, readCredentialsFile} from "./credentials"; import * as platform from "./platform"; const EDGEDB_PORT = 5656; export type Address = string | [string, number]; interface PartiallyNormalizedConfig { addrs: Address[]; user: string; password?: string; database: string; serverSettings?: {[key: string]: string}; tlsOptions?: tls.ConnectionOptions; // true if the program is run in a directory with `edgedb.toml` inProject: boolean; // true if the connection params were initialized from a project fromProject: boolean; // true if any of the connection params were sourced from environment fromEnv: boolean; } export interface NormalizedConnectConfig extends PartiallyNormalizedConfig { connectTimeout?: number; commandTimeout?: number; waitUntilAvailable: number; logging: boolean; } export interface ConnectConfig { dsn?: string; host?: string | string[]; port?: number | number[]; user?: string; password?: string; database?: string; timeout?: number; commandTimeout?: number; waitUntilAvailable?: number; serverSettings?: any; tlsCAFile?: string; tlsVerifyHostname?: boolean; logging?: boolean; } function mapParseInt(x: any): number { const res = parseInt(x, 10); if (isNaN(res)) { throw new Error( "could not convert " + JSON.stringify(x) + " to an integer" ); } return res; } function parseVerifyHostname(s: string): boolean { switch (s.toLowerCase()) { case "true": case "t": case "yes": case "y": case "on": case "1": return true; case "false": case "f": case "no": case "n": case "off": case "0": return false; default: throw new Error(`invalid tls_verify_hostname value: ${s}`); } } export function parseConnectArguments( opts: ConnectConfig = {} ): NormalizedConnectConfig { if (opts.commandTimeout != null) { if (typeof opts.commandTimeout !== "number" || opts.commandTimeout < 0) { throw new Error( "invalid commandTimeout value: " + "expected greater than 0 float (got " + JSON.stringify(opts.commandTimeout) + ")" ); } } const cwd = process.cwd(); const inProject = fs.existsSync(path.join(cwd, "edgedb.toml")); return { ...parseConnectDsnAndArgs(opts, cwd, inProject), connectTimeout: opts.timeout, commandTimeout: opts.commandTimeout, waitUntilAvailable: opts.waitUntilAvailable ?? 30_000, logging: opts.logging ?? true, }; } function stashPath(projectDir: string): string { let projectPath = fs.realpathSync(projectDir); if (platform.isWindows && !projectPath.startsWith("\\\\")) { projectPath = "\\\\?\\" + projectPath; } const hash = crypto.createHash("sha1").update(projectPath).digest("hex"); const baseName = path.basename(projectPath); const dirName = baseName + "-" + hash; return platform.searchConfigDir("projects", dirName); } function parseConnectDsnAndArgs( { dsn, host, port, user, password, database, tlsCAFile, tlsVerifyHostname, serverSettings, // @ts-ignore server_settings, }: ConnectConfig, cwd: string, inProject: boolean ): PartiallyNormalizedConfig { let usingCredentials: boolean = false; const tlsCAData: string[] = []; let fromProject = false; let fromEnv = false; if (server_settings) { // tslint:disable-next-line: no-console console.warn( "The `server_settings` parameter is deprecated and is scheduled " + "to be removed. Use `serverSettings` instead." ); serverSettings = server_settings; } if ( !( dsn || host || port || process.env.EDGEDB_HOST || process.env.EDGEDB_PORT ) ) { if (process.env.EDGEDB_INSTANCE) { dsn = process.env.EDGEDB_INSTANCE; fromEnv ||= true; } else { if (!inProject) { throw new errors.ClientConnectionError( "no `edgedb.toml` found and no connection options specified" + " either via arguments to connect API or via environment" + " variables EDGEDB_HOST/EDGEDB_PORT or EDGEDB_INSTANCE" ); } const stashDir = stashPath(cwd); if (fs.existsSync(stashDir)) { dsn = readFileUtf8Sync(path.join(stashDir, "instance-name")).trim(); } else { throw new errors.ClientConnectionError( "Found `edgedb.toml` but the project is not initialized. " + "Run `edgedb project init`." ); } fromProject = true; } } if (dsn && /^edgedb:\/\//.test(dsn)) { // Comma-separated hosts and empty hosts cannot always be parsed // correctly with new URL(), so if we detect them, we need to replace the // whole host before parsing. The comma-separated host list can then be // handled in the same way as if it came from any other source // (such as EDGEDB_HOST). const dsnHostMatch = /\/\/(.+?@)?(.*?)([/?])/.exec(dsn); let dsnHost: string | null = null; if (dsnHostMatch && typeof dsnHostMatch[2] === "string") { dsnHost = dsnHostMatch[2]; if (dsnHost === "" || dsnHost.includes(",")) { const rep = dsnHostMatch[1] ? "@" : "//"; const suffix = dsnHostMatch[3]; dsn = dsn.replace( rep + dsnHost + suffix, rep + "replaced_host" + suffix ); } else { dsnHost = null; } } const parsed = new URL(dsn); if (typeof parsed.protocol === "string") { if (parsed.protocol !== "edgedb:") { throw new Error( "invalid DSN: scheme is expected to be 'edgedb', got " + (parsed.protocol ? parsed.protocol.slice(0, -1) : parsed.protocol) ); } } else { throw new Error("invalid DSN: scheme is expected to be 'edgedb'"); } if (!host && parsed.host) { // if the host was replaced, use the original value to // process comma-separated hosts if (dsnHost !== null) { if (dsnHost !== "") { let portFromEnv: boolean; [host, port, portFromEnv] = parseHostlist(dsnHost, port); fromEnv ||= portFromEnv; } } else { host = parsed.hostname ?? undefined; if (parsed.port) { port = parseInt(parsed.port, 10); } } } if (parsed.pathname && database == null) { database = parsed.pathname; if (database[0] === "/") { database = database.slice(1); } } if (parsed.username && user == null) { user = parsed.username; } if (parsed.password && password == null) { password = parsed.password; } // extract the connection parameters from the query if (parsed.searchParams) { if (parsed.searchParams.has("port")) { const pport = parsed.searchParams.get("port")!; if (!port && pport) { port = pport.split(",").map(mapParseInt); } parsed.searchParams.delete("port"); } if (parsed.searchParams.has("host")) { const phost = parsed.searchParams.get("host")!; if (!host && phost) { let portFromEnv: boolean; [host, port, portFromEnv] = parseHostlist(phost, port); fromEnv ||= portFromEnv; } parsed.searchParams.delete("host"); } const parsedQ: Map<string, string> = new Map(); // when given multiple params of the same name, keep the last one only for (const [key, param] of parsed.searchParams.entries()) { parsedQ.set(key, param); } if (parsedQ.has("dbname")) { if (!database) { database = parsedQ.get("dbname"); } parsedQ.delete("dbname"); } if (parsedQ.has("database")) { if (!database) { database = parsedQ.get("database"); } parsedQ.delete("database"); } if (parsedQ.has("user")) { if (!user) { user = parsedQ.get("user"); } parsedQ.delete("user"); } if (parsedQ.has("password")) { if (!password) { password = parsedQ.get("password"); } parsedQ.delete("password"); } if (parsedQ.has("tls_cert_file")) { if (!tlsCAFile) { tlsCAFile = parsedQ.get("tls_cert_file"); } parsedQ.delete("tls_cert_file"); } if (parsedQ.has("tls_verify_hostname")) { if (tlsVerifyHostname == null) { tlsVerifyHostname = parseVerifyHostname( parsedQ.get("tls_verify_hostname") || "" ); } parsedQ.delete("tls_verify_hostname"); } // if there are more query params left, interpret them as serverSettings if (parsedQ.size) { if (serverSettings == null) { serverSettings = {}; } for (const [key, val] of parsedQ) { serverSettings[key] = val; } } } } else if (dsn) { if (!/^[A-Za-z_][A-Za-z_0-9]*$/.test(dsn)) { throw Error( `dsn "${dsn}" is neither a edgedb:// URI nor valid instance name` ); } usingCredentials = true; const credentialsFile = getCredentialsPath(dsn); const credentials = readCredentialsFile(credentialsFile); port = credentials.port; user = credentials.user; if (host == null && "host" in credentials) { host = credentials.host; } if (password == null && "password" in credentials) { password = credentials.password; } if (database == null && "database" in credentials) { database = credentials.database; } if (tlsCAFile == null && credentials.tlsCAData != null) { tlsCAData.push(credentials.tlsCAData); } if (tlsVerifyHostname == null && "tlsVerifyHostname" in credentials) { tlsVerifyHostname = credentials.tlsVerifyHostname; } } // figure out host setting if (!host) { const hostspec = process.env.EDGEDB_HOST; if (hostspec) { fromEnv ||= true; const hl = parseHostlist(hostspec, port); host = hl[0]; port = hl[1]; } else { host = ["localhost"]; } } else if (!(host instanceof Array)) { host = [host]; } // figure out port setting if (!port) { const portspec = process.env.EDGEDB_PORT; if (portspec) { fromEnv ||= true; port = portspec.split(",").map(mapParseInt); } else { port = EDGEDB_PORT; } } // validate and normalize host and port port = validatePortSpec(host, port); if (!user) { user = process.env.EDGEDB_USER; fromEnv ||= !!user; } if (!user) { user = "edgedb"; } if (!password) { password = process.env.EDGEDB_PASSWORD; fromEnv ||= !!password; } if (!database) { database = process.env.EDGEDB_DATABASE; fromEnv ||= !!database; } if (!database) { database = "edgedb"; } const addrs: Address[] = []; for (let i = 0; i < host.length; i++) { const h = host[i]; const p = port[i]; if (h[0] === "/") { // UNIX socket name throw new Error("UNIX sockets are not supported"); } else { // TCP host/port addrs.push([h, p]); } } if (addrs.length === 0) { throw new Error("could not determine the database address to connect to"); } let tlsOptions: tls.ConnectionOptions | undefined; if (tlsCAFile) { tlsCAData.push(readFileUtf8Sync(tlsCAFile)); } tlsOptions = {ALPNProtocols: ["edgedb-binary"]}; if (tlsCAData.length !== 0) { if (tlsVerifyHostname == null) { tlsVerifyHostname = false; } // this option replaces the system CA certificates with the one provided. tlsOptions.ca = tlsCAData; } else { if (tlsVerifyHostname == null) { tlsVerifyHostname = true; } } if (!tlsVerifyHostname) { tlsOptions.checkServerIdentity = (hostname: string, cert: any) => { const err = tls.checkServerIdentity(hostname, cert); if (err === undefined) { return undefined; } // ignore failed hostname check if (err.message.startsWith("Hostname/IP does not match certificate")) { return undefined; } return err; }; } return { addrs, user, password, database, serverSettings, tlsOptions, fromProject, fromEnv, inProject, }; } function parseHostlist( hostlist: string | string[], inputPort?: number | number[] ): [string[], number[], boolean] { let hostspecs: string[]; const hosts: string[] = []; const hostlistPorts: number[] = []; let defaultPort: number[] = []; let ports: number[] = []; let fromEnv = false; if (hostlist instanceof Array) { hostspecs = hostlist; } else { hostspecs = hostlist.split(","); } if (!inputPort) { const portspec = process.env.EDGEDB_PORT; if (portspec) { fromEnv = true; defaultPort = portspec.split(",").map(mapParseInt); defaultPort = validatePortSpec(hostspecs, defaultPort); } else { defaultPort = validatePortSpec(hostspecs, EDGEDB_PORT); } } else { ports = validatePortSpec(hostspecs, inputPort); } for (let i = 0; i < hostspecs.length; i++) { const [addr, hostspecPort] = hostspecs[i].split(":"); hosts.push(addr); if (!inputPort) { if (hostspecPort) { hostlistPorts.push(mapParseInt(hostspecPort)); } else { hostlistPorts.push(defaultPort[i]); } } } if (!inputPort) { ports = hostlistPorts; } return [hosts, ports, fromEnv]; } function validatePortSpec( inputHosts: string[], inputPort: number | number[] ): number[] { let ports: number[]; if (inputPort instanceof Array) { // If there is a list of ports, its length must // match that of the host list. if (inputPort.length !== inputHosts.length) { throw new Error( "could not match " + inputPort.length + " port numbers to " + inputHosts.length + " hosts" ); } ports = inputPort; } else { ports = Array(inputHosts.length).fill(inputPort); } // defensively convert ports into integers ports = ports.map(mapParseInt); return ports; }
the_stack
import { DecimalPipe } from '@angular/common'; import { Component } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { ModalController, NavController, NavParams, Platform } from 'ionic-angular'; import * as _ from 'lodash'; import * as moment from 'moment'; import { Subscription } from 'rxjs'; // Pages import { CoinAndWalletSelectorPage } from '../../pages/coin-and-wallet-selector/coin-and-wallet-selector'; import { ExchangeCheckoutPage } from '../../pages/exchange-crypto/exchange-checkout/exchange-checkout'; import { ExchangeCryptoSettingsPage } from '../../pages/exchange-crypto/exchange-crypto-settings/exchange-crypto-settings'; import { ChangellyPage } from '../../pages/integrations/changelly/changelly'; import { OneInchPage } from '../../pages/integrations/one-inch/one-inch'; import { AmountPage } from '../../pages/send/amount/amount'; import { TokenSwapApprovePage } from '../../pages/token-swap/token-swap-approve/token-swap-approve'; import { TokenSwapCheckoutPage } from '../../pages/token-swap/token-swap-checkout/token-swap-checkout'; // Providers import { ActionSheetProvider } from '../../providers/action-sheet/action-sheet'; import { ChangellyProvider } from '../../providers/changelly/changelly'; import { CurrencyProvider } from '../../providers/currency/currency'; import { ExchangeCryptoProvider } from '../../providers/exchange-crypto/exchange-crypto'; import { FeeProvider } from '../../providers/fee/fee'; import { LocationProvider } from '../../providers/location/location'; import { Logger } from '../../providers/logger/logger'; import { OnGoingProcessProvider } from '../../providers/on-going-process/on-going-process'; import { ProfileProvider } from '../../providers/profile/profile'; import { ThemeProvider } from '../../providers/theme/theme'; import { TxFormatProvider } from '../../providers/tx-format/tx-format'; import { WalletProvider } from '../../providers/wallet/wallet'; import { ConfigProvider } from '../../providers/config/config'; import { ExternalLinkProvider } from '../../providers/external-link/external-link'; import { OneInchProvider } from '../../providers/one-inch/one-inch'; import { ReplaceParametersProvider } from '../../providers/replace-parameters/replace-parameters'; @Component({ selector: 'page-exchange-crypto', templateUrl: 'exchange-crypto.html' }) export class ExchangeCryptoPage { private onResumeSubscription: Subscription; private onPauseSubscription: Subscription; public isOpenSelectorFrom: boolean; public isOpenSelectorTo: boolean; public allWallets; public toWallets; public fromWallets; public loading: boolean; public changellySwapTxs: any[]; public useSendMax: boolean; public sendMaxInfo; public exchangeToUse: string; public fromWalletSelectorTitle: string; public toWalletSelectorTitle: string; public fromWalletSelected; public toWalletSelected; public toWalletSelectedByDefault; public amountFrom: number; public amountTo: number; public minAmount: number; public maxAmount: number; public fixedRateId: string; public rate: number; public estimatedFee: number; public isAvailable: { changelly?: boolean; oneInch?: boolean; }; private exchangeCryptoSupportedCoins: any[]; private changellySupportedCoins: string[]; // Supported by Changelly and Bitpay // One Inch public oneInchSwapTxs: any[]; public showApproveButton: boolean; public showPendingApprove: boolean; public approveButtonText: string; private fromWalletAllowanceOk: boolean; private approveTxId: string; private approveSpenderAddress: string; private timeout: NodeJS.Timeout; public oneInchSupportedCoins: any[]; // Supported by oneInch and Bitpay public oneInchAllSupportedCoins: any[]; public oneInchAllSupportedCoinsSymbols: string[]; public oneInchSupportedCoinsFull; public slippageValues: any[]; public selectedSlippage: number; private referrerFee: number; public fromToken; public fromTokenBalance; public toToken; public swapData; constructor( private actionSheetProvider: ActionSheetProvider, private logger: Logger, private modalCtrl: ModalController, private changellyProvider: ChangellyProvider, private navCtrl: NavController, private navParams: NavParams, private onGoingProcessProvider: OnGoingProcessProvider, private platform: Platform, private profileProvider: ProfileProvider, private translate: TranslateService, public currencyProvider: CurrencyProvider, private txFormatProvider: TxFormatProvider, private exchangeCryptoProvider: ExchangeCryptoProvider, private feeProvider: FeeProvider, private walletProvider: WalletProvider, public themeProvider: ThemeProvider, private oneInchProvider: OneInchProvider, private configProvider: ConfigProvider, private externalLinkProvider: ExternalLinkProvider, private replaceParametersProvider: ReplaceParametersProvider, public decimalPipe: DecimalPipe, private locationProvider: LocationProvider ) { this.allWallets = []; this.toWallets = []; this.fromWallets = []; this.loading = false; this.exchangeCryptoSupportedCoins = []; this.oneInchSupportedCoins = []; // Supported by oneInch and Bitpay this.oneInchAllSupportedCoins = []; this.oneInchAllSupportedCoinsSymbols = []; this.showApproveButton = false; this.fromWalletAllowanceOk = false; this.fromWalletSelectorTitle = this.translate.instant( 'Select Source Wallet' ); this.toWalletSelectorTitle = this.translate.instant( 'Select Destination Wallet' ); this.isAvailable = { changelly: true, oneInch: true }; this.onGoingProcessProvider.set('exchangeCryptoInit'); this.slippageValues = [ { value: 0.1, selected: false }, { value: 0.5, selected: false }, { value: 1, selected: true }, { value: 5, selected: false } ]; this.setSlippage(1); this.exchangeCryptoProvider.getSwapTxs().then(res => { // TODO: unify getSwapTxs and review the html this.changellySwapTxs = res.changellySwapTxs; }); this.exchangeCryptoProvider.getSwapTxs().then(res => { this.oneInchSwapTxs = res.oneInchSwapTxs; }); } ngOnDestroy() { if (this.timeout) clearTimeout(this.timeout); this.onResumeSubscription.unsubscribe(); this.onPauseSubscription.unsubscribe(); } ionViewDidLoad() { this.logger.info('Loaded: ExchangeCryptoPage'); this.getExchangesCurrencies(); this.onPauseSubscription = this.platform.pause.subscribe(() => { this.logger.debug('Swap - onPauseSubscription called'); if (this.timeout) { this.logger.debug('Swap - onPauseSubscription clearing timeout'); clearTimeout(this.timeout); } }); this.onResumeSubscription = this.platform.resume.subscribe(() => { this.logger.debug('Swap - onResumeSubscription called'); if (this.exchangeToUse == '1inch' && !this.fromWalletAllowanceOk) { this.logger.debug('Swap - onResumeSubscription checking Confirmation'); this.checkConfirmation(1000); } }); } private async getExchangesCurrencies() { let country; const reflect = promiseObj => { return promiseObj.promise.then( v => { return { exchange: promiseObj.exchange, status: 'ok', data: v }; }, error => { return { exchange: promiseObj.exchange, status: 'failed', reason: error }; } ); }; const promises = [ { exchange: 'changelly', promise: this.changellyProvider.getCurrencies(true) } ]; try { country = await this.locationProvider.getCountry(); const opts = { country }; this.logger.debug(`Setting available currencies for country: ${country}`); this.isAvailable.oneInch = await this.exchangeCryptoProvider.checkServiceAvailability( '1inch', opts ); this.logger.debug(`1Inch isAvailable: ${this.isAvailable.oneInch}`); } catch (e) { this.logger.warn("It was not possible to get the user's country.", e); } if (this.isAvailable.oneInch) { promises.push({ exchange: '1inch', promise: this.oneInchProvider.getCurrencies1inch() }); } const results = await Promise.all(promises.map(reflect)); const successfulPromises = results.filter(p => p.status === 'ok'); const failedPromises = results.filter(p => p.status === 'failed'); failedPromises.forEach(promise => { switch (promise.exchange) { case '1inch': this.logger.error('1Inch getCurrencies Error'); if (promise.reason && promise.reason.message) this.logger.error(promise.reason.message); break; case 'changelly': this.logger.error('Changelly getCurrencies Error'); if (promise.reason && promise.reason.message) this.logger.error(promise.reason.message); break; default: break; } }); successfulPromises.forEach(promise => { switch (promise.exchange) { case '1inch': if (!promise.data || !promise.data.tokens) { this.logger.error('1Inch getCurrencies Error'); return; } this.oneInchSupportedCoins; this.oneInchAllSupportedCoins = []; this.oneInchAllSupportedCoinsSymbols = []; _.forEach(Object.keys(promise.data.tokens), key => { this.oneInchAllSupportedCoins.push(promise.data.tokens[key]); this.oneInchAllSupportedCoinsSymbols.push( promise.data.tokens[key].symbol.toLowerCase() ); }); if ( _.isArray(this.oneInchAllSupportedCoins) && this.oneInchAllSupportedCoins.length > 0 ) { this.oneInchSupportedCoins = _.intersection( this.currencyProvider.getAvailableCoins(), this.oneInchAllSupportedCoinsSymbols ); } this.oneInchSupportedCoinsFull = this.oneInchAllSupportedCoins.filter( token => { return this.oneInchSupportedCoins.includes( token.symbol.toLowerCase() ); } ); this.logger.debug( '1Inch supportedCoins: ' + this.oneInchSupportedCoins ); break; case 'changelly': if (promise.data.error) { this.logger.error( 'Changelly getCurrencies Error: ' + promise.data.error.message ); return; } if ( promise.data && promise.data.result && _.isArray(promise.data.result) && promise.data.result.length > 0 ) { const supportedCoinsWithFixRateEnabled = promise.data.result .filter(coin => coin.enabled && coin.fixRateEnabled) .map(({ name }) => name); // TODO: add support to float-rate coins supported by Changelly this.changellySupportedCoins = _.intersection( this.currencyProvider.getAvailableCoins(), supportedCoinsWithFixRateEnabled ); const coinsToRemove = country == 'US' ? ['xrp'] : []; coinsToRemove.forEach((coin: string) => { const index = this.changellySupportedCoins.indexOf(coin); if (index > -1) { this.logger.debug( `Removing ${coin.toUpperCase()} from Changelly supported coins` ); this.changellySupportedCoins.splice(index, 1); } }); } this.logger.debug( 'Changelly supportedCoins: ' + this.changellySupportedCoins ); break; default: break; } }); this.exchangeCryptoSupportedCoins = [ ...new Set([ ...this.changellySupportedCoins, ...this.oneInchSupportedCoins ]) ]; // Union between all arrays this.allWallets = this.profileProvider.getWallets({ network: 'livenet', onlyComplete: true, coin: this.exchangeCryptoSupportedCoins, backedUp: true }); this.onGoingProcessProvider.clear(); if (_.isEmpty(this.allWallets)) { this.showErrorAndBack( null, this.translate.instant( 'There are no wallets available that meet the requirements to operate with our supported exchanges' ) ); return; } this.fromWallets = this.allWallets.filter(w => { return w.cachedStatus && w.cachedStatus.availableBalanceSat > 0; }); if (_.isEmpty(this.fromWallets)) { this.showErrorAndBack( null, this.translate.instant('No wallets with funds') ); return; } if (this.navParams.data.walletId) { const wallet = this.profileProvider.getWallet( this.navParams.data.walletId ); if (wallet.network != 'livenet') { this.showErrorAndBack( null, this.translate.instant('Unsupported network') ); return; } if ( !wallet.coin || !this.exchangeCryptoSupportedCoins.includes(wallet.coin) ) { this.showErrorAndBack( null, this.translate.instant( 'Currently our partners does not support exchanges with the selected coin' ) ); return; } else { if ( wallet.cachedStatus && wallet.cachedStatus.spendableAmount && wallet.cachedStatus.spendableAmount > 0 ) { this.onFromWalletSelect(wallet); } else { this.toWalletSelectedByDefault = wallet; // Use navParams wallet as default let supportedCoins = []; if (this.oneInchSupportedCoins.includes(wallet.coin)) supportedCoins = supportedCoins.concat(this.oneInchSupportedCoins); if (this.changellySupportedCoins.includes(wallet.coin)) supportedCoins = _.uniq( supportedCoins.concat(this.changellySupportedCoins) ); this.allWallets = this.profileProvider.getWallets({ network: 'livenet', onlyComplete: true, coin: supportedCoins, backedUp: true }); if (_.isEmpty(this.allWallets)) { this.showErrorAndBack( null, this.translate.instant( 'There are no wallets available that meet the requirements to operate with our supported exchanges' ) ); return; } this.fromWallets = this.allWallets.filter(w => { return w.cachedStatus && w.cachedStatus.availableBalanceSat > 0; }); if (_.isEmpty(this.fromWallets)) { this.showErrorAndBack( null, this.translate.instant('No wallets with funds') ); return; } this.onToWalletSelect(wallet); } } } } public showFromWallets(): void { let walletsForActionSheet = []; let selectedWalletId: string; this.isOpenSelectorFrom = true; walletsForActionSheet = this.fromWallets; selectedWalletId = this.fromWalletSelected ? this.fromWalletSelected.id : null; const walletSelector = this.actionSheetProvider.createWalletSelector({ wallets: walletsForActionSheet, selectedWalletId, title: this.fromWalletSelectorTitle }); walletSelector.present(); walletSelector.onDidDismiss(wallet => { this.isOpenSelectorFrom = false; this.isOpenSelectorTo = false; setTimeout(() => { if (!_.isEmpty(wallet)) this.onFromWalletSelect(wallet); }, 100); }); } public showToWallets(): void { if (this.toWalletSelectedByDefault || !this.fromWalletSelected) return; this.isOpenSelectorTo = true; let supportedCoins: any[]; let showOneInchTokensSearchBtn: boolean = false; if ( this.oneInchSupportedCoins.includes(this.fromWalletSelected.coin) && this.changellySupportedCoins.includes(this.fromWalletSelected.coin) ) { supportedCoins = _.clone(this.exchangeCryptoSupportedCoins); showOneInchTokensSearchBtn = true; } else if ( this.oneInchSupportedCoins.includes(this.fromWalletSelected.coin) ) { supportedCoins = _.clone(this.oneInchSupportedCoins); showOneInchTokensSearchBtn = true; } else if ( this.changellySupportedCoins.includes(this.fromWalletSelected.coin) ) { supportedCoins = _.clone(this.changellySupportedCoins); showOneInchTokensSearchBtn = false; } const index = supportedCoins.indexOf(this.fromWalletSelected.coin); if (index > -1) { supportedCoins.splice(index, 1); } const bitpaySupportedTokens: string[] = this.currencyProvider .getBitpaySupportedTokens() .map(token => token.symbol.toLowerCase()); const oneInchAllSupportedCoins = this.oneInchAllSupportedCoins.filter( token => { return ![ 'eth', this.fromWalletSelected.coin, ...bitpaySupportedTokens ].includes(token.symbol.toLowerCase()); } ); let modal = this.modalCtrl.create( CoinAndWalletSelectorPage, { walletSelectorTitle: this.toWalletSelectorTitle, coinSelectorTitle: this.translate.instant('Select Destination Coin'), useAsModal: true, supportedCoins, removeSpecificWalletId: this.fromWalletSelected.id, onlyLivenet: true, oneInchAllSupportedCoins, showOneInchTokensSearchBtn }, { showBackdrop: true, enableBackdropDismiss: true } ); modal.present(); modal.onDidDismiss(data => { this.isOpenSelectorFrom = false; this.isOpenSelectorTo = false; if (data) { setTimeout(() => { if (!_.isEmpty(data.wallet)) { if (data.selectedToken) { this.onToWalletSelect(data.wallet, data.selectedToken); } else { this.onToWalletSelect(data.wallet); } } }, 100); } }); } private setExchangeToUse() { if (!this.fromWalletSelected || !this.toWalletSelected) return; const fromCoin = this.fromWalletSelected.coin; const toCoin = this.toToken ? this.toToken.symbol.toLowerCase() : this.toWalletSelected.coin; // Changelly has priority over 1inch if ( this.changellySupportedCoins.length > 0 && this.changellySupportedCoins.includes(fromCoin) && this.changellySupportedCoins.includes(toCoin) ) { this.exchangeToUse = 'changelly'; } else if ( this.oneInchAllSupportedCoinsSymbols.length > 0 && this.oneInchAllSupportedCoinsSymbols.includes(fromCoin) && this.oneInchAllSupportedCoinsSymbols.includes(toCoin) ) { this.exchangeToUse = '1inch'; } else { let msg = this.translate.instant( 'Currently none of our partners accept the exchange of the selected pair: ' ) + fromCoin + '_' + toCoin; this.showErrorAndBack(null, msg, true); return; } this.logger.debug('Exchange to use: ' + this.exchangeToUse); if (this.exchangeToUse == '1inch' && !this.isAvailable.oneInch) { const oneInchDisabledWarningSheet = this.actionSheetProvider.createInfoSheet( '1inch-disabled-warning' ); oneInchDisabledWarningSheet.present(); oneInchDisabledWarningSheet.onDidDismiss(() => { // Cleaning view if (!this.toWalletSelectedByDefault) { this.toWalletSelected = null; this.toToken = null; } this.fromWalletSelected = null; this.fromToken = null; this.amountFrom = null; this.amountTo = null; this.useSendMax = null; this.rate = null; this.fixedRateId = null; this.exchangeToUse = null; this.showPendingApprove = false; }); return; } switch (this.exchangeToUse) { case '1inch': this.onGoingProcessProvider.set('Verifiyng allowances and balances...'); if (this.timeout) clearTimeout(this.timeout); this.fromToken = this.oneInchSupportedCoinsFull.filter(token => { return ( token.symbol.toLowerCase() == this.fromWalletSelected.coin.toLowerCase() ); })[0]; this.verifyAllowances(); // this.oneInchGetRates() is inside this function break; case 'changelly': this.changellyGetRates(); break; } } public onFromWalletSelect(wallet): void { this.fromWalletSelected = wallet; if (!this.toWalletSelectedByDefault) { this.toWalletSelected = null; // Clear variable to select destination wallet again this.toToken = null; } this.amountFrom = null; // Clear amount and rate to avoid mistakes this.amountTo = null; this.useSendMax = null; this.rate = null; this.fixedRateId = null; this.exchangeToUse = null; this.showPendingApprove = false; this.setExchangeToUse(); } public onToWalletSelect(wallet, selectedToken?): void { // selectedToken: token from 1inch this.toWalletSelected = wallet; if (selectedToken) { this.toToken = selectedToken; this.toToken.isCustomToken = true; } else { this.toToken = null; } const isERCToken = this.currencyProvider.isERCToken( this.toWalletSelected.coin ); if ( isERCToken || (this.toWalletSelected.coin == 'eth' && selectedToken && selectedToken.symbol) ) { const coin = isERCToken ? this.toWalletSelected.coin.toUpperCase() : selectedToken.symbol; const linkedEthWalletName = isERCToken ? this.toWalletSelected.linkedEthWalletName : this.toWalletSelected.name; const infoSheet = this.actionSheetProvider.createInfoSheet( 'erc20-eth-fee-info', { coin, linkedEthWalletName } ); infoSheet.present(); } this.setExchangeToUse(); } private changellyGetRates() { this.amountTo = null; this.rate = null; if (!this.fromWalletSelected || !this.toWalletSelected || !this.amountFrom) return; this.loading = true; let pair = this.fromWalletSelected.coin + '_' + this.toWalletSelected.coin; this.logger.debug('Updating max and min with pair: ' + pair); const data = { coinFrom: this.fromWalletSelected.coin, coinTo: this.toWalletSelected.coin }; this.changellyProvider .getPairsParams(this.fromWalletSelected, data) .then(async data => { if (data.error) { let secondBtnText, url, msg = null; msg = 'Changelly getPairsParams Error: ' + data.error.message; if ( Math.abs(data.error.code) == 32602 && data.error.message.indexOf('Invalid currency:') != -1 ) { msg = `${data.error.message}. This is a temporary Changelly decision. If you have further questions please reach out to them.`; secondBtnText = this.translate.instant('Submit a ticket'); url = 'https://support.changelly.com/en/support/tickets/new'; } this.showErrorAndBack(null, msg, true, secondBtnText, url); return; } if ( data.result && data.result[0] && Number(data.result[0].maxAmountFixed) <= 0 ) { const msg = `Changelly has temporarily disabled ${this.fromWalletSelected.coin}-${this.toWalletSelected.coin} pair. If you have further questions please reach out to them.`; const secondBtnText = this.translate.instant('Submit a ticket'); const url = 'https://support.changelly.com/en/support/tickets/new'; this.showErrorAndBack(null, msg, true, secondBtnText, url); return; } this.minAmount = Number(data.result[0].minAmountFixed); this.maxAmount = Number(data.result[0].maxAmountFixed); this.logger.debug( `Min amount: ${this.minAmount} - Max amount: ${this.maxAmount}` ); if (this.useSendMax && this.shouldUseSendMax()) { this.onGoingProcessProvider.set('calculatingSendMax'); this.sendMaxInfo = await this.getSendMaxInfo(); if (this.sendMaxInfo) { this.logger.debug('Send max info', this.sendMaxInfo); this.amountFrom = this.txFormatProvider.satToUnit( this.sendMaxInfo.amount, this.fromWalletSelected.coin ); this.estimatedFee = this.txFormatProvider.satToUnit( this.sendMaxInfo.fee, this.fromWalletSelected.coin ); } } this.onGoingProcessProvider.clear(); if (this.amountFrom > this.maxAmount) { const errorActionSheet = this.actionSheetProvider.createInfoSheet( 'max-amount-allowed', { maxAmount: this.maxAmount, coin: this.fromWalletSelected.coin.toUpperCase() } ); errorActionSheet.present(); errorActionSheet.onDidDismiss(option => { this.loading = false; if (option) { this.amountFrom = this.maxAmount; this.useSendMax = null; this.updateReceivingAmount(); } }); return; } if (this.amountFrom < this.minAmount) { if (this.useSendMax && this.shouldUseSendMax()) { let msg; if (this.sendMaxInfo) { const warningMsg = this.exchangeCryptoProvider.verifyExcludedUtxos( this.fromWalletSelected.coin, this.sendMaxInfo ); msg = !_.isEmpty(warningMsg) ? warningMsg : ''; } const errorActionSheet = this.actionSheetProvider.createInfoSheet( 'send-max-min-amount', { amount: this.amountFrom, fee: this.estimatedFee, minAmount: this.minAmount, coin: this.fromWalletSelected.coin.toUpperCase(), msg } ); errorActionSheet.present(); errorActionSheet.onDidDismiss(() => { this.loading = false; this.useSendMax = null; this.amountFrom = null; this.amountTo = null; this.estimatedFee = null; this.sendMaxInfo = null; this.rate = null; this.fixedRateId = null; }); return; } else { const errorActionSheet = this.actionSheetProvider.createInfoSheet( 'min-amount-allowed', { minAmount: this.minAmount, coin: this.fromWalletSelected.coin.toUpperCase() } ); errorActionSheet.present(); errorActionSheet.onDidDismiss(option => { this.loading = false; if (option) { this.amountFrom = this.minAmount; this.useSendMax = null; this.sendMaxInfo = null; this.updateReceivingAmount(); } }); return; } } this.updateReceivingAmount(); }) .catch(err => { this.logger.error('Changelly getPairsParams Error: ', err); this.showErrorAndBack( null, this.translate.instant( 'Changelly is not available at this moment. Please, try again later.' ) ); }); } private async oneInchGetRates() { this.amountTo = null; this.rate = null; if (!this.fromWalletSelected || !this.toWalletSelected || !this.amountFrom) return; if (this.useSendMax && this.fromWalletSelected.coin == 'eth') { this.useSendMax = null; this.amountFrom = null; this.amountTo = null; this.showErrorAndBack( null, this.translate.instant( 'Currently the "Send Max" feature is not supported for ETH swaps on the 1Inch exchange. Try entering the amount manually.' ), true ); return; } if ( this.fromWalletSelected.cachedStatus && this.fromWalletSelected.cachedStatus.spendableAmount ) { const spendableAmount = this.txFormatProvider.satToUnit( this.fromWalletSelected.cachedStatus.spendableAmount, this.fromWalletSelected.coin ); if (spendableAmount < this.amountFrom && !this.useSendMax) { this.loading = false; this.amountFrom = null; this.amountTo = null; this.useSendMax = null; this.showErrorAndBack( null, this.translate.instant( 'You are trying to send more funds than you have available. Make sure you do not have funds locked by pending transaction proposals or enter a valid amount.' ), true ); return; } } this.loading = true; try { this.referrerFee = await this.oneInchProvider.getReferrerFee(); } catch (err) { if (err.error) this.logger.error('Could not get referrer fee: ', err.error); } this.logger.debug(`referrerFee setted to: ${this.referrerFee}%`); this.toToken = this.toToken && this.toToken.isCustomToken ? this.toToken : this.oneInchSupportedCoinsFull.filter(token => { return ( token.symbol.toLowerCase() == this.toWalletSelected.coin.toLowerCase() ); })[0]; // workaround to prevent scientific notation const _amount: number = this.amountFrom * 10 ** this.fromToken.decimals; const minUnitAmount: string = _amount.toLocaleString('fullwide', { useGrouping: false, maximumFractionDigits: 0 }); const data: any = { fromTokenAddress: this.fromToken.address, toTokenAddress: this.toToken.address, amount: minUnitAmount // amount in minimum unit }; if (this.referrerFee) { data.fee = this.referrerFee; // taking this fee from BWS. This percentage of fromTokenAddress token amount will be sent to referrerAddress, the rest will be used as input for a swap | min: 0; max: 3; default: 0; } this.logger.debug('quoteRequestData: ', data); this.oneInchProvider .getQuote1inch(data) .then(data => { const fromCoin = this.fromWalletSelected.coin; const toCoin = this.toToken ? this.toToken.symbol.toLowerCase() : this.toWalletSelected.coin; const pair = fromCoin + '_' + toCoin; this.logger.debug('Updating receiving amount with pair: ' + pair); this.amountTo = Number(data.toTokenAmount) / 10 ** this.toToken.decimals; this.rate = this.amountTo / this.amountFrom; this.loading = false; }) .catch(err => { this.processError1Inch(err); }); } private shouldUseSendMax() { const chain = this.currencyProvider.getAvailableChains(); return chain.includes(this.fromWalletSelected.coin); } private processError1Inch(err) { let msg = this.translate.instant( '1Inch is not available at this moment. Please, try again later.' ); this.logger.error( '1Inch getQuote1inch Error: ', err.error && err.error.message ? err.error.message : err ); if (err.error && err.error.message && _.isString(err.error.message)) { if (err.error.message.includes('cannot find path for')) { const fromCoin = this.fromWalletSelected.coin; const toCoin = this.toToken ? this.toToken.symbol.toLowerCase() : this.toWalletSelected.coin; msg = this.translate.instant( 'Currently it has not been possible to find a path that allows the transaction between the selected pair of tokens: ' ) + fromCoin + '_' + toCoin; } } this.showErrorAndBack(null, msg); } private showErrorAndBack( title: string, msg, noExit?: boolean, secondBtnText?: string, url?: string ): void { this.onGoingProcessProvider.clear(); this.loading = false; title = title ? title : this.translate.instant('Error'); this.logger.error(msg); msg = msg && msg.error && msg.error.message ? msg.error.message : msg; const errorActionSheet = this.actionSheetProvider.createInfoSheet( 'default-error', { msg, title, secondBtnText, url } ); errorActionSheet.present(); errorActionSheet.onDidDismiss(_option => { if (!noExit) this.navCtrl.pop(); }); } public openAmountModal() { let modal = this.modalCtrl.create( AmountPage, { fixedUnit: false, fromExchangeCrypto: true, walletId: this.fromWalletSelected.id, coin: this.fromWalletSelected.coin, useAsModal: true }, { showBackdrop: true, enableBackdropDismiss: true } ); modal.present(); modal.onDidDismiss(data => { if (data) { this.amountFrom = this.txFormatProvider.satToUnit( data.amount, data.coin ); this.useSendMax = data.useSendMax; switch (this.exchangeToUse) { case '1inch': this.oneInchGetRates(); break; case 'changelly': this.changellyGetRates(); break; } } }); } private updateReceivingAmount() { if ( !this.fromWalletSelected || !this.toWalletSelected || !this.amountFrom ) { this.loading = false; return; } if ( this.fromWalletSelected.cachedStatus && this.fromWalletSelected.cachedStatus.spendableAmount ) { const spendableAmount = this.txFormatProvider.satToUnit( this.fromWalletSelected.cachedStatus.spendableAmount, this.fromWalletSelected.coin ); if (spendableAmount < this.amountFrom) { this.loading = false; this.showErrorAndBack( null, this.translate.instant( 'You are trying to send more funds than you have available. Make sure you do not have funds locked by pending transaction proposals or enter a valid amount.' ), true ); return; } } const pair = this.fromWalletSelected.coin + '_' + this.toWalletSelected.coin; this.logger.debug('Updating receiving amount with pair: ' + pair); const data = { amountFrom: this.amountFrom, coinFrom: this.fromWalletSelected.coin, coinTo: this.toWalletSelected.coin }; this.changellyProvider .getFixRateForAmount(this.fromWalletSelected, data) .then(data => { if (data.error) { const msg = 'Changelly getFixRateForAmount Error: ' + data.error.message; this.showErrorAndBack(null, msg, true); return; } this.fixedRateId = data.result[0].id; this.amountTo = Number(data.result[0].amountTo); this.rate = Number(data.result[0].result); // result == rate this.loading = false; }) .catch(err => { this.logger.error('Changelly getFixRateForAmount Error: ', err); this.showErrorAndBack( null, this.translate.instant( 'Changelly is not available at this moment. Please, try again later.' ) ); }); } private getChain(coin: string): string { return this.currencyProvider.getChain(coin).toLowerCase(); } private getSendMaxInfo(): Promise<any> { return new Promise((resolve, reject) => { const feeLevel = this.fromWalletSelected.coin == 'btc' || this.getChain(this.fromWalletSelected.coin) == 'eth' ? 'priority' : this.feeProvider.getCoinCurrentFeeLevel( this.fromWalletSelected.coin ); this.feeProvider .getFeeRate( this.fromWalletSelected.coin, this.fromWalletSelected.network, feeLevel ) .then(feeRate => { this.walletProvider .getSendMaxInfo(this.fromWalletSelected, { feePerKb: feeRate, excludeUnconfirmedUtxos: true, // Do not use unconfirmed UTXOs returnInputs: true }) .then(res => { this.onGoingProcessProvider.clear(); return resolve(res); }) .catch(err => { this.onGoingProcessProvider.clear(); return reject(err); }); }); }); } public getAmountConteinerClass(length: number): string { if (length > 14) return 'fix-font-size-14'; if (length > 12) return 'fix-font-size-12'; if (length > 10) return 'fix-font-size-10'; if (length > 8) return 'fix-font-size-8'; return ''; } public canContinue(): boolean { switch (this.exchangeToUse) { case '1inch': return ( this.toWalletSelected && this.fromWalletSelected && this.fromWalletAllowanceOk && this.amountTo && this.amountFrom > 0 ); case 'changelly': return ( this.toWalletSelected && this.fromWalletSelected && this.amountTo && this.minAmount && this.maxAmount && this.amountFrom >= this.minAmount && this.amountFrom <= this.maxAmount ); default: return false; } } public goToExchangeCheckoutPage() { let data, checkoutPage; switch (this.exchangeToUse) { case '1inch': if (this.useSendMax && this.fromTokenBalance) { // Use fromTokenBalance for send max to prevent bigint issues this.amountFrom = this.txFormatProvider.satToUnit( this.fromTokenBalance, this.fromToken.symbol.toLowerCase() ); } data = { fromWalletSelectedId: this.fromWalletSelected.id, toWalletSelectedId: this.toWalletSelected.id, fromTokenSelected: this.fromToken, toTokenSelected: this.toToken, amountFrom: this.amountFrom, coinFrom: this.fromWalletSelected.coin, coinTo: this.toWalletSelected.coin, rate: this.rate, useSendMax: this.useSendMax, fromTokenBalance: this.fromTokenBalance, sendMaxInfo: this.sendMaxInfo, slippage: this.selectedSlippage, referrerFee: this.referrerFee }; checkoutPage = TokenSwapCheckoutPage; break; case 'changelly': data = { fromWalletSelectedId: this.fromWalletSelected.id, toWalletSelectedId: this.toWalletSelected.id, fixedRateId: this.fixedRateId, amountFrom: this.amountFrom, coinFrom: this.fromWalletSelected.coin, coinTo: this.toWalletSelected.coin, rate: this.rate, useSendMax: this.useSendMax, sendMaxInfo: this.sendMaxInfo }; checkoutPage = ExchangeCheckoutPage; break; default: this.logger.error( 'No exchanges matching. Exchange: ' + this.exchangeToUse ); break; } this.navCtrl.push(checkoutPage, data); } public goToExchangeHistory() { switch (this.exchangeToUse) { case '1inch': this.navCtrl.push(OneInchPage); break; case 'changelly': this.navCtrl.push(ChangellyPage); break; default: this.navCtrl.push(ExchangeCryptoSettingsPage, { // TODO: review this pages when checking 1inch allowances - use only this page? fromExchangeCryptoPage: true }); break; } } // ******************************************************* // 1Inch Exchange public setSlippage(value: number) { if (value == this.selectedSlippage) return; this.selectedSlippage = value; this.slippageValues.forEach(element => { element.selected = element.value == value ? true : false; }); } public showExchangeApproveModal() { let modal = this.modalCtrl.create( TokenSwapApprovePage, { fromWalletSelectedId: this.fromWalletSelected.id, fromTokenSelected: this.fromToken, toTokenSelected: this.toToken }, { showBackdrop: true, enableBackdropDismiss: true } ); modal.present(); modal.onWillDismiss(data => { if (data && data.txid) { this.approveTxId = data.txid; this.saveApproveData(this.approveTxId); this.checkConfirmation(15000); this.showPendingApprove = true; this.showApproveButton = false; } }); } private saveApproveData(txId: string): void { const now = moment().unix() * 1000; let newData = { walletId: this.fromWalletSelected.id, txId, date: now }; const opts = { isApprove: true }; this.oneInchProvider.saveOneInch(newData, opts).then(() => { this.logger.debug( 'Saved spender approve with walletId: ' + this.fromWalletSelected.id ); this.onGoingProcessProvider.clear(); }); } private checkConfirmation(ms: number) { this.logger.debug('Swap - checking confirmation'); this.timeout = setTimeout(() => this.verifyAllowances(), ms || 15000); } private verifyAllowances() { if ( !this.fromWalletSelected || !this.toWalletSelected || this.exchangeToUse != '1inch' ) return; this.logger.debug('Verifiying allowances...'); this.walletProvider .getAddress(this.fromWalletSelected, false) .then(async fromAddress => { if (!this.approveSpenderAddress) { const approveSpenderData: any = await this.oneInchProvider.approveSpender1inch(); if (!approveSpenderData || !approveSpenderData.address) { this.logger.error('1Inch approveSpender1inch Error'); this.showErrorAndBack( null, this.translate.instant( '1Inch is not available at this moment. Please, try again later.' ) ); return; } this.approveSpenderAddress = approveSpenderData.address; this.logger.debug( '1inch spender address: ' + this.approveSpenderAddress ); } const data = { spenderAddress: this.approveSpenderAddress, addressToCheck: fromAddress }; this.oneInchProvider .verifyAllowancesAndBalances(data) .then(allowancesData => { this.logger.debug(allowancesData[this.fromToken.address]); if ( allowancesData[this.fromToken.address] && allowancesData[this.fromToken.address].balance ) { this.fromTokenBalance = allowancesData[this.fromToken.address].balance; } if ( allowancesData[this.fromToken.address] && allowancesData[this.fromToken.address].allowance > 0 ) { this.logger.debug( 'This wallet has the necessary allowances to continue with the token swap' ); this.showApproveButton = false; this.showPendingApprove = false; this.approveButtonText = ''; this.fromWalletAllowanceOk = true; } else { // check if an approve transaction was already sent for this wallet this.oneInchProvider .getOneInchApproveData() .then(oneInchApproveData => { const approveTxs: any = {}; Object.assign(approveTxs, oneInchApproveData); if ( approveTxs && approveTxs[this.fromWalletSelected.id] && approveTxs[this.fromWalletSelected.id].txId ) { this.logger.debug( 'There is a pending transaction waiting for confirmation' ); this.showPendingApprove = true; this.fromWalletAllowanceOk = false; this.approveTxId = approveTxs[this.fromWalletSelected.id].txId; this.checkConfirmation(15000); } else { this.showPendingApprove = false; this.fromWalletAllowanceOk = false; this.showApproveButton = true; this.approveButtonText = this.replaceParametersProvider.replace( this.translate.instant(`Approve {{fromWalletCoin}}`), { fromWalletCoin: this.fromWalletSelected.coin.toUpperCase() } ); } }) .catch(err => { this.logger.error('1Inch getOneInchApproveData Error: ', err); this.showErrorAndBack( null, this.translate.instant( '1Inch is not available at this moment. Please, try again later.' ) ); return; }); } this.onGoingProcessProvider.clear(); this.oneInchGetRates(); }) .catch(err => { this.logger.error('1Inch verifyAllowancesAndBalances Error: ', err); this.showErrorAndBack( null, this.translate.instant( '1Inch is not available at this moment. Please, try again later.' ) ); return; }); }) .catch(err => { this.logger.error('Could not get fromAddress address', err); this.showErrorAndBack( null, this.translate.instant( 'There was a problem retrieving the address. Please, try again later.' ) ); return; }); } public showSlippageInfo(): void { const infoSheet = this.actionSheetProvider.createInfoSheet('slippage-info'); infoSheet.present(); infoSheet.onDidDismiss(option => { if (option) { } }); } public viewOnBlockchain(): void { let defaults = this.configProvider.getDefaults(); const blockexplorerUrl = defaults.blockExplorerUrl[this.fromWalletSelected.coin]; let url = `https://${blockexplorerUrl}tx/${this.approveTxId}`; this.externalLinkProvider.open(url); } }
the_stack
import { Action } from '@ngrx/store'; import { type } from '../../shared/ngrx/type'; import { SectionVisibility, SubmissionError, SubmissionSectionError } from './submission-objects.reducer'; import { WorkspaceitemSectionUploadFileObject } from '../../core/submission/models/workspaceitem-section-upload-file.model'; import { WorkspaceitemSectionDataType, WorkspaceitemSectionsObject } from '../../core/submission/models/workspaceitem-sections.model'; import { SubmissionObject } from '../../core/submission/models/submission-object.model'; import { SubmissionDefinitionsModel } from '../../core/config/models/config-submission-definitions.model'; import { SectionsType } from '../sections/sections-type'; import { Item } from '../../core/shared/item.model'; /** * For each action type in an action group, make a simple * enum object for all of this group's action types. * * The 'type' utility function coerces strings into string * literal types and runs a simple check to guarantee all * action types in the application are unique. */ export const SubmissionObjectActionTypes = { // Section types INIT_SUBMISSION_FORM: type('dspace/submission/INIT_SUBMISSION_FORM'), RESET_SUBMISSION_FORM: type('dspace/submission/RESET_SUBMISSION_FORM'), CANCEL_SUBMISSION_FORM: type('dspace/submission/CANCEL_SUBMISSION_FORM'), COMPLETE_INIT_SUBMISSION_FORM: type('dspace/submission/COMPLETE_INIT_SUBMISSION_FORM'), SAVE_FOR_LATER_SUBMISSION_FORM: type('dspace/submission/SAVE_FOR_LATER_SUBMISSION_FORM'), SAVE_FOR_LATER_SUBMISSION_FORM_SUCCESS: type('dspace/submission/SAVE_FOR_LATER_SUBMISSION_FORM_SUCCESS'), SAVE_FOR_LATER_SUBMISSION_FORM_ERROR: type('dspace/submission/SAVE_FOR_LATER_SUBMISSION_FORM_ERROR'), SAVE_SUBMISSION_FORM: type('dspace/submission/SAVE_SUBMISSION_FORM'), SAVE_SUBMISSION_FORM_SUCCESS: type('dspace/submission/SAVE_SUBMISSION_FORM_SUCCESS'), SAVE_SUBMISSION_FORM_ERROR: type('dspace/submission/SAVE_SUBMISSION_FORM_ERROR'), SAVE_SUBMISSION_SECTION_FORM: type('dspace/submission/SAVE_SUBMISSION_SECTION_FORM'), SAVE_SUBMISSION_SECTION_FORM_SUCCESS: type('dspace/submission/SAVE_SUBMISSION_SECTION_FORM_SUCCESS'), SAVE_SUBMISSION_SECTION_FORM_ERROR: type('dspace/submission/SAVE_SUBMISSION_SECTION_FORM_ERROR'), CHANGE_SUBMISSION_COLLECTION: type('dspace/submission/CHANGE_SUBMISSION_COLLECTION'), SET_ACTIVE_SECTION: type('dspace/submission/SET_ACTIVE_SECTION'), INIT_SECTION: type('dspace/submission/INIT_SECTION'), ENABLE_SECTION: type('dspace/submission/ENABLE_SECTION'), DISABLE_SECTION: type('dspace/submission/DISABLE_SECTION'), SET_SECTION_FORM_ID: type('dspace/submission/SET_SECTION_FORM_ID'), SECTION_STATUS_CHANGE: type('dspace/submission/SECTION_STATUS_CHANGE'), SECTION_LOADING_STATUS_CHANGE: type('dspace/submission/SECTION_LOADING_STATUS_CHANGE'), UPDATE_SECTION_DATA: type('dspace/submission/UPDATE_SECTION_DATA'), UPDATE_SECTION_DATA_SUCCESS: type('dspace/submission/UPDATE_SECTION_DATA_SUCCESS'), SAVE_AND_DEPOSIT_SUBMISSION: type('dspace/submission/SAVE_AND_DEPOSIT_SUBMISSION'), DEPOSIT_SUBMISSION: type('dspace/submission/DEPOSIT_SUBMISSION'), DEPOSIT_SUBMISSION_SUCCESS: type('dspace/submission/DEPOSIT_SUBMISSION_SUCCESS'), DEPOSIT_SUBMISSION_ERROR: type('dspace/submission/DEPOSIT_SUBMISSION_ERROR'), DISCARD_SUBMISSION: type('dspace/submission/DISCARD_SUBMISSION'), DISCARD_SUBMISSION_SUCCESS: type('dspace/submission/DISCARD_SUBMISSION_SUCCESS'), DISCARD_SUBMISSION_ERROR: type('dspace/submission/DISCARD_SUBMISSION_ERROR'), // Upload file types NEW_FILE: type('dspace/submission/NEW_FILE'), EDIT_FILE_DATA: type('dspace/submission/EDIT_FILE_DATA'), DELETE_FILE: type('dspace/submission/DELETE_FILE'), // Errors ADD_SECTION_ERROR: type('dspace/submission/ADD_SECTION_ERROR'), DELETE_SECTION_ERROR: type('dspace/submission/DELETE_SECTION_ERROR'), REMOVE_SECTION_ERRORS: type('dspace/submission/REMOVE_SECTION_ERRORS'), }; /* tslint:disable:max-classes-per-file */ /** * Insert a new error of type SubmissionSectionError into the given section * @param {string} submissionId * @param {string} sectionId * @param {SubmissionSectionError} error */ export class InertSectionErrorsAction implements Action { type: string = SubmissionObjectActionTypes.ADD_SECTION_ERROR; payload: { submissionId: string; sectionId: string; error: SubmissionSectionError | SubmissionSectionError[]; }; constructor(submissionId: string, sectionId: string, error: SubmissionSectionError | SubmissionSectionError[]) { this.payload = { submissionId, sectionId, error }; } } /** * Delete a SubmissionSectionError from the given section * @param {string} submissionId * @param {string} sectionId * @param {string | SubmissionSectionError} error */ export class DeleteSectionErrorsAction implements Action { type: string = SubmissionObjectActionTypes.DELETE_SECTION_ERROR; payload: { submissionId: string; sectionId: string; errors: SubmissionSectionError | SubmissionSectionError[]; }; constructor(submissionId: string, sectionId: string, errors: SubmissionSectionError | SubmissionSectionError[]) { this.payload = { submissionId, sectionId, errors }; } } // Section actions export class InitSectionAction implements Action { type = SubmissionObjectActionTypes.INIT_SECTION; payload: { submissionId: string; sectionId: string; header: string; config: string; mandatory: boolean; sectionType: SectionsType; visibility: SectionVisibility; enabled: boolean; data: WorkspaceitemSectionDataType; errors: SubmissionSectionError[]; }; /** * Create a new InitSectionAction * * @param submissionId * the submission's ID to remove * @param sectionId * the section's ID to add * @param header * the section's header * @param config * the section's config * @param mandatory * the section's mandatory * @param sectionType * the section's type * @param visibility * the section's visibility * @param enabled * the section's enabled state * @param data * the section's data * @param errors * the section's errors */ constructor(submissionId: string, sectionId: string, header: string, config: string, mandatory: boolean, sectionType: SectionsType, visibility: SectionVisibility, enabled: boolean, data: WorkspaceitemSectionDataType, errors: SubmissionSectionError[]) { this.payload = { submissionId, sectionId, header, config, mandatory, sectionType, visibility, enabled, data, errors }; } } export class EnableSectionAction implements Action { type = SubmissionObjectActionTypes.ENABLE_SECTION; payload: { submissionId: string; sectionId: string; }; /** * Create a new EnableSectionAction * * @param submissionId * the submission's ID to remove * @param sectionId * the section's ID to add */ constructor(submissionId: string, sectionId: string) { this.payload = { submissionId, sectionId }; } } export class DisableSectionAction implements Action { type = SubmissionObjectActionTypes.DISABLE_SECTION; payload: { submissionId: string; sectionId: string; }; /** * Create a new DisableSectionAction * * @param submissionId * the submission's ID to remove * @param sectionId * the section's ID to remove */ constructor(submissionId: string, sectionId: string) { this.payload = { submissionId, sectionId }; } } export class UpdateSectionDataAction implements Action { type = SubmissionObjectActionTypes.UPDATE_SECTION_DATA; payload: { submissionId: string; sectionId: string; data: WorkspaceitemSectionDataType; errorsToShow: SubmissionSectionError[]; serverValidationErrors: SubmissionSectionError[]; metadata: string[]; }; /** * Create a new EnableSectionAction * * @param submissionId * the submission's ID to remove * @param sectionId * the section's ID to add * @param data * the section's data * @param errorsToShow * the list of the section's errors to show * @param serverValidationErrors * the list of the section errors detected by the server * @param metadata * the section's metadata */ constructor(submissionId: string, sectionId: string, data: WorkspaceitemSectionDataType, errorsToShow: SubmissionSectionError[], serverValidationErrors: SubmissionSectionError[], metadata?: string[]) { this.payload = { submissionId, sectionId, data, errorsToShow, serverValidationErrors, metadata }; } } export class UpdateSectionDataSuccessAction implements Action { type = SubmissionObjectActionTypes.UPDATE_SECTION_DATA_SUCCESS; } export class RemoveSectionErrorsAction implements Action { type = SubmissionObjectActionTypes.REMOVE_SECTION_ERRORS; payload: { submissionId: string; sectionId: string; }; /** * Create a new RemoveSectionErrorsAction * * @param submissionId * the submission's ID to remove * @param sectionId * the section's ID to add */ constructor(submissionId: string, sectionId: string) { this.payload = { submissionId, sectionId }; } } export class SetSectionFormId implements Action { type = SubmissionObjectActionTypes.SET_SECTION_FORM_ID; payload: { submissionId: string; sectionId: string; formId: string; }; /** * Create a new SetSectionFormId * * @param submissionId * the submission's ID * @param sectionId * the section's ID * @param formId * the section's formId */ constructor(submissionId: string, sectionId: string, formId: string) { this.payload = { submissionId, sectionId, formId }; } } // Submission actions export class CompleteInitSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.COMPLETE_INIT_SUBMISSION_FORM; payload: { submissionId: string; }; /** * Create a new CompleteInitSubmissionFormAction * * @param submissionId * the submission's ID */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class InitSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.INIT_SUBMISSION_FORM; payload: { collectionId: string; submissionId: string; selfUrl: string; submissionDefinition: SubmissionDefinitionsModel; sections: WorkspaceitemSectionsObject; item: Item; errors: SubmissionError; }; /** * Create a new InitSubmissionFormAction * * @param collectionId * the collection's Id where to deposit * @param submissionId * the submission's ID * @param selfUrl * the submission object url * @param submissionDefinition * the submission's sections definition * @param sections * the submission's sections * @param errors * the submission's sections errors */ constructor(collectionId: string, submissionId: string, selfUrl: string, submissionDefinition: SubmissionDefinitionsModel, sections: WorkspaceitemSectionsObject, item: Item, errors: SubmissionError) { this.payload = { collectionId, submissionId, selfUrl, submissionDefinition, sections, item, errors }; } } export class SaveForLaterSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.SAVE_FOR_LATER_SUBMISSION_FORM; payload: { submissionId: string; }; /** * Create a new SaveForLaterSubmissionFormAction * * @param submissionId * the submission's ID */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class SaveForLaterSubmissionFormSuccessAction implements Action { type = SubmissionObjectActionTypes.SAVE_FOR_LATER_SUBMISSION_FORM_SUCCESS; payload: { submissionId: string; submissionObject: SubmissionObject[]; }; /** * Create a new SaveForLaterSubmissionFormSuccessAction * * @param submissionId * the submission's ID * @param submissionObject * the submission's Object */ constructor(submissionId: string, submissionObject: SubmissionObject[]) { this.payload = { submissionId, submissionObject }; } } export class SaveForLaterSubmissionFormErrorAction implements Action { type = SubmissionObjectActionTypes.SAVE_FOR_LATER_SUBMISSION_FORM_ERROR; payload: { submissionId: string; }; /** * Create a new SaveForLaterSubmissionFormErrorAction * * @param submissionId * the submission's ID */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class SaveSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_FORM; payload: { submissionId: string; isManual?: boolean; }; /** * Create a new SaveSubmissionFormAction * * @param submissionId * the submission's ID */ constructor(submissionId: string, isManual: boolean = false) { this.payload = { submissionId, isManual }; } } export class SaveSubmissionFormSuccessAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_FORM_SUCCESS; payload: { submissionId: string; submissionObject: SubmissionObject[]; notify?: boolean }; /** * Create a new SaveSubmissionFormSuccessAction * * @param submissionId * the submission's ID * @param submissionObject * the submission's Object */ constructor(submissionId: string, submissionObject: SubmissionObject[], notify?: boolean) { this.payload = { submissionId, submissionObject, notify }; } } export class SaveSubmissionFormErrorAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_FORM_ERROR; payload: { submissionId: string; }; /** * Create a new SaveSubmissionFormErrorAction * * @param submissionId * the submission's ID */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class SaveSubmissionSectionFormAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_SECTION_FORM; payload: { submissionId: string; sectionId: string; }; /** * Create a new SaveSubmissionSectionFormAction * * @param submissionId * the submission's ID * @param sectionId * the section's ID */ constructor(submissionId: string, sectionId: string) { this.payload = { submissionId, sectionId }; } } export class SaveSubmissionSectionFormSuccessAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_SECTION_FORM_SUCCESS; payload: { submissionId: string; submissionObject: SubmissionObject[]; notify?: boolean }; /** * Create a new SaveSubmissionSectionFormSuccessAction * * @param submissionId * the submission's ID * @param submissionObject * the submission's Object */ constructor(submissionId: string, submissionObject: SubmissionObject[], notify?: boolean) { this.payload = { submissionId, submissionObject, notify }; } } export class SaveSubmissionSectionFormErrorAction implements Action { type = SubmissionObjectActionTypes.SAVE_SUBMISSION_SECTION_FORM_ERROR; payload: { submissionId: string; }; /** * Create a new SaveSubmissionFormErrorAction * * @param submissionId * the submission's ID */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class ResetSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.RESET_SUBMISSION_FORM; payload: { collectionId: string; submissionId: string; selfUrl: string; sections: WorkspaceitemSectionsObject; submissionDefinition: SubmissionDefinitionsModel; item: Item; }; /** * Create a new ResetSubmissionFormAction * * @param collectionId * the collection's Id where to deposit * @param submissionId * the submission's ID * @param selfUrl * the submission object url * @param sections * the submission's sections * @param submissionDefinition * the submission's form definition */ constructor(collectionId: string, submissionId: string, selfUrl: string, sections: WorkspaceitemSectionsObject, submissionDefinition: SubmissionDefinitionsModel, item: Item) { this.payload = { collectionId, submissionId, selfUrl, sections, submissionDefinition, item }; } } export class CancelSubmissionFormAction implements Action { type = SubmissionObjectActionTypes.CANCEL_SUBMISSION_FORM; } export class ChangeSubmissionCollectionAction implements Action { type = SubmissionObjectActionTypes.CHANGE_SUBMISSION_COLLECTION; payload: { submissionId: string; collectionId: string; }; /** * Create a new ChangeSubmissionCollectionAction * * @param submissionId * the submission's ID * @param collectionId * the new collection's ID */ constructor(submissionId: string, collectionId: string) { this.payload = { submissionId, collectionId }; } } export class SaveAndDepositSubmissionAction implements Action { type = SubmissionObjectActionTypes.SAVE_AND_DEPOSIT_SUBMISSION; payload: { submissionId: string; }; /** * Create a new SaveAndDepositSubmissionAction * * @param submissionId * the submission's ID to deposit */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DepositSubmissionAction implements Action { type = SubmissionObjectActionTypes.DEPOSIT_SUBMISSION; payload: { submissionId: string; }; /** * Create a new DepositSubmissionAction * * @param submissionId * the submission's ID to deposit */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DepositSubmissionSuccessAction implements Action { type = SubmissionObjectActionTypes.DEPOSIT_SUBMISSION_SUCCESS; payload: { submissionId: string; }; /** * Create a new DepositSubmissionSuccessAction * * @param submissionId * the submission's ID to deposit */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DepositSubmissionErrorAction implements Action { type = SubmissionObjectActionTypes.DEPOSIT_SUBMISSION_ERROR; payload: { submissionId: string; }; /** * Create a new DepositSubmissionErrorAction * * @param submissionId * the submission's ID to deposit */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DiscardSubmissionAction implements Action { type = SubmissionObjectActionTypes.DISCARD_SUBMISSION; payload: { submissionId: string; }; /** * Create a new DiscardSubmissionAction * * @param submissionId * the submission's ID to discard */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DiscardSubmissionSuccessAction implements Action { type = SubmissionObjectActionTypes.DISCARD_SUBMISSION_SUCCESS; payload: { submissionId: string; }; /** * Create a new DiscardSubmissionSuccessAction * * @param submissionId * the submission's ID to discard */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class DiscardSubmissionErrorAction implements Action { type = SubmissionObjectActionTypes.DISCARD_SUBMISSION_ERROR; payload: { submissionId: string; }; /** * Create a new DiscardSubmissionErrorAction * * @param submissionId * the submission's ID to discard */ constructor(submissionId: string) { this.payload = { submissionId }; } } export class SectionStatusChangeAction implements Action { type = SubmissionObjectActionTypes.SECTION_STATUS_CHANGE; payload: { submissionId: string; sectionId: string; status: boolean }; /** * Change the section validity status * * @param submissionId * the submission's ID * @param sectionId * the section's ID to change * @param status * the section validity status (true if is valid) */ constructor(submissionId: string, sectionId: string, status: boolean) { this.payload = { submissionId, sectionId, status }; } } export class SetActiveSectionAction implements Action { type = SubmissionObjectActionTypes.SET_ACTIVE_SECTION; payload: { submissionId: string; sectionId: string; }; /** * Create a new SetActiveSectionAction * * @param submissionId * the submission's ID * @param sectionId * the section's ID to active */ constructor(submissionId: string, sectionId: string) { this.payload = { submissionId, sectionId }; } } // Upload file actions export class NewUploadedFileAction implements Action { type = SubmissionObjectActionTypes.NEW_FILE; payload: { submissionId: string; sectionId: string; fileId: string; data: WorkspaceitemSectionUploadFileObject; }; /** * Add a new uploaded file * * @param submissionId * the submission's ID * @param sectionId * the section's ID * @param fileId * the file's ID * @param data * the metadata of the new bitstream */ constructor(submissionId: string, sectionId: string, fileId: string, data: WorkspaceitemSectionUploadFileObject) { this.payload = { submissionId, sectionId, fileId, data }; } } export class EditFileDataAction implements Action { type = SubmissionObjectActionTypes.EDIT_FILE_DATA; payload: { submissionId: string; sectionId: string; fileId: string; data: WorkspaceitemSectionUploadFileObject; }; /** * Edit a file data * * @param submissionId * the submission's ID * @param sectionId * the section's ID * @param fileId * the file's ID * @param data * the metadata of the new bitstream */ constructor(submissionId: string, sectionId: string, fileId: string, data: WorkspaceitemSectionUploadFileObject) { this.payload = { submissionId, sectionId, fileId: fileId, data }; } } export class DeleteUploadedFileAction implements Action { type = SubmissionObjectActionTypes.DELETE_FILE; payload: { submissionId: string; sectionId: string; fileId: string; }; /** * Delete a uploaded file * * @param submissionId * the submission's ID * @param sectionId * the section's ID * @param fileId * the file's ID */ constructor(submissionId: string, sectionId: string, fileId: string) { this.payload = { submissionId, sectionId, fileId }; } } /* tslint:enable:max-classes-per-file */ /** * Export a type alias of all actions in this action group * so that reducers can easily compose action types */ export type SubmissionObjectAction = DisableSectionAction | InitSectionAction | SetSectionFormId | EnableSectionAction | InitSubmissionFormAction | ResetSubmissionFormAction | CancelSubmissionFormAction | CompleteInitSubmissionFormAction | ChangeSubmissionCollectionAction | SaveAndDepositSubmissionAction | DepositSubmissionAction | DepositSubmissionSuccessAction | DepositSubmissionErrorAction | DiscardSubmissionAction | DiscardSubmissionSuccessAction | DiscardSubmissionErrorAction | SectionStatusChangeAction | NewUploadedFileAction | EditFileDataAction | DeleteUploadedFileAction | InertSectionErrorsAction | DeleteSectionErrorsAction | UpdateSectionDataAction | RemoveSectionErrorsAction | SaveForLaterSubmissionFormAction | SaveForLaterSubmissionFormSuccessAction | SaveForLaterSubmissionFormErrorAction | SaveSubmissionFormAction | SaveSubmissionFormSuccessAction | SaveSubmissionFormErrorAction | SaveSubmissionSectionFormAction | SaveSubmissionSectionFormSuccessAction | SaveSubmissionSectionFormErrorAction | SetActiveSectionAction;
the_stack
import { Helper } from '../Helper'; import { Point, Rect, RectPoints, Segment } from '../BasicTypes'; import { FlipCorner, FlipDirection } from './Flip'; /** * Class representing mathematical methods for calculating page position (rotation angle, clip area ...) */ export class FlipCalculation { /** Calculated rotation angle to flipping page */ private angle: number; /** Calculated position to flipping page */ private position: Point; private rect: RectPoints; /** The point of intersection of the page with the borders of the book */ private topIntersectPoint: Point = null; // With top border private sideIntersectPoint: Point = null; // With side border private bottomIntersectPoint: Point = null; // With bottom border private readonly pageWidth: number; private readonly pageHeight: number; /** * @constructor * * @param {FlipDirection} direction - Flipping direction * @param {FlipCorner} corner - Flipping corner * @param pageWidth - Current page width * @param pageHeight - Current page height */ constructor( private direction: FlipDirection, private corner: FlipCorner, pageWidth: string, pageHeight: string ) { this.pageWidth = parseInt(pageWidth, 10); this.pageHeight = parseInt(pageHeight, 10); } /** * The main calculation method * * @param {Point} localPos - Touch Point Coordinates (relative active page!) * * @returns {boolean} True - if the calculations were successful, false if errors occurred */ public calc(localPos: Point): boolean { try { // Find: page rotation angle and active corner position this.position = this.calcAngleAndPosition(localPos); // Find the intersection points of the scrolling page and the book this.calculateIntersectPoint(this.position); return true; } catch (e) { return false; } } /** * Get the crop area for the flipping page * * @returns {Point[]} Polygon page */ public getFlippingClipArea(): Point[] { const result = []; let clipBottom = false; result.push(this.rect.topLeft); result.push(this.topIntersectPoint); if (this.sideIntersectPoint === null) { clipBottom = true; } else { result.push(this.sideIntersectPoint); if (this.bottomIntersectPoint === null) clipBottom = false; } result.push(this.bottomIntersectPoint); if (clipBottom || this.corner === FlipCorner.BOTTOM) { result.push(this.rect.bottomLeft); } return result; } /** * Get the crop area for the page that is below the page to be flipped * * @returns {Point[]} Polygon page */ public getBottomClipArea(): Point[] { const result = []; result.push(this.topIntersectPoint); if (this.corner === FlipCorner.TOP) { result.push({ x: this.pageWidth, y: 0 }); } else { if (this.topIntersectPoint !== null) { result.push({ x: this.pageWidth, y: 0 }); } result.push({ x: this.pageWidth, y: this.pageHeight }); } if (this.sideIntersectPoint !== null) { if ( Helper.GetDistanceBetweenTwoPoint( this.sideIntersectPoint, this.topIntersectPoint ) >= 10 ) result.push(this.sideIntersectPoint); } else { if (this.corner === FlipCorner.TOP) { result.push({ x: this.pageWidth, y: this.pageHeight }); } } result.push(this.bottomIntersectPoint); result.push(this.topIntersectPoint); return result; } /** * Get page rotation angle */ public getAngle(): number { if (this.direction === FlipDirection.FORWARD) { return -this.angle; } return this.angle; } /** * Get page area while flipping */ public getRect(): RectPoints { return this.rect; } /** * Get the position of the active angle when turning */ public getPosition(): Point { return this.position; } /** * Get the active corner of the page (which pull) */ public getActiveCorner(): Point { if (this.direction === FlipDirection.FORWARD) { return this.rect.topLeft; } return this.rect.topRight; } /** * Get flipping direction */ public getDirection(): FlipDirection { return this.direction; } /** * Get flipping progress (0-100) */ public getFlippingProgress(): number { return Math.abs(((this.position.x - this.pageWidth) / (2 * this.pageWidth)) * 100); } /** * Get flipping corner position (top, bottom) */ public getCorner(): FlipCorner { return this.corner; } /** * Get start position for the page that is below the page to be flipped */ public getBottomPagePosition(): Point { if (this.direction === FlipDirection.BACK) { return { x: this.pageWidth, y: 0 }; } return { x: 0, y: 0 }; } /** * Get the starting position of the shadow */ public getShadowStartPoint(): Point { if (this.corner === FlipCorner.TOP) { return this.topIntersectPoint; } else { if (this.sideIntersectPoint !== null) return this.sideIntersectPoint; return this.topIntersectPoint; } } /** * Get the rotate angle of the shadow */ public getShadowAngle(): number { const angle = Helper.GetAngleBetweenTwoLine(this.getSegmentToShadowLine(), [ { x: 0, y: 0 }, { x: this.pageWidth, y: 0 }, ]); if (this.direction === FlipDirection.FORWARD) { return angle; } return Math.PI - angle; } private calcAngleAndPosition(pos: Point): Point { let result = pos; this.updateAngleAndGeometry(result); if (this.corner === FlipCorner.TOP) { result = this.checkPositionAtCenterLine( result, { x: 0, y: 0 }, { x: 0, y: this.pageHeight } ); } else { result = this.checkPositionAtCenterLine( result, { x: 0, y: this.pageHeight }, { x: 0, y: 0 } ); } if (Math.abs(result.x - this.pageWidth) < 1 && Math.abs(result.y) < 1) { throw new Error('Point is too small'); } return result; } private updateAngleAndGeometry(pos: Point): void { this.angle = this.calculateAngle(pos); this.rect = this.getPageRect(pos); } private calculateAngle(pos: Point): number { const left = this.pageWidth - pos.x + 1; const top = this.corner === FlipCorner.BOTTOM ? this.pageHeight - pos.y : pos.y; let angle = 2 * Math.acos(left / Math.sqrt(top * top + left * left)); if (top < 0) angle = -angle; const da = Math.PI - angle; if (!isFinite(angle) || (da >= 0 && da < 0.003)) throw new Error('The G point is too small'); if (this.corner === FlipCorner.BOTTOM) angle = -angle; return angle; } private getPageRect(localPos: Point): RectPoints { if (this.corner === FlipCorner.TOP) { return this.getRectFromBasePoint( [ { x: 0, y: 0 }, { x: this.pageWidth, y: 0 }, { x: 0, y: this.pageHeight }, { x: this.pageWidth, y: this.pageHeight }, ], localPos ); } return this.getRectFromBasePoint( [ { x: 0, y: -this.pageHeight }, { x: this.pageWidth, y: -this.pageHeight }, { x: 0, y: 0 }, { x: this.pageWidth, y: 0 }, ], localPos ); } private getRectFromBasePoint(points: Point[], localPos: Point): RectPoints { return { topLeft: this.getRotatedPoint(points[0], localPos), topRight: this.getRotatedPoint(points[1], localPos), bottomLeft: this.getRotatedPoint(points[2], localPos), bottomRight: this.getRotatedPoint(points[3], localPos), }; } private getRotatedPoint(transformedPoint: Point, startPoint: Point): Point { return { x: transformedPoint.x * Math.cos(this.angle) + transformedPoint.y * Math.sin(this.angle) + startPoint.x, y: transformedPoint.y * Math.cos(this.angle) - transformedPoint.x * Math.sin(this.angle) + startPoint.y, }; } private calculateIntersectPoint(pos: Point): void { const boundRect: Rect = { left: -1, top: -1, width: this.pageWidth + 2, height: this.pageHeight + 2, }; if (this.corner === FlipCorner.TOP) { this.topIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [pos, this.rect.topRight], [ { x: 0, y: 0 }, { x: this.pageWidth, y: 0 }, ] ); this.sideIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [pos, this.rect.bottomLeft], [ { x: this.pageWidth, y: 0 }, { x: this.pageWidth, y: this.pageHeight }, ] ); this.bottomIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [this.rect.bottomLeft, this.rect.bottomRight], [ { x: 0, y: this.pageHeight }, { x: this.pageWidth, y: this.pageHeight }, ] ); } else { this.topIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [this.rect.topLeft, this.rect.topRight], [ { x: 0, y: 0 }, { x: this.pageWidth, y: 0 }, ] ); this.sideIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [pos, this.rect.topLeft], [ { x: this.pageWidth, y: 0 }, { x: this.pageWidth, y: this.pageHeight }, ] ); this.bottomIntersectPoint = Helper.GetIntersectBetweenTwoSegment( boundRect, [this.rect.bottomLeft, this.rect.bottomRight], [ { x: 0, y: this.pageHeight }, { x: this.pageWidth, y: this.pageHeight }, ] ); } } private checkPositionAtCenterLine( checkedPos: Point, centerOne: Point, centerTwo: Point ): Point { let result = checkedPos; const tmp = Helper.LimitPointToCircle(centerOne, this.pageWidth, result); if (result !== tmp) { result = tmp; this.updateAngleAndGeometry(result); } const rad = Math.sqrt(Math.pow(this.pageWidth, 2) + Math.pow(this.pageHeight, 2)); let checkPointOne = this.rect.bottomRight; let checkPointTwo = this.rect.topLeft; if (this.corner === FlipCorner.BOTTOM) { checkPointOne = this.rect.topRight; checkPointTwo = this.rect.bottomLeft; } if (checkPointOne.x <= 0) { const bottomPoint = Helper.LimitPointToCircle(centerTwo, rad, checkPointTwo); if (bottomPoint !== result) { result = bottomPoint; this.updateAngleAndGeometry(result); } } return result; } private getSegmentToShadowLine(): Segment { const first = this.getShadowStartPoint(); const second = first !== this.sideIntersectPoint && this.sideIntersectPoint !== null ? this.sideIntersectPoint : this.bottomIntersectPoint; return [first, second]; } }
the_stack
import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import '@gravitee/ui-components/wc/gv-stepper'; import '@gravitee/ui-components/wc/gv-option'; import '@gravitee/ui-components/wc/gv-switch'; import '@gravitee/ui-components/wc/gv-file-upload'; import { TranslateService } from '@ngx-translate/core'; import { marker as i18n } from '@biesbjerg/ngx-translate-extract-marker'; import { ActivatedRoute, Router } from '@angular/router'; import { ConfigurationService } from '../../../services/configuration.service'; import { getApplicationTypeIcon } from '@gravitee/ui-components/src/lib/theme'; import { Api, ApiService, Application, ApplicationInput, ApplicationService, ApplicationType, Plan, PortalService, SubscriptionService, } from '../../../../../projects/portal-webclient-sdk/src/lib'; import { NotificationService } from '../../../services/notification.service'; export interface ApplicationTypeOption extends ApplicationType { icon: string; description: string; title: string; } interface StepState { description: string; valid: boolean; invalid: boolean; } @Component({ selector: 'app-application-creation', templateUrl: './application-creation.component.html', styleUrls: ['./application-creation.component.css'], }) export class ApplicationCreationComponent implements OnInit { private _allSteps: any; steps: any; currentStep: number; applicationForm: FormGroup; allowedTypes: Array<ApplicationTypeOption>; plans: Array<Plan>; subscribeList: any[]; private readSteps: number[]; creationInProgress: boolean; creationSuccess: boolean; creationError: boolean; createdApplication: Application; applicationType: ApplicationTypeOption; private stepOneForm: FormGroup; private stepTwoForm: FormGroup; subscriptionErrors: { api: Api; message: string }[]; constructor( private translateService: TranslateService, private configurationService: ConfigurationService, private formBuilder: FormBuilder, private router: Router, private route: ActivatedRoute, private portalService: PortalService, private notificationService: NotificationService, private apiService: ApiService, private activatedRoute: ActivatedRoute, private subscriptionService: SubscriptionService, private applicationService: ApplicationService, private ref: ChangeDetectorRef, ) { this.currentStep = 1; this.readSteps = [1]; this.subscriptionErrors = []; } async ngOnInit() { this._allSteps = await Promise.all( [ i18n('applicationCreation.step.general'), i18n('applicationCreation.step.security'), i18n('applicationCreation.step.subscription'), i18n('applicationCreation.step.validate'), ].map((_title) => this.translateService .get(_title) .toPromise() .then((title) => ({ title })), ), ); this.steps = this._allSteps; this.allowedTypes = await Promise.all( this.route.snapshot.data.enabledApplicationTypes.map((type, index) => { return this.translateService .get([`applicationType.${type.id}.title`, `applicationType.${type.id}.description`]) .toPromise() .then((translations) => { const [title, description] = Object.values(translations); return { ...type, icon: getApplicationTypeIcon(type.id), title, description, }; }); }), ); this.applicationForm = this.formBuilder.group({ name: new FormControl(null, [Validators.required]), description: new FormControl(null, [Validators.required]), domain: new FormControl(null), picture: new FormControl(null), settings: new FormControl(null, [Validators.required]), }); } setCurrentStep(step) { if (!this.creationSuccess) { if (!this.readSteps.includes(step)) { this.readSteps.push(step); if (step === 3) { this.subscribeList = []; } } this.ref.detectChanges(); this.updateSteps(); this.currentStep = step; } } onChangeStep({ detail: { current } }) { this.notificationService.reset(); this.creationError = false; this.setCurrentStep(current); } get requireClientId() { if (this.applicationType && this.isSimpleApp && this.subscribeList) { const subscription = this.subscribeList.find((s) => !this.hasValidClientId(s.plan)); if (subscription) { return true; } } return false; } hasValidClientId(plan) { if ( this.isSimpleApp && (plan.security.toUpperCase() === Plan.SecurityEnum.OAUTH2 || plan.security.toUpperCase() === Plan.SecurityEnum.JWT) ) { const { settings } = this.applicationForm.getRawValue(); if (settings.app) { if (settings.app.client_id == null || settings.app.client_id.trim() === '') { return false; } } } return true; } hasValidSubscriptions() { return ( this.readSteps.includes(3) && this.subscribeList.find((s) => this.hasRequireComment(s.plan) && (s.request == null || s.request.trim() === '')) == null ); } hasRequireComment(plan) { return plan && plan.comment_required; } onStepOneUpdated(stepOneForm: FormGroup) { this.stepOneForm = stepOneForm; this.applicationForm.patchValue(this.stepOneForm.getRawValue()); this.updateSteps(); } get stepOneState(): StepState { if (this.stepOneForm) { return { description: this.stepOneForm.get('name').value, valid: this.stepOneForm.valid, invalid: this.readSteps.includes(2) && this.stepOneForm.invalid, }; } return { description: '', valid: false, invalid: false }; } onStepTwoUpdated(stepTwoForm: FormGroup) { this.stepTwoForm = stepTwoForm; this.applicationForm.get('settings').patchValue(this.stepTwoForm.getRawValue()); this.updateSteps(); } get stepTwoState(): StepState { if (this.stepTwoForm) { const description = this.readSteps.includes(2) && this.applicationType ? this.applicationType.name : ''; return { description, valid: this.stepTwoForm.valid, invalid: this.stepTwoForm.invalid }; } return { description: '', valid: false, invalid: false }; } onStepThreeUpdated(subscribeList: any[]) { this.subscribeList = subscribeList; this.updateSteps().then(() => this.ref.detectChanges()); } async stepThreeState(): Promise<StepState> { if (this.subscribeList) { const description = await this.translateService .get(i18n('applicationCreation.subscription.description'), { count: this.subscribeList.length }) .toPromise(); const valid = this.hasValidSubscriptions(); return { description, valid, invalid: !valid }; } return { description: '', valid: false, invalid: false }; } private async updateSteps() { const createdAt = this.createdApplication ? new Date(this.createdApplication.created_at).toLocaleString(this.translateService.currentLang) : ''; const stepThreeStep = await this.stepThreeState(); this.steps = [ this.stepOneState, this.stepTwoState, stepThreeStep, { description: createdAt, valid: this.creationSuccess, invalid: false }, ].map(({ description, valid, invalid }, index) => { const step = this._allSteps[index]; step.description = description; step.valid = this.readSteps.includes(index + 1) && valid; step.invalid = this.readSteps.includes(index + 1) && invalid; return step; }); } onNext() { if (this.canNext()) { this.setCurrentStep(this.currentStep + 1); } } canNext() { return this._allSteps && this.currentStep < this._allSteps.length && !this.creationSuccess; } canPrevious() { return this.currentStep > 1 && !this.creationSuccess; } onPrevious() { if (this.canPrevious()) { this.setCurrentStep(this.currentStep - 1); } } onExit() { this.router.navigate(['../'], { relativeTo: this.route }); } canValidate() { if (this.steps && !this.creationSuccess) { const firstThree = this.steps.filter((step, index) => index <= 2 && step.valid); if (firstThree.length === 3) { return this.applicationForm.valid && this.hasValidSubscriptions(); } } return false; } hasNext() { return this.currentStep <= 3; } hasCreate() { return this.currentStep === 4 && !this.creationSuccess; } createApp() { this.creationSuccess = false; this.creationError = false; this.creationInProgress = true; this.subscriptionErrors = []; const applicationInput = this.applicationForm.getRawValue() as ApplicationInput; this.applicationService .createApplication({ applicationInput }) .toPromise() .then((application) => { this.createdApplication = application; this.subscribeList.forEach(async (subscription) => { const subscriptionInput: any = { application: application.id, plan: subscription.plan.id, request: subscription.request, }; if (subscription.general_conditions_accepted) { subscriptionInput.general_conditions_accepted = subscription.general_conditions_accepted; subscriptionInput.general_conditions_content_revision = subscription.general_conditions_content_revision; } try { await this.subscriptionService.createSubscription({ subscriptionInput }).toPromise(); } catch (exception) { let message = null; if (exception.error && exception.error.errors) { const error = exception.error.errors[0]; message = await this.translateService.get(error.code, error.parameters).toPromise(); } this.subscriptionErrors.push({ api: subscription.api, message }); } }); this.creationSuccess = true; this.creationInProgress = false; setTimeout(this.updateSteps.bind(this), 200); }) .catch(() => { this.creationError = true; this.creationInProgress = false; }); } onApplicationTypeSelected(applicationTypeOption: ApplicationTypeOption) { setTimeout(() => { this.applicationType = applicationTypeOption; this.updateSteps(); }, 0); } get isSimpleApp() { return this.applicationType.id.toLowerCase() === 'simple'; } onRequireChangeStep($event: { step; fragment }) { this.setCurrentStep($event.step); if ($event.fragment) { setTimeout(() => { const element = document.getElementById($event.fragment); if (element) { element.focus(); } }); } } }
the_stack
import { CommandBarButton, ContextualMenu, DefaultButton, DetailsList, DetailsListLayoutMode, Dialog, DialogFooter, DialogType, IColumn, Label, PrimaryButton, SearchBox, SelectionMode, Stack, TextField } from '@fluentui/react' import { useBoolean } from '@uifabric/react-hooks' import { useCallback, useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { useHistory } from 'react-router-dom' import { ManagementActions } from '../actions/ManagementAction' import { WizardNavBarActions } from '../actions/WizardNavBarAction' import { TestSuiteInfoActions } from '../actions/TestSuiteInfoAction' import { FileUploader, IFile } from '../components/FileUploader' import { PopupModal } from '../components/PopupModal' import { StackGap10, StackGap5 } from '../components/StackStyle' import { TestSuite } from '../model/TestSuite' import { ManagementDataSrv } from '../services/Management' import { AppState } from '../store/configureStore' import { RunSteps } from '../model/DefaultNavSteps' type TestSuiteManagementDialogKind = 'Install' | 'Update' | 'Remove' interface TestSuiteManagementDialogContentProps { kind: TestSuiteManagementDialogKind type: DialogType title: string } export function Management(props: any) { const history = useHistory() const dispatch = useDispatch() const managementState = useSelector((state: AppState) => state.management) const [isWarningDialogOpen, { setTrue: showWarningDialog, setFalse: hideWarningDialog }] = useBoolean(false) const [hideDialog, { toggle: toggleHideDialog }] = useBoolean(true) const [dialogContentProps, setDialogContentProps] = useState<TestSuiteManagementDialogContentProps | undefined>(undefined) const [currentTestSuite, setCurrentTestSuite] = useState<TestSuite | undefined>(undefined) const [testSuiteName, setTestSuiteName] = useState('') const [testSuiteDescription, setTestSuiteDescription] = useState('') const [testSuiteErrorMsg, setTestSuiteErrorMsg] = useState('') const [file, setFile] = useState<IFile>() useEffect(() => { dispatch(ManagementDataSrv.getTestSuiteList()) }, [dispatch]) useEffect(() => { if (managementState.errorMsg !== undefined) { showWarningDialog() } }, [managementState]) const onFieldChange = useCallback( (element: ElementType, newValue?: string) => { switch (element) { case ElementType.Name: setTestSuiteName(newValue!) break case ElementType.Description: setTestSuiteDescription(newValue!) break default: break } }, []) const installDialogContentProps: TestSuiteManagementDialogContentProps = { kind: 'Install', type: DialogType.normal, title: 'Install Test Suite' } const updateDialogContentProps: TestSuiteManagementDialogContentProps = { kind: 'Update', type: DialogType.normal, title: 'Update Test Suite' } const removeDialogContentProps: TestSuiteManagementDialogContentProps = { kind: 'Remove', type: DialogType.normal, title: 'Remove Test Suite' } const modalProps = { isBlocking: true, styles: { main: { innerWidth: 600, maxWidth: 650 } }, dragOptions: { moveMenuItemText: 'Move', closeMenuItemText: 'Close', menu: ContextualMenu } } const onTestSuiteInstall = () => { if (testSuiteName && (file != null)) { dispatch(ManagementDataSrv.installTestSuite({ TestSuiteName: testSuiteName, Description: testSuiteDescription, Package: file.File }, () => { toggleHideDialog() setCurrentTestSuite(undefined) setTestSuiteName('') setTestSuiteDescription('') setTestSuiteErrorMsg('') dispatch(ManagementDataSrv.getTestSuiteList()) })) } else { if (!testSuiteName) { setTestSuiteErrorMsg('TestSuite Name can\'t be null') return } if (file == null) { setTestSuiteErrorMsg('TestSuite package can\'t be null') return } setTestSuiteErrorMsg('') } } const onTestSuiteUpdate = () => { if (currentTestSuite !== undefined && testSuiteName && (file != null)) { setTestSuiteErrorMsg('') dispatch(ManagementDataSrv.updateTestSuite(currentTestSuite.Id, { TestSuiteName: testSuiteName, Description: testSuiteDescription, Package: file.File }, () => { toggleHideDialog() setCurrentTestSuite(undefined) setTestSuiteName('') setTestSuiteDescription('') dispatch(ManagementDataSrv.getTestSuiteList()) })) } else { if (!testSuiteName) { setTestSuiteErrorMsg('TestSuite Name can\'t be null') return } if (file == null) { setTestSuiteErrorMsg('TestSuite package can\'t be null') return } setTestSuiteErrorMsg('') } } const onTestSuiteRemove = () => { if (currentTestSuite !== undefined) { dispatch(ManagementDataSrv.removeTestSuite(currentTestSuite.Id, () => { toggleHideDialog() setCurrentTestSuite(undefined) setTestSuiteName('') setTestSuiteDescription('') setTestSuiteErrorMsg('') dispatch(ManagementDataSrv.getTestSuiteList()) })) } } const getCurrentTestSuite = (id: number) => managementState.displayList.find((value) => value.Id === id) const columns = getTestSuiteGridColumns({ onRerun: (id: number) => { const foundTestSuite = getCurrentTestSuite(id) if (foundTestSuite != null) { dispatch(TestSuiteInfoActions.setSelectedTestSuiteAction(foundTestSuite)) dispatch(WizardNavBarActions.setWizardNavBarAction(RunSteps.SELECT_CONFIGURATION)) dispatch(() => history.push('/Tasks/NewRun#SelectConfiguration', { from: 'Management' })) } }, onUpdate: (id: number) => { const foundTestSuite = getCurrentTestSuite(id) if (foundTestSuite != null) { setCurrentTestSuite(foundTestSuite) setTestSuiteName(foundTestSuite.Name) setTestSuiteDescription(foundTestSuite.Description ?? '') setDialogContentProps(updateDialogContentProps) toggleHideDialog() } }, onRemove: (id: number) => { const foundTestSuite = getCurrentTestSuite(id) if (foundTestSuite != null) { setCurrentTestSuite(foundTestSuite) setTestSuiteName(foundTestSuite.Name) setTestSuiteDescription(foundTestSuite.Description ?? '') setDialogContentProps(removeDialogContentProps) toggleHideDialog() } } }) const onSearchChanged = (newValue: string): void => { dispatch(ManagementActions.setSearchTextAction(newValue)) } const onFileUploadSuccess = (files: IFile[]): void => { if (files.length > 0) { setFile(files[0]) } } return ( <div> <Stack horizontal horizontalAlign="end" style={{ paddingLeft: 10, paddingRight: 10, paddingTop: 10 }} tokens={StackGap10}> <SearchBox placeholder="Search" onSearch={onSearchChanged} /> <PrimaryButton iconProps={{ iconName: 'Add' }} allowDisabledFocus text='Install Test Suite' onClick={() => { setDialogContentProps(installDialogContentProps) toggleHideDialog() }} /> </Stack> <hr style={{ border: '1px solid #d9d9d9' }} /> <div style={{ padding: 10 }}> <DetailsList items={managementState.displayList} compact={true} columns={columns} selectionMode={SelectionMode.none} layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={true} /> </div> <Dialog hidden={hideDialog} onDismiss={toggleHideDialog} dialogContentProps={dialogContentProps} modalProps={modalProps}> { dialogContentProps !== undefined && dialogContentProps.kind !== 'Remove' ? <Stack tokens={StackGap10}> <TextField label="Test Suite Name" value={testSuiteName} disabled={managementState.isProcessing} onChange={(event: any, newValue?: string) => { onFieldChange(ElementType.Name, newValue) }} /> <FileUploader label="Package" onSuccess={onFileUploadSuccess} disabled={managementState.isProcessing} maxFileCount={1} suffix={['.zip', '.gz']} placeholder="Please click to upload test suite package" /> <TextField label="Description" multiline={true} value={testSuiteDescription} disabled={managementState.isProcessing} errorMessage={testSuiteErrorMsg} onChange={(event: any, newValue?: string) => { onFieldChange(ElementType.Description, newValue) }} /> </Stack> : <div style={{ fontSize: 'large' }}> <Stack horizontalAlign='start' tokens={StackGap5}> <Label>Do you want to remove the following test suite?</Label> <Stack horizontal><div style={{ paddingRight: 5 }}>ID:</div>{currentTestSuite?.Id}</Stack> <Stack horizontal><div style={{ paddingRight: 5 }}>TestSuite:</div>{testSuiteName + ' ' + currentTestSuite?.Version}</Stack> <Stack horizontal><div style={{ paddingRight: 5 }}>Description:</div>{testSuiteDescription}</Stack> </Stack> </div> } { dialogContentProps !== undefined ? <DialogFooter> { dialogContentProps.kind === 'Install' ? <PrimaryButton onClick={onTestSuiteInstall} text={managementState.isProcessing ? 'Installing' : 'Install'} disabled={managementState.isProcessing} /> : null } { dialogContentProps.kind === 'Update' ? <PrimaryButton onClick={onTestSuiteUpdate} text={managementState.isProcessing ? 'Updating' : 'Update'} disabled={managementState.isProcessing} /> : null } <DefaultButton onClick={toggleHideDialog} text="Close" disabled={managementState.isProcessing} /> { dialogContentProps.kind === 'Remove' ? <PrimaryButton onClick={onTestSuiteRemove} style={{ backgroundColor: '#ff4949' }} text={managementState.isProcessing ? 'Removing' : 'Remove'} disabled={managementState.isProcessing} /> : null } </DialogFooter> : null } </Dialog> <PopupModal isOpen={isWarningDialogOpen} header={'Warning'} onClose={hideWarningDialog} text={managementState.errorMsg} /> </div> ) }; function getTestSuiteGridColumns(props: { onRerun: (id: number) => void onUpdate: (id: number) => void onRemove: (id: number) => void }): IColumn[] { return [ { key: 'Name', name: 'Test Suite', ariaLabel: 'Name of the Test Suite', fieldName: 'Name', minWidth: 200, maxWidth: 300, isResizable: true }, { key: 'Version', name: 'Version', fieldName: 'Version', minWidth: 200, maxWidth: 200, isRowHeader: true, isResizable: true, data: 'string', isPadded: true }, { key: 'Description', name: 'Description', fieldName: 'Description', minWidth: 300, isRowHeader: true, isResizable: true, data: 'string', isPadded: true }, { key: 'Action', name: 'Action', minWidth: 300, isRowHeader: true, isResizable: true, data: 'string', isPadded: true, onRender: (item: TestSuite, index, column) => { return <Stack horizontal tokens={StackGap10}> <CommandBarButton iconProps={{ iconName: 'Rerun' }} text="Rerun" onClick={() => { props.onRerun(item.Id) }} /> <CommandBarButton iconProps={{ iconName: 'UpgradeAnalysis' }} text="Update" onClick={() => { props.onUpdate(item.Id) }} /> <CommandBarButton iconProps={{ iconName: 'RemoveFromTrash' }} text="Remove" onClick={() => { props.onRemove(item.Id) }} /> </Stack> } } ] } enum ElementType { Name, Description, }
the_stack
declare var dashboardTabId: number; declare var qs: any; declare var tabid: number; declare var vorlonDashboard: VORLON.DashboardManager; declare module VORLON { class DashboardManager { static ExtensionConfigUrl: string; static TargetTabid: number; static DisplayingTab: boolean; static TabList: any; static PluginsLoaded: boolean; constructor(tabId: any); static GetInternalTabObject(tab: browser.tabs.Tab): any; static GetTabs(): void; static AddTabToList(tab: any): void; static TabCount(): number; static loadPlugins(): void; static hideWaitingLogo(): void; static showWaitingLogo(): void; static divMapper(pluginId: number): HTMLDivElement; static addTab(tab: any): void; static removeTab(tab: any): void; static renameTab(tab: any): void; static removeInTabList(tab: any): void; } } interface Thenable<R> { then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Thenable<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Thenable<U>; } declare class Promise<R> implements Thenable<R> { /** * If you call resolve in the body of the callback passed to the constructor, * your promise is fulfilled with result object passed to resolve. * If you call reject your promise is rejected with the object passed to reject. * For consistency and debugging (eg stack traces), obj should be an instanceof Error. * Any errors thrown in the constructor callback will be implicitly passed to reject(). */ constructor(callback: (resolve: (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => void); /** * onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects. * Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called. * Both callbacks have a single parameter , the fulfillment value or rejection reason. * "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve. * If an error is thrown in the callback, the returned promise rejects with that error. * * @param onFulfilled called when/if "promise" resolves * @param onRejected called when/if "promise" rejects */ then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => U | Thenable<U>): Promise<U>; then<U>(onFulfilled?: (value: R) => U | Thenable<U>, onRejected?: (error: any) => void): Promise<U>; /** * Sugar for promise.then(undefined, onRejected) * * @param onRejected called when/if "promise" rejects */ catch<U>(onRejected?: (error: any) => U | Thenable<U>): Promise<U>; } declare module Promise { /** * Make a new promise from the thenable. * A thenable is promise-like in as far as it has a "then" method. */ function resolve<R>(value?: R | Thenable<R>): Promise<R>; /** * Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error */ function reject(error: any): Promise<any>; /** * Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects. * the array passed to all can be a mixture of promise-like objects and other objects. * The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value. */ function all<R>(promises: (R | Thenable<R>)[]): Promise<R[]>; /** * Make a Promise that fulfills when any item fulfills, and rejects if any item rejects. */ function race<R>(promises: (R | Thenable<R>)[]): Promise<R>; } declare module 'es6-promise' { var foo: typeof Promise; module rsvp { var Promise: typeof foo; } export = rsvp; } declare var cssjs: any; declare module VORLON { class WebStandardsClient extends ClientPlugin { sendedHTML: string; private _doctype; private _currentAnalyze; private _refreshLoop; constructor(); refresh(): void; startClientSide(): void; startNewAnalyze(data: any): void; checkLoadingState(): void; initialiseRuleSummary(rule: any, analyze: any): any; prepareAnalyze(analyze: any): void; endAnalyze(analyze: any): void; cancelAnalyse(id: string): void; analyzeDOM(document: HTMLDocument, htmlContent: string, analyze: any): void; analyzeDOMNode(node: Node, rules: any, analyze: any, htmlContent: string): void; applyDOMNodeRule(node: Node, rule: IDOMRule, analyze: any, htmlContent: string): void; analyzeCssDocument(url: any, content: any, analyze: any): void; analyzeFiles(analyze: any): void; analyzeJsDocument(url: any, content: any, analyze: any): void; getDocumentContent(data: { analyzeid: string; url: string; }, file: { content: string; loaded: boolean; status?: number; encoding?: string; contentLength?: number; error?: any; }, resultcallback: (url: string, file: { content: string; loaded: boolean; }) => void): void; xhrDocumentContent(data: { analyzeid: string; url: string; }, resultcallback: (url: string, content: string, status: number, contentlength?: number, encoding?: string, errors?: any) => void): void; getAbsolutePath(url: any): string; } } declare var cssjs: any; declare module VORLON { class WebStandardsDashboard extends DashboardPlugin { constructor(); private _startCheckButton; private _rootDiv; private _currentAnalyseId; private _analysePending; private _analyseResult; private _cancelMode; private _rulesPanel; private _ruleDetailPanel; private _switchToRun(); private _switchToCancel(); startDashboardSide(div?: HTMLDivElement): void; setAnalyseResult(result: any): void; analyseCanceled(id: string): void; checkLoadingState(): void; } } declare module VORLON { interface IRuleCheck { items?: IRuleCheck[]; title?: string; description?: string; alert?: string; message?: string; content?: string; type?: string; failed?: boolean; data?: any; skipRootLevel?: boolean; } interface IRule { id: string; title: string; disabled?: boolean; description?: string; prepare?: (rulecheck: IRuleCheck, analyzeSummary) => void; endcheck?: (rulecheck: IRuleCheck, analyzeSummary) => void; } interface IDOMRule extends IRule { nodeTypes: string[]; check: (node, rulecheck: IRuleCheck, analyze, htmlcontent) => void; generalRule?: boolean; } interface ICSSRule extends IRule { check: (url: string, ast, rulecheck, analyzeSummary) => void; } interface IFileRule extends IRule { check: (rulecheck: any, analyzeSummary: any) => void; } interface IScriptRule extends IRule { check: (url: string, javascriptContent: string, rulecheck: any, analyzeSummary: any) => void; } } declare module VORLON { class BasePlugin { name: string; _ready: boolean; protected _id: string; _type: PluginType; loadingDirectory: string; constructor(name: string); Type: PluginType; getID(): string; isReady(): boolean; } } declare module VORLON { interface VorlonMessageMetadata { pluginID: string; side: RuntimeSide; messageType: string; } interface VorlonMessage { metadata: VorlonMessageMetadata; command?: string; data?: any; } class ClientMessenger { private _targetTabId; onRealtimeMessageReceived: (message: VorlonMessage) => void; constructor(side: RuntimeSide, targetTabId?: number); sendRealtimeMessage(pluginID: string, objectToSend: any, side: RuntimeSide, messageType?: string, command?: string): void; } } declare module VORLON { class ClientPlugin extends BasePlugin { ClientCommands: any; constructor(name: string); startClientSide(): void; onRealtimeMessageReceivedFromDashboardSide(receivedObject: any): void; sendToDashboard(data: any): void; sendCommandToDashboard(command: string, data?: any): void; trace(message: string): void; refresh(): void; _loadNewScriptAsync(scriptName: string, callback: () => void, waitForDOMContentLoaded?: boolean): void; } } declare module VORLON { } declare module VORLON { class _Core { _clientPlugins: ClientPlugin[]; _dashboardPlugins: DashboardPlugin[]; _messenger: ClientMessenger; _side: RuntimeSide; Messenger: ClientMessenger; ClientPlugins: Array<ClientPlugin>; DashboardPlugins: Array<DashboardPlugin>; RegisterClientPlugin(plugin: ClientPlugin): void; RegisterDashboardPlugin(plugin: DashboardPlugin): void; StartClientSide(): void; StartDashboardSide(tabid: number, divMapper: (number) => HTMLDivElement): void; private _Dispatch(message); private _DispatchPluginMessage(plugin, message); private _DispatchFromClientPluginMessage(plugin, message); private _DispatchFromDashboardPluginMessage(plugin, message); } var Core: _Core; } declare module VORLON { class DashboardPlugin extends BasePlugin { htmlFragmentUrl: any; cssStyleSheetUrl: any; DashboardCommands: any; constructor(name: string, htmlFragmentUrl: string, cssStyleSheetUrl: string); startDashboardSide(div: HTMLDivElement): void; onRealtimeMessageReceivedFromClientSide(receivedObject: any): void; sendToClient(data: any): void; sendCommandToClient(command: string, data?: any): void; trace(message: string): void; _insertHtmlContentAsync(divContainer: HTMLDivElement, callback: (filledDiv: HTMLDivElement) => void): void; private _stripContent(content); } } declare module VORLON { enum RuntimeSide { Client = 0, Dashboard = 1, Both = 2, } enum PluginType { OneOne = 0, MulticastReceiveOnly = 1, Multicast = 2, } } declare module VORLON { class Tools { static QueryString(): {}; static QuerySelectorById(root: HTMLElement, id: string): HTMLElement; static SetImmediate(func: () => void): void; static setLocalStorageValue(key: string, data: string): void; static getLocalStorageValue(key: string): any; static interceptAddEventListener(): void; static Hook(rootObject: any, functionToHook: string, hookingFunction: (...optionalParams: any[]) => void): void; static _callBackID: number; static HookProperty(rootObjectName: string, propertyToHook: string, callback: (stackData: any) => void): void; static getCallStack(skipped: any): any; static CreateCookie(name: string, value: string, days: number): void; static ReadCookie(name: string): string; static CreateGUID(): string; static RemoveEmpties(arr: string[]): number; static AddClass(e: HTMLElement, name: string): HTMLElement; static RemoveClass(e: HTMLElement, name: string): HTMLElement; static ToggleClass(e: HTMLElement, name: string, callback?: (hasClass: boolean) => void): void; static htmlToString(text: any): any; } class FluentDOM { element: HTMLElement; childs: Array<FluentDOM>; parent: FluentDOM; constructor(nodeType: string, className?: string, parentElt?: Element, parent?: FluentDOM); static forElement(element: HTMLElement): FluentDOM; addClass(classname: string): FluentDOM; toggleClass(classname: string): FluentDOM; hasClass(classname: string): boolean; className(classname: string): FluentDOM; opacity(opacity: string): FluentDOM; display(display: string): FluentDOM; hide(): FluentDOM; visibility(visibility: string): FluentDOM; text(text: string): FluentDOM; html(text: string): FluentDOM; attr(name: string, val: string): FluentDOM; editable(editable: boolean): FluentDOM; style(name: string, val: string): FluentDOM; appendTo(elt: Element): FluentDOM; append(nodeType: string, className?: string, callback?: (fdom: FluentDOM) => void): FluentDOM; createChild(nodeType: string, className?: string): FluentDOM; click(callback: (EventTarget) => void): FluentDOM; blur(callback: (EventTarget) => void): FluentDOM; keydown(callback: (EventTarget) => void): FluentDOM; } } declare var axe: any; declare module VORLON.WebStandards.Rules.Accessibility { var aXeCheck: IRule; } declare module VORLON.WebStandards.Rules.DOM { var deviceIcons: IDOMRule; } declare module VORLON.WebStandards.Rules.CSS { var mobileMediaqueries: ICSSRule; } declare module VORLON.WebStandards.Rules.DOM { var mobileMediaqueries: IDOMRule; } declare module VORLON.WebStandards.Rules.DOM { var useViewport: IDOMRule; } declare module VORLON.WebStandards.Rules.Files { var filesBundle: IFileRule; } declare module VORLON.WebStandards.Rules.Files { var contentEncoding: IFileRule; } declare module VORLON.WebStandards.Rules.Files { var filesMinification: IFileRule; } declare module VORLON.WebStandards.Rules.DOM { var dontUsePlugins: IDOMRule; } declare module VORLON.WebStandards.Rules.DOM { var browserdetection: IDOMRule; } declare module VORLON.WebStandards.Rules.DOM { var browserinterop: IDOMRule; } declare module VORLON.WebStandards.Rules.DOM { var dontUseBrowserConditionalComment: IDOMRule; } declare module VORLON.WebStandards.Rules.CSS { var cssfallback: ICSSRule; } declare module VORLON.WebStandards.Rules.CSS { var cssprefixes: ICSSRule; } declare module VORLON.WebStandards.Rules.DOM { var modernDocType: IDOMRule; } declare module VORLON.WebStandards.Rules.JavaScript { var librariesVersions: IScriptRule; }
the_stack
/// <reference types="node" /> import { EventEmitter } from 'events'; export class VASTTracker extends EventEmitter { /** * The VAST tracker constructor will process the tracking URLs of the selected ad/creative and returns an instance of VASTTracker. */ constructor( /** * An optional instance of VASTClient that can be updated by the tracker. */ client: VASTClient | null, /** * The ad of the selected mediaFile to track */ ad: VastAd, /** * The creative of the selected mediaFile to track */ creative: VastCreativeLinear, /** * An optional variation of the creative, for Companion and NonLinear Ads */ variation?: VastCreativeCompanion | VastCreativeNonLinear, ); /** * Sets the duration of the ad and updates the quartiles based on that. */ setDuration(duration: number): void; /** * Update the current time value. * This is required for tracking time related events such as start, firstQuartile, midpoint, thirdQuartile or rewind. */ setProgress( /** * Current playback time in seconds. */ progress: number ): void; /** * Update the mute state and call the mute/unmute tracking URLs. Emit a mute or unmute event. */ setMuted( /** * Indicate if the video is muted or not. */ muted: boolean ): void; /** * Update the pause state and call the resume/pause tracking URLs. Emit a resume or pause event. */ setPaused( /** * Indicate if the video is paused or not. */ paused: boolean ): void; /** * Update the fullscreen state and call the fullscreen tracking URLs. Emit a fullscreen or exitFullscreen event. */ setFullscreen( /** * Indicate the fullscreen mode. */ fullscreen: boolean ): void; /** * Update the expand state and call the expand/collapse tracking URLs. Emit a expand or collapse event */ setExpand( /** * Indicate if the video is expanded or no */ expanded: boolean, ): void; /** * Must be called if you want to overwrite the <Linear> Skipoffset value. This will init the skip countdown duration. * Then, every time you call setProgress(), it will decrease the countdown and emit a skip-countdown event with the remaining time. * Do not call this method if you want to keep the original Skipoffset value. */ setSkipDelay( /** * The time in seconds until the skip button is displayed. */ duration: number ): void; /** * Report the impression URI. Can only be called once. Will report the following URI: * * - All <Impression> URI from the <InLine> and <Wrapper> tracking elements. * - The creativeView URI from the <Tracking> events * * Once done, a creativeView event is emitted. */ trackImpression(): void; /** * Send a request to the URI provided by the VAST <Error> element. If an [ERRORCODE] macro is included, it will be substitute with code. */ errorWithCode( /** * Replaces [ERRORCODE] macro. [ERRORCODE] values are liste in the VAST specification. */ errorCode: string ): void; /** * Must be called when the user watched the linear creative until its end. Call the complete tracking URLs. * Emit a complete events when done. */ complete(): void; /** * Must be called when the player or the window is closed during the ad. Call the closeLinear (in VAST 3.0) and close tracking URLs. * Emit a closeLinear or a close event when done. */ close(): void; /** * Must be called when the skip button is clicked. Call the skip tracking URLs. Emit a skip event when done. */ skip(): void; /** * Must be called when the user clicks on the creative. Call the tracking URLs. * Emit a clickthrough event with the resolved clickThrough URL when done. */ click(): void; /** * Calls the tracking URLs for the given eventName and emits the event. */ track( /** * The name of the event. Call the specified event tracking URLs. Emit the specified event when done. */ eventName: string, /** * Indicate if the event has to be tracked only once. * Default: false */ once?: boolean ): void; } export class VASTClient { constructor( /** * Used for ignoring the first n calls. Automatically reset 1 hour after the 1st ignored call. Free Lunch capping is disable if sets to 0. * Default: 0 */ cappingFreeLunch?: number, /** * Used for ignoring calls that happen n ms after the previous call. Minimum time interval is disabled if sets to 0. * Default: 0 */ cappingMinimumTimeInterval?: number, /** * Optional custom storage to be used instead of the default one */ customStorage?: VASTClientCustomStorage, ); cappingFreeLunch: number; cappingMinimumTimeInterval: number; storage: VASTClientCustomStorage | Storage; /** * Fetch a URL and parse the response into a valid VAST object. * * @param url Contains the URL for fetching the VAST XML document. * @param options An optional set of key/value to configure the Ajax request */ get(url: string, options?: VastRequestOptions): Promise<VastResponse>; /** * Returns a boolean indicating if there are more ads to resolve for the current parsing. */ hasRemainingAds(): boolean; /** * Resolves the next group of ads. If all is true resolves all the remaining ads. */ getNextAds(all?: boolean): Promise<VastResponse>; /** * Returns the instance of VASTParser used by the client to parse the VAST. * Use it to directly call a method provided by the VASTParser class. */ getParser(): VASTParser; } export class VASTParser extends EventEmitter { /** * util method for handling urls, it is used to make the requests. */ urlHandler: VASTClientUrlHandler; /** * Add the replace function at the end of the URLTemplateFilters array. * All functions in URLTemplateFilters will be called with the VAST URL as parameter before fetching the VAST URL document. */ addURLTemplateFilter(cb: (vastUrl: string) => string): void; /** * Removes the last element of the url templates filters array. */ removeURLTemplateFilter(): void; /** * Reset URLTemplateFilters to empty, previous replace function set with addURLTemplateFilter() are no longer called. */ clearUrlTemplateFilters(): void; /** * Returns how many replace function are set (ie: URLTemplateFilters length) */ countURLTemplateFilters(): number; /** * Tracks the error provided in the errorCode parameter and emits a VAST-error event for the given error. */ trackVastError( /** * An Array of url templates to use to make the tracking call */ urlTemplates: string[], errorCode: Pick<VastError, 'ERRORCODE'>, ...data: Array<Pick<VastError, Exclude<keyof VastError, 'ERRORCODE'>>>, ): void; /** * Fetches a VAST document for the given url. * Returns a Promise which resolves with the fetched xml or rejects with an error, according to the result of the request. */ fetchVAST( /** * The url to request the VAST document. */ url: string, /** * how many times the current url has been wrapped */ wrapperDepth?: number, /** * url of original wrapper */ originalUrl?: string ): Promise<Document>; /** * Fetches and parses a VAST for the given url. * Returns a Promise which resolves with a fully parsed VASTResponse or rejects with an Error. */ getAndParseVAST( /** * The url to request the VAST document. */ url: string, /** * An optional Object of parameters to be used in the parsing process. */ options?: VastRequestOptions, ): Promise<VastResponse>; /** * Parses the given xml Object into a VASTResponse. * Returns a Promise which either resolves with the fully parsed VASTResponse or rejects with an Error. */ parseVAST( /** * A VAST XML document */ vastXml: Document, /** * An optional Object of parameters to be used in the parsing process. */ options?: VastRequestOptions, ): Promise<VastResponse>; } export interface VASTClientCustomStorage { getItem(key: string): string | null; setItem(key: string, val: string): void; [key: string]: any | (() => any); } export function UrlHandlerCbType(err: null, xml: XMLDocument): void; export function UrlHandlerCbType(err: Error): void; export interface VASTClientUrlHandler { get( url: string, options: { timeout: number, withCredentials: boolean }, cb: typeof UrlHandlerCbType, ): void; } export interface VastRequestOptions { /** * A custom timeout for the requests (default 0) */ timeout?: number | undefined; /** * A boolean to enable the withCredentials options for the XHR and FLASH URLHandlers (default false) */ withCredentials?: boolean | undefined; /** * A number of Wrapper responses that can be received with no InLine response (default 0) */ wrapperLimit?: number | undefined; /** * Custom urlhandler to be used instead of the default ones urlhandlers */ urlHandler?: VASTClientUrlHandler | undefined; /** * Allows you to parse all the ads contained in the VAST or to parse them ad by ad or adPod by adPod (default true) */ resolveAll?: boolean | undefined; } export interface VastResponse { ads: VastAd[]; errorURLTemplates: string[]; } export interface VastError { /** * Whenever an error occurs during the VAST parsing, the parser will call on its own all related tracking error URLs. Reported errors are: * no_ad: The VAST document is empty * VAST error 101: VAST schema validation error. * VAST error 301: Timeout of VAST URI provided in Wrapper element. * VAST error 302: Wrapper limit reached. * VAST error 303: No VAST response after one or more Wrappers. */ ERRORCODE: string | number; ERRORMESSAGE?: string | undefined; extensions?: VastAdExtension[] | undefined; system?: VastSystem | string | null | undefined; } export interface VastCreative { id: string | null; adId: string | null; trackingEvents: VastTrackingEvents; apiFramework: string | null; sequence: string | number | null; type: string; } export interface VastCreativeLinear extends VastCreative { adParameters: string | null; duration: number; icons: VastIcon[]; mediaFiles: VastMediaFile[]; skipDelay: number | null; videoClickThroughURLTemplate: string | null; videoClickTrackingURLTemplates: string[]; videoCustomClickURLTemplates: string[]; } export interface VastCreativeNonLinear extends VastCreative { variations: VastNonLinearAd[]; } export interface VastCreativeCompanion extends VastCreative { variations: VastCompanionAd[]; } export interface VastAd { advertiser: string | null; creatives: VastCreative[]; description: string | null; errorURLTemplates: string[]; extensions: VastAdExtension[]; id: string | null; impressionURLTemplates: string[]; pricing: string | null; sequence: string | null; survey: string | null; system: VastSystem | string | null; title: string | null; } export interface VastAdExtension { attributes: VastAdAttributes; children: VastAdExtensionChild[]; } export interface VastAdAttributes { type: string; fallback_index: string | null; } export interface VastAdExtensionChild { attributes: VastAdChildAttributes; name: string | undefined; value: string | number; } export interface VastAdChildAttributes { [key: string]: any; } export interface VastNonLinearAd { nonLinearClickTrackingURLTemplates: string[]; nonLinearClickThroughURLTemplate: string | null; adParameters: string | null; type: string | null; iframeResource: string | null; htmlResource: string | null; id: string | null; width: string; height: string; expandedWidth: string; expandedHeight: string; scalable: boolean; maintainAspectRatio: boolean; minSuggestedDuration: number; apiFramework: string; staticResource: string | null; } export interface VastCompanionAd { companionClickThroughURLTemplate: string | null; companionClickTrackingURLTemplate: string | null | undefined; companionClickTrackingURLTemplates: string[]; height: string; htmlResource: string | null; id: string | null; iframeResource: string | null; staticResource: string | null; trackingEvents: VastCompanionTrackingEvents; type: string | null; width: string; altText: string | null; } export interface VastCompanionTrackingEvents { creativeView: string[]; [key: string]: string[]; } export interface VastMediaFile { apiFramework: string | null; bitrate: number; codec: string | null; deliveryType: string; fileURL: string | null; height: number; id: string | null; maintainAspectRatio: boolean | null; maxBitrate: number; mimeType: string | null; minBitrate: number; scalable: boolean | null; width: number; } export interface VastTrackingEvents { complete: string[]; firstQuartile: string[]; midpoint: string[]; thirdQuartile: string[]; [key: string]: string[]; } export interface VastSystem { value: string; version: string | null; } export interface VastIcon { program: string | null; height: number; width: number; xPosition: number; yPosition: number; apiFramework: string | null; offset: string | null; duration: number; type: string | null; staticResource: string | null; htmlResource: string | null; iframeResource: string | null; iconClickThroughURLTemplate: string | null; iconClickTrackingURLTemplates: string[]; iconViewTrackingURLTemplate: string | null; }
the_stack
import '../../../test/common-test-setup-karma'; import './gr-admin-view'; import {AdminSubsectionLink, GrAdminView} from './gr-admin-view'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import {getPluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader'; import {mockPromise, stubBaseUrl, stubRestApi} from '../../../test/test-utils'; import {GerritView} from '../../../services/router/router-model'; import {query, queryAll, queryAndAssert} from '../../../test/test-utils'; import {GrRepoList} from '../gr-repo-list/gr-repo-list'; import {GroupId, GroupName, RepoName, Timestamp} from '../../../types/common'; import {GrDropdownList} from '../../shared/gr-dropdown-list/gr-dropdown-list'; import {GrGroup} from '../gr-group/gr-group'; const basicFixture = fixtureFromElement('gr-admin-view'); function createAdminCapabilities() { return { createGroup: true, createProject: true, viewPlugins: true, }; } suite('gr-admin-view tests', () => { let element: GrAdminView; setup(async () => { element = basicFixture.instantiate(); stubRestApi('getProjectConfig').returns(Promise.resolve(undefined)); const pluginsLoaded = Promise.resolve(); sinon.stub(getPluginLoader(), 'awaitPluginsLoaded').returns(pluginsLoaded); await pluginsLoaded; await element.updateComplete; }); test('link URLs', () => { assert.equal( element.computeLinkURL({name: '', url: '/test', noBaseUrl: true}), '//' + window.location.host + '/test' ); stubBaseUrl('/foo'); assert.equal( element.computeLinkURL({name: '', url: '/test', noBaseUrl: true}), '//' + window.location.host + '/foo/test' ); assert.equal( element.computeLinkURL({name: '', url: '/test', noBaseUrl: false}), '/test' ); assert.equal( element.computeLinkURL({ name: '', url: '/test', target: '_blank', noBaseUrl: false, }), '/test' ); }); test('current page gets selected and is displayed', async () => { element.filteredLinks = [ { name: 'Repositories', url: '/admin/repos', view: 'gr-repo-list' as GerritView, noBaseUrl: false, }, ]; element.params = { view: GerritView.ADMIN, adminView: 'gr-repo-list', }; await element.updateComplete; assert.equal(queryAll<HTMLLIElement>(element, '.selected').length, 1); assert.ok(queryAndAssert<GrRepoList>(element, 'gr-repo-list')); assert.isNotOk(query(element, 'gr-admin-create-repo')); }); test('filteredLinks admin', async () => { stubRestApi('getAccount').returns( Promise.resolve({ name: 'test-user', registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); await element.reload(); assert.equal(element.filteredLinks!.length, 3); // Repos assert.isNotOk(element.filteredLinks![0].subsection); // Groups assert.isNotOk(element.filteredLinks![0].subsection); // Plugins assert.isNotOk(element.filteredLinks![0].subsection); }); test('filteredLinks non admin authenticated', async () => { await element.reload(); assert.equal(element.filteredLinks!.length, 2); // Repos assert.isNotOk(element.filteredLinks![0].subsection); // Groups assert.isNotOk(element.filteredLinks![0].subsection); }); test('filteredLinks non admin unathenticated', async () => { stubRestApi('getAccount').returns(Promise.resolve(undefined)); await element.reload(); assert.equal(element.filteredLinks!.length, 1); // Repos assert.isNotOk(element.filteredLinks![0].subsection); }); test('filteredLinks from plugin', () => { stubRestApi('getAccount').returns(Promise.resolve(undefined)); sinon.stub(element.jsAPI, 'getAdminMenuLinks').returns([ {capability: null, text: 'internal link text', url: '/internal/link/url'}, { capability: null, text: 'external link text', url: 'http://external/link/url', }, ]); return element.reload().then(() => { assert.equal(element.filteredLinks!.length, 3); assert.deepEqual(element.filteredLinks![1], { capability: undefined, url: '/internal/link/url', name: 'internal link text', noBaseUrl: true, view: undefined, viewableToAll: true, target: null, }); assert.deepEqual(element.filteredLinks![2], { capability: undefined, url: 'http://external/link/url', name: 'external link text', noBaseUrl: false, view: undefined, viewableToAll: true, target: '_blank', }); }); }); test('Repo shows up in nav', async () => { element.repoName = 'Test Repo' as RepoName; stubRestApi('getAccount').returns( Promise.resolve({ name: 'test-user', registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); await element.reload(); await element.updateComplete; assert.equal(queryAll<HTMLLIElement>(element, '.sectionTitle').length, 3); assert.equal( queryAndAssert<HTMLSpanElement>(element, '.breadcrumbText').innerText, 'Test Repo' ); assert.equal( queryAndAssert<GrDropdownList>(element, '#pageSelect').items!.length, 7 ); }); test('Group shows up in nav', async () => { element.groupId = 'a15262' as GroupId; element.groupName = 'my-group' as GroupName; element.groupIsInternal = true; stubRestApi('getIsAdmin').returns(Promise.resolve(true)); stubRestApi('getAccount').returns( Promise.resolve({ name: 'test-user', registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); await element.reload(); await element.updateComplete; assert.equal(element.filteredLinks!.length, 3); // Repos assert.isNotOk(element.filteredLinks![0].subsection); // Groups assert.equal(element.filteredLinks![1].subsection!.children!.length, 2); assert.equal(element.filteredLinks![1].subsection!.name, 'my-group'); // Plugins assert.isNotOk(element.filteredLinks![2].subsection); }); test('Nav is reloaded when repo changes', async () => { stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); stubRestApi('getAccount').returns( Promise.resolve({ _id: 1, registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); const reloadStub = sinon.stub(element, 'reload'); element.params = {repo: 'Test Repo' as RepoName, view: GerritView.REPO}; await element.updateComplete; assert.equal(reloadStub.callCount, 1); element.params = {repo: 'Test Repo 2' as RepoName, view: GerritView.REPO}; await element.updateComplete; assert.equal(reloadStub.callCount, 2); }); test('Nav is reloaded when group changes', async () => { sinon.stub(element, 'computeGroupName'); stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); stubRestApi('getAccount').returns( Promise.resolve({ _id: 1, registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); const reloadStub = sinon.stub(element, 'reload'); element.params = {groupId: '1' as GroupId, view: GerritView.GROUP}; await element.updateComplete; assert.equal(reloadStub.callCount, 1); }); test('Nav is reloaded when group name changes', async () => { const newName = 'newName' as GroupName; const reloadCalled = mockPromise(); sinon.stub(element, 'computeGroupName'); sinon.stub(element, 'reload').callsFake(() => { reloadCalled.resolve(); return Promise.resolve(); }); element.params = {groupId: '1' as GroupId, view: GerritView.GROUP}; element.groupName = 'oldName' as GroupName; await element.updateComplete; queryAndAssert<GrGroup>(element, 'gr-group').dispatchEvent( new CustomEvent('name-changed', { detail: {name: newName}, composed: true, bubbles: true, }) ); await reloadCalled; assert.equal(element.groupName, newName); }); test('dropdown displays if there is a subsection', async () => { assert.isNotOk(query(element, '.mainHeader')); element.subsectionLinks = [ { text: 'Home', value: 'repo', view: GerritView.REPO, parent: 'my-repo' as RepoName, detailType: undefined, }, ]; await element.updateComplete; assert.isOk(query(element, '.mainHeader')); element.subsectionLinks = undefined; await element.updateComplete; assert.isNotOk(query(element, '.mainHeader')); }); test('Dropdown only triggers navigation on explicit select', async () => { element.repoName = 'my-repo' as RepoName; element.params = { repo: 'my-repo' as RepoName, view: GerritNav.View.REPO, detail: GerritNav.RepoDetailView.ACCESS, }; stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); stubRestApi('getAccount').returns( Promise.resolve({ _id: 1, registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); await element.updateComplete; const expectedFilteredLinks = [ { name: 'Repositories', noBaseUrl: true, url: '/admin/repos', view: 'gr-repo-list' as GerritView, viewableToAll: true, subsection: { name: 'my-repo', view: GerritView.REPO, children: [ { name: 'General', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.GENERAL, }, { name: 'Access', view: GerritView.REPO, detailType: GerritNav.RepoDetailView.ACCESS, url: '', }, { name: 'Commands', view: GerritView.REPO, detailType: GerritNav.RepoDetailView.COMMANDS, url: '', }, { name: 'Branches', view: GerritView.REPO, detailType: GerritNav.RepoDetailView.BRANCHES, url: '', }, { name: 'Tags', view: GerritView.REPO, detailType: GerritNav.RepoDetailView.TAGS, url: '', }, { name: 'Dashboards', view: GerritView.REPO, detailType: GerritNav.RepoDetailView.DASHBOARDS, url: '', }, ], }, }, { name: 'Groups', section: 'Groups', noBaseUrl: true, url: '/admin/groups', view: 'gr-admin-group-list' as GerritView, }, { name: 'Plugins', capability: 'viewPlugins', section: 'Plugins', noBaseUrl: true, url: '/admin/plugins', view: 'gr-plugin-list' as GerritView, }, ]; const expectedSubsectionLinks = [ { text: 'Home', value: 'repo', view: GerritView.REPO, url: undefined, parent: 'my-repo' as RepoName, detailType: undefined, }, { text: 'General', value: 'repogeneral', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.GENERAL, parent: 'my-repo' as RepoName, }, { text: 'Access', value: 'repoaccess', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.ACCESS, parent: 'my-repo' as RepoName, }, { text: 'Commands', value: 'repocommands', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.COMMANDS, parent: 'my-repo' as RepoName, }, { text: 'Branches', value: 'repobranches', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.BRANCHES, parent: 'my-repo' as RepoName, }, { text: 'Tags', value: 'repotags', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.TAGS, parent: 'my-repo' as RepoName, }, { text: 'Dashboards', value: 'repodashboards', view: GerritView.REPO, url: '', detailType: GerritNav.RepoDetailView.DASHBOARDS, parent: 'my-repo' as RepoName, }, ]; const navigateToRelativeUrlStub = sinon.stub( GerritNav, 'navigateToRelativeUrl' ); const selectedIsCurrentPageSpy = sinon.spy( element, 'selectedIsCurrentPage' ); sinon.spy(element, 'handleSubsectionChange'); await element.reload(); assert.deepEqual(element.filteredLinks, expectedFilteredLinks); assert.deepEqual(element.subsectionLinks, expectedSubsectionLinks); assert.equal( queryAndAssert<GrDropdownList>(element, '#pageSelect').value, 'repoaccess' ); assert.isTrue(selectedIsCurrentPageSpy.calledOnce); // Doesn't trigger navigation from the page select menu. assert.isFalse(navigateToRelativeUrlStub.called); // When explicitly changed, navigation is called queryAndAssert<GrDropdownList>(element, '#pageSelect').value = 'repogeneral'; assert.isTrue(selectedIsCurrentPageSpy.calledTwice); assert.isTrue(navigateToRelativeUrlStub.calledOnce); }); test('selectedIsCurrentPage', () => { element.repoName = 'my-repo' as RepoName; element.params = {view: GerritView.REPO, repo: 'my-repo' as RepoName}; const selected = { view: GerritView.REPO, parent: 'my-repo' as RepoName, value: '', text: '', } as AdminSubsectionLink; assert.isTrue(element.selectedIsCurrentPage(selected)); selected.parent = 'my-second-repo' as RepoName; assert.isFalse(element.selectedIsCurrentPage(selected)); selected.detailType = GerritNav.RepoDetailView.GENERAL; assert.isFalse(element.selectedIsCurrentPage(selected)); }); suite('computeSelectedClass', () => { setup(async () => { stubRestApi('getAccountCapabilities').returns( Promise.resolve(createAdminCapabilities()) ); stubRestApi('getAccount').returns( Promise.resolve({ _id: 1, registered_on: '2015-03-12 18:32:08.000000000' as Timestamp, }) ); await element.reload(); }); suite('repos', () => { setup(() => { stub('gr-repo-access', '_repoChanged').callsFake(() => Promise.resolve() ); }); test('repo list', async () => { element.params = { view: GerritNav.View.ADMIN, adminView: 'gr-repo-list', openCreateModal: false, }; await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'Repositories'); }); test('repo', async () => { element.params = { view: GerritNav.View.REPO, repo: 'foo' as RepoName, }; element.repoName = 'foo' as RepoName; await element.reload(); await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'foo'); }); test('repo access', async () => { element.params = { view: GerritNav.View.REPO, detail: GerritNav.RepoDetailView.ACCESS, repo: 'foo' as RepoName, }; element.repoName = 'foo' as RepoName; await element.reload(); await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'Access'); }); test('repo dashboards', async () => { element.params = { view: GerritNav.View.REPO, detail: GerritNav.RepoDetailView.DASHBOARDS, repo: 'foo' as RepoName, }; element.repoName = 'foo' as RepoName; await element.reload(); await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'Dashboards'); }); }); suite('groups', () => { let getGroupConfigStub: sinon.SinonStub; setup(async () => { stub('gr-group', 'loadGroup').callsFake(() => Promise.resolve()); stub('gr-group-members', 'loadGroupDetails').callsFake(() => Promise.resolve() ); getGroupConfigStub = stubRestApi('getGroupConfig'); getGroupConfigStub.returns( Promise.resolve({ name: 'foo', id: 'c0f83e941ce90caea30e6ad88f0d4ea0e841a7a9', }) ); stubRestApi('getIsGroupOwner').returns(Promise.resolve(true)); await element.reload(); }); test('group list', async () => { element.params = { view: GerritNav.View.ADMIN, adminView: 'gr-admin-group-list', openCreateModal: false, }; await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'Groups'); }); test('internal group', async () => { element.params = { view: GerritNav.View.GROUP, groupId: '1234' as GroupId, }; element.groupName = 'foo' as GroupName; await element.reload(); await element.updateComplete; const subsectionItems = queryAll<HTMLLIElement>( element, '.subsectionItem' ); assert.equal(subsectionItems.length, 2); assert.isTrue(element.groupIsInternal); const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'foo'); }); test('external group', async () => { getGroupConfigStub.returns( Promise.resolve({ name: 'foo', id: 'external-id', }) ); element.params = { view: GerritNav.View.GROUP, groupId: '1234' as GroupId, }; element.groupName = 'foo' as GroupName; await element.reload(); await element.updateComplete; const subsectionItems = queryAll<HTMLLIElement>( element, '.subsectionItem' ); assert.equal(subsectionItems.length, 0); assert.isFalse(element.groupIsInternal); const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'foo'); }); test('group members', async () => { element.params = { view: GerritNav.View.GROUP, detail: GerritNav.GroupDetailView.MEMBERS, groupId: '1234' as GroupId, }; element.groupName = 'foo' as GroupName; await element.reload(); await element.updateComplete; const selected = queryAndAssert(element, 'gr-page-nav .selected'); assert.isOk(selected); assert.equal(selected.textContent!.trim(), 'Members'); }); }); }); });
the_stack
import { state, mechanicsEngine } from "../.."; import { Language } from "../../state"; /** * Translations table */ export class Translations { /** * Spanish translations */ private readonly es = { ////////////////////////////////////// // Action chart / object tables ////////////////////////////////////// "actionChart" : "Carta de Acción", "combatSkill" : "Destreza en el Combate", "endurancePoints" : "Puntos de Resistencia", "actionBeltPouch" : "Bolsa (Máx. 50)", "kaiDisciplines" : "Diciplinas del Kai", "weapons" : "Armas", "currentWeapon" : "Arma actual:", "backpackItems" : "Objetos de Mochila", "meals" : "Comidas", "specialItems" : "Objetos Especiales", "noneFemenine" : "Ninguna", "noneMasculine" : "Ninguno", "disciplineDescription" : "Descripción de la disciplina", "goldCrowns" : "Coronas de Oro", "arrows" : "Flechas", "current" : "Actual", "backpackLost" : "Has perdido tu mochila", "buyObject" : "Comprar objeto", "pickObject" : "Coger objeto", "sellObject" : "Vender objeto", "use": "Usar", "setCurrentWeapon" : "Establecer como arma actual", "dropObject" : "Dejar objeto", "confirmSell" : "¿Seguro que quieres vender el objeto por {0} Coronas de Oro?", "confirmUse" : '¿Estás seguro que quieres usar "{0}"?', "confirmDrop" : '¿Seguro que quieres dejar "{0}"?', "noEnoughMoney" : "No tienes suficiente dinero", "confirmBuy" : "¿Seguro que quieres comprar el objeto por {0} Coronas de Oro?", "msgGetObject" : 'Has cogido "{0}"', "msgDropObject" : 'Has dejado "{0}"', "msgGetMeal" : "Has cogido {0} comidas", "msgDropMeal" : "Has dejado {0} comidas", "msgGetMoney" : "Has cogido {0} Coronas de Oro", "msgGetArrows" : "Has cogido {0} Flechas", "msgDropMoney" : "Has perdido {0} Coronas de Oro", "msgDropArrows" : "Has perdido {0} Flechas", "msgEndurance" : "{0} Puntos de Resistencia", "msgCombatSkill" : "{0} Destreza en el Combate", "msgCurrentWeapon" : 'Tu arma actual es ahora "{0}"', "msgIncompatible" : 'Ya tienes un "{0}"', "msgNoMoreWeapons" : "No puedes coger mas armas", "msgAlreadyBackpack" : "Ya tienes una mochila", "msgNoMoreBackpackItems" : "No puedes coger mas Objetos de Mochila", "msgNoMoreSpecialItems" : "No puedes coger mas Objetos Especiales", "noWeapon" : "Sin arma", "weaponskill" : "Dominio Manejo Armas", "weaponmastery" : "Maestría Manejo Armas", "grdweaponmastery" : "Gran Maestría en el Manejo de Armas", "mindblast" : "Ataque Psíquico", "psisurge" : "Acometida Psíquica", "kaisurge": "Embestida Psíquica", "countAsObjects" : "(Cuenta como {0} objetos)", "annotations" : "Anotaciones", "circleFire" : "Círculo de Fuego", "circleLight" : "Círculo de Luz", "circleSolaris" : "Círculo de Solaris", "circleSpirit" : "Círculo del Espíritu", "circles" : "Círculos de la Ciencia:", "kaiLevel" : "Nivel del Kai", "dropMoney" : "Dejar dinero", "pickMoney" : "Coger dinero", "amount" : "Cantidad", "maxSpecialItems" : "A partir de este libro, el número máximo de Objetos Especiales que puedes " + "llevar es de 12. Podrás dejar el resto en un lugar seguro del monasterio del Kai, o dejarlo aquí. " + "Si se deja aquí, el objeto se perderá. Por favor, deja los Objetos Especiales antes de continuar.", "noQuiversEnough" : "No tienes suficientes Carcajes (sólo 6 Flechas por Carcaj)", "restore20EPMagnakaiButton": "Medicina: +20 R (sólo si R 6 o menos, cada 100 días)", "restore20EPGrdMasterButton": "Sanación: +20 R (sólo si R 8 o menos, cada 20 días)", "confirm20EP": "Esta habilidad solo puede ser usada una vez cada 100 días. ¿Continuamos?", "confirm20EPGrdMaster": "Esta habilidad solo puede ser usada una vez cada 20 días. ¿Continuamos?", "more" : "Más", "fightUnarmed" : "Luchar desarmado", "permanent" : "Permanente", "usageCount" : "(se puede usar {0} veces)", "objectUsed" : "{0} usado", "mentora": "Mentor", ////////////////////////////////////// // Combats ////////////////////////////////////// "combatRatio" : "PUNTUACIÓN EN EL COMBATE", "randomTable" : "Tabla de la Suerte", "randomTableSmall" : "T.S.", "loneWolf": "Lobo Solitario", "combatSkillUpper" : "DESTREZA EN EL COMBATE", "enduranceUpper" : "RESISTENCIA", "playTurn" : "Jugar turno", "eludeCombat" : "Eludir combate", "deathLetter" : "M", "mechanics-combat-psisurge" : "Acometida Psíquica: +{0} DC, -{1} R por asalto", "mechanics-combat-kaisurge" : "Embestida Psíquica: +{0} DC, -{1} R por asalto", "sectionModifier" : "Modificador sección", "objectsUse" : "Uso objetos", "enemyMindblast" : "Ataque psíquico enemigo", ////////////////////////////////////// // Meals ////////////////////////////////////// "meal" : "Comida", "useHunting" : "Usar la disciplina de Caza", "eatBackpackMeal" : "Comer una Comida de la Mochila", "eatBackpackObject" : "Comer", "buyMeal" : "Comprar comida", "doNotEat" : "No comer (-3 RESISTENCIA)", ////////////////////////////////////// // Death ////////////////////////////////////// "msgDeath" : "Tu vida y tu misión terminan aquí", "deathRestartBook" : "Haz click aquí para reiniciar el libro", "deathLoadGame" : "Haz click aquí para cargar un juego salvado", ////////////////////////////////////// // Number picker ////////////////////////////////////// "npWrongValue" : 'Valor erroneo para "{0}"', "npMinValue" : 'El valor mínimo para "{0}" es {1}', "npMaxValue" : 'El valor máximo para "{0}" es {1}', ////////////////////////////////////// // Game setup ////////////////////////////////////// "chooseNumberOn" : "Elige un numero en la", "determineCS" : "para determinar tu Destreza en el Combate", "determineE" : "para determinar tu Resistencia", "combatSkillSet" : "Tu Destreza en el Combate es {0}", "enduranceSet" : "Tus puntos de Resistencia son {0}", "selectNDisciplines" : 'Por favor, selecciona <span id="mechanics-nDisciplines"></span> disciplinas antes de continuar.', "selectNWeapons" : 'Por favor, selecciona <span id="mechanics-setDisciplines-weaponsmax">3</span> armas para Maestría en el Manejo de Armas', "choose" : "Elige", "maxDisciplines" : "Sólo puede elegir {0} disciplinas", "onlyNWeapons" : "Sólo puedes elegir {0} armas", "actionchartinfo" : "<p>" + "Las siguientes secciones explican como jugar con los libros en papel. Esta aplicación es una adaptación de los " + 'librojuegos, y no necesitarás escribir nada en la Carta de Acción (excepto en el campo de "Anotaciones"). La ' + "aplicación intenta hacer toda la contabilidad del juego.</p>" + "<p>En la Carta de Acción puedes consultar tus estadisticas y gestionar tu inventario (usar o dejar objetos, " + "cambiar tu arma actual, ...).</p>" + '<p>Cada vez que vean un texto azul en negrita como este "<a class="random action">Un texto</a>" en el texto ' + "del libro, es una acción. Normalmente será elegir un número de la Tabla de la Suerte. Pincha en el para hacer " + "dicha acción.</p>" + '<p>Los textos en azul que no estén en negrita como este "<a>Un texto</a>" son enlaces a otros sitios (p.ej. a ' + "la Carta de Acción, o al mapa, ...). Si pinchas en ellos irás allí.</p>" + "Al final de esta página encontrás dos enlaces para elegir tu Destreza en el Combate y Resistencia. Pincha en " + "ellos antes de continuar a la siguiente sección.</p>", ////////////////////////////////////// // Grand Master upgrade ////////////////////////////////////// "gmupgrade-info": 'De acuerdo con <a href="https://www.projectaon.org/en/ReadersHandbook/GrandMaster" target="_blank">El Manual del Lector</a>, ' + "puedes cambiar tus puntuaciones al inicio de Gran Maestro. Soportamos las recomendaciones del Manual:", "gmupgrade-same": "Continuar con tus puntuaciones, bonus y objetos actuales", "gmupgrade-nobonus": "Descartar tus puntuaciones actuales y elegir nuevas, sumando 25 y 30 a la Tabla de la Suerte, descartar " + "todos los bonus, y mantener tus armas y objetos", "gmupgrade-reroll": "Descartar tus puntuaciones actuales y elegir nuevas, sumando 25 y 30 a la Tabla de la Suerte, pero mantener " + "todos los bonus, armas y objetos", "gmupgrade-increasestats": "Compensar el cambio de los modificadores a la Tabla de la Suerte, añadiendo 15 y 10 a tus anteriores " + "puntuaciones", "gmupgrade-newplayer": "Descartar todo (esto es: puntuaciones, armas, bonus y objetos) y empezar con un nuevo personaje", "gmupgrade-apply": "Aplicar cambios", "gmupgrade-confirm": "¡ESTOS CAMBIOS NO SE PUEDEN DESHACER! ¿Estas seguro que quieres aplicarlos?", "gmupgrade-applied": "Cambios aplicados", ////////////////////////////////////// // Special sections ////////////////////////////////////// "beltPouch" : "Bolsa", "moneyWon" : "Dinero ganado", "numberToBet" : "Numero a apostar", "crownsToBet" : "Coronas a apostar", "play" : "Jugar", "playerDices" : "Dados de {0}", "playerNumber" : "Jugador {0}", "targetPoints" : "BLANCOS LOBO SOLITARIO:", "number" : "Número {0}", "shoot" : "Disparo", "adganaUse" : "Uso de adgana, número Tabla Suerte: {0}", "heads" : "Cara", "tails" : "Cruz", ////////////////////////////////////// // About page ////////////////////////////////////// "about" : "Acerca del libro", "forSommerlund" : "¡Por Sommerlund y el Kai!", "dedication" : "Dedicatoria", "gameMechanics" : "Mecanicas del juego", "aboutKaiChronicles" : "Mecánicas del juego escritas por Toni Bennasar, Timendum, Michael Terry, Javier Fernández-Sanguino, James Koval, Rendall, Garrett Scott, Julian Egelstaff y Cracrayol. El código está bajo licencia MIT. Contiene partes de código de Lone Wolf Adventures, creado por Liquid State Limited.", "distribution" : "Distribución", "distributionInfo" : 'Libro distribuido por el <a href="https://www.projectaon.org">Proyecto Aon</a>, bajo la <a href="#projectAonLicense">licencia del Proyecto Aon</a>.', "about-authors" : "Sobre los autores del libro", "webPlay" : 'Puedes jugar a este juego en un navegador web en <a class="breakable" href="https://www.projectaon.org/staff/toni">https://www.projectaon.org/staff/toni</a>.', ////////////////////////////////////// // Main menu ////////////////////////////////////// "appInfo" : "Esto es una aplicación para jugar a los librojuegos de Lobo Solitario, del 1 al 13.", "browsersWarning" : "Sólo se soportan las últimas versiones de Chrome y Firefox. Otros navegadores o versiones no están soportados (pueden funcionar... o no).", "historyWarning" : "Ten en cuenta que si borras el historial de tu navegador, perderás la partida actual. Puedes guardar la partida actual a un archivo en <i>Ajustes &gt; Guardar juego</i>.", "androidInfo" : 'Puedes jugar a esto en una aplicación Android (versión mínima 5.1). Descárgala en el <a href="https://play.google.com/store/apps/details?id=org.projectaon.kaichronicles">Google Play</a>.', "haveFun" : "¡Divierte!", "continueGame" : "Continuar el juego", "newGame" : "Nuevo juego", "downloadBooks" : "Descargar libros", "privacy" : "Política de privacidad", "menu-changecolor" : "Cambiar color", ////////////////////////////////////// // New game ////////////////////////////////////// "book" : "Libro", "language" : "Idioma", "english" : "Ingles", "spanish" : "Español", "agreeLicense" : "Estoy de acuerdo con los términos de la licencia del Proyecto Aon", "youMustAgree" : "Has de estar de acuerdo con la licencia para poder continuar", "licenseText" : "Texto de la licencia", "startGame" : "Iniciar juego", "noDownloadedBooks" : 'No se ha descargado ningún libro. Ve a "Descargar libros" en el menú principal', ////////////////////////////////////// // Settings ////////////////////////////////////// "settings" : "Ajustes", "saveGame" : "Guardar partida", "restartBook" : "Reiniciar libro", "downloading" : "Descargando", "downloadingWait" : "Descargando el libro, por favor, espere...", "fileName" : "Nombre archivo", "close" : "Cerrar", "wrongFileName" : "El nombre de archivo contiene carácteres no válidos", "gameSaved" : "Partida guardada", "confirmRestart" : "¿Seguro que quieres reiniciar el libro?", "randomTableValues" : "Valores de la Tabla de la Suerte", "computerGenerated" : "Generados por ordenador", "manual" : "Manuales", "extendedCRT" : "¿Usar Tablas de Combate Extendidas (LW club newsletter 29)?", "Yes" : "Sí", "No" : "No", "colorTheme" : "Tema de color", "settings-light" : "Dia", "settings-dark" : "Noche", ////////////////////////////////////// // Template (Main page) ////////////////////////////////////// "CS" : "D.C.", "E" : "R.", "map" : "Mapa", ////////////////////////////////////// // Map ////////////////////////////////////// "map-clickinfo" : "Haz click en el mapa para ajustar al tamaño de la pantalla / restaurar a su tamaño original.", "map-changezoom" : "Cambiar zoom:", ////////////////////////////////////// // Download books ////////////////////////////////////// "applyChanges" : "Aplicar cambios", "selectBooks" : 'Selecciona los libros que quieres descargar del <a href="https://www.projectaon.org">Proyecto Aon</a>.', "noChangesSelected" : "No se han seleccionado cambios", "confirmChanges" : "¿Seguro que quieres hacer los cambios seleccionados?", "deletingBook" : "Borrando libro {0}", "bookDeleted" : "Libro {0} borrado", "deletionFailed" : "Borrado del libro {0} fallido: {1}", "downloadingBook" : "Descargando libro {0}", "bookDownloaded" : "Libro {0} descargado", "downloadFailed" : "Descarga del libro {0} fallida: {1}", "processFinishedErrors" : "¡Proceso finalizado con errores!", "size" : "Tam.", "noInternet" : "No hay conexión a Internet", "cancel" : "Cancelar", "processCancelled" : "Proceso cancelado", "confirmCancel" : "¿Seguro que quiere cancelar?", ////////////////////////////////////// // Kai monastery safekeeping ////////////////////////////////////// "kaiMonasteryStorage" : "Objetos en el monasterio del Kai", "kaiMonastery" : "Monasterio del Kai", "kaiMonasteryInfo" : "Aquí puedes guardar objetos en custodia en el monasterio del Kai. Los objetos " + 'dejados aquí estarán disponibles cuando continues al próximo libro, en la sección "Equipo". Para guardarlos, ve ' + 'a la <a href="#actionChart">Carta de Acción</a> y deja los objetos que quieres guardar.', "backToEquipment" : "Volver a la sección de Equipo", ////////////////////////////////////// // Load game ////////////////////////////////////// "loadGame" : "Cargar juego", "fileDeleted" : "{0} borrado", "confirmDeleteSave" : "¿Seguro que quiere borrar el juego guardado {0}?", "noSavedGames" : "No se encontraron juegos guardados", "exportedDownloads" : "Juegos exportados a Descargas", "importedGames" : "{0} juegos importados", "exportGames" : "Exportar juegos guardados...", "importGames" : "Importar juegos guardados...", "importExtensionsError" : 'Sólo se pueden importar archivos con extensión "zip" o "json"', "confirmSavedOverwrite" : "Las siguientes partidas se sobreescribirán. ¿Seguro que quiere continuar?:\n{0}", "confirmExport" : 'Esto creará un archivo Zip con todos los juegos guardados en "Descargas". ' + "Esto puede ser útil para copiar tus juegos guardados a otro dispositivo, o como copia de seguridad. ¿Continuamos?", "infoImport" : "Con esta función puedes importar juegos guardados a la aplicación. Esto puede ser útil para copiar " + "tus juegos guardados desde otro dispositivo. Puedes seleccionar ficheros con " + 'extensión "json" (un juego guardado) o "zip" (múltiples juegos guardados)', "fileslistExplain" : "Pincha en un juego de la lista para recuperarlo. Puedes guardar el juego actual en " + "<i>Ajustes &gt; Guardar partida</i>.", "exportImportGames" : "Exportar / importar partidas", "exportImportGamesExplain": "Puedes exportar e importar las partidas guardadas en la aplicación. Esto puede ser útil " + "para copiarlas desde / hacia otros dispositivos.", "errorExporting" : "Error exportando juegos guardados", "noGamesToExport" : "No hay ninguna partida guardada que exportar", ////////////////////////////////////// // Others ////////////////////////////////////// "tableAvailableObjects" : "Objetos disponibles:", "tableSellObjects" : "Vender objetos:", "doMealFirst" : "Haz primero la comida", "kaiChronicles" : "Crónicas del Kai", "gameRules" : "Reglas del juego", "projectAonLicense" : "Licencia del Proyecto Aon", "combatTables" : "Tablas de Combate", "mainMenu" : "Menú principal", "bookNotDownloaded" : "El libro {0} no está descargado", "maximumPick" : "Sólo puedes coger {0} objetos", "zeroIgnored" : "Cero ignorado", "faq" : "Preguntas frecuentes" }; /** * English translations */ private readonly en = { ////////////////////////////////////// // Action chart / object tables ////////////////////////////////////// "actionChart" : "Action Chart", "noneFemenine" : "None", "noneMasculine" : "None", "disciplineDescription" : "Discipline description", "goldCrowns" : "Gold Crowns", "arrows" : "Arrows", "current" : "Current", "backpackLost" : "You have lost your backpack", "buyObject" : "Buy object", "pickObject" : "Get object", "sellObject" : "Sell object", "use": "Use", "setCurrentWeapon" : "Set as current weapon", "dropObject" : "Drop object", "confirmSell" : "Are you sure you want to sell the object for {0} Gold Crowns?", "confirmUse" : 'Are you sure you want to use "{0}"?', "confirmDrop" : 'Are you sure you want to drop "{0}"?', "noEnoughMoney" : "You don't have enough money", "confirmBuy" : "Are you sure you want to buy the object for {0} Gold Crowns?", "msgGetObject" : 'You get "{0}"', "msgDropObject" : 'You drop "{0}"', "msgGetMeal" : "You get {0} meals", "msgDropMeal" : "You drop {0} meals", "msgGetMoney" : "You get {0} Gold Crowns", "msgGetArrows" : "You get {0} Arrows", "msgDropMoney" : "You lost {0} Gold Crowns", "msgDropArrows" : "You lost {0} Arrows", "msgEndurance" : "{0} Endurance Points", "msgCombatSkill" : "{0} Combat Skill", "msgCurrentWeapon" : 'Your current weapon is now "{0}"', "msgIncompatible" : 'You already have a "{0}"', "msgNoMoreWeapons" : "You cannot get more weapons", "msgAlreadyBackpack" : "You already have a Backpack", "msgNoMoreBackpackItems" : "You cannot get more Backpack Items", "msgNoMoreSpecialItems" : "You cannot get more Special Items", "noWeapon" : "No weapon", "weaponskill" : "Weaponskill", "weaponmastery" : "Weaponmastery", "grdweaponmastery" : "Grand Weaponmastery", "mindblast" : "Mindblast", "psisurge" : "Psi-surge", "kaisurge" : "Kai-surge", "countAsObjects" : "(Counts as {0} items)", "circleFire" : "Circle of Fire", "circleLight" : "Circle of Light", "circleSolaris" : "Circle of Solaris", "circleSpirit" : "Circle of the Spirit", "kaiLevel" : "Kai Level", "dropMoney" : "Drop money", "pickMoney" : "Pick money", "amount" : "Amount", "noQuiversEnough" : "You don't have enough Quivers (only 6 Arrows per Quiver)", "restore20EPMagnakaiButton": "Curing: +20 EP (only if EP 6 or less, once every 100 days)", "restore20EPGrdMasterButton": "Deliverance: +20 EP (only if EP 8 or less, once every 20 days)", "confirm20EP": "This ability can only be used once every 100 days. Continue?", "confirm20EPGrdMaster": "This ability can only be used once every 20 days. Continue?", "more" : "More", "permanent" : "Permanent", "usageCount" : "(can be used {0} times)", "objectUsed" : "{0} has been used", "mentora": "Mentora", ////////////////////////////////////// // Combats ////////////////////////////////////// "randomTable" : "Random Number Table", "combatSkillUpper" : "COMBAT SKILL", "enduranceUpper" : "ENDURANCE", "loneWolf": "Lone Wolf", "deathLetter" : "K", "mechanics-combat-psisurge" : "Psi-surge: +{0} CS, -{1} EP per round", "mechanics-combat-kaisurge" : "Kai-surge: +{0} CS, -{1} EP per round", "sectionModifier" : "Section modifier", "objectsUse" : "Objects use", "enemyMindblast" : "Enemy mindblast", ////////////////////////////////////// // Number picker ////////////////////////////////////// "npWrongValue" : 'Wrong value for "{0}"', "npMinValue" : 'Minimum value for "{0}" is {1}', "npMaxValue" : 'Maximum value for "{0}" is {1}', ////////////////////////////////////// // Game setup ////////////////////////////////////// "combatSkillSet" : "Your Combat Skill is {0}", "enduranceSet" : "Your Endurance Points are {0}", "maxDisciplines" : "You can choose only {0} disciplines", "onlyNWeapons" : "You can select only {0} weapons", ////////////////////////////////////// // Grand Master upgrade ////////////////////////////////////// "gmupgrade-confirm": "THESE CHANGES CANNOT BE UNDONE! Are you sure you want to apply them?", "gmupgrade-applied": "Changes applied", ////////////////////////////////////// // Special sections ////////////////////////////////////// "playerDices" : "{0} dices", "playerNumber" : "Player {0}", "number" : "Number {0}", "adganaUse" : "Adgana use, Random Table number: {0}", "heads" : "Heads", "tails" : "Tails", ////////////////////////////////////// // About page ////////////////////////////////////// "about" : "About the book", ////////////////////////////////////// // New game ////////////////////////////////////// "youMustAgree" : "You must agree the licence to continue", "noDownloadedBooks" : 'There are no downloaded books. Go to "Download books" on the main menu', ////////////////////////////////////// // Settings ////////////////////////////////////// "settings" : "Settings", "wrongFileName" : "The file name contains invalid characters", "gameSaved" : "Game saved", "confirmRestart" : "Are you sure you want to restart the book?", "close" : "Close", ////////////////////////////////////// // Template (Main page) ////////////////////////////////////// "CS" : "C.S.", "E" : "E.", "map" : "Map", ////////////////////////////////////// // Download books ////////////////////////////////////// "noChangesSelected" : "No changes selected", "confirmChanges" : "Are you sure you want to do the selected changes?", "deletingBook" : "Deleting book {0}", "bookDeleted" : "Book {0} deleted", "deletionFailed" : "Book {0} deletion failed: {1}", "downloadingBook" : "Downloading book {0}", "bookDownloaded" : "Book {0} downloaded", "downloadFailed" : "Book {0} download failed: {1}", "processFinishedErrors" : "Process finished with errors!", "noInternet" : "There is no Internet connection", "cancel" : "Cancel", "processCancelled" : "Process cancelled", "confirmCancel" : "Are you sure you want to cancel?", ////////////////////////////////////// // Load game ////////////////////////////////////// "noSavedGames" : "No saved games found", "confirmDeleteSave" : "Are you sure you want to delete the save game {0} ?", "fileDeleted" : "{0} deleted", "exportedDownloads" : "Saved games exported to Downloads", "importedGames" : "{0} games imported", "importExtensionsError" : 'Only files with extension "zip" or "json" can be imported', "confirmSavedOverwrite" : "Following saved games will be overwritten. Are you sure you want to continue?:\n{0}", "confirmExport" : 'This will create a Zip file with all your saved games at "Downloads". ' + "This can be useful to copy your saved games to other device, or as a backup. Continue?", "infoImport" : "With this function you can import saved games to the application. " + "This can be useful to copy your saved games from other device. You can select files with " + 'extension "json" (single saved games) or "zip" (multiple saved games)', "errorExporting" : "Error exporting saved games", "noGamesToExport" : "There is no saved game to export", ////////////////////////////////////// // Others ////////////////////////////////////// "doMealFirst" : "Please, do the Meal first", "kaiChronicles" : "Kai Chronicles", "projectAonLicense" : "Project Aon license", "combatTables" : "Combat Tables", "mainMenu" : "Main Menu", "bookNotDownloaded" : "Book {0} is not downloaded", "maximumPick" : "You can pick only {0} objects", "zeroIgnored" : "Zero ignored", "gameRules" : "Game rules" }; /** * Returns a DOM view translated to the current language * @param {DOM} view The view to translate * @param {boolean} doNotClone True if the view should be modified. False, if a clone of the view * should be returned */ public translateView( view: HTMLElement | JQuery<HTMLElement> , doNotClone: boolean = false ): JQuery<HTMLElement> { const table = this[state.language]; if ( !table ) { // Translation not available mechanicsEngine.debugWarning("Translations table not found: " + state.language); return $(view); } let $clonedView; if ( doNotClone ) { $clonedView = $(view); } else { $clonedView = $(view).clone(); } // Translate the view this.translateTags( $clonedView , table ); return $clonedView; } /** * Translate an HTML fragment * @param $tags jQuery selector of tags to translate * @param table Translations table to use. If null, the current language will be used */ public translateTags( $tags: JQuery<HTMLElement> , table: { [key: string]: string } = null ) { // TODO: Is all this needed for SOME English translation? I suspect not, as the default text for HTML texts is English... // TODO: As I'm not sure, I will not change it if ( !table ) { table = this[state.language]; if ( !table ) { // Translation not available mechanicsEngine.debugWarning("Translations table not found: " + state.language); return; } } const $translatedTags = $tags .find("[data-translation]") .addBack("[data-translation]"); for (const translatedTag of $translatedTags.toArray()) { const $t = $(translatedTag); const translationId = $t.attr("data-translation"); const html = table[ translationId ]; if ( html ) { $t.html( html ); } else if (state.language !== Language.ENGLISH) { mechanicsEngine.debugWarning("data-translation not found: " + translationId + ", language: " + state.language); } } } /** * Get a translated message * @param {string} textId The text it to get * @param {Array<object>} replacements Replacements to do on the message. It can be null * @returns {string} The text */ public text( textId: string , replacements: any[] = null ): string { try { let table = this[state.language]; if ( !table ) { // Use english as default mechanicsEngine.debugWarning("Translations table not found: " + state.language); table = this.en; } let text = table[textId]; if ( !text ) { mechanicsEngine.debugWarning("Text code not found: " + textId + ", language: " + state.language); text = textId; } if ( replacements ) { // TODO: Check replacements in debug mode for (let i = 0; i < replacements.length; i++) { text = text.replaceAll( "{" + i + "}" , replacements[i].toString() ); } } return text; } catch (e) { mechanicsEngine.debugWarning(e); return textId; } } } /** * The translations singleton */ export const translations = new Translations();
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as crypto from 'crypto'; import * as EventEmitter from 'events'; import { format, debuglog } from 'util'; import * as moment from 'moment'; import * as assert from 'assert'; import { debounce } from './util'; const debug = debuglog('midway-logger'); const staticFrequency = ['daily', 'test', 's', 'm', 'h', 'custom']; const DATE_FORMAT = 'YYYYMMDDHHmm'; /** * Returns frequency metadata for minute/hour rotation * @param type * @param num * @returns {*} * @private */ const checkNumAndType = function (type, num) { if (typeof num === 'number') { switch (type) { case 's': case 'm': if (num < 0 || num > 60) { return false; } break; case 'h': if (num < 0 || num > 24) { return false; } break; } return { type: type, digit: num }; } }; /** * Returns frequency metadata for defined frequency * @param freqType * @returns {*} * @private */ const _checkDailyAndTest = function (freqType) { switch (freqType) { case 'custom': case 'daily': return { type: freqType, digit: undefined }; case 'test': return { type: freqType, digit: 0 }; } return false; }; /** * Removes old log file * @param file * @param file.hash * @param file.name * @param file.date */ function removeFile(file) { if ( file.hash === crypto .createHash('md5') .update(file.name + 'LOG_FILE' + file.date) .digest('hex') ) { try { if (fs.existsSync(file.name)) { fs.unlinkSync(file.name); } } catch (e) { debug( new Date().toLocaleString(), '[FileStreamRotator] Could not remove old log file: ', file.name ); } } } /** * Create symbolic link to current log file * @param {String} logfile * @param {String} name Name to use for symbolic link */ function createCurrentSymLink(logfile, name) { const symLinkName = name || 'current.log'; const logPath = path.dirname(logfile); const logfileName = path.basename(logfile); const current = logPath + '/' + symLinkName; try { const stats = fs.lstatSync(current); if (stats.isSymbolicLink()) { fs.unlinkSync(current); fs.symlinkSync(logfileName, current); } } catch (err) { if (err && err.code === 'ENOENT') { try { fs.symlinkSync(logfileName, current); } catch (e) { debug( new Date().toLocaleString(), '[FileStreamRotator] Could not create symlink file: ', current, ' -> ', logfileName ); } } } } /** * Check and make parent directory * @param pathWithFile */ const mkDirForFile = function (pathWithFile) { const _path = path.dirname(pathWithFile); _path.split(path.sep).reduce((fullPath, folder) => { fullPath += folder + path.sep; if (!fs.existsSync(fullPath)) { fs.mkdirSync(fullPath); } return fullPath; }, ''); }; /** * Bubbles events to the proxy * @param emitter * @param proxy * @constructor */ function BubbleEvents(emitter, proxy) { emitter.on('close', () => { proxy.emit('close'); }); emitter.on('finish', () => { proxy.emit('finish'); }); emitter.on('error', err => { proxy.emit('error', err); }); emitter.on('open', fd => { proxy.emit('open', fd); }); } export class FileStreamRotator { /** * Returns frequency metadata * @param frequency * @returns {*} */ getFrequency(frequency) { const f = frequency.toLowerCase().match(/^(\d+)([smh])$/); if (f) { return checkNumAndType(f[2], parseInt(f[1])); } const dailyOrTest = _checkDailyAndTest(frequency); if (dailyOrTest) { return dailyOrTest; } return false; } /** * Returns a number based on the option string * @param size * @returns {Number} */ parseFileSize(size) { if (size && typeof size === 'string') { const _s: any = size.toLowerCase().match(/^((?:0\.)?\d+)([kmg])$/); if (_s) { switch (_s[2]) { case 'k': return _s[1] * 1024; case 'm': return _s[1] * 1024 * 1024; case 'g': return _s[1] * 1024 * 1024 * 1024; } } } return null; } /** * Returns date string for a given format / date_format * @param format * @param date_format * @param {boolean} utc * @returns {string} */ getDate(format, date_format, utc) { date_format = date_format || DATE_FORMAT; const currentMoment = utc ? moment.utc() : moment().local(); if (format && staticFrequency.indexOf(format.type) !== -1) { switch (format.type) { case 's': /*eslint-disable-next-line no-case-declarations*/ const second = Math.floor(currentMoment.seconds() / format.digit) * format.digit; return currentMoment.seconds(second).format(date_format); case 'm': /*eslint-disable-next-line no-case-declarations*/ const minute = Math.floor(currentMoment.minutes() / format.digit) * format.digit; return currentMoment.minutes(minute).format(date_format); case 'h': /*eslint-disable-next-line no-case-declarations*/ const hour = Math.floor(currentMoment.hour() / format.digit) * format.digit; return currentMoment.hour(hour).format(date_format); case 'daily': case 'custom': case 'test': return currentMoment.format(date_format); } } return currentMoment.format(date_format); } /** * Read audit json object from disk or return new object or null * @param max_logs * @param audit_file * @param log_file * @returns {Object} auditLogSettings * @property {Object} auditLogSettings.keep * @property {Boolean} auditLogSettings.keep.days * @property {Number} auditLogSettings.keep.amount * @property {String} auditLogSettings.auditLog * @property {Array} auditLogSettings.files */ setAuditLog(max_logs, audit_file, log_file) { let _rtn = null; if (max_logs) { const use_days = max_logs.toString().substr(-1); const _num = max_logs.toString().match(/^(\d+)/); if (Number(_num[1]) > 0) { const baseLog = path.dirname(log_file.replace(/%DATE%.+/, '_filename')); try { if (audit_file) { const full_path = path.resolve(audit_file); _rtn = JSON.parse( fs.readFileSync(full_path, { encoding: 'utf-8' }) ); } else { const full_path = path.resolve(baseLog + '/' + '.audit.json'); _rtn = JSON.parse( fs.readFileSync(full_path, { encoding: 'utf-8' }) ); } } catch (e) { if (e.code !== 'ENOENT') { return null; } _rtn = { keep: { days: false, amount: Number(_num[1]), }, auditLog: audit_file || baseLog + '/' + '.audit.json', files: [], }; } _rtn.keep = { days: use_days === 'd', amount: Number(_num[1]), }; } } return _rtn; } /** * Write audit json object to disk * @param {Object} audit * @param {Object} audit.keep * @param {Boolean} audit.keep.days * @param {Number} audit.keep.amount * @param {String} audit.auditLog * @param {Array} audit.files */ writeAuditLog(audit) { try { mkDirForFile(audit.auditLog); fs.writeFileSync(audit.auditLog, JSON.stringify(audit, null, 4)); } catch (e) { debug( new Date().toLocaleString(), '[FileStreamRotator] Failed to store log audit at:', audit.auditLog, 'Error:', e ); } } /** * Write audit json object to disk * @param {String} logfile * @param {Object} audit * @param {Object} audit.keep * @param {Boolean} audit.keep.days * @param {Number} audit.keep.amount * @param {String} audit.auditLog * @param {Array} audit.files * @param {EventEmitter} stream */ addLogToAudit(logfile, audit, stream) { if (audit && audit.files) { // Based on contribution by @nickbug - https://github.com/nickbug const index = audit.files.findIndex(file => { return file.name === logfile; }); if (index !== -1) { // nothing to do as entry already exists. return audit; } const time = Date.now(); audit.files.push({ date: time, name: logfile, hash: crypto .createHash('md5') .update(logfile + 'LOG_FILE' + time) .digest('hex'), }); if (audit.keep.days) { const oldestDate = moment() .subtract(audit.keep.amount, 'days') .valueOf(); const recentFiles = audit.files.filter(file => { if (file.date > oldestDate) { return true; } removeFile(file); stream.emit('logRemoved', file); return false; }); audit.files = recentFiles; } else { const filesToKeep = audit.files.splice(-audit.keep.amount); if (audit.files.length > 0) { audit.files.filter(file => { removeFile(file); stream.emit('logRemoved', file); return false; }); } audit.files = filesToKeep; } this.writeAuditLog(audit); } return audit; } /** * * @param options * @param options.filename * @param options.frequency * @param options.date_format * @param options.size * @param options.max_logs * @param options.audit_file * @param options.file_options * @param options.utc * @param options.extension File extension to be added at the end of the filename * @param options.create_symlink * @param options.symlink_name * @returns {Object} stream */ getStream(options: { filename: string; frequency?: string; size?: string; max_logs?: number | string; end_stream?: boolean; extension?: string; create_symlink?: boolean; date_format?: string; audit_file?: string; symlink_name?: string; utc?: boolean; file_options?: any; }) { let frequencyMetaData = null; let curDate = null; assert(options.filename, 'options.filename must be supplied'); if (options.frequency) { frequencyMetaData = this.getFrequency(options.frequency); } const auditLog = this.setAuditLog( options.max_logs, options.audit_file, options.filename ); let fileSize = null; let fileCount = 0; let curSize = 0; if (options.size) { fileSize = this.parseFileSize(options.size); } let dateFormat = options.date_format || DATE_FORMAT; if (frequencyMetaData && frequencyMetaData.type === 'daily') { if (!options.date_format) { dateFormat = 'YYYY-MM-DD'; } if ( moment().format(dateFormat) !== moment().endOf('day').format(dateFormat) || moment().format(dateFormat) === moment().add(1, 'day').format(dateFormat) ) { debug( new Date().toLocaleString(), '[FileStreamRotator] Changing type to custom as date format changes more often than once a day or not every day' ); frequencyMetaData.type = 'custom'; } } if (frequencyMetaData) { curDate = options.frequency ? this.getDate(frequencyMetaData, dateFormat, options.utc) : ''; } options.create_symlink = options.create_symlink || false; options.extension = options.extension || ''; const filename = options.filename; let oldFile = null; let logfile = filename + (curDate ? '.' + curDate : ''); if (filename.match(/%DATE%/)) { logfile = filename.replace( /%DATE%/g, curDate ? curDate : this.getDate(null, dateFormat, options.utc) ); } if (fileSize) { // 下面应该是启动找到已经创建了的文件,做一些预先处理,比如找到最新的那个文件,方便写入 let lastLogFile = null; let t_log = logfile; if ( auditLog && auditLog.files && auditLog.files instanceof Array && auditLog.files.length > 0 ) { const lastEntry = auditLog.files[auditLog.files.length - 1].name; if (lastEntry.match(t_log)) { const lastCount = lastEntry.match(t_log + '\\.(\\d+)'); // Thanks for the PR contribution from @andrefarzat - https://github.com/andrefarzat if (lastCount) { t_log = lastEntry; fileCount = lastCount[1]; } } } if (fileCount === 0 && t_log === logfile) { t_log += options.extension; } // 计数,找到数字最大的那个日志文件 while (fs.existsSync(t_log)) { lastLogFile = t_log; fileCount++; t_log = logfile + '.' + fileCount + options.extension; } if (lastLogFile) { const lastLogFileStats = fs.statSync(lastLogFile); // 看看最新的那个日志有没有超过设置的大小 if (lastLogFileStats.size < fileSize) { // 没有超,把新文件退栈 t_log = lastLogFile; fileCount--; curSize = lastLogFileStats.size; } } logfile = t_log; } else { logfile += options.extension; } debug( new Date().toLocaleString(), '[FileStreamRotator] Logging to: ', logfile ); // 循环创建目录和文件,类似 mkdirp mkDirForFile(logfile); const file_options = options.file_options || { flags: 'a' }; // 创建文件流 let rotateStream = fs.createWriteStream(logfile, file_options); if ( (curDate && frequencyMetaData && staticFrequency.indexOf(frequencyMetaData.type) > -1) || fileSize > 0 ) { debug( new Date().toLocaleString(), '[FileStreamRotator] Rotating file: ', frequencyMetaData ? frequencyMetaData.type : '', fileSize ? 'size: ' + fileSize : '' ); // 这里用了一个事件代理,方便代理的内容做处理 const stream: any = new EventEmitter(); stream.auditLog = auditLog; stream.end = (...args) => { rotateStream.end(...args); resetCurLogSize.clear(); }; BubbleEvents(rotateStream, stream); stream.on('new', newLog => { // 创建审计的日志,记录最新的日志文件,切割的记录等 stream.auditLog = this.addLogToAudit(newLog, stream.auditLog, stream); // 创建软链 if (options.create_symlink) { createCurrentSymLink(newLog, options.symlink_name); } }); // 这里采用 1s 的防抖,避免过于频繁的获取文件大小 const resetCurLogSize = debounce(() => { const lastLogFileStats = fs.statSync(logfile); if (lastLogFileStats.size > curSize) { curSize = lastLogFileStats.size; } }, 1000); stream.write = (str, encoding) => { resetCurLogSize(); const newDate = this.getDate( frequencyMetaData, dateFormat, options.utc ); if ( (curDate && newDate !== curDate) || (fileSize && curSize > fileSize) ) { let newLogfile = filename + (curDate ? '.' + newDate : ''); if (filename.match(/%DATE%/) && curDate) { newLogfile = filename.replace(/%DATE%/g, newDate); } if (fileSize && curSize > fileSize) { fileCount++; newLogfile += '.' + fileCount + options.extension; } else { // reset file count fileCount = 0; newLogfile += options.extension; } curSize = 0; debug( new Date().toLocaleString(), format( '[FileStreamRotator] Changing logs from %s to %s', logfile, newLogfile ) ); curDate = newDate; oldFile = logfile; logfile = newLogfile; // Thanks to @mattberther https://github.com/mattberther for raising it again. if (options.end_stream === true) { rotateStream.end(); } else { rotateStream.destroy(); } mkDirForFile(logfile); rotateStream = fs.createWriteStream(newLogfile, file_options); stream.emit('new', newLogfile); stream.emit('rotate', oldFile, newLogfile); BubbleEvents(rotateStream, stream); } rotateStream.write(str, encoding); // Handle length of double-byte characters curSize += Buffer.byteLength(str, encoding); }; process.nextTick(() => { stream.emit('new', logfile); }); stream.emit('new', logfile); return stream; } else { debug( new Date().toLocaleString(), "[FileStreamRotator] File won't be rotated: ", options.frequency, options.size ); process.nextTick(() => { rotateStream.emit('new', logfile); }); return rotateStream; } } }
the_stack
import { AndExpression, BlockClass, BooleanExpression, Conditional, Dependency, DynamicClasses, HasAttrValue, HasGroup, IndexedClassRewrite, NotExpression, OrExpression, Style, Switch, hasDependency, isConditional, isFalseCondition, isSwitch, isTrueCondition, } from "@css-blocks/core"; import { AST, Syntax, } from "@glimmer/syntax"; import { isAndExpression, isNotExpression, isOrExpression, } from "@opticss/template-api"; import { assertNever, isSome, unwrap, } from "@opticss/util"; import * as debugGenerator from "debug"; import { BooleanExpression as BooleanAST, StringExpression as StringAST, TemplateElement, TernaryExpression as TernaryAST, } from "./ElementAnalyzer"; import { CLASSNAMES_HELPER_NAME, CONCAT_HELPER_NAME } from "./helpers"; import { isConcatStatement, isMustacheStatement, isPathExpression, isStringLiteral, isSubExpression } from "./utils"; const enum SourceExpression { ternary, dependency, boolean, booleanWithDep, switch, switchWithDep, } const enum FalsySwitchBehavior { error, unset, default, } const enum BooleanExpr { not = -1, or = -2, and = -3, } type Builders = Syntax["builders"]; const debug = debugGenerator("css-blocks:glimmer"); export function classnamesHelper(builders: Builders, rewrite: IndexedClassRewrite<Style>, element: TemplateElement): AST.MustacheStatement { return builders.mustache( builders.path(CLASSNAMES_HELPER_NAME), constructArgs(builders, rewrite, element), ); } export function classnamesSubexpr(builders: Builders, rewrite: IndexedClassRewrite<Style>, element: TemplateElement): AST.SubExpression { return builders.sexpr( builders.path(CLASSNAMES_HELPER_NAME), constructArgs(builders, rewrite, element), ); } // tslint:disable-next-line:prefer-unknown-to-any function constructArgs(builders: Builders, rewrite: IndexedClassRewrite<any>, element: TemplateElement): AST.Expression[] { let expr = new Array<AST.Expression>(); expr.push(builders.number(element.dynamicClasses.length + element.dynamicAttributes.length)); expr.push(builders.number(rewrite.dynamicClasses.length)); expr.push(...constructSourceArgs(builders, rewrite, element)); expr.push(...constructOutputArgs(builders, rewrite)); return expr; } // tslint:disable-next-line:prefer-unknown-to-any function constructSourceArgs(builders: Builders, rewrite: IndexedClassRewrite<any>, element: TemplateElement): AST.Expression[] { let expr = new Array<AST.Expression>(); for (let classes of element.dynamicClasses) { // type of expression expr.push(builders.number(SourceExpression.ternary)); expr.push(...constructTernary(builders, classes, rewrite)); } for (let stateExpr of element.dynamicAttributes) { if (isSwitch(stateExpr)) { if (hasDependency(stateExpr)) { expr.push(builders.number(SourceExpression.switchWithDep)); expr.push(...constructDependency(builders, stateExpr, rewrite)); } else { expr.push(builders.number(SourceExpression.switch)); } expr.push(...constructSwitch(builders, stateExpr, rewrite)); } else { let type = 0; if (hasDependency(stateExpr)) { type = type | SourceExpression.dependency; } if (isConditional(stateExpr)) { type = type | SourceExpression.boolean; } expr.push(builders.number(type)); if (hasDependency(stateExpr)) { expr.push(...constructDependency(builders, stateExpr, rewrite)); } if (isConditional(stateExpr)) { expr.push(...constructConditional(builders, stateExpr, rewrite)); } expr.push(...constructStateReferences(builders, stateExpr, rewrite)); } } return expr; } /** * Boolean Ternary: * 1: expression to evaluate as truthy * 2: number (t) of source styles set if true * 3..(3+t-1): indexes of source styles set if true * (3+t): number (f) of source styles set if false * (4+t)..(4+t+f-1): indexes of source styles set if false */ function constructTernary(builders: Builders, classes: DynamicClasses<TernaryAST>, rewrite: IndexedClassRewrite<Style>): AST.Expression[] { let expr = new Array<AST.Expression>(); // The boolean expression if (isMustacheStatement(classes.condition!)) { expr.push(moustacheToExpression(builders, classes.condition)); } else { expr.push(classes.condition!); } // The true styles if (isTrueCondition(classes)) { let trueClasses = resolveInheritance(classes.whenTrue, rewrite); expr.push(builders.number(trueClasses.length)); expr.push(...trueClasses.map(style => { let n: number = unwrap(rewrite.indexOf(style)); return builders.number(n); })); } else { expr.push(builders.number(0)); } // The false styles if (isFalseCondition(classes)) { let falseClasses = resolveInheritance(classes.whenFalse, rewrite); expr.push(builders.number(falseClasses.length)); expr.push(...falseClasses.map(style => builders.number(unwrap(rewrite.indexOf(style))))); } else { expr.push(builders.number(0)); } return expr; } function resolveInheritance(classes: Array<BlockClass>, rewrite: IndexedClassRewrite<Style>) { let allClasses = [...classes]; for (let c of classes) { allClasses.push(...c.resolveInheritance()); } return allClasses.filter(c => isSome(rewrite.indexOf(c))); } /* * if conditional type has a dependency: * 3/4: number (d) of style indexes this is dependent on. * 4/5..((4/5)+d-1): style indexes that must be set for this to be true */ function constructDependency(builders: Builders, stateExpr: Dependency, rewrite: IndexedClassRewrite<Style>): AST.Expression[] { let expr = new Array<AST.Expression>(); expr.push(builders.number(1)); expr.push(builders.number(unwrap(rewrite.indexOf(stateExpr.container)))); return expr; } function constructConditional(builders: Builders, stateExpr: Conditional<BooleanAST> & HasAttrValue, _rewrite: IndexedClassRewrite<Style>): AST.Expression[] { let expr = new Array<AST.Expression>(); expr.push(moustacheToBooleanExpression(builders, stateExpr.condition)); return expr; } function constructStateReferences(builders: Builders, stateExpr: HasAttrValue, rewrite: IndexedClassRewrite<Style>): AST.Expression[] { let expr = new Array<AST.Expression>(); // TODO: inheritance expr.push(builders.number(stateExpr.value.size)); for (let val of stateExpr.value) { expr.push(builders.number(unwrap(rewrite.indexOf(val)))); } return expr; } /* * * String switch: * 1: conditional type: 4 - switch, 5 - both switch and dependency * if conditional type has a dependency: * 2: number (d) of style indexes this is dependent on. * 3..((3)+d-1): style indexes that must be set for this to be true * 1: number (n) of strings that can be returned * 2: whether a falsy value is an error (0), unsets the values (1) * or provide a default (2) if a string * 3?: the default value if the falsy behavior is default (2) * then: expression to evaluate as a string * For each of the <n> strings that can be returned: * 1: string that can be returned by the expression * 2: number (s) of source styles set. s >= 1 * 3..3+s-1: indexes of source styles set */ function constructSwitch(builders: Builders, stateExpr: Switch<StringAST> & HasGroup & HasAttrValue, rewrite: IndexedClassRewrite<Style>): AST.Expression[] { let expr = new Array<AST.Expression>(); let values = Object.keys(stateExpr.group); expr.push(builders.number(values.length)); if (stateExpr.disallowFalsy) { expr.push(builders.number(FalsySwitchBehavior.error)); } else { expr.push(builders.number(FalsySwitchBehavior.unset)); } expr.push(moustacheToStringExpression(builders, stateExpr.stringExpression!)); for (let value of values) { let obj = stateExpr.group[value]; expr.push(builders.string(value)); // If there are values provided for this conditional, they are meant to be // applied instead of the selected attribute group member. if (stateExpr.value.size) { expr.push(builders.number(stateExpr.value.size)); for (let val of stateExpr.value) { expr.push(builders.number(unwrap(rewrite.indexOf(val)))); } } else { let styles = obj.resolveStyles(); expr.push(builders.number(styles.size)); for (let s of styles) { expr.push(builders.number(unwrap(rewrite.indexOf(s)))); } } } return expr; } function moustacheToBooleanExpression(builders: Builders, booleanExpression: BooleanAST): AST.Expression { if (booleanExpression.type === "MustacheStatement") { return moustacheToExpression(builders, booleanExpression); } else { return booleanExpression; } } function moustacheToExpression(builders: Builders, expr: AST.MustacheStatement): AST.Expression { if (isPathExpression(expr.path)) { if (expr.params.length === 0 && expr.hash.pairs.length === 0) { debug("converting", expr.path.original, "to path"); return expr.path; } else { debug("converting", expr.path.original, "to sexpr"); return builders.sexpr(expr.path, expr.params, expr.hash); } } else if (isStringLiteral(expr.path)) { debug("preserving literal", expr.path.original, "as literal"); return expr.path; } else { debug("preserving unknown path expression"); return expr.path; } } function moustacheToStringExpression(builders: Builders, stringExpression: Exclude<StringAST, null>): AST.Expression { if (isConcatStatement(stringExpression)) { return builders.sexpr( builders.path(CONCAT_HELPER_NAME), stringExpression.parts.reduce( (arr, val) => { if (val.type === "TextNode") { arr.push(builders.string(val.chars)); } else { arr.push(val.path); } return arr; }, new Array<AST.Expression>())); } else if (isSubExpression(stringExpression)) { return stringExpression; } else if (isPathExpression(stringExpression)) { return builders.sexpr(stringExpression); } else if (isMustacheStatement(stringExpression)) { return moustacheToExpression(builders, stringExpression); } else { return assertNever(stringExpression); } } // tslint:disable-next-line:prefer-unknown-to-any function constructOutputArgs(builders: Builders, rewrite: IndexedClassRewrite<any>): AST.Expression[] { let expr = new Array<AST.Expression>(); for (let out of rewrite.dynamicClasses) { expr.push(builders.string(out)); expr.push(...constructBoolean(builders, rewrite.dynamicClass(out)!)); } return expr; } type ConditionalArg = number | BooleanExpression<number>; function constructBoolean(builders: Builders, bool: ConditionalArg): AST.Expression[] { if (typeof bool === "number") { return [builders.number(bool)]; } else if (isAndExpression(bool)) { return constructAndExpression(builders, bool); } else if (isOrExpression(bool)) { return constructOrExpression(builders, bool); } else if (isNotExpression(bool)) { return constructNotExpression(builders, bool); } else { return assertNever(bool); } } function constructAndExpression(builders: Builders, bool: AndExpression<number>): AST.Expression[] { return constructConditionalExpression(builders, BooleanExpr.and, bool.and); } function constructOrExpression(builders: Builders, bool: OrExpression<number>): AST.Expression[] { return constructConditionalExpression(builders, BooleanExpr.or, bool.or); } function constructNotExpression(builders: Builders, bool: NotExpression<number>): AST.Expression[] { return [builders.number(BooleanExpr.not), ...constructBoolean(builders, bool.not)]; } function constructConditionalExpression(builders: Builders, type: BooleanExpr, args: Array<ConditionalArg>): AST.Expression[] { let expr = new Array<AST.Expression>(); if (args.length === 1) { let n = args[0]; if (typeof n === "number") { expr.push(builders.number(n)); return expr; } } expr.push(builders.number(type)); expr.push(builders.number(args.length)); for (let e of args) { if (typeof e === "number") { expr.push(builders.number(e)); } else { expr.push(...constructBoolean(builders, e)); } } return expr; }
the_stack
export const mockDataFrame = { data: { cols: [ { int64s: { data: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90] }, type: "int64s", }, { int64s: { data: [1, 11, 21, 31, 41, 51, 61, 71, 81, 91] }, type: "int64s", }, { int64s: { data: [2, 12, 22, 32, 42, 52, 62, 72, 82, 92] }, type: "int64s", }, { int64s: { data: [3, 13, 23, 33, 43, 53, 63, 73, 83, 93] }, type: "int64s", }, { int64s: { data: [4, 14, 24, 34, 44, 54, 64, 74, 84, 94] }, type: "int64s", }, { int64s: { data: [5, 15, 25, 35, 45, 55, 65, 75, 85, 95] }, type: "int64s", }, { int64s: { data: [6, 16, 26, 36, 46, 56, 66, 76, 86, 96] }, type: "int64s", }, { int64s: { data: [7, 17, 27, 37, 47, 57, 67, 77, 87, 97] }, type: "int64s", }, { int64s: { data: [8, 18, 28, 38, 48, 58, 68, 78, 88, 98] }, type: "int64s", }, { int64s: { data: [9, 19, 29, 39, 49, 59, 69, 79, 89, 99] }, type: "int64s", }, ], }, index: { rangeIndex: { start: 0, stop: 10 }, type: "rangeIndex" }, columns: { rangeIndex: { start: 0, stop: 10 }, type: "rangeIndex" }, style: { cols: [ { styles: [ { css: [{ property: "background-color", value: "yellow" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, { styles: [ { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, { css: [{ property: "background-color", value: "white" }], displayValue: "", hasDisplayValue: false, }, ], }, ], }, } export const mockStringDataFrame = { ...mockDataFrame, data: { cols: [ { strings: { data: ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90"], }, type: "strings", }, { strings: { data: ["1", "11", "21", "31", "41", "51", "61", "71", "81", "91"], }, type: "strings", }, { strings: { data: ["2", "12", "22", "32", "42", "52", "62", "72", "82", "92"], }, type: "strings", }, { strings: { data: ["3", "13", "23", "33", "43", "53", "63", "73", "83", "93"], }, type: "strings", }, { strings: { data: ["4", "14", "24", "34", "44", "54", "64", "74", "84", "94"], }, type: "strings", }, { strings: { data: ["5", "15", "25", "35", "45", "55", "65", "75", "85", "95"], }, type: "strings", }, { strings: { data: ["6", "16", "26", "36", "46", "56", "66", "76", "86", "96"], }, type: "strings", }, { strings: { data: ["7", "17", "27", "37", "47", "57", "67", "77", "87", "97"], }, type: "strings", }, { strings: { data: ["8", "18", "28", "38", "48", "58", "68", "78", "88", "98"], }, type: "strings", }, { strings: { data: ["9", "19", "29", "39", "49", "59", "69", "79", "89", "99"], }, type: "strings", }, ], }, }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages a VPN Gateway Nat Rule. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleVirtualWan = new azure.network.VirtualWan("exampleVirtualWan", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * }); * const exampleVirtualHub = new azure.network.VirtualHub("exampleVirtualHub", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * addressPrefix: "10.0.1.0/24", * virtualWanId: exampleVirtualWan.id, * }); * const exampleVpnGateway = new azure.network.VpnGateway("exampleVpnGateway", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * virtualHubId: exampleVirtualHub.id, * }); * const exampleVnpGatewayNatRule = new azure.network.VnpGatewayNatRule("exampleVnpGatewayNatRule", { * resourceGroupName: exampleResourceGroup.name, * vpnGatewayId: exampleVpnGateway.id, * externalAddressSpaceMappings: ["192.168.21.0/26"], * internalAddressSpaceMappings: ["10.4.0.0/26"], * }); * ``` * * ## Import * * VPN Gateway Nat Rules can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:network/vnpGatewayNatRule:VnpGatewayNatRule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Network/vpnGateways/vpnGateway1/natRules/natRule1 * ``` */ export class VnpGatewayNatRule extends pulumi.CustomResource { /** * Get an existing VnpGatewayNatRule resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: VnpGatewayNatRuleState, opts?: pulumi.CustomResourceOptions): VnpGatewayNatRule { return new VnpGatewayNatRule(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:network/vnpGatewayNatRule:VnpGatewayNatRule'; /** * Returns true if the given object is an instance of VnpGatewayNatRule. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is VnpGatewayNatRule { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === VnpGatewayNatRule.__pulumiType; } /** * A list of CIDR Ranges which are used for external mapping of the VPN Gateway Nat Rule. */ public readonly externalAddressSpaceMappings!: pulumi.Output<string[]>; /** * A list of CIDR Ranges which are used for internal mapping of the VPN Gateway Nat Rule. */ public readonly internalAddressSpaceMappings!: pulumi.Output<string[]>; /** * The ID of the IP Configuration this VPN Gateway Nat Rule applies to. Possible values are `Instance0` and `Instance1`. */ public readonly ipConfigurationId!: pulumi.Output<string | undefined>; /** * The source Nat direction of the VPN Nat. Possible values are `EgressSnat` and `IngressSnat`. Defaults to `EgressSnat`. Changing this forces a new resource to be created. */ public readonly mode!: pulumi.Output<string | undefined>; /** * The name which should be used for this VPN Gateway Nat Rule. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * The Name of the Resource Group in which this VPN Gateway Nat Rule should be created. Changing this forces a new resource to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The type of the VPN Gateway Nat Rule. Possible values are `Dynamic` and `Static`. Defaults to `Static`. Changing this forces a new resource to be created. */ public readonly type!: pulumi.Output<string | undefined>; /** * The ID of the VPN Gateway that this VPN Gateway Nat Rule belongs to. Changing this forces a new resource to be created. */ public readonly vpnGatewayId!: pulumi.Output<string>; /** * Create a VnpGatewayNatRule resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: VnpGatewayNatRuleArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: VnpGatewayNatRuleArgs | VnpGatewayNatRuleState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as VnpGatewayNatRuleState | undefined; inputs["externalAddressSpaceMappings"] = state ? state.externalAddressSpaceMappings : undefined; inputs["internalAddressSpaceMappings"] = state ? state.internalAddressSpaceMappings : undefined; inputs["ipConfigurationId"] = state ? state.ipConfigurationId : undefined; inputs["mode"] = state ? state.mode : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["type"] = state ? state.type : undefined; inputs["vpnGatewayId"] = state ? state.vpnGatewayId : undefined; } else { const args = argsOrState as VnpGatewayNatRuleArgs | undefined; if ((!args || args.externalAddressSpaceMappings === undefined) && !opts.urn) { throw new Error("Missing required property 'externalAddressSpaceMappings'"); } if ((!args || args.internalAddressSpaceMappings === undefined) && !opts.urn) { throw new Error("Missing required property 'internalAddressSpaceMappings'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.vpnGatewayId === undefined) && !opts.urn) { throw new Error("Missing required property 'vpnGatewayId'"); } inputs["externalAddressSpaceMappings"] = args ? args.externalAddressSpaceMappings : undefined; inputs["internalAddressSpaceMappings"] = args ? args.internalAddressSpaceMappings : undefined; inputs["ipConfigurationId"] = args ? args.ipConfigurationId : undefined; inputs["mode"] = args ? args.mode : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["type"] = args ? args.type : undefined; inputs["vpnGatewayId"] = args ? args.vpnGatewayId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(VnpGatewayNatRule.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering VnpGatewayNatRule resources. */ export interface VnpGatewayNatRuleState { /** * A list of CIDR Ranges which are used for external mapping of the VPN Gateway Nat Rule. */ externalAddressSpaceMappings?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of CIDR Ranges which are used for internal mapping of the VPN Gateway Nat Rule. */ internalAddressSpaceMappings?: pulumi.Input<pulumi.Input<string>[]>; /** * The ID of the IP Configuration this VPN Gateway Nat Rule applies to. Possible values are `Instance0` and `Instance1`. */ ipConfigurationId?: pulumi.Input<string>; /** * The source Nat direction of the VPN Nat. Possible values are `EgressSnat` and `IngressSnat`. Defaults to `EgressSnat`. Changing this forces a new resource to be created. */ mode?: pulumi.Input<string>; /** * The name which should be used for this VPN Gateway Nat Rule. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The Name of the Resource Group in which this VPN Gateway Nat Rule should be created. Changing this forces a new resource to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The type of the VPN Gateway Nat Rule. Possible values are `Dynamic` and `Static`. Defaults to `Static`. Changing this forces a new resource to be created. */ type?: pulumi.Input<string>; /** * The ID of the VPN Gateway that this VPN Gateway Nat Rule belongs to. Changing this forces a new resource to be created. */ vpnGatewayId?: pulumi.Input<string>; } /** * The set of arguments for constructing a VnpGatewayNatRule resource. */ export interface VnpGatewayNatRuleArgs { /** * A list of CIDR Ranges which are used for external mapping of the VPN Gateway Nat Rule. */ externalAddressSpaceMappings: pulumi.Input<pulumi.Input<string>[]>; /** * A list of CIDR Ranges which are used for internal mapping of the VPN Gateway Nat Rule. */ internalAddressSpaceMappings: pulumi.Input<pulumi.Input<string>[]>; /** * The ID of the IP Configuration this VPN Gateway Nat Rule applies to. Possible values are `Instance0` and `Instance1`. */ ipConfigurationId?: pulumi.Input<string>; /** * The source Nat direction of the VPN Nat. Possible values are `EgressSnat` and `IngressSnat`. Defaults to `EgressSnat`. Changing this forces a new resource to be created. */ mode?: pulumi.Input<string>; /** * The name which should be used for this VPN Gateway Nat Rule. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The Name of the Resource Group in which this VPN Gateway Nat Rule should be created. Changing this forces a new resource to be created. */ resourceGroupName: pulumi.Input<string>; /** * The type of the VPN Gateway Nat Rule. Possible values are `Dynamic` and `Static`. Defaults to `Static`. Changing this forces a new resource to be created. */ type?: pulumi.Input<string>; /** * The ID of the VPN Gateway that this VPN Gateway Nat Rule belongs to. Changing this forces a new resource to be created. */ vpnGatewayId: pulumi.Input<string>; }
the_stack
import type { Domain } from '@h5web/shared'; import { ScaleType } from '@h5web/shared'; import { tickStep } from 'd3-array'; import { computeCanvasSize, getDomain, getDomains, extendDomain, getValueToIndexScale, getIntegerTicks, getCombinedDomain, clampBound, } from './utils'; const MAX = Number.MAX_VALUE / 2; const POS_MIN = Number.MIN_VALUE; const { NaN: NAN, POSITIVE_INFINITY: INFINITY } = Number; describe('computeCanvasSize', () => { describe('with aspect ratio > 1', () => { it('should return available size with width reduced', () => { const availableSize = { width: 20, height: 10 }; const size = computeCanvasSize(availableSize, 1.5); expect(size?.width).toBeLessThanOrEqual(availableSize.width); expect(size?.height).toBeLessThanOrEqual(availableSize.height); expect(size).toEqual({ width: 10 * 1.5, height: 10 }); }); it('should return available size with height reduced', () => { const availableSize = { width: 12, height: 50 }; const size = computeCanvasSize(availableSize, 3); expect(size?.width).toBeLessThanOrEqual(availableSize.width); expect(size?.height).toBeLessThanOrEqual(availableSize.height); expect(size).toEqual({ width: 12, height: 12 / 3 }); }); }); describe('with aspect ratio < 1', () => { it('should return available size with width reduced', () => { const availableSize = { width: 20, height: 10 }; const size = computeCanvasSize(availableSize, 0.5); expect(size?.width).toBeLessThanOrEqual(availableSize.width); expect(size?.height).toBeLessThanOrEqual(availableSize.height); expect(size).toEqual({ width: 10 * 0.5, height: 10 }); }); it('should return available size with height reduced', () => { const availableSize = { width: 12, height: 50 }; const size = computeCanvasSize(availableSize, 0.75); expect(size?.width).toBeLessThanOrEqual(availableSize.width); expect(size?.height).toBeLessThanOrEqual(availableSize.height); expect(size).toEqual({ width: 12, height: 12 / 0.75 }); }); }); it('should return available size when no aspect ratio is provided', () => { const size = computeCanvasSize({ width: 20, height: 10 }, undefined); expect(size).toEqual({ width: 20, height: 10 }); }); it('should return `undefined` when no space is available for visualization', () => { const size = computeCanvasSize({ width: 0, height: 0 }, 1); expect(size).toBeUndefined(); }); }); describe('getDomain', () => { it('should return min and max values of data array', () => { const data = [2, 0, 10, 5, 2, -1]; const domain = getDomain(data); expect(domain).toEqual([-1, 10]); }); it('should return `undefined` if data is empty', () => { const domain = getDomain([]); expect(domain).toBeUndefined(); }); it('should ignore NaN and Infinity', () => { const domain = getDomain([2, NAN, 10, INFINITY, 2, -1]); expect(domain).toEqual([-1, 10]); }); it('should return `undefined` if data contains only NaN and Infinity', () => { const domain = getDomain([NAN, NAN, -INFINITY, INFINITY]); expect(domain).toBeUndefined(); }); describe('with log scale', () => { it('should support negative domain', () => { const domain = getDomain([-2, -10, -5, -2, -1], ScaleType.Log); expect(domain).toEqual([-10, -1]); }); it('should clamp domain min to first strict positive value when domain crosses zero', () => { const domain = getDomain([2, 0, 10, 5, 2, -1], ScaleType.Log); expect(domain).toEqual([2, 10]); }); it('should return `undefined` if domain is not supported', () => { const domain = getDomain([-2, 0, -10, -5, -2, -1], ScaleType.Log); expect(domain).toBeUndefined(); }); }); describe('with sqrt scale', () => { it('should support negative domain', () => { const domain = getDomain([-2, -10, -5, -2, -1], ScaleType.Sqrt); expect(domain).toEqual([-10, -1]); }); it('should support negative domain including 0', () => { const domain = getDomain([-2, 0, -10, -5, -2, -1], ScaleType.Sqrt); expect(domain).toEqual([-10, 0]); }); it('should clamp domain min to first positive value when domain crosses zero', () => { const domain = getDomain([2, 0, 10, 5, 2, -1], ScaleType.Sqrt); expect(domain).toEqual([0, 10]); const domain2 = getDomain([2, 10, 5, 2, -1], ScaleType.Sqrt); expect(domain2).toEqual([2, 10]); }); }); }); describe('getDomains', () => { it('should return domains of multiple arrays', () => { const arr1 = [2, 0, 10, 5, 2, -1]; const arr2: number[] = []; const arr3 = [100]; const domain = getDomains([arr1, arr2, arr3]); expect(domain).toEqual([[-1, 10], undefined, [100, 100]]); }); it('should return domains of multiple arrays in log scale', () => { const arr1 = [-2, -10, -5, -2, -1]; const arr2 = [2, 0, 10, 5, 2, -1]; const arr3 = [-2, 0, -10, -5, -2, -1]; const domain = getDomains([arr1, arr2, arr3], ScaleType.Log); expect(domain).toEqual([[-10, -1], [2, 10], undefined]); }); }); describe('clampBound', () => { it('should clamp to `Number.MAX_VALUE / 2` and keep sign', () => { expect(clampBound(Infinity)).toEqual(MAX); expect(clampBound(-Infinity)).toEqual(-MAX); expect(clampBound(MAX)).toEqual(MAX); expect(clampBound(-MAX)).toEqual(-MAX); expect(clampBound(MAX - 1)).toEqual(MAX - 1); expect(clampBound(-MAX + 1)).toEqual(-MAX + 1); }); }); describe('extendDomain', () => { it('should extend domain with linear scale', () => { const extendedDomain = extendDomain([0, 100], 0.5); expect(extendedDomain).toEqual([-50, 150]); }); it('should extend domain with symlog scale', () => { const [min, max] = [-10, 0]; const [extMin, extMax] = extendDomain([min, max], 0.1, ScaleType.SymLog); expect(extMin).toBeLessThan(min); expect(extMax).toBeGreaterThan(max); }); it('should extend domain with log scale', () => { const [min, max] = [1, 10]; const [extMin1, extMax1] = extendDomain([min, max], 0.1, ScaleType.Log); expect(extMin1).toBeLessThan(min); expect(extMax1).toBeGreaterThan(max); // Extension factor of 1 for log scale means one decade const [extMin2, extMax2] = extendDomain([10, 100], 1, ScaleType.Log); expect(extMin2).toBeCloseTo(1); expect(extMax2).toBeCloseTo(1000); }); it('should extend domain with sqrt scale', () => { const [min, max] = [1, 10]; const [extMin1, extMax1] = extendDomain([min, max], 0.1, ScaleType.Sqrt); expect(extMin1).toBeLessThan(min); expect(extMax1).toBeGreaterThan(max); }); it('should extend positive single-value domain', () => { expect(extendDomain([2, 2], 0.5)).toEqual([1, 3]); expect(extendDomain([1, 1], 1)).toEqual([0, 2]); expect(extendDomain([1, 1], 1, ScaleType.Log)).toEqual([0.1, 10]); }); it('should extend negative single-value domain', () => { expect(extendDomain([-1, -1], 0.5)).toEqual([-1.5, -0.5]); expect(extendDomain([-2, -2], 1, ScaleType.SymLog)).toEqual([-4, 0]); }); it('should return [-1, 1] regardless of factor when trying to extend [0, 0]', () => { expect(extendDomain([0, 0], 0.5)).toEqual([-1, 1]); expect(extendDomain([0, 0], 1, ScaleType.SymLog)).toEqual([-1, 1]); }); it('should return [0, 1] when trying to extend [0, 0] for sqrt scale', () => { expect(extendDomain([0, 0], 1, ScaleType.Sqrt)).toEqual([0, 1]); }); it('should not extend domain when factor is 0', () => { const extendedDomain = extendDomain([10, 100], 0, ScaleType.Log); expect(extendedDomain).toEqual([10, 100]); }); it('should not extend domain outside of supported values with log scale', () => { const domain: Domain = [POS_MIN * 2, 100]; const [extMin1, extMax1] = extendDomain(domain, 0.75, ScaleType.Log); expect(extMin1).toEqual(POS_MIN); expect(extMax1).toBeGreaterThan(100); }); it('should throw if domain is not compatible with log scale', () => { const errRegex = /compatible with log scale/; expect(() => extendDomain([-1, 1], 0.5, ScaleType.Log)).toThrow(errRegex); expect(() => extendDomain([0, 1], 0.5, ScaleType.Log)).toThrow(errRegex); expect(() => extendDomain([0, 0], 0.5, ScaleType.Log)).toThrow(errRegex); }); it('should not extend domain outside of supported values with sqrt scale', () => { const domain: Domain = [POS_MIN, 100]; const [extMin1, extMax1] = extendDomain(domain, 0.75, ScaleType.Sqrt); expect(extMin1).toEqual(0); expect(extMax1).toBeGreaterThan(100); }); it('should throw if domain is not compatible with sqrt scale', () => { expect(() => extendDomain([-1, 1], 0.5, ScaleType.Sqrt)).toThrow( /compatible with sqrt scale/ ); }); }); describe('getValueToIndexScale', () => { it('should create threshold scale from values to indices', () => { const scale = getValueToIndexScale([10, 20, 30]); expect(scale(0)).toEqual(0); expect(scale(10)).toEqual(0); expect(scale(19.9)).toEqual(0); expect(scale(20)).toEqual(1); expect(scale(100)).toEqual(2); }); it('should allow scale to switch at midpoints', () => { const scale = getValueToIndexScale([10, 20, 30], true); expect(scale(0)).toEqual(0); expect(scale(14.9)).toEqual(0); expect(scale(15)).toEqual(1); expect(scale(24.9)).toEqual(1); expect(scale(25)).toEqual(2); expect(scale(100)).toEqual(2); }); }); describe('getIntegerTicks', () => { it('should return zero tick values when visible domain spans zero indices', () => { const prop1 = getIntegerTicks([0.2, 0.8], 3); expect(prop1).toEqual([]); const prop2 = getIntegerTicks([5.01, 5.02], 3); expect(prop2).toEqual([]); }); it('should return as many integer tick values as indices when space allows for it', () => { const prop1 = getIntegerTicks([0, 3], 10); expect(prop1).toEqual([0, 1, 2, 3]); const prop2 = getIntegerTicks([5.4, 6.9], 10); expect(prop2).toEqual([6]); }); it('should return evenly-spaced tick values for available space', () => { const prop1 = getIntegerTicks([0.8, 20.2], 10); // domain has 20 potential ticks but space allows for 10 expect(prop1).toEqual([2, 4, 6, 8, 10, 12, 14, 16, 18, 20]); const prop2 = getIntegerTicks([2, 7], 3); // domain has 8 potential ticks but space allows for 3 expect(prop2).toEqual([2, 4, 6]); }); it('should always return integer tick values', () => { // Tick count is not always respected, which is acceptable const prop1 = getIntegerTicks([0, 4], 3); // domain has 5 potential ticks but space allows for 3 expect(prop1).toEqual([0, 1, 2, 3, 4]); // This is because `d3.tickStep` is not too worried about the count... expect(tickStep(0, 4, 3)).toBe(1); // step should actually be 2 to end up with 3 ticks: `[0, 2, 4]` // Unfortunately, this behaviour can lead to decimal tick values (i.e. step < 1)... expect(tickStep(0, 2, 3)).toBe(0.5); // we'd end up with `[0, 0.5, 1, 1.5, 2]` instead of `[0, 1, 2]` // So we specifically work around it by forcing the step to be greater than or equal to 1 const prop2 = getIntegerTicks([0, 2], 3); expect(prop2).toEqual([0, 1, 2]); }); }); describe('getCombinedDomain', () => { it('should return the minimum of minima and the maximum of maxima', () => { const combinedDomain = getCombinedDomain([ [0, 1], [-1, 0.5], [-0.2, 10], ]); expect(combinedDomain).toEqual([-1, 10]); }); it('should return undefined when there is no domain to combine', () => { const combinedDomain = getCombinedDomain([]); expect(combinedDomain).toBeUndefined(); }); it('should ignore undefined domains', () => { const combinedDomain1 = getCombinedDomain([[-5, 8], undefined, undefined]); expect(combinedDomain1).toEqual([-5, 8]); const combinedDomain2 = getCombinedDomain([undefined, [0, 1], undefined]); expect(combinedDomain2).toEqual([0, 1]); }); it('should return undefined when all domains are undefined', () => { const combinedDomain = getCombinedDomain([undefined, undefined]); expect(combinedDomain).toBeUndefined(); }); });
the_stack
import { Component, OnInit, OnDestroy, ViewChild, ElementRef } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { ActivatedRoute, Router } from '@angular/router'; import * as _ from 'lodash'; import { tags } from '../tags.data'; import { AdminService } from '../admin.service'; import { AuthService } from '../auth.service'; import { TimeSlot } from '../conference.model'; import { DateService } from '../date.service'; import { Speaker } from '../speaker.model'; import { SessionService } from '../session.service'; import { SpeakerService } from '../speaker.service'; import { TransitionService } from '../transition.service'; import { ToastComponent } from '../toast.component'; import { Session } from '../session.model'; @Component({ selector: 'session', templateUrl: './session.component.html', styleUrls: ['./session.component.scss'] }) export class SessionComponent implements OnInit, OnDestroy { @ViewChild('toast') toast: ToastComponent; @ViewChild('dates') dates: ElementRef; datesSelect: HTMLSelectElement; @ViewChild('partSelect') partSelect: ElementRef; selectedDaySlots: BehaviorSubject<TimeSlot[]> = new BehaviorSubject([]); currentOccurrences = []; private paramsub: any; sessionSpeakers: BehaviorSubject<{mainPresenter: Speaker, coPresenters: Speaker[]}> = new BehaviorSubject(null); model: Session; requiredSessionFields = ['type', 'length', 'title', 'descriptionWebsite', 'descriptionProgram', 'level', 'willingToBeRecorded', 'isMediaOrPressFriendly', 'willingToRepeat', 'hasAVneeds', 'avNeeds']; tags = tags; presentationTypeLabel = ` *Please note that case studies MUST be presented by at least two parties involved in the case, one of which must be the investigator and/or prosecutor. Additional co-presenters are welcome. Examples of Acceptable Co-Presenters: - Prosecutor + investigator - Prosecutor + advocate - Prosecutor + survivor - Investigator + advocate - Investigator + survivor There are no restrictions on acceptable presenters for workshops. `; constructor(private transitionService: TransitionService, private sessionService: SessionService, private speakerService: SpeakerService, private route: ActivatedRoute, private authService: AuthService, private adminService: AdminService, private dateService: DateService, private router: Router) { } ngOnInit() { this.transitionService.transition(); // Check for params this.paramsub = this.route.params.subscribe(params => { if (!params['id']) { // Initialize default values for fields that need it this.tags.forEach(tag => { if (tag.checked) { tag.checked = false; } }); this.model = <Session>{ approval: 'pending', tags: _.clone(this.tags), } } else { this.model = this.sessionService.getSession(params['id']); this.sessionService.sessionsUnfiltered.subscribe(sessions => { this.getSessionSpeakers(); this.getCurrentOccurrences(); }); } // If a speaker is submitting, set him as lead presenter if (params['leadPresId']) { if (this.model.speakers) { this.model.speakers.mainPresenter = params['leadPresId']; } else { this.model.speakers = { mainPresenter: params['leadPresId'], coPresenters: [] } } } }); } ngOnDestroy() { this.paramsub.unsubscribe(); } mainPresenter() { return this.sessionSpeakers.getValue().mainPresenter; } /** Only current conference year occurrences should be displayed */ getCurrentOccurrences() { let defaultConf = this.adminService.defaultConference.getValue().title; this.currentOccurrences = []; if (this.model.statusTimeLocation && this.model.statusTimeLocation.length > 0) { this.model.statusTimeLocation.forEach(occurrence => { if (occurrence.conferenceTitle === defaultConf) { this.currentOccurrences.push(occurrence); } }); } } getPart(occurrence) { if (this.model.length === '90') { return ''; } else { return `Part ${occurrence.part}: `; } } getDate(occurrence) { return this.adminService.findDateBySlot(occurrence.timeSlot); } slot(occurrence) { return this.adminService.findSlotById(occurrence.timeSlot); } capitalize(word: string): string { return word.charAt(0).toUpperCase() + word.slice(1); } updateSelectedDate(selectedDate: string, slotId?: string) { let dbDate = this.dateService.formatDateForDatabase(selectedDate); let day = _.find(this.adminService.defaultConference.getValue().days, day => day.date === dbDate); // Check if we have any timeslots yet if (!(typeof day === 'undefined') && !(typeof day.timeSlots === 'undefined')) { let slots = day.timeSlots; // Sort slots from earliest to latest by end time slots = _.sortBy(slots, slot => slot.end); this.selectedDaySlots.next(slots); } else { this.selectedDaySlots.next([]); } } changeTag(isChecked: boolean, tagChecked) { let tag = _.find(this.model.tags, tag => tag.name === tagChecked.name); tag.checked = isChecked; } changeAssociatedConf(conferenceTitle: string) { this.sessionService .changeAssociatedConf(this.model, conferenceTitle) .then(res => this.toast.success(`Now associated with: ${conferenceTitle}`)); } saveToSlot(slotId: string, room: string) { let part = '0'; if (this.model.length === '180') { part = this.partSelect.nativeElement.value; } let slot = this.adminService.findSlotById(slotId); this.sessionService.setSession(slot, room, this.model._id, part) .then((res: any) => { if (res.occupied) { this.toast.error('Time/room slot is occupied! Clear it first to add new session.') } else if (res.alreadyScheduled) { this.toast.error('This session is already scheduled in a room for this time slot.') } else { this.toast.success('Session assigned to slot'); } }); } clearSlot(occurrence) { let slot = this.adminService.findSlotById(occurrence.timeSlot); this.sessionService.clearSlotSession(slot, occurrence.room) .then((res: any) => { if (res !== 'No scheduled session') { if (res.errMsg) { this.toast.error(res.errMsg); } else { this.toast.success('Removed session from slot'); this.getCurrentOccurrences(); } } }); } assignSpeaker(speakerId: string, isLead: boolean) { this.sessionService.assignSpeaker(speakerId, isLead, this.model._id) .then(res => { if (!(res.message === 'duplicate')) { this.toast.success('Speaker assigned'); } }); } removeSpeaker(speakerId: string) { if (speakerId === 'main') { speakerId = this.model.speakers.mainPresenter; } this.sessionService.removeSpeaker(speakerId, this.model._id) .then(res => { this.toast.success('Speaker removed'); }); } getSessionSpeakers() { let mainPresenter = this.speakerService.getSpeaker(this.model.speakers.mainPresenter); let coPresenters = []; this.model.speakers.coPresenters.forEach(coPresId => { let coPres = this.speakerService.getSpeaker(coPresId); if (coPres) coPresenters.push(coPres); }); this.sessionSpeakers.next({ mainPresenter: mainPresenter, coPresenters: coPresenters }); } updateSession(form: any) { this.model.sessionComplete = this.checkSession(form); this.model.associatedConf = this.adminService.defaultConference.getValue().title; this.sessionService .updateSession(this.model) .then(res => { if (!this.authService.user.getValue().admin) { this.router.navigate(['/dashboard', { msg: 'Presentation proposal saved!' }]); } else { this.router.navigate(['/session-list', { msg: 'Session saved!' }]); } }); } checkSession(form: any) { let flag = true; this.requiredSessionFields.forEach(item => { if (item === 'avNeeds') { if (form['hasAVneeds'] === 'yes') { if (!form['avNeeds']) { flag = false; } } } else { if (typeof form[item] !== undefined) { if (typeof form[item] !== 'boolean') { if (!form[item]) { flag = false; } } } else { flag = false; } } }); if (!this.atLeastOneChecked()) flag = false; return flag; } atLeastOneChecked(): boolean { let atLeastOne = false; this.model.tags.forEach(tag => { if (tag.checked) atLeastOne = true }); return atLeastOne; } changeApproval(approval: string) { this.sessionService .changeApproval(this.model, approval) .then(res => { this.toast.success(`Session is now ${approval}`); }); } email() { window.open('mailto:bmeyer@genesisshelter.org'); } deleteSession() { var confirmation = confirm('Are you sure you want to delete this session?'); if (confirmation) { this.sessionService .deleteSession(this.model) .then(res => { this.sessionService .getAllSessions().then(() => { this.router.navigate(['/home', { msg: 'Session has been deleted.' }]); }); }); } } willingToRepeatComplete(): boolean { if (typeof this.model.willingToRepeat === 'boolean') { return true; } else { return false; } } lockSession(): boolean { if (!this.model.statusTimeLocation) return false; let scheduledForCurrentConf = false; this.model.statusTimeLocation.forEach(event => { if (event.conferenceTitle === this.adminService.defaultConference.getValue().title) { scheduledForCurrentConf = true; } }); return scheduledForCurrentConf && this.model.approval === 'approved'; } }
the_stack
import { ComponentMapping } from '../componentMap' /** * Use .+ to avoid escape of regular expression, could be replaced with escaped string. */ export const antdComponentMapV4: ComponentMapping = { Affix: { anchorBeforeProps: '## API', methods: ['target', 'onChange'], }, Alert: { anchorBeforeProps: '## API', methods: ['afterClose', 'onClose'], }, 'Alert.ErrorBoundary': { docAlias: 'alert', anchorBeforeProps: '### Alert.ErrorBoundary', methods: [], }, Anchor: { anchorBeforeProps: '### Anchor Props', methods: ['getContainer', 'onClick', 'getCurrentAnchor', 'onChange'], }, 'Anchor.Link': { docAlias: 'anchor', anchorBeforeProps: '### Link Props', methods: [], }, AutoComplete: { anchorBeforeProps: '## API', methods: [ 'filterOption', 'getPopupContainer', 'onBlur', 'onChange', 'onFocus', 'onSearch', 'onSelect', 'onDropdownVisibleChange', ], }, Avatar: { anchorBeforeProps: '### Avatar', methods: ['onError'], }, 'Avatar.Group': { docAlias: 'avatar', anchorBeforeProps: '### Avatar.Group .+', methods: ['onError'], }, BackTop: { anchorBeforeProps: '## API', methods: ['target', 'onClick'], }, Badge: { anchorBeforeProps: '### Badge', methods: [], }, 'Badge.Ribbon': { docAlias: 'badge', anchorBeforeProps: '### Badge.Ribbon .+', methods: [], }, Breadcrumb: { anchorBeforeProps: '## API', methods: ['itemRender'], }, 'Breadcrumb.Item': { docAlias: 'breadcrumb', anchorBeforeProps: '### Breadcrumb.Item', methods: ['overlay', 'onClick'], }, 'Breadcrumb.Separator': { docAlias: 'breadcrumb', anchorBeforeProps: '### Breadcrumb.Separator', methods: [], }, Button: { anchorBeforeProps: '## API', methods: ['onClick'], }, Calendar: { anchorBeforeProps: '## API', methods: [ 'dateCellRender', 'dateFullCellRender', 'disabledDate', 'monthCellRender', 'monthFullCellRender', 'onPanelChange', 'onSelect', 'onChange', 'headerRender', ], }, Card: { anchorBeforeProps: '### Card', methods: ['onTabChange'], }, 'Card.Grid': { docAlias: 'card', anchorBeforeProps: '### Card.Grid', methods: [], }, 'Card.Meta': { docAlias: 'card', anchorBeforeProps: '### Card.Meta', methods: [], }, Carousel: { anchorBeforeProps: '## API', methods: ['afterChange', 'beforeChange'], }, Cascader: { anchorBeforeProps: '## API', methods: [ 'displayRender', 'getPopupContainer', 'loadData', 'onChange', 'onPopupVisibleChange', 'filter', 'render', 'sort', ], }, Checkbox: { anchorBeforeProps: '## API', methods: ['onChange'], }, 'Checkbox.Group': { docAlias: 'checkbox', anchorBeforeProps: '#### Checkbox Group', methods: ['onChange'], }, Collapse: { anchorBeforeProps: '### Collapse', methods: ['onChange', 'expandIcon'], }, 'Collapse.Panel': { docAlias: 'collapse', anchorBeforeProps: '### Collapse.Panel', methods: [], }, Comment: { anchorBeforeProps: '## API', methods: [], }, DatePicker: { anchorBeforeProps: ['### DatePicker'], methods: [ // Picker 'dateRender', 'disabledDate', 'getCalendarContainer', 'onOpenChange', 'onPanelChange', 'disabledTime', 'renderExtraFooter', 'onChange', 'onOk', 'onPanelChange', ], }, Descriptions: { anchorBeforeProps: '### Descriptions', methods: [], }, 'Descriptions.Item': { docAlias: 'descriptions', anchorBeforeProps: '### DescriptionItem', methods: [], }, Divider: { anchorBeforeProps: '## API', methods: [], }, Drawer: { anchorBeforeProps: '## API', methods: ['getContainer', 'onClose', 'afterVisibleChange'], }, Dropdown: { anchorBeforeProps: '## API', methods: ['getPopupContainer', 'overlay', 'onVisibleChange'], }, 'Dropdown.Button': { docAlias: 'dropdown', anchorBeforeProps: '### Dropdown.Button', methods: ['onClick', 'onVisibleChange'], }, Empty: { anchorBeforeProps: '## API', methods: [], }, Form: { anchorBeforeProps: '### Form', methods: ['onSubmit'], }, 'Form.Item': { docAlias: 'form', anchorBeforeProps: '## Form.Item', methods: [], }, 'Form.List': { docAlias: 'form', anchorBeforeProps: '## Form.List', methods: [], }, 'Form.ErrorList': { docAlias: 'form', anchorBeforeProps: '## Form.ErrorList', methods: [], }, 'Form.Provider': { docAlias: 'form', anchorBeforeProps: '## Form.Provider', methods: [], }, Row: { docAlias: 'grid', anchorBeforeProps: '### Row', methods: [], }, Col: { docAlias: 'grid', anchorBeforeProps: '### Col', methods: [], }, Icon: { anchorBeforeProps: '## API', methods: [], }, Image: { anchorBeforeProps: '## API', methods: [], }, Input: { anchorBeforeProps: '### Input', methods: ['onChange', 'onPressEnter'], }, 'Input.TextArea': { docAlias: 'input', anchorBeforeProps: '### Input.TextArea', methods: ['onPressEnter'], }, 'Input.Search': { docAlias: 'input', anchorBeforeProps: ['#### Input.Search'], methods: ['onSearch', 'onChange', 'onPressEnter'], }, 'Input.Group': { docAlias: 'input', anchorBeforeProps: '#### Input.Group', methods: [], }, 'Input.Password': { docAlias: 'input', anchorBeforeProps: '#### Input.Password', methods: [], }, InputNumber: { anchorBeforeProps: '## API', methods: ['formatter', 'parser', 'onChange', 'onPressEnter'], }, Layout: { anchorBeforeProps: '### Layout', methods: [], }, 'Layout.Sider': { docAlias: 'layout', anchorBeforeProps: '### Layout.Sider', methods: ['onCollapse', 'onBreakpoint'], }, List: { anchorBeforeProps: '## API', methods: ['renderItem'], }, 'List.Item': { docAlias: 'list', anchorBeforeProps: '### List.Item', methods: [], }, 'List.Item.Meta': { docAlias: 'list', anchorBeforeProps: '### List.Item.Meta', methods: [], }, Mentions: { // EN document shows `### Mention`, it's a typo. anchorBeforeProps: ['### Mentions', '### Mention'], methods: [ 'filterOption', 'validateSearch', 'onChange', 'onSelect', 'onSearch', 'onFocus', 'onBlur', 'getPopupContainer', 'onResize', ], }, 'Mentins.Option': { docAlias: 'mentions', anchorBeforeProps: '### Option', methods: [], }, Menu: { anchorBeforeProps: '## API', methods: ['onClick', 'onDeselect', 'onOpenChange', 'onSelect'], }, 'Menu.Item': { docAlias: 'menu', anchorBeforeProps: '### Menu.Item', methods: [], }, 'Menu.SubMenu': { docAlias: 'menu', anchorBeforeProps: '### Menu.SubMenu', methods: ['onTitleClick'], }, 'Menu.ItemGroup': { docAlias: 'menu', anchorBeforeProps: '### Menu.ItemGroup', methods: [], }, // Message: { // anchorBeforeProps: '## API', // methods: ['onClose'], // }, Modal: { anchorBeforeProps: '## API', methods: ['afterClose', 'getContainer', 'onCancel', 'onOk'], }, // Notification: { // anchorBeforeProps: '## API', // methods: ['getContainer', 'onClose', 'onClick'], // }, PageHeader: { anchorBeforeProps: '## API', methods: ['onBack'], }, Pagination: { anchorBeforeProps: '## API', methods: ['itemRender', 'showTotal', 'onChange', 'onShowSizeChange'], }, Popconfirm: { anchorBeforeProps: '## API', methods: ['onCancel', 'onConfirm', 'getPopupContainer', 'onVisibleChange'], }, Popover: { anchorBeforeProps: '## API', methods: ['getPopupContainer', 'onVisibleChange'], }, Progress: { anchorBeforeProps: '## API', methods: ['format'], }, Radio: { anchorBeforeProps: '## API', methods: [], }, 'Radio.Group': { docAlias: 'radio', anchorBeforeProps: '### RadioGroup', methods: ['onChange'], }, Rate: { anchorBeforeProps: '## API', methods: ['onBlur', 'onChange', 'onFocus', 'onHoverChange', 'onKeyDown'], }, Result: { anchorBeforeProps: '## API', methods: [], }, Select: { anchorBeforeProps: '### Select props', methods: [ 'dropdownRender', 'filterOption', 'getPopupContainer', 'maxTagPlaceholder', 'onBlur', 'onChange', 'onDeselect', 'onFocus', 'onInputKeyDown', 'onMouseEnter', 'onMouseLeave', 'onPopupScroll', 'onSearch', 'onSelect', 'onDropdownVisibleChange', ], }, 'Select.Option': { docAlias: 'select', anchorBeforeProps: '### Option props', methods: [], }, 'Select.OptGroup': { docAlias: 'select', anchorBeforeProps: '### OptGroup props', methods: [], }, Skeleton: { anchorBeforeProps: '### Skeleton', methods: [], }, Slider: { anchorBeforeProps: '## API', methods: ['tipFormatter', 'onAfterChange', 'onChange', 'getTooltipPopupContainer'], }, Space: { anchorBeforeProps: '## API', methods: [], }, Spin: { anchorBeforeProps: '## API', methods: [], }, Statistic: { anchorBeforeProps: '#### Statistic', methods: ['formatter'], }, 'Statistic.Countdown': { docAlias: 'statistic', anchorBeforeProps: '#### Statistic.Countdown', methods: ['onFinish'], }, Steps: { anchorBeforeProps: '### Steps', methods: ['progressDot', 'onChange'], }, 'Steps.Step': { docAlias: 'steps', anchorBeforeProps: '### Steps.Step', methods: [], }, Switch: { anchorBeforeProps: '## API', methods: ['onChange', 'onClick'], }, Table: { anchorBeforeProps: '### Table', methods: [ 'expandedRowRender', 'expandIcon', 'footer', 'rowClassName', 'rowKey', 'title', 'onChange', 'onExpand', 'onExpandedRowsChange', 'onHeaderRow', 'onRow', 'getPopupContainer', ], }, 'Table.Column': { docAlias: 'table', anchorBeforeProps: '### Column', methods: [ 'filterDropdown', 'filterIcon', 'render', 'sorter', 'title', 'onCell', 'onFilter', 'onFilterDropdownVisibleChange', 'onHeaderCell', ], }, 'Table.ColumnGroup': { docAlias: 'table', anchorBeforeProps: '### ColumnGroup', methods: [], }, Tabs: { anchorBeforeProps: '### Tabs', methods: ['renderTabBar', 'onChange', 'onEdit', 'onNextClick', 'onPrevClick', 'onTabClick'], }, 'Tabs.TabPane': { docAlias: 'tabs', anchorBeforeProps: '### Tabs.TabPane', methods: [], }, Tag: { anchorBeforeProps: '### Tag', methods: ['afterClose', 'onClose'], }, 'Tag.CheckableTag': { docAlias: 'tag', anchorBeforeProps: '### Tag.CheckableTag', methods: ['onChange'], }, TimePicker: { anchorBeforeProps: '## API', methods: [ 'addon', 'disabledHours', 'disabledMinutes', 'disabledSeconds', 'getPopupContainer', 'onChange', 'onOpenChange', ], }, Timeline: { anchorBeforeProps: '### Timeline', methods: [], }, 'Timeline.Item': { docAlias: 'timeline', anchorBeforeProps: '### Timeline.Item', methods: [], }, Tooltip: { anchorBeforeProps: ['### Common API', '### 共同的 API', '## API'], methods: ['title', 'getPopupContainer', 'onVisibleChange'], }, Transfer: { anchorBeforeProps: '## API', methods: [ 'filterOption', 'footer', 'listStyle', 'render', 'onChange', 'onScroll', 'onSearch', 'onSelectChange', ], }, Tree: { anchorBeforeProps: '### Tree props', methods: [ 'filterTreeNode', 'loadData', 'onCheck', 'onDragEnd', 'onDragEnter', 'onDragLeave', 'onDragOver', 'onDragStart', 'onDrop', 'onExpand', 'onLoad', 'onRightClick', 'onSelect', ], }, 'Tree.TreeNode': { docAlias: 'tree', anchorBeforeProps: '### TreeNode props', methods: ['icon'], }, 'Tree.DirectoryTree': { docAlias: 'tree', anchorBeforeProps: '### DirectoryTree props', methods: [], }, TreeSelect: { anchorBeforeProps: '### Tree props', methods: [ 'filterTreeNode', 'getPopupContainer', 'loadData', 'maxTagPlaceholder', 'onChange', 'onSearch', 'onSelect', 'onTreeExpand', ], }, 'TreeSelect.TreeNode': { docAlias: 'tree-select', anchorBeforeProps: '### TreeNode props', methods: [], }, 'Typography.Text': { docAlias: 'typography', anchorBeforeProps: '### Typography.Text', methods: [], }, 'Typography.Title': { docAlias: 'typography', anchorBeforeProps: '### Typography.Title', methods: ['onChange'], }, 'Typography.Paragraph': { docAlias: 'typography', anchorBeforeProps: '### Typography.Paragraph', methods: ['onChange'], }, Upload: { anchorBeforeProps: '## API', methods: [ 'action', 'beforeUpload', 'customRequest', 'data', 'previewFile', 'showUploadList', 'onPreview', 'onRemove', 'onDownload', 'transformFile', ], }, }
the_stack
import { defineContainer } from './vue-component-lib/utils'; import type { JSX } from '@ionic/core/components'; import { defineCustomElement as defineIonAccordion } from '@ionic/core/components/ion-accordion.js'; import { defineCustomElement as defineIonAccordionGroup } from '@ionic/core/components/ion-accordion-group.js'; import { defineCustomElement as defineIonAvatar } from '@ionic/core/components/ion-avatar.js'; import { defineCustomElement as defineIonBackdrop } from '@ionic/core/components/ion-backdrop.js'; import { defineCustomElement as defineIonBadge } from '@ionic/core/components/ion-badge.js'; import { defineCustomElement as defineIonBreadcrumb } from '@ionic/core/components/ion-breadcrumb.js'; import { defineCustomElement as defineIonBreadcrumbs } from '@ionic/core/components/ion-breadcrumbs.js'; import { defineCustomElement as defineIonButton } from '@ionic/core/components/ion-button.js'; import { defineCustomElement as defineIonButtons } from '@ionic/core/components/ion-buttons.js'; import { defineCustomElement as defineIonCard } from '@ionic/core/components/ion-card.js'; import { defineCustomElement as defineIonCardContent } from '@ionic/core/components/ion-card-content.js'; import { defineCustomElement as defineIonCardHeader } from '@ionic/core/components/ion-card-header.js'; import { defineCustomElement as defineIonCardSubtitle } from '@ionic/core/components/ion-card-subtitle.js'; import { defineCustomElement as defineIonCardTitle } from '@ionic/core/components/ion-card-title.js'; import { defineCustomElement as defineIonCheckbox } from '@ionic/core/components/ion-checkbox.js'; import { defineCustomElement as defineIonChip } from '@ionic/core/components/ion-chip.js'; import { defineCustomElement as defineIonCol } from '@ionic/core/components/ion-col.js'; import { defineCustomElement as defineIonContent } from '@ionic/core/components/ion-content.js'; import { defineCustomElement as defineIonDatetime } from '@ionic/core/components/ion-datetime.js'; import { defineCustomElement as defineIonFab } from '@ionic/core/components/ion-fab.js'; import { defineCustomElement as defineIonFabButton } from '@ionic/core/components/ion-fab-button.js'; import { defineCustomElement as defineIonFabList } from '@ionic/core/components/ion-fab-list.js'; import { defineCustomElement as defineIonFooter } from '@ionic/core/components/ion-footer.js'; import { defineCustomElement as defineIonGrid } from '@ionic/core/components/ion-grid.js'; import { defineCustomElement as defineIonHeader } from '@ionic/core/components/ion-header.js'; import { defineCustomElement as defineIonImg } from '@ionic/core/components/ion-img.js'; import { defineCustomElement as defineIonInfiniteScroll } from '@ionic/core/components/ion-infinite-scroll.js'; import { defineCustomElement as defineIonInfiniteScrollContent } from '@ionic/core/components/ion-infinite-scroll-content.js'; import { defineCustomElement as defineIonInput } from '@ionic/core/components/ion-input.js'; import { defineCustomElement as defineIonItem } from '@ionic/core/components/ion-item.js'; import { defineCustomElement as defineIonItemDivider } from '@ionic/core/components/ion-item-divider.js'; import { defineCustomElement as defineIonItemGroup } from '@ionic/core/components/ion-item-group.js'; import { defineCustomElement as defineIonItemOption } from '@ionic/core/components/ion-item-option.js'; import { defineCustomElement as defineIonItemOptions } from '@ionic/core/components/ion-item-options.js'; import { defineCustomElement as defineIonItemSliding } from '@ionic/core/components/ion-item-sliding.js'; import { defineCustomElement as defineIonLabel } from '@ionic/core/components/ion-label.js'; import { defineCustomElement as defineIonList } from '@ionic/core/components/ion-list.js'; import { defineCustomElement as defineIonListHeader } from '@ionic/core/components/ion-list-header.js'; import { defineCustomElement as defineIonMenu } from '@ionic/core/components/ion-menu.js'; import { defineCustomElement as defineIonMenuButton } from '@ionic/core/components/ion-menu-button.js'; import { defineCustomElement as defineIonMenuToggle } from '@ionic/core/components/ion-menu-toggle.js'; import { defineCustomElement as defineIonNav } from '@ionic/core/components/ion-nav.js'; import { defineCustomElement as defineIonNavLink } from '@ionic/core/components/ion-nav-link.js'; import { defineCustomElement as defineIonNote } from '@ionic/core/components/ion-note.js'; import { defineCustomElement as defineIonProgressBar } from '@ionic/core/components/ion-progress-bar.js'; import { defineCustomElement as defineIonRadio } from '@ionic/core/components/ion-radio.js'; import { defineCustomElement as defineIonRadioGroup } from '@ionic/core/components/ion-radio-group.js'; import { defineCustomElement as defineIonRange } from '@ionic/core/components/ion-range.js'; import { defineCustomElement as defineIonRefresher } from '@ionic/core/components/ion-refresher.js'; import { defineCustomElement as defineIonRefresherContent } from '@ionic/core/components/ion-refresher-content.js'; import { defineCustomElement as defineIonReorder } from '@ionic/core/components/ion-reorder.js'; import { defineCustomElement as defineIonReorderGroup } from '@ionic/core/components/ion-reorder-group.js'; import { defineCustomElement as defineIonRippleEffect } from '@ionic/core/components/ion-ripple-effect.js'; import { defineCustomElement as defineIonRow } from '@ionic/core/components/ion-row.js'; import { defineCustomElement as defineIonSearchbar } from '@ionic/core/components/ion-searchbar.js'; import { defineCustomElement as defineIonSegment } from '@ionic/core/components/ion-segment.js'; import { defineCustomElement as defineIonSegmentButton } from '@ionic/core/components/ion-segment-button.js'; import { defineCustomElement as defineIonSelect } from '@ionic/core/components/ion-select.js'; import { defineCustomElement as defineIonSelectOption } from '@ionic/core/components/ion-select-option.js'; import { defineCustomElement as defineIonSkeletonText } from '@ionic/core/components/ion-skeleton-text.js'; import { defineCustomElement as defineIonSlide } from '@ionic/core/components/ion-slide.js'; import { defineCustomElement as defineIonSlides } from '@ionic/core/components/ion-slides.js'; import { defineCustomElement as defineIonSpinner } from '@ionic/core/components/ion-spinner.js'; import { defineCustomElement as defineIonSplitPane } from '@ionic/core/components/ion-split-pane.js'; import { defineCustomElement as defineIonText } from '@ionic/core/components/ion-text.js'; import { defineCustomElement as defineIonTextarea } from '@ionic/core/components/ion-textarea.js'; import { defineCustomElement as defineIonThumbnail } from '@ionic/core/components/ion-thumbnail.js'; import { defineCustomElement as defineIonTitle } from '@ionic/core/components/ion-title.js'; import { defineCustomElement as defineIonToggle } from '@ionic/core/components/ion-toggle.js'; import { defineCustomElement as defineIonToolbar } from '@ionic/core/components/ion-toolbar.js'; import { defineCustomElement as defineIonVirtualScroll } from '@ionic/core/components/ion-virtual-scroll.js'; export const IonAccordion = /*@__PURE__*/ defineContainer<JSX.IonAccordion>('ion-accordion', defineIonAccordion, [ 'value', 'disabled', 'readonly', 'toggleIcon', 'toggleIconSlot' ]); export const IonAccordionGroup = /*@__PURE__*/ defineContainer<JSX.IonAccordionGroup>('ion-accordion-group', defineIonAccordionGroup, [ 'animated', 'multiple', 'value', 'disabled', 'readonly', 'expand', 'ionChange' ], 'value', 'v-ion-change', 'ionChange'); export const IonAvatar = /*@__PURE__*/ defineContainer<JSX.IonAvatar>('ion-avatar', defineIonAvatar); export const IonBackdrop = /*@__PURE__*/ defineContainer<JSX.IonBackdrop>('ion-backdrop', defineIonBackdrop, [ 'visible', 'tappable', 'stopPropagation', 'ionBackdropTap' ]); export const IonBadge = /*@__PURE__*/ defineContainer<JSX.IonBadge>('ion-badge', defineIonBadge, [ 'color' ]); export const IonBreadcrumb = /*@__PURE__*/ defineContainer<JSX.IonBreadcrumb>('ion-breadcrumb', defineIonBreadcrumb, [ 'collapsed', 'last', 'showCollapsedIndicator', 'color', 'active', 'disabled', 'download', 'href', 'rel', 'separator', 'target', 'routerDirection', 'routerAnimation', 'ionFocus', 'ionBlur', 'collapsedClick' ]); export const IonBreadcrumbs = /*@__PURE__*/ defineContainer<JSX.IonBreadcrumbs>('ion-breadcrumbs', defineIonBreadcrumbs, [ 'color', 'maxItems', 'itemsBeforeCollapse', 'itemsAfterCollapse', 'ionCollapsedClick' ]); export const IonButton = /*@__PURE__*/ defineContainer<JSX.IonButton>('ion-button', defineIonButton, [ 'color', 'buttonType', 'disabled', 'expand', 'fill', 'routerDirection', 'routerAnimation', 'download', 'href', 'rel', 'shape', 'size', 'strong', 'target', 'type', 'ionFocus', 'ionBlur' ]); export const IonButtons = /*@__PURE__*/ defineContainer<JSX.IonButtons>('ion-buttons', defineIonButtons, [ 'collapse' ]); export const IonCard = /*@__PURE__*/ defineContainer<JSX.IonCard>('ion-card', defineIonCard, [ 'color', 'button', 'type', 'disabled', 'download', 'href', 'rel', 'routerDirection', 'routerAnimation', 'target' ]); export const IonCardContent = /*@__PURE__*/ defineContainer<JSX.IonCardContent>('ion-card-content', defineIonCardContent); export const IonCardHeader = /*@__PURE__*/ defineContainer<JSX.IonCardHeader>('ion-card-header', defineIonCardHeader, [ 'color', 'translucent' ]); export const IonCardSubtitle = /*@__PURE__*/ defineContainer<JSX.IonCardSubtitle>('ion-card-subtitle', defineIonCardSubtitle, [ 'color' ]); export const IonCardTitle = /*@__PURE__*/ defineContainer<JSX.IonCardTitle>('ion-card-title', defineIonCardTitle, [ 'color' ]); export const IonCheckbox = /*@__PURE__*/ defineContainer<JSX.IonCheckbox>('ion-checkbox', defineIonCheckbox, [ 'color', 'name', 'checked', 'indeterminate', 'disabled', 'value', 'ionChange', 'ionFocus', 'ionBlur', 'ionStyle' ], 'checked', 'v-ion-change', 'ionChange'); export const IonChip = /*@__PURE__*/ defineContainer<JSX.IonChip>('ion-chip', defineIonChip, [ 'color', 'outline', 'disabled' ]); export const IonCol = /*@__PURE__*/ defineContainer<JSX.IonCol>('ion-col', defineIonCol, [ 'offset', 'offsetXs', 'offsetSm', 'offsetMd', 'offsetLg', 'offsetXl', 'pull', 'pullXs', 'pullSm', 'pullMd', 'pullLg', 'pullXl', 'push', 'pushXs', 'pushSm', 'pushMd', 'pushLg', 'pushXl', 'size', 'sizeXs', 'sizeSm', 'sizeMd', 'sizeLg', 'sizeXl' ]); export const IonContent = /*@__PURE__*/ defineContainer<JSX.IonContent>('ion-content', defineIonContent, [ 'color', 'fullscreen', 'forceOverscroll', 'scrollX', 'scrollY', 'scrollEvents', 'ionScrollStart', 'ionScroll', 'ionScrollEnd' ]); export const IonDatetime = /*@__PURE__*/ defineContainer<JSX.IonDatetime>('ion-datetime', defineIonDatetime, [ 'color', 'name', 'disabled', 'readonly', 'isDateEnabled', 'min', 'max', 'presentation', 'cancelText', 'doneText', 'clearText', 'yearValues', 'monthValues', 'dayValues', 'hourValues', 'minuteValues', 'locale', 'firstDayOfWeek', 'value', 'showDefaultTitle', 'showDefaultButtons', 'showClearButton', 'showDefaultTimeLabel', 'hourCycle', 'size', 'ionCancel', 'ionChange', 'ionFocus', 'ionBlur', 'ionStyle' ], 'value', 'v-ion-change', 'ionChange'); export const IonFab = /*@__PURE__*/ defineContainer<JSX.IonFab>('ion-fab', defineIonFab, [ 'horizontal', 'vertical', 'edge', 'activated' ]); export const IonFabButton = /*@__PURE__*/ defineContainer<JSX.IonFabButton>('ion-fab-button', defineIonFabButton, [ 'color', 'activated', 'disabled', 'download', 'href', 'rel', 'routerDirection', 'routerAnimation', 'target', 'show', 'translucent', 'type', 'size', 'closeIcon', 'ionFocus', 'ionBlur' ]); export const IonFabList = /*@__PURE__*/ defineContainer<JSX.IonFabList>('ion-fab-list', defineIonFabList, [ 'activated', 'side' ]); export const IonFooter = /*@__PURE__*/ defineContainer<JSX.IonFooter>('ion-footer', defineIonFooter, [ 'collapse', 'translucent' ]); export const IonGrid = /*@__PURE__*/ defineContainer<JSX.IonGrid>('ion-grid', defineIonGrid, [ 'fixed' ]); export const IonHeader = /*@__PURE__*/ defineContainer<JSX.IonHeader>('ion-header', defineIonHeader, [ 'collapse', 'translucent' ]); export const IonImg = /*@__PURE__*/ defineContainer<JSX.IonImg>('ion-img', defineIonImg, [ 'alt', 'src', 'ionImgWillLoad', 'ionImgDidLoad', 'ionError' ]); export const IonInfiniteScroll = /*@__PURE__*/ defineContainer<JSX.IonInfiniteScroll>('ion-infinite-scroll', defineIonInfiniteScroll, [ 'threshold', 'disabled', 'position', 'ionInfinite' ]); export const IonInfiniteScrollContent = /*@__PURE__*/ defineContainer<JSX.IonInfiniteScrollContent>('ion-infinite-scroll-content', defineIonInfiniteScrollContent, [ 'loadingSpinner', 'loadingText' ]); export const IonInput = /*@__PURE__*/ defineContainer<JSX.IonInput>('ion-input', defineIonInput, [ 'fireFocusEvents', 'color', 'accept', 'autocapitalize', 'autocomplete', 'autocorrect', 'autofocus', 'clearInput', 'clearOnEdit', 'debounce', 'disabled', 'enterkeyhint', 'inputmode', 'max', 'maxlength', 'min', 'minlength', 'multiple', 'name', 'pattern', 'placeholder', 'readonly', 'required', 'spellcheck', 'step', 'size', 'type', 'value', 'ionInput', 'ionChange', 'ionBlur', 'ionFocus', 'ionStyle' ], 'value', 'v-ion-change', 'ionChange'); export const IonItem = /*@__PURE__*/ defineContainer<JSX.IonItem>('ion-item', defineIonItem, [ 'color', 'button', 'detail', 'detailIcon', 'disabled', 'download', 'fill', 'shape', 'href', 'rel', 'lines', 'counter', 'routerAnimation', 'routerDirection', 'target', 'type', 'counterFormatter' ]); export const IonItemDivider = /*@__PURE__*/ defineContainer<JSX.IonItemDivider>('ion-item-divider', defineIonItemDivider, [ 'color', 'sticky' ]); export const IonItemGroup = /*@__PURE__*/ defineContainer<JSX.IonItemGroup>('ion-item-group', defineIonItemGroup); export const IonItemOption = /*@__PURE__*/ defineContainer<JSX.IonItemOption>('ion-item-option', defineIonItemOption, [ 'color', 'disabled', 'download', 'expandable', 'href', 'rel', 'target', 'type' ]); export const IonItemOptions = /*@__PURE__*/ defineContainer<JSX.IonItemOptions>('ion-item-options', defineIonItemOptions, [ 'side', 'ionSwipe' ]); export const IonItemSliding = /*@__PURE__*/ defineContainer<JSX.IonItemSliding>('ion-item-sliding', defineIonItemSliding, [ 'disabled', 'ionDrag' ]); export const IonLabel = /*@__PURE__*/ defineContainer<JSX.IonLabel>('ion-label', defineIonLabel, [ 'color', 'position', 'ionColor', 'ionStyle' ]); export const IonList = /*@__PURE__*/ defineContainer<JSX.IonList>('ion-list', defineIonList, [ 'lines', 'inset' ]); export const IonListHeader = /*@__PURE__*/ defineContainer<JSX.IonListHeader>('ion-list-header', defineIonListHeader, [ 'color', 'lines' ]); export const IonMenu = /*@__PURE__*/ defineContainer<JSX.IonMenu>('ion-menu', defineIonMenu, [ 'contentId', 'menuId', 'type', 'disabled', 'side', 'swipeGesture', 'maxEdgeStart', 'ionWillOpen', 'ionWillClose', 'ionDidOpen', 'ionDidClose', 'ionMenuChange' ]); export const IonMenuButton = /*@__PURE__*/ defineContainer<JSX.IonMenuButton>('ion-menu-button', defineIonMenuButton, [ 'color', 'disabled', 'menu', 'autoHide', 'type' ]); export const IonMenuToggle = /*@__PURE__*/ defineContainer<JSX.IonMenuToggle>('ion-menu-toggle', defineIonMenuToggle, [ 'menu', 'autoHide' ]); export const IonNav = /*@__PURE__*/ defineContainer<JSX.IonNav>('ion-nav', defineIonNav, [ 'delegate', 'swipeGesture', 'animated', 'animation', 'rootParams', 'root', 'ionNavWillLoad', 'ionNavWillChange', 'ionNavDidChange' ]); export const IonNavLink = /*@__PURE__*/ defineContainer<JSX.IonNavLink>('ion-nav-link', defineIonNavLink, [ 'component', 'componentProps', 'routerDirection', 'routerAnimation' ]); export const IonNote = /*@__PURE__*/ defineContainer<JSX.IonNote>('ion-note', defineIonNote, [ 'color' ]); export const IonProgressBar = /*@__PURE__*/ defineContainer<JSX.IonProgressBar>('ion-progress-bar', defineIonProgressBar, [ 'type', 'reversed', 'value', 'buffer', 'color' ]); export const IonRadio = /*@__PURE__*/ defineContainer<JSX.IonRadio>('ion-radio', defineIonRadio, [ 'color', 'name', 'disabled', 'value', 'ionStyle', 'ionFocus', 'ionBlur' ], 'value', 'v-ion-change', 'ionChange'); export const IonRadioGroup = /*@__PURE__*/ defineContainer<JSX.IonRadioGroup>('ion-radio-group', defineIonRadioGroup, [ 'allowEmptySelection', 'name', 'value', 'ionChange' ], 'value', 'v-ion-change', 'ionChange'); export const IonRange = /*@__PURE__*/ defineContainer<JSX.IonRange>('ion-range', defineIonRange, [ 'color', 'debounce', 'name', 'dualKnobs', 'min', 'max', 'pin', 'pinFormatter', 'snaps', 'step', 'ticks', 'disabled', 'value', 'ionChange', 'ionStyle', 'ionFocus', 'ionBlur', 'ionKnobMoveStart', 'ionKnobMoveEnd' ], 'value', 'v-ion-change', 'ionChange'); export const IonRefresher = /*@__PURE__*/ defineContainer<JSX.IonRefresher>('ion-refresher', defineIonRefresher, [ 'pullMin', 'pullMax', 'closeDuration', 'snapbackDuration', 'pullFactor', 'disabled', 'ionRefresh', 'ionPull', 'ionStart' ]); export const IonRefresherContent = /*@__PURE__*/ defineContainer<JSX.IonRefresherContent>('ion-refresher-content', defineIonRefresherContent, [ 'pullingIcon', 'pullingText', 'refreshingSpinner', 'refreshingText' ]); export const IonReorder = /*@__PURE__*/ defineContainer<JSX.IonReorder>('ion-reorder', defineIonReorder); export const IonReorderGroup = /*@__PURE__*/ defineContainer<JSX.IonReorderGroup>('ion-reorder-group', defineIonReorderGroup, [ 'disabled', 'ionItemReorder' ]); export const IonRippleEffect = /*@__PURE__*/ defineContainer<JSX.IonRippleEffect>('ion-ripple-effect', defineIonRippleEffect, [ 'type' ]); export const IonRow = /*@__PURE__*/ defineContainer<JSX.IonRow>('ion-row', defineIonRow); export const IonSearchbar = /*@__PURE__*/ defineContainer<JSX.IonSearchbar>('ion-searchbar', defineIonSearchbar, [ 'color', 'animated', 'autocomplete', 'autocorrect', 'cancelButtonIcon', 'cancelButtonText', 'clearIcon', 'debounce', 'disabled', 'inputmode', 'enterkeyhint', 'placeholder', 'searchIcon', 'showCancelButton', 'showClearButton', 'spellcheck', 'type', 'value', 'ionInput', 'ionChange', 'ionCancel', 'ionClear', 'ionBlur', 'ionFocus', 'ionStyle' ], 'value', 'v-ion-change', 'ionChange'); export const IonSegment = /*@__PURE__*/ defineContainer<JSX.IonSegment>('ion-segment', defineIonSegment, [ 'color', 'disabled', 'scrollable', 'swipeGesture', 'value', 'selectOnFocus', 'ionChange', 'ionSelect', 'ionStyle' ], 'value', 'v-ion-change', 'ionChange'); export const IonSegmentButton = /*@__PURE__*/ defineContainer<JSX.IonSegmentButton>('ion-segment-button', defineIonSegmentButton, [ 'disabled', 'layout', 'type', 'value' ], 'value', 'v-ion-change', 'ionChange'); export const IonSelect = /*@__PURE__*/ defineContainer<JSX.IonSelect>('ion-select', defineIonSelect, [ 'disabled', 'cancelText', 'okText', 'placeholder', 'name', 'selectedText', 'multiple', 'interface', 'interfaceOptions', 'compareWith', 'value', 'ionChange', 'ionCancel', 'ionDismiss', 'ionFocus', 'ionBlur', 'ionStyle' ], 'value', 'v-ion-change', 'ionChange'); export const IonSelectOption = /*@__PURE__*/ defineContainer<JSX.IonSelectOption>('ion-select-option', defineIonSelectOption, [ 'disabled', 'value' ]); export const IonSkeletonText = /*@__PURE__*/ defineContainer<JSX.IonSkeletonText>('ion-skeleton-text', defineIonSkeletonText, [ 'animated' ]); export const IonSlide = /*@__PURE__*/ defineContainer<JSX.IonSlide>('ion-slide', defineIonSlide); export const IonSlides = /*@__PURE__*/ defineContainer<JSX.IonSlides>('ion-slides', defineIonSlides, [ 'options', 'pager', 'scrollbar', 'ionSlidesDidLoad', 'ionSlideTap', 'ionSlideDoubleTap', 'ionSlideWillChange', 'ionSlideDidChange', 'ionSlideNextStart', 'ionSlidePrevStart', 'ionSlideNextEnd', 'ionSlidePrevEnd', 'ionSlideTransitionStart', 'ionSlideTransitionEnd', 'ionSlideDrag', 'ionSlideReachStart', 'ionSlideReachEnd', 'ionSlideTouchStart', 'ionSlideTouchEnd' ]); export const IonSpinner = /*@__PURE__*/ defineContainer<JSX.IonSpinner>('ion-spinner', defineIonSpinner, [ 'color', 'duration', 'name', 'paused' ]); export const IonSplitPane = /*@__PURE__*/ defineContainer<JSX.IonSplitPane>('ion-split-pane', defineIonSplitPane, [ 'contentId', 'disabled', 'when', 'ionSplitPaneVisible' ]); export const IonText = /*@__PURE__*/ defineContainer<JSX.IonText>('ion-text', defineIonText, [ 'color' ]); export const IonTextarea = /*@__PURE__*/ defineContainer<JSX.IonTextarea>('ion-textarea', defineIonTextarea, [ 'fireFocusEvents', 'color', 'autocapitalize', 'autofocus', 'clearOnEdit', 'debounce', 'disabled', 'inputmode', 'enterkeyhint', 'maxlength', 'minlength', 'name', 'placeholder', 'readonly', 'required', 'spellcheck', 'cols', 'rows', 'wrap', 'autoGrow', 'value', 'ionChange', 'ionInput', 'ionStyle', 'ionBlur', 'ionFocus' ], 'value', 'v-ion-change', 'ionChange'); export const IonThumbnail = /*@__PURE__*/ defineContainer<JSX.IonThumbnail>('ion-thumbnail', defineIonThumbnail); export const IonTitle = /*@__PURE__*/ defineContainer<JSX.IonTitle>('ion-title', defineIonTitle, [ 'color', 'size', 'ionStyle' ]); export const IonToggle = /*@__PURE__*/ defineContainer<JSX.IonToggle>('ion-toggle', defineIonToggle, [ 'color', 'name', 'checked', 'disabled', 'value', 'ionChange', 'ionFocus', 'ionBlur', 'ionStyle' ], 'checked', 'v-ion-change', 'ionChange'); export const IonToolbar = /*@__PURE__*/ defineContainer<JSX.IonToolbar>('ion-toolbar', defineIonToolbar, [ 'color' ]); export const IonVirtualScroll = /*@__PURE__*/ defineContainer<JSX.IonVirtualScroll>('ion-virtual-scroll', defineIonVirtualScroll, [ 'approxItemHeight', 'approxHeaderHeight', 'approxFooterHeight', 'headerFn', 'footerFn', 'items', 'itemHeight', 'headerHeight', 'footerHeight', 'renderItem', 'renderHeader', 'renderFooter', 'nodeRender', 'domRender' ]);
the_stack
import { Elm } from '../../elm/Main.elm' import { LiaEvents, lia_execute_event, lia_eval_event } from './events' // import persistent from './persistent.ts' import log from './log' import * as Swipe from './swipe' import './types/globals' import Lia from './types/lia.d' import Port from './types/ports' import TTS from './tts' import { Connector } from '../connectors/Base/index' import { updateClassName } from '../connectors/Base/settings' window.img_Zoom = function (e: MouseEvent | TouchEvent) { const target = e.target as HTMLImageElement if (target) { const zooming = e.currentTarget as HTMLImageElement if (zooming) { if (target.width < target.naturalWidth) { var offsetX = e instanceof MouseEvent ? e.offsetX : e.touches[0].pageX var offsetY = e instanceof MouseEvent ? e.offsetY : e.touches[0].pageY var x = (offsetX / zooming.offsetWidth) * 100 var y = (offsetY / zooming.offsetHeight) * 100 zooming.style.backgroundPosition = x + '% ' + y + '%' zooming.style.cursor = 'zoom-in' } else { zooming.style.cursor = '' } } } } function isInViewport(elem: HTMLElement) { const bounding = elem.getBoundingClientRect() return ( bounding.top >= 85 && bounding.left >= 0 && bounding.bottom <= (window.innerHeight - 40 || document.documentElement.clientHeight - 40) && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) ) } function scrollIntoView(id: string, delay: number) { setTimeout(function () { const elem = document.getElementById(id) if (elem) { elem.scrollIntoView({ behavior: 'smooth' }) } }, delay) } function handleEffects( event: Lia.Event, elmSend: Lia.Send, section: number = -1, self?: LiaScript ) { switch (event.topic) { case 'scrollTo': scrollIntoView(event.message, 350) break case 'persistent': // Todo // setTimeout((e) => { persistent.load(event.section) }, 10) break case 'execute': lia_execute_event(event.message, elmSend, section) break case 'speak': { let msg = { topic: Port.SETTINGS, section: -1, message: { topic: 'speak', section: -1, message: 'stop', }, } if (section >= 0) { msg = { topic: Port.EFFECT, section: section, message: { topic: 'speak', section: event.section, message: 'stop', }, } } try { if (event.message === 'cancel') { TTS.cancel() msg.message.message = 'stop' elmSend(msg) } else if (event.message === 'repeat') { event.message = [ttsBackup[0], ttsBackup[1], 'true'] handleEffects(event, elmSend) } else if ( typeof event.message === 'string' && event.message.startsWith('lia-tts-') ) { setTimeout(function () { let element = document.getElementsByClassName(event.message) let voice = element[0].getAttribute('data-voice') || 'default' let text = '' for (let i = 0; i < element.length; i++) { text += (element[i] as HTMLElement).innerText || element[i].textContent } // This is used to clean up effect numbers, which are marked by a \b text = text.replace(/\\u001a\\d+\\u001a/g, '').trim() if (text !== '' && element[0]) { TTS.speak( text, voice, function () { msg.topic = Port.SETTINGS msg.message.message = 'start' elmSend(msg) }, function () { msg.topic = Port.SETTINGS msg.message.message = 'stop' elmSend(msg) }, function (e: any) { msg.message.message = e.toString() elmSend(msg) } ) } }, 500) } else if (firstSpeak) { // this is a hack to deal with the delay in responsivevoice firstSpeak = false setTimeout(function () { handleEffects(event, elmSend) }, 200) } else { ttsBackup = event.message if (event.message[2] === 'true') { TTS.speak( event.message[1], event.message[0], function () { msg.message.message = 'start' elmSend(msg) }, function () { msg.message.message = 'stop' elmSend(msg) }, function (e: any) { msg.message.message = e.toString() elmSend(msg) } ) } } } catch (e: any) { msg.message.message = e.toString() elmSend(msg) } break } case 'sub': { if (self != undefined && event.message != null) { const newSend = function (subEvent: Lia.Event) { elmSend({ topic: Port.EFFECT, section: section, message: { topic: 'sub', section: event.section, message: subEvent, }, }) } process(false, self, newSend, event.message) } break } default: { // checking for sub-events log.warn('effect missed => ', event, section) } } } function meta(name: string, content: string) { if (content !== '') { let meta = document.createElement('meta') meta.name = name meta.content = content document.getElementsByTagName('head')[0].appendChild(meta) } } // ----------------------------------------------------------------------------- var eventHandler: LiaEvents var liaStorage: any var ttsBackup: [string, string] var firstSpeak = true class LiaScript { private app: any public connector: Connector constructor( elem: HTMLElement, connector: Connector, debug: boolean = false, courseUrl: string | null = null, script: string | null = null ) { if (debug) window.debug__ = true eventHandler = new LiaEvents() this.app = Elm.Main.init({ node: elem, flags: { courseUrl: window.liaDefaultCourse || courseUrl, script: script, settings: connector.getSettings(), screen: { width: window.innerWidth, height: window.innerHeight, }, hasShareAPI: !!navigator.share, hasIndex: connector.hasIndex(), }, }) const sendTo = this.app.ports.event2elm.send const sender = function (msg: Lia.Event) { log.info(`LIA <<< (${msg.topic}:${msg.section})`, msg.message) sendTo(msg) } this.connector = connector this.connector.connect(sender) this.initEventSystem(elem, this.app.ports.event2js.subscribe, sender) liaStorage = this.connector.storage() window.playback = function (event) { handleEffects(event.message, sender, event.section) } let self = this window.showFootnote = (key) => { self.footnote(key) } window.img_ = (src: string, width: number, height: number) => { self.img_(src, width, height) } window.img_Click = (url: string) => { self.img_Click(url) } setTimeout(function () { firstSpeak = false }, 1000) } footnote(key: string) { this.app.ports.footnote.send(key) } img_(src: string, width: number, height: number) { this.app.ports.media.send([src, width, height]) } img_Click(url: string) { // abuse media port to open modals if (document.getElementsByClassName('lia-modal').length === 0) { this.app.ports.media.send([url, null, null]) } } initNavigation(elem: HTMLElement, elmSend: Lia.Send) { Swipe.detect(elem, function (swipeDir) { if (document.getElementsByClassName('lia-modal').length === 0) { elmSend({ topic: Port.SWIPE, section: -1, message: swipeDir, }) } }) elem.addEventListener( 'keydown', (e) => { switch (e.key) { case 'ArrowRight': { if (document.getElementsByClassName('lia-modal').length === 0) { elmSend({ topic: Port.SWIPE, section: -1, message: Swipe.Dir.left, }) } break } case 'ArrowLeft': { if (document.getElementsByClassName('lia-modal').length === 0) { elmSend({ topic: Port.SWIPE, section: -1, message: Swipe.Dir.right, }) } break } } }, false ) } reset() { this.app.ports.event2elm.send({ topic: Port.RESET, section: -1, message: null, }) } initEventSystem( elem: HTMLElement, jsSubscribe: (fn: (_: Lia.Event) => void) => void, elmSend: Lia.Send ) { log.info('initEventSystem') let self = this this.initNavigation(elem, elmSend) var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { changeGoogleStyles() elmSend({ topic: 'lang', section: -1, message: document.documentElement.lang, }) }) }) observer.observe(document.documentElement, { attributes: true, childList: false, characterData: false, attributeFilter: ['lang'], }) jsSubscribe((event: Lia.Event) => { process(true, self, elmSend, event) }) } } function process( isConnected: boolean, self: LiaScript, elmSend: Lia.Send, event: Lia.Event ) { log.info(`LIA >>> (${event.topic}:${event.section})`, event.message) switch (event.topic) { case Port.SLIDE: { self.connector.slide(event.section) const sec = document.getElementsByTagName('main')[0] if (sec) { sec.scrollTo(0, 0) if (sec.children.length > 0) (sec.children[0] as HTMLElement).focus() } const elem = document.getElementById('focusedToc') if (elem) { if (!isInViewport(elem)) { elem.scrollIntoView({ behavior: 'smooth', }) } } break } case Port.LOAD: { self.connector.load({ topic: event.message, section: event.section, message: null, }) break } case Port.CODE: { switch (event.message.topic) { case 'eval': lia_eval_event(elmSend, eventHandler, event) break case 'store': if (isConnected) { event.message = event.message.message self.connector.store(event) } break case 'input': eventHandler.dispatch_input(event) break case 'stop': eventHandler.dispatch_input(event) break default: { if (isConnected) { self.connector.update(event.message, event.section) } } } break } case Port.QUIZ: { if (isConnected && event.message.topic === 'store') { event.message = event.message.message self.connector.store(event) } else if (event.message.topic === 'eval') { lia_eval_event(elmSend, eventHandler, event) } break } case Port.SURVEY: { if (isConnected && event.message.topic === 'store') { event.message = event.message.message self.connector.store(event) } else if (event.message.topic === 'eval') { lia_eval_event(elmSend, eventHandler, event) } break } case Port.TASK: { if (isConnected && event.message.topic === 'store') { event.message = event.message.message self.connector.store(event) } else if (event.message.topic === 'eval') { lia_eval_event(elmSend, eventHandler, event) } break } case Port.EFFECT: { handleEffects(event.message, elmSend, event.section, self) break } case Port.LOG: { switch (event.section) { case 0: log.info(event.message) break case 1: log.warn(event.message) break case 2: log.error(event.message) break default: console.warn('unknown log event ', event.section, event.message) } break } case Port.SETTINGS: { // if (self.channel) { // self.channel.push('lia', {settings: event.message}); // } else { try { updateClassName(event.message[0]) const conf = self.connector.getSettings() setTimeout(function () { window.dispatchEvent(new Event('resize')) }, 333) let style = document.getElementById('lia-custom-style') if (typeof event.message[1] === 'string') { if (style == null) { style = document.createElement('style') style.id = 'lia-custom-style' document.head.appendChild(style) } style.innerHTML = ':root {' + event.message[1] + '}' } else if (style !== null) { style.innerHTML = '' } } catch (e) {} if (isConnected) { self.connector.setSettings(event.message[0]) } break } case Port.RESOURCE: { let elem = event.message[0] let url = event.message[1] log.info('loading resource => ', elem, ':', url) try { let tag = document.createElement(elem) if (elem === 'link') { tag.href = url tag.rel = 'stylesheet' } else { window.event_semaphore++ tag.src = url tag.async = false tag.defer = true tag.onload = function () { window.event_semaphore-- log.info('successfully loaded =>', url) } tag.onerror = function (e: Error) { window.event_semaphore-- log.warn('could not load =>', url, e) } } document.head.appendChild(tag) } catch (e) { log.error('loading resource => ', e) } break } case Port.PERSISTENT: { if (event.message === 'store') { // todo, needs to be moved back // persistent.store(event.section) elmSend({ topic: Port.LOAD, section: -1, message: null, }) } break } case Port.INIT: { let data = event.message let isPersistent = true try { isPersistent = !( data.definition.macro['persistent'].trim().toLowerCase() === 'false' ) } catch (e) {} if (isConnected && isPersistent) { self.connector.open( data.readme, data.version, data.section_active, data ) } if (data.definition.onload !== '') { lia_execute_event({ code: data.definition.onload, delay: 350, }) } document.documentElement.lang = data.definition.language meta('author', data.definition.author) meta('og:description', data.comment) meta('og:title', data.str_title) meta('og:type', 'website') meta('og:url', '') meta('og:image', data.definition.logo) // store the basic info in the offline-repositories if (isConnected && isPersistent) { self.connector.storeToIndex(data) } break } case Port.INDEX: { if (!isConnected) break switch (event.message.topic) { case 'list': { try { TTS.cancel() } catch (e) {} self.connector.getIndex() break } case 'delete': { self.connector.deleteFromIndex(event.message.message) break } case 'restore': { self.connector.restoreFromIndex( event.message.message, event.message.section ) break } case 'reset': { self.connector.reset(event.message.message, event.message.section) break } case 'get': { self.connector.getFromIndex(event.message.message) break } default: log.error('Command not found => ', event.message) } break } case Port.SHARE: { try { if (navigator.share) { navigator.share(event.message) } } catch (e) { log.error('sharing was not possible => ', event.message, e) } break } case Port.RESET: { self.connector.reset() window.location.reload() break } case Port.TRANSLATE: { injectGoogleTranslate() break } default: log.error('Command not found => ', event) } } var googleTranslate = false function injectGoogleTranslate() { // inject the google translator if (!googleTranslate) { let tag = document.createElement('script') tag.src = '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit' tag.type = 'text/javascript' document.head.appendChild(tag) window.googleTranslateElementInit = function () { // @ts-ignore: will be injected by google new google.translate.TranslateElement( { pageLanguage: document.documentElement.lang, // includedLanguages: 'ar,en,es,jv,ko,pa,pt,ru,zh-CN', // layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL, autoDisplay: false, }, 'google_translate_element' ) } googleTranslate = true } } function changeGoogleStyles() { let goog = document.getElementById(':1.container') if (goog) { goog.style.visibility = 'hidden' document.body.style.top = '' } } export default LiaScript
the_stack
declare namespace AMap { class TileLayer extends MapEventListener<'complete'> { static Satellite: typeof Satellite; static Traffic: typeof Traffic; static RoadNet: typeof RoadNet; static Flexible: typeof Flexible; static WMS: typeof WMS; static WMTS: typeof WMTS; constructor(opts: TileLayerOptions); /** 设置图层的取图地址 */ setTileUrl(url: string): void; /** 重新加载图层资源,重新渲染 */ reload(): void; /** 设置图层层级,数字越大图层层级越高 */ setzIndex(zIndex: number): number; /** 获取图层层级 */ getzIndex(): number; /** 设置图层透明度,范围 [0 ~ 1] */ setOpacity(opacity): number; /** 获取图层透明度 */ getOpacity(): number; /** 获取图层参数信息 */ getOptions(): any; /** 获取该图层可显示的级别范围,默认取值范围为[2-20] */ getZooms(): [number, number]; /** 获取该图层可显示的级别范围 */ setZooms(zooms: [number, number]): void; } interface TileLayerOptions { /** * 切片取图地址 如:'https://abc{0,1,2,3}.amap.com/tile?x=[x]&y=[y]&z=[z]' [x]、 [y] 、 [z] 分别替代切片的xyz。 */ tileUrl?: string; /** * 支持的缩放级别范围,默认范围 [2-20] */ zooms?: [number, number]; /** * 数据支持的缩放级别范围,默认范围 [2-20] */ dataZooms?: [number, number]; /** * 透明度,默认 1 */ opacity?: number; /** * 是否显示,默认 true */ visible?: boolean; /** * 图层叠加的顺序值,1 表示最底层。默认 zIndex:4 */ zIndex?: number; /** * 切片大小,取值: * - 256,表示切片大小为256 256, * - 128,表示切片大小为128 128, * - 64,表示切片大小为64*64。默认值为256 * @default 256 */ tileSize?: number; } /** * 用于加载OGC标准的WMS地图服务的一种图层类,仅支持EPSG3857坐标系统的WMS图层。[查看 WMS的OGC标准](http://www.opengeospatial.org/standards/wms)。 */ class WMS extends MapEventListener<'complete'> { constructor(opts: WMSLayerOptions); /** 设置OGC标准的WMS getMap接口的参数,包括VERSION、LAYERS、STYLES、FORMAT、TRANSPARENT等 */ setParams(params: any): void; getParams(): any; setUrl(url: string): void; getUrl(): string; setOpacity(opacity: number): void; getOpacity(): number; setZooms(zooms: [number, number]): void; getZooms(): [number, number]; setzIndex(zIndex: number): void; getzIndex(): number; getOptions(): any; } interface WMSLayerOptions { /** wmts服务的url地址,如:' https://services.arcgisonline.com/arcgis/rest/services/'+ 'Demographics/USA_Population_Density/MapServer/WMTS/' */ url?: string; /** 地图级别切换时,不同级别的图片是否进行混合,如图层的图像内容为部分透明请设置为false */ blend?: boolean; /** OGC标准的WMS地图服务的GetMap接口的参数 */ param?: any; /** 支持的缩放级别范围,默认范围 [2-20] */ zooms?: [number, number]; /** 透明度,默认 1 */ opacity?: number; /** 是否显示,默认 true */ visible?: boolean; /** 图层叠加的顺序值,1 表示最底层。默认 zIndex:4 */ zIndex?: number; } class WMTS extends WMS { constructor(opts: WMTSLayerOptions); } interface WMTSLayerOptions extends WMSLayerOptions {} /** 卫星图层类,继承自 TileLayer。 */ class Satellite extends Omit<TileLayer, 'setTileUrl', 'reload'> { constructor(opts: SatelliteLayerOptions); /** 销毁图层 */ destroy(): void; } /** 卫星图层类,继承自 TileLayer。 */ interface SatelliteLayerOptions extends Omit<TileLayerOptions, 'tileUrl' | 'dataZooms'> {} /** 实时交通图层类,继承自TileLayer。 */ class Traffic extends Omit<TileLayer, 'setTileUrl', 'reload'> { constructor(opts: TrafficLayerOptions); /** 停止自动更新数据 */ stopFresh(): void; } interface TrafficLayerOptions extends SatelliteLayerOptions { /** 是否自动更新数据,默认开启 */ autoRefresh?: boolean; /** 自动更新数据的间隔毫秒数,默认 180ms */ interval?: number; } /** * 路网图层,展示道路信息 */ class RoadNet extends Satellite { constructor(opts: RoadNetLayerOptions); } interface RoadNetLayerOptions extends TrafficLayerOptions {} /** * 建筑楼块 3D 图层 */ class Buildings extends Satellite { constructor(opts: BuildingsLayerOptions, styleOpts: BuildingStyleOptions); setStyle(): void; } interface BuildingsLayerOptions { /** 楼块侧面颜色,支持 rgba、rgb、十六进制等 */ wallColor?: Array<string> | string; /** 楼块顶面颜色,支持 rgba、rgb、十六进制等 */ roofColor?: Array<string> | string; /** 楼块的高度系数因子,默认为 1,也就是正常高度 */ heightFactor?: number; /** 楼块的围栏和样式设置 */ BuildingStyleOptions?: BuildingStyleOptions; /** 图层缩放等级范围,默认 [2, 20] (default [2,20]) */ zooms?: [number, number]; /** 图层透明度,默认为 1 (default 1); */ opacity?: number; /** 图层是否可见,默认为 true (default true); */ visible?: boolean; /** 图层的层级,默认为 11 (default 11); */ zIndex?: number; } interface BuildingStyleOptions { /** 是否隐藏围栏之外的楼块 */ hideWithoutStyle?: boolean; /** 围栏信息数组 */ areas?: Array<BuildingStyleArea>; } interface BuildingStyleArea { /** 是否隐藏围栏之外的楼块 */ rejectTexture?: boolean; /** 围栏信息数组 */ visible?: boolean; /** 围栏经纬度列表 */ path?: Array<number>; /** 围栏区域内楼块顶面颜色,支持 rgba、rgb、十六进制等 */ color1?: Array<string> | string; /** 围栏区域内楼块侧面颜色,支持 rgba、rgb、十六进制等 */ color2?: Array<string> | string; areas?: BuildingStyleArea; } /** 室内图层,用于在适当级别展示室内地图,并提供显示商铺tip、切换楼层等功能。 */ class IndoorMap extends MapEventListener { constructor(opts: IndoorMapOptions); /** 显示指定 POI 的室内地图 */ showIndoorMap(indoorid: number, floor: number, shopid: number): void; /** 显示指定的楼层 */ showFloor(floor: number): void; /** 设置显示室内图层的地图对象 */ setMap(map: Map): void; /** 设置室内地图的显示顺序 */ setzIndex(index: number): void; /** 显示楼层切换控件 */ showFloorBar(): void; /** 隐藏楼层切换控件 */ hideFloorBar(): void; /** 设置室内图层透明度 */ setOpacity(opacity: number): void; /** 获取室内图层透明度 */ getOpacity(): number; /** 显示室内图层上的标注 */ showLabels(): void; /** 隐藏室内图层上的标注 */ hideLabels(): void; /** 获取被选中室内的 POIID */ getSelectedBuildingId(): void; /** 获取被选中的室内地图的一些基本信息,包含名称、当前楼层、所有楼层信息、POIID等 */ getSelectedBuilding(): void; } interface IndoorMapOptions { /** 室内图层叠加的顺序值 */ zIndex?: number; /** 图层的透明度,取值范围 [0,1] */ opacity?: number; /** 指定鼠标悬停到店铺面时的鼠标样式 */ cursor?: string; /** 是否隐藏楼层切换控件,默认值:false */ hideFloorBar?: boolean; } /** 矢量覆盖物图层,可添加/删除/查询矢量覆盖物(Polygon/Polyline/CircleMarker/Ellipse/RectAngle/BezierCurve)的图层 */ class VectorLayer { constructor(opts: VectorLayerOptions); /** 添加矢量覆盖物到集合中,不支持添加重复的覆盖物 */ add(vectors): void; /** 删除矢量覆盖物 */ remove(vectors: VectorLayer | Array<VectorLayer>): void; /** 判断传入的矢量覆盖物实例是否在VectorLayer这中 */ has(vector: VectorLayer): void; /** 清空 VectorLayer */ clear(): void; /** 批量修改矢量覆盖物属性(包括线样式、样色等等) */ setOptions(opt: any): void; /** 根据经纬度查询矢量覆盖物信息 */ query(geometry: LngLatLike): VectorOverlay | undefined; /** 获取 VectorOverlay 所有覆盖物显示的范围 */ getBounds(): Bounds | undefined; } interface VectorLayerOptions { /** (default true) 是否显示 */ visible?: boolean; } class HeatMap extends MapEventListener { constructor(map: Map, opts: HeatMapOptions); /** 获取热力图的属性信息 */ getOptions(): HeatMapOptions; /** 设置热力图要叠加的地图实例,也可以在Map中的layers属性中设置为默认显示的图层 */ setMap(map: Map): void; /** 设置热力图层叠加层级 */ setzIndex(zIndex: number): void; /** 获得热力图层叠加层级 */ getzIndex(): number; /** 向热力图数据集中添加坐标点,count不填写时默认:1 */ addDataPoint(longitude: string, latitude: string, count: number): void; /** * 设置热力图展现的数据集,dataset数据集格式为: * ```js * { max: Number 权重的最大值, data: Array 坐标数据集 } * ``` * 其中max不填则取数据集count最大值 例: * ```js * { max: 100, data: [{lng: 116.405285, lat: 39.904989, count: 65},{}, …] } * ``` * 也可以通过url来加载数据,格式为 * ```js * { * data: jsonp格式数据的服务地址URL, * dataParser: 数据格式转换function * //当jsonp返回结果和官方结构不一致的时候,用户可以传递一个函数用来进行数据格式转换; * } * ``` * 例: * ```js * { * data:'http://abc.com/jsonp.js', * dataParser: function(data){ * // 返回的对象结果应该与上面例子的data字段结构相同 * return doSomthing(data); * } * } * ``` */ setDataSet(dataset: HeatMapDataSet): void; /** 输出热力图的数据集,数据结构同setDataSet中的数据集 */ getDataSet(): HeatMapDataSet; /** 设置热力图属性,请参考 HeatMapOptions 列表中的说明 */ setOptions(options: HeatMapOptions): void; /** 获取热力图叠加地图对象 */ getMap(): Map; } type HeatMapDataSet = { /** 权重的最大值 */ max?: number, /** 坐标数据集 */ data: string | LngLat[] | { lng: number, lat: number, count: number }, /** 数据格式转换 Function */ dataParser?: (data: LngLat[] | { lng: number, lat: number, count: number }) => LngLat[] | { lng: number, lat: number, count: number } } interface HeatMapOptions { /** 热力图中单个点的半径,默认:30,单位:pixel */ radius?: number; /** 热力图的渐变区间,热力图按照设置的颜色及间隔显示热力图,例{0.4:'rgb(0, 255, 255)',0.85:'rgb(100, 0, 255)',},其中 key 表示间隔位置,取值范围: [0,1] ,value 为颜色值。默认:heatmap.js标准配色方案 */ gradient?: object; /** 热力图透明度区间数组,取值范围 [0,1] ,0表示完全透明,1表示不透明,默认: [0,1] */ opacity?: array; /** 支持的缩放级别范围,取值范围 [3-20] ,默认: [3,20] */ zooms?: array; /** 是否可见 */ visible?: boolean; /** 热力图层在地图上的叠加顺序,默认 130 */ zIndex?: number; /** 3D热力图属性 */ '3d'?: HeatMap3DOptions; } interface HeatMap3DOptions { /** 高度缩放因子,表示在单位高度上的缩放比例, 默认为 1 */ heightScale?: number; /** 影响高度平滑度的贝塞尔曲线因子,默认 [0.5, 0, 1, 0.5] , */ heightBezier?: array; /** 取样精度,越小越平滑,越大性能越高 */ gridSize?: number; } class LabelsLayer extends MapEventListener { constructor(opts: LabelsLayerOptions); /** 获取标注层透明度 */ getOpacity(): number; /** 设置标注层透明度 */ setOpacity(opacity: boolean): void; /** 获取标注层叠加顺序 */ getzIndex(): number; /** 设置标注层叠加顺序 */ setzIndex(zIndex: number): void; /** 获取标注层显示层级范围 */ getZooms(): [number, number]; /** 设置标注层显示层级范围 */ setZooms(zooms: [number, number]): void; // ^^^^^^^^ 上面公共部分 ^^^^^^^^ /** 获取标注层是否支持内部标注避让 */ getCollision(): void; /** 设置标注层是否支持内部标注避让 */ setCollision(collision: boolean): void; /** 获取标注层是否允许其它层标注避让 */ getAllowCollision(): void; /** 设置标注层是否允许其它层标注避让,开启该功能可实现地图标注对 LabelMarker 的避让,[相关示例](https://lbs.amap.com/api/jsapi-v2/example/marker/labelsmarker) */ setAllowCollision(allowCollision: boolean): void; /** 将 labelMarker 添加到标注层上 */ add(labelMarkers: LabelsLayer[]): void; /** 将 labelMarker 从标注层上移除 */ remove(labelMarkers: LabelsLayer | LabelsLayer[]): void; /** 清空标注层上的标注 */ clear(): void; /** 获取标注层内的所有标注对象 */ getAllOverlays(): any[]; } interface LabelsLayerOptions { /** 标注层展示层级范围 */ zooms?: Array<number>; /** 标注层透明度 */ opacity?: number; /** 标注层是否可见,默认值:true */ visible?: boolean; /** 标注层与其它图层的叠加顺序,默认值:120 */ zIndex?: number; // ^^^^^^^^ 上面公共部分 ^^^^^^^^ /** 标注层内的标注是否互相避让,默认值: true */ collision?: boolean; /** 标注层内的标注是否允许其它标注层对它避让,默认值:false,开启该功能可实现地图标注对 LabelMarker 的避让 */ allowCollision?: boolean; } class CustomLayer extends MapEventListener { constructor(canvas: HTMLCanvasElement, opts: CustomLayerOption); /** 获取标注层透明度 */ getOpacity(): number; /** 设置标注层透明度 */ setOpacity(opacity: boolean): void; /** 获取标注层叠加顺序 */ getzIndex(): number; /** 设置标注层叠加顺序 */ setzIndex(zIndex: number): void; /** 获取标注层显示层级范围 */ getZooms(): [number, number]; /** 设置标注层显示层级范围 */ setZooms(zooms: [number, number]): void; // ^^^^^^^^ 上面公共部分 ^^^^^^^^ getOptions(): CustomLayerOption; setMap(map: Map): void; } /** * 灵活切片图层,继承自AMap.TileLayer,开发者可通过构造时传入给其传入createTile字段来指定每一个切片的内容[相关示例](https://lbs.amap.com/api/jsapi-v2/example/selflayer/flex-canvas/) */ class Flexible extends MapEventListener<'complete'> { constructor(opts: FlexibleLayerOptions); /** 获取标注层透明度 */ getOpacity(): number; /** 设置标注层透明度 */ setOpacity(opacity: boolean): void; /** 获取标注层叠加顺序 */ getzIndex(): number; /** 设置标注层叠加顺序 */ setzIndex(zIndex: number): void; /** 获取标注层显示层级范围 */ getZooms(): [number, number]; /** 设置标注层显示层级范围 */ setZooms(zooms: [number, number]): void; // ^^^^^^^^ 上面公共部分 ^^^^^^^^ getOptions(): any; destroy(): void; } interface FlexibleLayerOptions { /** 缓存瓦片数量 */ cacheSize?: Number; /** 由开发者实现,由API自动调用,xyz分别为切片横向纵向编号和层级,切片大小 256。假设每次创建的贴片为A(支持img或者canvas),当创建或者获取成功时请回调success(A),不需要显示或者失败时请回调fail() */ createTile?: (x: number, y: number, z: number, success: () => void, fail: () => void) => void; /** 支持的缩放级别范围,默认范围 [2-20] */ zooms?: [Number, Number]; /** 透明度,默认 1 */ opacity?: Number; /** 是否显示,默认 true */ visible?: Boolean; /** 图层叠加的顺序值,1 表示最底层。默认 zIndex:4 */ zIndex?: Number; /** * 切片大小,默认: 256 取值: * - 256,表示切片大小为256 256, * -128,表示切片大小为128 128, * - 64,表示切片大小为64*64。默认值为256 */ tileSize?: Number; } interface CustomLayerOption extends Omit<LabelsLayerOptions, 'collision' | 'allowCollision'> { /** 绘制函数,初始化完成时候,开发者需要给该图层设定render方法,该方法需要实现图层的绘制,API会在合适的时机自动调用该方法 */ render?: () => void; } class ImageLayer extends MapEventListener<'complete'> { constructor(opts: ImageLayerOptions); /** 获取标注层透明度 */ getOpacity(): number; /** 设置标注层透明度 */ setOpacity(opacity: boolean): void; /** 获取标注层叠加顺序 */ getzIndex(): number; /** 设置标注层叠加顺序 */ setzIndex(zIndex: number): void; /** 获取标注层显示层级范围 */ getZooms(): [number, number]; /** 设置标注层显示层级范围 */ setZooms(zooms: [number, number]): void; // ^^^^^^^^ 上面公共部分 ^^^^^^^^ getOptions(): CustomLayerOption; getImageUrl(): string; setImageUrl(url: string): void; getBounds(): Bounds; setBounds(bounds: Bounds): void; } interface ImageLayerOptions extends Omit<CustomLayerOption, 'render'> { /** 图片地址链接 */ url?: string; /** 图片的范围大小经纬度,如果传递数字数组类型: [minlng,minlat,maxlng,maxlat] */ bounds?: [number, number, number, number] | Bounds; } /** * Canvas图层类,用户可以将一个 Canvas 作为图层添加在地图上,Canvas图层会随缩放级别而自适应缩放。[相关示例](https://lbs.amap.com/api/jsapi-v2/example/selflayer/canvaslayer) */ class CanvasLayer extends MapEventListener { constructor(opts: CanvasLayerOptions); } interface CanvasLayerOptions extends Omit<ImageLayerOptions, 'url'> { /** Canvas DOM 对象 */ canvas?: HTMLCanvasElement; } }
the_stack
import { BufferAttribute, BufferGeometry, ImmediateRenderObject, Material, Vector3 } from "three"; class MarchingCubes extends ImmediateRenderObject { public isovalue: number; public enableUvs: boolean; public enableColors: boolean; public enableNormals: boolean; public dirty: boolean; public resolution: [number, number, number]; public stepSizeX: number; public stepSizeY: number; public stepSizeZ: number; public sizeX: number; public sizeY: number; public sizeZ: number; public sizeXY: number; public sizeXYZ: number; public size3: number; public halfsizeX: number; public halfsizeY: number; public halfsizeZ: number; public deltaX: number; public deltaY: number; public deltaZ: number; public yd: number; public zd: number; public field: Uint8Array | Float32Array; public normal_cache: Float32Array; public maxCount = 16384; //4096; // TODO: find the fastest size for this buffer public count = 0; public hasPositions = false; public hasNormals = false; public hasColors = false; public hasUvs = false; public positionArray: Float32Array; public normalArray: Float32Array; public uvArray: Float32Array; public colorArray: Float32Array; private init: (res: [number, number, number], vol: Uint8Array) => void; private begin: () => void; private end: (renderCallback: (mc: MarchingCubes) => void) => void; private reset: () => void; public render: (renderCallback: (mc: MarchingCubes) => void) => void; public generateGeometry: () => BufferGeometry[] | undefined; constructor( resolution: [number, number, number], material: Material, enableUvs: boolean, enableColors: boolean, enableNormals: boolean, volumeFieldRef: Uint8Array ) { super(material); const scope = this; // basic default init; these should be reset later. //this.position = new Vector3(); //this.scale = new Vector3(1, 1, 1); this.isovalue = 0; // temp buffers used in polygonize const vlist = new Float32Array(12 * 3); const nlist = new Float32Array(12 * 3); this.enableUvs = !!enableUvs; this.enableColors = !!enableColors; this.enableNormals = !!enableNormals; this.dirty = true; this.resolution = [0, 0, 0]; this.stepSizeX = 0; this.stepSizeY = 0; this.stepSizeZ = 0; this.sizeX = 0; this.sizeY = 0; this.sizeZ = 0; this.sizeXY = 0; this.sizeXYZ = 0; this.size3 = 0; this.halfsizeX = 0; this.halfsizeY = 0; this.halfsizeZ = 0; this.deltaX = 0; this.deltaY = 0; this.deltaZ = 0; this.yd = 0; this.zd = 0; this.field = new Uint8Array(); this.normal_cache = new Float32Array(); this.positionArray = new Float32Array(); this.normalArray = new Float32Array(); this.uvArray = new Float32Array(); this.colorArray = new Float32Array(); // functions have to be object properties // prototype functions kill performance // (tested and it was 4x slower !!!) this.init = function (resolution: [number, number, number], volumeFieldRef: Uint8Array) { this.dirty = true; this.resolution = resolution; // parameters this.isovalue = 0.05; this.stepSizeX = 1; this.stepSizeY = 1; this.stepSizeZ = 1; // size of field, 32 is pushing it in Javascript :) this.sizeX = resolution[0]; this.sizeY = resolution[1]; this.sizeZ = resolution[2]; this.sizeXY = this.sizeX * this.sizeY; this.sizeXYZ = this.sizeXY * this.sizeZ; this.size3 = this.sizeXYZ; this.halfsizeX = this.sizeX / 2.0; this.halfsizeY = this.sizeY / 2.0; this.halfsizeZ = this.sizeZ / 2.0; // deltas this.deltaX = 2.0 / this.sizeX; this.deltaY = 2.0 / this.sizeY; this.deltaZ = 2.0 / this.sizeZ; this.yd = this.sizeX; this.zd = this.sizeXY; if (volumeFieldRef) { this.field = volumeFieldRef; } else { this.field = new Float32Array(this.size3); } this.normal_cache = new Float32Array(this.size3 * 3); // immediate render mode simulator this.maxCount = 16384; //4096; // TODO: find the fastest size for this buffer this.count = 0; this.hasPositions = false; this.hasNormals = false; this.hasColors = false; this.hasUvs = false; this.positionArray = new Float32Array(this.maxCount * 3); if (this.enableNormals) { this.normalArray = new Float32Array(this.maxCount * 3); } if (this.enableUvs) { this.uvArray = new Float32Array(this.maxCount * 2); } if (this.enableColors) { this.colorArray = new Float32Array(this.maxCount * 3); } }; /////////////////////// // Polygonization /////////////////////// function lerp(a, b, t) { return a + (b - a) * t; } function VIntX(q, offset, isol, x, y, z, valp1, valp2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x + mu * scope.deltaX * scope.stepSizeX; vlist[offset + 1] = y; vlist[offset + 2] = z; nlist[offset + 0] = lerp(nc[q + 0], nc[q + 3], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q + 4], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q + 5], mu); } function VIntY(q, offset, isol, x, y, z, valp1, valp2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x; vlist[offset + 1] = y + mu * scope.deltaY * scope.stepSizeY; vlist[offset + 2] = z; const q2 = q + scope.yd * 3; nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); } function VIntZ(q, offset, isol, x, y, z, valp1, valp2) { const mu = (isol - valp1) / (valp2 - valp1), nc = scope.normal_cache; vlist[offset + 0] = x; vlist[offset + 1] = y; vlist[offset + 2] = z + mu * scope.deltaZ * scope.stepSizeZ; const q2 = q + scope.zd * 3; nlist[offset + 0] = lerp(nc[q + 0], nc[q2 + 0], mu); nlist[offset + 1] = lerp(nc[q + 1], nc[q2 + 1], mu); nlist[offset + 2] = lerp(nc[q + 2], nc[q2 + 2], mu); } function compNorm(q) { const q3 = q * 3; if (scope.normal_cache[q3] === 0.0) { scope.normal_cache[q3 + 0] = scope.field[q - 1 * scope.stepSizeX] - scope.field[q + 1 * scope.stepSizeX]; scope.normal_cache[q3 + 1] = scope.field[q - scope.yd * scope.stepSizeY] - scope.field[q + scope.yd * scope.stepSizeY]; scope.normal_cache[q3 + 2] = scope.field[q - scope.zd * scope.stepSizeZ] - scope.field[q + scope.zd * scope.stepSizeZ]; } } // Returns total number of triangles. Fills triangles. // (this is where most of time is spent - it's inner work of O(n3) loop ) function polygonize(fx, fy, fz, q, isol, renderCallback) { // cache indices const q1 = q + 1 * scope.stepSizeX, qy = q + scope.yd * scope.stepSizeY, qz = q + scope.zd * scope.stepSizeZ, q1y = q1 + scope.yd * scope.stepSizeY, q1z = q1 + scope.zd * scope.stepSizeZ, qyz = q + scope.yd * scope.stepSizeY + scope.zd * scope.stepSizeZ, q1yz = q1 + scope.yd * scope.stepSizeY + scope.zd * scope.stepSizeZ; let cubeindex = 0; const field0 = scope.field[q], field1 = scope.field[q1], field2 = scope.field[qy], field3 = scope.field[q1y], field4 = scope.field[qz], field5 = scope.field[q1z], field6 = scope.field[qyz], field7 = scope.field[q1yz]; if (field0 < isol) cubeindex |= 1; if (field1 < isol) cubeindex |= 2; if (field2 < isol) cubeindex |= 8; if (field3 < isol) cubeindex |= 4; if (field4 < isol) cubeindex |= 16; if (field5 < isol) cubeindex |= 32; if (field6 < isol) cubeindex |= 128; if (field7 < isol) cubeindex |= 64; // if cube is entirely in/out of the surface - bail, nothing to draw const bits = edgeTable[cubeindex]; if (bits === 0) return 0; const dx = scope.deltaX * scope.stepSizeX, dy = scope.deltaY * scope.stepSizeY, dz = scope.deltaZ * scope.stepSizeZ, fx2 = fx + dx, fy2 = fy + dy, fz2 = fz + dz; // top of the cube if (bits & 1) { compNorm(q); compNorm(q1); VIntX(q * 3, 0, isol, fx, fy, fz, field0, field1); } if (bits & 2) { compNorm(q1); compNorm(q1y); VIntY(q1 * 3, 3, isol, fx2, fy, fz, field1, field3); } if (bits & 4) { compNorm(qy); compNorm(q1y); VIntX(qy * 3, 6, isol, fx, fy2, fz, field2, field3); } if (bits & 8) { compNorm(q); compNorm(qy); VIntY(q * 3, 9, isol, fx, fy, fz, field0, field2); } // bottom of the cube if (bits & 16) { compNorm(qz); compNorm(q1z); VIntX(qz * 3, 12, isol, fx, fy, fz2, field4, field5); } if (bits & 32) { compNorm(q1z); compNorm(q1yz); VIntY(q1z * 3, 15, isol, fx2, fy, fz2, field5, field7); } if (bits & 64) { compNorm(qyz); compNorm(q1yz); VIntX(qyz * 3, 18, isol, fx, fy2, fz2, field6, field7); } if (bits & 128) { compNorm(qz); compNorm(qyz); VIntY(qz * 3, 21, isol, fx, fy, fz2, field4, field6); } // vertical lines of the cube if (bits & 256) { compNorm(q); compNorm(qz); VIntZ(q * 3, 24, isol, fx, fy, fz, field0, field4); } if (bits & 512) { compNorm(q1); compNorm(q1z); VIntZ(q1 * 3, 27, isol, fx2, fy, fz, field1, field5); } if (bits & 1024) { compNorm(q1y); compNorm(q1yz); VIntZ(q1y * 3, 30, isol, fx2, fy2, fz, field3, field7); } if (bits & 2048) { compNorm(qy); compNorm(qyz); VIntZ(qy * 3, 33, isol, fx, fy2, fz, field2, field6); } cubeindex <<= 4; // re-purpose cubeindex into an offset into triTable let o1, o2, o3, numtris = 0, i = 0; // here is where triangles are created while (triTable[cubeindex + i] != -1) { o1 = cubeindex + i; o2 = o1 + 1; o3 = o1 + 2; posnormtriv(vlist, nlist, 3 * triTable[o1], 3 * triTable[o2], 3 * triTable[o3], renderCallback); i += 3; numtris++; } return numtris; } ///////////////////////////////////// // Immediate render mode simulator ///////////////////////////////////// function posnormtriv(pos, norm, o1, o2, o3, renderCallback) { const c = scope.count * 3; // positions scope.positionArray[c + 0] = pos[o1]; scope.positionArray[c + 1] = pos[o1 + 1]; scope.positionArray[c + 2] = pos[o1 + 2]; scope.positionArray[c + 3] = pos[o2]; scope.positionArray[c + 4] = pos[o2 + 1]; scope.positionArray[c + 5] = pos[o2 + 2]; scope.positionArray[c + 6] = pos[o3]; scope.positionArray[c + 7] = pos[o3 + 1]; scope.positionArray[c + 8] = pos[o3 + 2]; // normals if (scope.enableNormals) { scope.normalArray[c + 0] = norm[o1]; scope.normalArray[c + 1] = norm[o1 + 1]; scope.normalArray[c + 2] = norm[o1 + 2]; scope.normalArray[c + 3] = norm[o2]; scope.normalArray[c + 4] = norm[o2 + 1]; scope.normalArray[c + 5] = norm[o2 + 2]; scope.normalArray[c + 6] = norm[o3]; scope.normalArray[c + 7] = norm[o3 + 1]; scope.normalArray[c + 8] = norm[o3 + 2]; } // uvs if (scope.enableUvs) { const d = scope.count * 2; scope.uvArray[d + 0] = pos[o1]; scope.uvArray[d + 1] = pos[o1 + 2]; scope.uvArray[d + 2] = pos[o2]; scope.uvArray[d + 3] = pos[o2 + 2]; scope.uvArray[d + 4] = pos[o3]; scope.uvArray[d + 5] = pos[o3 + 2]; } // colors if (scope.enableColors) { scope.colorArray[c + 0] = pos[o1]; scope.colorArray[c + 1] = pos[o1 + 1]; scope.colorArray[c + 2] = pos[o1 + 2]; scope.colorArray[c + 3] = pos[o2]; scope.colorArray[c + 4] = pos[o2 + 1]; scope.colorArray[c + 5] = pos[o2 + 2]; scope.colorArray[c + 6] = pos[o3]; scope.colorArray[c + 7] = pos[o3 + 1]; scope.colorArray[c + 8] = pos[o3 + 2]; } scope.count += 3; if (scope.count >= scope.maxCount - 3) { scope.hasPositions = true; if (scope.enableNormals) { scope.hasNormals = true; } if (scope.enableUvs) { scope.hasUvs = true; } if (scope.enableColors) { scope.hasColors = true; } renderCallback(scope); } } this.begin = function () { this.count = 0; this.hasPositions = false; this.hasNormals = false; this.hasUvs = false; this.hasColors = false; }; this.end = function (renderCallback) { if (this.count === 0) return; for (let i = this.count * 3; i < this.positionArray.length; i++) { this.positionArray[i] = 0.0; } this.hasPositions = true; if (this.enableNormals) { this.hasNormals = true; } if (this.enableUvs) { this.hasUvs = true; } if (this.enableColors) { this.hasColors = true; } renderCallback(this); }; ///////////////////////////////////// // Updates ///////////////////////////////////// this.reset = function () { var i; // wipe the normal cache for (i = 0; i < this.size3; i++) { this.normal_cache[i * 3] = 0.0; this.field[i] = 0.0; } }; this.render = function (renderCallback) { if (!this.dirty) { this.end(renderCallback); return; } this.begin(); // Triangulate. Yeah, this is slow. const smin2x = this.sizeX - 2; const smin2y = this.sizeY - 2; const smin2z = this.sizeZ - 2; for (let z = 1; z < smin2z; z += this.stepSizeZ) { const z_offset = this.sizeXY * z; const fz = (z - this.halfsizeZ) / this.halfsizeZ; //+ 1 for (let y = 1; y < smin2y; y += this.stepSizeY) { const y_offset = z_offset + this.sizeX * y; const fy = (y - this.halfsizeY) / this.halfsizeY; //+ 1 for (let x = 1; x < smin2x; x += this.stepSizeX) { const fx = (x - this.halfsizeX) / this.halfsizeX; //+ 1 const q = y_offset + x; polygonize(fx, fy, fz, q, this.isovalue, renderCallback); } } } this.end(renderCallback); }; this.generateGeometry = function () { if (!this.dirty) { return; } let start = 0; const geoparent: BufferGeometry[] = []; //var normals = []; const geo_callback = function (object) { const geo = new BufferGeometry(); geo.setAttribute("position", new BufferAttribute(object.positionArray.slice(), 3)); if (object.enableNormals) { geo.setAttribute("normal", new BufferAttribute(object.normalArray.slice(), 3)); } // for ( var i = 0; i < object.count; i ++ ) { // // var vertex = new Vector3().fromArray( object.positionArray, i * 3 ); // var normal = new Vector3().fromArray( object.normalArray, i * 3 ); // // geo.vertices.push( vertex ); // normals.push( normal ); // // } const inds = new Uint16Array(object.count); const nfaces = object.count / 3; for (let i = 0; i < nfaces; i++) { const a = /* start + */ i * 3; const b = a + 1; const c = a + 2; inds[i * 3 + 0] = a; inds[i * 3 + 1] = b; inds[i * 3 + 2] = c; // var na = normals[ a ]; // var nb = normals[ b ]; // var nc = normals[ c ]; // // var face = new Face3( a, b, c, [ na, nb, nc ] ); // geo.faces.push( face ); } geo.setIndex(new BufferAttribute(inds, 1)); geoparent.push(geo); start += nfaces; object.count = 0; }; this.render(geo_callback); // console.log( "generated " + geo.faces.length + " triangles" ); this.dirty = false; return geoparent; }; this.init(resolution, volumeFieldRef); } } ///////////////////////////////////// // Marching cubes lookup tables ///////////////////////////////////// // These tables are straight from Paul Bourke's page: // http://local.wasp.uwa.edu.au/~pbourke/geometry/polygonise/ // who in turn got them from Cory Gene Bloyd. const edgeTable = new Int32Array([ 0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0, ]); const triTable = new Int32Array([ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1, 3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1, 3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1, 9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, 9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1, 8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1, 3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1, 1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1, 4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1, 4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1, 2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1, 9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1, 0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, 2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1, 10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1, 5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1, 5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1, 0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1, 1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1, 8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1, 2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, 7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, 9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1, 2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1, 11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1, 9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1, 5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1, 11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1, 11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1, 9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1, 5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1, 2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1, 6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1, 3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1, 6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, 10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1, 6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, 1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1, 8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1, 7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1, 3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, 5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1, 0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, 9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1, 8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1, 5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1, 0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1, 6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1, 10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, 10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1, 8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1, 1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1, 0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, 10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1, 0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1, 3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1, 6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1, 9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1, 8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1, 3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1, 6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1, 10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1, 10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1, 1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1, 7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1, 7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1, 2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1, 1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1, 11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1, 8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1, 0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1, 7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1, 7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1, 2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1, 1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1, 10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1, 10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1, 0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1, 7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1, 6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1, 9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1, 6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1, 4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1, 10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1, 8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, 0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1, 1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1, 8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1, 10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1, 4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1, 10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, 5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1, 9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, 6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1, 7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1, 3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1, 7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1, 9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1, 3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1, 6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1, 9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1, 1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1, 4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1, 7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1, 6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1, 3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1, 0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1, 6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1, 0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1, 11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1, 6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1, 5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1, 9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1, 1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1, 1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1, 10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1, 0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1, 5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1, 10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1, 11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1, 9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1, 7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1, 2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, 8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1, 9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1, 9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1, 1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1, 9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1, 9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, 5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1, 0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1, 10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1, 2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1, 0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1, 0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1, 9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1, 5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1, 3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1, 5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1, 0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1, 9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1, 0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1, 1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1, 3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1, 4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1, 9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1, 11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1, 11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1, 2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1, 9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1, 3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1, 1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1, 4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1, 4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1, 0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1, 3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1, 3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1, 0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1, 9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1, 1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ]); export { MarchingCubes, edgeTable, triTable }; export default MarchingCubes;
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_problematicasset_Information { interface tab_tab_2_Sections { tab_2_section_1: DevKit.Controls.Section; } interface tab_tab_2 extends DevKit.Controls.ITab { Section: tab_tab_2_Sections; } interface Tabs { tab_2: tab_tab_2; } interface Body { Tab: Tabs; /** Lookup field for customer asset */ msdyn_Asset: DevKit.Controls.Lookup; /** Unique identifier of customer asset */ msdyn_AssetId: DevKit.Controls.String; /** Probability of predicting customer asset to be problematic in current date */ msdyn_Confidence: DevKit.Controls.Double; /** The name of the custom entity. */ msdyn_Name: DevKit.Controls.String; /** The option set value indicating how many days the record is preficted from current */ msdyn_NumberofDays: DevKit.Controls.OptionSet; /** Probability of customer asset to be problematic asset */ msdyn_Score: DevKit.Controls.Double; /** Optionset value of suggestions for customer asset */ msdyn_Suggestion: DevKit.Controls.OptionSet; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_problematicasset_msdyn_customerasset_ProblematicAsset: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem } } class Formmsdyn_problematicasset_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_problematicasset_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_problematicasset_Information */ Body: DevKit.Formmsdyn_problematicasset_Information.Body; /** The Navigation of form msdyn_problematicasset_Information */ Navigation: DevKit.Formmsdyn_problematicasset_Information.Navigation; } class msdyn_problematicassetApi { /** * DynamicsCrm.DevKit msdyn_problematicassetApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Lookup field for customer asset */ msdyn_Asset: DevKit.WebApi.LookupValue; /** Unique identifier of customer asset */ msdyn_AssetId: DevKit.WebApi.StringValue; /** Value of breakfix cost for customer asset */ msdyn_BreakfixCost: DevKit.WebApi.MoneyValue; /** Value of the Breakfix Cost in base currency. */ msdyn_breakfixcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Value of breakfix sale of customer asset */ msdyn_BreakfixSale: DevKit.WebApi.MoneyValue; /** Value of the Breakfix Sale in base currency. */ msdyn_breakfixsale_Base: DevKit.WebApi.MoneyValueReadonly; /** Expected break/fix work order count for customer asset */ msdyn_BreakfixWorkOrderCount: DevKit.WebApi.IntegerValue; /** Probability of predicting customer asset to be problematic in current date */ msdyn_Confidence: DevKit.WebApi.DoubleValue; /** Flag value indicating if customer asset has higher total cost than similar assets or not */ msdyn_HigherTotalCost: DevKit.WebApi.OptionSetValue; /** Flag value indicating if customer asset work order count is higher than similar assets or not */ msdyn_HigherWorkOrderCount: DevKit.WebApi.OptionSetValue; /** Value of maintenance cost of customer asset */ msdyn_MaintenanceCost: DevKit.WebApi.MoneyValue; /** Value of the Maintenance Cost in base currency. */ msdyn_maintenancecost_Base: DevKit.WebApi.MoneyValueReadonly; /** Value of maintenance sale of customer asset */ msdyn_MaintenanceSale: DevKit.WebApi.MoneyValue; /** Value of the Maintenance Sale in base currency. */ msdyn_maintenancesale_Base: DevKit.WebApi.MoneyValueReadonly; /** Expected maintenance work order count from model output */ msdyn_MaintenanceWorkOrderCount: DevKit.WebApi.IntegerValue; /** The name of the custom entity. */ msdyn_Name: DevKit.WebApi.StringValue; /** The option set value indicating how many days the record is preficted from current */ msdyn_NumberofDays: DevKit.WebApi.OptionSetValue; /** Unique identifier for entity instances */ msdyn_problematicassetId: DevKit.WebApi.GuidValue; /** Value of replacement cost of customer asset */ msdyn_ReplacementCost: DevKit.WebApi.MoneyValue; /** Value of the Replacement Cost in base currency. */ msdyn_replacementcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Value of replacement sale of customer asset */ msdyn_ReplacementSale: DevKit.WebApi.MoneyValue; /** Value of the Replacement Sale in base currency. */ msdyn_replacementsale_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier of model run id */ msdyn_RunId: DevKit.WebApi.StringValue; /** Probability of customer asset to be problematic asset */ msdyn_Score: DevKit.WebApi.DoubleValue; /** Optionset value of suggestions for customer asset */ msdyn_Suggestion: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Problematic Asset */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Problematic Asset */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_problematicasset { enum msdyn_HigherTotalCost { /** 0 */ No, /** 1 */ Yes } enum msdyn_HigherWorkOrderCount { /** 0 */ No, /** 1 */ Yes } enum msdyn_NumberofDays { /** 192350000 */ _0, /** 192350001 */ _15, /** 192350002 */ _30, /** 192350003 */ _60, /** 192350004 */ _90 } enum msdyn_Suggestion { /** 192350002 */ None, /** 192350000 */ Repair, /** 192350001 */ Replace } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
export interface Cache { /** Defines which files or directories to cache. */ readonly paths?: string[]; /** Used the to give each cache a unique identifying key. All jobs that use the same cache key use the same cache. */ readonly key?: string | CacheKeyFiles; /** If set to true all files that are untracked in your Git repository will be cached. */ readonly untracked?: boolean; /** Defines the upload and download behaviour of the cache. */ readonly policy?: CachePolicy; /** Defines when to save the cache, based on the status of the job (Default: Job Success). */ readonly when?: CacheWhen; } /** * Use this construct to generate a new key when one or two specific files change. * @see https://docs.gitlab.com/ee/ci/yaml/#cachekeyfiles */ export interface CacheKeyFiles { /** The files that are checked against. If the SHA checksum changes, the cache becomes invalid. */ readonly files: string[]; /** Adds a custom prefix to the checksums computed. */ readonly prefix?: string; } /** * Configure the upload and download behaviour of a cache. * @see https://docs.gitlab.com/ee/ci/yaml/#cachepolicy */ export enum CachePolicy { /** Only download the cache when the job starts, but never upload changes when the job finishes. */ PULL = "pull", /** Only upload a cache when the job finishes, but never download the cache when the job starts. */ PUSH = "push", /** The job downloads the cache when the job starts, and uploads changes to the cache when the job ends. */ PULL_PUSH = "pull-push", } /** * Configure when artifacts are uploaded depended on job status. * @see https://docs.gitlab.com/ee/ci/yaml/#cachewhen */ export enum CacheWhen { /** Upload artifacts regardless of job status. */ ALWAYS = "always", /** Upload artifacts only when the job fails. */ ON_FAILURE = "on_failure", /** Upload artifacts only when the job succeeds (this is the default). */ ON_SUCCESS = "on_success", } /** * Default settings for the CI Configuration. Jobs that do not define one or more of the listed keywords use the value defined in the default section. * @see https://docs.gitlab.com/ee/ci/yaml/#default */ export interface Default { /* Defines scripts that should run *after* all jobs. Can be overriden by the job level `afterScript. */ readonly afterScript?: string[]; /* List of files and directories that should be attached to the job if it succeeds. Artifacts are sent to Gitlab where they can be downloaded. */ readonly artifacts?: Artifacts; /* Defines scripts that should run *before* all jobs. Can be overriden by the job level `afterScript`. */ readonly beforeScript?: string[]; /* A list of files and directories to cache between jobs. You can only use paths that are in the local working copy. */ readonly cache?: Cache; /* Specifies the default docker image to use globally for all jobs. */ readonly image?: Image; /* If a job should be canceled when a newer pipeline starts before the job completes (Default: false).*/ readonly interruptible?: boolean; /* How many times a job is retried if it fails. If not defined, defaults to 0 and jobs do not retry. */ readonly retry?: Retry; /* Additional Docker images to run scripts in. The service image is linked to the image specified in the image parameter. */ readonly services?: Service[]; /* Used to select a specific runner from the list of all runners that are available for the project. */ readonly tags?: string[]; /* A default timeout job written in natural language (Ex. one hour, 3600 seconds, 60 minutes). */ readonly timeout?: string; } /** * Used to specify a list of files and directories that should be attached to the job if it * succeeds. Artifacts are sent to Gitlab where they can be downloaded. * @see https://docs.gitlab.com/ee/ci/yaml/#artifacts */ export interface Artifacts { /** A list of paths to files/folders that should be excluded in the artifact. */ readonly exclude?: string[]; /** How long artifacts should be kept. They are saved 30 days by default. Artifacts that have expired are removed periodically via cron job. Supports a wide variety of formats, e.g. '1 week', '3 mins 4 sec', '2 hrs 20 min', '2h20min', '6 mos 1 day', '47 yrs 6 mos and 4d', '3 weeks and 2 days'. */ readonly expireIn?: string; /** Can be used to expose job artifacts in the merge request UI. GitLab will add a link <expose_as> to the relevant merge request that points to the artifact. */ readonly exposeAs?: string; /** Name for the archive created on job success. Can use variables in the name, e.g. '$CI_JOB_NAME' */ readonly name?: string; /** A list of paths to files/folders that should be included in the artifact. */ readonly paths?: string[]; /** Reports will be uploaded as artifacts, and often displayed in the Gitlab UI, such as in Merge Requests.*/ readonly reports?: Reports; /** Whether to add all untracked files (along with 'artifacts.paths') to the artifact.*/ readonly untracked?: boolean; /** Configure when artifacts are uploaded depended on job status.*/ readonly when?: CacheWhen; } /** * Reports will be uploaded as artifacts, and often displayed in the Gitlab UI, such as in * Merge Requests. * @see https://docs.gitlab.com/ee/ci/yaml/#artifactsreports */ export interface Reports { /** Path for file(s) that should be parsed as Cobertura XML coverage report*/ readonly cobertura?: string[]; /** Path to file or list of files with code quality report(s) (such as Code Climate).*/ readonly codequality?: string[]; /** Path to file or list of files with Container scanning vulnerabilities report(s).*/ readonly containerScanning?: string[]; /** Path to file or list of files with DAST vulnerabilities report(s).*/ readonly dast?: string[]; /** Path to file or list of files with Dependency scanning vulnerabilities report(s).*/ readonly dependencyScanning?: string[]; /** Path to file or list of files containing runtime-created variables for this job.*/ readonly dotenv?: string[]; /** Path for file(s) that should be parsed as JUnit XML result*/ readonly junit?: string[]; /** Deprecated in 12.8: Path to file or list of files with license report(s).*/ readonly licenseManagement?: string[]; /** Path to file or list of files with license report(s).*/ readonly licenseScanning?: string[]; /** Path to file or list of files containing code intelligence (Language Server Index Format).*/ readonly lsif?: string[]; /** Path to file or list of files with custom metrics report(s).*/ readonly metrics?: string[]; /** Path to file or list of files with performance metrics report(s).*/ readonly performance?: string[]; /** Path to file or list of files with requirements report(s).*/ readonly requirements?: string[]; /** Path to file or list of files with SAST vulnerabilities report(s).*/ readonly sast?: string[]; /** Path to file or list of files with secret detection report(s).*/ readonly secretDetection?: string[]; /** Path to file or list of files with terraform plan(s).*/ readonly terraform?: string[]; } /** * Specifies the docker image to use for the job or globally for all jobs. Job configuration * takes precedence over global setting. Requires a certain kind of Gitlab runner executor. * @see https://docs.gitlab.com/ee/ci/yaml/#image */ export interface Image { /** Command or script that should be executed as the container's entrypoint. It will be translated to Docker's --entrypoint option while creating the container. The syntax is similar to Dockerfile's ENTRYPOINT directive, where each shell token is a separate string in the array.*/ readonly entrypoint?: any[]; /** Full name of the image that should be used. It should contain the Registry part if needed.*/ readonly name: string; } /** * How many times a job is retried if it fails. If not defined, defaults to 0 and jobs do not retry. * @see https://docs.gitlab.com/ee/ci/yaml/#retry */ export interface Retry { /** 0 (default), 1, or 2.*/ readonly max?: number; /** Either a single or array of error types to trigger job retry.*/ readonly when?: any; } /** * Used to specify an additional Docker image to run scripts in. The service image is linked to the image specified in the @Default image keyword. * @see https://docs.gitlab.com/ee/ci/yaml/#services */ export interface Service { /** Additional alias that can be used to access the service from the job's container. Read Accessing the services for more information.*/ readonly alias?: string; /** Command or script that should be used as the container's command. It will be translated to arguments passed to Docker after the image's name. The syntax is similar to Dockerfile's CMD directive, where each shell token is a separate string in the array.*/ readonly command?: string[]; /** Command or script that should be executed as the container's entrypoint. It will be translated to Docker's --entrypoint option while creating the container. The syntax is similar to Dockerfile's ENTRYPOINT directive, where each shell token is a separate string in the array.*/ readonly entrypoint?: string[]; /** Full name of the image that should be used. It should contain the Registry part if needed.*/ readonly name: string; } /** * An included YAML file. * @see https://docs.gitlab.com/ee/ci/yaml/#include */ export interface Include { /** Relative path from local repository root (`/`) to the `yaml`/`yml` file template. The file must be on the same branch, and does not work across git submodules.*/ readonly local?: string; /**Rules allows for an array of individual rule objects to be evaluated in order, until one matches and dynamically provides attributes to the job. */ readonly rules?: IncludeRule[]; /** Files from another private project on the same GitLab instance. You can use `file` in combination with `project` only. */ readonly file?: string[]; /** Path to the project, e.g. `group/project`, or `group/sub-group/project`.*/ readonly project?: string; /** Branch/Tag/Commit-hash for the target project.*/ readonly ref?: string; /** Use a `.gitlab-ci.yml` template as a base, e.g. `Nodejs.gitlab-ci.yml`.*/ readonly template?: string; /** URL to a `yaml`/`yml` template file using HTTP/HTTPS.*/ readonly remote?: string; } /** * Rules allows for an array of individual rule objects to be evaluated in order, until one * matches and dynamically provides attributes to the job. * @see https://docs.gitlab.com/ee/ci/yaml/includes.html#use-rules-with-include */ export interface IncludeRule { /* Whether a pipeline should continue running when a job fails. */ readonly allowFailure?: boolean | AllowFailure; /* Specify when to add a job to a pipeline by checking for changes to specific files. */ readonly changes?: string[]; /* Run a job when certain files exist in the repository. */ readonly exists?: string[]; /* Clauses to specify when to add a job to a pipeline.*/ readonly if?: string; /* Execute scripts after a waiting period written in natural language (Ex. one hour, 3600 seconds, 60 minutes). */ readonly startIn?: string; /* Use variables in rules to define variables for specific conditions. */ readonly variables?: Record<string, number | string>; /* Conditions for when to run the job. Defaults to 'on_success' */ readonly when?: JobWhen; } /** * Exit code that are not considered failure. The job fails for any other exit code. * You can list which exit codes are not considered failures. The job fails for any other * exit code. * @see https://docs.gitlab.com/ee/ci/yaml/#allow_failure */ export interface AllowFailure { readonly exitCodes: number[] | number; } /** * Describes the conditions for when to run the job. Defaults to 'on_success'. * @see https://docs.gitlab.com/ee/ci/yaml/#when */ export enum JobWhen { ALWAYS = "always", DELAYED = "delayed", MANUAL = "manual", NEVER = "never", ON_FAILURE = "on_failure", ON_SUCCESS = "on_success", } /** * Jobs are the most fundamental element of a .gitlab-ci.yml file. * @see https://docs.gitlab.com/ee/ci/jobs/ */ export interface Job { /* Defines scripts that should run *after* the job. */ readonly afterScript?: string[]; /** Whether to allow the pipeline to continue running on job failure (Default: false). */ readonly allowFailure?: boolean | AllowFailure; /* A list of files and directories that should be attached to the job if it succeeds. Artifacts are sent to Gitlab where they can be downloaded. */ readonly artifacts?: Artifacts; /* Defines scripts that should run *before* the job. */ readonly beforeScript?: string[]; /* A list of files and directories to cache between jobs. You can only use paths that are in the local working copy. */ readonly cache?: Cache; /** Must be a regular expression, optionally but recommended to be quoted, and must be surrounded with '/'. Example: '/Code coverage: \d+\.\d+/'*/ readonly coverage?: string; /** Specify a list of job names from earlier stages from which artifacts should be loaded. By default, all previous artifacts are passed. Use an empty array to skip downloading artifacts.*/ readonly dependencies?: string[]; /** Used to associate environment metadata with a deploy. Environment can have a name and URL attached to it, and will be displayed under /environments under the project.*/ readonly environment?: Environment | string; /** Job will run *except* for when these filtering options match.*/ readonly except?: string[] | Filter; /** The name of one or more jobs to inherit configuration from.*/ readonly extends?: string[]; /* Specifies the default docker image to used for the job. */ readonly image?: Image; /** Controls inheritance of globally-defined defaults and variables. Boolean values control inheritance of all default: or variables: keywords. To inherit only a subset of default: or variables: keywords, specify what you wish to inherit. Anything not listed is not inherited.*/ readonly inherit?: Inherit; /* If a job should be canceled when a newer pipeline starts before the job completes (Default: false).*/ readonly interruptible?: boolean; /** The list of jobs in previous stages whose sole completion is needed to start the current job.*/ readonly needs?: Array<Need | string>; /** Job will run *only* when these filtering options match.*/ readonly only?: string[] | Filter; /** Parallel will split up a single job into several, and provide `CI_NODE_INDEX` and `CI_NODE_TOTAL` environment variables for the running jobs.*/ readonly parallel?: Parallel | number; /** Indicates that the job creates a Release.*/ readonly release?: Release; /** Limit job concurrency. Can be used to ensure that the Runner will not run certain jobs simultaneously.*/ readonly resourceGroup?: string; /* How many times a job is retried if it fails. If not defined, defaults to 0 and jobs do not retry. */ readonly retry?: Retry; /**Rules allows for an array of individual rule objects to be evaluated in order, until one matches and dynamically provides attributes to the job. */ readonly rules?: IncludeRule[]; /** Shell scripts executed by the Runner. The only required property of jobs. Be careful with special characters (e.g. `:`, `{`, `}`, `&`) and use single or double quotes to avoid issues.*/ readonly script?: string[]; /** CI/CD secrets */ readonly secrets?: Record<string, Record<string, Secret>>; /* Additional Docker images to run scripts in. The service image is linked to the image specified in the image parameter. */ readonly services?: Service[]; /** Define what stage the job will run in.*/ readonly stage?: string; /* Execute scripts after a waiting period written in natural language (Ex. one hour, 3600 seconds, 60 minutes). */ readonly startIn?: string; /* Used to select a specific runner from the list of all runners that are available for the project. */ readonly tags?: string[]; /* A default timeout job written in natural language (Ex. one hour, 3600 seconds, 60 minutes). */ readonly timeout?: string; /** Trigger allows you to define downstream pipeline trigger. When a job created from trigger definition is started by GitLab, a downstream pipeline gets created. Read more: https://docs.gitlab.com/ee/ci/yaml/README.html#trigger*/ readonly trigger?: Trigger | string; /** Configurable values that are passed to the Job. */ readonly variables?: Record<string, number | string>; /** Describes the conditions for when to run the job. Defaults to 'on_success'. */ readonly when?: JobWhen; } /** * The environment that a job deploys to. */ export interface Environment { /** Specifies what this job will do. 'start' (default) indicates the job will start the deployment. 'prepare' indicates this will not affect the deployment. 'stop' indicates this will stop the deployment.*/ readonly action?: Action; /** The amount of time it should take before Gitlab will automatically stop the environment. Supports a wide variety of formats, e.g. '1 week', '3 mins 4 sec', '2 hrs 20 min', '2h20min', '6 mos 1 day', '47 yrs 6 mos and 4d', '3 weeks and 2 days'.*/ readonly autoStopIn?: string; /** Explicitly specifies the tier of the deployment environment if non-standard environment name is used.*/ readonly deploymentTier?: DeploymentTier; /** Used to configure the kubernetes deployment for this environment. This is currently not supported for kubernetes clusters that are managed by Gitlab.*/ readonly kubernetes?: KubernetesConfig; /** The name of the environment, e.g. 'qa', 'staging', 'production'.*/ readonly name: string; /** The name of a job to execute when the environment is about to be stopped.*/ readonly onStop?: string; /** When set, this will expose buttons in various places for the current environment in Gitlab, that will take you to the defined URL.*/ readonly url?: string; } /** * Specifies what this job will do. 'start' (default) indicates the job will start the * deployment. 'prepare' indicates this will not affect the deployment. 'stop' indicates * this will stop the deployment. */ export enum Action { PREPARE = "prepare", START = "start", STOP = "stop", } /** * Explicitly specifies the tier of the deployment environment if non-standard environment * name is used. */ export enum DeploymentTier { DEVELOPMENT = "development", OTHER = "other", PRODUCTION = "production", STAGING = "staging", TESTING = "testing", } /** * Used to configure the kubernetes deployment for this environment. This is currently not * supported for kubernetes clusters that are managed by Gitlab. */ export interface KubernetesConfig { /** The kubernetes namespace where this environment should be deployed to.*/ readonly namespace?: string; } /** * Filtering options for when a job will run. */ export interface Filter { /** Filter job creation based on files that were modified in a git push.*/ readonly changes?: string[]; /** Filter job based on if Kubernetes integration is active.*/ readonly kubernetes?: KubernetesEnum; /** Control when to add jobs to a pipeline based on branch names or pipeline types. */ readonly refs?: string[]; /** Filter job by checking comparing values of environment variables. Read more about variable expressions: https://docs.gitlab.com/ee/ci/variables/README.html#variables-expressions*/ readonly variables?: string[]; } /** * Filter job based on if Kubernetes integration is active. */ export enum KubernetesEnum { ACTIVE = "active", } /** * Controls inheritance of globally-defined defaults and variables. Boolean values control * inheritance of all default: or variables: keywords. To inherit only a subset of default: * or variables: keywords, specify what you wish to inherit. Anything not listed is not * inherited. */ export interface Inherit { /** Whether to inherit all globally-defined defaults or not. Or subset of inherited defaults*/ readonly default?: DefaultElement[] | boolean; /** Whether to inherit all globally-defined variables or not. Or subset of inherited variables*/ readonly variables?: string[] | boolean; } export enum DefaultElement { AFTER_SCRIPT = "after_script", ARTIFACTS = "artifacts", BEFORE_SCRIPT = "before_script", CACHE = "cache", IMAGE = "image", INTERRUPTIBLE = "interruptible", RETRY = "retry", SERVICES = "services", TAGS = "tags", TIMEOUT = "timeout", } /** * A jobs in a previous stage whose sole completion is needed to start the current job. */ export interface Need { readonly artifacts?: boolean; readonly job: string; readonly optional?: boolean; readonly pipeline?: string; readonly project?: string; readonly ref?: string; } /** * Used to run a job multiple times in parallel in a single pipeline. */ export interface Parallel { /** Defines different variables for jobs that are running in parallel.*/ readonly matrix: Record<string, any[]>[]; } /** * Indicates that the job creates a Release. */ export interface Release { readonly assets?: Assets; /** Specifies the longer description of the Release.*/ readonly description: string; /** The title of each milestone the release is associated with.*/ readonly milestones?: string[]; /** The Release name. If omitted, it is populated with the value of release: tag_name.*/ readonly name?: string; /** If the release: tag_name doesn’t exist yet, the release is created from ref. ref can be a commit SHA, another tag name, or a branch name.*/ readonly ref?: string; /** The date and time when the release is ready. Defaults to the current date and time if not defined. Should be enclosed in quotes and expressed in ISO 8601 format.*/ readonly releasedAt?: string; /** The tag_name must be specified. It can refer to an existing Git tag or can be specified by the user.*/ readonly tagName: string; } /** * Asset configuration for a release. */ export interface Assets { /** Include asset links in the release.*/ readonly links: Link[]; } /** * Link configuration for an asset. */ export interface Link { /** The redirect link to the url.*/ readonly filepath?: string; /** The content kind of what users can download via url.*/ readonly linkType?: LinkType; /** The name of the link.*/ readonly name: string; /** The URL to download a file.*/ readonly url: string; } /** * The content kind of what users can download via url. */ export enum LinkType { IMAGE = "image", OTHER = "other", PACKAGE = "package", RUNBOOK = "runbook", } /** * A CI/CD secret */ export interface Secret { /* Specification for a secret provided by a HashiCorp Vault. */ readonly vault: VaultConfig; } /** * Specification for a secret provided by a HashiCorp Vault. * @see https://www.vaultproject.io/ */ export interface VaultConfig { /* The engine configuration for a secret. */ readonly engine: Engine; /* The name of the field where the password is stored. */ readonly field: string; /** Path to the secret. */ readonly path: string; } /** * The engine configuration for a secret. */ export interface Engine { /** Name of the secrets engine. */ readonly name: string; /** Path to the secrets engine. */ readonly path: string; } /** * Trigger a multi-project or a child pipeline. Read more: * @see https://docs.gitlab.com/ee/ci/yaml/README.html#simple-trigger-syntax-for-multi-project-pipelines * @see https://docs.gitlab.com/ee/ci/yaml/README.html#trigger-syntax-for-child-pipeline */ export interface Trigger { /** The branch name that a downstream pipeline will use*/ readonly branch?: string; /** Path to the project, e.g. `group/project`, or `group/sub-group/project`.*/ readonly project?: string; /** You can mirror the pipeline status from the triggered pipeline to the source bridge job by using strategy: depend*/ readonly strategy?: Strategy; /** A list of local files or artifacts from other jobs to define the pipeline */ readonly include?: TriggerInclude[]; } /** * References a local file or an artifact from another job to define the pipeline * configuration. * @see https://docs.gitlab.com/ee/ci/yaml/#triggerinclude */ export interface TriggerInclude { /** Relative path from local repository root (`/`) to the local YAML file to define the pipeline configuration.*/ readonly local?: string; /** Name of the template YAML file to use in the pipeline configuration.*/ readonly template?: string; /** Relative path to the generated YAML file which is extracted from the artifacts and used as the configuration for triggering the child pipeline.*/ readonly artifact?: string; /** Job name which generates the artifact*/ readonly job?: string; /** Relative path from repository root (`/`) to the pipeline configuration YAML file.*/ readonly file?: string; /** Path to another private project under the same GitLab instance, like `group/project` or `group/sub-group/project`.*/ readonly project?: string; /** Branch/Tag/Commit hash for the target project.*/ readonly ref?: string; } /** * You can mirror the pipeline status from the triggered pipeline to the source bridge job * by using strategy: depend * @see https://docs.gitlab.com/ee/ci/yaml/#triggerstrategy */ export enum Strategy { DEPEND = "depend", } /** * Explains what the global variable is used for, what the acceptable values are. * @see https://docs.gitlab.com/ee/ci/yaml/#variables */ export interface VariableConfig { /** Define a global variable that is prefilled when running a pipeline manually. Must be used with value. */ readonly description?: string; /** The variable value. */ readonly value?: string; } /** * Used to control pipeline behavior. * @see https://docs.gitlab.com/ee/ci/yaml/#workflow */ export interface Workflow { /** Used to control whether or not a whole pipeline is created. */ readonly rules?: WorkflowRule[]; } /** * Used to control whether or not a whole pipeline is created. * @see https://docs.gitlab.com/ee/ci/yaml/#workflowrules */ export interface WorkflowRule { /* Specify when to add a job to a pipeline by checking for changes to specific files. */ readonly changes?: string[]; /* Run a job when certain files exist in the repository. */ readonly exists?: string[]; /* Clauses to specify when to add a job to a pipeline.*/ readonly if?: string; /* Use variables in rules to define variables for specific conditions. */ readonly variables?: Record<string, number | string>; /* Conditions for when to run the job. Defaults to 'on_success' */ readonly when?: JobWhen; } /** * Describes the conditions for when to run the job. Defaults to 'on_success'. * The value can only be 'always' or 'never' when used with workflow. * @see https://docs.gitlab.com/ee/ci/yaml/#workflowrules */ export enum WorkflowWhen { ALWAYS = "always", NEVER = "never", }
the_stack
import { ContractAddresses } from '@0x/contract-addresses'; import { Web3Wrapper } from '@0x/dev-utils'; import { RFQTIndicativeQuote } from '@0x/quote-server'; import { SignedOrder } from '@0x/types'; import { BigNumber, NULL_ADDRESS } from '@0x/utils'; import * as _ from 'lodash'; import { IS_PRICE_AWARE_RFQ_ENABLED } from '../../constants'; import { MarketOperation, Omit } from '../../types'; import { QuoteRequestor } from '../quote_requestor'; import { generateQuoteReport, QuoteReport } from './../quote_report_generator'; import { BUY_SOURCE_FILTER, COMPARISON_PRICE_DECIMALS, DEFAULT_GET_MARKET_ORDERS_OPTS, FEE_QUOTE_SOURCES, ONE_ETHER, SELL_SOURCE_FILTER, SOURCE_FLAGS, ZERO_AMOUNT, } from './constants'; import { createFills } from './fills'; import { getBestTwoHopQuote } from './multihop_utils'; import { createOrdersFromTwoHopSample, createSignedOrdersFromRfqtIndicativeQuotes, createSignedOrdersWithFillableAmounts, getNativeOrderTokens, } from './orders'; import { findOptimalPathAsync } from './path_optimizer'; import { DexOrderSampler, getSampleAmounts } from './sampler'; import { SourceFilters } from './source_filters'; import { AggregationError, CollapsedFill, DexSample, ERC20BridgeSource, GenerateOptimizedOrdersOpts, GetMarketOrdersOpts, MarketSideLiquidity, OptimizedMarketOrder, OptimizerResult, OptimizerResultWithReport, OrderDomain, TokenAdjacencyGraph, } from './types'; // tslint:disable:boolean-naming /** * Returns a indicative quotes or an empty array if RFQT is not enabled or requested * @param makerAssetData the maker asset data * @param takerAssetData the taker asset data * @param marketOperation Buy or Sell * @param assetFillAmount the amount to fill, in base units * @param opts market request options */ export async function getRfqtIndicativeQuotesAsync( makerAssetData: string, takerAssetData: string, marketOperation: MarketOperation, assetFillAmount: BigNumber, comparisonPrice: BigNumber | undefined, opts: Partial<GetMarketOrdersOpts>, ): Promise<RFQTIndicativeQuote[]> { if (opts.rfqt && opts.rfqt.isIndicative === true && opts.rfqt.quoteRequestor) { return opts.rfqt.quoteRequestor.requestRfqtIndicativeQuotesAsync( makerAssetData, takerAssetData, assetFillAmount, marketOperation, comparisonPrice, opts.rfqt, ); } else { return Promise.resolve<RFQTIndicativeQuote[]>([]); } } export class MarketOperationUtils { private readonly _wethAddress: string; private readonly _multiBridge: string; private readonly _sellSources: SourceFilters; private readonly _buySources: SourceFilters; private readonly _feeSources = new SourceFilters(FEE_QUOTE_SOURCES); private static _computeQuoteReport( nativeOrders: SignedOrder[], quoteRequestor: QuoteRequestor | undefined, marketSideLiquidity: MarketSideLiquidity, optimizerResult: OptimizerResult, ): QuoteReport { const { side, dexQuotes, twoHopQuotes, orderFillableAmounts } = marketSideLiquidity; const { liquidityDelivered } = optimizerResult; return generateQuoteReport( side, _.flatten(dexQuotes), twoHopQuotes, nativeOrders, orderFillableAmounts, liquidityDelivered, quoteRequestor, ); } constructor( private readonly _sampler: DexOrderSampler, private readonly contractAddresses: ContractAddresses, private readonly _orderDomain: OrderDomain, private readonly _liquidityProviderRegistry: string = NULL_ADDRESS, private readonly _tokenAdjacencyGraph: TokenAdjacencyGraph = {}, ) { this._wethAddress = contractAddresses.etherToken.toLowerCase(); this._multiBridge = contractAddresses.multiBridge.toLowerCase(); const optionalQuoteSources = []; if (this._liquidityProviderRegistry !== NULL_ADDRESS) { optionalQuoteSources.push(ERC20BridgeSource.LiquidityProvider); } if (this._multiBridge !== NULL_ADDRESS) { optionalQuoteSources.push(ERC20BridgeSource.MultiBridge); } this._buySources = BUY_SOURCE_FILTER.validate(optionalQuoteSources); this._sellSources = SELL_SOURCE_FILTER.validate(optionalQuoteSources); } /** * Gets the liquidity available for a market sell operation * @param nativeOrders Native orders. * @param takerAmount Amount of taker asset to sell. * @param opts Options object. * @return MarketSideLiquidity. */ public async getMarketSellLiquidityAsync( nativeOrders: SignedOrder[], takerAmount: BigNumber, opts?: Partial<GetMarketOrdersOpts>, ): Promise<MarketSideLiquidity> { if (nativeOrders.length === 0) { throw new Error(AggregationError.EmptyOrders); } const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts }; const [makerToken, takerToken] = getNativeOrderTokens(nativeOrders[0]); const sampleAmounts = getSampleAmounts(takerAmount, _opts.numSamples, _opts.sampleDistributionBase); const requestFilters = new SourceFilters().exclude(_opts.excludedSources).include(_opts.includedSources); const quoteSourceFilters = this._sellSources.merge(requestFilters); const feeSourceFilters = this._feeSources.exclude(_opts.excludedFeeSources); const { onChain: sampleBalancerOnChain, offChain: sampleBalancerOffChain, } = this._sampler.balancerPoolsCache.howToSampleBalancer( takerToken, makerToken, quoteSourceFilters.isAllowed(ERC20BridgeSource.Balancer), ); const { onChain: sampleCreamOnChain, offChain: sampleCreamOffChain, } = this._sampler.creamPoolsCache.howToSampleCream( takerToken, makerToken, quoteSourceFilters.isAllowed(ERC20BridgeSource.Cream), ); const offChainSources = [ ...(!sampleCreamOnChain ? [ERC20BridgeSource.Cream] : []), ...(!sampleBalancerOnChain ? [ERC20BridgeSource.Balancer] : []), ]; // Call the sampler contract. const samplerPromise = this._sampler.executeAsync( this._sampler.getTokenDecimals(makerToken, takerToken), // Get native order fillable amounts. this._sampler.getOrderFillableTakerAmounts(nativeOrders, this.contractAddresses.exchange), // Get ETH -> maker token price. this._sampler.getMedianSellRate( feeSourceFilters.sources, makerToken, this._wethAddress, ONE_ETHER, this._wethAddress, this._liquidityProviderRegistry, this._multiBridge, ), // Get ETH -> taker token price. this._sampler.getMedianSellRate( feeSourceFilters.sources, takerToken, this._wethAddress, ONE_ETHER, this._wethAddress, this._liquidityProviderRegistry, this._multiBridge, ), // Get sell quotes for taker -> maker. this._sampler.getSellQuotes( quoteSourceFilters.exclude(offChainSources).sources, makerToken, takerToken, sampleAmounts, this._wethAddress, this._liquidityProviderRegistry, this._multiBridge, ), this._sampler.getTwoHopSellQuotes( quoteSourceFilters.isAllowed(ERC20BridgeSource.MultiHop) ? quoteSourceFilters.sources : [], makerToken, takerToken, takerAmount, this._tokenAdjacencyGraph, this._wethAddress, this._liquidityProviderRegistry, ), ); const rfqtPromise = !IS_PRICE_AWARE_RFQ_ENABLED && quoteSourceFilters.isAllowed(ERC20BridgeSource.Native) ? getRfqtIndicativeQuotesAsync( nativeOrders[0].makerAssetData, nativeOrders[0].takerAssetData, MarketOperation.Sell, takerAmount, undefined, _opts, ) : Promise.resolve([]); const offChainBalancerPromise = sampleBalancerOffChain ? this._sampler.getBalancerSellQuotesOffChainAsync(makerToken, takerToken, sampleAmounts) : Promise.resolve([]); const offChainCreamPromise = sampleCreamOffChain ? this._sampler.getCreamSellQuotesOffChainAsync(makerToken, takerToken, sampleAmounts) : Promise.resolve([]); const offChainBancorPromise = quoteSourceFilters.isAllowed(ERC20BridgeSource.Bancor) ? this._sampler.getBancorSellQuotesOffChainAsync(makerToken, takerToken, [takerAmount]) : Promise.resolve([]); const [ [tokenDecimals, orderFillableAmounts, ethToMakerAssetRate, ethToTakerAssetRate, dexQuotes, twoHopQuotes], rfqtIndicativeQuotes, offChainBalancerQuotes, offChainCreamQuotes, offChainBancorQuotes, ] = await Promise.all([ samplerPromise, rfqtPromise, offChainBalancerPromise, offChainCreamPromise, offChainBancorPromise, ]); const [makerTokenDecimals, takerTokenDecimals] = tokenDecimals; return { side: MarketOperation.Sell, inputAmount: takerAmount, inputToken: takerToken, outputToken: makerToken, dexQuotes: dexQuotes.concat([...offChainBalancerQuotes, ...offChainCreamQuotes, offChainBancorQuotes]), nativeOrders, orderFillableAmounts, ethToOutputRate: ethToMakerAssetRate, ethToInputRate: ethToTakerAssetRate, rfqtIndicativeQuotes, twoHopQuotes, quoteSourceFilters, makerTokenDecimals: makerTokenDecimals.toNumber(), takerTokenDecimals: takerTokenDecimals.toNumber(), }; } /** * Gets the liquidity available for a market buy operation * @param nativeOrders Native orders. * @param makerAmount Amount of maker asset to buy. * @param opts Options object. * @return MarketSideLiquidity. */ public async getMarketBuyLiquidityAsync( nativeOrders: SignedOrder[], makerAmount: BigNumber, opts?: Partial<GetMarketOrdersOpts>, ): Promise<MarketSideLiquidity> { if (nativeOrders.length === 0) { throw new Error(AggregationError.EmptyOrders); } const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts }; const [makerToken, takerToken] = getNativeOrderTokens(nativeOrders[0]); const sampleAmounts = getSampleAmounts(makerAmount, _opts.numSamples, _opts.sampleDistributionBase); const requestFilters = new SourceFilters().exclude(_opts.excludedSources).include(_opts.includedSources); const quoteSourceFilters = this._buySources.merge(requestFilters); const feeSourceFilters = this._feeSources.exclude(_opts.excludedFeeSources); const { onChain: sampleBalancerOnChain, offChain: sampleBalancerOffChain, } = this._sampler.balancerPoolsCache.howToSampleBalancer( takerToken, makerToken, quoteSourceFilters.isAllowed(ERC20BridgeSource.Balancer), ); const { onChain: sampleCreamOnChain, offChain: sampleCreamOffChain, } = this._sampler.creamPoolsCache.howToSampleCream( takerToken, makerToken, quoteSourceFilters.isAllowed(ERC20BridgeSource.Cream), ); const offChainSources = [ ...(!sampleCreamOnChain ? [ERC20BridgeSource.Cream] : []), ...(!sampleBalancerOnChain ? [ERC20BridgeSource.Balancer] : []), ]; // Call the sampler contract. const samplerPromise = this._sampler.executeAsync( this._sampler.getTokenDecimals(makerToken, takerToken), // Get native order fillable amounts. this._sampler.getOrderFillableMakerAmounts(nativeOrders, this.contractAddresses.exchange), // Get ETH -> makerToken token price. this._sampler.getMedianSellRate( feeSourceFilters.sources, makerToken, this._wethAddress, ONE_ETHER, this._wethAddress, this._liquidityProviderRegistry, this._multiBridge, ), // Get ETH -> taker token price. this._sampler.getMedianSellRate( feeSourceFilters.sources, takerToken, this._wethAddress, ONE_ETHER, this._wethAddress, this._liquidityProviderRegistry, this._multiBridge, ), // Get buy quotes for taker -> maker. this._sampler.getBuyQuotes( quoteSourceFilters.exclude(offChainSources).sources, makerToken, takerToken, sampleAmounts, this._wethAddress, this._liquidityProviderRegistry, ), this._sampler.getTwoHopBuyQuotes( quoteSourceFilters.isAllowed(ERC20BridgeSource.MultiHop) ? quoteSourceFilters.sources : [], makerToken, takerToken, makerAmount, this._tokenAdjacencyGraph, this._wethAddress, this._liquidityProviderRegistry, ), ); const rfqtPromise = !IS_PRICE_AWARE_RFQ_ENABLED && quoteSourceFilters.isAllowed(ERC20BridgeSource.Native) ? getRfqtIndicativeQuotesAsync( nativeOrders[0].makerAssetData, nativeOrders[0].takerAssetData, MarketOperation.Buy, makerAmount, undefined, _opts, ) : Promise.resolve([]); const offChainBalancerPromise = sampleBalancerOffChain ? this._sampler.getBalancerBuyQuotesOffChainAsync(makerToken, takerToken, sampleAmounts) : Promise.resolve([]); const offChainCreamPromise = sampleCreamOffChain ? this._sampler.getCreamBuyQuotesOffChainAsync(makerToken, takerToken, sampleAmounts) : Promise.resolve([]); const [ [tokenDecimals, orderFillableAmounts, ethToMakerAssetRate, ethToTakerAssetRate, dexQuotes, twoHopQuotes], rfqtIndicativeQuotes, offChainBalancerQuotes, offChainCreamQuotes, ] = await Promise.all([samplerPromise, rfqtPromise, offChainBalancerPromise, offChainCreamPromise]); // Attach the MultiBridge address to the sample fillData (dexQuotes.find(quotes => quotes[0] && quotes[0].source === ERC20BridgeSource.MultiBridge) || []).forEach( q => (q.fillData = { poolAddress: this._multiBridge }), ); const [makerTokenDecimals, takerTokenDecimals] = tokenDecimals; return { side: MarketOperation.Buy, inputAmount: makerAmount, inputToken: makerToken, outputToken: takerToken, dexQuotes: dexQuotes.concat(offChainBalancerQuotes, offChainCreamQuotes), nativeOrders, orderFillableAmounts, ethToOutputRate: ethToTakerAssetRate, ethToInputRate: ethToMakerAssetRate, rfqtIndicativeQuotes, twoHopQuotes, quoteSourceFilters, makerTokenDecimals: makerTokenDecimals.toNumber(), takerTokenDecimals: takerTokenDecimals.toNumber(), }; } /** * gets the orders required for a market sell operation by (potentially) merging native orders with * generated bridge orders. * @param nativeOrders Native orders. * @param takerAmount Amount of taker asset to sell. * @param opts Options object. * @return object with optimized orders and a QuoteReport */ public async getMarketSellOrdersAsync( nativeOrders: SignedOrder[], takerAmount: BigNumber, opts?: Partial<GetMarketOrdersOpts>, ): Promise<OptimizerResultWithReport> { return this._getMarketSideOrdersAsync(nativeOrders, takerAmount, MarketOperation.Sell, opts); } /** * gets the orders required for a market buy operation by (potentially) merging native orders with * generated bridge orders. * @param nativeOrders Native orders. * @param makerAmount Amount of maker asset to buy. * @param opts Options object. * @return object with optimized orders and a QuoteReport */ public async getMarketBuyOrdersAsync( nativeOrders: SignedOrder[], makerAmount: BigNumber, opts?: Partial<GetMarketOrdersOpts>, ): Promise<OptimizerResultWithReport> { return this._getMarketSideOrdersAsync(nativeOrders, makerAmount, MarketOperation.Buy, opts); } /** * gets the orders required for a batch of market buy operations by (potentially) merging native orders with * generated bridge orders. * * NOTE: Currently `getBatchMarketBuyOrdersAsync()` does not support external liquidity providers. * * @param batchNativeOrders Batch of Native orders. * @param makerAmounts Array amount of maker asset to buy for each batch. * @param opts Options object. * @return orders. */ public async getBatchMarketBuyOrdersAsync( batchNativeOrders: SignedOrder[][], makerAmounts: BigNumber[], opts?: Partial<GetMarketOrdersOpts>, ): Promise<Array<OptimizedMarketOrder[] | undefined>> { if (batchNativeOrders.length === 0) { throw new Error(AggregationError.EmptyOrders); } const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts }; const requestFilters = new SourceFilters().exclude(_opts.excludedSources).include(_opts.includedSources); const quoteSourceFilters = this._buySources.merge(requestFilters); const feeSourceFilters = this._feeSources.exclude(_opts.excludedFeeSources); const ops = [ ...batchNativeOrders.map(orders => this._sampler.getOrderFillableMakerAmounts(orders, this.contractAddresses.exchange), ), ...batchNativeOrders.map(orders => this._sampler.getMedianSellRate( feeSourceFilters.sources, getNativeOrderTokens(orders[0])[1], this._wethAddress, ONE_ETHER, this._wethAddress, ), ), ...batchNativeOrders.map((orders, i) => this._sampler.getBuyQuotes( quoteSourceFilters.sources, getNativeOrderTokens(orders[0])[0], getNativeOrderTokens(orders[0])[1], [makerAmounts[i]], this._wethAddress, ), ), ]; const executeResults = await this._sampler.executeBatchAsync(ops); const batchOrderFillableAmounts = executeResults.splice(0, batchNativeOrders.length) as BigNumber[][]; const batchEthToTakerAssetRate = executeResults.splice(0, batchNativeOrders.length) as BigNumber[]; const batchDexQuotes = executeResults.splice(0, batchNativeOrders.length) as DexSample[][][]; const ethToInputRate = ZERO_AMOUNT; return Promise.all( batchNativeOrders.map(async (nativeOrders, i) => { if (nativeOrders.length === 0) { throw new Error(AggregationError.EmptyOrders); } const [makerToken, takerToken] = getNativeOrderTokens(nativeOrders[0]); const orderFillableAmounts = batchOrderFillableAmounts[i]; const ethToTakerAssetRate = batchEthToTakerAssetRate[i]; const dexQuotes = batchDexQuotes[i]; const makerAmount = makerAmounts[i]; try { const { optimizedOrders } = await this._generateOptimizedOrdersAsync( { side: MarketOperation.Buy, nativeOrders, orderFillableAmounts, dexQuotes, inputAmount: makerAmount, ethToOutputRate: ethToTakerAssetRate, ethToInputRate, rfqtIndicativeQuotes: [], inputToken: makerToken, outputToken: takerToken, twoHopQuotes: [], quoteSourceFilters, }, { bridgeSlippage: _opts.bridgeSlippage, maxFallbackSlippage: _opts.maxFallbackSlippage, excludedSources: _opts.excludedSources, feeSchedule: _opts.feeSchedule, allowFallback: _opts.allowFallback, }, ); return optimizedOrders; } catch (e) { // It's possible for one of the pairs to have no path // rather than throw NO_OPTIMAL_PATH we return undefined return undefined; } }), ); } public async _generateOptimizedOrdersAsync( marketSideLiquidity: Omit<MarketSideLiquidity, 'makerTokenDecimals' | 'takerTokenDecimals'>, opts: GenerateOptimizedOrdersOpts, ): Promise<OptimizerResult> { const { inputToken, outputToken, side, inputAmount, nativeOrders, orderFillableAmounts, rfqtIndicativeQuotes, dexQuotes, ethToOutputRate, ethToInputRate, } = marketSideLiquidity; const maxFallbackSlippage = opts.maxFallbackSlippage || 0; const orderOpts = { side, inputToken, outputToken, orderDomain: this._orderDomain, contractAddresses: this.contractAddresses, bridgeSlippage: opts.bridgeSlippage || 0, }; // Convert native orders and dex quotes into `Fill` objects. const fills = createFills({ side, // Augment native orders with their fillable amounts. orders: [ ...createSignedOrdersWithFillableAmounts(side, nativeOrders, orderFillableAmounts), ...createSignedOrdersFromRfqtIndicativeQuotes(rfqtIndicativeQuotes), ], dexQuotes, targetInput: inputAmount, ethToOutputRate, ethToInputRate, excludedSources: opts.excludedSources, feeSchedule: opts.feeSchedule, }); // Find the optimal path. const optimizerOpts = { ethToOutputRate, ethToInputRate, exchangeProxyOverhead: opts.exchangeProxyOverhead || (() => ZERO_AMOUNT), }; const optimalPath = await findOptimalPathAsync(side, fills, inputAmount, opts.runLimit, optimizerOpts); const optimalPathRate = optimalPath ? optimalPath.adjustedRate() : ZERO_AMOUNT; const { adjustedRate: bestTwoHopRate, quote: bestTwoHopQuote } = getBestTwoHopQuote( marketSideLiquidity, opts.feeSchedule, opts.exchangeProxyOverhead, ); if (bestTwoHopQuote && bestTwoHopRate.isGreaterThan(optimalPathRate)) { const twoHopOrders = createOrdersFromTwoHopSample(bestTwoHopQuote, orderOpts); return { optimizedOrders: twoHopOrders, liquidityDelivered: bestTwoHopQuote, sourceFlags: SOURCE_FLAGS[ERC20BridgeSource.MultiHop], }; } // If there is no optimal path AND we didn't return a MultiHop quote, then throw if (optimalPath === undefined) { throw new Error(AggregationError.NoOptimalPath); } // Generate a fallback path if native orders are in the optimal path. const nativeFills = optimalPath.fills.filter(f => f.source === ERC20BridgeSource.Native); if (opts.allowFallback && nativeFills.length !== 0) { // We create a fallback path that is exclusive of Native liquidity // This is the optimal on-chain path for the entire input amount const nonNativeFills = fills.filter(p => p.length > 0 && p[0].source !== ERC20BridgeSource.Native); const nonNativeOptimalPath = await findOptimalPathAsync(side, nonNativeFills, inputAmount, opts.runLimit); // Calculate the slippage of on-chain sources compared to the most optimal path if ( nonNativeOptimalPath !== undefined && (nativeFills.length === optimalPath.fills.length || nonNativeOptimalPath.adjustedSlippage(optimalPathRate) <= maxFallbackSlippage) ) { optimalPath.addFallback(nonNativeOptimalPath); } } const collapsedPath = optimalPath.collapse(orderOpts); return { optimizedOrders: collapsedPath.orders, liquidityDelivered: collapsedPath.collapsedFills as CollapsedFill[], sourceFlags: collapsedPath.sourceFlags, }; } private async _getMarketSideOrdersAsync( nativeOrders: SignedOrder[], amount: BigNumber, side: MarketOperation, opts?: Partial<GetMarketOrdersOpts>, ): Promise<OptimizerResultWithReport> { const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts }; const optimizerOpts: GenerateOptimizedOrdersOpts = { bridgeSlippage: _opts.bridgeSlippage, maxFallbackSlippage: _opts.maxFallbackSlippage, excludedSources: _opts.excludedSources, feeSchedule: _opts.feeSchedule, allowFallback: _opts.allowFallback, exchangeProxyOverhead: _opts.exchangeProxyOverhead, }; // Compute an optimized path for on-chain DEX and open-orderbook. This should not include RFQ liquidity. const marketLiquidityFnAsync = side === MarketOperation.Sell ? this.getMarketSellLiquidityAsync.bind(this) : this.getMarketBuyLiquidityAsync.bind(this); const marketSideLiquidity = await marketLiquidityFnAsync(nativeOrders, amount, _opts); let optimizerResult: OptimizerResult | undefined; try { optimizerResult = await this._generateOptimizedOrdersAsync(marketSideLiquidity, optimizerOpts); } catch (e) { // If no on-chain or off-chain Open Orderbook orders are present, a `NoOptimalPath` will be thrown. // If this happens at this stage, there is still a chance that an RFQ order is fillable, therefore // we catch the error and continue. if (e.message !== AggregationError.NoOptimalPath) { throw e; } } // If RFQ liquidity is enabled, make a request to check RFQ liquidity const { rfqt } = _opts; if ( IS_PRICE_AWARE_RFQ_ENABLED && rfqt && rfqt.quoteRequestor && marketSideLiquidity.quoteSourceFilters.isAllowed(ERC20BridgeSource.Native) ) { // Calculate a suggested price. For now, this is simply the overall price of the aggregation. let comparisonPrice: BigNumber | undefined; if (optimizerResult) { const totalMakerAmount = BigNumber.sum( ...optimizerResult.optimizedOrders.map(order => order.makerAssetAmount), ); const totalTakerAmount = BigNumber.sum( ...optimizerResult.optimizedOrders.map(order => order.takerAssetAmount), ); if (totalMakerAmount.gt(0)) { const totalMakerAmountUnitAmount = Web3Wrapper.toUnitAmount( totalMakerAmount, marketSideLiquidity.makerTokenDecimals, ); const totalTakerAmountUnitAmount = Web3Wrapper.toUnitAmount( totalTakerAmount, marketSideLiquidity.takerTokenDecimals, ); comparisonPrice = totalMakerAmountUnitAmount .div(totalTakerAmountUnitAmount) .decimalPlaces(COMPARISON_PRICE_DECIMALS); } } // If we are making an indicative quote, make the RFQT request and then re-run the sampler if new orders come back. if (rfqt.isIndicative) { const indicativeQuotes = await getRfqtIndicativeQuotesAsync( nativeOrders[0].makerAssetData, nativeOrders[0].takerAssetData, side, amount, comparisonPrice, _opts, ); // Re-run optimizer with the new indicative quote if (indicativeQuotes.length > 0) { optimizerResult = await this._generateOptimizedOrdersAsync( { ...marketSideLiquidity, rfqtIndicativeQuotes: indicativeQuotes, }, optimizerOpts, ); } } else { // A firm quote is being requested. Ensure that `intentOnFilling` is enabled. if (rfqt.intentOnFilling) { // Extra validation happens when requesting a firm quote, such as ensuring that the takerAddress // is indeed valid. if (!rfqt.takerAddress || rfqt.takerAddress === NULL_ADDRESS) { throw new Error('RFQ-T requests must specify a taker address'); } const firmQuotes = await rfqt.quoteRequestor.requestRfqtFirmQuotesAsync( nativeOrders[0].makerAssetData, nativeOrders[0].takerAssetData, amount, side, comparisonPrice, rfqt, ); if (firmQuotes.length > 0) { // Re-run optimizer with the new firm quote. This is the second and last time // we run the optimized in a block of code. In this case, we don't catch a potential `NoOptimalPath` exception // and we let it bubble up if it happens. // // NOTE: as of now, we assume that RFQ orders are 100% fillable because these are trusted market makers, therefore // we do not perform an extra check to get fillable taker amounts. optimizerResult = await this._generateOptimizedOrdersAsync( { ...marketSideLiquidity, nativeOrders: marketSideLiquidity.nativeOrders.concat( firmQuotes.map(quote => quote.signedOrder), ), orderFillableAmounts: marketSideLiquidity.orderFillableAmounts.concat( firmQuotes.map(quote => quote.signedOrder.takerAssetAmount), ), }, optimizerOpts, ); } } } } // At this point we should have at least one valid optimizer result, therefore we manually raise // `NoOptimalPath` if no optimizer result was ever set. if (optimizerResult === undefined) { throw new Error(AggregationError.NoOptimalPath); } // Compute Quote Report and return the results. let quoteReport: QuoteReport | undefined; if (_opts.shouldGenerateQuoteReport) { quoteReport = MarketOperationUtils._computeQuoteReport( nativeOrders, _opts.rfqt ? _opts.rfqt.quoteRequestor : undefined, marketSideLiquidity, optimizerResult, ); } return { ...optimizerResult, quoteReport }; } } // tslint:disable: max-file-line-count
the_stack
import {setUpFoundationTest} from '../../../../testing/helpers/setup'; import {MDCChipActionFocusBehavior, MDCChipActionType} from '../../action/constants'; import {MDCChipAnimation} from '../../chip/constants'; import {MDCChipSetAttributes, MDCChipSetEvents} from '../constants'; import {MDCChipSetFoundation} from '../foundation'; import {ChipAnimationEvent, ChipInteractionEvent, ChipNavigationEvent} from '../types'; interface FakeAction { type: MDCChipActionType; isSelectable: boolean; isSelected: boolean; isFocusable: boolean; } interface FakeChip { actions: FakeAction[]; id: string; } function fakeMultiActionChip(id: string): FakeChip { return { actions: [ { type: MDCChipActionType.PRIMARY, isSelectable: false, isSelected: false, isFocusable: true }, { type: MDCChipActionType.TRAILING, isSelectable: false, isSelected: false, isFocusable: true }, ], id, }; } function fakeSingleActionChip(id: string): FakeChip { return { actions: [ { type: MDCChipActionType.PRIMARY, isSelectable: false, isSelected: false, isFocusable: true }, { type: MDCChipActionType.TRAILING, isSelectable: false, isSelected: false, isFocusable: false }, ], id, }; } function fakeDisabledMultiActionChip(id: string): FakeChip { return { actions: [ { type: MDCChipActionType.PRIMARY, isSelectable: false, isSelected: false, isFocusable: false }, { type: MDCChipActionType.TRAILING, isSelectable: false, isSelected: false, isFocusable: false }, ], id, }; } function fakeSelectableChip(id: string, isSelected: boolean = false): FakeChip { return { actions: [{ type: MDCChipActionType.PRIMARY, isSelectable: true, isFocusable: true, isSelected }], id, }; } interface TestOptions { chips: FakeChip[]; supportsMultiSelection: boolean; } describe('MDCChipSetFoundation', () => { const setupTest = () => { const {foundation, mockAdapter} = setUpFoundationTest(MDCChipSetFoundation); return {foundation, mockAdapter}; }; function setupChipSetTest(options: TestOptions) { const {chips, supportsMultiSelection} = options; const {foundation, mockAdapter} = setupTest(); mockAdapter.getChipIdAtIndex.and.callFake((index: number) => { if (index < 0 || index >= chips.length) return ''; return chips[index].id; }); mockAdapter.getChipIndexById.and.callFake((id: string) => { return chips.findIndex((chip) => chip.id === id); }); mockAdapter.getChipActionsAtIndex.and.callFake((index: number) => { if (index < 0 || index >= chips.length) { return []; } return chips[index].actions.map((a) => a.type); }); mockAdapter.getChipCount.and.callFake(() => { return chips.length; }); mockAdapter.getAttribute.and.callFake((attr: MDCChipSetAttributes) => { if (attr === MDCChipSetAttributes.ARIA_MULTISELECTABLE && supportsMultiSelection) { return 'true'; } return null; }); mockAdapter.isChipSelectableAtIndex.and.callFake( (index: number, action: MDCChipActionType) => { if (index < 0 || index >= chips.length) { return false; } const actions = chips[index].actions.filter((a) => a.type === action); if (actions.length === 0) { return false; } return actions[0].isSelectable; }); mockAdapter.isChipSelectedAtIndex.and.callFake( (index: number, action: MDCChipActionType) => { if (index < 0 || index >= chips.length) { return false; } const actions = chips[index].actions.filter((a) => a.type === action); if (actions.length === 0) { return false; } return actions[0].isSelected; }); mockAdapter.isChipFocusableAtIndex.and.callFake( (index: number, action: MDCChipActionType) => { if (index < 0 || index >= chips.length) { return false; } const chipAction = chips[index].actions.find((a) => a.type === action); if (chipAction) { return chipAction.isFocusable; } return false; }); mockAdapter.removeChipAtIndex.and.callFake((index: number) => { if (index < 0 || index >= chips.length) return; chips.splice(index, 1); }); return {foundation, mockAdapter}; } it(`#handleChipInteraction emits an interaction event`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: {source: MDCChipActionType.PRIMARY, chipID: 'c0'}, } as ChipInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.INTERACTION, { chipID: 'c0', chipIndex: 0, }); }); it(`#handleChipInteraction focuses the source chip action`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: {source: MDCChipActionType.PRIMARY, chipID: 'c0'}, } as ChipInteractionEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE); }); it(`#handleChipInteraction unfocuses all other chip actions`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: {source: MDCChipActionType.PRIMARY, chipID: 'c0'}, } as ChipInteractionEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipInteraction emits a selection event when the chip is selectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.SELECTION, { chipID: 'c0', chipIndex: 0, isSelected: true, }); }); it(`#handleChipInteraction selects the source chip when not multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(0, MDCChipActionType.PRIMARY, true); }); it(`#handleChipInteraction unselects other chips when not multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(1, MDCChipActionType.PRIMARY, false); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(2, MDCChipActionType.PRIMARY, false); }); it(`#handleChipInteraction only selects the source chip when multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); // Only expect it to be called once for the selection expect(mockAdapter.setChipSelectedAtIndex).toHaveBeenCalledTimes(1); }); it(`#handleChipInteraction selects the source chip when multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(0, MDCChipActionType.PRIMARY, true); }); it(`#handleChipInteraction does not unselect other chips when multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); foundation.handleChipInteraction({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', isSelectable: true, isSelected: false }, } as ChipInteractionEvent); // Only expect it to be called once for the selection expect(mockAdapter.setChipSelectedAtIndex).toHaveBeenCalledTimes(1); }); it(`#handleChipInteraction starts the exit animation on the source chip when removable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { chipID: 'c1', shouldRemove: true, }, } as ChipInteractionEvent); expect(mockAdapter.startChipAnimationAtIndex) .toHaveBeenCalledWith(1, MDCChipAnimation.EXIT); }); it(`#handleChipInteraction emits a removal event when the source chip is removable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { chipID: 'c1', shouldRemove: true, }, } as ChipInteractionEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.REMOVAL, { chipID: 'c1', chipIndex: 1, isComplete: false, }); }); it(`#handleChipInteraction does not emit an interaction event when the source chip is removable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { chipID: 'c1', shouldRemove: true, }, } as ChipInteractionEvent); expect(mockAdapter.emitEvent) .not.toHaveBeenCalledWith( MDCChipSetEvents.INTERACTION, jasmine.anything()); }); it(`#handleChipInteraction does not change focus when the source chip is removable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipInteraction({ detail: { chipID: 'c1', shouldRemove: true, }, } as ChipInteractionEvent); expect(mockAdapter.setChipFocusAtIndex).not.toHaveBeenCalled(); }); it(`#handleChipAnimation announces the added message when present`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeDisabledMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeDisabledMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.ENTER, addedAnnouncement: 'Added foo', isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.announceMessage).toHaveBeenCalledWith('Added foo'); }); it(`#handleChipAnimation removes the source chip when exit animation is complete`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.removeChipAtIndex).toHaveBeenCalledWith(1); }); it(`#handleChipAnimation emits a removal event when the source chip exit animation is complete`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.REMOVAL, { chipID: 'c1', chipIndex: 1, isComplete: true, }); }); it(`#handleChipAnimation does not remove the source chip when the animation is incomplete`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, isComplete: false, }, } as ChipAnimationEvent); expect(mockAdapter.removeChipAtIndex).not.toHaveBeenCalled(); }); it(`#handleChipAnimation does not remove the source chip for non-exit animations`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.ENTER, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.removeChipAtIndex).not.toHaveBeenCalled(); }); it(`#handleChipAnimation focuses the nearest focusable chip with a preference for the source index`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipAnimation focuses the nearest focusable chip (0), avoiding disabled chips`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeDisabledMultiActionChip('c1'), fakeDisabledMultiActionChip('c2'), fakeDisabledMultiActionChip('c3'), fakeMultiActionChip('c4'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c4', animation: MDCChipAnimation.EXIT, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipAnimation focuses the nearest focusable chip (3), avoiding disabled chips`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeDisabledMultiActionChip('c1'), fakeDisabledMultiActionChip('c2'), fakeDisabledMultiActionChip('c3'), fakeMultiActionChip('c4'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c0', animation: MDCChipAnimation.EXIT, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 3, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipAnimation focuses no chip when all remaining are disabled`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeDisabledMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeDisabledMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, removedAnnouncement: undefined, isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith(0, jasmine.anything(), jasmine.anything()); expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith(1, jasmine.anything(), jasmine.anything()); }); it(`#handleChipAnimation announces the removed message when present`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeDisabledMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeDisabledMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipAnimation({ detail: { chipID: 'c1', animation: MDCChipAnimation.EXIT, removedAnnouncement: 'Removed foo', isComplete: true, }, } as ChipAnimationEvent); expect(mockAdapter.announceMessage).toHaveBeenCalledWith('Removed foo'); }); it(`#handleChipNavigation focuses the next available action with ArrowRight`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c0', key: 'ArrowRight', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowRight`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c0', key: 'ArrowRight', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the next available action with ArrowLeft`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowLeft', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowLeft`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowLeft', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the next available action with ArrowRight in RTL`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowRight', isRTL: true, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowRight in RTL`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowRight', isRTL: true, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the next available action with ArrowLeft in TRL`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c1', key: 'ArrowLeft', isRTL: true, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowLeft in RTL`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c1', key: 'ArrowLeft', isRTL: true, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation does not focus unfocusable actions`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeDisabledMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c0', key: 'ArrowRight', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation focuses the next matching action with ArrowUp`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowUp', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowUp`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowUp', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the previous matching action with ArrowDown`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowDown', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with ArrowDown`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c1', key: 'ArrowDown', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the first matching action with Home`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c2', key: 'Home', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with Home`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c2', key: 'Home', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation focuses the first matching action with End`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', key: 'End', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation unfocuses all other actions with End`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.PRIMARY, chipID: 'c0', key: 'End', isRTL: false, }, } as ChipNavigationEvent); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.NOT_FOCUSABLE); expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 2, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.NOT_FOCUSABLE); }); it(`#handleChipNavigation does not focus unfocusable actions with ArrowUp`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSingleActionChip('c0'), // Trailing action is not focusable fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c1', key: 'ArrowUp', isRTL: false, }, } as ChipNavigationEvent); // Verify that the 0th index trailing action is not focused expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith( 0, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation focuses the available focusable action with ArrowUp`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSingleActionChip('c0'), // Trailing action is not focusable fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c1', key: 'ArrowUp', isRTL: false, }, } as ChipNavigationEvent); // Verify that the primary action is focused expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 0, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation does not focus unfocusable actions with ArrowDown`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeSingleActionChip('c1'), // Trailing action is not focusable fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c0', key: 'ArrowDown', isRTL: false, }, } as ChipNavigationEvent); // Verify that the 0th index trailing action is not focused expect(mockAdapter.setChipFocusAtIndex) .not.toHaveBeenCalledWith( 1, MDCChipActionType.TRAILING, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#handleChipNavigation focuses the available focusable action with ArrowDown`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeSingleActionChip('c1'), // Trailing action is not focusable fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.handleChipNavigation({ detail: { source: MDCChipActionType.TRAILING, chipID: 'c0', key: 'ArrowDown', isRTL: false, }, } as ChipNavigationEvent); // Verify that the primary action is focused expect(mockAdapter.setChipFocusAtIndex) .toHaveBeenCalledWith( 1, MDCChipActionType.PRIMARY, MDCChipActionFocusBehavior.FOCUSABLE_AND_FOCUSED); }); it(`#setChipSelected emits a selection event`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.setChipSelected(0, MDCChipActionType.PRIMARY, true); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.SELECTION, { chipID: 'c0', chipIndex: 0, isSelected: true, }); }); it(`#setChipSelected selects the target chip when not multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.setChipSelected(0, MDCChipActionType.PRIMARY, true); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(0, MDCChipActionType.PRIMARY, true); }); it(`#setChipSelected unselects other chips when not multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: false, }); foundation.setChipSelected(0, MDCChipActionType.PRIMARY, true); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(1, MDCChipActionType.PRIMARY, false); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(2, MDCChipActionType.PRIMARY, false); }); it(`#setChipSelected selects the target chip when multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); foundation.setChipSelected(0, MDCChipActionType.PRIMARY, true); expect(mockAdapter.setChipSelectedAtIndex) .toHaveBeenCalledWith(0, MDCChipActionType.PRIMARY, true); }); it(`#setChipSelected does not unselect other chips when multiselectable`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); foundation.setChipSelected(0, MDCChipActionType.PRIMARY, true); // Only expect it to be called once for the selection expect(mockAdapter.setChipSelectedAtIndex).toHaveBeenCalledTimes(1); }); it(`#isChipSelected returns true if the chip is selected`, () => { const {foundation} = setupChipSetTest({ chips: [ fakeSelectableChip('c0', true), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); expect(foundation.isChipSelected(0, MDCChipActionType.PRIMARY)).toBe(true); }); it(`#isChipSelected returns false if the chip is not selected`, () => { const {foundation} = setupChipSetTest({ chips: [ fakeSelectableChip('c0'), fakeSelectableChip('c1'), fakeSelectableChip('c2'), ], supportsMultiSelection: true, }); expect(foundation.isChipSelected(1, MDCChipActionType.PRIMARY)).toBe(false); }); it(`#getSelectedChipIndexes returns the selected chip indexes`, () => { const {foundation} = setupChipSetTest({ chips: [ fakeSelectableChip('c0', true), fakeSelectableChip('c1'), fakeSelectableChip('c2', true), ], supportsMultiSelection: true, }); expect(foundation.getSelectedChipIndexes().has(0)).toBe(true); expect(foundation.getSelectedChipIndexes().has(1)).toBe(false); expect(foundation.getSelectedChipIndexes().has(2)).toBe(true); }); it(`#removeChip starts the removal animation at the given index`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.removeChip(1); expect(mockAdapter.startChipAnimationAtIndex) .toHaveBeenCalledWith(1, MDCChipAnimation.EXIT); }); it(`#removeChip emits the removal event at the given index`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.removeChip(1); expect(mockAdapter.emitEvent) .toHaveBeenCalledWith(MDCChipSetEvents.REMOVAL, { chipID: 'c1', chipIndex: 1, isComplete: false, }); }); it(`#removeChip does nothing if the index is out of bounds`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.removeChip(-1); foundation.removeChip(3); expect(mockAdapter.startChipAnimationAtIndex).not.toHaveBeenCalled(); expect(mockAdapter.emitEvent).not.toHaveBeenCalled(); }); it(`#addChip starts the enter animation at the given index`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.addChip(0); expect(mockAdapter.startChipAnimationAtIndex) .toHaveBeenCalledWith(0, MDCChipAnimation.ENTER); }); it(`#addChip does nothing if the index is out of bounds`, () => { const {foundation, mockAdapter} = setupChipSetTest({ chips: [ fakeMultiActionChip('c0'), fakeMultiActionChip('c1'), fakeMultiActionChip('c2'), ], supportsMultiSelection: false, }); foundation.addChip(-1); foundation.addChip(3); expect(mockAdapter.startChipAnimationAtIndex).not.toHaveBeenCalled(); }); });
the_stack
import test from "tape"; import { find, Query } from "../src"; import { OperatorType, useOperators } from "../src/core"; import { $where } from "../src/operators/query/evaluation/where"; import { Collection, RawArray, RawObject } from "../src/types"; import * as samples from "./support"; class ObjectId { constructor(readonly _id: string) {} } const idStr = "123456789abe"; const obj = Object.assign({}, samples.personData, { _id: new ObjectId(idStr) }); useOperators(OperatorType.QUERY, { $where }); interface UserResult { user: { username: string }; } test("Comparison, Evaluation, and Element Operators", (t) => { const queries = [ [{ _id: new ObjectId(idStr) }, "can match against user-defined types"], [{ firstName: "Francis" }, "can check for equality with $eq"], [{ lastName: /^a.+e/i }, "can check against regex with literal"], [ { lastName: { $regex: "a.+e", $options: "i" } }, "can check against regex with $regex operator", ], [{ username: { $not: "mufasa" } }, "can apply $not to direct values"], [ { username: { $not: { $ne: "kofrasa" } } }, "can apply $not to sub queries", ], [{ jobs: { $gt: 1 } }, "can compare with $gt"], [{ jobs: { $gte: 6 } }, "can compare with $gte"], [{ jobs: { $lt: 10 } }, "can compare with $lt"], [{ jobs: { $lte: 6 } }, "can compare with $lte"], [ { middlename: { $exists: false } }, "can check if value does not exists with $exists", ], [{ projects: { $exists: true } }, "can check if value exists with $exists"], [ { "projects.C.1": "student_record" }, "can compare value inside array at a given index", ], [ { "circles.school": { $in: ["Henry"] } }, "can check that value is in array with $in", ], [ { middlename: { $in: [null, "David"] } }, "can check if value does not exist with $in", ], [ { "circles.family": { $nin: ["Pamela"] } }, "can check that value is not in array with $nin", ], [{ firstName: { $nin: [null] } }, "can check if value exists with $nin"], [ { "languages.programming": { $size: 7 } }, "can determine size of nested array with $size", ], [{ "projects.Python": "Flaskapp" }, "can match nested elements in array"], [{ "date.month": { $mod: [8, 1] } }, "can find modulo of values with $mod"], [ { "languages.spoken": { $all: ["french", "english"] } }, "can check that all values exists in array with $all", ], [ { "languages.spoken": { $all: [/french/, /english/] } }, "can check that all values exists in array with $all using regex", ], [ { date: { year: 2013, month: 9, day: 25 } }, "can match field with object values", ], [ { "grades.0.grade": 92 }, "can match fields for objects in a given position in an array with dot notation", ], [ { "grades.mean": { $gt: 70 } }, "can match fields for all objects within an array with dot notation", ], [ { grades: { $elemMatch: { mean: { $gt: 70 } } } }, "can match fields for all objects within an array with $elemMatch", ], [{ today: { $type: 9 } }, "can match type of fields with $type"], [ { $where: "this.jobs === 6 && this.grades.length < 10" }, "can match with $where expression", ], ]; queries.forEach((q: RawArray) => { const query = new Query(q[0] as RawObject); t.ok(query.test(obj), q[1] as string); }); //https://github.com/kofrasa/mingo/issues/54 const data = [{ _id: 1, item: null }, { _id: 2 }]; const result = find(data, { item: null }).all(); t.deepEqual(result, data, "can match null and missing types correctly"); t.end(); }); test("project $type operator", (t) => { const obj = { double: 12323.4, string: "me", obj: {}, array: [], boolean: true, date: new Date(), nothing: null, regex: /ab/, int: 49023, long: Math.pow(2, 32), decimal: 20.7823e10, }; const queries = [ [{ double: { $type: 1 } }, 'can match $type 1 "double"'], [{ string: { $type: 2 } }, 'can match $type 2 "string"'], [{ obj: { $type: 3 } }, 'can match $type 3 "object"'], [{ array: { $type: 4 } }, 'can match $type 4 "array"'], [{ missing: { $type: 6 } }, 'can match $type 6 "undefined"'], [{ boolean: { $type: 8 } }, 'can match $type 8 "boolean"'], [{ date: { $type: 9 } }, 'can match $type 9 "date"'], [{ nothing: { $type: 10 } }, 'can match $type 10 "null"'], [{ regex: { $type: 11 } }, 'can match $type 11 "regexp"'], [{ int: { $type: 16 } }, 'can match $type 16 "int"'], [{ long: { $type: 18 } }, 'can match $type 18 "long"'], [{ decimal: { $type: 19 } }, 'can match $type 19 "decimal"'], [{ obj: { $not: { $type: 100 } } }, "do not match unknown $type"], // { $type: array } [{ double: { $type: [1] } }, 'can match $type [1] "double"'], [{ double: { $type: [1, 4] } }, 'can match $type [1, 4] "double"'], [{ array: { $type: [1, 4] } }, 'can match $type [1, 4] "array"'], [{ double: { $not: { $type: [] } } }, "do not match $type []"], ]; queries.forEach(function (q) { const query = new Query(q[0] as RawObject); t.ok(query.test(obj), q[1] as string); }); t.end(); }); test("Match $all with $elemMatch on nested elements", (t) => { t.plan(1); const data = [ { user: { username: "User1", projects: [ { name: "Project 1", rating: { complexity: 6 } }, { name: "Project 2", rating: { complexity: 2 } }, ], }, }, { user: { username: "User2", projects: [ { name: "Project 1", rating: { complexity: 6 } }, { name: "Project 2", rating: { complexity: 8 } }, ], }, }, ]; const criteria = { "user.projects": { $all: [{ $elemMatch: { "rating.complexity": { $gt: 6 } } }], }, }; // It should return one user object const result = find(data, criteria).count(); t.ok(result === 1, "can match using $all with $elemMatch on nested elements"); }); test("Match $all with regex", (t) => { t.plan(3); const data = [ { user: { username: "User1", projects: ["foo", "bar"], }, }, { user: { username: "User2", projects: ["foo", "baz"], }, }, { user: { username: "User3", projects: ["fizz", "buzz"], }, }, { user: { username: "User4", projects: [], }, }, ]; const criteria = { "user.projects": { $all: ["foo", /^ba/], }, }; // It should return two user objects const results = find(data, criteria).all(); t.equal( results.length, 2, "can match using $all with regex mixed with strings" ); t.equal( (results[0] as UserResult).user.username, "User1", "returns user1 using $all with regex" ); t.equal( // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (results[1] as UserResult).user.username, "User2", "returns user2 using $all with regex" ); }); test("Match $all with strings, numbers and empty lists", (t) => { t.plan(3); const data = [ { user: { username: "User1", projects: ["foo", 1], }, }, { user: { username: "User2", projects: ["foo", 2, "1"], }, }, { user: { username: "User3", projects: [], }, }, ]; const criteria = { "user.projects": { $all: ["foo", 1], }, }; // It should return two user objects const results = find(data, criteria).all(); t.equal(results.length, 1, "can match using $all with strings and numbers"); t.equal( // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access (results[0] as UserResult).user.username, "User1", "returns user1 using $all with strings and numbers" ); criteria["user.projects"].$all = []; t.equal( find(data, criteria).count(), 0, "match $all with an empty query returns no items" ); }); test("Projection $elemMatch operator", (t) => { const data = [ { _id: 1, zipcode: "63109", students: [ { name: "john", school: 102, age: 10 }, { name: "jess", school: 102, age: 11 }, { name: "jeff", school: 108, age: 15 }, ], }, { _id: 2, zipcode: "63110", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ], }, { _id: 3, zipcode: "63109", students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ], }, { _id: 4, zipcode: "63109", students: [ { name: "barney", school: 102, age: 7 }, { name: "ruth", school: 102, age: 16 }, ], }, ]; const result1 = find( data, { zipcode: "63109" }, { students: { $elemMatch: { school: 102 } } } ).all(); t.deepEqual( result1, [ { _id: 1, students: [{ name: "john", school: 102, age: 10 }] }, { _id: 3 }, { _id: 4, students: [{ name: "barney", school: 102, age: 7 }] }, ], "can project with $elemMatch" ); const result2 = find( data, { zipcode: "63109" }, { students: { $elemMatch: { school: 102, age: { $gt: 10 } } } } ).all(); t.deepEqual( result2, [ { _id: 1, students: [{ name: "jess", school: 102, age: 11 }] }, { _id: 3 }, { _id: 4, students: [{ name: "ruth", school: 102, age: 16 }] }, ], "can project multiple fields with $elemMatch" ); const result3 = find(data, {}, { students: { $slice: 1 } }).all()[0] as { students: RawArray; }; t.equal(result3.students.length, 1, "can project $slice with limit"); const result4 = find(data, {}, { students: { $slice: [1, 2] } }).all()[0] as { students: RawArray; }; t.equal(result4.students.length, 2, "can project $slice with skip and limit"); t.end(); }); test("Query $elemMatch operator", (t) => { let result = find( [ { _id: 1, results: [82, 85, 88] }, { _id: 2, results: [75, 88, 89] }, ], { results: { $elemMatch: { $gte: 80, $lt: 85 } } } ).all()[0]; t.deepEqual( result, { _id: 1, results: [82, 85, 88] }, "simple $elemMatch query" ); const products = [ { _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 }, ], }, { _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 }, ], }, { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, ]; result = find(products, { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } }, }).all()[0]; t.deepEqual( result, { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, "$elemMatch on embedded documents" ); result = find(products, { results: { $elemMatch: { product: "xyz" } }, }).all(); t.deepEqual(result, products, "$elemMatch single document"); // Test for https://github.com/kofrasa/mingo/issues/103 const fixtures = [ [{ $eq: 50 }], [{ $lt: 50 }], [{ $lte: 50 }], [{ $gt: 50 }], [{ $gte: 50 }], ]; fixtures.forEach(function (args) { const query = new Query({ scores: { $elemMatch: args[0] } }); const op = Object.keys(args[0])[0]; // test if an object matches query t.ok( query.test({ scores: [10, 50, 100] }), "$elemMatch: should filter with " + op ); }); t.end(); }); test("Query $elemMatch operator with non-boolean operators", (t) => { const products = [ { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, ]; let result = find(products, { results: { $elemMatch: { $and: [{ product: "xyz" }, { score: 8 }], }, }, }).all()[0]; t.deepEqual( result, { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, "$elemMatch with $and" ); result = find(products, { results: { $elemMatch: { $and: [{ product: "xyz" }, { score: 9 }], }, }, }).all()[0]; t.deepEqual(result, undefined, "$elemMatch with $and that does not match"); result = find(products, { results: { $elemMatch: { $or: [{ product: "xyz" }, { score: 8 }], }, }, }).all()[0]; t.deepEqual( result, { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, "$elemMatch with $or" ); result = find(products, { results: { $elemMatch: { $nor: [{ product: "abc" }, { score: 7 }], }, }, }).all()[0]; t.deepEqual( result, { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 }, ], }, "$elemMatch with $nor" ); t.end(); }); test("Evaluate $where last", (t) => { t.plan(2); const data = [ { user: { username: "User1", projects: [ { name: "Project 1", rating: { complexity: 6 } }, { name: "Project 2", rating: { complexity: 2 } }, ], color: "green", number: 42, }, }, { user: { username: "User2", projects: [ { name: "Project 1", rating: { complexity: 6 } }, { name: "Project 2", rating: { complexity: 8 } }, ], }, }, ]; let criteria: RawObject = { "user.color": { $exists: true }, "user.number": { $exists: true }, $where: 'this.user.color === "green" && this.user.number === 42', }; // It should return one user object let result = find(data, criteria).count(); t.ok( result === 1, "can safely reference properties on this using $where and $exists" ); criteria = { "user.color": { $exists: true }, "user.number": { $exists: true }, $and: [ { $where: 'this.user.color === "green"' }, { $where: "this.user.number === 42" }, ], }; // It should return one user object result = find(data, criteria).count(); t.ok( result === 1, "can safely reference properties on this using multiple $where operators and $exists" ); }); test("Query projection operators", (t) => { { const data: Collection = [obj]; const result = find( data, {}, { "languages.programming": { $slice: [-3, 2] } } ).next() as typeof samples.personData; t.deepEqual( result["languages"]["programming"], ["Javascript", "Bash"], "should project with $slice operator" ); } { // special tests // https://github.com/kofrasa/mingo/issues/25 const data = [ { key0: [ { key1: [ [[{ key2: [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }]], { key2: "value" }, ], key1a: { key2a: "value2a" }, }, ], }, ]; const expected = { key0: [{ key1: [[[{ key2: [{ a: "value2" }, { a: "dummy" }] }]]] }], }; const result = find( data, { "key0.key1.key2": "value" }, { "key0.key1.key2.a": 1 } ).next(); t.deepEqual( result, expected, "should project only selected object graph from nested arrays" ); t.notDeepEqual(data[0], result, "should not modify original"); } { const data = [ { name: "Steve", age: 15, features: { hair: "brown", eyes: "brown" } }, ]; let result = find(data, {}, { "features.hair": 1 }).next(); t.deepEqual( result, { features: { hair: "brown" } }, "should project only selected object graph" ); t.notDeepEqual(data[0], result, "should not modify original"); t.throws( function () { find(data, {}, { "features.hair": 0, name: 1 }).next(); }, Error, "should throw exception: Projection cannot have a mix of inclusion and exclusion" ); result = find(data, {}, { "features.hair": 0 }).next(); t.deepEqual( result, { name: "Steve", age: 15, features: { eyes: "brown" } }, "should omit key" ); t.notDeepEqual(data[0], result, "should not modify original"); } { const data = [ { name: "Steve", age: 15, features: ["hair", "eyes", "nose"] }, ]; let result = find(data, {}, { "features.1": 0 }).next(); t.deepEqual( result, { name: "Steve", age: 15, features: ["hair", "nose"] }, "should omit second element in array" ); t.notDeepEqual(data[0], result, "should not modify original"); result = find(data, {}, { "features.1": 1 }).next(); t.deepEqual( result, { features: ["eyes"] }, "should select only second element in array" ); t.notDeepEqual(data[0], result, "should not modify original"); result = find( [ { id: 1, sub: [{ id: 11, name: "OneOne", test: true }] }, { id: 2, sub: [{ id: 22, name: "TwoTwo", test: false }] }, ], {}, { "sub.id": 1, "sub.name": 1 } ).next(); t.deepEqual( result, { sub: [{ id: 11, name: "OneOne" }] }, "should project nested elements in array" ); } t.end(); }); test("Logical Operators", (t) => { const queries: Array<RawArray> = [ [ { $and: [{ firstName: "Francis" }, { lastName: /^a.+e/i }] }, "can use conjunction true AND true", ], [ { $and: [{ firstName: "Francis" }, { lastName: "Amoah" }] }, false, "can use conjunction true AND false", ], [ { $and: [{ firstName: "Enoch" }, { lastName: "Asante" }] }, false, "can use conjunction false AND true", ], [ { $and: [{ firstName: "Enoch" }, { age: { $exists: true } }] }, false, "can use conjunction false AND false", ], // or [ { $or: [{ firstName: "Francis" }, { lastName: /^a.+e/i }] }, "can use conjunction true OR true", ], [ { $or: [{ firstName: "Francis" }, { lastName: "Amoah" }] }, "can use conjunction true OR false", ], [ { $or: [{ firstName: "Enoch" }, { lastName: "Asante" }] }, "can use conjunction false OR true", ], [ { $or: [{ firstName: "Enoch" }, { age: { $exists: true } }] }, false, "can use conjunction false OR false", ], // nor [ { $nor: [{ firstName: "Francis" }, { lastName: /^a.+e/i }] }, false, "can use conjunction true NOR true", ], [ { $nor: [{ firstName: "Francis" }, { lastName: "Amoah" }] }, false, "can use conjunction true NOR false", ], [ { $nor: [{ firstName: "Enoch" }, { lastName: "Asante" }] }, false, "can use conjunction false NOR true", ], [ { $nor: [{ firstName: "Enoch" }, { age: { $exists: true } }] }, "can use conjunction false NOR false", ], ]; queries.forEach(function (q) { if (q.length === 2) { t.ok(new Query(q[0] as RawObject).test(obj), q[1] as string); } else if (q.length === 3) { t.equal(new Query(q[0] as RawObject).test(obj), q[1], q[2] as string); } }); t.end(); }); test("Query array operators", (t) => { let data: Array<RawObject> = [ { _id: "5234ccb7687ea597eabee677", code: "efg", tags: ["school", "book"], qty: [ { size: "S", num: 10, color: "blue" }, { size: "M", num: 100, color: "blue" }, { size: "L", num: 100, color: "green" }, ], }, { _id: "52350353b2eff1353b349de9", code: "ijk", tags: ["electronics", "school"], qty: [{ size: "M", num: 100, color: "green" }], }, ]; const q = new Query({ qty: { $all: [ { $elemMatch: { size: "M", num: { $gt: 50 } } }, { $elemMatch: { num: 100, color: "green" } }, ], }, }); let booleanResult = true; data.forEach(function (obj) { booleanResult = booleanResult && q.test(obj); }); t.ok(booleanResult, "can match object using $all with $elemMatch"); data = [ { key0: [ { key1: [ [[{ key2: [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }]], { key2: "value" }, ], key1a: { key2a: "value2a" }, }, ], }, ]; let fixtures: Array<RawArray> = [ [ { "key0.key1.key2.a": "value2" }, [], "should not match without array index selector to nested value ", ], [ { "key0.key1.0.key2.a": "value2" }, [], "should not match without enough depth for array index selector to nested value", ], [ { "key0.key1.0.0.key2.a": "value2" }, data, "should match with full array index selector to deeply nested value", ], [ { "key0.key1.0.0.key2": { b: 20 } }, data, "should match with array index selector to nested value at depth 1", ], [ { "key0.key1.1.key2": "value" }, data, "should match with full array index selector to nested value", ], [ { "key0.key1.key2": "value" }, data, "should match without array index selector to nested value at depth 1", ], [ { "key0.key1.1.key2": "value" }, data, "should match shallow nested value with array index selector", ], ]; fixtures.forEach((row: RawArray) => { const query = row[0] as RawObject; const expected = row[1]; const message = row[2] as string; const result = find(data, query).all(); t.deepEqual(result, expected, message); }); fixtures = [ [ { "key0.key1": [[{ key2: [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }]], }, "should match full key selector", ], [ { "key0.key1.0": [ [{ key2: [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }], ], }, "should match with key<-->index selector", ], [ { "key0.key1.0.0": [ { key2: [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }, ], }, "should match with key<-->multi-index selector", ], [ { "key0.key1.0.0.key2": [{ a: "value2" }, { a: "dummy" }, { b: 20 }] }, "should match with key<-->multi-index<-->key selector", ], ]; // should match whole objects fixtures.forEach(function (row) { const query = row[0] as RawObject; const message = row[1] as string; const result = find(data, query) as Iterable<RawObject>; // using iterator t.deepEqual(Array.from(result), data, message); t.ok(Array.from(result).length === 0, "iterator should be empty"); }); // https://github.com/kofrasa/mingo/issues/51 data = [{ key0: [{ key1: ["value"] }, { key1: ["value1"] }] }]; const singleResult = find(data, { "key0.key1": { $eq: "value" } }).next(); t.deepEqual( singleResult, data[0], "should match nested array of objects without indices" ); // https://github.com/kofrasa/mingo/issues/93 data = [ { id: 1, sub: [ { id: 11, name: "OneOne", test: true }, { id: 22, name: "TwoTwo", test: false }, ], }, ]; let arrayResult = find(data, {}, { "sub.id": 1, "sub.name": 1 }).all(); t.deepEqual( arrayResult, [ { sub: [ { id: 11, name: "OneOne" }, { id: 22, name: "TwoTwo" }, ], }, ], "should project all matched elements of nested array" ); // https://github.com/kofrasa/mingo/issues/105 - fix merging distinct objects during projection arrayResult = find( [{ items: [{ from: 1 }, { to: 2 }] }], {}, { "items.from": 1, "items.to": 1 } ).all(); t.deepEqual( arrayResult, [{ items: [{ from: 1 }, { to: 2 }] }], "should project multiple nested elements" ); // extended test for missing keys of nested values arrayResult = find( [{ items: [{ from: 1, to: null }, { to: 2 }] }], {}, { "items.from": 1, "items.to": 1 } ).all(); t.deepEqual( arrayResult, [{ items: [{ from: 1, to: null }, { to: 2 }] }], "project multiple nested elements with missing keys" ); // https://github.com/kofrasa/mingo/issues/106 - fix nested elements splitting after projection due to out of order matching arrayResult = find( [{ history: [{ user: "Jeff", notes: "asdf" }, { user: "Gary" }] }], {}, { "history.user": 1, "history.notes": 1, } ).all(); t.deepEqual( arrayResult, [ { history: [ { user: "Jeff", notes: "asdf", }, { user: "Gary", }, ], }, ], "project multiple nested objects with missing keys and matched out of order" ); t.end(); }); test("$regex test", (t) => { // no regex - returns expected list: 1 element - ok const res: Array<RawArray> = []; res.push( find([{ l1: [{ tags: ["tag1", "tag2"] }, { notags: "yep" }] }], { "l1.tags": "tag1", }).all() ); // with regex - but searched property is not an array: ok res.push( find([{ l1: [{ tags: "tag1" }, { notags: "yep" }] }], { "l1.tags": { $regex: ".*tag.*", $options: "i" }, }).all() ); // with regex - but searched property is an array, with all elements matching: not ok - expected 1, returned 0 res.push( find([{ l1: [{ tags: ["tag1", "tag2"] }, { tags: ["tag66"] }] }], { "l1.tags": { $regex: "tag", $options: "i" }, }).all() ); // with regex - but searched property is an array, only one element matching: not ok - returns 0 elements - expected 1 res.push( find([{ l1: [{ tags: ["tag1", "tag2"] }, { notags: "yep" }] }], { "l1.tags": { $regex: "tag", $options: "i" }, }).all() ); t.ok( res.every((x) => x.length === 1), "can $regex match nested values" ); t.end(); }); test("$expr tests", (t) => { // https://docs.mongodb.com/manual/reference/operator/query/expr/ let res = find( [ { _id: 1, category: "food", budget: 400, spent: 450 }, { _id: 2, category: "drinks", budget: 100, spent: 150 }, { _id: 3, category: "clothes", budget: 100, spent: 50 }, { _id: 4, category: "misc", budget: 500, spent: 300 }, { _id: 5, category: "travel", budget: 200, spent: 650 }, ], { $expr: { $gt: ["$spent", "$budget"] } } ).all(); t.deepEqual( res, [ { _id: 1, category: "food", budget: 400, spent: 450 }, { _id: 2, category: "drinks", budget: 100, spent: 150 }, { _id: 5, category: "travel", budget: 200, spent: 650 }, ], "compare two fields from a single document" ); res = find( [ { _id: 1, item: "binder", qty: 100, price: 12 }, { _id: 2, item: "notebook", qty: 200, price: 8 }, { _id: 3, item: "pencil", qty: 50, price: 6 }, { _id: 4, item: "eraser", qty: 150, price: 3 }, ], { $expr: { $lt: [ { $cond: { if: { $gte: ["$qty", 100] }, then: { $divide: ["$price", 2] }, else: { $divide: ["$price", 4] }, }, }, 5, ], }, } ).all(); t.deepEqual( res, [ { _id: 2, item: "notebook", qty: 200, price: 8 }, { _id: 3, item: "pencil", qty: 50, price: 6 }, { _id: 4, item: "eraser", qty: 150, price: 3 }, ], "using $expr with conditional statements" ); t.end(); }); test("null or missing fields", (t) => { const data = [{ _id: 1, item: null }, { _id: 2 }]; const fixtures: RawArray = [ // query, result, message [ { item: null }, [{ _id: 1, item: null }, { _id: 2 }], "should return all documents", ], [ { item: { $type: 10 } }, [{ _id: 1, item: null }], "should return one document with null field", ], [ { item: { $exists: false } }, [{ _id: 2 }], "should return one document without null field", ], [ { item: { $in: [null, false] } }, [{ _id: 1, item: null }, { _id: 2 }], "$in should return all documents", ], ]; for (let i = 0; i < fixtures.length; i++) { const arr = fixtures[i]; const res = find(data, arr[0]).all(); t.deepEqual(res, arr[1], arr[2]); } t.end(); }); test("hash function collision", (t) => { const data = [{ codes: ["KNE_OC42-midas"] }, { codes: ["KNE_OCS3-midas"] }]; const fixtures = [ { query: { codes: { $in: ["KNE_OCS3-midas"] } }, result: [{ codes: ["KNE_OC42-midas"] }, { codes: ["KNE_OCS3-midas"] }], options: {}, message: "should return both documents due to hash collision with default hash function", }, { query: { codes: { $in: ["KNE_OCS3-midas"] } }, result: [{ codes: ["KNE_OCS3-midas"] }], options: { hashFunction: (v) => JSON.stringify(v), // basic hash function, but has low performances }, message: "should return the good document due to no hash collision with custom hash function", }, ]; for (let i = 0; i < fixtures.length; i++) { const line = fixtures[i]; const query = new Query(line.query, line.options); const res = query.find(data).all(); t.deepEqual(res, line.result, line.message); } t.end(); });
the_stack
class UrlController { private _urlDictionary: any; public constructor() { this._urlDictionary = { "dayTime": "d", "title": "t", "shadows": "s", "terrainShadows": "ts", "latitude": "la", "lat": "la_", "longitude": "lo", "lon": "lo_", "height": "h", "heading": "hd", "pitch": "p", "roll": "r", // layer infos "layer_": "l_", "url": "u", "name": "n", "layerDataType": "ld", "layerProxy": "lp", "layerClampToGround": "lc", "gltfVersion": "gv", "active": "a", "thematicDataUrl": "tdu", "thematicDataSource": "ds", "tableType": "tt", // "googleSheetsApiKey": "gk", // "googleSheetsRanges": "gr", // "googleSheetsClientId": "tid", "cityobjectsJsonUrl": "gc", "minLodPixels": "il", "maxLodPixels": "al", "maxSizeOfCachedTiles": "ac", "maxCountOfVisibleTiles": "av", // basemap infos "basemap": "bm", // "name" : "n", "iconUrl": "iu", "tooltip": "ht", // "url" : "u", "layers": "ls", "additionalParameters": "ap", "proxyUrl": "pu", // terrain infos "cesiumWorldTerrain": "ct", "terrain": "tr", // "name" : "n, // "iconUrl" : "iu", // "tooltip" : "ht", // "url" : "u" // splash window infos "splashWindow": "sw", // "url": "u", "showOnStart": "ss", "ionToken": "it", "bingToken": "bt", "debug": "db", "googleClientId": "gid" }; } // return only the shortened name of the URL parameters private getUrlParaForward(parameter: string): string { let value = ""; if (parameter.indexOf("layer_") >= 0) { // layer_N, with N as a number value = this._urlDictionary["layer_"] + parameter.substring("layer_".length); } else { value = this._urlDictionary[parameter]; } if (typeof value !== "undefined" && value !== "") { return value; } return null; } // return only the full name of the URL parameters private getUrlParaAuxReverse(parameter: string): string { for (let key in this._urlDictionary) { if (this._urlDictionary[key] === parameter) { return key; } } return null; } // return the value defined by the URL parameter public getUrlParaValue(parameter: string, url: string, CitydbUtil: any): string { let result: any = CitydbUtil.parse_query_string(this.getUrlParaForward(parameter), url); if (result == null || result === "") { // reverse mapping // result = CitydbUtil.parse_query_string(this.getUrlParaAuxReverse(parameter), url); result = CitydbUtil.parse_query_string(parameter, url); } return result; } public generateLink( webMap: any, addWmsViewModel: any, addTerrainViewModel: any, addSplashWindowModel: any, tokens: any, signInController: any, googleClientId: any, splashController: SplashController, cesiumViewer: any, Cesium: any ): string { let cameraPosition = this.getCurrentCameraPostion(cesiumViewer, Cesium); let projectLink = location.protocol + '//' + location.host + location.pathname + '?'; let clock = cesiumViewer.cesiumWidget.clock; if (!clock.shouldAnimate) { let currentJulianDate = clock.currentTime; let daytimeObject = {}; daytimeObject[this.getUrlParaForward('dayTime')] = Cesium.JulianDate.toIso8601(currentJulianDate, 0); projectLink = projectLink + Cesium.objectToQuery(daytimeObject) + '&'; } projectLink = projectLink + this.getUrlParaForward('title') + '=' + document.title + '&' + this.getUrlParaForward('shadows') + '=' + cesiumViewer.shadows + '&' + this.getUrlParaForward('terrainShadows') + '=' + (isNaN(cesiumViewer.terrainShadows) ? 0 : cesiumViewer.terrainShadows) + '&' + this.getUrlParaForward('latitude') + '=' + Math.round(cameraPosition.latitude * 1e6) / 1e6 + '&' + this.getUrlParaForward('longitude') + '=' + Math.round(cameraPosition.longitude * 1e6) / 1e6 + '&' + this.getUrlParaForward('height') + '=' + Math.round(cameraPosition.height * 1e3) / 1e3 + '&' + this.getUrlParaForward('heading') + '=' + Math.round(cameraPosition.heading * 1e2) / 1e2 + '&' + this.getUrlParaForward('pitch') + '=' + Math.round(cameraPosition.pitch * 1e2) / 1e2 + '&' + this.getUrlParaForward('roll') + '=' + Math.round(cameraPosition.roll * 1e2) / 1e2 + '&' + this.layersToQuery(webMap, Cesium); let basemap = this.basemapToQuery(addWmsViewModel, cesiumViewer, Cesium); if (basemap != null && basemap !== "") { projectLink = projectLink + '&' + basemap; } let terrain = this.terrainToQuery(addTerrainViewModel, cesiumViewer, Cesium); if (terrain != null && terrain !== "") { projectLink = projectLink + '&' + terrain; } let splashWindow = this.splashWindowToQuery(addSplashWindowModel, splashController, Cesium); if (splashWindow != null && splashWindow !== "") { projectLink = projectLink + '&' + splashWindow; } // export ion and Bing token if available if (tokens.ionToken != null && tokens.ionToken !== "") { projectLink = projectLink + '&' + this.getUrlParaForward('ionToken') + '=' + tokens.ionToken; } if (tokens.bingToken != null && tokens.bingToken !== "") { projectLink = projectLink + '&' + this.getUrlParaForward('bingToken') + '=' + tokens.bingToken; } // only export client ID if user is logged in if ((signInController && signInController.clientID && signInController.isSignIn())) { projectLink = projectLink + '&' + this.getUrlParaForward('googleClientId') + '=' + (signInController.clientID ? signInController.clientID : googleClientId); } return projectLink; } private getCurrentCameraPostion(cesiumViewer: any, Cesium: any): any { let cesiumCamera = cesiumViewer.scene.camera; let position = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cesiumCamera.position); let latitude = Cesium.Math.toDegrees(position.latitude); let longitude = Cesium.Math.toDegrees(position.longitude); let height = position.height; let heading = Cesium.Math.toDegrees(cesiumCamera.heading); let pitch = Cesium.Math.toDegrees(cesiumCamera.pitch); let roll = Cesium.Math.toDegrees(cesiumCamera.roll); let result = { latitude: latitude, longitude: longitude, height: height, heading: heading, pitch: pitch, roll: roll }; return result; } private layersToQuery(webMap: any, Cesium: any): string { let layerGroupObject = new Object(); let layers = webMap._layers; for (let i = 0; i < layers.length; i++) { let layer = layers[i]; let layerConfig = {}; layerConfig[this.getUrlParaForward('url')] = Cesium.defaultValue(layer.url, ""); layerConfig[this.getUrlParaForward('name')] = Cesium.defaultValue(layer.name, ""); layerConfig[this.getUrlParaForward('layerDataType')] = Cesium.defaultValue(layer.layerDataType, ""); layerConfig[this.getUrlParaForward('layerProxy')] = Cesium.defaultValue(layer.layerProxy, ""); layerConfig[this.getUrlParaForward('layerClampToGround')] = Cesium.defaultValue(layer.layerClampToGround, ""); layerConfig[this.getUrlParaForward('gltfVersion')] = Cesium.defaultValue(layer.gltfVersion, ""); layerConfig[this.getUrlParaForward('active')] = Cesium.defaultValue(layer.active, ""); layerConfig[this.getUrlParaForward('thematicDataUrl')] = Cesium.defaultValue(layer.thematicDataUrl, ""); layerConfig[this.getUrlParaForward('thematicDataSource')] = Cesium.defaultValue(layer.thematicDataSource, ""); layerConfig[this.getUrlParaForward('tableType')] = Cesium.defaultValue(layer.tableType, ""); // layerConfig[this.getUrlParaForward('googleSheetsApiKey')] = Cesium.defaultValue(layer.googleSheetsApiKey, ""); // layerConfig[this.getUrlParaForward('googleSheetsRanges')] = Cesium.defaultValue(layer.googleSheetsRanges, ""); // layerConfig[this.getUrlParaForward('googleSheetsClientId')] = Cesium.defaultValue(layer.googleSheetsClientId, "")layer.; layerConfig[this.getUrlParaForward('cityobjectsJsonUrl')] = Cesium.defaultValue(layer.cityobjectsJsonUrl, ""); layerConfig[this.getUrlParaForward('minLodPixels')] = Cesium.defaultValue(layer.minLodPixels, ""); layerConfig[this.getUrlParaForward('maxLodPixels')] = Cesium.defaultValue(layer.maxLodPixels, ""); layerConfig[this.getUrlParaForward('maxSizeOfCachedTiles')] = Cesium.defaultValue(layer.maxSizeOfCachedTiles, ""); layerConfig[this.getUrlParaForward('maxCountOfVisibleTiles')] = Cesium.defaultValue(layer.maxCountOfVisibleTiles, ""); layerGroupObject[this.getUrlParaForward('layer_') + i] = Cesium.objectToQuery(layerConfig); } return Cesium.objectToQuery(layerGroupObject) } private basemapToQuery(addWmsViewModel: any, cesiumViewer: any, Cesium: any): string { let baseLayerPickerViewModel = cesiumViewer.baseLayerPicker.viewModel; let baseLayerProviderFunc = baseLayerPickerViewModel.selectedImagery.creationCommand(); if (baseLayerProviderFunc instanceof Cesium.WebMapServiceImageryProvider) { let basemapObject = {}; basemapObject[this.getUrlParaForward('basemap')] = Cesium.objectToQuery(addWmsViewModel); return Cesium.objectToQuery(basemapObject); } else { return null; } } private terrainToQuery(addTerrainViewModel: any, cesiumViewer: any, Cesium: any): string { let baseLayerPickerViewModel = cesiumViewer.baseLayerPicker.viewModel; let baseLayerProviderFunc = baseLayerPickerViewModel.selectedTerrain.creationCommand(); if (baseLayerProviderFunc instanceof Cesium.CesiumTerrainProvider) { if (baseLayerPickerViewModel.selectedTerrain.name.indexOf('Cesium World Terrain') !== -1) { return this.getUrlParaForward('cesiumWorldTerrain') + '=true'; } let terrainObject = {}; terrainObject[this.getUrlParaForward('terrain')] = Cesium.objectToQuery(addTerrainViewModel); return Cesium.objectToQuery(terrainObject); } else { return null; } } private splashWindowToQuery(addSplashWindowModel: any, splashController: SplashController, Cesium: any): string { if (addSplashWindowModel.url) { let splashObjectTmp: any = {} let default_obj = splashController.getDefaultAddSplashWindowModel(); // only export info that are not the same as default if (addSplashWindowModel.url !== default_obj.url) { splashObjectTmp.url = addSplashWindowModel.url; } if (addSplashWindowModel.showOnStart !== default_obj.showOnStart) { splashObjectTmp.showOnStart = addSplashWindowModel.showOnStart; } let splashObject = {}; splashObject[this.getUrlParaForward('splashWindow')] = Cesium.objectToQuery(splashObjectTmp); return Cesium.objectToQuery(splashObject); } return null; } private getValueFromObject(name: string, customObject: any, defaultValue?: any, Cesium?: any) { let result = customObject[this.getUrlParaForward(name)]; if (typeof result === "undefined" || result === "") { result = customObject[name]; } if (typeof Cesium === "undefined") { return result; } return Cesium.defaultValue(result, defaultValue); } public getLayersFromUrl(url: any, CitydbUtil: any, CitydbKmlLayer: any, Cesium3DTilesDataLayer: any, Cesium: any): any { let index = 0; let nLayers = []; let layerConfigString = this.getUrlParaValue('layer_' + index, url, CitydbUtil); while (layerConfigString) { let layerConfig = Cesium.queryToObject(Object.keys(Cesium.queryToObject(layerConfigString))[0]); let options = { url: this.getValueFromObject('url', layerConfig), name: this.getValueFromObject('name', layerConfig), layerDataType: this.getValueFromObject('layerDataType', layerConfig, 'COLLADA/KML/glTF', Cesium), layerProxy: this.getValueFromObject('layerProxy', layerConfig, false, Cesium) === "true", layerClampToGround: this.getValueFromObject('layerClampToGround', layerConfig, true, Cesium) === "true", gltfVersion: this.getValueFromObject('gltfVersion', layerConfig, '2.0', Cesium), thematicDataUrl: layerConfig['spreadsheetUrl'] ? this.getValueFromObject('spreadsheetUrl', layerConfig, '', Cesium) : this.getValueFromObject('thematicDataUrl', layerConfig, '', Cesium), thematicDataSource: this.getValueFromObject('thematicDataSource', layerConfig, 'GoogleSheets', Cesium), tableType: this.getValueFromObject('tableType', layerConfig, 'Horizontal', Cesium), // googleSheetsApiKey: this.getValueFromObject('googleSheetsApiKey', layerConfig, '', Cesium), // googleSheetsRanges: this.getValueFromObject('googleSheetsRanges', layerConfig, '', Cesium), // googleSheetsClientId: this.getValueFromObject('googleSheetsClientId', layerConfig, '', Cesium), cityobjectsJsonUrl: this.getValueFromObject('cityobjectsJsonUrl', layerConfig, '', Cesium), active: this.getValueFromObject('active', layerConfig, false, Cesium) === "true", minLodPixels: this.getValueFromObject('minLodPixels', layerConfig, 140, Cesium), maxLodPixels: this.getValueFromObject('maxLodPixels', layerConfig, Number.MAX_VALUE, Cesium) === -1 ? Number.MAX_VALUE : this.getValueFromObject('maxLodPixels', layerConfig, Number.MAX_VALUE, Cesium), maxSizeOfCachedTiles: this.getValueFromObject('maxSizeOfCachedTiles', layerConfig, 140, Cesium), maxCountOfVisibleTiles: this.getValueFromObject('maxCountOfVisibleTiles', layerConfig, 140, Cesium), } if (['kml', 'kmz', 'json', 'czml'].indexOf(CitydbUtil.get_suffix_from_filename(options.url)) > -1 && options.layerDataType === "COLLADA/KML/glTF") { nLayers.push(new CitydbKmlLayer(options)); } else { nLayers.push(new Cesium3DTilesDataLayer(options)); } index++; layerConfigString = this.getUrlParaValue('layer_' + index, url, CitydbUtil); } return nLayers; } get urlDictionary(): any { return this._urlDictionary; } set urlDictionary(value: any) { this._urlDictionary = value; } }
the_stack
import { JSONSchema4, JSONSchema6, JSONSchema7 } from 'json-schema'; export = merger; type JSONSchema = JSONSchema4 | JSONSchema6 | JSONSchema7; type JSONSchema46 = JSONSchema4 | JSONSchema6; declare function merger<T extends JSONSchema>(rootSchema: T, options: merger.Options<T> & { ignoreAdditionalProperties: true }): T; declare function merger(rootSchema: JSONSchema4, options?: merger.Options<JSONSchema4>): JSONSchema4; declare function merger(rootSchema: JSONSchema6, options?: merger.Options<JSONSchema6>): JSONSchema6; declare function merger(rootSchema: JSONSchema7, options?: merger.Options<JSONSchema7>): JSONSchema7; declare function merger(rootSchema: JSONSchema46, options?: merger.Options<JSONSchema46>): JSONSchema46; declare function merger(rootSchema: JSONSchema, options?: merger.Options): JSONSchema; declare namespace merger { interface Options<Schema extends JSONSchema = JSONSchema> { /** * **ignoreAdditionalProperties** default **false** * * Allows you to combine schema properties even though some schemas have * `additionalProperties: false` This is the most common issue people * face when trying to expand schemas using allOf and a limitation of * the json schema spec. Be aware though that the schema produced will * allow more than the original schema. But this is useful if just want * to combine schemas using allOf as if additionalProperties wasn't * false during the merge process. The resulting schema will still get * additionalProperties set to false. */ ignoreAdditionalProperties?: boolean | undefined; /** * **resolvers** Object * * Override any default resolver like this: * * ```js * mergeAllOf(schema, { * resolvers: { * title: function(values, path, mergeSchemas, options) { * // choose what title you want to be used based on the conflicting values * // resolvers MUST return a value other than undefined * } * } * }) * ``` * * The function is passed: * * - **values** an array of the conflicting values that need to be * resolved * - **path** an array of strings containing the path to the position in * the schema that caused the resolver to be called (useful if you use * the same resolver for multiple keywords, or want to implement * specific logic for custom paths) * - **mergeSchemas** a function you can call that merges an array of * schemas * - **options** the options mergeAllOf was called with */ resolvers?: Partial<Resolvers<Schema>> & { /** * ### Default resolver * You can set a default resolver that catches any unknown keyword. * Let's say you want to use the same strategy as the ones for the * meta keywords, to use the first value found. You can accomplish * that like this: * * ```js * mergeJsonSchema({ * ... * }, { * resolvers: { * defaultResolver: mergeJsonSchema.options.resolvers.title * } * }) * ``` */ defaultResolver?(values: any[], path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): any; } | undefined; } type MergeSchemas = <T extends JSONSchema>(schemas: ReadonlyArray<T>) => T; type MergeChildSchemas = <T extends JSONSchema>(schemas: ReadonlyArray<T>, childSchemaName: string) => T; interface Resolvers<Schema extends JSONSchema = JSONSchema> { $id( values: Array<Extract<Schema, { $id?: any }>['$id']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>, ): NonNullable<Extract<Schema, { $id?: any }>['$id']>; $ref(values: Array<Schema['$ref']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['$ref']>; $schema(values: Array<Schema['$schema']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['$schema']>; additionalItems(values: Array<Schema['additionalItems']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['additionalItems']>; additionalProperties(values: Array<Schema['additionalProperties']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['additionalProperties']>; anyOf(values: Array<Schema['anyOf']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['anyOf']>; contains( values: Array<Extract<Schema, { contains?: any }>['contains']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>, ): NonNullable<Extract<Schema, { contains?: any }>['contains']>; default(values: Array<Schema['default']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['default']>; definitions(values: Array<Schema['definitions']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['definitions']>; dependencies(values: Array<Schema['dependencies']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['dependencies']>; description(values: Array<Schema['description']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['description']>; enum(values: Array<Schema['enum']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['enum']>; examples( values: Array<Extract<Schema, { examples?: any }>['examples']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>, ): NonNullable<Extract<Schema, { examples?: any }>['examples']>; exclusiveMaximum(values: Array<Schema['exclusiveMaximum']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['exclusiveMaximum']>; exclusiveMinimum(values: Array<Schema['exclusiveMinimum']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['exclusiveMinimum']>; items(values: Array<Schema['items']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['items']>; maxItems(values: Array<Schema['maxItems']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['maxItems']>; maxLength(values: Array<Schema['maxLength']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['maxLength']>; maxProperties(values: Array<Schema['maxProperties']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['maxProperties']>; maximum(values: Array<Schema['maximum']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['maximum']>; minItems(values: Array<Schema['minItems']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['minItems']>; minLength(values: Array<Schema['minLength']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['minLength']>; minProperties(values: Array<Schema['minProperties']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['minProperties']>; minimum(values: Array<Schema['minimum']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['minimum']>; multipleOf(values: Array<Schema['multipleOf']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['multipleOf']>; not(values: Array<Schema['not']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['not']>; oneOf(values: Array<Schema['oneOf']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['oneOf']>; pattern(values: Array<Schema['pattern']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['pattern']>; /** * ### Combined resolvers * No separate resolver is called for patternProperties and * additionalProperties, only the properties resolver is called. Same * for additionalItems, only items resolver is called. This is because * those keywords need to be resolved together as they affect each * other. * * Those two resolvers are expected to return an object containing the * resolved values of all the associated keywords. The keys must be the * name of the keywords. So the properties resolver need to return an * object like this containing the resolved values for each keyword: * * ```js * { * properties: ..., * patternProperties: ..., * additionalProperties: ..., * } * ``` * * Also the resolve function is not passed **mergeSchemas**, but an * object **mergers** that contains mergers for each of the related * keywords. So properties get passed an object like this: * * ```js * var mergers = { * properties: function mergeSchemas(schemas, childSchemaName){...}, * patternProperties: function mergeSchemas(schemas, childSchemaName){...}, * additionalProperties: function mergeSchemas(schemas){...}, * } * ``` * * Some of the mergers requires you to supply a string of the name or * index of the subschema you are currently merging. This is to make * sure the path passed to child resolvers are correct. */ properties( values: Schema[], path: string[], mergers: { properties: MergeChildSchemas; patternProperties: MergeChildSchemas; additionalProperties: MergeSchemas; }, options: Options<Schema>, ): Pick<Schema, 'properties' | 'patternProperties' | 'additionalProperties'>; propertyNames( values: Array<Extract<Schema, { propertyNames?: any }>['propertyNames']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>, ): NonNullable<Extract<Schema, { propertyNames?: any }>['propertyNames']>; required( values: Array<Schema['required']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>, ): NonNullable<Schema['required']>; title(values: Array<Schema['title']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['title']>; type(values: Array<Schema['type']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['type']>; uniqueItems(values: Array<Schema['uniqueItems']>, path: string[], mergeSchemas: MergeSchemas, options: Options<Schema>): NonNullable<Schema['uniqueItems']>; } const options: { resolvers: Resolvers; }; }
the_stack
import type {Mutable, Proto, ObserverType} from "@swim/util"; import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component"; import {GestureInputType, GestureInput} from "./GestureInput"; import {View} from "../"; // forward import /** @internal */ export type MemberGestureView<O, K extends keyof O> = O[K] extends Gesture<any, infer V> ? V : never; /** @internal */ export type GestureView<G extends Gesture<any, any>> = G extends Gesture<any, infer V> ? V : never; /** @public */ export type GestureMethod = "auto" | "pointer" | "touch" | "mouse"; /** @public */ export interface GestureInit<V extends View = View> extends FastenerInit { extends?: {prototype: Gesture<any, any>} | string | boolean | null; method?: GestureMethod; key?: string | boolean; self?: boolean; binds?: boolean; observes?: boolean; willAttachView?(view: V, target: View | null): void; didAttachView?(view: V, target: View | null): void; willDetachView?(view: V): void; didDetachView?(view: V): void; detectView?(view: View): V | null; } /** @public */ export type GestureDescriptor<O = unknown, V extends View = View, I = {}> = ThisType<Gesture<O, V> & I> & GestureInit<V> & Partial<I>; /** @public */ export interface GestureClass<G extends Gesture<any, any> = Gesture<any, any>> extends FastenerClass<G> { } /** @public */ export interface GestureFactory<G extends Gesture<any, any> = Gesture<any, any>> extends GestureClass<G> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): GestureFactory<G> & I; specialize(method: GestureMethod): GestureFactory | null; define<O, V extends View = View>(className: string, descriptor: GestureDescriptor<O, V>): GestureFactory<Gesture<any, V>>; define<O, V extends View = View>(className: string, descriptor: {observes: boolean} & GestureDescriptor<O, V, ObserverType<V>>): GestureFactory<Gesture<any, V>>; define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown} & GestureDescriptor<O, V, I>): GestureFactory<Gesture<any, V> & I>; define<O, V extends View = View, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & GestureDescriptor<O, V, I & ObserverType<V>>): GestureFactory<Gesture<any, V> & I>; <O, V extends View = View>(descriptor: GestureDescriptor<O, V>): PropertyDecorator; <O, V extends View = View>(descriptor: {observes: boolean} & GestureDescriptor<O, V, ObserverType<V>>): PropertyDecorator; <O, V extends View = View, I = {}>(descriptor: {implements: unknown} & GestureDescriptor<O, V, I>): PropertyDecorator; <O, V extends View = View, I = {}>(descriptor: {implements: unknown; observes: boolean} & GestureDescriptor<O, V, I & ObserverType<V>>): PropertyDecorator; } /** @public */ export interface Gesture<O = unknown, V extends View = View> extends Fastener<O> { (): V | null; (view: V | null, targetView?: View | null): O; /** @override */ get fastenerType(): Proto<Gesture<any, any>>; readonly view: V | null; getView(): V; setView(newView: V | null, targetView?: View | null): V | null; /** @protected */ willAttachView(view: V, target: View | null): void; /** @protected */ onAttachView(view: V, target: View | null): void; /** @protected */ didAttachView(view: V, target: View | null): void; /** @protected */ willDetachView(view: V): void; /** @protected */ onDetachView(view: V): void; /** @protected */ didDetachView(view: V): void; /** @internal @protected */ attachEvents(view: V): void; /** @internal @protected */ detachEvents(view: V): void; /** @internal */ readonly inputs: {readonly [inputId: string]: GestureInput | undefined}; readonly inputCount: number; getInput(inputId: string | number): GestureInput | null; /** @internal */ createInput(inputId: string, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): GestureInput; /** @internal */ getOrCreateInput(inputId: string | number, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): GestureInput; /** @internal */ clearInput(input: GestureInput): void; /** @internal */ clearInputs(): void; /** @internal */ bindView(view: View, target?: View | null): void; /** @internal */ unbindView(view: View): void; detectView(view: View): V | null; /** @internal */ viewWillUnmount(view: V): void; /** @protected @override */ onMount(): void; /** @internal */ get key(): string | undefined; // optional prototype field /** @internal */ get self(): boolean | undefined; // optional prototype property /** @internal */ get binds(): boolean | undefined; // optional prototype property /** @internal */ get observes(): boolean | undefined; // optional prototype property /** @internal @override */ get lazy(): boolean; // prototype property /** @internal @override */ get static(): string | boolean; // prototype property } /** @public */ export const Gesture = (function (_super: typeof Fastener) { const Gesture: GestureFactory = _super.extend("Gesture"); Object.defineProperty(Gesture.prototype, "fastenerType", { get: function (this: Gesture): Proto<Gesture<any, any>> { return Gesture; }, configurable: true, }); Gesture.prototype.getView = function <V extends View>(this: Gesture<unknown, V>): V { const view = this.view; if (view === null) { throw new TypeError("null " + this.name + " view"); } return view; }; Gesture.prototype.setView = function <V extends View>(this: Gesture<unknown, V>, newView: V | null, target?: View | null): V | null { const oldView = this.view; if (oldView !== newView) { if (oldView !== null) { this.willDetachView(oldView); (this as Mutable<typeof this>).view = null; this.onDetachView(oldView); this.didDetachView(oldView); } if (newView !== null) { if (target === void 0) { target = null; } this.willAttachView(newView, target); (this as Mutable<typeof this>).view = newView; this.onAttachView(newView, target); this.didAttachView(newView, target); } } return oldView; }; Gesture.prototype.willAttachView = function <V extends View>(this: Gesture<unknown, V>, view: V, target: View | null): void { // hook }; Gesture.prototype.onAttachView = function <V extends View>(this: Gesture<unknown, V>, view: V, target: View | null): void { this.attachEvents(view); if (this.observes === true) { view.observe(this as ObserverType<V>); } }; Gesture.prototype.didAttachView = function <V extends View>(this: Gesture<unknown, V>, view: V, target: View | null): void { // hook }; Gesture.prototype.willDetachView = function <V extends View>(this: Gesture<unknown, V>, view: V): void { // hook }; Gesture.prototype.onDetachView = function <V extends View>(this: Gesture<unknown, V>, view: V): void { this.clearInputs(); if (this.observes === true) { view.unobserve(this as ObserverType<V>); } this.detachEvents(view); }; Gesture.prototype.didDetachView = function <V extends View>(this: Gesture<unknown, V>, view: V): void { // hook }; Gesture.prototype.attachEvents = function <V extends View>(this: Gesture<unknown, V>, view: V): void { // hook }; Gesture.prototype.detachEvents = function <V extends View>(this: Gesture<unknown, V>, view: V): void { // hook }; Gesture.prototype.getInput = function (this: Gesture, inputId: string | number): GestureInput | null { if (typeof inputId === "number") { inputId = "" + inputId; } const input = this.inputs[inputId]; return input !== void 0 ? input : null; }; Gesture.prototype.createInput = function (this: Gesture, inputId: string, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): GestureInput { return new GestureInput(inputId, inputType, isPrimary, x, y, t); }; Gesture.prototype.getOrCreateInput = function (this: Gesture, inputId: string | number, inputType: GestureInputType, isPrimary: boolean, x: number, y: number, t: number): GestureInput { if (typeof inputId === "number") { inputId = "" + inputId; } const inputs = this.inputs as {[inputId: string]: GestureInput | undefined}; let input = inputs[inputId]; if (input === void 0) { input = this.createInput(inputId, inputType, isPrimary, x, y, t); inputs[inputId] = input; (this as Mutable<typeof this>).inputCount += 1; } return input; }; Gesture.prototype.clearInput = function (this: Gesture, input: GestureInput): void { const inputs = this.inputs as {[inputId: string]: GestureInput | undefined}; delete inputs[input.inputId]; (this as Mutable<typeof this>).inputCount -= 1; }; Gesture.prototype.clearInputs = function (this: Gesture): void { (this as Mutable<typeof this>).inputs = {}; (this as Mutable<typeof this>).inputCount = 0; }; Gesture.prototype.bindView = function <V extends View>(this: Gesture<unknown, V>, view: View, target?: View | null): void { if (this.binds && this.view === null) { const newView = this.detectView(view); if (newView !== null) { this.setView(newView, target); } } }; Gesture.prototype.unbindView = function <V extends View>(this: Gesture<unknown, V>, view: View): void { if (this.binds && this.view === view) { this.setView(null); } }; Gesture.prototype.detectView = function <V extends View>(this: Gesture<unknown, V>, view: View): V | null { if (this.key !== void 0 && this.key === view.key) { return view as V; } return null; }; Gesture.prototype.viewWillUnmount = function (this: Gesture, view: View): void { this.clearInputs(); }; Gesture.prototype.onMount = function (this: Gesture): void { _super.prototype.onMount.call(this); if (this.self === true && this.owner instanceof View) { this.setView(this.owner); } }; Object.defineProperty(Gesture.prototype, "lazy", { get: function (this: Gesture): boolean { return false; }, configurable: true, }); Object.defineProperty(Gesture.prototype, "static", { get: function (this: Gesture): string | boolean { return true; }, configurable: true, }); Gesture.construct = function <G extends Gesture<any, any>>(gestureClass: {prototype: G}, gesture: G | null, owner: FastenerOwner<G>): G { if (gesture === null) { gesture = function (view?: GestureView<G> | null, targetView?: View | null): GestureView<G> | null | FastenerOwner<G> { if (view === void 0) { return gesture!.view; } else { gesture!.setView(view, targetView); return gesture!.owner; } } as G; delete (gesture as Partial<Mutable<G>>).name; // don't clobber prototype name Object.setPrototypeOf(gesture, gestureClass.prototype); } gesture = _super.construct(gestureClass, gesture, owner) as G; (gesture as Mutable<typeof gesture>).view = null; (gesture as Mutable<typeof gesture>).inputs = {}; (gesture as Mutable<typeof gesture>).inputCount = 0; return gesture; }; Gesture.specialize = function (method: GestureMethod): GestureFactory | null { return null; }; Gesture.define = function <O, V extends View>(className: string, descriptor: GestureDescriptor<O, V>): GestureFactory<Gesture<any, V>> { let superClass = descriptor.extends as GestureFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; let method = descriptor.method; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.method; if (descriptor.key === true) { Object.defineProperty(descriptor, "key", { value: className, configurable: true, }); } else if (descriptor.key === false) { Object.defineProperty(descriptor, "key", { value: void 0, configurable: true, }); } if (method === void 0) { method = "auto"; } if (superClass === void 0 || superClass === null) { superClass = Gesture.specialize(method); } if (superClass === null) { superClass = this; } const gestureClass = superClass.extend(className, descriptor); gestureClass.construct = function (gestureClass: {prototype: Gesture<any, any>}, gesture: Gesture<O, V> | null, owner: O): Gesture<O, V> { gesture = superClass!.construct(gestureClass, gesture, owner); if (affinity !== void 0) { gesture.initAffinity(affinity); } if (inherits !== void 0) { gesture.initInherits(inherits); } return gesture; }; return gestureClass; }; return Gesture; })(Fastener);
the_stack
import rimraf = require('rimraf'); import { Semver, SemverRange } from 'sver'; import fs = require('graceful-fs'); import path = require('path'); import mkdirp = require('mkdirp'); import { PackageName, ExactPackage, PackageConfig, ProcessedPackageConfig, parsePackageName, processPackageConfig, overridePackageConfig, serializePackageConfig } from './package'; import { readJSON, JspmError, JspmUserError, sha256, md5, encodeInvalidFileChars, bold, isWindows, winSepRegEx, highlight, underline, hasProperties } from '../utils/common'; import { readJSONStyled, writeJSONStyled, defaultStyle } from '../config/config-file'; import Cache from '../utils/cache'; import globalConfig from '../config/global-config-file'; import { Logger, input, confirm } from '../project'; import { resolveSource, downloadSource } from '../install/source'; import FetchClass, { Fetch, GetCredentials, Credentials } from './fetch'; import { convertCJSPackage, convertCJSConfig } from '../compile/cjs-convert'; import { runBinaryBuild } from './binary-build'; import { Readable } from 'stream'; const VerifyState = { NOT_INSTALLED: 0, INVALID: 1, HASH_VALID: 2, VERIFIED_VALID: 3 }; export interface LookupData { meta: any, redirect?: string, versions?: { [name: string]: { resolved: Resolved | void, meta?: any } } } export interface Resolved { version?: string, source?: string, override?: PackageConfig, deprecated?: string } export interface SourceInfo { source: string, opts: any } export interface PublishOptions { tag?: string; access?: string; otp?: string; } export interface RegistryEndpoint { configure?: () => Promise<void>; dispose: () => Promise<void>; auth: (url: URL, method: string, credentials: Credentials, unauthorizedHeaders?: Record<string, string>) => Promise<void | boolean>; lookup: (pkgName: string, versionRange: SemverRange, lookup: LookupData) => Promise<void | boolean>; resolve?: (pkgName: string, version: string, lookup: LookupData) => Promise<void | boolean>; publish?: (packagePath: string, pjson: any, tarStream: Readable, options: PublishOptions) => Promise<void>; } export interface RegistryEndpointConstructable { new(utils: EndpointUtils, config: any): RegistryEndpoint; } export interface EndpointUtils { encodeVersion: (version: string) => string; JspmUserError: typeof JspmUserError; log: Logger; input: input; confirm: confirm; bold: typeof bold; highlight: typeof highlight; underline: typeof underline; globalConfig: typeof globalConfig; fetch: Fetch; getCredentials: GetCredentials; } export interface Registry { handler: RegistryEndpointConstructable | string; config: any; } export interface ConstructorOptions { cacheDir: string, timeouts: { resolve: number, download: number }, defaultRegistry: string, log: Logger, input: input, confirm: confirm, Cache: typeof Cache, userInput: boolean, offline: boolean, preferOffline: boolean, strictSSL: boolean, fetch: FetchClass, registries: {[name: string]: Registry} } export default class RegistryManager { userInput: boolean; offline: boolean; preferOffline: boolean; timeouts: { resolve: number, download: number }; cacheDir: string; defaultRegistry: string; // getEndpoint: (string) => { endpoint: RegistryEndpoint, cache: Cache }; cache: Cache; verifiedCache: { [hash: string]: number }; endpoints: Map<string,{ endpoint: RegistryEndpoint, cache: Cache }>; util: EndpointUtils; instanceId: number; strictSSL: boolean; fetch: FetchClass; registries: {[name: string]: Registry}; constructor ({ cacheDir, timeouts, Cache, userInput, offline, preferOffline, strictSSL, defaultRegistry, log, input, confirm, fetch, registries }: ConstructorOptions) { this.userInput = userInput; this.offline = offline; this.preferOffline = preferOffline; this.cacheDir = cacheDir; this.strictSSL = strictSSL; this.timeouts = timeouts; this.defaultRegistry = defaultRegistry; this.instanceId = Math.round(Math.random() * 10**10); this.registries = registries; this.util = { encodeVersion: encodeInvalidFileChars, JspmUserError, log, input, confirm, bold, highlight, underline, globalConfig, fetch: fetch.fetch.bind(fetch), getCredentials: fetch.getCredentials.bind(fetch) }; this.fetch = fetch; // note which installs have been verified in this session // so we only have to perform verification once per package this.verifiedCache = {}; this.endpoints = new Map<string, { endpoint: RegistryEndpoint, cache: Cache }>(); this.cache = new Cache(path.resolve(cacheDir, 'pcfg')); mkdirp.sync(path.resolve(cacheDir, 'packages')); } loadEndpoints() { Object.keys(this.registries).forEach((registryName) => { if (registryName === 'jspm') return; try { this.getEndpoint(registryName); } catch (err) { if (err && err.code === 'REGISTRY_NOT_FOUND') this.util.log.warn(err.message.substr(err.message.indexOf('\n')).trim()); else throw err; } }); } getEndpoint (name) { let endpointEntry = this.endpoints.get(name); if (endpointEntry) return endpointEntry; // config returned by config get is a new object owned by us const registry = this.registries[name]; const config = registry.config; if (config.strictSSL !== 'boolean') config.strictSSL = this.strictSSL; config.timeout = this.timeouts.resolve; config.userInput = this.userInput; config.offline = this.offline; config.preferOffline = this.preferOffline; let EndpointConstructor: RegistryEndpointConstructable; if (typeof registry.handler === "string") { try { EndpointConstructor = require(registry.handler) as RegistryEndpointConstructable; } catch (e) { if (e && e.code === 'MODULE_NOT_FOUND') { if (e.message && e.message.indexOf(registry.handler) !== -1) { this.util.log.warn(`Registry module '${registry.handler}' not found loading package ${bold(name)}. This may be from a previous jspm version and can be removed with ${bold(`jspm config --unset registries.${name}`)}.`); return; } else { throw new JspmError(`Error loading registry ${bold(name)} from module '${registry.handler}'.`, 'REGISTRY_LOAD_ERROR', e); } } else { throw e; } } } else { EndpointConstructor = registry.handler; } const endpoint = new EndpointConstructor(this.util, config); const cache = new Cache(path.resolve(this.cacheDir, 'registry_cache', name)); endpointEntry = { endpoint, cache }; this.endpoints.set(name, endpointEntry); return endpointEntry; } dispose () { return Promise.all(Array.from(this.endpoints.values()).map(entry => entry.endpoint.dispose ? entry.endpoint.dispose() : undefined)); } async configure (registryName: string) { const { endpoint } = this.getEndpoint(registryName); if (!endpoint.configure) throw new JspmUserError(`The ${registryName} registry doesn't have any configuration hook.`); await endpoint.configure(); } async auth (url: URL, method: string, credentials: Credentials, unauthorizedHeaders?: Record<string, string>): Promise<string> { for (let [registry, { endpoint }] of this.endpoints.entries()) { if (!endpoint.auth) continue; if (await endpoint.auth(url, method, credentials, unauthorizedHeaders)) return registry; } return undefined; } async resolve (pkg: PackageName, override: ProcessedPackageConfig | void, edge = false): Promise<{ pkg: ExactPackage, target: PackageName, source: string, override: ProcessedPackageConfig | void, deprecated: string }> { let registry = pkg.registry || this.defaultRegistry; let { endpoint, cache } = this.getEndpoint(registry); let resolveRange = new SemverRange(pkg.version || '*'); let lookup: LookupData, resolvedVersion: string, redirect: string, resolved: Resolved; try { // loop over any redirects while (true) { lookup = await cache.getUnlocked(pkg.name, this.timeouts.resolve); if (resolveRange.isExact) { resolvedVersion = resolveRange.version.toString(); lookup = lookup || { versions: {}, meta: {} }; } else if (lookup && (this.offline || this.preferOffline)) { if (lookup.redirect) { redirect = lookup.redirect; } else { let versionList = Object.keys(lookup.versions); resolvedVersion = resolveRange.bestMatch(versionList, edge); if (resolvedVersion === undefined && edge === false) resolvedVersion = resolveRange.bestMatch(versionList, true); if (resolvedVersion !== undefined) resolvedVersion = resolvedVersion.toString(); } } if (resolvedVersion === undefined && redirect === undefined) { // no resolution available offline if (this.offline) return; const unlock = await cache.lock(pkg.name, this.timeouts.resolve); try { // cache could have been written while we were getting the lock, although don't bother rechecking resolved as small benefit lookup = await cache.get(pkg.name) || { versions: {}, meta: {} }; const logEnd = this.util.log.taskStart(`Looking up ${this.util.highlight(pkg.name)}`); let changed; try { changed = await endpoint.lookup(pkg.name, resolveRange, lookup); } finally { logEnd(); } logEnd(); if (changed && hasProperties(lookup.versions)) cache.setUnlock(pkg.name, lookup).catch(() => {}); else unlock().catch(() => {}); } catch (e) { unlock().catch(() => {}); throw e; } } if (lookup.redirect) redirect = lookup.redirect; if (redirect) { var redirects = redirects || []; redirects.push(redirect); if (redirects.indexOf(redirect) !== redirects.length - 1) throw new JspmUserError(`Circular redirect during lookup - ${redirects.join(' -> ')}.`); // loop while redirecting let redirectPkg = parsePackageName(redirect); pkg = redirectPkg; ({ endpoint, cache } = this.getEndpoint(registry = pkg.registry)); } else { if (resolvedVersion === undefined) { const versionList = Object.keys(lookup.versions); resolvedVersion = resolveRange.bestMatch(versionList, edge); if (resolvedVersion === undefined && edge === false) resolvedVersion = resolveRange.bestMatch(versionList, true); if (resolvedVersion !== undefined) resolvedVersion = resolvedVersion.toString(); } // 404 if (!resolvedVersion) return; let version = lookup.versions[resolvedVersion]; if ((this.preferOffline || this.offline) && version && version.resolved) { resolved = version.resolved; } else { if (this.offline) return; // this could result in a cache change... but it's local so we don't lock before we start const logEnd = this.util.log.taskStart(`Resolving ${this.util.highlight(`${pkg.name}@${resolvedVersion}`)}`); let changed; try { changed = await endpoint.resolve(pkg.name, resolvedVersion, lookup); } finally { logEnd(); } if (changed) { version = lookup.versions[resolvedVersion]; if (!version) return; resolved = <Resolved>version.resolved; // cache update individual resolve (async () => { const unlock = await cache.lock(pkg.name, this.timeouts.resolve); await cache.set(pkg.name, lookup); return unlock(); })().catch(() => {}); } else if (!version) { return; } else { resolved = <Resolved>version.resolved; } if (!resolved) throw new Error(`jspm registry endpoint for ${bold(registry)} did not properly resolve ${highlight(pkg.name)}.`); } break; } } } catch (e) { if (redirects) e.redirects = redirects; throw e; } let resolvedOverride; if (resolved.override) { resolvedOverride = processPackageConfig(resolved.override, true, override && override.registry); if (override) ({ config: override } = overridePackageConfig(resolvedOverride, override)); else override = resolvedOverride; } return { pkg: <ExactPackage>{ registry, name: pkg.name, version: resolved.version || resolvedVersion, semver: new Semver(resolvedVersion) }, target: redirects ? <PackageName>{ registry, name: pkg.name, version: pkg.version } : pkg, source: resolved.source, override, deprecated: resolved.deprecated }; } async resolveSource (source: string, packagePath: string, projectPath: string): Promise<string> { if (source.startsWith('link:') || source.startsWith('file:') || source.startsWith('git+file:')) { let sourceProtocol = source.substr(0, source[0] === 'g' ? 9 : 5); let sourcePath = path.resolve(source.substr(source[0] === 'g' ? 9 : 5)); // relative file path installs that are not for the top-level project are relative to their package real path if (packagePath !== process.cwd()) { if ((isWindows && (source[0] === '/' || source[0] === '\\')) || sourcePath[0] === '.' && (sourcePath[1] === '/' || sourcePath[1] === '\\' || ( sourcePath[1] === '.' && (sourcePath[2] === '/' || sourcePath[2] === '\\')))) { const realPackagePath = await new Promise<string>((resolve, reject) => fs.realpath(packagePath, (err, realpath) => err ? reject(err) : resolve(realpath))); sourcePath = path.resolve(realPackagePath, sourcePath); } } // if a file: install and it is a directory then it is a link: install if (source.startsWith('file:')) { try { const stats = fs.statSync(sourcePath); if (stats.isDirectory()) sourceProtocol = 'link:'; } catch (e) { if (e && e.code === 'ENOENT') throw new JspmUserError(`Path ${sourcePath} is not a valid file or directory.`); throw e; } } sourcePath = path.relative(projectPath, sourcePath) + '/'; if (isWindows) sourcePath = sourcePath.replace(winSepRegEx, '/'); source = sourceProtocol + sourcePath; } if (this.offline) return source; return resolveSource(this.util.log, this.fetch, source, this.timeouts.resolve); } async verifyInstallDir (dir: string, verifyHash: string, fullVerification: boolean): Promise<number> { const cachedState = this.verifiedCache[verifyHash]; if (cachedState !== undefined && (cachedState !== VerifyState.HASH_VALID || !fullVerification)) return cachedState; const installFile = path.resolve(dir, '.jspm'); const jspmJson = await readJSON(installFile); if (!jspmJson) return this.verifiedCache[verifyHash] = VerifyState.NOT_INSTALLED; if (typeof jspmJson.mtime !== 'number' || jspmJson.hash !== verifyHash) return this.verifiedCache[verifyHash] = VerifyState.INVALID; // if not doing full verification for perf, stop here if (!fullVerification) return this.verifiedCache[verifyHash] = VerifyState.HASH_VALID; // mtime check (skipping .jspm file) let failure = false; await dirWalk(dir, async (filePath, stats) => { if (filePath === installFile) return; if (stats.mtimeMs > jspmJson.mtime) { failure = true; return true; } }); return this.verifiedCache[verifyHash] = failure ? VerifyState.INVALID : VerifyState.VERIFIED_VALID; /* let fileHashes = await Promise.all(fileList.map(getFileHash)); let installedDirHash = sha256(fileHashes.sort().join('')); // hash match -> update the mtime in the install file so we dont check next time if (installedDirHash === dirHash) { await new Promise((resolve, reject) => { fs.writeFile(installFile, mtime + '\n' + hash + '\n' + dirHash, err => err ? reject(err) : resolve()) }); return true; }*/ } // on verification failure, we remove the directory and redownload // moving to a tmp location can be done during the verificationFailure call, to diff and determine route forward // if deciding to checkout, "ensureInstall" operation is cancelled by returning true // build support will be added to build into a newly prefixed folder, with build as a boolean argument async ensureInstall (source: string, override: ProcessedPackageConfig | void, verificationFailure: (dir: string) => Promise<boolean>, fullVerification: boolean = false): Promise<{ config: ProcessedPackageConfig, override: ProcessedPackageConfig | void, dir: string, hash: string, changed: boolean }> { let sourceHash = sha256(source); var { config = undefined, hash = undefined }: { config: ProcessedPackageConfig, hash: string } = await this.cache.getUnlocked(sourceHash, this.timeouts.download) || {}; if (config) { config = processPackageConfig(<any>config); if (override) { ({ config, override } = overridePackageConfig(config, override)); hash = sourceHash + (override ? md5(JSON.stringify(override)) : ''); } convertCJSConfig(config); var dir = path.join(this.cacheDir, 'packages', hash); const verifyState = await this.verifyInstallDir(dir, hash, fullVerification); if (verifyState > VerifyState.INVALID) return { config, override, dir, hash, changed: false }; else if (verifyState !== VerifyState.NOT_INSTALLED && await verificationFailure(dir)) return; } if (this.offline) throw new JspmUserError(`Package is not available for offline install.`); let unlock = await this.cache.lock(sourceHash, this.timeouts.download); try { // could have been a write while we were getting the lock if (!config) { var { config = undefined, hash = undefined }: { config: ProcessedPackageConfig, hash: string } = await this.cache.get(sourceHash) || {}; if (config) { config = processPackageConfig(<any>config); if (override) { ({ config, override } = overridePackageConfig(config, override)); hash = sourceHash + (override ? md5(JSON.stringify(override)) : ''); } convertCJSConfig(config); var dir = path.join(this.cacheDir, 'packages', hash); const verifyState = await this.verifyInstallDir(dir, hash, fullVerification); if (verifyState > VerifyState.INVALID) return { config, override, dir, hash, changed: false }; else if (verifyState !== VerifyState.NOT_INSTALLED && await verificationFailure(dir)) return; } } // if we dont know the config then we dont know the canonical override (and hence hash) // so we download to a temporary folder first if (!config) dir = path.join(this.cacheDir, 'tmp', sha256(Math.random().toString())); await new Promise((resolve, reject) => rimraf(dir, err => err ? reject(err) : resolve())); await new Promise((resolve, reject) => mkdirp(dir, err => err ? reject(err) : resolve())); if (this.offline) throw new JspmUserError(`Source ${source} is not available offline.`); // if source is linked, can return the linked dir directly await downloadSource(this.util.log, this.fetch, source, dir, this.timeouts.download); const logEnd = this.util.log.taskStart('Finalizing ' + highlight(source)); try { let pjsonPath = path.resolve(dir, 'package.json'); let { json: pjson, style } = await readJSONStyled(pjsonPath); if (!pjson) pjson = {}; if (!config) { let pjsonConfig = processPackageConfig(pjson); const serializedConfig = serializePackageConfig(pjsonConfig, this.defaultRegistry); if (override) ({ config, override } = overridePackageConfig(pjsonConfig, override)); else config = pjsonConfig; convertCJSConfig(config); hash = sourceHash + (override ? md5(JSON.stringify(override)) : ''); await Promise.all([ this.cache.set(sourceHash, { config: serializedConfig, hash }), // move the tmp folder to the known hash now (async () => { const toDir = path.join(this.cacheDir, 'packages', hash); await new Promise((resolve, reject) => rimraf(toDir, err => err ? reject(err) : resolve())); await new Promise((resolve, reject) => { fs.rename(dir, dir = toDir, err => err ? reject(err) : resolve()); }); })() ]); pjsonPath = path.resolve(dir, 'package.json'); } await writeJSONStyled(pjsonPath, Object.assign(pjson, serializePackageConfig(config)), style || defaultStyle); await runBinaryBuild(this.util.log, dir, pjson.name, pjson.scripts); // run package conversion // (on any subfolder containing a "type": "commonjs") await convertCJSPackage(this.util.log, dir, config.name, config, this.defaultRegistry); var mtime = await new Promise((resolve, reject) => fs.stat(pjsonPath, (err, stats) => err ? reject(err) : resolve(stats.mtimeMs))); // todo: diffs for invalid? // const fileHashes = await calculateFileHashes(dir); // will be useful for avoiding mistaken mtime bumps when viewing await new Promise((resolve, reject) => { fs.writeFile(path.join(dir, '.jspm'), JSON.stringify({ mtime, hash }), err => err ? reject(err) : resolve()) }); this.verifiedCache[hash] = VerifyState.VERIFIED_VALID; return { config, override, dir, hash, changed: true }; } finally { logEnd(); } } finally { unlock(); } } async publish (packagePath: string, registry: string, pjson: any, tarStream: Readable, opts: PublishOptions) { const { endpoint } = this.getEndpoint(registry); if (!endpoint.publish) throw new JspmUserError(`Registry ${highlight(pjson.registry)} does not support publishing.`); const logEnd = this.util.log.taskStart(`Publishing ${this.util.highlight(`${registry}:${pjson.name}@${pjson.version}`)}`); try { await endpoint.publish(packagePath, pjson, tarStream, opts); } finally { logEnd(); } } } function dirWalk (dir: string, visit: (filePath: string, stats, files?: string[]) => void | boolean | Promise<void | boolean>) { return new Promise((resolve, reject) => { let errored = false; let cnt = 0; visitFileOrDir(path.resolve(dir)); function handleError (err) { if (!errored) { errored = true; reject(err); } } function visitFileOrDir (fileOrDir) { cnt++; fs.stat(fileOrDir, async (err, stats) => { if (err || errored) return handleError(err); try { if (await visit(fileOrDir, stats)) return resolve(); } catch (err) { return handleError(err); } if (stats.isDirectory()) { fs.readdir(fileOrDir, (err, paths) => { if (err || errored) return handleError(err); cnt--; if (paths.length === 0 && !errored && cnt === 0) return resolve(); paths.forEach(fileOrDirPath => visitFileOrDir(path.resolve(fileOrDir, fileOrDirPath))); }); } else if (!errored && --cnt === 0) { resolve(); } }); } }); }
the_stack
import { UnionToIntersection } from 'ts-essentials' import type { Expectation } from '../Expectation' import { ExpectedEqual } from '../isEqual/rules' import type { Mock, MockArgs } from '../mocks/types' import type { Newable } from '../types' // registry for validators added by plugins export interface Validators { // (this: Expectation<number>, expected: number) => void } export type ValidatorsFor<T> = __ValidatorsFor<Values<AllValidators<T>>, T> // Distributes validators uniob and filters export type __ValidatorsFor<TValidators, TActual> = UnionToIntersection< TValidators extends [infer A, infer Matchers] ? TActual extends A ? Matchers : // if TActual is exactly `unknown`, we'll allow all matchers for convenience when user calls `expect()` without argument and tests autocomplete. unknown extends TActual ? Matchers : never : never > & { // validators from plugins [P in keyof Validators]: Validators[P] extends (this: Expectation<infer A>, ...args: infer Args) => void ? TActual extends A ? (...args: Args) => void : unknown extends TActual ? (...args: Args) => void : never : never } export type Values<T> = T[keyof T & number] export type ItemOfIterable<T> = Extract<T, Iterable<any>> extends Iterable<infer R> ? R : never // @todo should we extract a type from __Validators of and use it here, turning it into a big intersection type? // We could do without UnionToIntersection then I guess... export type AllValidators<T> = [ [unknown, CommonValidators<T>], [Mock<any[], any>, MockValidators<T>], [number, NumberValidators], [object, ObjectValidators], [any[], ArrayValidators], [Iterable<any>, IterableValidators<ItemOfIterable<T>>], [Promise<unknown>, PromiseValidators], [() => any, FunctionValidators], ] export interface CommonValidators<T> extends BooleanValidators, OptionalValidators { /** * Performs a recursive equality check. Objects are equal if their fields * are equal and they share the same prototype. * * You can use matchers in place of a value. When a matcher is encountered its * internal rules are used instead of the usual checks. * * @param value - value to check against. * * @example * ```ts * expect('foo').toEqual('foo') // Equality check against primitive value * expect([1, { a: 2 }]).toEqual([1, { a: expect.a(Number) }]) // Usage with "a" matcher * expect({ a: 2, b: 2 }).not.toEqual({ a: 2 }) // Negated equality check * ``` */ toEqual(value: ExpectedEqual<T>): void /** * Performs a recursive equality check. Objects are equal if their fields * are equal. Object prototypes are ignored. * * You can use matchers in place of a value. When a matcher is encountered its * internal rules are used instead of the usual checks. * * @param value - value to check against. * * @example * ```ts * class A { * a = 1 * } * * // using toEqual requires matching prototypes * expect(new A()).not.toEqual({ a: 1 }) * // toLooseEqual ignores prototypes and focuses only on the value * expect(new A()).toLooseEqual({ a: 1 }) * ``` */ toLooseEqual(value: any): void /** * Performs a referential equality check using `Object.is`. It is similar to * `===`, with two differences: * * 1. `Object.is(-0, +0)` returns `false` * 2. `Object.is(NaN, NaN)` returns `true` * * This function should be used if you care about object identity rather than * deep equality. * * @param value - value to check against. * * @example * ```ts * const x = {} * expect(x).toReferentiallyEqual(x) * expect({}).not.toReferentiallyEqual(x) * expect(NaN).toReferentiallyEqual(NaN) * ``` */ toReferentiallyEqual(value: T): void /** * Checks if the value is an instance of a provided class or a primitive type. Works as expected with builtin types like strings, numbers, dates. * * 1. `expect.a(MyClass)` - matches `new MyClass`, but not `new Other()` * 2. `expect.a(String)` - matches `"foo"`, but not `123` * * @param clazz - type class or primitive constructor to match against. * @example * ```ts * expect(object).toBeA(MyClass) // checks if object is instance of `MyClass`, but not `Other` * expect(foo).toBeA(String) // checks if foo is instance of string * expect(foo).toBeA(Object) // matches any object (not null) * ``` */ toBeA(clazz: any): void /** * Checks that the value is the same as in the previous test execution. */ toMatchSnapshot(): void } export interface FunctionValidators { /** * Calls the provided function and expects an error to be thrown. The message * of the error is also checked. * * @param message - string or matcher to check the message against. * * @example * ```ts * const doThrow = () => { throw new Error('oops, sorry') } * * expect(() => doThrow()).toThrow('oops') * expect(() => doThrow()).not.toThrow(expect.stringMatching(/end$/)) * ``` */ toThrow(message?: string): void /** * Calls the provided function and expects an error to be thrown. The error's * class and message are also checked. * * @param errorClass - expected class of the thrown error. * @param message - string or matcher to check the message against. * * @example * ```ts * const doThrow = () => { * throw new Error('oops, sorry') * } * * expect(() => doThrow()).toThrow(Error, 'oops') * expect(() => doThrow()).not.toThrow(TypeError) * ``` */ toThrow(errorClass: Newable<Error>, message?: string): void } export interface NumberValidators { /** * Checks if the value is greater than the provided target. * @param target - number to check against. * * @example * ```ts * expect(2).toBeGreaterThan(1) * expect(1).not.toBeGreaterThan(1) * expect(-3).not.toBeGreaterThan(1) * ``` */ toBeGreaterThan(target: number): void /** * Checks if the value is greater than or equal to the provided target. * @param target - number to check against. * * @example * ```ts * expect(2).toBeGreaterThanOrEqualTo(1) * expect(1).toBeGreaterThanOrEqualTo(1) * expect(-3).not.toBeGreaterThanOrEqualTo(1) * ``` */ toBeGreaterThanOrEqualTo(target: number): void /** * Checks if the value is less than the provided target. * @param target - number to check against. * * @example * ```ts * expect(-3).toBeLessThan(1) * expect(1).not.toBeLessThan(1) * expect(2).not.toBeLessThan(1) * ``` */ toBeLessThan(target: number): void /** * Checks if the value is less than or equal the provided target. * @param target - number to check against. * * @example * ```ts * expect(-3).toBeLessThanOrEqualTo(1) * expect(1).toBeLessThanOrEqualTo(1) * expect(2).not.toBeLessThanOrEqualTo(1) * ``` */ toBeLessThanOrEqualTo(target: number): void } export interface BooleanValidators { /** * Checks if the value is truthy. * * @example * ```ts * expect(1).toBeTruthy() * expect(false).not.toBeTruthy() * ``` * * There are six falsy values in JavaScript: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. \ * Everything else is truthy. */ toBeTruthy(): void /** * Checks if the value is falsy. * * @example * ```ts * expect(0).toBeFalsy() * expect(true).not.toBeFalsy() * ``` * * There are six falsy values in JavaScript: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. \ * Everything else is truthy. */ toBeFalsy(): void } export interface OptionalValidators { /** * Checks if the value is different to `undefined` and `null`. * * @example * ```ts * expect(0).toBeDefined() * expect(null).not.toBeDefined() * ``` */ toBeDefined(): void /** * Checks if the value is `undefined` or `null`. * * @example * ```ts * expect(undefined).toBeNullish() * expect(false).not.toBeNullish() * ``` */ toBeNullish(): void } export interface PromiseValidators { /** * Awaits the provided promise and expects it to be rejected. The message * of the error is also checked. * * @param message - string or matcher to check the message against. * @example * ```ts * const promise = Promise.reject(new Error('oops, sorry')) * * await expect(promise).toBeRejected(Error, 'oops') * await expect(promise).not.toBeRejected(TypeError) * ``` */ toBeRejected(message?: string): Promise<void> /** * Awaits the provided promise and expects it to be rejected. The error's * class and message are also checked. * * @param errorClass - expected class of the thrown error. * @param message - string or matcher to check the message against. */ toBeRejected(errorClass: Newable<Error>, message?: string): Promise<void> } export interface MockValidators<T> { /** * Checks if all the expected calls to the mock have been performed. */ toBeExhausted(): void /** * Check if the mock has been called with the provided arguments. * * You can use matchers in place of a value. When a matcher is encountered its * internal rules are used instead of the usual checks. * * @param args - an array of values or matchers to check the mock calls against. */ toHaveBeenCalledWith(args: MockArgs<T>): void /** * Checks the entire history of mock calls. * * You can use matchers in place of a value. When a matcher is encountered its * internal rules are used instead of the usual checks. * * @param args - an array where each item is an array of values or matchers to check the mock call against. */ toHaveBeenCalledExactlyWith(args: MockArgs<T>[]): void } export interface ObjectValidators { /** * Checks if the value is an object containing given key-value pairs. * * @param subset - an object to match against. * * @example * ```ts * expect({ a: 1, b: 2, c: 3 }).toBeAnObjectWith({ b: 2, a: 1 }) * ``` */ toBeAnObjectWith(subset: object): void } export interface ArrayValidators { /** * Checks if the values is an array containing exactly given number of items. * * @param length - expected array length. Can be a matcher. * @example * ```ts * expect([1, 2, 3]).toBeAnArrayOfLength(3) * expect([1, 2, 3]).toBeAnArrayOfLength(expect.numberGreaterThanOrEqualTo(3))) * ``` */ toBeAnArrayOfLength(length: number): void /** * Checks if the value is an array containing all of the provided items. Each expected item must be matched uniquely. * * @param expectedItems - values or matchers to look for in the matched array. Order of the items doesn't matter. * @example * ```ts * expect([1, 2, 3]).toBeAnArrayWith(1) * expect([1]).toBeAnArrayWith(1, 1) // throws b/c a second "1" is missing * ``` */ toBeAnArrayWith(...expectedItems: ReadonlyArray<any>): void } export interface IterableValidators<T> { /** * Checks if the value is an iterable containing all of the provided items. Internally, container is first turned into array and `toBeAnArrayWith` is used for final comparison. * * @param expectedItems - values or matchers to look for in the matched iterable. Order of the items doesn't matter. * @example * ```ts * expect([1, 2, 3]).toBeAContainerWith(1, 2) * ``` */ toBeAContainerWith(...expectedItems: T[]): void }
the_stack
declare const Zotero: any declare const window: any const marker = 'ZotodoMonkeyPatched' function patch(object, method, patcher) { if (object[method][marker]) return object[method] = patcher(object[method]) object[method][marker] = true } function getPref(pref_name: string): any { return Zotero.Prefs.get(`extensions.zotodo.${pref_name}`, true) } function showError(err: string, progWin: object) { show( 'chrome://zotero/skin/cross.png', 'Failed to make task for item!', err, progWin, true ) } function showSuccess(task_data: TaskData, progWin: object) { show( 'chrome://zotero/skin/tick.png', 'Made task for item!', `Created task "${task_data.contents} in project ${task_data.project_name}`, progWin, true ) } function show( icon: string, headline: string, body: string, win?: object, done: boolean = false, duration: number = 3000 ) { const progressWindow = win || new Zotero.ProgressWindow({ closeOnClick: true }) progressWindow.changeHeadline(`Zotodo: ${headline}`, icon) progressWindow.addLines([body], [icon]) if (win == null) { progressWindow.show() } if (done) { progressWindow.startCloseTimer(duration) } return progressWindow } interface ZoteroCreator { firstName: string lastName: string fieldMode: number creatorTypeID: number } interface ZoteroItem { key: string itemType: string libraryID: number id: number itemTypeID: number getField( field: string, unformatted: boolean, includeBaseMapped: boolean ): any getCollections(): number[] getAttachments(): number[] getCreators(): ZoteroCreator[] } class TaskData { public contents: string public note: string = null public due_string: string = null public project_name: string public section_name: string = null public priority: number public label_names: string[] constructor( contents: string, priority: number, project_name: string, label_names: string[] ) { this.contents = contents this.priority = priority this.project_name = project_name this.label_names = label_names } } class TodoistAPI { private token: string = null private projects: Record<string, number> = null private labels: Record<string, number> = null private sections: Record<string, Record<string, number>> = {} constructor(token: string) { this.token = token } public async createTask(task_data: TaskData) { const icon = `chrome://zotero/skin/spinner-16px${ Zotero.hiDPI ? '@2x' : '' }.png` const progWin = show(icon, 'Creating task', 'Making Todoist task for item') if (this.token == null || this.token === '') { this.token = getPref('todoist_token') } const project_id = await this.getProjectId(task_data.project_name, progWin) if (project_id == null) { return } let section_id = null if (task_data.section_name != null) { section_id = await this.getSectionId( task_data.section_name, task_data.project_name, progWin ) if (section_id == null) { return } } const label_ids = [] for (const label_name of task_data.label_names) { const label_id = await this.getLabelId(label_name, progWin) if (label_id == null) { return } label_ids.push(label_id) } const createPayload: { [k: string]: any } = { content: task_data.contents, project_id, priority: task_data.priority, } if (label_ids.length > 0) { createPayload.label_ids = label_ids } if (section_id != null) { createPayload.section_id = section_id } if (task_data.due_string != null) { createPayload.due_string = task_data.due_string } const createHeaders = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const createResponse = await fetch( 'https://api.todoist.com/rest/v1/tasks', { method: 'POST', headers: createHeaders, body: JSON.stringify(createPayload), } ) if (!createResponse.ok) { const err = await createResponse.text() const msg = `Error creating task: ${createResponse.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return } if (task_data.note != null) { const task_id = (await createResponse.json()).id const notePayload = { content: task_data.note, task_id, } const noteHeaders = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const noteResponse = await fetch( 'https://api.todoist.com/rest/v1/comments', { method: 'POST', headers: noteHeaders, body: JSON.stringify(notePayload), } ) if (!noteResponse.ok) { const err = await noteResponse.text() const msg = `Error adding comment: ${noteResponse.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return } } showSuccess(task_data, progWin) } private async getSectionId( section_name: string, project_name: string, progress_win: object ): Promise<number | null> { if (this.sections[project_name] == undefined) { const project_sections = await this.getSections( project_name, progress_win ) if (project_sections == null) { showError('Failed to get sections!', progress_win) return null } this.sections[project_name] = project_sections } if (!(section_name in this.sections[project_name])) { const section_result = await this.createSection( section_name, project_name, progress_win ) if (!section_result) { return null } } return this.sections[project_name][section_name] } private async getProjectId( project_name: string, progress_win: object ): Promise<number | null> { if (this.projects == null) { this.projects = await this.getProjects(progress_win) if (this.projects == null) { showError('Failed to get projects!', progress_win) return null } } if (!(project_name in this.projects)) { const project_result = await this.createProject( project_name, progress_win ) if (!project_result) { return null } } return this.projects[project_name] } private async getLabelId( label_name: string, progress_win: object ): Promise<number | null> { if (this.labels == null) { this.labels = await this.getLabels(progress_win) if (this.labels == null) { showError('Failed to get labels!', progress_win) return null } } if (!(label_name in this.labels)) { const label_result = await this.createLabel(label_name, progress_win) if (!label_result) { return null } } return this.labels[label_name] } private async createSection( section_name: string, project_name: string, progWin: object ): Promise<boolean> { const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const project_id = await this.getProjectId(project_name, progWin) if (project_id == null) { return } const payload = { name: section_name, project_id } const response = await fetch('https://api.todoist.com/rest/v1/sections', { method: 'POST', headers, body: JSON.stringify(payload), }) if (!response.ok) { const err = await response.text() const msg = `Error creating section ${section_name} in project ${project_name}: ${response.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return false } const data = await response.json() this.sections[project_name][data.name] = data.id return true } private async createProject( project_name: string, progWin: object ): Promise<boolean> { const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const payload = { name: project_name } const response = await fetch('https://api.todoist.com/rest/v1/projects', { method: 'POST', headers, body: JSON.stringify(payload), }) if (!response.ok) { const err = await response.text() const msg = `Error creating project ${project_name}: ${response.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return false } const data = await response.json() this.projects[data.name] = data.id return true } private async createLabel( label_name: string, progWin: object ): Promise<boolean> { const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const payload = { name: label_name } const response = await fetch('https://api.todoist.com/rest/v1/labels', { method: 'POST', headers, body: JSON.stringify(payload), }) if (!response.ok) { const err = await response.text() const msg = `Error creating label ${label_name}: ${response.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return false } const data = await response.json() this.labels[data.name] = data.id return true } private async getAll( endpoint: string, progWin: object ): Promise<Record<string, number>> { const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}`, } const response = await fetch(endpoint, { method: 'GET', headers, }) if (!response.ok) { const err = await response.text() const msg = `Error requesting from ${endpoint}: ${response.statusText} ${err}` showError(msg, progWin) Zotero.logError(msg) return null } const data = await response.json() const items: { [k: string]: number } = {} for (const item of data) { items[item.name] = item.id } return items } private async getSections( project_name: string, progWin: object ): Promise<Record<string, number>> { const project_id = await this.getProjectId(project_name, progWin) if (project_id == null) { return } return this.getAll( `https://api.todoist.com/rest/v1/sections?project_id=${project_id}`, progWin ) } private async getProjects(progWin: object): Promise<Record<string, number>> { return this.getAll('https://api.todoist.com/rest/v1/projects', progWin) } private async getLabels(progWin: object): Promise<Record<string, number>> { return this.getAll('https://api.todoist.com/rest/v1/labels', progWin) } } const Zotodo = // tslint:disable-line:variable-name Zotero.Zotodo || new (class { private initialized: boolean = false private todoist: TodoistAPI private notifierCallback: object = { notify(event: string, type: string, ids: number[], _: object) { if (getPref('automatic_add') && type === 'item' && event === 'add') { const items = Zotero.Items.get(ids) .map((item: ZoteroItem) => { item.itemType = Zotero.ItemTypes.getName(item.itemTypeID) return item }) .filter( (item: ZoteroItem) => item.itemType !== 'attachment' && item.itemType !== 'note' ) for (const item of items) { Zotero.log(`Making task for ${JSON.stringify(item)}`) Zotodo.makeTaskForItem(item) } } }, } constructor() { window.addEventListener( 'load',_ => { this.init().catch(err => Zotero.logError(err)) }, false ) } public async openPreferenceWindow(paneID: any, action: any) { const io = { pane: paneID, action } window.openDialog( 'chrome://zotodo/content/options.xul', 'zotodo-options', 'chrome,titlebar,toolbar,centerscreen' + Zotero.Prefs.get('browser.preferences.instantApply', true) ? 'dialog=no' : 'modal', io ) } public async makeTaskForSelectedItems() { const items = Zotero.getActiveZoteroPane() .getSelectedItems() .filter( (item: ZoteroItem) => Zotero.ItemTypes.getName(item.itemTypeID) !== 'attachment' && Zotero.ItemTypes.getName(item.itemTypeID) !== 'note' ) for (const item of items) { this.makeTaskForItem(item) } } private async init() { if (this.initialized) { return } // Get Todoist information const todoist_token: string = getPref('todoist_token') this.todoist = new TodoistAPI(todoist_token) // Register notifier const notifierID = Zotero.Notifier.registerObserver( this.notifierCallback, ['item'] ) // Unregister notifier when window closes to avoid memory leak window.addEventListener( 'unload',_ => { Zotero.Notifier.unregisterObserver(notifierID) }, false ) this.initialized = true } private async makeTaskForItem(item: ZoteroItem) { // Get the current preference values const due_string: string = getPref('due_string') const label_names_string: string = getPref('labels') as string let label_names: string[] = [] if (label_names_string !== '') { label_names = label_names_string.split(',') } const ignore_collections: string[] = (getPref( 'ignore_collections' ) as string).split(',') // Priority is the reverse of what you'd expect from the p1, p2, etc. pattern const priority: number = 5 - getPref('priority') // tslint:disable-line:no-magic-numbers const project_name: string = getPref('project') const section_name: string = getPref('section') const set_due: boolean = getPref('set_due') const include_note: boolean = getPref('include_note') let note_format: string = getPref('note_format') let task_format: string = getPref('task_format') // Is the item in an ignored collection? const item_collections = item .getCollections() .map(id => Zotero.Collections.get(id).name) for (const ignored_name of ignore_collections) { if (item_collections.includes(ignored_name)) { return } } const title: string = item.getField('title', false, true) const abstract: string = item.getField('abstractNote', false, true) const url: string = item.getField('url', false, true) const doi: string = item.getField('DOI', false, true) let pdf_path = '' let pdf_id = -1 const attachments: number[] = item.getAttachments() if (attachments.length > 0) { for (const id of attachments) { const attachment = Zotero.Items.get(id) if (attachment.attachmentContentType === 'application/pdf') { pdf_path = attachment.attachmentPath pdf_id = attachment.key break } } } const author_type_id: number = Zotero.CreatorTypes.getPrimaryIDForType( item.itemTypeID ) const author_names: string[] = item .getCreators() .filter( (creator: ZoteroCreator) => creator.creatorTypeID === author_type_id ) .map( (creator: ZoteroCreator) => `${creator.firstName} ${creator.lastName}` ) let et_al: string = '' if (author_names.length > 0) { et_al = author_names[0] + ' et al.' } const authors = author_names.join(', ') const item_id = item.key let library_path = 'library' if (Zotero.Libraries.get(item.libraryID).libraryType === 'group') { library_path = Zotero.URI.getLibraryPath(item.libraryID) } const select_uri = `zotero://select/${library_path}/items/${item_id}` let citekey = '' if ( typeof Zotero.BetterBibTeX === 'object' && Zotero.BetterBibTeX !== null ) { citekey = Zotero.BetterBibTeX.KeyManager.get( item.getField('id', false, true) ).citekey } const tokens = { title, abstract, url, doi, pdf_path, pdf_id, et_al, authors, item_id, select_uri, citekey, } for (const token_name of Object.keys(tokens)) { const pos_pat = RegExp(`\\?\\$\\{${token_name}\\}:([^?]*)\\?`, 'gm') const neg_pat = RegExp(`!\\$\\{${token_name}\\}:([^!]*)!`, 'gm') const token_defined = tokens[token_name] != null && tokens[token_name] !== '' if (token_defined) { note_format = note_format.replace(pos_pat, '$1') task_format = task_format.replace(pos_pat, '$1') note_format = note_format.replace(neg_pat, '') task_format = task_format.replace(neg_pat, '') } else { note_format = note_format.replace(neg_pat, '$1') task_format = task_format.replace(neg_pat, '$1') note_format = note_format.replace(pos_pat, '') task_format = task_format.replace(pos_pat, '') } } // tslint:disable:no-eval prefer-template const note_contents: string = eval('`' + note_format + '`') const task_contents: string = eval('`' + task_format + '`') // tslint:enable:no-eval prefer-template const task_data = new TaskData( task_contents, priority, project_name, label_names ) if (include_note) { task_data.note = note_contents } if (set_due) { task_data.due_string = due_string } if (section_name !== '') { task_data.section_name = section_name } this.todoist.createTask(task_data) } })() export = Zotodo // otherwise this entry point won't be reloaded: https://github.com/webpack/webpack/issues/156 delete require.cache[module.id]
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsfp_surveyinvite_Information { interface Header extends DevKit.Controls.IHeader { /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** Status of the activity. */ StateCode: DevKit.Controls.OptionSet; } interface tab__9556FAF0_FB19_453F_A229_3F55E2787722_Sections { _D2018D44_DE86_424D_889D_319B33BF6825: DevKit.Controls.Section; Email_Message: DevKit.Controls.Section; } interface tab__9556FAF0_FB19_453F_A229_3F55E2787722 extends DevKit.Controls.ITab { Section: tab__9556FAF0_FB19_453F_A229_3F55E2787722_Sections; } interface Tabs { _9556FAF0_FB19_453F_A229_3F55E2787722: tab__9556FAF0_FB19_453F_A229_3F55E2787722; } interface Body { Tab: Tabs; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.Controls.Lookup; /** Channel through which the survey invitation was sent. */ msfp_channel: DevKit.Controls.OptionSet; /** Content of the email message. */ msfp_emailmessage: DevKit.Controls.String; /** Email to which the survey invitation is sent. */ msfp_inviteemailaddress: DevKit.Controls.String; /** Date when the survey invitation was sent. */ msfp_invitesentdate: DevKit.Controls.Date; /** Status of the survey invitation. */ msfp_invitestatus: DevKit.Controls.OptionSet; /** Stores other survey invitation properties in JSON format. */ msfp_otherproperties: DevKit.Controls.String; /** Name of the respondent */ msfp_respondent: DevKit.Controls.String; /** Unique identifier for the survey in the source application. */ msfp_sourcesurveyidentifier: DevKit.Controls.String; /** Stores the survey associated with the survey invitation. */ msfp_surveyid: DevKit.Controls.Lookup; /** Personalized survey link sent with the invitation. */ msfp_surveyinvitationurl: DevKit.Controls.String; /** Unique identifier of the object with which the activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Reason for the status of the activity. */ StatusCode: DevKit.Controls.OptionSet; /** Subject associated with the activity. */ Subject: DevKit.Controls.String; /** Person who is the receiver of the activity. */ To: DevKit.Controls.Lookup; } } class Formmsfp_surveyinvite_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msfp_surveyinvite_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msfp_surveyinvite_Information */ Body: DevKit.Formmsfp_surveyinvite_Information.Body; /** The Header section of form msfp_surveyinvite_Information */ Header: DevKit.Formmsfp_surveyinvite_Information.Header; } class msfp_surveyinviteApi { /** * DynamicsCrm.DevKit msfp_surveyinviteApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Additional information provided by the external application as JSON. For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Actual duration of the activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Actual end time of the activity. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Actual start time of the activity. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Description of the activity. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Exchange rate for the currency associated with the activitypointer with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Information regarding whether the activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information regarding whether the activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the activitypointer. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Channel through which the survey invitation was sent. */ msfp_channel: DevKit.WebApi.OptionSetValue; /** Context parameters for the invitation. */ msfp_contextparameters: DevKit.WebApi.StringValue; msfp_CustomerVoiceSurveyInvite: DevKit.WebApi.StringValue; /** Content of the email message. */ msfp_emailmessage: DevKit.WebApi.StringValue; /** Email address from which the survey invitation was sent. */ msfp_fromemailaddress: DevKit.WebApi.StringValue; /** Email to which the survey invitation is sent. */ msfp_inviteemailaddress: DevKit.WebApi.StringValue; /** Date when the survey invitation was sent. */ msfp_invitesentdate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Status of the survey invitation. */ msfp_invitestatus: DevKit.WebApi.OptionSetValue; /** Survey invitation status reason. */ msfp_invitestatusreason: DevKit.WebApi.StringValue; /** Date when the survey invitation was updated. */ msfp_inviteupdateddate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msfp_isincentiveEnabled: DevKit.WebApi.BooleanValue; /** Stores other survey invitation properties in JSON format. */ msfp_otherproperties: DevKit.WebApi.StringValue; /** Name of the respondent */ msfp_respondent: DevKit.WebApi.StringValue; /** Unique identifier for the survey in the source application. */ msfp_sourcesurveyidentifier: DevKit.WebApi.StringValue; /** Stores the subject associated with the invitation. */ msfp_subject: DevKit.WebApi.StringValue; /** Stores the survey associated with the survey invitation. */ msfp_surveyid: DevKit.WebApi.LookupValue; /** Personalized survey link sent with the invitation. */ msfp_surveyinvitationurl: DevKit.WebApi.StringValue; /** Unique identifier for Customer Voice unsubscribed recipient associated with Customer Voice survey invite. */ msfp_UnsubscribedRecipientSurveyInviteId: DevKit.WebApi.LookupValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of the activity. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_account_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebooking_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bookableresourcebookingheader_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_bulkoperation_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaign_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_campaignactivity_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contact_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_contract_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlement_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_entitlementtemplate_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_incident_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_new_interactionforemail_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_invoice_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgearticle_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_knowledgebaserecord_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_lead_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreement_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingrule_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_customerasset_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventoryjournal_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_inventorytransfer_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_payment_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentdetail_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentmethod_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_paymentterm_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_playbookinstance_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalbum_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_postalcode_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_processnotes_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_productinventory_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_projectteam_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorder_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingincident_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservice_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_resourceterritory_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rma_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmaproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceipt_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rmasubstatus_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtv_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_shipvia_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroup_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timegroupdetail_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_timeoffrequest_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_warehouse_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorder_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderincident_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderproduct_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservice_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_msdyn_workorderservicetask_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_opportunity_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_quote_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_salesorder_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_site_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_action_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_hostedapplication_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_nonhostedapplication_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_option_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_savedsession_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflowstep_msfp_surveyinvite: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_msfp_surveyinvite: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Scheduled duration of the activity, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Scheduled end time of the activity. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Scheduled start time of the activity. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of an associated service. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the case record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this case. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Status of the activity. */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the activity. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Subject associated with the activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the activitypointer. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace msfp_surveyinvite { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum msfp_channel { /** 647390000 */ Email, /** 647390001 */ Flow } enum msfp_invitestatus { /** 647390005 */ Created, /** 647390008 */ Delayed, /** 647390004 */ Failed, /** 647390000 */ Queued, /** 647390006 */ Read, /** 647390011 */ Reminder_failed, /** 647390012 */ Reminder_in_progress, /** 647390009 */ Reminder_scheduled, /** 647390010 */ Reminder_sent, /** 647390003 */ Responded, /** 647390002 */ Sent, /** 647390013 */ Skipped, /** 647390007 */ Started, /** 647390001 */ UnSubscribed } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open, /** 3 */ Scheduled } enum StatusCode { /** 3 */ Canceled, /** 2 */ Completed, /** 1 */ Open, /** 4 */ Scheduled } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import * as tsa from 'ts-morph'; import { TypeGuards } from 'ts-morph'; import * as ts from 'typescript'; import { getKindName } from 'typescript-ast-util'; import { CodeFix, CodeFixOptions } from '../codeFixes'; import { buildRefactorEditInfo } from '../util'; /** # description declares missing member in a property access expression in some interface or class that the accessed reference implements/extends. Note: TypeScript 3.0 has some declare method and declare property refactors, but it won't declare in object literals # attacks ``` "code": "2339", "message": "Property 'bar' does not exist on type '{ foo: () => number; }'.", ``` # Example: ``` const o = { foo: () => { return 1 } } const val: string[] = o.bar(1, ['w'], true) // <---- will add bar as method of literal object o interface Hello {} const hello: Hello = {} let i: string[] i = hello.world([[1, 2, 3], [4, 5]]) // <----- will add world as method of interface Hello const k = hello.mama(1, 2, 3) + ' how are you?' // will add method mama to interface hello function f(h: Hello) { h.fromFunc = true // will add boolean property fromFunc to interface hello } var x: Date = new Date(hello.timeWhen('born')) // will add method timeWhen to interface Hello class C { hello: Hello m(s: number[]) { this.hello.grasp(s, [false, true]) } // will add method grasp to interface Hello } const notDefined:C const a = notDefined.foof + 9 // will add property foof to class C ``` # TODO: * use ast structures - we are not considering hasQuestion, modifiers, typeparams, etc * Probably we are loosing existing JSdocs ? * generate jsdoc for new members added to the interface ? * lots of unknown situations - test more * declare member in other than interfaces ike classes, literal objects and type declarations: for example this doest work: ``` class C {} new C().nonExistentMethod() ``` * (very low priority) return type for method in some scenario ``` interface Hello{} const hello: Hello = {} class C { hello: Hello // here - when we apply refactor on grasp I expect that generated method to return {modified: Date, fully: boolean} and not just any m(s: number[]):{modified: Date, fully: boolean} { return this.hello.grasp(s, [false, true]) } } ``` */ export const declareMember: CodeFix = { name: 'declareMember', config: {}, predicate: (arg: CodeFixOptions): boolean => { if (arg.containingTargetLight.kind === ts.SyntaxKind.Identifier && arg.containingTargetLight.parent.kind === ts.SyntaxKind.PropertyAccessExpression && arg.diagnostics.find(d => d.code === 2339 && d.start === arg.containingTargetLight.getStart())) { return true } else { arg.log('predicate false because child.kind dont match ' + getKindName(arg.containingTarget.kind)) return false } }, description: (arg: CodeFixOptions): string => `Declare missing member "${arg.containingTarget.getText()}"`, apply: (opts: CodeFixOptions) => { const node = opts.simpleNode const print = (msg) => { opts.log('apply ' + msg) } const typeChecker = opts.simpleProject.getTypeChecker() const newMemberName_ = node.getText() const accessExpr = node.getParent() if (!TypeGuards.isPropertyAccessExpression(accessExpr)) { return print(`WARNING !TypeGuards.isPropertyAccessExpression(accessExpr) ${accessExpr.getKindName()}`) } const expressionWithTheType = accessExpr.getParent().getKind() === ts.SyntaxKind.CallExpression ? accessExpr.getParent().getParent() : accessExpr.getParent() const newMemberType_ = typeChecker.getTypeAtLocation(expressionWithTheType).getBaseTypeOfLiteralType() // now we extract arguments in case is a method call, example: const k = hello.mama(1,2,3)+' how are you?'-. let args_ const callExpression = accessExpr.getParent() if (TypeGuards.isCallExpression(callExpression)) { let argCounter = 0 args_ = callExpression.getArguments().map(a => ({ name: `arg${argCounter++}`, type: typeChecker.getTypeAtLocation(a).getBaseTypeOfLiteralType() })) } const results: tsa.ts.RefactorEditInfo[] = [] fixTargetDecl(accessExpr, newMemberName_, newMemberType_, args_, print, results) return results.find(r => !!r) } } // now we need to get the target declaration and add the member. It could be an object literal decl{}, an interface decl or a class decl const fixTargetDecl = (targetNode: tsa.Node, newMemberName: string, newMemberType: tsa.Type, args: { name: string, type: tsa.Type }[], print: (msg: string) => void, results: tsa.ts.RefactorEditInfo[]): void => { let decls if (TypeGuards.isExpressionedNode(targetNode) || TypeGuards.isLeftHandSideExpressionedNode(targetNode)) { let expr = targetNode.getExpression() if (TypeGuards.isNewExpression(expr)) { expr = expr.getExpression() } decls = expr.getSymbol().getDeclarations() } else if (targetNode && targetNode.getKindName().endsWith('Declaration')) { decls = [targetNode] } else { return print(`WARNING cannot recognized targetNode : ${targetNode && targetNode.getKindName()} ${targetNode && targetNode.getText()}`) } // const sourceFile = targetNode.getSourceFile() decls.forEach(d => { if (TypeGuards.isVariableDeclaration(d)) { const targetInit = d.getInitializer() // Heads up - first of all - because this is a variable declaration we try to find a clear interface or class that this // variable implements and is in this and doesn't already have the new member - then we fix there and not here const typeDeclInThisFile = (d.getType() && d.getType().getSymbol() && d.getType().getSymbol().getDeclarations() && d.getType().getSymbol().getDeclarations() || []) .find(dd => (TypeGuards.isInterfaceDeclaration(dd) || TypeGuards.isClassDeclaration(dd)) && dd.getSourceFile() === d.getSourceFile() ) if (typeDeclInThisFile && (TypeGuards.isInterfaceDeclaration(typeDeclInThisFile) || TypeGuards.isClassDeclaration(typeDeclInThisFile))) { return fixTargetDecl(typeDeclInThisFile, newMemberName, newMemberType, args, print, results) } else if (!TypeGuards.isObjectLiteralExpression(targetInit)) { //TODO - unknown situation - we should print in the file for discover new cases. return print(`WARNING !TypeGuards.isObjectLiteralExpression(targetInit) targetInit.getKindName() === ${targetInit && targetInit.getKindName()} targetInit.getText() === ${targetInit && targetInit.getText()} d.getKindName() === ${d && d.getKindName()} d.getText() === ${d && d.getText()}`) } else if (!args) { const member = targetInit.addPropertyAssignment({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: newMemberName, initializer: 'null' }) pushMember(member, d.getSourceFile(), results) } else { const member = targetInit.addMethod({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: newMemberName, returnType: newMemberType.getText(), bodyText: `throw new Error('Not Implemented')`, parameters: args.map(a => ({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: a.name, type: a.type.getText() })) }) pushMember(member, d.getSourceFile(), results) } } else if (TypeGuards.isInterfaceDeclaration(d)) { if (!args) { const member = d.addProperty({ name: newMemberName, type: newMemberType.getText() }) pushMember(member, d.getSourceFile(), results) } else { const member = d.addMethod({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: newMemberName, returnType: newMemberType.getText(), parameters: args.map(a => ({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: a.name, type: a.type.getText() })) }) pushMember(member, d.getSourceFile(), results) } } else if (TypeGuards.isClassDeclaration(d)) { if (!args) { const member = d.addProperty({ name: newMemberName, type: newMemberType.getText() }) pushMember(member, d.getSourceFile(), results) } else { const member = d.addMethod({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: newMemberName, returnType: newMemberType.getText(), parameters: args.map(a => ({ //TODO: use ast getstructure. we are not considering: jsdoc, hasquestion, modifiers, etc name: a.name, type: a.type.getText() })), bodyText: `throw new Error('Not Implemented')` }) pushMember(member, d.getSourceFile(), results) } } else if (TypeGuards.isParameterDeclaration(d) || TypeGuards.isPropertyDeclaration(d)) { // we are referencing a parameter or a property - not a variable - so we need to go to the declaration's declaration d.getType().getSymbol().getDeclarations().map(dd => { fixTargetDecl(dd, newMemberName, newMemberType, args, print, results) // recursive! }) //TODO: support RefactorEditInfo ? } else { //TODO - unknown situation - we should print in the file for discover new cases. print(`WARNING: is another thing isParameterDeclaration ${d.getKindName()}`) } }) } function pushMember(member: tsa.Node, sourceFile: tsa.SourceFile, results: tsa.ts.RefactorEditInfo[]) { let start: number const previous = member.getPreviousSibling() if (!previous) { const openBrace = member.getParent().getChildren().find(c => c.getKind() === ts.SyntaxKind.OpenBraceToken) as tsa.Node start = openBrace && openBrace.getEnd()// : member.getFullStart() } else { start = previous.getEnd() } const text = `${TypeGuards.isObjectLiteralExpression(member.getParent()) && previous ? ',' : ''}${member.getFullText()}\n` results.push(buildRefactorEditInfo(sourceFile.compilerNode, text, start, 0)) }
the_stack
export enum CountryCode { /** * Afghanistan. */ Af = "AF", /** * Aland Islands. */ Ax = "AX", /** * Albania. */ Al = "AL", /** * Algeria. */ Dz = "DZ", /** * Andorra. */ Ad = "AD", /** * Angola. */ Ao = "AO", /** * Anguilla. */ Ai = "AI", /** * Antigua And Barbuda. */ Ag = "AG", /** * Argentina. */ Ar = "AR", /** * Armenia. */ Am = "AM", /** * Aruba. */ Aw = "AW", /** * Australia. */ Au = "AU", /** * Austria. */ At = "AT", /** * Azerbaijan. */ Az = "AZ", /** * Bahamas. */ Bs = "BS", /** * Bahrain. */ Bh = "BH", /** * Bangladesh. */ Bd = "BD", /** * Barbados. */ Bb = "BB", /** * Belarus. */ By = "BY", /** * Belgium. */ Be = "BE", /** * Belize. */ Bz = "BZ", /** * Benin. */ Bj = "BJ", /** * Bermuda. */ Bm = "BM", /** * Bhutan. */ Bt = "BT", /** * Bolivia. */ Bo = "BO", /** * Bosnia And Herzegovina. */ Ba = "BA", /** * Botswana. */ Bw = "BW", /** * Bouvet Island. */ Bv = "BV", /** * Brazil. */ Br = "BR", /** * British Indian Ocean Territory. */ Io = "IO", /** * Brunei. */ Bn = "BN", /** * Bulgaria. */ Bg = "BG", /** * Burkina Faso. */ Bf = "BF", /** * Burundi. */ Bi = "BI", /** * Cambodia. */ Kh = "KH", /** * Canada. */ Ca = "CA", /** * Cape Verde. */ Cv = "CV", /** * Caribbean Netherlands. */ Bq = "BQ", /** * Cayman Islands. */ Ky = "KY", /** * Central African Republic. */ Cf = "CF", /** * Chad. */ Td = "TD", /** * Chile. */ Cl = "CL", /** * China. */ Cn = "CN", /** * Christmas Island. */ Cx = "CX", /** * Cocos (Keeling) Islands. */ Cc = "CC", /** * Colombia. */ Co = "CO", /** * Comoros. */ Km = "KM", /** * Congo. */ Cg = "CG", /** * Congo, The Democratic Republic Of The. */ Cd = "CD", /** * Cook Islands. */ Ck = "CK", /** * Costa Rica. */ Cr = "CR", /** * Croatia. */ Hr = "HR", /** * Cuba. */ Cu = "CU", /** * Curaçao. */ Cw = "CW", /** * Cyprus. */ Cy = "CY", /** * Czech Republic. */ Cz = "CZ", /** * Côte d'Ivoire. */ Ci = "CI", /** * Denmark. */ Dk = "DK", /** * Djibouti. */ Dj = "DJ", /** * Dominica. */ Dm = "DM", /** * Dominican Republic. */ Do = "DO", /** * Ecuador. */ Ec = "EC", /** * Egypt. */ Eg = "EG", /** * El Salvador. */ Sv = "SV", /** * Equatorial Guinea. */ Gq = "GQ", /** * Eritrea. */ Er = "ER", /** * Estonia. */ Ee = "EE", /** * Eswatini. */ Sz = "SZ", /** * Ethiopia. */ Et = "ET", /** * Falkland Islands (Malvinas). */ Fk = "FK", /** * Faroe Islands. */ Fo = "FO", /** * Fiji. */ Fj = "FJ", /** * Finland. */ Fi = "FI", /** * France. */ Fr = "FR", /** * French Guiana. */ Gf = "GF", /** * French Polynesia. */ Pf = "PF", /** * French Southern Territories. */ Tf = "TF", /** * Gabon. */ Ga = "GA", /** * Gambia. */ Gm = "GM", /** * Georgia. */ Ge = "GE", /** * Germany. */ De = "DE", /** * Ghana. */ Gh = "GH", /** * Gibraltar. */ Gi = "GI", /** * Greece. */ Gr = "GR", /** * Greenland. */ Gl = "GL", /** * Grenada. */ Gd = "GD", /** * Guadeloupe. */ Gp = "GP", /** * Guatemala. */ Gt = "GT", /** * Guernsey. */ Gg = "GG", /** * Guinea. */ Gn = "GN", /** * Guinea Bissau. */ Gw = "GW", /** * Guyana. */ Gy = "GY", /** * Haiti. */ Ht = "HT", /** * Heard Island And Mcdonald Islands. */ Hm = "HM", /** * Holy See (Vatican City State). */ Va = "VA", /** * Honduras. */ Hn = "HN", /** * Hong Kong. */ Hk = "HK", /** * Hungary. */ Hu = "HU", /** * Iceland. */ Is = "IS", /** * India. */ In = "IN", /** * Indonesia. */ Id = "ID", /** * Iran, Islamic Republic Of. */ Ir = "IR", /** * Iraq. */ Iq = "IQ", /** * Ireland. */ Ie = "IE", /** * Isle Of Man. */ Im = "IM", /** * Israel. */ Il = "IL", /** * Italy. */ It = "IT", /** * Jamaica. */ Jm = "JM", /** * Japan. */ Jp = "JP", /** * Jersey. */ Je = "JE", /** * Jordan. */ Jo = "JO", /** * Kazakhstan. */ Kz = "KZ", /** * Kenya. */ Ke = "KE", /** * Kiribati. */ Ki = "KI", /** * Korea, Democratic People's Republic Of. */ Kp = "KP", /** * Kosovo. */ Xk = "XK", /** * Kuwait. */ Kw = "KW", /** * Kyrgyzstan. */ Kg = "KG", /** * Lao People's Democratic Republic. */ La = "LA", /** * Latvia. */ Lv = "LV", /** * Lebanon. */ Lb = "LB", /** * Lesotho. */ Ls = "LS", /** * Liberia. */ Lr = "LR", /** * Libyan Arab Jamahiriya. */ Ly = "LY", /** * Liechtenstein. */ Li = "LI", /** * Lithuania. */ Lt = "LT", /** * Luxembourg. */ Lu = "LU", /** * Macao. */ Mo = "MO", /** * Madagascar. */ Mg = "MG", /** * Malawi. */ Mw = "MW", /** * Malaysia. */ My = "MY", /** * Maldives. */ Mv = "MV", /** * Mali. */ Ml = "ML", /** * Malta. */ Mt = "MT", /** * Martinique. */ Mq = "MQ", /** * Mauritania. */ Mr = "MR", /** * Mauritius. */ Mu = "MU", /** * Mayotte. */ Yt = "YT", /** * Mexico. */ Mx = "MX", /** * Moldova, Republic of. */ Md = "MD", /** * Monaco. */ Mc = "MC", /** * Mongolia. */ Mn = "MN", /** * Montenegro. */ Me = "ME", /** * Montserrat. */ Ms = "MS", /** * Morocco. */ Ma = "MA", /** * Mozambique. */ Mz = "MZ", /** * Myanmar. */ Mm = "MM", /** * Namibia. */ Na = "NA", /** * Nauru. */ Nr = "NR", /** * Nepal. */ Np = "NP", /** * Netherlands. */ Nl = "NL", /** * Netherlands Antilles. */ An = "AN", /** * New Caledonia. */ Nc = "NC", /** * New Zealand. */ Nz = "NZ", /** * Nicaragua. */ Ni = "NI", /** * Niger. */ Ne = "NE", /** * Nigeria. */ Ng = "NG", /** * Niue. */ Nu = "NU", /** * Norfolk Island. */ Nf = "NF", /** * North Macedonia. */ Mk = "MK", /** * Norway. */ No = "NO", /** * Oman. */ Om = "OM", /** * Pakistan. */ Pk = "PK", /** * Palestinian Territory, Occupied. */ Ps = "PS", /** * Panama. */ Pa = "PA", /** * Papua New Guinea. */ Pg = "PG", /** * Paraguay. */ Py = "PY", /** * Peru. */ Pe = "PE", /** * Philippines. */ Ph = "PH", /** * Pitcairn. */ Pn = "PN", /** * Poland. */ Pl = "PL", /** * Portugal. */ Pt = "PT", /** * Qatar. */ Qa = "QA", /** * Republic of Cameroon. */ Cm = "CM", /** * Reunion. */ Re = "RE", /** * Romania. */ Ro = "RO", /** * Russia. */ Ru = "RU", /** * Rwanda. */ Rw = "RW", /** * Saint Barthélemy. */ Bl = "BL", /** * Saint Helena. */ Sh = "SH", /** * Saint Kitts And Nevis. */ Kn = "KN", /** * Saint Lucia. */ Lc = "LC", /** * Saint Martin. */ Mf = "MF", /** * Saint Pierre And Miquelon. */ Pm = "PM", /** * Samoa. */ Ws = "WS", /** * San Marino. */ Sm = "SM", /** * Sao Tome And Principe. */ St = "ST", /** * Saudi Arabia. */ Sa = "SA", /** * Senegal. */ Sn = "SN", /** * Serbia. */ Rs = "RS", /** * Seychelles. */ Sc = "SC", /** * Sierra Leone. */ Sl = "SL", /** * Singapore. */ Sg = "SG", /** * Sint Maarten. */ Sx = "SX", /** * Slovakia. */ Sk = "SK", /** * Slovenia. */ Si = "SI", /** * Solomon Islands. */ Sb = "SB", /** * Somalia. */ So = "SO", /** * South Africa. */ Za = "ZA", /** * South Georgia And The South Sandwich Islands. */ Gs = "GS", /** * South Korea. */ Kr = "KR", /** * South Sudan. */ Ss = "SS", /** * Spain. */ Es = "ES", /** * Sri Lanka. */ Lk = "LK", /** * St. Vincent. */ Vc = "VC", /** * Sudan. */ Sd = "SD", /** * Suriname. */ Sr = "SR", /** * Svalbard And Jan Mayen. */ Sj = "SJ", /** * Sweden. */ Se = "SE", /** * Switzerland. */ Ch = "CH", /** * Syria. */ Sy = "SY", /** * Taiwan. */ Tw = "TW", /** * Tajikistan. */ Tj = "TJ", /** * Tanzania, United Republic Of. */ Tz = "TZ", /** * Thailand. */ Th = "TH", /** * Timor Leste. */ Tl = "TL", /** * Togo. */ Tg = "TG", /** * Tokelau. */ Tk = "TK", /** * Tonga. */ To = "TO", /** * Trinidad and Tobago. */ Tt = "TT", /** * Tunisia. */ Tn = "TN", /** * Turkey. */ Tr = "TR", /** * Turkmenistan. */ Tm = "TM", /** * Turks and Caicos Islands. */ Tc = "TC", /** * Tuvalu. */ Tv = "TV", /** * Uganda. */ Ug = "UG", /** * Ukraine. */ Ua = "UA", /** * United Arab Emirates. */ Ae = "AE", /** * United Kingdom. */ Gb = "GB", /** * United States. */ Us = "US", /** * United States Minor Outlying Islands. */ Um = "UM", /** * Uruguay. */ Uy = "UY", /** * Uzbekistan. */ Uz = "UZ", /** * Vanuatu. */ Vu = "VU", /** * Venezuela. */ Ve = "VE", /** * Vietnam. */ Vn = "VN", /** * Virgin Islands, British. */ Vg = "VG", /** * Wallis And Futuna. */ Wf = "WF", /** * Western Sahara. */ Eh = "EH", /** * Yemen. */ Ye = "YE", /** * Zambia. */ Zm = "ZM", /** * Zimbabwe. */ Zw = "ZW", /** * Unknown Syrup enum. */ UnknownSyrupEnum = "UNKNOWN_SYRUP_ENUM" }
the_stack
import { pathToFileURL } from 'url'; import { DocumentSpan, Project, SyntaxKind } from 'ts-morph'; import { LocationLink, Position, Range } from 'vscode-languageserver'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { getWordAtOffset } from '../../common/documens/find-source-word'; import { PositionUtils } from '../../common/documens/PositionUtils'; import { getRelatedFilePath } from '../../common/documens/related'; import { TextDocumentUtils } from '../../common/documens/TextDocumentUtils'; import { UriUtils } from '../../common/view/uri-utils'; import { AureliaProjects } from '../../core/AureliaProjects'; import { Container } from '../../core/container'; import { findRegionsByWord, forEachRegionOfType, } from '../../core/regions/findSpecificRegion'; import { AbstractRegion, ViewRegionSubType, ViewRegionType, } from '../../core/regions/ViewRegions'; import { AureliaProgram, IAureliaComponent, } from '../../core/viewModel/AureliaProgram'; import { DocumentSettings } from '../configuration/DocumentSettings'; /** * 1. Only allow for Class or Bindable * 2. For Bindable, check if source or reference * 3. Find references in own and other Views */ export async function aureliaDefinitionFromViewModel( container: Container, document: TextDocument, position: Position ): Promise<LocationLink[] | undefined> { const offset = document.offsetAt(position); const viewModelPath = UriUtils.toSysPath(document.uri); const targetProject = container .get(AureliaProjects) .getFromPath(viewModelPath); if (!targetProject) return; const { aureliaProgram } = targetProject; if (!aureliaProgram) return; const tsMorphProject = aureliaProgram.tsMorphProject.get(); const sourceWord = getWordAtOffset(document.getText(), offset); const targetComponent = aureliaProgram.aureliaComponents.getOneBy('className', sourceWord) ?? aureliaProgram.aureliaComponents.getOneBy( 'viewModelFilePath', viewModelPath ); // 1. Only for Class and Bindables const isIdentifier = getIsIdentifier(tsMorphProject, viewModelPath, offset); if (!isIdentifier) return; const regularDefintions = findRegularTypescriptDefinitions(tsMorphProject, viewModelPath, offset) ?? []; const sourceDefinition = getSourceDefinition( regularDefintions, viewModelPath, position ); const finalDefinitions: LocationLink[] = []; /** Not source, so default */ if (!sourceDefinition) return; // Note, we need to handle references (instead of just letting it be the job of the TS Server), // because as long as we only return one valid defintion, the "default" suggestions are not returned // to the client anymore. // I made sure to test this out throughly by just returning one definition (any defintion data), then // check the client (ie. trigger suggestion inside a .ts file in VSCode). /** Source, so push references */ const regularReferences = findRegularTypescriptReferences(aureliaProgram, viewModelPath, offset) ?? []; // We filter out the definition source, else it would be duplicated const withoutTriggerDefinition = filterOutTriggerDefinition( regularReferences, sourceDefinition ); finalDefinitions.push(...withoutTriggerDefinition); const targetMember = targetComponent?.classMembers?.find( (member) => member.name === sourceWord ); // Class Member if (targetMember) { const viewRegionDefinitions_ClassMembers = await getAureliaClassMemberDefinitions_SameView( container, aureliaProgram, document, sourceWord ); finalDefinitions.push(...viewRegionDefinitions_ClassMembers); // Bindable const isBindable = targetMember.isBindable; if (isBindable) { const viewRegionDefinitions_Bindables = await getAureliaClassMemberDefinitions_OtherViewBindables( aureliaProgram, sourceWord ); finalDefinitions.push(...viewRegionDefinitions_Bindables); } } // Class else if (targetComponent) { const viewRegionDefinitions_Class: LocationLink[] = await getAureliaCustomElementDefinitions_OtherViews( aureliaProgram, targetComponent ); finalDefinitions.push(...viewRegionDefinitions_Class); } return finalDefinitions; } async function getAureliaCustomElementDefinitions_OtherViews( aureliaProgram: AureliaProgram, targetComponent: IAureliaComponent ) { const viewRegionDefinitions_Class: LocationLink[] = []; await forEachRegionOfType( aureliaProgram, ViewRegionType.CustomElement, (region, document) => { if (region.tagName !== targetComponent?.componentName) return; if (region.subType === ViewRegionSubType.EndTag) return; const locationLink = createLocationLinkFromRegion(region, document); if (!locationLink) return; viewRegionDefinitions_Class.push(locationLink); } ); return viewRegionDefinitions_Class; } async function getAureliaClassMemberDefinitions_SameView( container: Container, aureliaProgram: AureliaProgram, document: TextDocument, sourceWord: string ) { const documentSettings = container.get(DocumentSettings); const viewExtensions = documentSettings.getSettings().relatedFiles?.view; if (!viewExtensions) return []; const viewPath = getRelatedFilePath( UriUtils.toSysPath(document.uri), viewExtensions ); const viewDocument = TextDocumentUtils.createHtmlFromPath(viewPath); const viewRegionDefinitions_ClassMembers: LocationLink[] = []; const regions = await findRegionsByWord( aureliaProgram, viewDocument, sourceWord ); for (const region of regions) { const locationLink = createLocationLinkFromRegion(region, viewDocument); if (!locationLink) continue; viewRegionDefinitions_ClassMembers.push(locationLink); } return viewRegionDefinitions_ClassMembers; } async function getAureliaClassMemberDefinitions_OtherViewBindables( aureliaProgram: AureliaProgram, sourceWord: string ) { const viewRegionDefinitions_Bindables: LocationLink[] = []; await forEachRegionOfType( aureliaProgram, ViewRegionType.CustomElement, (region, document) => { region.data?.forEach((subRegion) => { if (subRegion.type !== ViewRegionType.BindableAttribute) return; if (subRegion.regionValue !== sourceWord) return; const locationLink = createLocationLinkFromRegion(subRegion, document); if (!locationLink) return; viewRegionDefinitions_Bindables.push(locationLink); }); } ); return viewRegionDefinitions_Bindables; } function findRegularTypescriptDefinitions( tsMorphProject: Project, viewModelPath: string, offset: number ) { const finalDefinitions: LocationLink[] = []; const sourceFile = tsMorphProject.getSourceFile(viewModelPath); if (!sourceFile) return; const sourceDefinitions = tsMorphProject .getLanguageService() .getDefinitionsAtPosition(sourceFile, offset); sourceDefinitions.forEach((definition) => { const locationLink = createLocationLinkFromDocumentSpan(definition); finalDefinitions.push(locationLink); }); return finalDefinitions; } function findRegularTypescriptReferences( aureliaProgram: AureliaProgram, viewModelPath: string, offset: number ) { const finalReferences: LocationLink[] = []; const tsMorphProject = aureliaProgram.tsMorphProject.get(); const sourceFile = tsMorphProject.getSourceFile(viewModelPath); if (!sourceFile) return; const references = tsMorphProject .getLanguageService() .findReferencesAtPosition(sourceFile, offset); references.forEach((reference) => { reference.getReferences().forEach((subReference) => { const locationLink = createLocationLinkFromDocumentSpan(subReference); finalReferences.push(locationLink); }); }); return finalReferences; } function createLocationLinkFromDocumentSpan(documentSpan: DocumentSpan) { const refNode = documentSpan.getNode(); const startLine = refNode.getStartLineNumber() - 1; const startOffset = refNode.getStart() - 1; const startPos = refNode.getStartLinePos() - 1; const startCol = startOffset - startPos; const endLine = refNode.getEndLineNumber() - 1; const endOffset = refNode.getEnd() - 1; const endPos = refNode.getStartLinePos() - 1; const endCol = endOffset - endPos; const range = Range.create( Position.create(startLine, startCol), Position.create(endLine, endCol) ); const path = documentSpan.getSourceFile().getFilePath(); const locationLink = LocationLink.create( pathToFileURL(path).toString(), range, range ); return locationLink; } function createLocationLinkFromRegion( region: AbstractRegion, document: TextDocument ) { if (region.sourceCodeLocation === undefined) return; const { startLine, startCol, endLine, endCol } = region.sourceCodeLocation; const range = Range.create( Position.create(startLine, startCol), Position.create(endLine, endCol) ); const locationLink = LocationLink.create( document.uri.toString(), range, range ); return locationLink; } /** * Given a position, check if the defintion is the source. * (If not source, then it would be a reference.) */ function getSourceDefinition( definitions: LocationLink[], viewModelPath: string, position: Position ) { const targetDefinition = definitions.find((definition) => { const { start, end } = definition.targetRange; const isIncludedPosition = PositionUtils.isIncluded(start, end, position); const isSamePath = UriUtils.toSysPath(definition.targetUri) === UriUtils.toSysPath(viewModelPath); const isSourceDefinition = isIncludedPosition && isSamePath; return isSourceDefinition; }); return targetDefinition; } function getIsIdentifier( tsMorphProject: Project, viewModelPath: string, offset: number ) { const sourceFile = tsMorphProject.getSourceFile(viewModelPath); const descandant = sourceFile?.getDescendantAtPos(offset); const is = descandant?.getKind() === SyntaxKind.Identifier; return is; } function filterOutTriggerDefinition( regularReferences: LocationLink[], sourceDefinition: LocationLink ) { const withoutTriggerDefinition = regularReferences.filter((reference) => { const referenceIsInSameUri = reference.targetUri === sourceDefinition.targetUri; if (!referenceIsInSameUri) return true; const { targetRange, targetSelectionRange } = reference; const sameRange = isSameRange(targetRange, sourceDefinition.targetRange); const sameSelectionRange = isSameRange( targetSelectionRange, sourceDefinition.targetSelectionRange ); const same = sameRange && sameSelectionRange; return !same; }); return withoutTriggerDefinition; } function isSameRange(rangeA: Range, rangeB: Range) { const sameStartChar = rangeA.start.character === rangeB.start.character; const sameStartLine = rangeA.start.line === rangeB.start.line; const sameEndChar = rangeA.end.character === rangeB.end.character; const sameEndLine = rangeA.end.line === rangeB.end.line; const same = sameStartChar && sameStartLine && sameEndChar && sameEndLine; return same; }
the_stack
import { Wallet, providers, BigNumber } from 'ethers'; import { ClientTypes, ExtensionTypes, IdentityTypes, PaymentTypes, RequestLogicTypes, } from '@requestnetwork/types'; import { encodeRequestApprovalAndPayment } from '../../src'; import { currencyManager } from './shared'; import { ERC20__factory } from '@requestnetwork/smart-contracts/types'; /* eslint-disable @typescript-eslint/no-unused-expressions */ /* eslint-disable @typescript-eslint/await-thenable */ const erc20ContractAddress = '0x9FBDa871d559710256a2502A2517b794B482Db40'; const feeAddress = '0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef'; // Cf. ERC20Alpha in TestERC20.sol const alphaContractAddress = '0x38cF23C52Bb4B13F051Aec09580a2dE845a7FA35'; const alphaConversionSettings = { currency: { type: RequestLogicTypes.CURRENCY.ERC20, value: alphaContractAddress, network: 'private', }, maxToSpend: BigNumber.from(2).pow(256).sub(1), currencyManager, }; const ethConversionSettings = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, maxToSpend: '2500000000000000', currencyManager, }; const alphaSwapSettings = { deadline: 2599732187000, // This test will fail in 2052 maxInputAmount: 204, path: [alphaContractAddress, erc20ContractAddress], }; const alphaSwapConversionSettings = { deadline: 2599732187000, // This test will fail in 2052 maxInputAmount: '100000000000000000000', path: [erc20ContractAddress, alphaContractAddress], }; const mnemonic = 'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat'; const mnemonicPath = `m/44'/60'/0'/0/20`; const paymentAddress = '0xf17f52151EbEF6C7334FAD080c5704D77216b732'; const provider = new providers.JsonRpcProvider('http://localhost:8545'); let wallet = Wallet.fromMnemonic(mnemonic, mnemonicPath).connect(provider); const baseValidRequest: ClientTypes.IRequestData = { balance: { balance: '0', events: [], }, contentData: {}, creator: { type: IdentityTypes.TYPE.ETHEREUM_ADDRESS, value: wallet.address, }, currency: 'DAI', currencyInfo: { network: 'private', type: RequestLogicTypes.CURRENCY.ERC20, value: erc20ContractAddress, }, events: [], expectedAmount: '100', extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { paymentAddress, salt: 'salt', }, version: '0.1.0', }, }, extensionsData: [], meta: { transactionManagerMeta: {}, }, pending: null, requestId: 'abcd', state: RequestLogicTypes.STATE.CREATED, timestamp: 0, version: '1.0', }; const validRequestERC20FeeProxy: ClientTypes.IRequestData = { ...baseValidRequest, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { feeAddress, feeAmount: '2', paymentAddress, salt: 'salt', }, version: '0.1.0', }, }, }; const validRequestERC20ConversionProxy: ClientTypes.IRequestData = { ...baseValidRequest, currency: 'EUR', currencyInfo: { type: RequestLogicTypes.CURRENCY.ISO4217, value: 'EUR', }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ANY_TO_ERC20_PROXY]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ERC20_PROXY, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { feeAddress, feeAmount: '2', paymentAddress, salt: 'salt', network: 'private', acceptedTokens: [alphaContractAddress], }, version: '0.1.0', }, }, }; const validRequestEthProxy: ClientTypes.IRequestData = { ...baseValidRequest, currency: 'ETH', currencyInfo: { network: 'private', type: RequestLogicTypes.CURRENCY.ETH, value: RequestLogicTypes.CURRENCY.ETH, }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { paymentAddress, salt: 'salt', }, version: '0.1.0', }, }, version: '2.0.3', }; const validRequestEthFeeProxy: ClientTypes.IRequestData = { ...baseValidRequest, currency: 'ETH', currencyInfo: { network: 'private', type: RequestLogicTypes.CURRENCY.ETH, value: RequestLogicTypes.CURRENCY.ETH, }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_FEE_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_FEE_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { feeAddress, feeAmount: '2', paymentAddress, salt: 'salt', }, version: '0.1.0', }, }, version: '2.0.3', }; const validRequestEthConversionProxy: ClientTypes.IRequestData = { ...baseValidRequest, currency: 'EUR', currencyInfo: { type: RequestLogicTypes.CURRENCY.ISO4217, value: 'EUR', }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ANY_TO_ETH_PROXY]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ANY_TO_ETH_PROXY, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { feeAddress, feeAmount: '2', paymentAddress, salt: 'salt', network: 'private', }, version: '0.1.0', }, }, }; beforeAll(async () => { const mainAddress = wallet.address; wallet = Wallet.fromMnemonic(mnemonic).connect(provider); const alphaContract = ERC20__factory.connect(alphaContractAddress, wallet); await alphaContract.transfer(mainAddress, BigNumber.from('500000000000000000000')); const erc20Contract = ERC20__factory.connect(erc20ContractAddress, wallet); await erc20Contract.transfer(mainAddress, BigNumber.from('500000000000000000000')); wallet.sendTransaction({ to: mainAddress, value: BigNumber.from('10000000000000000000'), }); wallet = Wallet.fromMnemonic(mnemonic, mnemonicPath).connect(provider); }); describe('Encoder', () => { it('Should handle ERC20 Proxy request', async () => { const encodedTransactions = await encodeRequestApprovalAndPayment( baseValidRequest, provider, wallet.address, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); tx = await wallet.sendTransaction(encodedTransactions[1]); confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle ERC20 Fee Proxy request', async () => { const encodedTransactions = await encodeRequestApprovalAndPayment( validRequestERC20FeeProxy, provider, wallet.address, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); tx = await wallet.sendTransaction(encodedTransactions[1]); confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle ERC20 Conversion Proxy request', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestERC20ConversionProxy, provider, wallet.address, { conversion: alphaConversionSettings, }, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); tx = await wallet.sendTransaction(encodedTransactions[1]); confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle ERC20 Swap Proxy request', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestERC20FeeProxy, provider, wallet.address, { swap: alphaSwapSettings, }, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); tx = await wallet.sendTransaction(encodedTransactions[1]); confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle ERC20 Swap and Conversion Proxy request', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestERC20ConversionProxy, provider, wallet.address, { swap: alphaSwapConversionSettings, conversion: alphaConversionSettings, }, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); tx = await wallet.sendTransaction(encodedTransactions[1]); confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle Eth Proxy request', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestEthProxy, provider, wallet.address, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle Eth Fee Proxy request', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestEthFeeProxy, provider, wallet.address, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); it('Should handle Eth Conversion Proxy', async () => { let encodedTransactions = await encodeRequestApprovalAndPayment( validRequestEthConversionProxy, provider, wallet.address, { conversion: ethConversionSettings, }, ); let tx = await wallet.sendTransaction(encodedTransactions[0]); let confirmedTx = await tx.wait(1); expect(confirmedTx.status).toBe(1); expect(tx.hash).not.toBeUndefined(); }); });
the_stack
import {Stream} from 'xstream'; import {h} from '@cycle/react'; import {StyleSheet, Text, View, Image, Platform} from 'react-native'; import {Palette} from '../../global-styles/palette'; import {Dimensions} from '../../global-styles/dimens'; import {getImg} from '../../global-styles/utils'; import tutorialSlide from '../../components/tutorial-slide'; import tutorialPresentation from '../../components/tutorial-presentation'; import Button from '../../components/Button'; import {t} from '../../drivers/localization'; import {State} from './model'; export const styles = StyleSheet.create({ screen: { flex: 1, alignSelf: 'stretch', justifyContent: 'center', alignItems: 'center', backgroundColor: Palette.brandMain, flexDirection: 'column', }, logo: { width: 48, height: 48, }, bold: { fontWeight: 'bold', }, italicBold: { fontStyle: 'italic', fontWeight: 'bold', }, link: { textDecorationLine: 'underline', }, button: { borderColor: Palette.colors.white, ...Platform.select({ web: {}, default: { marginBottom: 62, }, }), }, buttonText: { color: Palette.colors.white, }, ctaButton: { backgroundColor: Palette.backgroundCTA, marginBottom: Dimensions.verticalSpaceBig, }, }); function bold(innerText: string) { return h(Text, {style: styles.bold}, innerText); } type Actions = { scrollBy$: Stream<[number, boolean]>; }; function overviewSlide(state: State) { return tutorialSlide({ show: state.index >= 0, image: getImg(require('../../../../images/noun-butterfly.png')), portraitMode: state.isPortraitMode, title: t('welcome.overview.title', { // Only this screen needs a defaultValue because it's the // first screen, and in case or race conditions with loading // the translation files, we don't want there to be no text defaultValue: 'Welcome to Manyverse!', }), renderDescription: () => [ t('welcome.overview.description', { // Same reason as above defaultValue: 'Social networking can be simple, neutral, ' + 'non-commercial, and built on trust between friends. ' + 'This is what Manyverse stands for, and we hope you too ' + 'can make it your digital home. All this is made ' + 'possible by the novel SSB protocol.', }), ' ', h( Text, {sel: 'learn-more-ssb', style: styles.link}, t('welcome.learn_more', {defaultValue: 'Learn more'}), ), ], renderBottom: () => h(Button, { sel: 'overview-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue', { defaultValue: 'Continue', }), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue', { defaultValue: 'Continue', }), }), }); } function offTheGridSlide(state: State) { return tutorialSlide({ show: state.index >= 1, image: getImg(require('../../../../images/noun-camping.png')), portraitMode: state.isPortraitMode, title: t('welcome.off_the_grid.title'), renderDescription: () => [ t('welcome.off_the_grid.description.1_normal'), bold(t('welcome.off_the_grid.description.2_bold')), t('welcome.off_the_grid.description.3_normal'), bold(t('welcome.off_the_grid.description.4_bold')), t('welcome.off_the_grid.description.5_normal'), ' ', h( Text, {sel: 'learn-more-off-grid', style: styles.link}, t('welcome.learn_more', {defaultValue: 'Learn more'}), ), ], renderBottom: () => h(Button, { sel: 'offgrid-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue'), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue'), }), }); } function connectionsSlide(state: State) { return tutorialSlide({ show: state.index >= 2, image: getImg(require('../../../../images/noun-fish.png')), portraitMode: state.isPortraitMode, title: t('welcome.connections.title'), renderDescription: () => Platform.select({ ios: [ t('welcome.connections.description.ios.1_normal'), bold(t('welcome.connections.description.ios.2_bold')), t('welcome.connections.description.ios.3_normal'), bold(t('welcome.connections.description.ios.4_bold')), t('welcome.connections.description.ios.5_normal'), bold(t('welcome.connections.description.ios.6_bold')), t('welcome.connections.description.ios.7_normal'), ' ', h( Text, {sel: 'learn-more-connections', style: styles.link}, t('welcome.learn_more'), ), ], default: [ t('welcome.connections.description.default.1_normal'), bold(t('welcome.connections.description.default.2_bold')), t('welcome.connections.description.default.3_normal'), bold(t('welcome.connections.description.default.4_bold')), t('welcome.connections.description.default.5_normal'), bold(t('welcome.connections.description.default.6_bold')), t('welcome.connections.description.default.7_normal'), bold(t('welcome.connections.description.default.8_bold')), t('welcome.connections.description.default.9_normal'), ' ', h( Text, {sel: 'learn-more-connections', style: styles.link}, t('welcome.learn_more'), ), ], }), renderBottom: () => h(Button, { sel: 'connections-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue'), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue'), }), }); } function moderationSlide(state: State) { return tutorialSlide({ show: state.index >= 3, image: getImg(require('../../../../images/noun-farm.png')), portraitMode: state.isPortraitMode, title: t('welcome.moderation.title'), renderDescription: () => [ t('welcome.moderation.description.1_normal'), bold(t('welcome.moderation.description.2_bold')), t('welcome.moderation.description.3_normal'), ' ', h( Text, {sel: 'learn-more-moderation', style: styles.link}, t('welcome.learn_more'), ), ], renderBottom: () => h(Button, { sel: 'moderation-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue'), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue'), }), }); } function permanenceSlide(state: State) { return tutorialSlide({ show: state.index >= 4, image: getImg(require('../../../../images/noun-roots.png')), portraitMode: state.isPortraitMode, title: t('welcome.permanence.title'), renderDescription: () => [ t('welcome.permanence.description.1_normal'), bold(t('welcome.permanence.description.2_bold')), t('welcome.permanence.description.3_normal'), ' ', h( Text, {sel: 'learn-more-permanence', style: styles.link}, t('welcome.learn_more'), ), ], renderBottom: () => h(Button, { sel: 'permanence-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue'), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue'), }), }); } function inConstructionSlide(state: State) { return tutorialSlide({ show: state.index >= 5, image: getImg(require('../../../../images/noun-wheelbarrow.png')), portraitMode: state.isPortraitMode, title: t('welcome.in_construction.title'), renderDescription: () => [ t('welcome.in_construction.description.1_normal'), bold(t('welcome.in_construction.description.2_bold')), t('welcome.in_construction.description.3_normal'), ], renderBottom: () => h(Button, { sel: 'inconstruction-continue', style: styles.button, textStyle: styles.buttonText, text: t('call_to_action.continue'), strong: false, accessible: true, accessibilityLabel: t('call_to_action.continue'), }), }); } function setupAccountSlide(state: State) { return tutorialSlide({ show: state.index >= (Platform.OS === 'ios' ? 5 : 6), image: getImg(require('../../../../images/noun-flower.png')), portraitMode: state.isPortraitMode, title: t('welcome.setup_account.title'), renderDescription: () => [t('welcome.setup_account.description')], renderBottom: () => [ h(Button, { sel: 'create-account', style: styles.ctaButton, text: t('welcome.setup_account.call_to_action.create.label'), strong: true, accessible: true, accessibilityLabel: t( 'welcome.setup_account.call_to_action.create.accessibility_label', ), }), h(Button, { sel: 'restore-account', style: styles.button, textStyle: styles.buttonText, text: t('welcome.setup_account.call_to_action.restore.label'), strong: false, accessible: true, accessibilityLabel: t( 'welcome.setup_account.call_to_action.restore.accessibility_label', ), }), ], }); } export default function view(state$: Stream<State>, actions: Actions) { return state$.map((state) => h(View, {style: styles.screen}, [ !state.readyToStart ? h(Image, { source: getImg(require('../../../../images/logo_outline.png')), style: styles.logo, }) : tutorialPresentation('swiper', {scrollBy$: actions.scrollBy$}, [ overviewSlide(state), offTheGridSlide(state), connectionsSlide(state), moderationSlide(state), permanenceSlide(state), Platform.OS === 'ios' ? null : inConstructionSlide(state), setupAccountSlide(state), ]), ]), ); }
the_stack
import {Component, PureComponent, Fragment} from 'react'; import { View, Text, TouchableNativeFeedback, TouchableOpacity, Modal, StyleSheet, Platform, TouchableWithoutFeedback, ViewStyle, } from 'react-native'; import {h} from '@cycle/react'; import EmojiPicker from 'react-native-emoji-picker-staltz'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import {Msg, FeedId} from 'ssb-typescript'; import {t} from '../../drivers/localization'; import {Palette} from '../../global-styles/palette'; import {Dimensions} from '../../global-styles/dimens'; import {Typography} from '../../global-styles/typography'; import { Reactions as ReactionsType, PressReactionsEvent, PressAddReactionEvent, } from '../../ssb/types'; const THUMBS_UP_UNICODE = '\ud83d\udc4d'; const VICTORY_HAND_UNICODE = String.fromCodePoint(parseInt('270C', 16)); const HEART_UNICODE = '\u2764\ufe0f'; const SEE_NO_EVIL_MONKEY_UNICODE = String.fromCodePoint(parseInt('1F648', 16)); const SMILING_WITH_HEART_EYES_UNICODE = String.fromCodePoint( parseInt('1F60D', 16), ); const GRINNING_WITH_SMILE_UNICODE = String.fromCodePoint(parseInt('1F604', 16)); const CRYING_FACE_UNICODE = String.fromCodePoint(parseInt('1F622', 16)); const Touchable = Platform.select<any>({ android: TouchableNativeFeedback, default: TouchableOpacity, }); const touchableProps: any = {}; if (Platform.OS === 'android') { touchableProps.background = TouchableNativeFeedback.SelectableBackground(); } export const styles = StyleSheet.create({ container: { flexDirection: 'column', }, reactionsContainer: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', flex: 2, }, buttonsContainer: { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: Palette.textLine, flex: 3, flexDirection: 'row', alignItems: 'stretch', justifyContent: 'space-between', }, quickEmojiPickerModal: { flexDirection: 'column', alignItems: 'stretch', justifyContent: 'center', flex: 1, }, quickEmojiPickerBackground: { backgroundColor: Palette.transparencyDark, position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, zIndex: -1, }, quickEmojiPickerContainer: { backgroundColor: Palette.backgroundText, borderRadius: Dimensions.borderRadiusBig, marginHorizontal: Dimensions.horizontalSpaceNormal, marginVertical: Dimensions.verticalSpaceNormal, paddingHorizontal: Dimensions.horizontalSpaceNormal, paddingVertical: Dimensions.verticalSpaceNormal, flexDirection: 'column', ...Platform.select({ web: { width: '50vw', marginHorizontal: '25vw', }, }), }, quickEmojiPickerRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, quickEmojiChoiceTouchable: { height: 60, width: 60, flex: 0, flexBasis: 'auto', flexGrow: 0, flexShrink: 0, justifyContent: 'center', alignItems: 'center', }, quickEmojiChoice: { fontSize: 30, fontFamily: Platform.select({web: Typography.fontFamilyReadableText}), }, fullEmojiPickerModal: { flex: 1, }, fullEmojiPickerBackground: { backgroundColor: Palette.transparencyDark, }, fullEmojiPickerContainer: { backgroundColor: Palette.backgroundText, padding: 0, }, fullEmojiPickerScroll: { paddingTop: Dimensions.verticalSpaceTiny, paddingHorizontal: Dimensions.horizontalSpaceNormal, paddingBottom: Dimensions.verticalSpaceNormal, }, fullEmojiPickerHeader: { fontSize: Typography.fontSizeSmall, fontFamily: Typography.fontFamilyReadableText, fontWeight: 'bold', color: Palette.textWeak, }, fullEmojiPickerEmoji: { fontFamily: Platform.select({web: Typography.fontFamilyReadableText}), }, reactionsTouchable: { ...Platform.select({ web: { width: '100%', }, }), }, reactions: { flexDirection: 'row', justifyContent: 'flex-start', alignItems: 'stretch', }, reactionsText: { minWidth: 60, fontSize: Typography.fontSizeSmall, lineHeight: Typography.lineHeightSmall, fontFamily: Typography.fontFamilyReadableText, fontWeight: 'bold', textAlignVertical: 'center', textAlign: 'left', color: Palette.textWeak, }, repliesCounter: { marginRight: Dimensions.horizontalSpaceTiny, fontSize: Typography.fontSizeNormal, fontFamily: Typography.fontFamilyReadableText, textAlignVertical: 'center', textAlign: 'right', color: Palette.textWeak, }, myReaction: { color: Palette.text, fontSize: Typography.fontSizeBig, fontFamily: Platform.select({web: Typography.fontFamilyReadableText}), lineHeight: Typography.lineHeightSmall, }, prominentButtonContainer: Platform.select({ web: { width: '80px', }, default: { flex: 1, }, }), prominentButton: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, }); class Reactions extends PureComponent<{ onPress: () => void; reactions: NonNullable<ReactionsType>; }> { public render() { const {reactions, onPress} = this.props; const count = reactions.length; const summary = reactions.map(([_feed, reaction]) => reaction).join(''); const child = [ h(View, {style: styles.reactions, pointerEvents: 'box-only'}, [ h( Text, { style: styles.reactionsText, numberOfLines: 1, ellipsizeMode: 'tail', }, count > 0 ? summary : ' ', ), ]), ]; if (count > 0) { return h( Touchable, { ...touchableProps, style: styles.reactionsTouchable, onPress, accessible: true, accessibilityRole: 'button', accessibilityLabel: t( 'message.call_to_action.show_reactions.accessibility_label', ), }, child, ); } else { return h(Fragment, child); } } } class AddReactionButton extends PureComponent<{ onPress: () => void; myReaction: string | null; }> { public render() { const {myReaction} = this.props; return h( Touchable, { ...touchableProps, style: styles.prominentButtonContainer, onPress: this.props.onPress, delayLongPress: 100, delayPressIn: 20, accessible: true, accessibilityRole: 'button', accessibilityLabel: t( 'message.call_to_action.add_reaction.accessibility_label', ), }, [ h(View, {style: styles.prominentButton, pointerEvents: 'box-only'}, [ myReaction === null ? h(Icon, { key: 'icon', size: Dimensions.iconSizeSmall, color: Palette.textWeak, name: 'emoticon-happy-outline', }) : h(Text, {key: 'm', style: styles.myReaction}, myReaction), ]), ], ); } } class ReplyButton extends PureComponent<{ onPress?: () => void; enabled: boolean; replyCount: number; }> { public render() { const {replyCount, enabled} = this.props; if (enabled) { return h( Touchable, { ...touchableProps, style: styles.prominentButtonContainer, onPress: this.props.onPress, accessible: true, accessibilityRole: 'button', accessibilityLabel: t( 'message.call_to_action.reply.accessibility_label', ), }, [ h(View, {style: styles.prominentButton, pointerEvents: 'box-only'}, [ replyCount > 0 ? h( Text, { key: 't', style: styles.repliesCounter, numberOfLines: 1, }, String(replyCount), ) : null, h(Icon, { key: 'icon', size: Dimensions.iconSizeSmall, color: Palette.textWeak, name: 'comment-outline', }), ]), ], ); } else { return h(View, {style: styles.prominentButton}, [ h(Icon, { key: 'icon', size: Dimensions.iconSizeSmall, color: Palette.textVeryWeak, name: 'comment-outline', }), ]); } } } class EtcButton extends PureComponent<{onPress: () => void}> { public render() { return h( Touchable, { ...touchableProps, style: styles.prominentButtonContainer, onPress: this.props.onPress, accessible: true, accessibilityRole: 'button', accessibilityLabel: t('message.call_to_action.etc.accessibility_label'), }, [ h(View, {style: styles.prominentButton, pointerEvents: 'box-only'}, [ h(Icon, { size: Dimensions.iconSizeNormal, color: Palette.textWeak, name: 'dots-horizontal', }), ]), ], ); } } export type Props = { msg: Msg; selfFeedId: FeedId; reactions: ReactionsType; replyCount: number; style?: ViewStyle; onPressReactions?: (ev: PressReactionsEvent) => void; onPressAddReaction?: (ev: PressAddReactionEvent) => void; onPressReply?: () => void; onPressEtc?: (msg: Msg) => void; }; export type State = { showQuickEmojis: boolean; showFullEmojis: boolean; }; export default class MessageFooter extends Component<Props, State> { public state = { showQuickEmojis: false, showFullEmojis: false, }; /** * in pixels */ public static HEIGHT = 75; private myReaction: string | null = null; private onPressReactionsHandler = () => { this.props.onPressReactions?.({ msgKey: this.props.msg.key, reactions: this.props.reactions, }); }; private onPressAddReactionHandler = () => { if (this.myReaction === null) { this.setState((prev) => ({showQuickEmojis: !prev.showQuickEmojis})); } else { this.props.onPressAddReaction?.({ msgKey: this.props.msg.key, value: 0, reaction: null, }); } }; private closeQuickEmojiPicker = () => { this.setState({showQuickEmojis: false}); }; private openFullEmojiPicker = () => { this.setState({showQuickEmojis: false, showFullEmojis: true}); }; private closeFullEmojiPicker = () => { this.setState({showQuickEmojis: false, showFullEmojis: false}); }; private onSelectEmojiReaction = (emoji: string | null) => { if (emoji) { this.props.onPressAddReaction?.({ msgKey: this.props.msg.key, value: 1, reaction: emoji, }); } this.setState({showQuickEmojis: false, showFullEmojis: false}); }; private onPressEtcHandler = () => { this.props.onPressEtc?.(this.props.msg); }; private findMyLatestReaction(): string | null { const reactions = this.props.reactions; if (!reactions) return null; const selfFeedId = this.props.selfFeedId; for (let i = reactions.length - 1; i >= 0; i--) { if (reactions[i][0] === selfFeedId) { return reactions[i][1]; } } return null; } public shouldComponentUpdate(nextP: Props, nextS: State) { const prevP = this.props; const prevS = this.state; if (nextP.msg.key !== prevP.msg.key) return true; if (nextS.showQuickEmojis !== prevS.showQuickEmojis) return true; if (nextS.showFullEmojis !== prevS.showFullEmojis) return true; if (nextP.onPressReply !== prevP.onPressReply) return true; if (nextP.replyCount !== prevP.replyCount) return true; if ((nextP.reactions ?? []).length !== (prevP.reactions ?? []).length) { return true; } if ( // Check that the latest (the first entry) is // from the same author but has changed the emoji nextP.reactions && prevP.reactions && nextP.reactions.length > 0 && prevP.reactions.length > 0 && nextP.reactions[0][0] === prevP.reactions[0][0] && nextP.reactions[0][1] !== prevP.reactions[0][1] ) { return true; } // Deep comparison if (JSON.stringify(nextP.reactions) !== JSON.stringify(prevP.reactions)) { return true; } return false; } private renderQuickEmojiChoice(emoji: string) { const child = h(Text, {style: styles.quickEmojiChoice}, emoji); return h( Touchable, { ...touchableProps, onPress: () => this.onSelectEmojiReaction(emoji), style: Platform.OS === 'web' ? styles.quickEmojiChoiceTouchable : null, accessible: true, accessibilityRole: 'button', }, [ Platform.OS === 'web' ? child : h(View, {style: styles.quickEmojiChoiceTouchable}, [child]), ], ); } private renderShowAllEmojisChoice() { const child = h(Icon, { style: styles.quickEmojiChoice, key: 'showall', color: Palette.textWeak, name: 'dots-horizontal', }); return h( Touchable, { ...touchableProps, style: Platform.OS === 'web' ? styles.quickEmojiChoiceTouchable : null, onPress: this.openFullEmojiPicker, accessible: true, accessibilityRole: 'button', accessibilityLabel: t( 'message.reactions.show_more.accessibility_label', ), }, [ Platform.OS === 'web' ? child : h(View, {style: styles.quickEmojiChoiceTouchable}, [child]), ], ); } private renderQuickEmojiPickerModal() { return h( Modal, { animationType: 'none', transparent: true, hardwareAccelerated: true, visible: this.state.showQuickEmojis, onRequestClose: this.closeQuickEmojiPicker, }, [ h(View, {style: styles.quickEmojiPickerModal}, [ h(View, {style: styles.quickEmojiPickerContainer}, [ h(View, {style: styles.quickEmojiPickerRow}, [ this.renderQuickEmojiChoice(THUMBS_UP_UNICODE), this.renderQuickEmojiChoice(VICTORY_HAND_UNICODE), this.renderQuickEmojiChoice(HEART_UNICODE), this.renderQuickEmojiChoice(SEE_NO_EVIL_MONKEY_UNICODE), ]), h(View, {style: styles.quickEmojiPickerRow}, [ this.renderQuickEmojiChoice(SMILING_WITH_HEART_EYES_UNICODE), this.renderQuickEmojiChoice(GRINNING_WITH_SMILE_UNICODE), this.renderQuickEmojiChoice(CRYING_FACE_UNICODE), this.renderShowAllEmojisChoice(), ]), ]), h(TouchableWithoutFeedback, {onPress: this.closeQuickEmojiPicker}, [ h(View, {style: styles.quickEmojiPickerBackground}), ]), ]), ], ); } private renderFullEmojiPickerModal() { if (!this.state.showQuickEmojis && !this.state.showFullEmojis) return null; return h( Modal, { animationType: 'none', transparent: true, hardwareAccelerated: true, visible: this.state.showFullEmojis, onRequestClose: this.closeFullEmojiPicker, }, [ h(EmojiPicker, { onEmojiSelected: this.onSelectEmojiReaction, onPressOutside: this.closeFullEmojiPicker, rows: 6, hideClearButton: true, localizedCategories: [ t('message.reactions.categories.smileys_and_emotion'), t('message.reactions.categories.people_and_body'), t('message.reactions.categories.animals_and_nature'), t('message.reactions.categories.food_and_drink'), t('message.reactions.categories.activities'), t('message.reactions.categories.travel_and_places'), t('message.reactions.categories.objects'), t('message.reactions.categories.symbols'), ], modalStyle: styles.fullEmojiPickerModal, backgroundStyle: styles.fullEmojiPickerBackground, containerStyle: styles.fullEmojiPickerContainer, scrollStyle: styles.fullEmojiPickerScroll, headerStyle: styles.fullEmojiPickerHeader, emojiStyle: styles.fullEmojiPickerEmoji, }), ], ); } public render() { const props = this.props; const shouldShowReply = !!props.onPressReply; const reactions = props.reactions ?? []; const replyCount = props.replyCount; this.myReaction = this.findMyLatestReaction(); return h(View, {style: [styles.container, props.style]}, [ this.renderQuickEmojiPickerModal(), this.renderFullEmojiPickerModal(), h(View, {key: 'summary', style: styles.reactionsContainer}, [ h(Reactions, {reactions, onPress: this.onPressReactionsHandler}), ]), h(View, {key: 'buttons', style: styles.buttonsContainer}, [ h(AddReactionButton, { key: 'react', onPress: this.onPressAddReactionHandler, myReaction: this.myReaction, }), h(ReplyButton, { key: 'reply', replyCount, enabled: shouldShowReply, onPress: props.onPressReply, }), h(EtcButton, {key: 'etc', onPress: this.onPressEtcHandler}), ]), ]); } }
the_stack
import { CSS, KeyCode, KeyEvent } from '../lib/Constants'; import { LocalStorage } from '../lib/LocalStorage'; import { Messaging } from '../lib/Messaging'; import { Remote } from '../lib/Remote'; import { BooleanVariable } from './variables/BooleanVariable'; import { ColorVariable } from './variables/ColorVariable'; import { NumberVariable } from './variables/NumberVariable'; import { IRangeVariableParams, RangeVariable } from './variables/RangeVariable'; import { StringVariable } from './variables/StringVariable'; import { IVariableCallback, IVariableKeyMap, Variable } from './variables/Variable'; import '../ui/styles/iframe.less'; /** * A declaration used for the webpack `html-loader` module to load string * content from a given path. * @param {string} path The url path of string to content to load. * @return {string} Returns the string at given path. */ declare function require(path: string): string; /** * The Remixer class is a singleton class that keeps track of all the Variables * and deals with saving/syncing its values. * @class */ class Remixer { /** * Initializes a new instance of Remixer. * @private * @static * @return {Remixer} A new instance of Remixer. */ private static _sharedInstance = new Remixer(); /** * Provides ability for Remixer HTML iFrame to access this instance of Remixer. * @return {Remixer} The attached instance of Remixer. */ static get attachedInstance(): Remixer { const parentRemixer = window.parent['remixer']; if (parentRemixer) { return parentRemixer._sharedInstance as Remixer; } // Simply return shared remixer instance if no parent. return this._sharedInstance; } private _frameElement: HTMLFrameElement; /** * Returns the HTML iFrame added for this instance of Remixer. * @static * @return {HTMLFrameElement} The Remixer HTML iFrame. */ static get frameElement(): HTMLFrameElement { return this._sharedInstance._frameElement; } /** * Appends an HTML iFrame to the body of client page. * @private */ private appendFrameToBody(): void { if (!this._frameElement) { const frame = document.createElement('IFRAME') as HTMLFrameElement; frame.id = CSS.RMX_OVERLAY_FRAME; frame.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups'); document.getElementsByTagName('body')[0].appendChild(frame); // Until `srcdoc` is fully compatible with all browsers, lets simply // write the overlay html content to the iframe content window. const iframeContent: string = require('../ui/templates/overlay_iframe.html'); frame.contentWindow.document.open(); frame.contentWindow.document.write(iframeContent); frame.contentWindow.document.close(); this._frameElement = frame; } } /** * Adds a key listener used to trigger the Remixer overlay. * @private */ private addKeyListener(): void { document.addEventListener(KeyEvent.DOWN, (e: KeyboardEvent) => { if (e.keyCode === KeyCode.ESC) { Messaging.postToFrame(Messaging.type.ToggleVisibility); } }); } /** * Appends the HTML iFrame to body of client app. Attaches key listener to * toggle Overlay visibility. * @static * @param {{}} remoteConfig The optional firebase configuration. Provide this * configuration if you wish to use the remote * controller. */ static start(remoteConfig: {} = {}): void { this._sharedInstance.appendFrameToBody(); this._sharedInstance.addKeyListener(); Remote.initializeRemote(remoteConfig); } /** * Removes iFrame and attached key listener. * @static */ static stop(): void { // TODO(cjcox): Remove iframe and key listeners. } /** * Adds a boolean Variable to array of Variables with optional callback. * @param {string} key The key of the Variable. * @param {boolean} defaultValue The initial default value of the variable. * @param {IVariableCallback} callback The callback method to be invoked * when the Variable is updated. * @return {BooleanVariable} */ static addBooleanVariable( key: string, defaultValue: boolean, callback?: IVariableCallback, ): BooleanVariable { const variable = new BooleanVariable(key, defaultValue, callback); this.addVariable(variable); return variable; } /** * Adds a range Variable to array of Variables with optional callback. * @param {string} key The key of the Variable. * @param {number} defaultValue The initial default value of the variable. * @param {number} minValue The allowed minimum value of the variable. * @param {number} maxValue The allowed maximum value of the variable. * @param {number} increment The amount to increment the value. * @param {IVariableCallback} callback The callback method to be invoked * when the Variable is updated. * @return {RangeVariable} */ static addRangeVariable( key: string, defaultValue: number, minValue: number, maxValue: number, increment: number, callback?: IVariableCallback, ): RangeVariable { const variable = new RangeVariable(key, defaultValue, minValue, maxValue, increment, callback); this.addVariable(variable); return variable; } /** * Adds a string Variable to array of variables with optional callback * @param {string} key The key of the Variable. * @param {string} defaultValue The initial default value of the variable. * @param {string[]} limitedToValues The optional array of allowed values. * @param {IVariableCallback} callback The callback method to be invoked * when the Variable is updated. * @return {StringVariable} */ static addStringVariable( key: string, defaultValue: string, limitedToValues?: string[], callback?: IVariableCallback, ): StringVariable { const variable = new StringVariable(key, defaultValue, limitedToValues, callback); this.addVariable(variable); return variable; } /** * Adds a number variable to array of variables with optional callback. * @param {string} key The key of the Variable. * @param {number} defaultValue The initial default value of the variable. * @param {number[]} limitedToValues The optional array of allowed values. * @param {IVariableCallback} callback The callback method to be invoked * when the Variable is updated. * @return {NumberVariable} */ static addNumberVariable( key: string, defaultValue: number, limitedToValues?: number[], callback?: IVariableCallback, ): NumberVariable { const variable = new NumberVariable(key, defaultValue, limitedToValues, callback); this.addVariable(variable); return variable; } /** * Adds a color variable to array of variables with optional callback. * @param {string} key The key of the Variable. * @param {string} defaultValue The initial default value of the variable. * @param {string[]} limitedToValues The optional array of allowed values. * @param {IVariableCallback} callback The callback method to be invoked * when the Variable is updated. * @return {ColorVariable} */ static addColorVariable( key: string, defaultValue: string, limitedToValues?: string[], callback?: IVariableCallback, ): ColorVariable { const variable = new ColorVariable(key, defaultValue, limitedToValues, callback); this.addVariable(variable); return variable; } /** * Adds a variable to the array of variables. Once added, will save and * execute the callback. * @private * @static * @param {Variable} variable The variable to add. */ private static addVariable(variable: Variable): void { const key: string = variable.key; const existingVariable = this.getVariable(key); if (existingVariable) { // Variable with key already exists, so only add callback. // TODO(cjcox:) Determine what to do if variable key already exists. } else { this._sharedInstance._variables[key] = variable; const storedVariable = LocalStorage.getVariable(key); if (storedVariable) { // Update variable if exists in storage. this.updateVariable(variable, storedVariable.selectedValue); Remote.saveVariable(variable, false); } else { // Save variable first time. this.saveVariable(variable); variable.executeCallbacks(); } } } private _variables: IVariableKeyMap = {}; /** * Returns the Variable-Key mapping from the Remixer shared instance. * @return {IVariableKeyMap} */ get variables(): IVariableKeyMap { return this._variables; } /** * Returns an array of Variables from the Remixer shared instance. * @return {Variable[]} Array of Variables. */ get variablesArray(): Variable[] { return Object.keys(this._variables).map((key) => this._variables[key]); } /** * Returns an Variable for a given key from the Remixer shared instance. * @static * @return {Variable[]} Array of Variables. */ static getVariable(key: string): Variable { return this._sharedInstance._variables[key]; } /** * Updates the selected value of a given Variable from the Remixer shared * instance. * @static * @param {Variable} variable The Variable to update. * @param {any} selectedValue The new selected value. */ static updateVariable(variable: Variable, selectedValue: any): void { if (variable.selectedValue !== selectedValue) { variable.selectedValue = selectedValue; } } /** * Clones and updates the selected value of a given Variable from the Remixer * shared instance. Allows immutability update required for React rendering. * @static * @param {Variable} variable The variable to clone and update. * @param {any} selectedValue The new selected value. * @return {Variable} The cloned variable with updated selected value. */ static cloneAndUpdateVariable(variable: Variable, selectedValue: any): Variable { // First make sure selected value is in proper format. selectedValue = variable.formatValue(selectedValue); if (variable.selectedValue === selectedValue) { return variable; } const clonedVariable = variable.clone(); this.attachedInstance._variables[variable.key] = clonedVariable; this.updateVariable(clonedVariable, selectedValue); return clonedVariable; } /** * Saves the Variable to both local storage and remote. * @static * @param {Variable} variable The Variable to save. */ static saveVariable(variable: Variable): void { LocalStorage.saveVariable(variable); // Save remotely. If remote sharing is disabled, a call to this method // will simply be a no-op. Remote.saveVariable(variable); } /** * Returns the current remote controller class. * @return {Remote} */ get remote(): Remote { return Remote.attachedInstance; } } // Export Remixer. export { Remixer as remixer };
the_stack
import Point from '../util/point'; import {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf'; import type Anchor from './anchor'; import type {PositionedIcon, Shaping} from './shaping'; import {SHAPING_DEFAULT_OFFSET} from './shaping'; import {IMAGE_PADDING} from '../render/image_atlas'; import type SymbolStyleLayer from '../style/style_layer/symbol_style_layer'; import type {Feature} from '../style-spec/expression'; import type {StyleImage} from '../style/style_image'; import ONE_EM from './one_em'; import {Rect} from '../render/glyph_atlas'; /** * A textured quad for rendering a single icon or glyph. * * The zoom range the glyph can be shown is defined by minScale and maxScale. * * @param tl The offset of the top left corner from the anchor. * @param tr The offset of the top right corner from the anchor. * @param bl The offset of the bottom left corner from the anchor. * @param br The offset of the bottom right corner from the anchor. * @param tex The texture coordinates. * * @private */ export type SymbolQuad = { tl: Point; tr: Point; bl: Point; br: Point; tex: { x: number; y: number; w: number; h: number; }; pixelOffsetTL: Point; pixelOffsetBR: Point; writingMode: any | void; glyphOffset: [number, number]; sectionIndex: number; isSDF: boolean; minFontScaleX: number; minFontScaleY: number; }; // If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual // pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped // on one edge in some cases. const border = IMAGE_PADDING; /** * Create the quads used for rendering an icon. * @private */ export function getIconQuads( shapedIcon: PositionedIcon, iconRotate: number, isSDFIcon: boolean, hasIconTextFit: boolean ): Array<SymbolQuad> { const quads = []; const image = shapedIcon.image; const pixelRatio = image.pixelRatio; const imageWidth = image.paddedRect.w - 2 * border; const imageHeight = image.paddedRect.h - 2 * border; const iconWidth = shapedIcon.right - shapedIcon.left; const iconHeight = shapedIcon.bottom - shapedIcon.top; const stretchX = image.stretchX || [[0, imageWidth]]; const stretchY = image.stretchY || [[0, imageHeight]]; const reduceRanges = (sum, range) => sum + range[1] - range[0]; const stretchWidth = stretchX.reduce(reduceRanges, 0); const stretchHeight = stretchY.reduce(reduceRanges, 0); const fixedWidth = imageWidth - stretchWidth; const fixedHeight = imageHeight - stretchHeight; let stretchOffsetX = 0; let stretchContentWidth = stretchWidth; let stretchOffsetY = 0; let stretchContentHeight = stretchHeight; let fixedOffsetX = 0; let fixedContentWidth = fixedWidth; let fixedOffsetY = 0; let fixedContentHeight = fixedHeight; if (image.content && hasIconTextFit) { const content = image.content; stretchOffsetX = sumWithinRange(stretchX, 0, content[0]); stretchOffsetY = sumWithinRange(stretchY, 0, content[1]); stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]); stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]); fixedOffsetX = content[0] - stretchOffsetX; fixedOffsetY = content[1] - stretchOffsetY; fixedContentWidth = content[2] - content[0] - stretchContentWidth; fixedContentHeight = content[3] - content[1] - stretchContentHeight; } const makeBox = (left, top, right, bottom) => { const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth); const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight); const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left); const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth); const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top); const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight); const tl = new Point(leftEm, topEm); const tr = new Point(rightEm, topEm); const br = new Point(rightEm, bottomEm); const bl = new Point(leftEm, bottomEm); const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio); const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio); const angle = iconRotate * Math.PI / 180; if (angle) { const sin = Math.sin(angle), cos = Math.cos(angle), matrix = [cos, -sin, sin, cos]; tl._matMult(matrix); tr._matMult(matrix); bl._matMult(matrix); br._matMult(matrix); } const x1 = left.stretch + left.fixed; const x2 = right.stretch + right.fixed; const y1 = top.stretch + top.fixed; const y2 = bottom.stretch + bottom.fixed; const subRect = { x: image.paddedRect.x + border + x1, y: image.paddedRect.y + border + y1, w: x2 - x1, h: y2 - y1 }; const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth; const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight; // Icon quad is padded, so texture coordinates also need to be padded. return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon}; }; if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) { quads.push(makeBox( {fixed: 0, stretch: -1}, {fixed: 0, stretch: -1}, {fixed: 0, stretch: imageWidth + 1}, {fixed: 0, stretch: imageHeight + 1})); } else { const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth); const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight); for (let xi = 0; xi < xCuts.length - 1; xi++) { const x1 = xCuts[xi]; const x2 = xCuts[xi + 1]; for (let yi = 0; yi < yCuts.length - 1; yi++) { const y1 = yCuts[yi]; const y2 = yCuts[yi + 1]; quads.push(makeBox(x1, y1, x2, y2)); } } } return quads; } function sumWithinRange(ranges, min, max) { let sum = 0; for (const range of ranges) { sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0])); } return sum; } function stretchZonesToCuts(stretchZones, fixedSize, stretchSize) { const cuts = [{fixed: -border, stretch: 0}]; for (const [c1, c2] of stretchZones) { const last = cuts[cuts.length - 1]; cuts.push({ fixed: c1 - last.stretch, stretch: last.stretch }); cuts.push({ fixed: c1 - last.stretch, stretch: last.stretch + (c2 - c1) }); } cuts.push({ fixed: fixedSize + border, stretch: stretchSize }); return cuts; } function getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) { return stretchOffset / stretchSize * iconSize + iconOffset; } function getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) { return fixedOffset - fixedSize * stretchOffset / stretchSize; } /** * Create the quads used for rendering a text label. * @private */ export function getGlyphQuads( anchor: Anchor, shaping: Shaping, textOffset: [number, number], layer: SymbolStyleLayer, alongLine: boolean, feature: Feature, imageMap: {[_: string]: StyleImage}, allowVerticalPlacement: boolean ): Array<SymbolQuad> { const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180; const quads = []; for (const line of shaping.positionedLines) { for (const positionedGlyph of line.positionedGlyphs) { if (!positionedGlyph.rect) continue; const textureRect: Rect = positionedGlyph.rect || {} as Rect; // The rects have an additional buffer that is not included in their size. const glyphPadding = 1.0; let rectBuffer = GLYPH_PBF_BORDER + glyphPadding; let isSDF = true; let pixelRatio = 1.0; let lineOffset = 0.0; const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical; const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2; // Align images and scaled glyphs in the middle of a vertical line. if (allowVerticalPlacement && shaping.verticalizable) { const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM; const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2; lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset); } if (positionedGlyph.imageName) { const image = imageMap[positionedGlyph.imageName]; isSDF = image.sdf; pixelRatio = image.pixelRatio; rectBuffer = IMAGE_PADDING / pixelRatio; } const glyphOffset = alongLine ? [positionedGlyph.x + halfAdvance, positionedGlyph.y] : [0, 0]; let builtInOffset: [number, number] = alongLine ? [0, 0] : [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset]; let verticalizedLabelOffset = [0, 0] as [number, number]; if (rotateVerticalGlyph) { // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset. verticalizedLabelOffset = builtInOffset; builtInOffset = [0, 0]; } const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0]; const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1]; const x2 = x1 + textureRect.w * positionedGlyph.scale / pixelRatio; const y2 = y1 + textureRect.h * positionedGlyph.scale / pixelRatio; const tl = new Point(x1, y1); const tr = new Point(x2, y1); const bl = new Point(x1, y2); const br = new Point(x2, y2); if (rotateVerticalGlyph) { // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em) // In horizontal orientation, the y values for glyphs are below the midline // and we use a "yOffset" of -17 to pull them up to the middle. // By rotating counter-clockwise around the point at the center of the left // edge of a 24x24 layout box centered below the midline, we align the center // of the glyphs with the horizontal midline, so the yOffset is no longer // necessary, but we also pull the glyph to the left along the x axis. // The y coordinate includes baseline yOffset, thus needs to be accounted // for when glyph is rotated and translated. const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET); const verticalRotation = -Math.PI / 2; // xHalfWidthOffsetCorrection is a difference between full-width and half-width // advance, should be 0 for full-width glyphs and will pull up half-width glyphs. const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance; const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0; const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection); const verticalOffsetCorrection = new Point(...verticalizedLabelOffset); tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection); } if (textRotate) { const sin = Math.sin(textRotate), cos = Math.cos(textRotate), matrix = [cos, -sin, sin, cos]; tl._matMult(matrix); tr._matMult(matrix); bl._matMult(matrix); br._matMult(matrix); } const pixelOffsetTL = new Point(0, 0); const pixelOffsetBR = new Point(0, 0); const minFontScaleX = 0; const minFontScaleY = 0; quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY}); } } return quads; }
the_stack
import "./helpers/dotenv_helper"; import { getTestId, getState, dispatch } from "./helpers/test_helper"; import { testExport } from "./helpers/export_helper"; import { envkeyFetch } from "./helpers/fetch_helper"; import * as R from "ramda"; import { createApp } from "./helpers/apps_helper"; import { registerWithEmail, loadAccount } from "./helpers/auth_helper"; import { createBlock, connectBlocks } from "./helpers/blocks_helper"; import { getEnvironments, updateEnvs, updateLocals, } from "./helpers/envs_helper"; import { getUserEncryptedKeyOrBlobComposite } from "@core/lib/blob"; import { getAuth, getEnvWithMeta } from "@core/lib/client"; import { Client, Api, Model } from "@core/types"; import { graphTypes } from "@core/lib/graph"; import { acceptInvite } from "./helpers/invites_helper"; import { getUserEncryptedKeys } from "@api_shared/blob"; import { query } from "@api_shared/db"; import { log } from "@core/lib/utils/logger"; describe("blocks", () => { let email: string, ownerId: string, ownerDeviceId: string, orgId: string; beforeEach(async () => { email = `success+${getTestId()}@simulator.amazonses.com`; ({ userId: ownerId, orgId, deviceId: ownerDeviceId, } = await registerWithEmail(email)); }); test("create", async () => { await createBlock(ownerId); }); test("rename", async () => { const { id } = await createBlock(ownerId), promise = dispatch( { type: Api.ActionType.RENAME_BLOCK, payload: { id, name: "Renamed-Block", }, }, ownerId ); let state = getState(ownerId); expect(state.isRenaming[id]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); expect(state.isRenaming[id]).toBeUndefined(); expect(state.graph[id]).toEqual( expect.objectContaining({ name: "Renamed-Block", }) ); }); test("update settings", async () => { const { id } = await createBlock(ownerId), promise = dispatch( { type: Api.ActionType.UPDATE_BLOCK_SETTINGS, payload: { id, settings: { autoCaps: false }, }, }, ownerId ); let state = getState(ownerId); expect(state.isUpdatingSettings[id]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); expect(state.isUpdatingSettings[id]).toBeUndefined(); expect(state.graph[id]).toEqual( expect.objectContaining({ settings: { autoCaps: false, }, }) ); }); test("delete block", async () => { const { id: appId } = await createApp(ownerId); const { id: blockId } = await createBlock(ownerId); await updateEnvs(ownerId, appId); await updateLocals(ownerId, appId); await updateEnvs(ownerId, blockId); await updateLocals(ownerId, blockId); await connectBlocks(ownerId, [{ appId, blockId, orderIndex: 0 }]); let state = getState(ownerId), { orgRoles } = graphTypes(state.graph); const basicRole = R.indexBy(R.prop("name"), orgRoles)["Basic User"]; await dispatch( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Invited", lastName: "User", email: `success+invitee-${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+invitee-${getTestId()}@simulator.amazonses.com`, orgRoleId: basicRole.id, }, }, ], }, ownerId ); state = getState(ownerId); const inviteParams = state.generatedInvites[0], inviteeId = inviteParams.user.id; const { appRoles } = graphTypes(state.graph), prodRole = R.indexBy(R.prop("name"), appRoles)["DevOps"], [appDevelopment] = getEnvironments(ownerId, appId); await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: appDevelopment.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Test Server", environmentId: appDevelopment.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.GRANT_APPS_ACCESS, payload: [{ appId: appId, userId: inviteeId, appRoleId: prodRole.id }], }, ownerId ); await acceptInvite(inviteParams); state = getState(inviteeId); const inviteeDeviceId = getAuth<Client.ClientUserAuth>( state, inviteeId )!.deviceId; await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: appDevelopment.id, }, }, inviteeId ); await loadAccount(ownerId); const promise = dispatch( { type: Api.ActionType.DELETE_BLOCK, payload: { id: blockId }, }, ownerId ); state = getState(ownerId); expect(state.isRemoving[blockId]).toBeTrue(); const res = await promise; expect(res.success).toBeTrue(); state = getState(ownerId); const { appBlocks, generatedEnvkeys } = graphTypes(state.graph); expect(state.isRemoving[blockId]).toBeUndefined(); // ensure block deleted expect(state.graph[blockId]).toBeUndefined(); // ensure associations are deleted expect(R.flatten([appBlocks])).toEqual([]); // ensure encrypted keys are deleted // --> user encrypted keys for (let [userId, deviceId] of [ [ownerId, ownerDeviceId], [inviteeId, inviteeDeviceId], ]) { let encryptedKeys = await getUserEncryptedKeys( { orgId, userId, deviceId, blobType: "env", }, { transactionConn: undefined } ); encryptedKeys = encryptedKeys.filter( ({ envParentId }) => envParentId == blockId ); expect(encryptedKeys).toEqual([]); } // --> generated envkey encrypted keys for (let { id: generatedEnvkeyId } of generatedEnvkeys) { let blobs = await query<Api.Db.GeneratedEnvkeyEncryptedKey>({ pkey: ["envkey", generatedEnvkeyId].join("|"), transactionConn: undefined, }); blobs = blobs.filter((blob) => "blockId" in blob && blob.blockId); expect(blobs).toEqual([]); } }); test("manage app-block connections", async () => { const [{ id: appId }, { id: block1Id }, { id: block2Id }] = [ await createApp(ownerId), await createBlock(ownerId, "Block 1"), await createBlock(ownerId, "Block 2"), ]; let state = getState(ownerId); const { orgRoles, appRoles, environmentRoles } = graphTypes(state.graph), basicUserRole = R.indexBy(R.prop("name"), orgRoles)["Basic User"], appDevRole = R.indexBy(R.prop("name"), appRoles)["Developer"], [appDevelopment, appStaging, appProduction] = getEnvironments( ownerId, appId ), [block1Development, block1Staging, block1Production] = getEnvironments( ownerId, block1Id ), [block2Development, block2Staging, block2Production] = getEnvironments( ownerId, block2Id ), productionRole = R.indexBy(R.prop("name"), environmentRoles)[ "Production" ]; await dispatch<Client.Action.ClientActions["InviteUsers"]>( { type: Client.ActionType.INVITE_USERS, payload: [ { user: { firstName: "Dev", lastName: "User", email: `success+dev-user-${getTestId()}@simulator.amazonses.com`, provider: <const>"email", uid: `success+dev-user-${getTestId()}@simulator.amazonses.com`, orgRoleId: basicUserRole.id, }, appUserGrants: [ { appId, appRoleId: appDevRole.id, }, ], }, ], }, ownerId ); state = getState(ownerId); const devUserInviteParams = state.generatedInvites[0]; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { envParentId: appId, environmentRoleId: productionRole.id, isSub: true, parentEnvironmentId: appProduction.id, subName: "prod-sub", }, }, ownerId ); state = getState(ownerId); const appProdSubEnv = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) ) as Model.Environment; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { envParentId: block1Id, environmentRoleId: productionRole.id, isSub: true, parentEnvironmentId: block1Production.id, subName: "prod-sub", }, }, ownerId ); state = getState(ownerId); const block1ProdSubEnv = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) ) as Model.Environment; await dispatch( { type: Api.ActionType.CREATE_ENVIRONMENT, payload: { envParentId: block2Id, environmentRoleId: productionRole.id, isSub: true, parentEnvironmentId: block2Production.id, subName: "prod-sub", }, }, ownerId ); state = getState(ownerId); const block2ProdSubEnv = R.last( R.sortBy(R.prop("createdAt"), graphTypes(state.graph).environments) ) as Model.Environment; await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: appDevelopment.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Test Server", environmentId: appDevelopment.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Staging Server", environmentId: appStaging.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Production Server", environmentId: appProduction.id, }, }, ownerId ); await dispatch( { type: Client.ActionType.CREATE_SERVER, payload: { appId, name: "Prod SubEnv Server", environmentId: appProdSubEnv.id, }, }, ownerId ); state = getState(ownerId); const [ { envkeyIdPart: localEnvkeyIdPart, encryptionKey: localEncryptionKey }, { envkeyIdPart: developmentEnvkeyIdPart, encryptionKey: developmentEncryptionKey, }, { envkeyIdPart: stagingEnvkeyIdPart, encryptionKey: stagingEncryptionKey, }, { envkeyIdPart: productionEnvkeyIdPart, encryptionKey: productionEncryptionKey, }, { envkeyIdPart: prodSubEnvkeyIdPart, encryptionKey: prodSubEncryptionKey, }, ] = Object.values(state.generatedEnvkeys); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block1Id, entryKey: "BLOCK_1_KEY", vals: { [block1Development.id]: { val: "block-1-val" }, [block1Staging.id]: { val: "block-1-val" }, [block1Production.id]: { val: "block-1-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block1Id, entryKey: "BLOCK_WILL_OVERRIDE", vals: { [block1Development.id]: { val: "block-1-val" }, [block1Staging.id]: { val: "block-1-val" }, [block1Production.id]: { val: "block-1-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block1Id, entryKey: "APP_WILL_OVERRIDE", vals: { [block1Development.id]: { val: "block-1-val" }, [block1Staging.id]: { val: "block-1-val" }, [block1Production.id]: { val: "block-1-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block1Id, entryKey: "BLOCK_SUB_WILL_OVERRIDE", vals: { [block1Production.id]: { val: "block-1-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block1Id, entryKey: "BLOCK_INHERITANCE", vals: { [block1Development.id]: { inheritsEnvironmentId: block1Staging.id }, [block1Staging.id]: { inheritsEnvironmentId: block1Production.id }, [block1Production.id]: { val: "block-1-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block2Id, entryKey: "BLOCK_2_KEY", vals: { [block2Development.id]: { val: "block-2-val" }, [block2Staging.id]: { val: "block-2-val" }, [block2Production.id]: { val: "block-2-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: block2Id, entryKey: "BLOCK_WILL_OVERRIDE", vals: { [block2Development.id]: { val: "block-2-val" }, [block2Staging.id]: { val: "block-2-val" }, [block2Production.id]: { val: "block-2-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: appId, entryKey: "APP_KEY", vals: { [appDevelopment.id]: { val: "app-val" }, [appStaging.id]: { val: "app-val" }, [appProduction.id]: { val: "app-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY_ROW, payload: { envParentId: appId, entryKey: "APP_WILL_OVERRIDE", vals: { [appDevelopment.id]: { val: "app-val" }, [appStaging.id]: { val: "app-val" }, [appProduction.id]: { val: "app-val" }, }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: block1ProdSubEnv.id, entryKey: "BLOCK_1_SUB", val: { val: "block-1-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: block1ProdSubEnv.id, entryKey: "BLOCK_SUB_WILL_OVERRIDE", val: { val: "block-1-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: block1ProdSubEnv.id, entryKey: "APP_SUB_WILL_OVERRIDE", val: { val: "block-1-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: block2ProdSubEnv.id, entryKey: "BLOCK_2_SUB", val: { val: "block-2-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: block2Staging.id, entryKey: "BLOCK_2_SUB_INHERITANCE", val: { val: "block-2-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: block2ProdSubEnv.id, entryKey: "BLOCK_2_SUB_INHERITANCE", val: { inheritsEnvironmentId: block2Staging.id }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: block2ProdSubEnv.id, entryKey: "BLOCK_SUB_WILL_OVERRIDE", val: { val: "block-2-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: appId, environmentId: appProdSubEnv.id, entryKey: "APP_SUB", val: { val: "app-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: appId, environmentId: appProdSubEnv.id, entryKey: "APP_SUB_WILL_OVERRIDE", val: { val: "app-sub-val" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: [block1Id, ownerId].join("|"), entryKey: "BLOCK_1_LOCALS", val: { val: "block-1-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: [block1Id, ownerId].join("|"), entryKey: "BLOCK_LOCALS_WILL_OVERRIDE", val: { val: "block-1-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: [block2Id, ownerId].join("|"), entryKey: "BLOCK_2_LOCALS", val: { val: "block-2-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: [block2Id, ownerId].join("|"), entryKey: "BLOCK_LOCALS_WILL_OVERRIDE", val: { val: "block-2-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block2Id, environmentId: [block2Id, ownerId].join("|"), entryKey: "APP_LOCALS_WILL_OVERRIDE", val: { val: "block-2-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: appId, environmentId: [appId, ownerId].join("|"), entryKey: "APP_LOCALS", val: { val: "app-locals" }, }, }, ownerId ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: appId, environmentId: [appId, ownerId].join("|"), entryKey: "APP_LOCALS_WILL_OVERRIDE", val: { val: "app-locals" }, }, }, ownerId ); state = getState(ownerId); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: { message: "commit message" }, }, ownerId ); await connectBlocks(ownerId, [ { appId, blockId: block1Id, orderIndex: 0, }, { appId, blockId: block2Id, orderIndex: 1, }, ]); let [ localKeyEnv, devServerEnv, stagingServerEnv, prodServerEnv, prodSubEnv, ] = await Promise.all([ envkeyFetch(localEnvkeyIdPart, localEncryptionKey), envkeyFetch(developmentEnvkeyIdPart, developmentEncryptionKey), envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey), envkeyFetch(productionEnvkeyIdPart, productionEncryptionKey), envkeyFetch(prodSubEnvkeyIdPart, prodSubEncryptionKey), ]); let shouldEq: Client.Env.RawEnv = { BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_1_LOCALS: "block-1-locals", BLOCK_2_LOCALS: "block-2-locals", BLOCK_LOCALS_WILL_OVERRIDE: "block-2-locals", APP_LOCALS_WILL_OVERRIDE: "app-locals", APP_LOCALS: "app-locals", }; expect(localKeyEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: [appId, ownerId].join("|"), includeAncestors: true, }, shouldEq ); shouldEq = { BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", }; expect(devServerEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appDevelopment.id, includeAncestors: true, }, shouldEq ); expect(stagingServerEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_2_SUB_INHERITANCE: "block-2-val", }); expect(prodServerEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", BLOCK_SUB_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", }); shouldEq = { BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_1_SUB: "block-1-sub-val", BLOCK_SUB_WILL_OVERRIDE: "block-2-sub-val", APP_SUB_WILL_OVERRIDE: "app-sub-val", BLOCK_2_SUB: "block-2-sub-val", BLOCK_2_SUB_INHERITANCE: "block-2-val", APP_SUB: "app-sub-val", }; expect(prodSubEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appProdSubEnv.id, includeAncestors: true, }, shouldEq ); // accept invite and fetch with invitee and ensure proper block access await acceptInvite(devUserInviteParams); await dispatch( { type: Client.ActionType.GET_SESSION, }, devUserInviteParams.user.id ); await dispatch( { type: Client.ActionType.FETCH_ENVS, payload: { byEnvParentId: { [appId]: { envs: true, changesets: true }, }, }, }, devUserInviteParams.user.id ); state = getState(devUserInviteParams.user.id); expect( getEnvWithMeta(state, { envParentId: appId, environmentId: appDevelopment.id, }) ).toEqual({ inherits: {}, variables: { APP_WILL_OVERRIDE: { val: "app-val", }, APP_KEY: { val: "app-val", }, }, }); expect( getEnvWithMeta(state, { envParentId: appId, environmentId: appStaging.id, }) ).toEqual({ inherits: {}, variables: { APP_WILL_OVERRIDE: { val: "app-val", }, APP_KEY: { val: "app-val", }, }, }); expect( getEnvWithMeta(state, { envParentId: appId, environmentId: appProduction.id, }) ).toEqual({ inherits: {}, variables: { APP_WILL_OVERRIDE: {}, APP_KEY: {}, }, }); expect( getEnvWithMeta(state, { envParentId: appId, environmentId: appProdSubEnv.id, }) ).toEqual({ inherits: {}, variables: { APP_SUB_WILL_OVERRIDE: {}, APP_SUB: {}, }, }); expect( getEnvWithMeta(state, { envParentId: block1Id, environmentId: block1Development.id, }) ).toEqual({ inherits: { [block1Staging.id]: ["BLOCK_INHERITANCE"], }, variables: { BLOCK_1_KEY: { val: "block-1-val", }, BLOCK_WILL_OVERRIDE: { val: "block-1-val", }, APP_WILL_OVERRIDE: { val: "block-1-val", }, BLOCK_INHERITANCE: { inheritsEnvironmentId: block1Staging.id, }, }, }); expect( getEnvWithMeta(state, { envParentId: block1Id, environmentId: block1Staging.id, }) ).toEqual({ inherits: { [block1Production.id]: ["BLOCK_INHERITANCE"], }, variables: { BLOCK_1_KEY: { val: "block-1-val", }, BLOCK_WILL_OVERRIDE: { val: "block-1-val", }, APP_WILL_OVERRIDE: { val: "block-1-val", }, BLOCK_INHERITANCE: { inheritsEnvironmentId: block1Production.id, }, }, }); expect( getEnvWithMeta(state, { envParentId: block1Id, environmentId: block1Production.id, }) ).toEqual({ inherits: {}, variables: { BLOCK_1_KEY: {}, BLOCK_WILL_OVERRIDE: {}, APP_WILL_OVERRIDE: {}, BLOCK_INHERITANCE: {}, BLOCK_SUB_WILL_OVERRIDE: {}, }, }); expect( getEnvWithMeta(state, { envParentId: block1Id, environmentId: block1ProdSubEnv.id, }) ).toEqual({ inherits: {}, variables: { BLOCK_1_SUB: {}, BLOCK_SUB_WILL_OVERRIDE: {}, APP_SUB_WILL_OVERRIDE: {}, }, }); expect( getEnvWithMeta(state, { envParentId: block2Id, environmentId: block2Development.id, }) ).toEqual({ inherits: {}, variables: { BLOCK_2_KEY: { val: "block-2-val", }, BLOCK_WILL_OVERRIDE: { val: "block-2-val", }, }, }); expect( getEnvWithMeta(state, { envParentId: block2Id, environmentId: block2Staging.id, }) ).toEqual({ inherits: {}, variables: { BLOCK_2_KEY: { val: "block-2-val", }, BLOCK_WILL_OVERRIDE: { val: "block-2-val", }, BLOCK_2_SUB_INHERITANCE: { val: "block-2-val", }, }, }); expect( getEnvWithMeta(state, { envParentId: block2Id, environmentId: block2Production.id, }) ).toEqual({ inherits: {}, variables: { BLOCK_2_KEY: {}, BLOCK_WILL_OVERRIDE: {}, }, }); expect( getEnvWithMeta(state, { envParentId: block2Id, environmentId: block2ProdSubEnv.id, }) ).toEqual({ inherits: { [block2Staging.id]: ["BLOCK_2_SUB_INHERITANCE"], }, variables: { BLOCK_2_SUB: {}, BLOCK_SUB_WILL_OVERRIDE: {}, BLOCK_2_SUB_INHERITANCE: { inheritsEnvironmentId: block2Staging.id }, }, }); expect( state.envs[ getUserEncryptedKeyOrBlobComposite({ environmentId: [appId, ownerId].join("|"), }) ] ).toBeUndefined(); expect( state.envs[ getUserEncryptedKeyOrBlobComposite({ environmentId: [block1Id, ownerId].join("|"), }) ] ).toBeUndefined(); expect( state.envs[ getUserEncryptedKeyOrBlobComposite({ environmentId: [block2Id, ownerId].join("|"), }) ] ).toBeUndefined(); // ensure key generation works with connected blocks await dispatch( { type: Client.ActionType.CREATE_LOCAL_KEY, payload: { appId, name: "Development Key", environmentId: appDevelopment.id, }, }, devUserInviteParams.user.id ); state = getState(devUserInviteParams.user.id); const [ { envkeyIdPart: inviteeLocalEnvkeyIdPart, encryptionKey: inviteeLocalEncryptionKey, }, ] = Object.values(state.generatedEnvkeys); let inviteeLocalKeyEnv = await envkeyFetch( inviteeLocalEnvkeyIdPart, inviteeLocalEncryptionKey ); expect(inviteeLocalKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", }); // ensure updating block/app envs still works correctly dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block1Id, entryKey: "BLOCK_1_KEY", environmentId: block1Development.id, update: { val: "block-1-val-updated" }, }, }, devUserInviteParams.user.id ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block1Id, entryKey: "BLOCK_INHERITANCE", environmentId: block1Staging.id, update: { val: "block-1-val-updated" }, }, }, devUserInviteParams.user.id ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block2Id, entryKey: "BLOCK_2_SUB_INHERITANCE", environmentId: block2Staging.id, update: { val: "block-2-val-updated" }, }, }, devUserInviteParams.user.id ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: appId, entryKey: "APP_KEY", environmentId: appDevelopment.id, update: { val: "app-val-updated" }, }, }, devUserInviteParams.user.id ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: block1Id, environmentId: [block1Id, devUserInviteParams.user.id].join("|"), entryKey: "BLOCK_1_LOCALS", val: { val: "block-1-locals" }, }, }, devUserInviteParams.user.id ); dispatch( { type: Client.ActionType.CREATE_ENTRY, payload: { envParentId: appId, environmentId: [appId, devUserInviteParams.user.id].join("|"), entryKey: "APP_LOCALS", val: { val: "app-locals" }, }, }, devUserInviteParams.user.id ); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: { message: "commit message" }, }, devUserInviteParams.user.id ); [ inviteeLocalKeyEnv, localKeyEnv, devServerEnv, stagingServerEnv, prodSubEnv, ] = await Promise.all([ envkeyFetch(inviteeLocalEnvkeyIdPart, inviteeLocalEncryptionKey), envkeyFetch(localEnvkeyIdPart, localEncryptionKey), envkeyFetch(developmentEnvkeyIdPart, developmentEncryptionKey), envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey), envkeyFetch(prodSubEnvkeyIdPart, prodSubEncryptionKey), ]); expect(inviteeLocalKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals", APP_LOCALS: "app-locals", }); expect(localKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals", BLOCK_2_LOCALS: "block-2-locals", BLOCK_LOCALS_WILL_OVERRIDE: "block-2-locals", APP_LOCALS_WILL_OVERRIDE: "app-locals", APP_LOCALS: "app-locals", }); expect(devServerEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", }); expect(stagingServerEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", }); expect(prodSubEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_1_SUB: "block-1-sub-val", BLOCK_SUB_WILL_OVERRIDE: "block-2-sub-val", APP_SUB_WILL_OVERRIDE: "app-sub-val", BLOCK_2_SUB: "block-2-sub-val", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", APP_SUB: "app-sub-val", }); // ensure updating locals and subenv still working correctly await loadAccount(ownerId); // locals dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block1Id, environmentId: [block1Id, ownerId].join("|"), entryKey: "BLOCK_1_LOCALS", update: { val: "block-1-locals-updated" }, }, }, ownerId ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: appId, environmentId: [appId, ownerId].join("|"), entryKey: "APP_LOCALS", update: { val: "app-locals-updated" }, }, }, ownerId ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block1Id, environmentId: [block1Id, devUserInviteParams.user.id].join("|"), entryKey: "BLOCK_1_LOCALS", update: { val: "block-1-locals-updated" }, }, }, ownerId ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: appId, environmentId: [appId, devUserInviteParams.user.id].join("|"), entryKey: "APP_LOCALS", update: { val: "app-locals-updated" }, }, }, ownerId ); // subenv dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: block2Id, environmentId: block2ProdSubEnv.id, entryKey: "BLOCK_2_SUB", update: { val: "block-2-sub-val-updated" }, }, }, ownerId ); dispatch( { type: Client.ActionType.UPDATE_ENTRY_VAL, payload: { envParentId: appId, environmentId: appProdSubEnv.id, entryKey: "APP_SUB", update: { val: "app-sub-val-updated" }, }, }, ownerId ); await dispatch( { type: Client.ActionType.COMMIT_ENVS, payload: { message: "commit message" }, }, ownerId ); [inviteeLocalKeyEnv, localKeyEnv, prodSubEnv] = await Promise.all([ envkeyFetch(inviteeLocalEnvkeyIdPart, inviteeLocalEncryptionKey), envkeyFetch(localEnvkeyIdPart, localEncryptionKey), envkeyFetch(prodSubEnvkeyIdPart, prodSubEncryptionKey), ]); expect(inviteeLocalKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals-updated", APP_LOCALS: "app-locals-updated", }); expect(localKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals-updated", BLOCK_2_LOCALS: "block-2-locals", BLOCK_LOCALS_WILL_OVERRIDE: "block-2-locals", APP_LOCALS_WILL_OVERRIDE: "app-locals", APP_LOCALS: "app-locals-updated", }); expect(prodSubEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_1_SUB: "block-1-sub-val", BLOCK_SUB_WILL_OVERRIDE: "block-2-sub-val", APP_SUB_WILL_OVERRIDE: "app-sub-val", BLOCK_2_SUB: "block-2-sub-val-updated", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", APP_SUB: "app-sub-val-updated", }); // test reordering blocks const reorderPromise = dispatch( { type: Api.ActionType.REORDER_BLOCKS, payload: { appId, order: { [block2Id]: 0, [block1Id]: 1, }, }, }, ownerId ); state = getState(ownerId); expect(state.isReorderingAssociations[appId].appBlock).toBeTrue(); const reorderRes = await reorderPromise; expect(reorderRes.success).toBeTrue(); state = getState(ownerId); expect(state.isReorderingAssociations).toEqual({}); [ inviteeLocalKeyEnv, localKeyEnv, devServerEnv, stagingServerEnv, prodSubEnv, ] = await Promise.all([ envkeyFetch(inviteeLocalEnvkeyIdPart, inviteeLocalEncryptionKey), envkeyFetch(localEnvkeyIdPart, localEncryptionKey), envkeyFetch(developmentEnvkeyIdPart, developmentEncryptionKey), envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey), envkeyFetch(prodSubEnvkeyIdPart, prodSubEncryptionKey), ]); expect(inviteeLocalKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals-updated", APP_LOCALS: "app-locals-updated", }); expect(localKeyEnv).toEqual({ BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_1_LOCALS: "block-1-locals-updated", BLOCK_2_LOCALS: "block-2-locals", BLOCK_LOCALS_WILL_OVERRIDE: "block-1-locals", APP_LOCALS_WILL_OVERRIDE: "app-locals", APP_LOCALS: "app-locals-updated", }); shouldEq = { BLOCK_1_KEY: "block-1-val-updated", BLOCK_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", }; expect(devServerEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appDevelopment.id, includeAncestors: true, }, shouldEq ); shouldEq = { BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val-updated", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", }; expect(stagingServerEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appStaging.id, includeAncestors: true, }, shouldEq ); expect(prodSubEnv).toEqual({ BLOCK_1_KEY: "block-1-val", BLOCK_WILL_OVERRIDE: "block-1-val", APP_WILL_OVERRIDE: "app-val", BLOCK_INHERITANCE: "block-1-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_1_SUB: "block-1-sub-val", BLOCK_SUB_WILL_OVERRIDE: "block-1-sub-val", APP_SUB_WILL_OVERRIDE: "app-sub-val", BLOCK_2_SUB: "block-2-sub-val-updated", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", APP_SUB: "app-sub-val-updated", }); // test disconnecting block let { appBlocks } = graphTypes(state.graph), { id: appBlockId } = appBlocks.filter( (appBlock) => appBlock.appId == appId && appBlock.blockId == block1Id )[0], disconnectPromise = dispatch( { type: Api.ActionType.DISCONNECT_BLOCK, payload: { id: appBlockId, }, }, ownerId ); state = getState(ownerId); expect(state.isRemoving[appBlockId]).toBeTrue(); let disconnectRes = await disconnectPromise; expect(disconnectRes.success).toBeTrue(); state = getState(ownerId); expect(state.isRemoving[appBlockId]).toBeUndefined(); // re-connect and then re-disconnect to ensure primary key truncation/duplication issue is fixed await connectBlocks(ownerId, [ { appId, blockId: block1Id, orderIndex: 0, }, ]); state = getState(ownerId); ({ appBlocks } = graphTypes(state.graph)); ({ id: appBlockId } = appBlocks.filter( (appBlock) => appBlock.appId == appId && appBlock.blockId == block1Id )[0]); disconnectRes = await dispatch( { type: Api.ActionType.DISCONNECT_BLOCK, payload: { id: appBlockId, }, }, ownerId ); expect(disconnectRes.success).toBeTrue(); [ inviteeLocalKeyEnv, localKeyEnv, devServerEnv, stagingServerEnv, prodSubEnv, ] = await Promise.all([ envkeyFetch(inviteeLocalEnvkeyIdPart, inviteeLocalEncryptionKey), envkeyFetch(localEnvkeyIdPart, localEncryptionKey), envkeyFetch(developmentEnvkeyIdPart, developmentEncryptionKey), envkeyFetch(stagingEnvkeyIdPart, stagingEncryptionKey), envkeyFetch(prodSubEnvkeyIdPart, prodSubEncryptionKey), ]); expect(inviteeLocalKeyEnv).toEqual({ BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", APP_LOCALS: "app-locals-updated", }); expect(localKeyEnv).toEqual({ BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", BLOCK_2_LOCALS: "block-2-locals", BLOCK_LOCALS_WILL_OVERRIDE: "block-2-locals", APP_LOCALS_WILL_OVERRIDE: "app-locals", APP_LOCALS: "app-locals-updated", }); shouldEq = { BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val-updated", }; expect(devServerEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appDevelopment.id, includeAncestors: true, }, shouldEq ); shouldEq = { BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", }; expect(stagingServerEnv).toEqual(shouldEq); await testExport( ownerId, { envParentId: appId, environmentId: appStaging.id, includeAncestors: true, }, shouldEq ); expect(prodSubEnv).toEqual({ BLOCK_WILL_OVERRIDE: "block-2-val", APP_WILL_OVERRIDE: "app-val", BLOCK_2_KEY: "block-2-val", APP_KEY: "app-val", BLOCK_SUB_WILL_OVERRIDE: "block-2-sub-val", APP_SUB_WILL_OVERRIDE: "app-sub-val", BLOCK_2_SUB: "block-2-sub-val-updated", BLOCK_2_SUB_INHERITANCE: "block-2-val-updated", APP_SUB: "app-sub-val-updated", }); }); });
the_stack
import { Camera, ArcRotateCamera, Vector3, FreeCamera, SSAO2RenderingPipeline, DefaultRenderingPipeline, SerializationHelper, PostProcessRenderPipeline, MotionBlurPostProcess, ScreenSpaceReflectionPostProcess, } from "babylonjs"; import { Nullable } from "../../../shared/types"; import { Editor } from "../editor"; import { Tools } from "../tools/tools"; export class SceneSettings { /** * Defines the camera being used by the editor. */ public static Camera: Nullable<ArcRotateCamera> = null; /** * Defines the reference to the SSAO rendering pipeline. */ public static SSAOPipeline: Nullable<SSAO2RenderingPipeline> = null; /** * Defines the reference to the screen space reflections post-process. */ public static ScreenSpaceReflectionsPostProcess: Nullable<ScreenSpaceReflectionPostProcess> = null; /** * Defines the reference to the default rendering pipeline. */ public static DefaultPipeline: Nullable<DefaultRenderingPipeline> = null; /** * Defines the reference to the motion blur post-process. */ public static MotionBlurPostProcess: Nullable<MotionBlurPostProcess> = null; private static _SSAOPipelineEnabled: boolean = true; private static _ScreenSpaceReflectionsEnabled: boolean = false; private static _DefaultPipelineEnabled: boolean = true; private static _MotionBlurEnabled: boolean = false; /** * Returns wehter or not the camera is locked. */ public static get IsCameraLocked(): boolean { return this.Camera?.metadata.detached ?? false; } /** * Returns the editor cameras as an ArcRotateCamera. * @param editor the editor reference. */ public static GetArcRotateCamera(editor: Editor): ArcRotateCamera { if (this.Camera) { return this.Camera; } const camera = new ArcRotateCamera("Editor Camera", 0, 0, 10, Vector3.Zero(), editor.scene!); camera.attachControl(editor.scene!.getEngine().getRenderingCanvas()!, true, false); camera.id = Tools.RandomId(); camera.doNotSerialize = true; this.Camera = camera; this.SetActiveCamera(editor, this.Camera); return this.Camera as ArcRotateCamera; } /** * Updates the panning sensibility according to the current radius. */ public static UpdateArcRotateCameraPanning(): void { if (this.Camera) { this.Camera.panningSensibility = 1000 / this.Camera.radius; } } /** * Configures the editor from according to the given JSON representation of the saved camera. * @param json the JSON representation of the save camera. * @param editor the editor reference. */ public static ConfigureFromJson(json: any, editor: Editor): void { if (this.Camera) { this.Camera.dispose(); } this.Camera = Camera.Parse(json, editor.scene!) as ArcRotateCamera; this.Camera.attachControl(editor.scene!.getEngine().getRenderingCanvas()!, true, false); this.Camera.doNotSerialize = true; this.SetActiveCamera(editor, this.Camera); this.ResetPipelines(editor); } /** * Sets the new camera as active. * @param editor defines the reference to the editor. * @param camera defines the reference to the camera to set as active camera. */ public static SetActiveCamera(editor: Editor, camera: Camera): void { const scene = camera.getScene(); if (camera === scene.activeCamera) { return; } if (scene.activeCamera) { scene.activeCamera.detachControl(); } scene.activeCamera = camera; this.AttachControl(editor, camera); this.ResetPipelines(editor); } /** * Attachs the controls of the given camera to the editor's scene. * @param editor defines the reference to the editor. * @param camera defines the reference to the camera to attach control. */ public static AttachControl(editor: Editor, camera: Camera): void { const canvas = editor.scene!.getEngine().getRenderingCanvas(); if (!canvas) { return; } if (camera instanceof ArcRotateCamera) { camera.attachControl(canvas, true, false); } else if (camera instanceof FreeCamera) { camera.attachControl(canvas, true); } else { debugger; } } /** * Returns the SSAO rendering pipeline. * @param editor the editor reference. */ public static GetSSAORenderingPipeline(editor: Editor): SSAO2RenderingPipeline { if (this.SSAOPipeline) { return this.SSAOPipeline; } const ssao = new SSAO2RenderingPipeline("ssao", editor.scene!, { ssaoRatio: 0.5, blurRatio: 0.5 }, this._SSAOPipelineEnabled ? [editor.scene!.activeCamera!] : [], true); ssao.radius = 3.5; ssao.totalStrength = 1.3; ssao.expensiveBlur = true; ssao.samples = 16; ssao.maxZ = 250; this.SSAOPipeline = ssao; return ssao; } /** * Returns wether or not SSAO pipeline is enabled. */ public static IsSSAOEnabled(): boolean { return this._SSAOPipelineEnabled; } /** * Sets wether or not SSAO is enabled * @param editor the editor reference. * @param enabled wether or not the SSAO pipeline is enabled. */ public static SetSSAOEnabled(editor: Editor, enabled: boolean): void { if (this._SSAOPipelineEnabled === enabled) { return; } this._SSAOPipelineEnabled = enabled; this.ResetPipelines(editor); } /** * Returns the default rendering pipeline. * @param editor the editor reference. */ public static GetDefaultRenderingPipeline(editor: Editor): DefaultRenderingPipeline { if (this.DefaultPipeline) { return this.DefaultPipeline; } const pipeline = new DefaultRenderingPipeline("default", true, editor.scene!, this._DefaultPipelineEnabled ? [editor.scene!.activeCamera!] : []); // const curve = new ColorCurves(); // curve.globalHue = 200; // curve.globalDensity = 80; // curve.globalSaturation = 80; // curve.highlightsHue = 20; // curve.highlightsDensity = 80; // curve.highlightsSaturation = -80; // curve.shadowsHue = 2; // curve.shadowsDensity = 80; // curve.shadowsSaturation = 40; // pipeline.imageProcessing.colorCurves = curve; pipeline.depthOfField.focalLength = 150; pipeline.bloomEnabled = true; this.DefaultPipeline = pipeline; return pipeline; } /** * Returns wether or not default pipeline is enabled. */ public static IsDefaultPipelineEnabled(): boolean { return this._DefaultPipelineEnabled; } /** * Sets wether or not default pipeline is enabled * @param editor the editor reference. * @param enabled wether or not the default pipeline is enabled. */ public static SetDefaultPipelineEnabled(editor: Editor, enabled: boolean) { if (this._DefaultPipelineEnabled === enabled) { return; } this._DefaultPipelineEnabled = enabled; this.ResetPipelines(editor); } /** * Returns the reference to the motion blur post-process. * @param editor defines the refenrece to the editor. */ public static GetMotionBlurPostProcess(editor: Editor): MotionBlurPostProcess { if (this.MotionBlurPostProcess) { return this.MotionBlurPostProcess; } this.MotionBlurPostProcess = new MotionBlurPostProcess("motionBlur", editor.scene!, 1.0, editor.scene!.activeCamera, undefined, undefined, undefined, undefined, undefined, true); return this.MotionBlurPostProcess; } /** * Returns wether or not Motion Blur is enabled. */ public static IsMotionBlurEnabled(): boolean { return this._MotionBlurEnabled; } /** * Sets wether or not motion blur post-process is enabled. * @param editor defines the reference to the editor. * @param enabled defines wether or not motion blur post-process is enabled. */ public static SetMotionBlurEnabled(editor: Editor, enabled: boolean): void { if (this._MotionBlurEnabled === enabled) { return; } this._MotionBlurEnabled = enabled; this.ResetPipelines(editor); } /** * Returns the reference to the screen space reflections post-process. * @param editor defines the reference to the editor. */ public static GetScreenSpaceReflectionsPostProcess(editor: Editor): ScreenSpaceReflectionPostProcess { if (this.ScreenSpaceReflectionsPostProcess) { return this.ScreenSpaceReflectionsPostProcess; } this.ScreenSpaceReflectionsPostProcess = new ScreenSpaceReflectionPostProcess("ssr", editor.scene!, 1.0, editor.scene!.activeCamera!, undefined, undefined, undefined, undefined, undefined, true); return this.ScreenSpaceReflectionsPostProcess; } /** * Returns wether or not screen space reflections is enabled. */ public static IsScreenSpaceReflectionsEnabled(): boolean { return this._ScreenSpaceReflectionsEnabled; } /** * Sets wether or not screen space reflection post-process is enabled. * @param editor defines the reference to the editor. * @param enabled defines wether or not screen space reflections post-process is enabled. */ public static SetScreenSpaceReflectionsEnabled(editor: Editor, enabled: boolean): void { if (this._ScreenSpaceReflectionsEnabled === enabled) { return; } this._ScreenSpaceReflectionsEnabled = enabled; this.ResetPipelines(editor); } /** * Resets the rendering pipelines. * @param editor the editor reference. */ public static ResetPipelines(editor: Editor): void { editor.scene!.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline("ssao", editor.scene!.cameras); editor.scene!.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline("default", editor.scene!.cameras); const ssrSource = this.ScreenSpaceReflectionsPostProcess?.serialize(); this.ScreenSpaceReflectionsPostProcess?.dispose(editor.scene!.activeCamera!); this.ScreenSpaceReflectionsPostProcess = null; const motionBlurSource = this.MotionBlurPostProcess?.serialize(); this.MotionBlurPostProcess?.dispose(editor.scene!.activeCamera!); this.MotionBlurPostProcess = null; // SSAO if (this.SSAOPipeline) { const source = this.SSAOPipeline.serialize(); this.SSAOPipeline.dispose(false); this.SSAOPipeline = null; try { this.GetSSAORenderingPipeline(editor); SerializationHelper.Parse(() => this.SSAOPipeline, source, editor.scene!); editor.scene!.render(); } catch (e) { this._DisposePipeline(editor, this.SSAOPipeline); editor.console.logError("Failed to attach SSAO rendering pipeline to camera."); editor.console.logError(e.message); } } // Screen spsace reflections if (this._ScreenSpaceReflectionsEnabled) { try { this.GetScreenSpaceReflectionsPostProcess(editor); if (ssrSource) { SerializationHelper.Parse(() => this.ScreenSpaceReflectionsPostProcess, ssrSource, editor.scene!, ""); } editor.scene!.render(); } catch (e) { this.ScreenSpaceReflectionsPostProcess!.dispose(editor.scene!.activeCamera!); } } // Default if (this.DefaultPipeline) { const source = this.DefaultPipeline.serialize(); this.DefaultPipeline.dispose(); this.DefaultPipeline = null; try { this.GetDefaultRenderingPipeline(editor); SerializationHelper.Parse(() => this.DefaultPipeline, source, editor.scene!); editor.scene!.render(); } catch (e) { this._DisposePipeline(editor, this.DefaultPipeline); editor.console.logError("Failed to attach default rendering pipeline to camera."); editor.console.logError(e.message); } } // Motion Blur if (this._MotionBlurEnabled) { try { this.GetMotionBlurPostProcess(editor); if (motionBlurSource) { SerializationHelper.Parse(() => this.MotionBlurPostProcess, motionBlurSource, editor.scene!, ""); } editor.scene!.render(); } catch (e) { this.MotionBlurPostProcess!.dispose(editor.scene!.activeCamera!); } } } /** * Detaches the given rendering pipeline. */ private static _DisposePipeline(editor: Editor, pipeline: Nullable<PostProcessRenderPipeline>): void { if (!pipeline) { return; } editor.scene!.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(pipeline._name, editor.scene!.cameras); } }
the_stack
import { selectPlayground } from "../../playground/selectors"; // This module contains the wrappers for user's code in each lesson. import { MOD_ALLOC } from "../rust/alloc"; import { MOD_UDP_SOCKET } from "../rust/std_net"; export const initDefaultLessonState = (state) => { state.playgrounds.colorPlayground.code.default = COLOR_PLAYGROUND_CODE; state.playgrounds.colorPlayground.code.current = COLOR_PLAYGROUND_CODE; state.playgrounds.chunks.code.default = CHUNKS_CODE; state.playgrounds.chunks.code.current = CHUNKS_CODE; state.playgrounds.sendChunks.code.default = SEND_CHUNKS_CODE; state.playgrounds.sendChunks.code.current = SEND_CHUNKS_CODE; state.playgrounds.enumerateChunks.code.default = ENUMERATE_CHUNKS_CODE; state.playgrounds.enumerateChunks.code.current = ENUMERATE_CHUNKS_CODE; state.playgrounds.reorderChunks.code.default = REORDER_CHUNKS_CODE; state.playgrounds.reorderChunks.code.current = REORDER_CHUNKS_CODE; state.playgrounds.sendOrderedChunks.code.default = SEND_ORDERED_CHUNKS_CODE; state.playgrounds.sendOrderedChunks.code.current = SEND_ORDERED_CHUNKS_CODE; }; export const COLOR_PLAYGROUND_CODE = `// Each pixel in an image is represented by four bytes: // red, green, blue, and alpha. \`repr(C, packed)\` sets the alignment of the // structure: we want it to be of exactly 4 bytes in size. #[repr(C, packed)] struct Pixel { red: u8, green: u8, blue: u8, alpha: u8, // the alpha channel in an extra color component that sets the opacity } // We take an array of pixels as an argument for this function. // After calling this function, the image contains a different sequence of bytes. fn transform_image(image: &mut [Pixel]) { for pixel in image { // Set green and blue components of each pixel to zero. pixel.green = 0; pixel.blue = 0; } } // Try modifying this function to see how the image will change!`; const CHUNKS_CODE = `// Let's limit each chunk by 65000 bytes. // Try changing this to see if the resulting chunks will be different! const MAX_PACKET_SIZE: usize = 65000; type Chunk = Vec<Pixel>; // This function returns a list of chunks. // We define each chunk as a list of pixels (\`Vec<Pixel>\`) fn chunk_image(image: &mut [Pixel]) -> Vec<Chunk> { image.chunks(MAX_PACKET_SIZE / 4) // We divide by 4 here because each pixel is encoded with 4 bytes .map(|chunk| chunk.to_vec()) // Convert each chunk into a \`Vec<Pixel>\` .collect() // Return a list of chunks as a result implicitly (notice the lack of semicolon) } `; const SEND_CHUNKS_CODE = `// Alice's address const ALICE: &str = "10.0.0.42:1000"; // This example uses the \`chunk_image\` function defined above. // // It takes the following arguments: // - \`chunks\` - image chunks that we want to send over the network. // - \`socket\` - a UDP socket. fn send_image(chunks: &mut [Chunk], socket: &UdpSocket) { for chunk in chunks { socket.send_to(&chunk.as_bytes(), ALICE) // \`Chunk.as_bytes\` encodes pixels into bytes .expect("Couldn't send data"); } }`; const SEND_ORDERED_CHUNKS_CODE = `// Alice's address const ALICE: &str = "10.0.0.42:1000"; // This example uses the result from the \`reorder_chunks\` function defined above. // // It takes the following arguments: // - \`chunks\` - a list of ordered chunks. // - \`socket\` - a UDP socket. fn send_ordered_chunks(chunks: &mut [(usize, Chunk)], socket: &UdpSocket) { for (index, chunk) in chunks { // First, let's encode our chunk of pixels as bytes. // We allocate memory for it, leaving one extra byte for the chunk index (+ 1) let mut bytes = Vec::with_capacity(chunk.len() + 1); // The first byte is reserved for the chunk index: bytes.push(*index as u8); // Add the actual pixel bytes (\`Chunk.as_bytes\` encodes pixels into bytes): bytes.extend_from_slice(chunk.as_bytes()); // Finally, send the resulting chunk to Alice: socket.send_to(&bytes, ALICE) .expect("Couldn't send data"); } } // While this code does the trick, please bear in mind that it is not efficient. // We do a lot of unnecessary memory copying just in order to add the chunk index // in the beginning. In future lessons, we will learn how to use more efficient // serialization methods.`; const ENUMERATE_CHUNKS_CODE = `fn enumerate_chunks(chunks: Vec<Chunk>) -> Vec<(usize, Chunk)> { chunks.into_iter() .enumerate() .collect() }`; const REORDER_CHUNKS_CODE = `// This function takes an unordered list of chunks as its argument. // Try commenting out the \`sort_by\` call and see what will change. fn reorder_chunks(chunks: &mut [(usize, Chunk)]) { chunks .sort_by(|(index_a, chunk_a), (index_b, chunk_b)| index_a.cmp(&index_b)); // You can also try to reverse the order: // chunks.reverse(); }`; const countLines = (str) => str.split("\n").length - 1; // Tag for templates which calculates line offsets for user code. // TODO: ideally, this should be a const fn, or a preprocessor function. const rust = (strings, code) => { const lineOffset = countLines(strings[0]); return { lineOffset, code: `${strings[0]}${code}${strings[1]}`, }; }; export const wrapColorManipulation = (code) => { const wrappedCode = rust` ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize) { std::panic::set_hook(Box::new(panic_hook)); let mut pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); transform_image(pixels); } `; wrappedCode.code = MOD_ALLOC + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_ALLOC) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapChunks = (code) => { const wrappedCode = rust` #[repr(C, packed)] #[derive(Copy, Clone)] struct Pixel { red: u8, green: u8, blue: u8, alpha: u8, } ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } extern "C" { fn import_chunk(offset: usize, chunk_ptr: *const u8, chunk_len: usize, index: usize); } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize, _scramble_seed: u32) { std::panic::set_hook(Box::new(panic_hook)); let mut pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); let chunks = chunk_image(pixels); let mut offset = 0; for chunk in chunks { import_chunk(offset, chunk.as_ptr() as *const _, chunk.len() * 4, 0); offset += chunk.len() * 4; } } `; wrappedCode.code = MOD_ALLOC + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_ALLOC) + wrappedCode.lineOffset; return wrappedCode; }; const MOD_PIXEL = `#[repr(C, packed)] #[derive(Copy, Clone)] struct Pixel { red: u8, green: u8, blue: u8, alpha: u8, } trait AsBytes { fn as_bytes(&self) -> &[u8]; } impl AsBytes for Vec<Pixel> { fn as_bytes(&self) -> &[u8] { unsafe { std::slice::from_raw_parts( self.as_ptr() as *const u8, self.len() * 4 ) } } }`; export const wrapSendChunks = (code, state) => { const chunkFnCode = selectPlayground(state, "chunks").code.current; const wrappedCode = rust` ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); fn import_chunk(offset: usize, chunk_ptr: *const u8, chunk_len: usize, index: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize, scramble_seed: u32) { std::panic::set_hook(Box::new(panic_hook)); let pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); let socket = UdpSocket::bind("10.0.0.1:1000").expect("couldn't bind to address"); let mut chunks = chunk_image(pixels); if chunks.len() > 40 { panic!("Too many chunks; try setting a higher value for MAX_PACKET_SIZE"); } send_image(&mut chunks, &socket); // make sure all packets are processed let mut polls = 0; for _poll in 0..4 { poll_network(); } // Scramble the result let mut offset = 0; chunks.sort_by( |chunk_a, chunk_b| (scramble_seed % (chunk_a[0].red as u32)).partial_cmp(&(scramble_seed % (chunk_b[0].green as u32))).unwrap() ); for chunk in chunks { import_chunk(offset, chunk.as_ptr() as *const _, chunk.len() * 4, 0); offset += chunk.len() * 4; } } `; wrappedCode.code = MOD_PIXEL + MOD_ALLOC + MOD_UDP_SOCKET + chunkFnCode + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_PIXEL) + countLines(MOD_ALLOC) + countLines(MOD_UDP_SOCKET) + countLines(chunkFnCode) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapEnumerate = (code, state) => { const chunkFnCode = selectPlayground(state, "chunks").code.current; const wrappedCode = rust` ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } extern "C" { fn import_chunk(offset: usize, chunk_ptr: *const u8, chunk_len: usize, index: usize); } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize, scramble_seed: u32) { std::panic::set_hook(Box::new(panic_hook)); let mut pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); let chunks = chunk_image(pixels); let mut enumerated_chunks = enumerate_chunks(chunks); let mut offset = 0; enumerated_chunks.sort_by( |(_idx_a, chunk_a), (_idx_b, chunk_b)| (scramble_seed % (chunk_a[0].red as u32)).partial_cmp(&(scramble_seed % (chunk_b[0].green as u32))).unwrap() ); for (index, chunk) in enumerated_chunks { import_chunk(offset, chunk.as_ptr() as *const _, chunk.len() * 4, index); offset += chunk.len() * 4; } } `; wrappedCode.code = MOD_PIXEL + MOD_ALLOC + chunkFnCode + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_PIXEL) + countLines(MOD_ALLOC) + countLines(chunkFnCode) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapReorderChunks = (code, state) => { const chunkFnCode = selectPlayground(state, "chunks").code.current; const enumerateFnCode = selectPlayground(state, "enumerateChunks").code .current; const wrappedCode = rust` ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } extern "C" { fn import_chunk(offset: usize, chunk_ptr: *const u8, chunk_len: usize, index: usize); } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize, scramble_seed: u32) { std::panic::set_hook(Box::new(panic_hook)); let mut pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); let chunks = chunk_image(pixels); let mut enumerated_chunks = enumerate_chunks(chunks); reorder_chunks(&mut enumerated_chunks); let mut offset = 0; for (index, chunk) in enumerated_chunks { import_chunk(offset, chunk.as_ptr() as *const _, chunk.len() * 4, index); offset += chunk.len() * 4; } } `; wrappedCode.code = MOD_PIXEL + MOD_ALLOC + chunkFnCode + enumerateFnCode + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_PIXEL) + countLines(MOD_ALLOC) + countLines(enumerateFnCode) + countLines(chunkFnCode) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapSendOrderedChunks = (code, state) => { const chunkFnCode = selectPlayground(state, "chunks").code.current; const enumerateFnCode = selectPlayground(state, "enumerateChunks").code .current; const reorderFnCode = selectPlayground(state, "reorderChunks").code.current; const wrappedCode = rust` ${code} extern "C" { fn report_error(str: *const u8, str_len: usize); fn import_chunk(offset: usize, chunk_ptr: *const u8, chunk_len: usize, index: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } #[no_mangle] pub unsafe fn main(image: *mut u8, image_size: usize, scramble_seed: u32) { std::panic::set_hook(Box::new(panic_hook)); let pixels: &mut [Pixel] = std::slice::from_raw_parts_mut(image as *mut Pixel, image_size); let socket = UdpSocket::bind("10.0.0.1:1000").expect("couldn't bind to address"); let mut chunks = chunk_image(pixels); if chunks.len() > 40 { panic!("Too many chunks; try setting a higher value for MAX_PACKET_SIZE"); } let mut enumerated_chunks = enumerate_chunks(chunks); reorder_chunks(&mut enumerated_chunks); send_ordered_chunks(&mut enumerated_chunks, &socket); // make sure all packets are processed for _poll in 0..4 { poll_network(); } let mut offset = 0; for (index, chunk) in enumerated_chunks { import_chunk(offset, chunk.as_ptr() as *const _, chunk.len() * 4, index); offset += chunk.len() * 4; } } `; wrappedCode.code = MOD_PIXEL + MOD_ALLOC + MOD_UDP_SOCKET + chunkFnCode + enumerateFnCode + reorderFnCode + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_PIXEL) + countLines(MOD_ALLOC) + countLines(MOD_UDP_SOCKET) + countLines(chunkFnCode) + countLines(enumerateFnCode) + countLines(reorderFnCode) + wrappedCode.lineOffset; return wrappedCode; };
the_stack
import { Container } from 'aurelia-dependency-injection'; import { NavigationInstruction } from './navigation-instruction'; import { Router } from './router'; import { NavModel } from './nav-model'; import { RouterConfiguration } from './router-configuration'; import { NavigationCommand } from './navigation-commands'; import { IObservable } from './utilities-activation'; import { PipelineStatus } from './pipeline-status'; import { ActivationStrategyType } from './activation-strategy'; /**@internal */ declare module 'aurelia-dependency-injection' { interface Container { getChildRouter?: () => Router; } } /** * A configuration object that describes a route for redirection */ export interface RedirectConfig { /** * path that will be redirected to. This is relative to currently in process router */ redirect: string; /** * A backward compat interface. Should be ignored in new code */ [key: string]: any; } /** * A more generic RouteConfig for unknown route. Either a redirect config or a `RouteConfig` * Redirect config is generally used in `mapUnknownRoutes` of `RouterConfiguration` */ export type RouteOrRedirectConfig = RouteConfig | RedirectConfig; /** * A RouteConfig specifier. Could be a string, or an object with `RouteConfig` interface shape, * or could be an object with redirect interface shape */ export type RouteConfigSpecifier = string | RouteOrRedirectConfig | ((instruction: NavigationInstruction) => string | RouteOrRedirectConfig | Promise<string | RouteOrRedirectConfig>); /** * A configuration object that describes a route. */ export interface RouteConfig { /** * The route pattern to match against incoming URL fragments, or an array of patterns. */ route: string | string[]; /** * A unique name for the route that may be used to identify the route when generating URL fragments. * Required when this route should support URL generation, such as with [[Router.generate]] or * the route-href custom attribute. */ name?: string; /** * The moduleId of the view model that should be activated for this route. */ moduleId?: string; /** * A URL fragment to redirect to when this route is matched. */ redirect?: string; /** * A function that can be used to dynamically select the module or modules to activate. * The function is passed the current [[NavigationInstruction]], and should configure * instruction.config with the desired moduleId, viewPorts, or redirect. */ navigationStrategy?: (instruction: NavigationInstruction) => Promise<void> | void; /** * The view ports to target when activating this route. If unspecified, the target moduleId is loaded * into the default viewPort (the viewPort with name 'default'). The viewPorts object should have keys * whose property names correspond to names used by <router-view> elements. The values should be objects * specifying the moduleId to load into that viewPort. The values may optionally include properties related to layout: * `layoutView`, `layoutViewModel` and `layoutModel`. */ viewPorts?: any; /** * When specified, this route will be included in the [[Router.navigation]] nav model. Useful for * dynamically generating menus or other navigation elements. When a number is specified, that value * will be used as a sort order. */ nav?: boolean | number; /** * The URL fragment to use in nav models. If unspecified, the [[RouteConfig.route]] will be used. * However, if the [[RouteConfig.route]] contains dynamic segments, this property must be specified. */ href?: string; /** * Indicates that when route generation is done for this route, it should just take the literal value of the href property. */ generationUsesHref?: boolean; /** * The document title to set when this route is active. */ title?: string; /** * Arbitrary data to attach to the route. This can be used to attached custom data needed by components * like pipeline steps and activated modules. */ settings?: any; /** * The navigation model for storing and interacting with the route's navigation settings. */ navModel?: NavModel; /** * When true is specified, this route will be case sensitive. */ caseSensitive?: boolean; /** * Add to specify an activation strategy if it is always the same and you do not want that * to be in your view-model code. Available values are 'replace' and 'invoke-lifecycle'. */ activationStrategy?: ActivationStrategyType; /** * specifies the file name of a layout view to use. */ layoutView?: string; /** * specifies the moduleId of the view model to use with the layout view. */ layoutViewModel?: string; /** * specifies the model parameter to pass to the layout view model's `activate` function. */ layoutModel?: any; /** * @internal */ hasChildRouter?: boolean; [x: string]: any; } /** * An optional interface describing the canActivate convention. */ export interface RoutableComponentCanActivate { /** * Implement this hook if you want to control whether or not your view-model can be navigated to. * Return a boolean value, a promise for a boolean value, or a navigation command. */ canActivate( params: any, routeConfig: RouteConfig, navigationInstruction: NavigationInstruction ): boolean | Promise<boolean> | PromiseLike<boolean> | NavigationCommand | Promise<NavigationCommand> | PromiseLike<NavigationCommand>; } /** * An optional interface describing the activate convention. */ export interface RoutableComponentActivate { /** * Implement this hook if you want to perform custom logic just before your view-model is displayed. * You can optionally return a promise to tell the router to wait to bind and attach the view until * after you finish your work. */ activate(params: any, routeConfig: RouteConfig, navigationInstruction: NavigationInstruction): Promise<void> | PromiseLike<void> | IObservable | void; } /** * An optional interface describing the canDeactivate convention. */ export interface RoutableComponentCanDeactivate { /** * Implement this hook if you want to control whether or not the router can navigate away from your * view-model when moving to a new route. Return a boolean value, a promise for a boolean value, * or a navigation command. */ canDeactivate: () => boolean | Promise<boolean> | PromiseLike<boolean> | NavigationCommand; } /** * An optional interface describing the deactivate convention. */ export interface RoutableComponentDeactivate { /** * Implement this hook if you want to perform custom logic when your view-model is being * navigated away from. You can optionally return a promise to tell the router to wait until * after you finish your work. */ deactivate: () => Promise<void> | PromiseLike<void> | IObservable | void; } /** * An optional interface describing the determineActivationStrategy convention. */ export interface RoutableComponentDetermineActivationStrategy { /** * Implement this hook if you want to give hints to the router about the activation strategy, when reusing * a view model for different routes. Available values are 'replace' and 'invoke-lifecycle'. */ determineActivationStrategy(params: any, routeConfig: RouteConfig, navigationInstruction: NavigationInstruction): ActivationStrategyType; } /** * An optional interface describing the router configuration convention. */ export interface ConfiguresRouter { /** * Implement this hook if you want to configure a router. */ configureRouter(config: RouterConfiguration, router: Router): Promise<void> | PromiseLike<void> | void; } /** * A step to be run during processing of the pipeline. */ export interface PipelineStep { /** * Execute the pipeline step. The step should invoke next(), next.complete(), * next.cancel(), or next.reject() to allow the pipeline to continue. * * @param instruction The navigation instruction. * @param next The next step in the pipeline. */ run(instruction: NavigationInstruction, next: Next): Promise<any>; /** * @internal */ getSteps?(): any[]; } /** * A multi-step pipeline step that helps enable multiple hooks to the pipeline */ export interface IPipelineSlot { /**@internal */ getSteps(): (StepRunnerFunction | IPipelineSlot | PipelineStep)[]; } /** * The result of a pipeline run. */ export interface PipelineResult { status: string; instruction: NavigationInstruction; output: any; completed: boolean; } /** * The component responsible for routing */ export interface ViewPortComponent { viewModel: any; childContainer?: Container; router: Router; config?: RouteConfig; childRouter?: Router; /** * This is for backward compat, when moving from any to a more strongly typed interface */ [key: string]: any; } /** * A viewport used by a Router to render a route config */ export interface ViewPort { /**@internal */ container: Container; swap(viewportInstruction: ViewPortInstruction): void; process(viewportInstruction: ViewPortInstruction, waitToSwap?: boolean): Promise<void>; } /** * A viewport plan to create/update a viewport. */ export interface ViewPortPlan { name: string; config: RouteConfig; strategy: ActivationStrategyType; prevComponent?: ViewPortComponent; prevModuleId?: string; childNavigationInstruction?: NavigationInstruction; } export interface ViewPortInstruction { name?: string; strategy: ActivationStrategyType; childNavigationInstruction?: NavigationInstruction; moduleId: string; component: ViewPortComponent; childRouter?: Router; lifecycleArgs: LifecycleArguments; prevComponent?: ViewPortComponent; } export type NavigationResult = boolean | Promise<PipelineResult | boolean>; export type LifecycleArguments = [Record<string, string>, RouteConfig, NavigationInstruction]; /** * A callback to indicate when pipeline processing should advance to the next step * or be aborted. */ export interface Next<T = any> { /** * Indicates the successful completion of the pipeline step. */ (): Promise<any>; /** * Indicates the successful completion of the entire pipeline. */ complete: NextCompletionHandler<T>; /** * Indicates that the pipeline should cancel processing. */ cancel: NextCompletionHandler<T>; /** * Indicates that pipeline processing has failed and should be stopped. */ reject: NextCompletionHandler<T>; } /** * Next Completion result. Comprises of final status, output (could be value/error) and flag `completed` */ export interface NextCompletionResult<T = any> { status: PipelineStatus; output: T; completed: boolean; } /** * Handler for resolving `NextCompletionResult` */ export type NextCompletionHandler<T = any> = (output?: T) => Promise<NextCompletionResult<T>>; export type StepRunnerFunction = <TThis = any>(this: TThis, instruction: NavigationInstruction, next: Next) => any;
the_stack
import * as React from "react"; import { Select, Button, Tag, InputNumber } from 'antd'; import {getNodeColor, constructNeighborSet, getNodeStatisticStr, constructGraphIn, skew_weight} from '../../../helper'; import { SettingOutlined } from '@ant-design/icons'; import GraphViewSettingsModalContainer from '../../../container/GraphViewSettingsModalContainer'; import ForceDirectedGraphCanvasContainer from '../../../container/ForceDirectedGraphCanvasContainer'; const Option = Select.Option; export interface IProps { // For original graph object graph_object:any, model_nlabels:any, model_eweights:any, model_nweights:any, NLabelList:any, eweightList:any, // For subgraphs subgs:any, subgList:any, // For size of view. width: number, height: number, // For displayed nodes. selectedNodeIdList:any[], // For users selected node. changeSelectInspectNode:any, select_inspect_node : number, changeShowSource:any, showSource: boolean, // For extended mode. extendedMode: any, changeExtendedMode:any, // For Graph View Setting Modal. GraphViewSettingsModal_visible:any, changeGraphViewSettingsModal_visible:any, enableForceDirected: boolean, changeEnableForceDirected: any } export interface IState { } export default class GraphView extends React.Component<IProps, IState>{ public prevGraphJson:any = null; constructor(props:IProps) { super(props); this.onEnableForceDirected = this.onEnableForceDirected.bind(this); this.onExtendedModeChange = this.onExtendedModeChange.bind(this); this.onNodeClick = this.onNodeClick.bind(this); this.onChangeSelectInspectNode = this.onChangeSelectInspectNode.bind(this); this.UpdateCurrentGraphJson = this.UpdateCurrentGraphJson.bind(this); this.state = { } // Flow: // 1. Constructor // 2. componentWillMount() // 3. render() // 4. componentDidMount() // If props update: // 4.1 componentWillReceiveProps(nextProps : IProps), then goto 5. // If States update // 5. shouldComponentUpdate() if return false, then no rerendering. // 6. if True, then componentWillUpdate // 7. render() // 8. componentDidUpdate // If Unmount, then componentWillUnmount() } public UpdateCurrentGraphJson(current_graph_json:any){ //console.log("Store Graph Json.") this.prevGraphJson = current_graph_json; } // Handling the node click event. public onNodeClick(node_id:number){ let {showSource} = this.props; if(showSource === false){ // select node in graph view and update showSource mode. this.props.changeSelectInspectNode(node_id); this.props.changeShowSource(true); this.props.changeExtendedMode(3); }else{ this.props.changeSelectInspectNode(node_id); } } // Color Legend Info. public getColorLegend(color_mode:boolean, num_types:number){ let label = []; if (color_mode) { for(let i = 0; i< num_types; i++){ label.push({ "text":i, "color":getNodeColor(i,2) }) } } return label; } // Data Preprocessing for node subgraph // graph_object: original graph object. // model_nlabels: record mapping from model names to predicted nlabels // model_eweights: record mapping from eweight names to eweight values // model_nweights: record mapping from nweight names to nweight values // NLabelList: array of nlabel names, e.g. "ground_truth", "GCN" // eweightList: array of attention head names, e.g. "layer-0-head-1" // selecteedNodeIdList: displayed nodes. // enableForceDirected: control whether using force directed layout. // select_inspect_node: users selected node id. // showSource: current mode on whether showing only selected node. // width / height: the size of graph view. public constructNodeGraphJson(graph_object:any, model_nlabels:any, model_eweights:any, model_nweights:any, NLabelList:any, eweightList:any, selectedNodeIdList:any, enableForceDirected:boolean, select_inspect_node:number, showSource:boolean, width:number, height:number){ let ew = eweightList; let selectStr = selectedNodeIdList.join("_"); let NLabelName = NLabelList.join("_"); let common = graph_object; // 1. Data package fingerprint. let graph_name; graph_name = common.name+"_"+common.bundle_id +"_SELECTED_"+selectStr+"_SELECTEDEND_" +"_NLABEL_"+NLabelName+"_NLABELEND_" +"_EWEIGHT_"+ew+"_EWEIGHTEND_" +enableForceDirected+"_"+width+"_"+height+"_"; let graph_in = constructGraphIn(common); let graph_target = common.nlabels; // let graph_layout = common.layout; let source_list = graph_in.senders; let target_list = graph_in.receivers; let node_num = graph_in.num_nodes; let edge_num = graph_in.senders.length; let eweight = model_eweights; // let nweight = model_nweights; // 2. Default to show all nodes. if(selectedNodeIdList.length === 0){ selectedNodeIdList = [] for(let i = 0; i<node_num;i++){ selectedNodeIdList.push(i); } } // 3. Transform the graph layout. // let new_graph_layout = []; // for(let i = 0; i<node_num;i++){ // let xy = graph_layout[""+i]; // new_graph_layout.push(xy) // } // let enable_forceDirected = enableForceDirected; // if(new_graph_layout.length > 0){ // new_graph_layout = transform_graphlayout(new_graph_layout, width, height); // } // 4. If we have processed the graph layout, then we use previous graph layout. let enablePrevGraphLayout = false; let prevGraphJson = this.prevGraphJson; if(prevGraphJson && prevGraphJson["success"]){ if(prevGraphJson["nodes"].length === node_num){ enablePrevGraphLayout = true; } } //console.log("enablePrevGraphLayout, enableForceDirected, prevGraphJson", enablePrevGraphLayout, enableForceDirected, prevGraphJson); // 5. Derive the info of nodes and links. let nodes_json = []; // node info let links_json = []; // link info let links_color_json = []; // link color info // Prepare properties of nodes. let color_mode: boolean = NLabelList.length !== 0; // If ground truth is not selected, then we use dummycolor to fill the area of ground truth. let dummycolor = "#aaa"; let init_color:any = []; if (!color_mode) { init_color = [dummycolor]; } for(let i = 0; i<node_num;i++){ let label = 0; let index = i; let real_color:any; let highlight = 1; let node_weight = 1; let color = init_color.slice(); NLabelList.forEach((d:any)=>{ if(d === "ground_truth"){ let nlabel = graph_target[index]; color.push(getNodeColor(nlabel, 2)); }else{ let nlabel = model_nlabels[d][index]; color.push(getNodeColor(nlabel, 2)); } }) real_color = color.slice(); // original color storage. if(selectedNodeIdList.indexOf(index)<0){ // Unfocused nodes color will be set to "#ddd". color = ["#ddd"]; highlight = 0; } //if(nweight && NLabelList[0] && nweight[NLabelList[0]]) { // node_weight = nweight[NLabelList[0]][index]; //} let radius = 3; if(index === select_inspect_node && showSource === true){ radius = 6; } let node_object:any = { "id":index, "group":label, // dummy "color":color, "real_color":real_color, "radius":radius, // the radius of the node "highlight":highlight, // whether the node is highlighted. "node_weight":skew_weight(node_weight) } if(enablePrevGraphLayout){ node_object["x"] = prevGraphJson["nodes"][i]["x"]; node_object["y"] = prevGraphJson["nodes"][i]["y"]; } //else if(enable_forceDirected === false){ // node_object["x"] = new_graph_layout[i][0]; // node_object["y"] = new_graph_layout[i][1]; //} nodes_json.push(node_object); } // Prepare Properties of Links let edge_weighted: boolean; let current_eweights; if(eweightList && eweightList.length!==0) { edge_weighted = true; let graph_eweight_options = Object.keys(common.eweights); if (graph_eweight_options.indexOf(eweightList) > -1) { current_eweights = common.eweights[eweightList]; } else { current_eweights = eweight[eweightList]; } } else { edge_weighted = false; } for(let i = 0; i<edge_num;i++){ let link_color = "#eee"; // TODO: make default width configurable let edge_weight = 0.1; if(edge_weighted) { edge_weight = current_eweights[i] * 0.6; } let real_color = "#bbb"; if(selectedNodeIdList.indexOf(source_list[i])>=0){ if(selectedNodeIdList.indexOf(target_list[i])>=0){ link_color = "#bbb"; } } // Store the possible color. if(links_color_json.indexOf(link_color)>=0){ }else{ links_color_json.push(link_color); } links_json.push({ "source": source_list[i], "target": target_list[i], "value":1, "weight":skew_weight(edge_weight), "color":link_color, "real_color":real_color // For hovered link color. }) } let graph_json = { "success":true, "name":graph_name, "nodes":nodes_json, "links":links_json, "links_color":links_color_json, "nodenum":node_num, "edgenum":edge_num, "enable_forceDirected":enableForceDirected, "colorLegend":this.getColorLegend(color_mode, common.num_nlabel_types) } return graph_json; } // Data Preprocessing for edge subgraph // graph_object: original graph object. // model_nlabels: record mapping from model names to predicted nlabels // NLabelList: array of nlabel names, e.g. "ground_truth", "GCN" // select_inspect_node: selected node // subg_name: subgraph name // subgs: record mapping from subgraph name to subgraph collections // enableForceDirected: control whether using force directed layout. // showSource: current mode on whether showing only selected node. // width / height: the size of graph view. public constructEdgeGraphJson(graph_object:any, model_nlabels:any, NLabelList:any, select_inspect_node:number, subg_name:string, subgs:any, enableForceDirected:boolean, showSource:boolean, width:number, height:number){ let NLabelName = NLabelList.join("_"); let common = graph_object; // 1. Data package fingerprint. let graph_name = common.name+"_"+common.bundle_id +"_SUBG_"+subg_name+"_SUBGEND_" +"_NLABEL_"+NLabelName+"_NLABELEND_" +"_NODE_"+select_inspect_node+"_NODEEND_" +enableForceDirected+"_"+width+"_"+height+"_"; let node_num = common.num_nodes; let edge_num = common.srcs.length; let graph_target = common.nlabels; // let graph_layout = common.layout; let source_list = common.srcs; let target_list = common.dsts; // ordered let selectedNodeIdList = subgs[subg_name][select_inspect_node].nodes; // ordered let selectedEdgeIdList = subgs[subg_name][select_inspect_node].eids; let nweight = subgs[subg_name][select_inspect_node].nweight; let eweight = subgs[subg_name][select_inspect_node].eweight; // 2. Transform the graph layout. // TODO: revisit and see if this is really necessary. // let new_graph_layout = []; // for(let i = 0; i<node_num;i++){ // let xy = graph_layout[""+i]; // new_graph_layout.push(xy) // } let enable_forceDirected = enableForceDirected; // if(new_graph_layout.length > 0){ // new_graph_layout = transform_graphlayout(new_graph_layout, width, height); // } // 3. If we have processed the graph layout, then we use previous graph layout. let enablePrevGraphLayout = false; let prevGraphJson = this.prevGraphJson; if(prevGraphJson && prevGraphJson["success"]){ if(prevGraphJson["nodes"].length === node_num){ enablePrevGraphLayout = true; } } // 4. Derive the info of nodes and links. let nodes_json = []; // node info let links_json = []; // link info let links_color_json = []; // link color info // Prepare properties of nodes. let color_mode: boolean = NLabelList.length !== 0; // If ground truth is not selected, then we use dummycolor to fill the area of ground truth. let dummycolor = "#aaa"; let init_color:any = []; if (!color_mode) { init_color = [dummycolor]; } let selectedNodeOrder = 0; console.log('select_inspect_node', select_inspect_node); console.log('showSource', showSource); console.log('selectedNodeIdList', selectedNodeIdList); for(let i = 0; i<node_num;i++){ let label = 0; let index = i; let real_color:any; let highlight = 1; let node_weight = 1; let color = init_color.slice(); NLabelList.forEach((d:any)=>{ if(d === "ground_truth"){ let nlabel = graph_target[index]; color.push(getNodeColor(nlabel, 2)); }else{ let nlabel = model_nlabels[d][index]; color.push(getNodeColor(nlabel, 2)); } }) real_color = color.slice(); // original color storage. if(selectedNodeIdList[selectedNodeOrder] === i){ node_weight = nweight[selectedNodeOrder]; selectedNodeOrder = selectedNodeOrder + 1; } else { // Unfocused nodes color will be set to "#ddd". color = ["#ddd"]; highlight = 0; } let radius = 3; if(index === select_inspect_node && showSource === true){ radius = 6; } let node_object:any = { "id":index, "group":label, // dummy "color":color, "real_color":real_color, "radius":radius, // the radius of the node "highlight":highlight, // whether the node is highlighted. "node_weight":skew_weight(node_weight) } if(enablePrevGraphLayout){ node_object["x"] = prevGraphJson["nodes"][i]["x"]; node_object["y"] = prevGraphJson["nodes"][i]["y"]; } //else if(enable_forceDirected === false){ // node_object["x"] = new_graph_layout[i][0]; // node_object["y"] = new_graph_layout[i][1]; // } nodes_json.push(node_object); } // Prepare Properties of Links let selectedEdgeOrder = 0; for(let i = 0; i<edge_num;i++){ let link_color = "#eee"; // TODO: make default width configurable let edge_weight = 0.1; let real_color = "#bbb"; if(i === selectedEdgeIdList[selectedEdgeOrder]) { link_color = "#bbb"; edge_weight = eweight[selectedEdgeOrder] * 0.6; selectedEdgeOrder = selectedEdgeOrder + 1; } // Store the possible color. if(links_color_json.indexOf(link_color)>=0){ }else{ links_color_json.push(link_color); } links_json.push({ "source": source_list[i], "target": target_list[i], "value":1, "weight":skew_weight(edge_weight), "color":link_color, "real_color":real_color // For hovered link color. }) } let graph_json = { "success":true, "name":graph_name, "nodes":nodes_json, "links":links_json, "links_color":links_color_json, "nodenum":node_num, "edgenum":edge_num, "enable_forceDirected":enable_forceDirected, "colorLegend":this.getColorLegend(color_mode, common.num_nlabel_types) } return graph_json; } // Enable Force Directed Layout. public onEnableForceDirected(checked:boolean){ console.log("Change State,", checked); /*this.setState({ enableForceDirected: checked })*/ this.props.changeEnableForceDirected(checked); } // Extended Mode Change public onExtendedModeChange(e:any){ this.props.changeExtendedMode(e); } // Construct Extended Selected Node Id List public constructExtendedSelectedNodeIdList(selectedNodeIdList:any, NeighborSet:any){ if(selectedNodeIdList.length === 0){ return []; }else{ let new_selectedNodeIdList = selectedNodeIdList.slice(); for(let i = 0 ; i<selectedNodeIdList.length; i++){ let nodeId = selectedNodeIdList[i]; new_selectedNodeIdList = new_selectedNodeIdList.concat(NeighborSet[nodeId]) } new_selectedNodeIdList = Array.from(new Set(new_selectedNodeIdList)); return new_selectedNodeIdList; } } // change select node. public onChangeSelectInspectNode(node_id:any, node_num:number){ let new_node_id:number = parseInt(node_id); if(!new_node_id || new_node_id<0){ new_node_id = 0; } if(new_node_id>=node_num){ new_node_id = node_num - 1; } console.log("graphview, new_node_id", new_node_id); this.props.changeSelectInspectNode(new_node_id); } // show graph view setting modal. public showGraphViewSettingModal(){ this.props.changeGraphViewSettingsModal_visible(true); } public render() { let {graph_object, model_nlabels, model_eweights, model_nweights, subgs, NLabelList, eweightList, subgList, selectedNodeIdList, showSource, select_inspect_node, width, height, extendedMode} = this.props; let onNodeClick = this.onNodeClick; let UpdateCurrentGraphJson = this.UpdateCurrentGraphJson; let specificNodeIdList = selectedNodeIdList; let common = graph_object; let graph_in = constructGraphIn(common); // Construct Neighbor Set let NeighborSet = constructNeighborSet(graph_in); // Define Force Directed Graph Size. let ForceDirectedWidth = width - 10; let ForceDirectedHeight = height - 50; if(showSource){ if(width < 800 && width > 650){ ForceDirectedHeight = height - 50 - 23; }else if(width <= 650){ ForceDirectedHeight = height - 50 - 47; } }else{ if(width < 650 && width > 550){ ForceDirectedHeight = height - 50 - 23; }else if(width <= 550){ ForceDirectedHeight = height - 50 - 47; } } // Preprocess Data. let graph_json:any; if(extendedMode <= 3) { // According to the showSource to determine the displayed node. if(showSource){ specificNodeIdList = [select_inspect_node]; } // Extended Mode Configuration if(extendedMode === 2){ specificNodeIdList = this.constructExtendedSelectedNodeIdList(specificNodeIdList, NeighborSet); }else if(extendedMode === 3){ specificNodeIdList = this.constructExtendedSelectedNodeIdList(specificNodeIdList, NeighborSet); specificNodeIdList = this.constructExtendedSelectedNodeIdList(specificNodeIdList, NeighborSet); } graph_json = this.constructNodeGraphJson(graph_object, model_nlabels, model_eweights, model_nweights, NLabelList, eweightList, specificNodeIdList, this.props.enableForceDirected, select_inspect_node, showSource, ForceDirectedWidth, ForceDirectedHeight); } else { let subg_name = subgList[extendedMode-4]; specificNodeIdList = subgs[subg_name][select_inspect_node].nodes; graph_json = this.constructEdgeGraphJson(graph_object, model_nlabels, NLabelList, select_inspect_node, subg_name, subgs, this.props.enableForceDirected, showSource, ForceDirectedWidth, ForceDirectedHeight); } // Store NeighborSet. graph_json["NeighborSet"] = NeighborSet; if(graph_json["success"]){ // Store Graph Json. //console.log("Store Graph Json.") //this.prevGraphJson = graph_json; // Get node num. let nodenum: number = graph_json["nodenum"]; // Extended Options let extendedOptions = [ [1,"None"], [2,"One Hop"], [3,"Two Hop"]]; for (var subg_type_id = 0; subg_type_id < subgList.length; subg_type_id++) { extendedOptions.push([subg_type_id + 4, subgList[subg_type_id]]); } // Event Handler for Starting or Stoping Layout. let stopLayout = () =>{ this.onEnableForceDirected(false); } let startLayout = () =>{ this.onEnableForceDirected(true); } // If showSource is true, then it means that currently the user has selected a node in the graph view. return ( <div style={{width: "100%", height:""+(this.props.height - 10)+"px", overflowX: "hidden"}}> <div className="ViewTitle clearfix">Graph View <div style={{float:'right'}}> &nbsp;&nbsp;&nbsp;&nbsp; {/** Input Id */} {(showSource)?[<span key={"span"+1}>Id:</span>, <InputNumber min={0} max={nodenum} size="small" value={select_inspect_node} onChange={(e:any)=> {this.onChangeSelectInspectNode(e,nodenum);}} />, <span key={"span"+3}>&nbsp;</span>, <Button size="small" onClick={()=>{this.props.changeShowSource(false);this.props.changeExtendedMode(1);}}>X</Button> ]:[<span key={"span"+2}></span>]} {/** Setting Modal */} <GraphViewSettingsModalContainer /> &nbsp;&nbsp;&nbsp;&nbsp; {/** Extended Selector */} Subgraph:&nbsp; <Select placeholder="Select an extended mode" value={extendedMode} style={{ width: '120px' }} onChange={this.onExtendedModeChange} disabled={!showSource} size="small" > {extendedOptions.map((d:any)=>( <Option value={d[0]} key={d[0]}> {d[1]} </Option> ))} </Select> {/** Force Directed Layout Enabler */} &nbsp;&nbsp;&nbsp;&nbsp; {(this.props.enableForceDirected)? <Button type="primary" size="small" onClick={stopLayout}>Stop Simulation</Button>: <Button type="default" size="small" onClick={startLayout}>Start Simulation</Button>} {/** Setting Modal Button */} &nbsp;&nbsp;&nbsp;&nbsp; <Button type="default" size="small" onClick={()=>{this.showGraphViewSettingModal()}} ><SettingOutlined /></Button> {/** Node Num Info */} &nbsp;&nbsp;&nbsp;&nbsp; #Nodes: <Tag>{getNodeStatisticStr(specificNodeIdList.length, nodenum)} </Tag> </div> </div> {/** Force Directed Graph */} <div className="ViewBox"> <div style={{ width: '100%', }} > <ForceDirectedGraphCanvasContainer graph_json={graph_json} width={ForceDirectedWidth} height={ForceDirectedHeight} onNodeClick={onNodeClick} UpdateCurrentGraphJson={UpdateCurrentGraphJson}/> </div> </div> </div> )}else{ return <div /> } } }
the_stack
import { Injectable } from '@angular/core'; import * as Ro from '@nakedobjects/restful-objects'; import { CollectionViewState, ConfigService, ContextService, ErrorService, InteractionMode, MaskService, PaneRouteData } from '@nakedobjects/services'; import filter from 'lodash-es/filter'; import invert from 'lodash-es/invert'; import keys from 'lodash-es/keys'; import reduce from 'lodash-es/reduce'; import some from 'lodash-es/some'; import { getParametersAndCurrentValue } from './cicero-commands/command-result'; import { Result } from './cicero-commands/result'; import * as Msg from './user-messages'; @Injectable() export class CiceroRendererService { constructor( private readonly context: ContextService, private readonly configService: ConfigService, private readonly error: ErrorService, private readonly mask: MaskService ) { } protected get keySeparator() { return this.configService.config.keySeparator; } private returnResult = (input: string, output: string): Promise<Result> => Promise.resolve(Result.create(input, output)); // TODO: remove renderer. renderHome(routeData: PaneRouteData): Promise<Result> { if (routeData.menuId) { return this.renderOpenMenu(routeData); } else { return this.returnResult('', Msg.welcomeMessage); } } renderObject(routeData: PaneRouteData): Promise<Result> { const oid = Ro.ObjectIdWrapper.fromObjectId(routeData.objectId, this.keySeparator); return this.context.getObject(1, oid, routeData.interactionMode) // TODO: move following code out into a ICireroRenderers service with methods for rendering each context type .then((obj: Ro.DomainObjectRepresentation) => { const openCollIds = this.openCollectionIds(routeData); if (some(openCollIds)) { return this.renderOpenCollection(openCollIds[0], obj); } else if (obj.isTransient()) { return this.renderTransientObject(routeData, obj); } else if (routeData.interactionMode === InteractionMode.Edit || routeData.interactionMode === InteractionMode.Form) { return this.renderForm(routeData, obj); } else { return this.renderObjectTitleAndDialogIfOpen(routeData, obj); } }); } renderList(routeData: PaneRouteData): Promise<Result> { const listPromise = this.context.getListFromMenu(routeData, routeData.page, routeData.pageSize); return listPromise. then((list: Ro.ListRepresentation) => this.context.getMenu(routeData.menuId). then(menu => { const count = list.value().length; const description = this.getListDescription(list, count); const actionMember = menu.actionMember(routeData.actionId); const actionName = actionMember.extensions().friendlyName(); const output = `Result from ${actionName}:\n${description}`; return this.returnResult('', output); }) ); } renderError(message: string) { const err = this.context.getError(); const errRep = err ? err.error : null; const msg = (errRep instanceof Ro.ErrorRepresentation) ? errRep.message() : 'Unknown'; return this.returnResult('', `Sorry, an application error has occurred. ${msg}`); } private getListDescription(list: Ro.ListRepresentation, count: number) { const pagination = list.pagination(); if (pagination) { const numPages = pagination.numPages; if (numPages > 1) { const page = pagination.page; const totalCount = pagination.totalCount; return `Page ${page} of ${numPages} containing ${count} of ${totalCount} items`; } } return `${count} items`; } // TODO functions become 'private' // Returns collection Ids for any collections on an object that are currently in List or Table mode private renderOpenCollection(collId: string, obj: Ro.DomainObjectRepresentation): Promise<Result> { const coll = obj.collectionMember(collId); const output = `${this.renderCollectionNameAndSize(coll)}(${Msg.collection} ${Msg.on} ${Ro.typePlusTitle(obj)})`; return this.returnResult('', output); } private renderTransientObject(routeData: PaneRouteData, obj: Ro.DomainObjectRepresentation) { const output = `${Msg.unsaved} ${obj.extensions().friendlyName()}\n${this.renderModifiedProperties(obj, routeData, this.mask)}`; return this.returnResult('', output); } private renderForm(routeData: PaneRouteData, obj: Ro.DomainObjectRepresentation) { const prefix = `${Msg.editing} ${Ro.typePlusTitle(obj)}\n`; if (routeData.dialogId) { return this.context.getInvokableAction(obj.actionMember(routeData.dialogId)). then(invokableAction => { const output = `${prefix}${this.renderActionDialog(invokableAction, routeData, this.mask)}`; return this.returnResult('', output); }); } else { const output = `${prefix}${this.renderModifiedProperties(obj, routeData, this.mask)}`; return this.returnResult('', output); } } private renderObjectTitleAndDialogIfOpen(routeData: PaneRouteData, obj: Ro.DomainObjectRepresentation) { const prefix = `${Ro.typePlusTitle(obj)}\n`; if (routeData.dialogId) { return this.context.getInvokableAction(obj.actionMember(routeData.dialogId)). then(invokableAction => { const output = `${prefix}${this.renderActionDialog(invokableAction, routeData, this.mask)}`; return this.returnResult('', output); }); } else { return this.returnResult('', prefix); } } private renderOpenMenu(routeData: PaneRouteData): Promise<Result> { return this.context.getMenu(routeData.menuId).then(menu => { const prefix = Msg.menuTitle(menu.title()); if (routeData.dialogId) { return this.context.getInvokableAction(menu.actionMember(routeData.dialogId)).then(invokableAction => { const output = `${prefix}\n${this.renderActionDialog(invokableAction, routeData, this.mask)}`; return this.returnResult('', output); }); } else { return this.returnResult('', prefix); } }); } private renderActionDialog(invokable: Ro.ActionRepresentation | Ro.InvokableActionMember, routeData: PaneRouteData, mask: MaskService): string { const actionName = invokable.extensions().friendlyName(); const prefix = `Action dialog: ${actionName}\n`; const parms = getParametersAndCurrentValue(invokable, this.context); return reduce(parms, (s, value, paramId) => { const param = invokable.parameters()[paramId]; return `${s}${Ro.friendlyNameForParam(invokable, paramId)}: ${this.renderFieldValue(param, value, mask)}\n`; }, prefix); } private renderModifiedProperties(obj: Ro.DomainObjectRepresentation, routeData: PaneRouteData, mask: MaskService): string { const props = this.context.getObjectCachedValues(obj.id()); if (keys(props).length > 0) { const prefix = `${Msg.modifiedProperties}:\n`; return reduce(props, (s, value, propId) => { const pm = obj.propertyMember(propId); return `${s}${Ro.friendlyNameForProperty(obj, propId)}: ${this.renderFieldValue(pm, value, mask)}\n`; }, prefix); } return ''; } private renderSingleChoice(field: Ro.IField, value: Ro.Value) { // This is to handle an enum: render it as text, not a number: const inverted = invert(field.choices()!); return (<any>inverted)[value.toValueString()]; } private renderMultipleChoicesCommaSeparated(field: Ro.IField, value: Ro.Value) { // This is to handle an enum: render it as text, not a number: const inverted = invert(field.choices()!); const values = value.list()!; return reduce(values, (s, v) => `${s}${(<any>inverted)[v.toValueString()]},`, ''); } // helpers renderCollectionNameAndSize(coll: Ro.CollectionMember): string { const prefix = `${coll.extensions().friendlyName()}`; const size = coll.size() || 0; switch (size) { case 0: return `${prefix}: ${Msg.empty}\n`; case 1: return `${prefix}: 1 ${Msg.item}\n`; default: return `${prefix}: ${Msg.numberOfItems(size)}\n`; } } openCollectionIds(routeData: PaneRouteData): string[] { return filter(keys(routeData.collections), k => routeData.collections[k] !== CollectionViewState.Summary); } // Handles empty values, and also enum conversion renderFieldValue(field: Ro.IField, value: Ro.Value, mask: MaskService): string { if (!field.isScalar()) { // i.e. a reference return value.isNull() ? Msg.empty : value.toString(); } // Rest is for scalar fields only: if (value.toString()) { // i.e. not empty if (field.entryType() === Ro.EntryType.Choices) { return this.renderSingleChoice(field, value); } else if (field.entryType() === Ro.EntryType.MultipleChoices && value.isList()) { return this.renderMultipleChoicesCommaSeparated(field, value); } } let properScalarValue: number | string | boolean | Date | null; if (Ro.isDateOrDateTime(field)) { properScalarValue = Ro.toUtcDate(value); } else { properScalarValue = value.scalar(); } if (properScalarValue === '' || properScalarValue == null) { return Msg.empty; } else { const remoteMask = field.extensions().mask(); const format = field.extensions().format()!; return mask.toLocalFilter(remoteMask, format).filter(properScalarValue); } } }
the_stack
import dayjs from 'dayjs'; import Bot from '../../classes/Bot'; export default function stats(bot: Bot): Stats { const now = dayjs(); const aDayAgo = dayjs().subtract(24, 'hour'); const startOfDay = dayjs().startOf('day'); let acceptedTradesTotal = 0; let acceptedOfferTrades24Hours = 0; let acceptedOfferTradesToday = 0; let acceptedCountered24Hours = 0; let acceptedCounteredToday = 0; let acceptedSentTrades24Hours = 0; let acceptedSentTradesToday = 0; let skipped24Hours = 0; let skippedToday = 0; let declineOffer24Hours = 0; let declineOfferToday = 0; let declinedCounter24Hours = 0; let declinedCounterToday = 0; let declineSent24Hours = 0; let declineSentToday = 0; let canceledByUser24Hours = 0; let canceledByUserToday = 0; let isFailedConfirmation24Hours = 0; let isFailedConfirmationToday = 0; let isCanceledUnknown24Hours = 0; let isCanceledUnknownToday = 0; let isInvalid24Hours = 0; let isInvalidToday = 0; const pollData = bot.manager.pollData; const oldestId = pollData.offerData === undefined ? undefined : Object.keys(pollData.offerData)[0]; const timeSince = +bot.options.statistics.startingTimeInUnix === 0 ? pollData.timestamps[oldestId] : +bot.options.statistics.startingTimeInUnix; const totalDays = !timeSince ? 0 : now.diff(dayjs.unix(timeSince), 'day'); const offerData = bot.manager.pollData.offerData; for (const offerID in offerData) { if (!Object.prototype.hasOwnProperty.call(offerData, offerID)) { continue; } const offer = offerData[offerID]; if (offer.handledByUs === true && offer.action !== undefined) { // action not undefined means offer received if (offer.isAccepted === true) { if (offer.action.action === 'accept') { // Successful trades handled by the bot acceptedTradesTotal++; if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours acceptedOfferTrades24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. acceptedOfferTradesToday++; } } if (offer.action.action === 'counter') { acceptedTradesTotal++; if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours acceptedOfferTrades24Hours++; acceptedCountered24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. acceptedOfferTradesToday++; acceptedCounteredToday++; } } } if (offer.action.action === 'decline') { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours declineOffer24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. declineOfferToday++; } } if (offer.action.action === 'counter') { if (offer.isDeclined === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours declineOffer24Hours++; declinedCounter24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. declineOfferToday++; declinedCounterToday++; } } } if (offer.action.action === 'skip') { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours skipped24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. skippedToday++; } } } if (offer.handledByUs === true && offer.action === undefined) { // action undefined means offer sent if (offer.isAccepted === true) { // Successful trades handled by the bot acceptedTradesTotal++; if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours acceptedSentTrades24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. acceptedSentTradesToday++; } } if (offer.isDeclined === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours declineSent24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. declineSentToday++; } } } if (offer.handledByUs === true && offer.canceledByUser === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours canceledByUser24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. canceledByUserToday++; } } if (offer.handledByUs === true && offer.isFailedConfirmation === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours isFailedConfirmation24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. isFailedConfirmationToday++; } } if (offer.handledByUs === true && offer.isCanceledUnknown === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours isCanceledUnknown24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. isCanceledUnknownToday++; } } if (offer.handledByUs === true && offer.isInvalid === true) { if (offer.finishTimestamp >= aDayAgo.valueOf()) { // Within the last 24 hours isInvalid24Hours++; } if (offer.finishTimestamp >= startOfDay.valueOf()) { // All trades since 0:00 in the morning. isInvalidToday++; } } } const totalProcessedToday = acceptedSentTradesToday + acceptedOfferTradesToday + skippedToday + declineOfferToday + canceledByUserToday + isFailedConfirmationToday + isCanceledUnknownToday + isInvalidToday + acceptedCounteredToday + declinedCounterToday; const totalProcessed24Hours = acceptedSentTrades24Hours + acceptedOfferTrades24Hours + skipped24Hours + declineOffer24Hours + canceledByUser24Hours + isFailedConfirmation24Hours + isCanceledUnknown24Hours + isInvalid24Hours + acceptedCountered24Hours + declinedCounter24Hours; return { totalDays: totalDays, totalAcceptedTrades: acceptedTradesTotal, today: { processed: totalProcessedToday, accepted: { offer: { total: acceptedOfferTradesToday, countered: acceptedCounteredToday }, sent: acceptedSentTradesToday }, decline: { offer: { total: declineOfferToday, countered: declinedCounterToday }, sent: declineSentToday }, skipped: skippedToday, canceled: { total: canceledByUserToday + isFailedConfirmationToday + isCanceledUnknownToday, byUser: canceledByUserToday, failedConfirmation: isFailedConfirmationToday, unknown: isCanceledUnknownToday }, invalid: isInvalidToday }, hours24: { processed: totalProcessed24Hours, accepted: { offer: { total: acceptedOfferTrades24Hours, countered: acceptedCountered24Hours }, sent: acceptedSentTrades24Hours }, decline: { offer: { total: declineOffer24Hours, countered: declinedCounter24Hours }, sent: declineSent24Hours }, skipped: skipped24Hours, canceled: { total: canceledByUser24Hours + isFailedConfirmation24Hours + isCanceledUnknown24Hours, byUser: canceledByUser24Hours, failedConfirmation: isFailedConfirmation24Hours, unknown: isCanceledUnknown24Hours }, invalid: isInvalid24Hours } }; } interface Stats { totalDays: number; totalAcceptedTrades: number; today: TodayOr24Hours; hours24: TodayOr24Hours; } interface Canceled { total: number; byUser: number; failedConfirmation: number; unknown: number; } interface TodayOr24Hours { processed: number; accepted: AcceptedOrDeclinedWithCounter; decline: AcceptedOrDeclinedWithCounter; skipped: number; canceled: Canceled; invalid: number; } interface AcceptedOrDeclinedWithCounter { offer: { total: number; countered: number; }; sent: number; }
the_stack
import vec3 from 'gl-vec3'; import { PhysicsOptionsType } from '../core'; import { Helper } from '../utils'; import { AABB } from './aabb'; import { RigidBody } from './rigid-body'; import { sweep } from './sweep'; import { BodyOptionsType } from './types'; // huge thanks to https://github.com/andyhall/voxel-physics-engine/blob/master/src/index.js type TestFunctionType = (vx: number, vy: number, vz: number) => boolean; class Physics { public bodies: RigidBody[] = []; private a = vec3.create(); private dv = vec3.create(); private dx = vec3.create(); private impacts = vec3.create(); private oldResting = vec3.create(); private sleepVec = vec3.create(); private fluidVec = vec3.create(); private lateralVel = vec3.create(); private tmpBox = new AABB([], []); private tmpResting = vec3.create(); private targetPos = vec3.create(); private upvec = vec3.create(); private leftover = vec3.create(); constructor( private testSolid: TestFunctionType, private testFluid: TestFunctionType, public options: PhysicsOptionsType, ) {} addBody = (options: Partial<BodyOptionsType>) => { const defaultOptions = { aabb: new AABB([0, 0, 0], [1, 1, 1]), mass: 1, friction: 1, restitution: 0, gravityMultiplier: 1, onCollide: () => {}, autoStep: false, }; const { aabb, mass, friction, restitution, gravityMultiplier, onCollide, autoStep } = { ...defaultOptions, ...options, }; const b = new RigidBody(aabb, mass, friction, restitution, gravityMultiplier, onCollide, autoStep); this.bodies.push(b); return b; }; removeBody = (b: RigidBody) => { const i = this.bodies.indexOf(b); if (i < 0) return undefined; this.bodies.splice(i, 1); // not sure if this is needed. // b.aabb = b.onCollide = null; }; tick = (dt: number) => { const noGravity = Helper.approxEquals(0, vec3.len(this.options.gravity) ** 2); this.bodies.forEach((b) => this.iterateBody(b, dt, noGravity)); }; iterateBody = (b: RigidBody, dt: number, noGravity: boolean) => { vec3.copy(this.oldResting, b.resting); // treat bodies with <= mass as static if (b.mass <= 0) { vec3.set(b.velocity, 0, 0, 0); vec3.set(b.forces, 0, 0, 0); vec3.set(b.impulses, 0, 0, 0); return; } // skip bodies if static or no velocity/forces/impulses const localNoGrav = noGravity || b.gravityMultiplier === 0; if (this.bodyAsleep(b, dt, localNoGrav)) return; b.sleepFrameCount--; // check if under water, if so apply buoyancy and drag forces this.applyFluidForces(b); // semi-implicit Euler integration // a = f/m + gravity*gravityMultiplier vec3.scale(this.a, b.forces, 1 / b.mass); vec3.scaleAndAdd(this.a, this.a, this.options.gravity, b.gravityMultiplier); // dv = i/m + a*dt // v1 = v0 + dv vec3.scale(this.dv, b.impulses, 1 / b.mass); vec3.scaleAndAdd(this.dv, this.dv, this.a, dt); vec3.add(b.velocity, b.velocity, this.dv); // apply friction based on change in velocity this frame if (b.friction) { this.applyFrictionByAxis(0, b, this.dv); this.applyFrictionByAxis(1, b, this.dv); this.applyFrictionByAxis(2, b, this.dv); } // linear air or fluid friction - effectively v *= drag // body settings override global settings let drag = b.airDrag >= 0 ? b.airDrag : this.options.airDrag; if (b.inFluid) { drag = b.fluidDrag >= 0 ? b.fluidDrag : this.options.fluidDrag; drag *= 1 - (1 - b.ratioInFluid) ** 2; } const mult = Math.max(1 - (drag * dt) / b.mass, 0); vec3.scale(b.velocity, b.velocity, mult); // x1-x0 = v1*dt vec3.scale(this.dx, b.velocity, dt); // clear forces and impulses for next timestep vec3.set(b.forces, 0, 0, 0); vec3.set(b.impulses, 0, 0, 0); // cache old position for use in autostepping if (b.autoStep) { Helper.cloneAABB(this.tmpBox, b.aabb); } // sweeps aabb along dx and accounts for collisions this.processCollisions(b.aabb, this.dx, b.resting); // if autostep, and on ground, run collisions again with stepped up aabb if (b.autoStep) { this.tryAutoStepping(b, this.tmpBox, this.dx); } // Collision impacts. b.resting shows which axes had collisions: for (let i = 0; i < 3; ++i) { this.impacts[i] = 0; if (b.resting[i]) { // count impact only if wasn't collided last frame if (!this.oldResting[i]) this.impacts[i] = -b.velocity[i]; b.velocity[i] = 0; } } const mag = vec3.len(this.impacts); if (mag > 0.001) { // epsilon // send collision event - allows client to optionally change // body's restitution depending on what terrain it hit // event argument is impulse J = m * dv vec3.scale(this.impacts, this.impacts, b.mass); if (b.onCollide) b.onCollide(this.impacts); // bounce depending on restitution and minBounceImpulse if (b.restitution > 0 && mag > this.options.minBounceImpulse) { vec3.scale(this.impacts, this.impacts, b.restitution); b.applyImpulse(this.impacts); } } // sleep check const vsq = vec3.len(b.velocity) ** 2; if (vsq > 1e-5) b.markActive(); }; applyFluidForces = (body: RigidBody) => { // First pass at handling fluids. Assumes fluids are settled // thus, only check at corner of body, and only from bottom up const box = body.aabb; const cx = Math.floor(box.base[0]); const cz = Math.floor(box.base[2]); const y0 = Math.floor(box.base[1]); const y1 = Math.floor(box.max[1]); if (!this.testFluid(cx, y0, cz)) { body.inFluid = false; body.ratioInFluid = 0; return; } // body is in a fluid - find out how much of body is submerged let submerged = 1; let cy = y0 + 1; while (cy <= y1 && this.testFluid(cx, cy, cz)) { submerged++; cy++; } const fluidLevel = y0 + submerged; const heightInFluid = fluidLevel - box.base[1]; let ratioInFluid = heightInFluid / box.vec[1]; if (ratioInFluid > 1) ratioInFluid = 1; const vol = box.vec[0] * box.vec[1] * box.vec[2]; const displaced = vol * ratioInFluid; // bouyant force = -gravity * fluidDensity * volumeDisplaced const f = this.fluidVec; vec3.scale(f, this.options.gravity, -this.options.fluidDensity * displaced); body.applyForce(f); body.inFluid = true; body.ratioInFluid = ratioInFluid; }; applyFrictionByAxis = (axis: number, body: RigidBody, dvel: number[]) => { // friction applies only if moving into a touched surface const restDir = body.resting[axis]; const vNormal = dvel[axis]; if (restDir === 0) return; if (restDir * vNormal <= 0) return; // current vel lateral to friction axis vec3.copy(this.lateralVel, body.velocity); this.lateralVel[axis] = 0; const vCurr = vec3.len(this.lateralVel); if (Helper.approxEquals(vCurr, 0)) return; // treat current change in velocity as the result of a pseudoforce // Fpseudo = m*dv/dt // Base friction force on normal component of the pseudoforce // Ff = u * Fnormal // Ff = u * m * dvnormal / dt // change in velocity due to friction force // dvF = dt * Ff / m // = dt * (u * m * dvnormal / dt) / m // = u * dvnormal const dvMax = Math.abs(body.friction * vNormal); // decrease lateral vel by dvMax (or clamp to zero) const scaler = vCurr > dvMax ? (vCurr - dvMax) / vCurr : 0; body.velocity[(axis + 1) % 3] *= scaler; body.velocity[(axis + 2) % 3] *= scaler; }; processCollisions = (box: AABB, velocity: number[], resting: number[]) => { vec3.set(resting, 0, 0, 0); return sweep(this.testSolid, box, velocity, function (_: never, axis: number, dir: number, vec: number[]) { resting[axis] = dir; vec[axis] = 0; }); }; tryAutoStepping = (b: RigidBody, oldBox: AABB, dx: number[]) => { if (b.resting[1] >= 0 && !b.inFluid) return; // // direction movement was blocked before trying a step const xBlocked = b.resting[0] !== 0; const zBlocked = b.resting[2] !== 0; if (!(xBlocked || zBlocked)) return; // continue autostepping only if headed sufficiently into obstruction const ratio = Math.abs(dx[0] / dx[2]); const cutoff = 4; if (!xBlocked && ratio > cutoff) return; if (!zBlocked && ratio < 1 / cutoff) return; // original target position before being obstructed vec3.add(this.targetPos, oldBox.base, dx); // move towards the target until the first X/Z collision const getVoxels = this.testSolid; sweep(getVoxels, oldBox, dx, function (_: never, axis: number, dir: number, vec: number[]) { if (axis === 1) vec[axis] = 0; else return true; }); const y = b.aabb.base[1]; const ydist = Math.floor(y + 1.001) - y; vec3.set(this.upvec, 0, ydist, 0); let collided = false; // sweep up, bailing on any obstruction sweep(getVoxels, oldBox, this.upvec, function () { collided = true; return true; }); if (collided) return; // could't move upwards // now move in X/Z however far was left over before hitting the obstruction vec3.sub(this.leftover, this.targetPos, oldBox.base); this.leftover[1] = 0; this.processCollisions(oldBox, this.leftover, this.tmpResting); // bail if no movement happened in the originally blocked direction if (xBlocked && !Helper.approxEquals(oldBox.base[0], this.targetPos[0])) return; if (zBlocked && !Helper.approxEquals(oldBox.base[2], this.targetPos[2])) return; // done - oldBox is now at the target autostepped position Helper.cloneAABB(b.aabb, oldBox); b.resting[0] = this.tmpResting[0]; b.resting[2] = this.tmpResting[2]; if (b.onStep) b.onStep(); }; bodyAsleep = (body: RigidBody, dt: number, noGravity: boolean) => { if (body.sleepFrameCount > 0) return false; // without gravity bodies stay asleep until a force/impulse wakes them up if (noGravity) return true; // otherwise check body is resting against something // i.e. sweep along by distance d = 1/2 g*t^2 // and check there's still a collision let isResting = false; const gmult = 0.5 * dt * dt * body.gravityMultiplier; vec3.scale(this.sleepVec, this.options.gravity, gmult); sweep( this.testSolid, body.aabb, this.sleepVec, function () { isResting = true; return true; }, true, ); return isResting; }; } export { Physics };
the_stack
'use strict'; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import * as path from 'path'; import LineCounter from './LineCounter'; import Gitignore from './Gitignore'; import * as JSONC from 'jsonc-parser'; import * as minimatch from 'minimatch'; import { TextDecoder, TextEncoder } from 'util'; // import { debug } from 'console'; const EXTENSION_ID = 'uctakeoff.vscode-counter'; const EXTENSION_NAME = 'VSCodeCounter'; const CONFIGURATION_SECTION = 'VSCodeCounter'; const toZeroPadString = (num: number, fig: number) => num.toString().padStart(fig, '0'); const toLocalDateString = (date: Date, delims:[string,string,string] = ['-',' ',':']) => { return `${date.getFullYear()}${delims[0]}${toZeroPadString(date.getMonth()+1, 2)}${delims[0]}${toZeroPadString(date.getDate(), 2)}${delims[1]}` + `${toZeroPadString(date.getHours(), 2)}${delims[2]}${toZeroPadString(date.getMinutes(), 2)}${delims[2]}${toZeroPadString(date.getSeconds(), 2)}`; } const toStringWithCommas = (obj: any) => { if (typeof obj === 'number') { return new Intl.NumberFormat('en-US').format(obj); } else { return obj.toString(); } }; const log = (message: string, ...items:any[]) => console.log(`[${EXTENSION_NAME}] ${new Date().toISOString()} ${message}`, ...items); const showError = (message: string, ...items:any[]) => vscode.window.showErrorMessage(`[${EXTENSION_NAME}] ${message}`, ...items); const sleep = (msec: number) => new Promise(resolve => setTimeout(resolve, msec)); // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { const version = vscode.extensions.getExtension(EXTENSION_ID)?.packageJSON?.version; log(`${EXTENSION_ID} ver.${version} now active! : ${context.extensionPath}`); const codeCountController = new CodeCounterController(); context.subscriptions.push( codeCountController, vscode.commands.registerCommand('extension.vscode-counter.countInWorkspace', () => codeCountController.countLinesInWorkSpace()), vscode.commands.registerCommand('extension.vscode-counter.countInDirectory', (targetDir: vscode.Uri|undefined) => codeCountController.countLinesInDirectory(targetDir)), vscode.commands.registerCommand('extension.vscode-counter.countInFile', () => codeCountController.toggleVisible()), vscode.commands.registerCommand('extension.vscode-counter.saveLanguageConfigurations', () => codeCountController.saveLanguageConfigurations()), vscode.commands.registerCommand('extension.vscode-counter.outputAvailableLanguages', () => codeCountController.outputAvailableLanguages()) ); } // this method is called when your extension is deactivated export function deactivate() { } async function currentWorkspaceFolder() { const folders = vscode.workspace.workspaceFolders ?? []; if (folders.length <= 0) { return undefined; } else if (folders.length === 1) { return folders[0]; } else { return await vscode.window.showWorkspaceFolderPick(); } } class CodeCounterController { private codeCounter_: LineCounterTable|null = null; private statusBarItem: vscode.StatusBarItem|null = null; private outputChannel: vscode.OutputChannel|null = null; private disposable: vscode.Disposable; constructor() { // subscribe to selection change and editor activation events let subscriptions: vscode.Disposable[] = []; vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, subscriptions); vscode.window.onDidChangeTextEditorSelection(this.onDidChangeTextEditorSelection, this, subscriptions); vscode.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, subscriptions); vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, subscriptions); // vscode.workspace.onDidChangeWorkspaceFolders(this.onDidChangeWorkspaceFolders, this, subscriptions); // create a combined disposable from both event subscriptions this.disposable = vscode.Disposable.from(...subscriptions); } dispose() { this.statusBarItem?.dispose(); this.statusBarItem = null; this.outputChannel?.dispose(); this.outputChannel = null; this.disposable.dispose(); this.codeCounter_ = null; } // private onDidChangeWorkspaceFolders(e: vscode.WorkspaceFoldersChangeEvent) { // log(`onDidChangeWorkspaceFolders()`); // // e.added.forEach((f) => log(` added [${f.index}] ${f.name} : ${f.uri}`)); // // e.removed.forEach((f) => log(` removed [${f.index}] ${f.name} : ${f.uri}`)); // // vscode.workspace.workspaceFolders?.forEach((f) => log(` [${f.index}] ${f.name} : ${f.uri}`)); // } private onDidChangeActiveTextEditor(e: vscode.TextEditor|undefined) { if (this.codeCounter_) { // log(`onDidChangeActiveTextEditor(${!e ? 'undefined' : e.document.uri})`); this.countLinesInEditor(e); } } private onDidChangeTextEditorSelection(e: vscode.TextEditorSelectionChangeEvent) { if (this.codeCounter_) { // log(`onDidChangeTextEditorSelection(${e.selections.length}selections, ${e.selections[0].isEmpty} )`, e.selections[0]); this.countLinesInEditor(e.textEditor); } } private onDidChangeTextDocument(e: vscode.TextDocumentChangeEvent) { if (this.codeCounter_) { // log(`onDidChangeTextDocument(${e.document.uri})`); this.countLinesOfFile(e.document); } } private onDidChangeConfiguration() { // log(`onDidChangeConfiguration()`); this.codeCounter_ = null; this.countLinesInEditor(vscode.window.activeTextEditor); } public toggleVisible() { if (!this.statusBarItem) { this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); this.countLinesInEditor(vscode.window.activeTextEditor); } else { this.statusBarItem.dispose(); this.statusBarItem = null; } } private async getCodeCounter() { if (this.codeCounter_) { return this.codeCounter_ } const langs = await loadLanguageConfigurations(); log(`load Language Settings = ${langs.size}`); await collectLanguageConfigurations(langs); log(`collect Language Settings = ${langs.size}`); const filesConf = vscode.workspace.getConfiguration("files", null); this.codeCounter_ = new LineCounterTable(langs, Object.entries(filesConf.get<{[key:string]:string}>('associations', {}))); //this.saveLanguageConfigurations(langs); return this.codeCounter_; } public saveLanguageConfigurations() { this.getCodeCounter() .then(c => saveLanguageConfigurations(c.entries())) .catch(reason => showError(`saveLanguageConfigurations() failed.`, reason)); } public outputAvailableLanguages() { this.getCodeCounter().then(c => { c.entries().forEach((lang, id) => { this.toOutputChannel(`${id} : aliases[${lang.aliases}], extensions[${lang.extensions}], filenames:[${lang.filenames}]`); }); this.toOutputChannel(`VS Code Counter : available all ${c.entries().size} languages.`); }) .catch(reason => showError(`outputAvailableLanguages() failed.`, reason)); } public async countLinesInDirectory(targetDir: vscode.Uri|undefined) { try { const folder = await currentWorkspaceFolder(); if (!folder) { showError(`No open workspace`); } else if (targetDir) { this.countLinesInDirectory_(targetDir, folder.uri); } else { const option = { value : folder.uri.toString(true), placeHolder: "Input Directory Path", prompt: "Input Directory Path. " }; const uri = await vscode.window.showInputBox(option); if (uri) { this.countLinesInDirectory_(vscode.Uri.parse(uri), folder.uri); } } } catch (e) { showError(`countLinesInDirectory() failed.`, e.message); } } public async countLinesInWorkSpace() { try { const folder = await currentWorkspaceFolder(); if (folder) { this.countLinesInDirectory_(folder.uri, folder.uri); } else { showError(`No folder are open.`); } } catch (e) { showError(`countLinesInWorkSpace() failed.`, e.message); } } private async countLinesInDirectory_(targetUri: vscode.Uri, workspaceDir: vscode.Uri) { const statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); statusBar.show(); statusBar.text = `VSCodeCounter: Preparing...`; const date = new Date(); const conf = vscode.workspace.getConfiguration(CONFIGURATION_SECTION); const confFiles = vscode.workspace.getConfiguration("files", null); const outputDir = buildUri(workspaceDir, conf.get('outputDirectory', '.VSCodeCounter')); const includes = conf.get<string[]>('include', ['**/*']); const excludes = conf.get<string[]>('exclude', []); if (conf.get('useFilesExclude', true)) { excludes.push(...Object.keys(confFiles.get<object>('exclude', {}))); } excludes.push(vscode.workspace.asRelativePath(outputDir)); const encoding = confFiles.get('encoding', 'utf8'); const useGitignore = conf.get('useGitignore', true); const targetFiles = await findTargetFiles(targetUri, `{${includes.join(',')}}`, `{${excludes.join(',')}}`, useGitignore); const counter = await this.getCodeCounter(); const maxOpenFiles = conf.get('maxOpenFiles', 500); const ignoreUnsupportedFile = conf.get('ignoreUnsupportedFile', true); const results = await countLines(counter, targetFiles, maxOpenFiles, encoding, ignoreUnsupportedFile, (msg:string) => statusBar.text = `VSCodeCounter: ${msg}`); if (results.length <= 0) { showError(`There was no target file.`); return; } statusBar.text = `VSCodeCounter: Totaling...`; const historyCount = conf.get('history', 5); if (historyCount > 0) { await outputResults(date, targetUri, results, buildUri(outputDir, toLocalDateString(date, ['-','_','-'])), conf); const regex = /^\d\d\d\d-\d\d-\d\d\_\d\d-\d\d-\d\d$/; const outputSubDirs = (await vscode.workspace.fs.readDirectory(outputDir)) .filter(d => ((d[1] & vscode.FileType.Directory) != 0) && regex.test(d[0])) .map(d => d[0]) .sort(); if (outputSubDirs.length > historyCount) { outputSubDirs.length -= historyCount; outputSubDirs.forEach(dirname => vscode.workspace.fs.delete(buildUri(outputDir, dirname), {recursive:true})); } } else { await outputResults(date, targetUri, results, outputDir, conf); } log(` finished. ${(new Date().getTime() - date.getTime())}ms`); statusBar.dispose(); } private countLinesInEditor(editor: vscode.TextEditor|undefined) { const doc = editor?.document; if (!editor || !doc) { this.showStatusBar(`${EXTENSION_NAME}:Unsupported`); } else if (editor.selection.isEmpty) { this.countLinesOfFile(doc); } else { this.getCodeCounter().then(c =>{ const lineCounter = c.getById(doc.languageId) || c.getByUri(doc.uri); if (lineCounter) { const result = editor.selections .map(s => lineCounter.count(doc.getText(s))) .reduce((prev, cur) => { return { code: prev.code + cur.code, comment: prev.comment + cur.comment, blank: prev.blank + cur.blank, }; }, {code:0, comment:0, blank:0}); this.showStatusBar(`Selected Code:${result.code} Comment:${result.comment} Blank:${result.blank}`); } else { this.showStatusBar(`${EXTENSION_NAME}:Unsupported`); } }); } } private countLinesOfFile(doc: vscode.TextDocument|undefined) { if (!doc) { this.showStatusBar(`${EXTENSION_NAME}:Unsupported`); } else { this.getCodeCounter().then(c =>{ const lineCounter = c.getById(doc.languageId) || c.getByUri(doc.uri); if (lineCounter) { const result = lineCounter?.count(doc.getText()); this.showStatusBar(`Code:${result.code} Comment:${result.comment} Blank:${result.blank}`); } else { this.showStatusBar(`${EXTENSION_NAME}:Unsupported`); } }); } } private showStatusBar(text: string) { if (this.statusBarItem) { this.statusBarItem.show(); this.statusBarItem.text = text; } } private toOutputChannel(text: string) { if (!this.outputChannel) { this.outputChannel = vscode.window.createOutputChannel(EXTENSION_NAME); } this.outputChannel.show(); this.outputChannel.appendLine(text); } } const encodingTable = new Map<string, string>([ ['big5hkscs', 'big5-hkscs'], // ['cp437', ''], // ['cp850', ''], // ['cp852', ''], // ['cp865', ''], // ['cp866', ''], // ['cp950', ''], ['eucjp', 'euc-jp'], ['euckr', 'euc-kr'], // ['gb18030', ''], // ['gb2312', ''], // ['gbk', ''], // ['iso88591', ''], // ['iso885910', ''], // ['iso885911', ''], // ['iso885913', ''], // ['iso885914', ''], // ['iso885915', ''], // ['iso88592', ''], // ['iso88593', ''], // ['iso88594', ''], // ['iso88595', ''], // ['iso88596', ''], // ['iso88597', ''], // ['iso88598', ''], // ['iso88599', ''], ['iso885916', 'iso-8859-16'], ['koi8r', 'koi8-r'], ['koi8ru', 'koi8-ru'], ['koi8t', 'koi8-t'], ['koi8u', 'koi8-u'], ['macroman', 'x-mac-roman'], ['shiftjis', 'shift-jis'], ['utf16be', 'utf-16be'], ['utf16le', 'utf-16le'], // ['utf8', ''], ['utf8bom', 'utf8'], ['windows1250', 'windows-1250'], ['windows1251', 'windows-1251'], ['windows1252', 'windows-1252'], ['windows1253', 'windows-1253'], ['windows1254', 'windows-1254'], ['windows1255', 'windows-1255'], ['windows1256', 'windows-1256'], ['windows1257', 'windows-1257'], ['windows1258', 'windows-1258'], ['windows874', 'windows-874'], ]); const buildUri = (uri: vscode.Uri, filename: string) => uri.with({path: `${uri.path}/${filename}`}); const dirUri = (uri: vscode.Uri) => uri.with({path: path.dirname(uri.path)}); function readFileAll(fileUris: vscode.Uri[]) : Promise<{uri:vscode.Uri, data:Uint8Array|null, error?:any}[]> { const ret: {uri:vscode.Uri, data:Uint8Array|null, error?:any}[] = []; return new Promise((resolve: (values: {uri:vscode.Uri, data:Uint8Array|null, error?:any}[])=> void, reject: (reason: any) => void) => { if (fileUris.length > 0) { fileUris.forEach(fileUri => { vscode.workspace.fs.readFile(fileUri).then(data => { log(`readfile : ${fileUri} : ${data.length}B`); ret.push({uri:fileUri, data: data}); if (ret.length === fileUris.length) { resolve(ret); } }, (reason:any) => { log(`readfile : ${fileUri} : error ${reason}`); ret.push({uri:fileUri, data: null, error: reason}); if (ret.length === fileUris.length) { resolve(ret); } }); }); } else { resolve(ret); } }); } function findTargetFiles(targetUri: vscode.Uri, include: vscode.GlobPattern, exclude: vscode.GlobPattern, useGitignore: boolean) { log(`includes : "${include}"`); log(`excludes : "${exclude}"`); const decoderU8 = new TextDecoder('utf8'); return new Promise((resolve: (p: vscode.Uri[])=> void, reject: (reason: any) => void) => { vscode.workspace.findFiles(include, exclude).then((files: vscode.Uri[]) => { const fileUris = files.filter(uri => !path.relative(targetUri.path, uri.path).startsWith("..")); if (useGitignore) { log(`target : ${fileUris.length} files -> use .gitignore`); vscode.workspace.findFiles('**/.gitignore', '').then((gitignoreFiles: vscode.Uri[]) => { gitignoreFiles.forEach(f => log(`use gitignore : ${f}`)); readFileAll(gitignoreFiles.sort()).then((values) => { const gitignores = new Gitignore('').merge(...values.map(p => new Gitignore(decoderU8.decode(p.data), dirUri(p.uri).fsPath))); resolve(fileUris.filter(p => gitignores.excludes(p.fsPath))); }, reject ); }, reject ); } else { resolve(fileUris); } }); }); } function countLines(lineCounterTable: LineCounterTable, fileUris: vscode.Uri[], maxOpenFiles:number, fileEncoding:string, ignoreUnsupportedFile: boolean, showStatus:(text:string)=>void) { log(`countLines : target ${fileUris.length} files`); return new Promise(async (resolve: (value: Result[])=> void, reject: (reason: string) => void) => { const results: Result[] = []; if (fileUris.length <= 0) { resolve(results); } const decoder = new TextDecoder(encodingTable.get(fileEncoding) || fileEncoding); const totalFiles = fileUris.length; let fileCount = 0; const onFinish = () => { ++fileCount; if (fileCount === totalFiles) { log(`finished : total:${totalFiles} valid:${results.length}`); resolve(results); } }; // fileUris.forEach(async fileUri => { for (let i = 0; i < totalFiles; ++i) { const fileUri = fileUris[i]; const lineCounter = lineCounterTable.getByUri(fileUri); if (lineCounter) { while ((i - fileCount) >= maxOpenFiles) { // log(`sleep : total:${totalFiles} current:${i} finished:${fileCount} valid:${results.length}`); showStatus(`${fileCount}/${totalFiles}`); await sleep(50); } vscode.workspace.fs.readFile(fileUri).then(data => { try { results.push(new Result(fileUri, lineCounter.name, lineCounter.count(decoder.decode(data)))); } catch (e) { log(`"${fileUri}" Read Error : ${e.message}.`); results.push(new Result(fileUri, '(Read Error)')); } onFinish(); }, (reason: any) => { log(`"${fileUri}" Read Error : ${reason}.`); results.push(new Result(fileUri, '(Read Error)')); onFinish(); }); } else { if (!ignoreUnsupportedFile) { results.push(new Result(fileUri, '(Unsupported)')); } onFinish(); } } // }); }); } type VscodeLanguage = { id: string aliases?: string[] filenames?: string[] extensions?: string[] configuration?: string }; type LanguageConf = { aliases: string[] filenames: string[] extensions: string[] lineComments: string[] blockComments: [string,string][] blockStrings: [string,string][] } function pushUnique<T>(array: T[], ...values: T[]) { values.forEach(value => { if (array.indexOf(value) < 0) { array.push(value); } }); } const append = (langs: Map<string, LanguageConf>, l:VscodeLanguage) => { const langExt = getOrSet(langs, l.id, ():LanguageConf => { return { aliases:[], filenames:[], extensions:[], lineComments:[], blockComments:[], blockStrings:[] } }); // l.aliases?.filter(v => langExt.aliases.indexOf(v) < 0).forEach(v => langExt.aliases.push(v)); // l.filenames?.filter(v => langExt.filenames.indexOf(v) < 0).forEach(v => langExt.filenames.push(v)); // l.extensions?.filter(v => langExt.extensions.indexOf(v) < 0).forEach(v => langExt.extensions.push(v)); pushUnique(langExt.aliases, ...(l.aliases??[])); pushUnique(langExt.filenames, ...(l.filenames??[])); pushUnique(langExt.extensions, ...(l.extensions??[])); return langExt; } function collectLanguageConfigurations(langs: Map<string, LanguageConf>) : Promise<Map<string, LanguageConf>> { return new Promise((resolve: (values: Map<string, LanguageConf>)=> void, reject: (reason: any) => void) => { if (vscode.extensions.all.length <= 0) { resolve(langs); } else { let finishedCount = 0; let totalCount = 0; const decoderU8 = new TextDecoder('utf8'); vscode.extensions.all.forEach(ex => { const languages = ex.packageJSON.contributes?.languages as VscodeLanguage[] ?? undefined; if (languages) { totalCount += languages.length languages.forEach(l => { const langExt = append(langs, l); if (l.configuration) { const confUrl = vscode.Uri.file(path.join(ex.extensionPath, l.configuration)); vscode.workspace.fs.readFile(confUrl).then(data => { // log(`${confUrl} ${data.length}B :${l.id}`); const langConf = JSONC.parse(decoderU8.decode(data)) as vscode.LanguageConfiguration; if (langConf.comments) { if (langConf.comments.lineComment) { pushUnique(langExt.lineComments, langConf.comments.lineComment); } if (langConf.comments.blockComment && langConf.comments.blockComment.length >= 2) { pushUnique(langExt.blockComments, langConf.comments.blockComment); } } if (++finishedCount >= totalCount) { resolve(langs); } }, (reason:any) => { log(`${confUrl} : error ${reason}`); if (++finishedCount >= totalCount) { resolve(langs); } }); } else { if (++finishedCount >= totalCount) { resolve(langs); } } }); } }); } }); } function saveLanguageConfigurations_(langs: {[key:string]:LanguageConf}) { const conf = vscode.workspace.getConfiguration(CONFIGURATION_SECTION); const saveLocation = conf.get<string>('saveLocation', 'global settings'); if (saveLocation === "global settings") { conf.update('languages', langs, vscode.ConfigurationTarget.Global); } else if (saveLocation === "workspace settings") { conf.update('languages', langs, vscode.ConfigurationTarget.Workspace); } else if (saveLocation === "output directory") { currentWorkspaceFolder().then(async (folder) => { if (!folder) return; const outputDirUri = buildUri(folder.uri, conf.get('outputDirectory', '.VSCodeCounter')); const uri = buildUri(outputDirUri, 'languages.json'); await makeDirectories(outputDirUri); writeTextFile(uri, JSON.stringify(langs)); }); } } function saveLanguageConfigurations(langs: Map<string, LanguageConf>) { saveLanguageConfigurations_(mapToObject(langs)); } async function loadLanguageConfigurations_() { const conf = vscode.workspace.getConfiguration(CONFIGURATION_SECTION); const saveLocation = conf.get<string>('saveLocation', 'global settings'); if (saveLocation === "global settings") { return conf.get<{[key:string]:LanguageConf}>('languages', {}); } else if (saveLocation === "workspace settings") { return conf.get<{[key:string]:LanguageConf}>('languages', {}); } else if (saveLocation === "output directory") { const workFolder = await currentWorkspaceFolder(); if (!workFolder) return {}; const outputDirUri = buildUri(workFolder.uri, conf.get('outputDirectory', '.VSCodeCounter')); const uri = buildUri(outputDirUri, 'languages.json'); const data = await vscode.workspace.fs.readFile(uri); const decoderU8 = new TextDecoder('utf8'); return JSONC.parse(decoderU8.decode(data)) as {[key:string]:LanguageConf}; } else { return {}; } } async function loadLanguageConfigurations() { return objectToMap(await loadLanguageConfigurations_()); } class LineCounterTable { private langExtensions: Map<string, LanguageConf>; private langIdTable: Map<string, LineCounter>; private aliasTable: Map<string, LineCounter>; private fileextRules: Map<string, LineCounter>; private filenameRules: Map<string, LineCounter>; private associations: [string, string][]; constructor(langExtensions: Map<string, LanguageConf>, associations: [string, string][]) { this.langExtensions = langExtensions; this.langIdTable = new Map<string, LineCounter>(); this.aliasTable = new Map<string, LineCounter>(); this.fileextRules = new Map<string, LineCounter>(); this.filenameRules = new Map<string, LineCounter>(); this.associations = associations; log(`associations : ${this.associations.length}\n[${this.associations.join("],[")}]`); langExtensions.forEach((lang, id) => { const langName = lang.aliases.length > 0 ? lang.aliases[0] : id; const lineCounter = new LineCounter(langName, lang.lineComments, lang.blockComments, lang.blockStrings); lang.aliases.forEach(v => this.aliasTable.set(v, lineCounter)); lang.extensions.forEach(v => this.fileextRules.set(v.startsWith('.') ? v : `.${v}`, lineCounter)); lang.filenames.forEach(v => this.filenameRules.set(v, lineCounter)); }); } public entries = () => this.langExtensions; public getById(langId: string) { return this.langIdTable.get(langId) || this.aliasTable.get(langId); } public getByPath(filePath: string) { const lineCounter = this.fileextRules.get(filePath) || this.fileextRules.get(path.extname(filePath)) || this.filenameRules.get(path.basename(filePath)); if (lineCounter !== undefined) { return lineCounter; } const patType = this.associations.find(([pattern, ]) => minimatch(filePath, pattern, {matchBase: true})); //log(`## ${filePath}: ${patType}`); return (patType !== undefined) ? this.getById(patType[1]) : undefined; } public getByUri(uri: vscode.Uri) { return this.getByPath(uri.fsPath); } } async function outputResults(date: Date, workspaceUri: vscode.Uri, results: Result[], outputDirUri: vscode.Uri, conf: vscode.WorkspaceConfiguration) { const resultTable = new ResultTable(workspaceUri, results, conf.get('printNumberWithCommas', true) ? toStringWithCommas : (obj:any) => obj.toString() ); const endOfLine = conf.get('endOfLine', '\n'); log(`count ${results.length} files`); const previewType = conf.get<string>('outputPreviewType', ''); log(`OutputDir : ${outputDirUri}`); await makeDirectories(outputDirUri); if (conf.get('outputAsText', true)) { const resultsUri = buildUri(outputDirUri, 'results.txt'); const promise = writeTextFile(resultsUri, resultTable.toTextLines(date).join(endOfLine)); if (previewType === 'text') { promise.then(() => showTextFile(resultsUri)).catch(err => showError(`failed to output text.`, err)); } else { promise.catch(err => showError(`failed to output text.`, err)); } } if (conf.get('outputAsCSV', true)) { const resultsUri = buildUri(outputDirUri, 'results.csv'); const promise = writeTextFile(resultsUri, resultTable.toCSVLines().join(endOfLine)); if (previewType === 'csv') { promise.then(() => showTextFile(resultsUri)).catch(err => showError(`failed to output csv.`, err)); } else { promise.catch(err => showError(`failed to output csv.`, err)); } } if (conf.get('outputAsMarkdown', true)) { const detailsUri = buildUri(outputDirUri, 'details.md'); const resultsUri = buildUri(outputDirUri, 'results.md'); const promise = conf.get('outputMarkdownSeparately', true) ? writeTextFile(detailsUri, [ '# Details', '', ...resultTable.toMarkdownHeaderLines(date), '', `[summary](results.md)`, '', ...resultTable.toMarkdownDetailsLines(), '', `[summary](results.md)`, ].join(endOfLine) ).then(() => writeTextFile(resultsUri, [ '# Summary', '', ...resultTable.toMarkdownHeaderLines(date), '', `[details](details.md)`, '', ...resultTable.toMarkdownSummaryLines(), '', `[details](details.md)` ].join(endOfLine)) ) : writeTextFile(resultsUri, [ ...resultTable.toMarkdownHeaderLines(date), '', ...resultTable.toMarkdownSummaryLines(), '', ...resultTable.toMarkdownDetailsLines(), ].join(endOfLine) ); if (previewType === 'markdown') { promise.then(() => vscode.commands.executeCommand("markdown.showPreview", resultsUri)) .catch(err => showError(`failed to output markdown text.`, err)); } else { promise.catch(err => showError(`failed to output markdown text.`, err)); } } } class Result { public uri: vscode.Uri; public filename: string; public language: string; public code = 0; public comment = 0; public blank = 0; get total(): number { return this.code + this.comment + this.blank; } constructor(uri: vscode.Uri, language: string, value: {code:number, comment:number, blank:number} ={code:-1,comment:0,blank:0}) { this.uri = uri; this.filename = uri.fsPath; this.language = language; this.code = value.code; this.comment = value.comment; this.blank = value.blank; } } class Statistics { public name: string; public files = 0; public code = 0; public comment = 0; public blank = 0; get total(): number { return this.code + this.comment + this.blank; } constructor(name: string) { this.name = name; } public append(result: Result) { this.files++; this.code += result.code; this.comment += result.comment; this.blank += result.blank; return this; } } class MarkdownTableFormatter { private valueToString: (obj:any) => string; private columnInfo: {title:string, format:string}[]; constructor(valueToString: (obj:any) => string, ...columnInfo: {title:string, format:string}[]) { this.valueToString = valueToString; this.columnInfo = columnInfo; } get lineSeparator() { return '| ' + this.columnInfo.map(i => (i.format === 'number') ? '---:' : ':---').join(' | ') + ' |'; } get headerLines() { return ['| ' + this.columnInfo.map(i => i.title).join(' | ') + ' |', this.lineSeparator]; } public line(...data: (string|number|vscode.Uri)[]) { return '| ' + data.map((d, i) => { if (typeof d === 'number') { return this.valueToString(d); } if (typeof d === 'string') { return d; } const relativePath = vscode.workspace.asRelativePath(d); return `[${relativePath}](/${relativePath})`; }) .join(' | ') + ' |'; } } class ResultTable { private targetDirPath: string; private fileResults: Result[] = []; private dirResultTable = new Map<string, Statistics>(); private langResultTable = new Map<string, Statistics>(); private total = new Statistics('Total'); private valueToString: (obj:any) => string; constructor(workspaceUri: vscode.Uri, results:Result[], valueToString = (obj:any) => obj.toString()) { this.targetDirPath = workspaceUri.fsPath; this.fileResults = results; this.valueToString = valueToString; results .filter((result) => result.code >= 0) .forEach((result) => { let parent = path.dirname(path.relative(this.targetDirPath, result.filename)); while (parent.length >= 0) { getOrSet(this.dirResultTable, parent, () => new Statistics(parent)).append(result); const p = path.dirname(parent); if (p === parent) { break; } parent = p; } getOrSet(this.langResultTable, result.language, () => new Statistics(result.language)).append(result); this.total.append(result); }); } /* public toCSVLines() { const languages = [...this.langResultTable.keys()]; return [ `filename, language, ${languages.join(', ')}, comment, blank, total`, ...this.fileResults.sort((a,b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0) .map(v => `${v.filename}, ${v.language}, ${languages.map(l => l === v.language ? v.code : 0).join(', ')}, ${v.comment}, ${v.blank}, ${v.total}`), `Total, -, ${[...this.langResultTable.values()].map(r => r.code).join(', ')}, ${this.total.comment}, ${this.total.blank}, ${this.total.total}` ]; } */ public toCSVLines() { const languages = [...this.langResultTable.keys()]; return [ `"filename", "language", "${languages.join('", "')}", "comment", "blank", "total"`, ...this.fileResults.sort((a,b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0) .map(v => `"${v.filename}", "${v.language}", ${languages.map(l => l === v.language ? v.code : 0).join(', ')}, ${v.comment}, ${v.blank}, ${v.total}`), `"Total", "-", ${[...this.langResultTable.values()].map(r => r.code).join(', ')}, ${this.total.comment}, ${this.total.blank}, ${this.total.total}` ]; } public toTextLines(date: Date) { class TextTableFormatter { private valueToString: (obj:any) => string; private columnInfo: {title:string, width:number}[]; constructor(valueToString: (obj:any) => string, ...columnInfo: {title:string, width:number}[]) { this.valueToString = valueToString; this.columnInfo = columnInfo; for (const info of this.columnInfo) { info.width = Math.max(info.title.length, info.width); } } public get lineSeparator() { return '+-' + this.columnInfo.map(i => '-'.repeat(i.width)).join('-+-') + '-+'; } get headerLines() { return [this.lineSeparator, '| ' + this.columnInfo.map(i => i.title.padEnd(i.width)).join(' | ') + ' |', this.lineSeparator]; } get footerLines() { return [this.lineSeparator]; } public line(...data: (string|number|boolean)[]) { return '| ' + data.map((d, i) => { if (typeof d === 'string') { return d.padEnd(this.columnInfo[i].width); } else { return this.valueToString(d).padStart(this.columnInfo[i].width); } }).join(' | ') + ' |'; } } const maxNamelen = Math.max(...this.fileResults.map(res => res.filename.length)); const maxLanglen = Math.max(...[...this.langResultTable.keys()].map(l => l.length)); const resultFormat = new TextTableFormatter(this.valueToString, {title:'filename', width:maxNamelen}, {title:'language', width:maxLanglen}, {title:'code', width:10}, {title:'comment', width:10}, {title:'blank', width:10}, {title:'total', width:10}); const dirFormat = new TextTableFormatter(this.valueToString, {title:'path', width:maxNamelen}, {title:'files', width:10}, {title:'code', width:10}, {title:'comment', width:10}, {title:'blank', width:10}, {title:'total', width:10}); const langFormat = new TextTableFormatter(this.valueToString, {title:'language', width:maxLanglen}, {title:'files', width:10}, {title:'code', width:10}, {title:'comment', width:10}, {title:'blank', width:10}, {title:'total', width:10}); return [ `Date : ${toLocalDateString(date)}`, `Directory : ${this.targetDirPath}`, // `Total : code: ${this.total.code}, comment : ${this.total.comment}, blank : ${this.total.blank}, all ${this.total.total} lines`, `Total : ${this.total.files} files, ${this.total.code} codes, ${this.total.comment} comments, ${this.total.blank} blanks, all ${this.total.total} lines`, '', 'Languages', ...langFormat.headerLines, ...[...this.langResultTable.values()].sort((a,b) => b.code - a.code) .map(v => langFormat.line(v.name, v.files, v.code, v.comment, v.blank, v.total)), ...langFormat.footerLines, '', 'Directories', ...dirFormat.headerLines, ...[...this.dirResultTable.values()].sort((a,b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) .map(v => dirFormat.line(v.name, v.files, v.code, v.comment, v.blank, v.total)), ...dirFormat.footerLines, '', 'Files', ...resultFormat.headerLines, ...this.fileResults.sort((a,b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0) .map(v => resultFormat.line(v.filename, v.language, v.code, v.comment, v.blank, v.total)), resultFormat.line('Total', '', this.total.code, this.total.comment, this.total.blank, this.total.total), ...resultFormat.footerLines, ]; } public toMarkdownHeaderLines(date: Date) { return [ `Date : ${toLocalDateString(date)}`, '', `Directory ${this.targetDirPath}`, '', `Total : ${this.total.files} files, ${this.total.code} codes, ${this.total.comment} comments, ${this.total.blank} blanks, all ${this.total.total} lines`, ]; } public toMarkdownSummaryLines() { const dirFormat = new MarkdownTableFormatter(this.valueToString, {title:'path', format:'string'}, {title:'files', format:'number'}, {title:'code', format:'number'}, {title:'comment', format:'number'}, {title:'blank', format:'number'}, {title:'total', format:'number'} ); const langFormat = new MarkdownTableFormatter(this.valueToString, {title:'language', format:'string'}, {title:'files', format:'number'}, {title:'code', format:'number'}, {title:'comment', format:'number'}, {title:'blank', format:'number'}, {title:'total', format:'number'} ); return [ '## Languages', ...langFormat.headerLines, ...[...this.langResultTable.values()].sort((a,b) => b.code - a.code) .map(v => langFormat.line(v.name, v.files, v.code, v.comment, v.blank, v.total)), '', '## Directories', ...dirFormat.headerLines, ...[...this.dirResultTable.values()].sort((a,b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0) .map(v => dirFormat.line(v.name, v.files, v.code, v.comment, v.blank, v.total)), ]; } public toMarkdownDetailsLines() { const resultFormat = new MarkdownTableFormatter(this.valueToString, {title:'filename', format:'uri'}, {title:'language', format:'string'}, {title:'code', format:'number'}, {title:'comment', format:'number'}, {title:'blank', format:'number'}, {title:'total', format:'number'} ); return [ '## Files', ...resultFormat.headerLines, ...this.fileResults.sort((a,b) => a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0) .map(v => resultFormat.line(v.uri, v.language, v.code, v.comment, v.blank, v.total)), ]; } } function mapToObject<K,V>(map: Map<K,V>) { const obj: any = {} map.forEach((v,id)=>{ obj[id] = v }) return obj; } function objectToMap<V>(obj: {[key: string]: V}): Map<string,V> { return new Map<string, V>(Object.entries(obj)); } function getOrSet<K,V>(map: Map<K,V>, key: K, otherwise: () => V) { let v = map.get(key); if (v === undefined) { v = otherwise(); map.set(key, v); } return v; } function makeDirectories_(dirpath: vscode.Uri, resolve: ()=> void, reject: (reason: string) => void) { // log(`makeDirectories ${dirpath}`); vscode.workspace.fs.stat(dirpath).then((fileStat) => { if ((fileStat.type & vscode.FileType.Directory) != 0) { resolve(); } else { reject(`${dirpath} is not directory.`); } }, (reason) => { log(`vscode.workspace.fs.stat failed: ${reason}`); const curPath = dirpath.path; const parent = path.dirname(curPath); if (parent !== curPath) { makeDirectories_(dirpath.with({path: parent}), () => { log(`vscode.workspace.fs.createDirectory ${dirpath}`); vscode.workspace.fs.createDirectory(dirpath).then(resolve, reject); }, reject); } else { reject(reason); } }); } function makeDirectories(dirpath: vscode.Uri): Promise<void> { return new Promise((resolve: ()=> void, reject: (reason: string) => void) => makeDirectories_(dirpath, resolve, reject)); } function showTextFile(uri: vscode.Uri) { log(`showTextFile : ${uri}`); return new Promise((resolve: (editor: vscode.TextEditor)=> void, reject: (err: any) => void) => { vscode.workspace.openTextDocument(uri) .then((doc) => vscode.window.showTextDocument(doc, vscode.ViewColumn.One, true), reject) .then(resolve, reject); }); } function writeTextFile(uri: vscode.Uri, text: string): Promise<void> { log(`writeTextFile : ${uri} ${text.length}B`); return new Promise((resolve: ()=> void, reject: (err: any) => void) => { vscode.workspace.fs.writeFile(uri, new TextEncoder().encode(text)).then(resolve, reject); }); }
the_stack
import { Acker, Identity, EventPayload, Listener, Func } from '../../../shapes'; import { addEventListener as addNoteListener } from '../../api/notifications/subscriptions'; import { addRemoteSubscription, subscribeToAllRuntimes, RemoteSubscriptionProps } from '../../remote_subscriptions'; import { Application } from '../../api/application'; import { Channel } from '../../api/channel'; import { addEventListener as addViewListener } from '../../api/browser_view'; import { ExternalApplication } from '../../api/external_application'; import { Frame } from '../../api/frame'; import { getWindowByUuidName, isLocalUuid, getBrowserViewByIdentity } from '../../core_state'; import { GlobalHotkey } from '../../api/global_hotkey'; import { Identity as NoteIdentity } from '../../api/notifications/shapes'; import { noop } from '../../../common/main'; import { System } from '../../api/system'; import { Window } from '../../api/window'; import * as _ from 'underscore'; import * as apiProtocolBase from './api_protocol_base'; import ofEvents from '../../of_events'; import * as ExternalWindow from '../../api/external_window'; type Subscribe = ( identity: Identity | NoteIdentity, eventName: string, payload: EventPayload, listener: Listener ) => Promise<Func>; interface SubscriptionMap { [eventType: string]: Subscribe; } const successAck = { success: true }; const eventMap = { 'subscribe-to-desktop-event': subToDesktopEvent, 'unsubscribe-to-desktop-event': unSubToDesktopEvent }; export function init() { apiProtocolBase.registerActionMap(eventMap); } /* Subscribe to a window event */ const subWindow = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const { uuid, name } = payload; const windowIdentity = apiProtocolBase.getTargetWindowIdentity(payload); const targetUuid = windowIdentity.uuid; const islocalWindow = !!getWindowByUuidName(targetUuid, targetUuid); const localUnsub = Window.addEventListener(identity, windowIdentity, eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); let remoteUnSub = noop; if (!islocalWindow && !isExternalClient) { const subscription: RemoteSubscriptionProps = { className: 'window', eventName, listenType: 'on', name, uuid }; remoteUnSub = await addRemoteSubscription(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to a view event */ const subView = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const { uuid, name } = payload; const viewIdentity = apiProtocolBase.getTargetWindowIdentity(payload); const isLocalView = !!getBrowserViewByIdentity(viewIdentity); const localUnsub = addViewListener(viewIdentity, eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); let remoteUnSub = noop; if (!isLocalView && !isExternalClient) { const subscription: RemoteSubscriptionProps = { className: 'view', eventName, listenType: 'on', name, uuid }; remoteUnSub = await addRemoteSubscription(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to a frame event */ const subFrame = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const { uuid, name } = payload; const frameIdentity = apiProtocolBase.getTargetWindowIdentity(payload); const targetUuid = frameIdentity.uuid; const islocalWindow = !!getWindowByUuidName(targetUuid, targetUuid); const localUnsub = Frame.addEventListener(frameIdentity, eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); let remoteUnSub = noop; if (!islocalWindow && !isExternalClient) { const subscription: RemoteSubscriptionProps = { className: 'frame', eventName, listenType: 'on', name, uuid }; remoteUnSub = await addRemoteSubscription(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to an application event */ const subApplication = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const { uuid } = payload; const appIdentity = apiProtocolBase.getTargetApplicationIdentity(payload); const targetUuid = appIdentity.uuid; const islocalApp = !!getWindowByUuidName(targetUuid, targetUuid); const localUnsub = Application.addEventListener(appIdentity, eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); let remoteUnSub = noop; if (!islocalApp && !isExternalClient) { const subscription: RemoteSubscriptionProps = { className: 'application', eventName, listenType: 'on', uuid }; remoteUnSub = await addRemoteSubscription(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to a channel event */ const subChannel = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const targetIdentity = apiProtocolBase.getTargetWindowIdentity(payload); const { uuid } = targetIdentity; const islocalUuid = isLocalUuid(uuid); const localUnsub = Channel.addEventListener(targetIdentity, eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); let remoteUnSub = noop; const systemWideEvents: {[key: string]: boolean} = { 'connected': true, 'disconnected': true, 'client-disconnected': true }; // these events act like system events if (!islocalUuid && !isExternalClient && systemWideEvents[eventName]) { const subscription: RemoteSubscriptionProps = { className: 'channel', eventName, listenType: 'on' }; remoteUnSub = await subscribeToAllRuntimes(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to a system event */ const subSystem = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const localUnsub = System.addEventListener(eventName, listener); const isExternalClient = ExternalApplication.isRuntimeClient(identity.uuid); const ignoredMultiRuntimeEvents = [ 'external-window-closed', 'external-window-created', 'external-window-hidden', 'external-window-shown' ]; let remoteUnSub = noop; if (!isExternalClient && !ignoredMultiRuntimeEvents.includes(eventName)) { const subscription: RemoteSubscriptionProps = { className: 'system', eventName, listenType: 'on' }; remoteUnSub = await subscribeToAllRuntimes(subscription); } return () => { localUnsub(); remoteUnSub(); }; }; /* Subscribe to a notification event */ const subNotifications = async (identity: NoteIdentity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { return addNoteListener(identity, eventName, payload, listener); }; /* Subscribe to an external app event */ const subExternalApp = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const { uuid } = payload; const externalAppIdentity = { uuid }; return ExternalApplication.addEventListener(externalAppIdentity, eventName, listener); }; /* Subscribe to an external window event */ const subExternalWindow = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { const externalWindowIdentity = apiProtocolBase.getTargetExternalWindowIdentity(payload); return await ExternalWindow.addEventListener(externalWindowIdentity, eventName, listener); }; /* Subscribe to a global hotkey event */ const subGlobalHotkey = async (identity: Identity, eventName: string, payload: EventPayload, listener: Listener): Promise<Func> => { return GlobalHotkey.addEventListener(identity, eventName, listener); }; const subscriptionMap: SubscriptionMap = { 'application': subApplication, 'channel': subChannel, 'external-application': subExternalApp, 'external-window': subExternalWindow, 'frame': subFrame, 'global-hotkey': subGlobalHotkey, 'notifications': subNotifications, 'system': subSystem, 'window': subWindow, 'view': subView }; /* Subscribe to an event */ async function subToDesktopEvent(identity: Identity, message: any, ack: Acker) { const { payload } = message; const { name, topic, type, uuid } = payload; const subscribe: Subscribe = subscriptionMap[topic]; const listener = (emittedPayload: any) => { const event: any = { action: 'process-desktop-event', payload: { topic, type, uuid } }; if (name) { event.payload.name = name; // name may exist in emittedPayload } if (!uuid && emittedPayload.uuid) { event.payload.uuid = emittedPayload.uuid; } if (typeof emittedPayload === 'object') { _.extend(event.payload, _.omit(emittedPayload, _.keys(event.payload))); } apiProtocolBase.sendToIdentity(identity, event); }; if (apiProtocolBase.subscriptionExists(identity, topic, uuid, type, name)) { apiProtocolBase.uppSubscriptionRefCount(identity, topic, uuid, type, name); } else if (typeof subscribe === 'function') { const unsubscribe = await subscribe(identity, type, payload, listener); apiProtocolBase.registerSubscription(unsubscribe, identity, topic, uuid, type, name); } ack(successAck); ofEvents.checkMissedEvents(payload, listener); } /* Unsubscribe from an event */ function unSubToDesktopEvent(identity: Identity, message: any, ack: Acker) { const { payload } = message; const { name, topic, type, uuid } = payload; apiProtocolBase.removeSubscription(identity, topic, uuid, type, name); ack(successAck); }
the_stack
import AtomicValue from '../../../expressions/dataTypes/AtomicValue'; import castToType from '../../../expressions/dataTypes/castToType'; import createAtomicValue from '../../../expressions/dataTypes/createAtomicValue'; import isSubtypeOf from '../../../expressions/dataTypes/isSubtypeOf'; import { ValueType, valueTypeToString, ValueValue } from '../../../expressions/dataTypes/Value'; import ExecutionParameters from '../../../expressions/ExecutionParameters'; import atomize from '../../dataTypes/atomize'; import sequenceFactory from '../../dataTypes/sequenceFactory'; import { SequenceType } from '../../dataTypes/Value'; import DynamicContext from '../../DynamicContext'; import Expression from '../../Expression'; import { hash, operationMap, returnTypeMap } from './BinaryEvaluationFunctionMap'; /** * Lambda helper function to the binary operator */ export type BinaryEvaluationFunction = (left: ValueValue, right: ValueValue) => ValueValue; function determineReturnType(typeA: ValueType, typeB: ValueType): ValueType { if (isSubtypeOf(typeA, ValueType.XSINTEGER) && isSubtypeOf(typeB, ValueType.XSINTEGER)) { return ValueType.XSINTEGER; } if (isSubtypeOf(typeA, ValueType.XSDECIMAL) && isSubtypeOf(typeB, ValueType.XSDECIMAL)) { return ValueType.XSDECIMAL; } if (isSubtypeOf(typeA, ValueType.XSFLOAT) && isSubtypeOf(typeB, ValueType.XSFLOAT)) { return ValueType.XSFLOAT; } return ValueType.XSDOUBLE; } /** * An array with every possible parent type contained in the returnTypeMap and the operationsMap. */ const allTypes = [ ValueType.XSNUMERIC, ValueType.XSYEARMONTHDURATION, ValueType.XSDAYTIMEDURATION, ValueType.XSDATETIME, ValueType.XSDATE, ValueType.XSTIME, ]; /** * Generate the return function of the binary operator. * * @param operator The binary operator * @param typeA the left part of the operation * @param typeB the right part of the operation * @returns The function used to evaluate the binary operator */ export function generateBinaryOperatorFunction( operator: string, typeA: ValueType, typeB: ValueType ): BinaryEvaluationFunction { let castFunctionForValueA: any = null; let castFunctionForValueB: any = null; if (isSubtypeOf(typeA, ValueType.XSUNTYPEDATOMIC)) { castFunctionForValueA = (value: any) => castToType(value, ValueType.XSDOUBLE); typeA = ValueType.XSDOUBLE; } if (isSubtypeOf(typeB, ValueType.XSUNTYPEDATOMIC)) { castFunctionForValueB = (value: any) => castToType(value, ValueType.XSDOUBLE); typeB = ValueType.XSDOUBLE; } // Filter all the possible types to only those which the operands are a subtype of. const parentTypesOfA = allTypes.filter((e) => isSubtypeOf(typeA, e)); const parentTypesOfB = allTypes.filter((e) => isSubtypeOf(typeB, e)); function applyCastFunctions(valueA: AtomicValue, valueB: AtomicValue) { return { castA: castFunctionForValueA ? castFunctionForValueA(valueA) : valueA, castB: castFunctionForValueB ? castFunctionForValueB(valueB) : valueB, }; } // As the Numeric operands need some checks done beforehand we need to evaluate them seperatly. if ( parentTypesOfA.includes(ValueType.XSNUMERIC) && parentTypesOfB.includes(ValueType.XSNUMERIC) ) { const fun = operationMap[hash(ValueType.XSNUMERIC, ValueType.XSNUMERIC, operator)]; let retType = returnTypeMap[hash(ValueType.XSNUMERIC, ValueType.XSNUMERIC, operator)]; if (!retType) retType = determineReturnType(typeA, typeB); if (operator === 'divOp' && retType === ValueType.XSINTEGER) retType = ValueType.XSDECIMAL; if (operator === 'idivOp') return iDivOpChecksFunction(applyCastFunctions, fun)[0]; return (a, b) => { const { castA, castB } = applyCastFunctions(a, b); return createAtomicValue(fun(castA.value, castB.value), retType); }; } // Loop through the 2 arrays to find a combination of parentTypes and operand that has an entry in the operationsMap and the returnTypeMap. for (const typeOfA of parentTypesOfA) { for (const typeOfB of parentTypesOfB) { const func = operationMap[hash(typeOfA, typeOfB, operator)]; const ret = returnTypeMap[hash(typeOfA, typeOfB, operator)]; if (func && ret !== undefined) { return (a, b) => { const { castA, castB } = applyCastFunctions(a, b); return createAtomicValue(func(castA.value, castB.value), ret); }; } } } return undefined; } /** * Generate the return type of the function. * @param operator The binary operator * @param typeA the left part of the operation * @param typeB the right part of the operation * @returns The type of the entire binary operation */ export function generateBinaryOperatorType( operator: string, typeA: ValueType, typeB: ValueType ): ValueType { const GENERIC_NUMERIC_VALUE_TYPES = [ ValueType.XSNUMERIC, ValueType.NODE, ValueType.ITEM, ValueType.XSANYATOMICTYPE, ValueType.ATTRIBUTE, ]; if ( GENERIC_NUMERIC_VALUE_TYPES.includes(typeA) || GENERIC_NUMERIC_VALUE_TYPES.includes(typeB) ) { return ValueType.XSNUMERIC; } let castFunctionForValueA: any = null; let castFunctionForValueB: any = null; if (isSubtypeOf(typeA, ValueType.XSUNTYPEDATOMIC)) { castFunctionForValueA = (value: any) => castToType(value, ValueType.XSDOUBLE); typeA = ValueType.XSDOUBLE; } if (isSubtypeOf(typeB, ValueType.XSUNTYPEDATOMIC)) { castFunctionForValueB = (value: any) => castToType(value, ValueType.XSDOUBLE); typeB = ValueType.XSDOUBLE; } function applyCastFunctions(valueA: AtomicValue, valueB: AtomicValue) { return { castA: castFunctionForValueA ? castFunctionForValueA(valueA) : valueA, castB: castFunctionForValueB ? castFunctionForValueB(valueB) : valueB, }; } // Filter all the possible types to only those which the operands are a subtype of. const parentTypesOfA = allTypes.filter((e) => isSubtypeOf(typeA, e)); const parentTypesOfB = allTypes.filter((e) => isSubtypeOf(typeB, e)); // As the Numeric operands need some checks done beforehand we need to evaluate them seperatly. if ( parentTypesOfA.includes(ValueType.XSNUMERIC) && parentTypesOfB.includes(ValueType.XSNUMERIC) ) { let retType = returnTypeMap[hash(ValueType.XSNUMERIC, ValueType.XSNUMERIC, operator)]; if (retType === undefined) retType = determineReturnType(typeA, typeB); if (operator === 'divOp' && retType === ValueType.XSINTEGER) retType = ValueType.XSDECIMAL; if (operator === 'idivOp') return iDivOpChecksFunction(applyCastFunctions, (a, b) => Math.trunc(a / b))[1]; return retType; } // Loop through the 2 arrays to find a combination of parentTypes and operand that has an entry in the operationsMap and the returnTypeMap. for (const typeOfA of parentTypesOfA) { for (const typeOfB of parentTypesOfB) { const ret = returnTypeMap[hash(typeOfA, typeOfB, operator)]; if (ret !== undefined) { return ret; } } } return undefined; } /** * The integerDivision needs some seperate more ellaborate checks so is moved into a seperate function. * @param applyCastFunctions The casting function * @param fun The function retrieved from the map * @returns A tuple of a function that needs to be applied to the operands and the returnType of the integerDivision. */ function iDivOpChecksFunction( applyCastFunctions: (a: AtomicValue, b: AtomicValue) => any, fun: (a: any, b: any) => any ): [(a: any, b: any) => AtomicValue, ValueType] { return [ (a, b) => { const { castA, castB } = applyCastFunctions(a, b); if (castB.value === 0) { throw new Error('FOAR0001: Divisor of idiv operator cannot be (-)0'); } if ( Number.isNaN(castA.value) || Number.isNaN(castB.value) || !Number.isFinite(castA.value) ) { throw new Error( 'FOAR0002: One of the operands of idiv is NaN or the first operand is (-)INF' ); } if (Number.isFinite(castA.value) && !Number.isFinite(castB.value)) { return createAtomicValue(0, ValueType.XSINTEGER); } return createAtomicValue(fun(castA.value, castB.value), ValueType.XSINTEGER); }, ValueType.XSINTEGER, ]; } /** * A cache to store the generated functions. */ const operatorsByTypingKey: Record<string, BinaryEvaluationFunction> = Object.create(null); /** * retrieve the function used to evaluate a binary operator. * @param leftType the left part of the operation * @param rightType the right part of the operation * @param operator the kind of operation * @returns the function of the binOp */ export function getBinaryPrefabOperator( leftType: ValueType, rightType: ValueType, operator: string ): BinaryEvaluationFunction { const typingKey = `${leftType}~${rightType}~${operator}`; let prefabOperator = operatorsByTypingKey[typingKey]; if (!prefabOperator) { prefabOperator = operatorsByTypingKey[typingKey] = generateBinaryOperatorFunction( operator, leftType, rightType ); } return prefabOperator; } /** * A class representing a BinaryOperationExpression */ class BinaryOperator extends Expression { private _evaluateFunction?: BinaryEvaluationFunction; private _firstValueExpr: Expression; private _operator: string; private _secondValueExpr: Expression; /** * @param operator One of addOp, substractOp, multiplyOp, divOp, idivOp, modOp * @param firstValueExpr The selector evaluating to the first value to process * @param secondValueExpr The selector evaluating to the second value to process */ constructor( operator: string, firstValueExpr: Expression, secondValueExpr: Expression, type: SequenceType, evaluateFunction: BinaryEvaluationFunction ) { super( firstValueExpr.specificity.add(secondValueExpr.specificity), [firstValueExpr, secondValueExpr], { canBeStaticallyEvaluated: false, }, false, type ); this._firstValueExpr = firstValueExpr; this._secondValueExpr = secondValueExpr; this._operator = operator; this._evaluateFunction = evaluateFunction; } /** * A method to evaluate the BinaryOperation. * @param dynamicContext The context in which it will be evaluated * @param executionParameters options * @returns The value to which the operation evaluates. */ public evaluate(dynamicContext: DynamicContext, executionParameters: ExecutionParameters) { const firstValueSequence = atomize( this._firstValueExpr.evaluateMaybeStatically(dynamicContext, executionParameters), executionParameters ); return firstValueSequence.mapAll((firstValues) => { if (firstValues.length === 0) { // Shortcut, if the first part is empty, we can return empty. // As per spec, we do not have to evaluate the second part, though we could. return sequenceFactory.empty(); } const secondValueSequence = atomize( this._secondValueExpr.evaluateMaybeStatically(dynamicContext, executionParameters), executionParameters ); return secondValueSequence.mapAll((secondValues) => { if (secondValues.length === 0) { return sequenceFactory.empty(); } if (firstValues.length > 1 || secondValues.length > 1) { throw new Error( 'XPTY0004: the operands of the "' + this._operator + '" operator should be empty or singleton.' ); } const firstValue = firstValues[0]; const secondValue = secondValues[0]; // We could infer all the necessary type information to do an early return if (this._evaluateFunction && this.type) { return sequenceFactory.singleton( this._evaluateFunction(firstValue, secondValue) ); } const prefabOperator = getBinaryPrefabOperator( firstValue.type, secondValue.type, this._operator ); if (!prefabOperator) { throw new Error( `XPTY0004: ${this._operator} not available for types ${valueTypeToString( firstValue.type )} and ${valueTypeToString(secondValue.type)}` ); } return sequenceFactory.singleton(prefabOperator(firstValue, secondValue)); }); }); } } export default BinaryOperator;
the_stack
import { ChainEpoch, Cid, KeyInfo, Message, MethodMultisig, NewAddressType, Signature, SignedMessage } from '../Types'; import { BaseWalletProvider } from './BaseWalletProvider'; import { MultisigProviderInterface, WalletProviderInterface } from "../ProviderInterfaces"; import { LotusClient } from '../..'; export class LotusWalletProvider extends BaseWalletProvider implements WalletProviderInterface, MultisigProviderInterface { constructor(client: LotusClient) { super(client); } // WaletProvider implementation /** * create new wallet * @param type */ public async newAddress(type: NewAddressType = NewAddressType.SECP256K1): Promise<string> { const ret = await this.client.wallet.new(type); return ret as string; } /** * delete address from lotus * @param address */ public async deleteAddress(address: string): Promise<any> { const ret = await this.client.wallet.delete(address); return ret as boolean; } /** * get wallet list */ public async getAddresses(): Promise<string[]> { const ret = await this.client.wallet.list(); return ret as string[]; } /** * check if address is in keystore * @param address */ public async hasAddress(address: string): Promise<boolean> { const ret = await this.client.wallet.has(address); return ret as boolean; } /** * set default address * @param address */ public async setDefaultAddress(address: string): Promise<undefined> { const ret = await this.client.wallet.setDefault(address); return ret as undefined; } /** * get default address */ public async getDefaultAddress(): Promise<string> { const ret = await this.client.wallet.getDefaultAddress(); return ret as string; } /** * walletExport returns the private key of an address in the wallet. * @param address */ public async exportPrivateKey(address: string): Promise<KeyInfo> { const ret = await this.client.wallet.export(address); return ret as KeyInfo; } /** * send message, signed with default lotus wallet * @param msg */ public async sendMessage(msg: Message): Promise<SignedMessage> { const ret = await this.client.mpool.pushMessage(msg) return ret as SignedMessage; } /** * sign message * @param msg */ public async signMessage(msg: Message): Promise<SignedMessage> { const ret = await this.client.wallet.signMessage(msg); return ret as SignedMessage; } /** * sign raw message * @param data */ public async sign(data: string | ArrayBuffer): Promise<Signature> { const ret = await this.client.wallet.sign(data); return ret as Signature; } /** * verify message signature * @param data * @param sign */ public async verify(address: string, data: string | ArrayBuffer, sign: Signature): Promise<boolean> { const ret = await this.client.wallet.verify(address, data, sign); return ret as boolean; } //MultisigProvider Implementation /** * creates a multisig wallet * @param requiredNumberOfSenders * @param approvingAddresses * @param startEpoch * @param unlockDuration * @param initialBalance * @param senderAddressOfCreateMsg */ public async msigCreate( requiredNumberOfSenders: number, approvingAddresses: string[], startEpoch: ChainEpoch, unlockDuration: ChainEpoch, initialBalance: string, senderAddressOfCreateMsg: string, ): Promise<Cid> { const ret = await this.client.msig.create(requiredNumberOfSenders, approvingAddresses, unlockDuration, initialBalance, senderAddressOfCreateMsg, '0'); return ret; } /** * proposes a multisig message * @param address * @param recipientAddres * @param value * @param senderAddressOfProposeMsg */ public async msigProposeTransfer( address: string, recipientAddres: string, value: string, senderAddressOfProposeMsg: string ): Promise<Cid> { const ret = await this.client.msig.propose(address, recipientAddres, value, senderAddressOfProposeMsg, 0, []); return ret; } /** * approves a previously-proposed multisig message by transaction ID * @param address * @param proposedTransactionId * @param signerAddress */ public async msigApproveTransfer( address: string, proposedTransactionId: number, signerAddress: string, ): Promise<Cid> { const ret = await this.client.msig.approve(address, proposedTransactionId, signerAddress); return ret; } /** * approves a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfApproveMsg */ public async msigApproveTransferTxHash( address: string, proposedMessageId: number, proposerAddress: string, recipientAddres: string, value: string, senderAddressOfApproveMsg: string ): Promise<Cid> { const ret = await this.client.msig.approveTxnHash(address, proposedMessageId, proposerAddress, recipientAddres, value, senderAddressOfApproveMsg, 0, []); return ret; } /** * cancels a previously-proposed multisig message * @param address * @param proposedMessageId * @param proposerAddress * @param recipientAddres * @param value * @param senderAddressOfCancelMsg */ public async msigCancelTransfer( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, recipientAddres: string, value: string, ): Promise<Cid> { const ret = await this.client.msig.cancel(address, proposedMessageId, senderAddressOfCancelMsg, recipientAddres, value, senderAddressOfCancelMsg, 0, []); return ret; } /** * proposes adding a signer in the multisig * @param address * @param senderAddressOfProposeMsg * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigProposeAddSigner( address: string, senderAddressOfProposeMsg: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean, ): Promise<Cid> { const ret = await this.client.msig.addPropose(address, senderAddressOfProposeMsg, newSignerAddress, increaseNumberOfRequiredSigners); return ret; } /** * approves a previously proposed AddSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigApproveAddSigner( address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean ): Promise<Cid> { const ret = await this.client.msig.addApprove(address, senderAddressOfApproveMsg, proposedMessageId, proposerAddress, newSignerAddress, increaseNumberOfRequiredSigners); return ret; } /** * cancels a previously proposed AddSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param newSignerAddress * @param increaseNumberOfRequiredSigners */ public async msigCancelAddSigner( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, newSignerAddress: string, increaseNumberOfRequiredSigners: boolean ): Promise<Cid> { const ret = await this.client.msig.addCancel(address, senderAddressOfCancelMsg, proposedMessageId, newSignerAddress, increaseNumberOfRequiredSigners); return ret; } /** * proposes swapping 2 signers in the multisig * @param address * @param senderAddressOfProposeMsg * @param oldSignerAddress * @param newSignerAddress */ public async msigProposeSwapSigner( address: string, senderAddressOfProposeMsg: string, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const ret = await this.client.msig.swapPropose(address, senderAddressOfProposeMsg, oldSignerAddress, newSignerAddress); return ret; } /** * approves a previously proposed SwapSigner * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param oldSignerAddress * @param newSignerAddress */ public async msigApproveSwapSigner( address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const ret = await this.client.msig.swapApprove(address, senderAddressOfApproveMsg, proposedMessageId, proposerAddress, oldSignerAddress, newSignerAddress); return ret; } /** * cancels a previously proposed SwapSigner message * @param address * @param senderAddressOfCancelMsg * @param proposedMessageId * @param oldSignerAddress * @param newSignerAddress */ public async msigCancelSwapSigner( address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, oldSignerAddress: string, newSignerAddress: string, ): Promise<Cid> { const ret = await this.client.msig.swapCancel(address, senderAddressOfCancelMsg, proposedMessageId, oldSignerAddress, newSignerAddress); return ret; } /** * proposes removing a signer from the multisig * @param address * @param senderAddressOfProposeMsg * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigProposeRemoveSigner( address: string, senderAddressOfProposeMsg: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean, ): Promise<Cid> { const ret = await this.client.msig.removeSigner(address, senderAddressOfProposeMsg, addressToRemove, decreaseNumberOfRequiredSigners); return ret; }; /** * approves a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param proposerAddress * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigApproveRemoveSigner(address: string, senderAddressOfApproveMsg: string, proposedMessageId: number, proposerAddress: string, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid> { return undefined as any; }; /** * cancels a previously proposed RemoveSigner message * @param address * @param senderAddressOfApproveMsg * @param proposedMessageId * @param addressToRemove * @param decreaseNumberOfRequiredSigners */ public async msigCancelRemoveSigner(address: string, senderAddressOfCancelMsg: string, proposedMessageId: number, addressToRemove: string, decreaseNumberOfRequiredSigners: boolean): Promise<Cid> { return undefined as any; }; // Own functions /** * walletImport returns the private key of an address in the wallet. * @param keyInfo */ public async walletImport(keyInfo: KeyInfo): Promise<string> { const ret = await this.client.wallet.import(keyInfo); return ret as string; } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQuery UI plugin that lets users edit an array of values where each entry in the array is represented by a pane of fields. */ namespace VRS { /** * The options for the OptionFieldPaneListPlugin. */ export interface OptionFieldPaneListPlugin_Options extends OptionControl_BaseOptions { field: OptionFieldPaneList; } /** * The object that carries state for the OptionFieldPaneListPlugin. */ class OptionFieldPaneListPlugin_State { /** * A jQuery object describing the container for the list. */ container: JQuery; /** * A jQuery object describing the container for the panes. */ panesParent: JQuery; /** * A jQuery object describing the container for the add panel. */ addParent: JQuery; /** * An array of containers, one for each pane in index order. */ paneContainers: JQuery[] = []; /** * The option pane for the "add a pane" panel. */ addPaneContainer: JQuery = null; /** * The hook result from the pane added event we're hooking on OptionPaneListTypeSettings. */ paneAddedHookResult: IEventHandle; /** * The hook result from the pane removed event we're hooking on OptionPaneListTypeSettings. */ paneRemovedHookResult: IEventHandle; /** * The hook result from the max panes changed event we're hooking on OptionPaneListTypeSettings. */ maxPanesChangedHookResult: IEventHandle; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getOptionFieldPaneListPlugin = function(jQueryElement: JQuery) : OptionFieldPaneListPlugin { return jQueryElement.data('vrsVrsOptionFieldPaneList'); } VRS.jQueryUIHelper.getOptionFieldPaneListOptions = function(overrides: OptionFieldPaneListPlugin_Options) : OptionFieldPaneListPlugin_Options { return $.extend({ optionPageParent: null, }, overrides); } /** * A jQuery UI widget that allows an array to be edited via a list of panes. */ export class OptionFieldPaneListPlugin extends JQueryUICustomWidget { options: OptionFieldPaneListPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getOptionFieldPaneListOptions(); } private _getState() : OptionFieldPaneListPlugin_State { var result = this.element.data('optionFieldPanelListState'); if(result === undefined) { result = new OptionFieldPaneListPlugin_State(); this.element.data('optionFieldPanelListState', result); } return result; } _create() { var state = this._getState(); var field = this.options.field; var panes = field.getPanes(); state.paneAddedHookResult = field.hookPaneAdded(this._paneAdded, this); state.paneRemovedHookResult = field.hookPaneRemoved(this._paneRemoved, this); state.maxPanesChangedHookResult = field.hookMaxPanesChanged(this._maxPanesChanged, this); state.container = this.element; state.panesParent = $('<div/>') .appendTo(state.container); var length = panes.length; for(var i = 0;i < length;++i) { var pane = panes[i]; this._addPane(pane, state); } var addPanel = field.getAddPane(); if(addPanel) { state.addParent = $('<div/>') .appendTo(state.container); state.addPaneContainer = this._addOptionsPane(addPanel, state.addParent); } this._refreshControlStates(); } _destroy() { var state = this._getState(); var field = this.options.field; if(state.paneAddedHookResult) { field.unhook(state.paneAddedHookResult); state.paneAddedHookResult = undefined; } if(state.paneRemovedHookResult) { field.unhook(state.paneRemovedHookResult); state.paneRemovedHookResult = undefined; } if(state.maxPanesChangedHookResult) { field.unhook(state.maxPanesChangedHookResult); state.maxPanesChangedHookResult = undefined; } if(state.addPaneContainer) { var widget = VRS.jQueryUIHelper.getOptionPanePlugin(state.addPaneContainer); widget.destroy(); } $.each(state.paneContainers, function(idx, optionPane) { var widget = VRS.jQueryUIHelper.getOptionPanePlugin(optionPane); widget.destroy(); }); this.element.empty(); } /** * Adds a new pane that represents an item in the array to the list of panes. */ private _addPane(pane: OptionPane, state: OptionFieldPaneListPlugin_State) { var field = this.options.field; var showRemoveButton = !field.getSuppressRemoveButton(); if(pane.getFieldCount()) { var lastField = pane.getField(pane.getFieldCount() - 1); var lastFieldKeepWithNext = lastField.getKeepWithNext(); var removeButtonFieldName = 'removePane'; if(showRemoveButton) { lastField.setKeepWithNext(true); pane.addField(new VRS.OptionFieldButton({ name: removeButtonFieldName, labelKey: 'Remove', saveState: function() { field.removePane(pane); }, icon: 'trash', showText: false })); } var paneContainer = this._addOptionsPane(pane, state.panesParent); state.paneContainers.push(paneContainer); if(showRemoveButton) { pane.removeFieldByName(removeButtonFieldName); lastField.setKeepWithNext(lastFieldKeepWithNext); } } } /** * Adds a new pane containing controls that can add item panes to the UI. It always appears after the list of * item panes. */ private _addOptionsPane(pane: OptionPane, parent: JQuery) : JQuery { return $('<div/>') .vrsOptionPane(VRS.jQueryUIHelper.getOptionPaneOptions({ optionPane: pane, optionPageParent: this.options.optionPageParent, isInStack: true })) .appendTo(parent); } /** * Updates the enabled and disabled states of all of the panes and their controls. */ private _refreshControlStates() { var state = this._getState(); var field = this.options.field; if(state.addParent) { var maxPanes = field.getMaxPanes(); var disabled = maxPanes !== -1 && state.paneContainers.length >= maxPanes; field.getRefreshAddControls()(disabled, state.addParent); } } /** * Called when the user adds a new item and pane to the list. */ private _paneAdded(pane: OptionPane) { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); this._addPane(pane, state); this._refreshControlStates(); } /** * Called when the user removes an existing item and pane from the list. */ _paneRemoved(pane: OptionPane, index: number) { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); var paneContainer = state.paneContainers[index]; state.paneContainers.splice(index, 1); paneContainer.remove(); this._refreshControlStates(); } /** * Called when something has changed the maximum number of panes (and thereby items) that the user can have in the list. */ private _maxPanesChanged() { this._refreshControlStates(); } } $.widget('vrs.vrsOptionFieldPaneList', new OptionFieldPaneListPlugin()); if(VRS.optionControlTypeBroker) { VRS.optionControlTypeBroker.addControlTypeHandlerIfNotRegistered( VRS.optionControlTypes.paneList, function(settings: OptionFieldPaneListPlugin_Options) { return $('<div/>') .appendTo(settings.fieldParentJQ) .vrsOptionFieldPaneList(VRS.jQueryUIHelper.getOptionFieldPaneListOptions(settings)); } ); } } declare interface JQuery { vrsOptionFieldPaneList(); vrsOptionFieldPaneList(options: VRS.OptionFieldPaneListPlugin_Options); vrsOptionFieldPaneList(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import React, { Component } from 'react' import { Text, View, TouchableNativeFeedback, RefreshControl, InteractionManager, FlatList } from 'react-native' declare var global import Ionicons from 'react-native-vector-icons/Ionicons' import { getMyGameAPI } from '../../dao' import UserGameItem from '../../component/UserGameItem' import FooterProgress from '../../component/FooterProgress' let toolbarActions = [ { title: '跳页', iconName: 'md-map', show: 'always' } ] class UserGame extends Component<any, any> { static navigationOptions = { tabBarLabel: '游戏' } constructor(props) { super(props) this.state = { list: [], numberPerPage: 60, numPages: 1, commentTotal: 1, currentPage: 1, isRefreshing: true, isLoadingMore: false, modalVisible: false, sliderValue: 1, pf: 'all', ob: 'date', dlc: 'all', text: '', scrollEnabled: true } } async componentWillMount() { const { screenProps } = this.props const name = '游戏' let params: any = {} screenProps.toolbar.forEach(({ text, url}) => { // console.log(text, name, text.includes(name)) if (text.includes(name)) { params.text = text params.URL = url } }) if (!params.URL) { params = { ...screenProps.toolbar[1] } } this.URL = params.URL.includes('?page') ? params.URL : `${params.URL}?page=1` this.originURL = params.URL this.fetchMessages(params.URL, 'jump') } originURL: any = '' URL: any = '' flatlist: any = false fetchMessages = (url, type = 'down') => { this.setState({ [type === 'down' ? 'isLoadingMore' : 'isRefreshing'] : true }, () => { if (type !== 'down') { this.flatlist && this.flatlist.scrollToOffset({ offset: 0, animated: true }) } InteractionManager.runAfterInteractions(() => { // alert(url) getMyGameAPI(url).then(data => { let thisList: any[] = [] const thisPage = parseInt((url.match(/\page=(\d+)/) || [0, 1])[1], 10) let cb = () => {} if (type === 'down') { thisList = this.state.list.concat(data.list) this.pageArr.push(thisPage) } else if (type === 'up') { thisList = this.state.list.slice() thisList.unshift(...data.list) this.pageArr.unshift(thisPage) } else if (type === 'jump') { // cb = () => this.listView.scrollTo({ y: 0, animated: true }); thisList = data.list this.pageArr = [thisPage] } this.pageArr = this.pageArr.sort((a, b) => a - b) this.setState({ list: thisList, numberPerPage: data.numberPerPage, numPages: data.numPages, commentTotal: data.len, currentPage: thisPage, isLoadingMore: false, isRefreshing: false }, () => { cb() const componentDidFocus = () => { InteractionManager.runAfterInteractions(() => { this.props.screenProps.setToolbar({ toolbar: toolbarActions, toolbarActions: this.onActionSelected, componentDidFocus: { index: 1, handler: componentDidFocus, afterSnap: (scrollEnabled) => { const refs = this.flatlist && this.flatlist._listRef && this.flatlist._listRef.getScrollableNode() if (refs && refs.setNativeProps) { refs.setNativeProps({ scrollEnabled }) } else { this.setState({ scrollEnabled }) } } } }) }) } componentDidFocus() }) }) }) }) } pageArr = [1] _onRefresh = () => { const { URL } = this const currentPage = this.pageArr[0] || 1 let type = currentPage === 1 ? 'jump' : 'up' let targetPage = currentPage - 1 if (type === 'jump') { targetPage = 1 } if (this.pageArr.includes(targetPage)) type = 'jump' if (this.state.isLoadingMore || this.state.isRefreshing) return this.fetchMessages(URL.split('=').slice(0, -1).concat(targetPage).join('='), type) } _onEndReached = () => { const { URL } = this const currentPage = this.pageArr[this.pageArr.length - 1] const targetPage = currentPage + 1 if (targetPage > this.state.numPages) return if (this.state.isLoadingMore || this.state.isRefreshing) return this.fetchMessages(URL.split('=').slice(0, -1).concat(targetPage).join('='), 'down') } onActionSelected = (index) => { switch (index) { case 0: this.setState({ modalVisible: true }) return } } ITEM_HEIGHT = 83 _renderItem = ({ item: rowData }) => { const { modeInfo, navigation } = this.props.screenProps const { ITEM_HEIGHT } = this return <UserGameItem {...{ navigation, rowData, modeInfo, ITEM_HEIGHT }} /> } sliderValue = 1 render() { const { modeInfo } = this.props.screenProps // console.log('Message.js rendered'); return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <FlatList style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} ref={flatlist => this.flatlist = flatlist} refreshControl={ <RefreshControl refreshing={this.state.isRefreshing} onRefresh={this._onRefresh} colors={[modeInfo.accentColor]} progressBackgroundColor={modeInfo.backgroundColor} /> } ListFooterComponent={() => <FooterProgress isLoadingMore={this.state.isLoadingMore} modeInfo={modeInfo}/>} data={this.state.list} scrollEnabled={this.state.scrollEnabled} removeClippedSubviews={false} keyExtractor={(item) => item.href} renderItem={this._renderItem} onEndReached={this._onEndReached} onEndReachedThreshold={0.5} extraData={modeInfo} windowSize={21} updateCellsBatchingPeriod={1} initialNumToRender={42} maxToRenderPerBatch={8} disableVirtualization={false} key={modeInfo.themeName} renderScrollComponent={props => <global.NestedScrollView {...props}/>} numColumns={modeInfo.numColumns} viewabilityConfig={{ minimumViewTime: 1, viewAreaCoveragePercentThreshold: 0, waitForInteractions: true }} /> <View style={{ position: 'absolute', right: 16, bottom: 16, width: 56, height: 56, borderRadius: 28, justifyContent: 'center', alignItems: 'center', elevation: 6 }} ref={float => this.float = float}> <TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()} useForeground={false} onPress={() => this.setState({ modalVisible: true })} onPressIn={() => { this.float.setNativeProps({ style: { elevation: 12 } }) }} onPressOut={() => { this.float.setNativeProps({ style: { elevation: 6 } }) }}> <View pointerEvents='box-only' style={{ backgroundColor: modeInfo.accentColor, borderRadius: 28, width: 56, height: 56, flex: -1, justifyContent: 'center', alignItems: 'center' }}> <Ionicons name='md-search' size={24} color={modeInfo.backgroundColor}/> </View> </TouchableNativeFeedback> </View> {this.state.modalVisible && ( <global.MyDialog modeInfo={modeInfo} modalVisible={this.state.modalVisible} onDismiss={() => { this.setState({ modalVisible: false }); this.isValueChanged = false }} onRequestClose={() => { this.setState({ modalVisible: false }); this.isValueChanged = false }} renderContent={() => ( <View style={{ justifyContent: 'center', alignItems: 'flex-start', backgroundColor: modeInfo.backgroundColor, paddingVertical: 20, paddingHorizontal: 20, elevation: 4, opacity: 1, borderRadius: 2 }} > { Object.keys(filters).map((kind, index) => { return ( <View style={{flexDirection: 'row', padding: 5}} key={index}> <Text style={{color: modeInfo.standardTextColor, textAlignVertical: 'center'}}>{filters[kind].text}: </Text> { filters[kind].value.map((item, inner) => { return ( <View key={inner} style={{margin: 2}}> <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPress={() => { this.setState({ [kind]: item.value, modalVisible: false }, () => { const { pf, ob, dlc, text } = this.state this.URL = this.originURL + `?${text ? 'title=' + text + '&' : ''}&pf=${pf}&ob=${ob}&dlc=${dlc}&page=1` this.fetchMessages(this.URL, 'jump') }) }}> <View style={{ flex: -1, padding: 4, paddingHorizontal: 6, backgroundColor: modeInfo[item.value === this.state[kind] ? 'accentColor' : 'standardColor'], borderRadius: 2 }}> <Text style={{ color: modeInfo.backgroundColor }}>{item.text}</Text> </View> </TouchableNativeFeedback> </View> ) }) } </View> ) }) } <View style={{ alignSelf: 'stretch', justifyContent: 'center' }}> <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPress={this.goToSearch}> <View pointerEvents='box-only' style={{ flex: 0, padding: 4, paddingHorizontal: 6, margin: 4, backgroundColor: modeInfo.standardColor, borderRadius: 2, alignSelf: 'stretch' }}> <Text style={{ color: modeInfo.backgroundColor, textAlign: 'center', textAlignVertical: 'center' }}>搜索</Text> </View> </TouchableNativeFeedback> { this.state.text && <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPress={() => this.search('')}> <View pointerEvents='box-only' style={{ flex: 0, padding: 4, paddingHorizontal: 6, margin: 4, backgroundColor: modeInfo.standardColor, borderRadius: 2, alignSelf: 'stretch' }}> <Text style={{ color: modeInfo.backgroundColor, textAlign: 'center', textAlignVertical: 'center' }}>清空搜索</Text> </View> </TouchableNativeFeedback> || undefined} </View> </View> )} /> )} </View> ) } isValueChanged = false float: any = false search = (text) => { this.setState({ modalVisible: false, text }, () => { const { pf, ob, dlc, text } = this.state this.URL = this.originURL + `?${text ? 'title=' + text + '&' : ''}pf=${pf}&ob=${ob}&dlc=${dlc}&page=1` this.fetchMessages(this.URL, 'jump') }) } goToSearch = async () => { await this.setState({ modalVisible: false }) this.props.screenProps.navigation.navigate('Search', { callback: (text) => { if (text === this.state.text) return this.search(text) }, content: this.state.text, placeholder: '搜索游戏', shouldSeeBackground: true }) } } const filters = { pf: { text: '平台', value: [{ text: '全部', value: 'all' }, { text: 'PSV', value: 'psvita' }, { text: 'PS3', value: 'ps3' }, { text: 'PS4', value: 'ps4' }] }, ob: { text: '排序', value: [{ text: '最新', value: 'date' }, { text: '进度最快', value: 'ratio' }, { text: '进度最慢', value: 'hole' }, { text: '完美难度', value: 'difficulty' }] }, dlc: { text: 'DLC', value: [{ text: '全部', value: 'all' }, { text: '有DLC', value: 'dlc' }, { text: '无DLC', value: 'nodlc' }] } } export default UserGame
the_stack
import BI from 'big-integer'; import hexToBinaryUtil from 'hex-to-binary'; import { Buffer } from 'safe-buffer'; import crypto from 'crypto'; // CONVERSION FUNCTIONS /** Helper function for the converting any base to any base */ export const parseToDigitsArray = (str, base): number[] | null => { const digits = str.split(''); const ary: number[] = []; for (let i = digits.length - 1; i >= 0; i -= 1) { const n = parseInt(digits[i], base); if (Number.isNaN(n)) { return null; } ary.push(n); } return ary; }; /** Helper function for the converting any base to any base */ export const add = (x, y, base): number[] => { const z: number[] = []; const n = Math.max(x.length, y.length); let carry = 0; let i = 0; while (i < n || carry) { const xi = i < x.length ? x[i] : 0; const yi = i < y.length ? y[i] : 0; const zi = carry + xi + yi; z.push(zi % base); carry = Math.floor(zi / base); i += 1; } return z; }; /** * Helper function for the converting any base to any base Returns a*x, * where x is an array of decimal digits and a is an ordinary JavaScript * number. base is the number base of the array x. */ export const multiplyByNumber = (num, x, base): number[] | null => { if (num < 0) { return null; } if (num === 0) { return []; } let result: number[] = []; let power = x; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-next-line no-bitwise if (num & 1) { result = add(result, power, base); } num >>= 1; // eslint-disable-line if (num === 0) { break; } power = add(power, power, base); } return result; }; /** * Helper function for the converting any base to any base */ export const convertBase = (str, fromBase, toBase): string | null => { const digits = parseToDigitsArray(str, fromBase); if (digits === null) { return null; } let outArray: number[] = []; let power: number[] = [1]; for (let i = 0; i < digits.length; i += 1) { // invariant: at this point, fromBase^i = power if (digits[i]) { outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase); } power = multiplyByNumber(fromBase, power, toBase) as number[]; } let out = ''; for (let i = outArray.length - 1; i >= 0; i -= 1) { out += outArray[i].toString(toBase); } // if the original input was equivalent to zero, then 'out' will still be empty ''. Let's check for zero. if (out === '') { let sum = 0; for (let i = 0; i < digits.length; i += 1) { sum += digits[i]; } if (sum === 0) { out = '0'; } } return out; }; // FUNCTIONS ON HEX VALUES /** function to generate a promise that resolves to a string of hex @param {int} bytes - the number of bytes of hex that should be returned */ export const rndHex = bytes => { const buf = crypto.randomBytes(bytes); return `0x${buf.toString('hex')}`; }; /** utility function to remove a leading 0x on a string representing a hex number. If no 0x is present then it returns the string un-altered. */ export const strip0x = (hex): string => { if (typeof hex === 'undefined') { return ''; } if (typeof hex === 'string' && hex.indexOf('0x') === 0) { return hex.slice(2).toString(); } return hex.toString(); }; /** utility function to check that a string has a leading 0x (which the Solidity compiler uses to check for a hex string). It adds it if it's not present. If it is present then it returns the string unaltered */ export const ensure0x = (hex = ''): string => { const hexString = hex.toString(); if (typeof hexString === 'string' && hexString.indexOf('0x') !== 0) { return `0x${hexString}`; } return hexString; }; export const isHex = value => { const regexp = /^[0-9a-fA-F]+$/; return regexp.test(strip0x(value)); }; export const requireHex = (value): void => { if (isHex(value) === false) { throw new Error('value is not hex'); } }; /** * Utility function to convert a string into a hex representation of fixed length. * * @param {string} str - the string to be converted * @param {int} outLength - the length of the output hex string in bytes * * If the string is too short to fill the output hex string, it is padded on the left with 0s. * If the string is too long, an error is thrown. */ export const utf8ToHex = (str, outLengthBytes): string => { const outLength = outLengthBytes * 2; // work in characters rather than bytes const buf = Buffer.from(str, 'utf8'); let hex = buf.toString('hex'); if (outLength < hex.length) { throw new Error('String is to long, try increasing the length of the output hex'); } hex = hex.padStart(outLength, '00'); return ensure0x(hex); }; export const hexToUtf8 = (hex): string => { const cleanHex = strip0x(hex).replace(/00/g, ''); const buf = Buffer.from(cleanHex, 'hex'); return buf.toString('utf8'); }; /** * Utility function to convert a string into a hex representation of fixed length. * * @param {string} str - the string to be converted * @param {int} outLength - the length of the output hex string in bytes * * If the string is too short to fill the output hex string, it is padded on the left with 0s. * If the string is too long, an error is thrown. */ export const asciiToHex = (str, outLengthBytes): string => { const outLength = outLengthBytes * 2; // work in characters rather than bytes const buf = Buffer.from(str, 'ascii'); let hex = buf.toString('hex'); if (outLength < hex.length) { throw new Error('String is to long, try increasing the length of the output hex'); } hex = hex.padStart(outLength, '00'); return ensure0x(hex); }; export const hexToAscii = (hex): string => { const cleanHex = strip0x(hex).replace(/00/g, ''); const buf = Buffer.from(cleanHex, 'hex'); return buf.toString('ascii'); }; /** Converts hex strings into binary, so that they can be passed into merkle-proof.code for example (0xff -> [1,1,1,1,1,1,1,1]) */ export const hexToBinaryArray = (hex): number[] => { return hexToBinaryUtil(strip0x(hex)).split(''); }; // the hexToBinaryUtil library was giving some funny values with 'undefined' elements // within the binary string. Using convertBase seems to be working nicely. THe 'Simple' // suffix is to distinguish from hexToBinaryArray, which outputs an array of bit elements. export const hexToBinary = hex => { const bin = convertBase(strip0x(hex), 16, 2); return bin; }; /** Converts hex strings into byte (decimal) values. This is so that they can be passed into merkle-proof.code in a more compressed fromat than bits. Each byte is invididually converted so 0xffff becomes [15,15] */ export const hexToBytes = (hex): string[] => { const cleanHex = strip0x(hex); const out: string[] = []; for (let i = 0; i < cleanHex.length; i += 2) { const h = ensure0x(cleanHex[i] + cleanHex[i + 1]); out.push(parseInt(h, 10).toString()); } return out; }; // Converts hex strings to decimal values export const hexToDec = (hexStr): string | null => { if (hexStr.substring(0, 2) === '0x') { return convertBase(hexStr.substring(2).toLowerCase(), 16, 10); } return convertBase(hexStr.toLowerCase(), 16, 10); }; /** converts a hex string to an element of a Finite Field GF(fieldSize) (note, decimal representation is used for all field elements) @param {string} hexStr A hex string. @param {integer} fieldSize The number of elements in the finite field. @return {string} A Field Value (decimal value) (formatted as string, because they're very large) */ export const hexToField = (hexStr, fieldSize): string => { const cleanHexStr = strip0x(hexStr); const decStr = hexToDec(cleanHexStr) as string; const q = BI(fieldSize); return BI(decStr).mod(q).toString(); }; /** Left-pads the input hex string with zeros, so that it becomes of size N octets. @param {string} hexStr A hex number/string. @param {integer} N The string length (i.e. the number of octets). @return A hex string (padded) to size N octets, (plus 0x at the start). */ export const leftPadHex = (hexStr, n): string => { return ensure0x(strip0x(hexStr).padStart(n, '0')); }; // function to pad out a Hex value with leading zeros to l bits total length, // preserving the '0x' at the start export const padHex = (A, l) => { if (l % 8 !== 0) { throw new Error('cannot convert bits into a whole number of bytes'); } return ensure0x(strip0x(A).padStart(l / 4, '0')); }; /** Used by splitAndPadBitsN function. Left-pads the input binary string with zeros, so that it becomes of size N bits. @param {string} bitStr A binary number/string. @param {integer} N The 'chunk size'. @return A binary string (padded) to size N bits. */ export const leftPadBits = (bitStr, n): string => { const len = bitStr.length; if (len > n) { throw new Error(`String larger than ${n} bits passed to leftPadBitsN`); } if (len === n) { return bitStr; } return bitStr.padStart(n, '0'); }; /** * Used by split'X'ToBitsN functions. * Checks whether a binary number is larger than N bits, and splits its binary representation into chunks * of size = N bits. The left-most (big endian) chunk will be the only chunk of size <= N bits. If the * inequality is strict, it left-pads this left-most chunk with zeros. * * @param {string} bitStr A binary number/string. * @param {integer} N The 'chunk size'. * @return An array whose elements are binary 'chunks' which altogether represent the input binary number. */ export const splitAndPadBits = (bitStr, n): string[] => { let a: string[] = []; const len = bitStr.length; if (len <= n) { return [leftPadBits(bitStr, n)]; } const nStr = bitStr.slice(-n); // the rightmost N bits const remainderStr = bitStr.slice(0, len - n); // the remaining rightmost bits a = [...splitAndPadBits(remainderStr, n), nStr, ...a]; return a; }; /** * Checks whether a hex number is larger than N bits, and splits its binary representation into chunks * of size = N bits. The left-most (big endian) chunk will be the only chunk of size <= N bits. If the * inequality is strict, it left-pads this left-most chunk with zeros. * * @param {string} hexStr A hex number/string. * @param {integer} N The 'chunk size'. * @return An array whose elements are binary 'chunks' which altogether represent the input hex number. */ export const splitHexToBits = (hexStr, n): string[] => { const strippedHexStr = strip0x(hexStr); const bitStr = hexToBinary(strippedHexStr.toString()); let a: string[] = []; a = splitAndPadBits(bitStr, n); return a; }; // Converts binary value strings to decimal values export const binToDec = (binStr): string | null => { const dec = convertBase(binStr, 2, 10); return dec; }; // Converts binary value strings to hex values export const binToHex = (binStr): string => { const hex = ensure0x(convertBase(binStr, 2, 16) as string); return hex; }; // Converts binary value strings to hex values export const decToHex = (decStr): string => { const hex = ensure0x(convertBase(decStr, 10, 16) as string); return hex; }; // Converts decimal value strings to binary values export const decToBin = (decStr): string => { return convertBase(decStr, 10, 2) as string; }; /** * Preserves the magnitude of a hex number in a finite field, even if the order of the field is smaller * than hexStr. hexStr is converted to decimal (as fields work in decimal integer representation) and * then split into limbs of length limbBitLength. Relies on a sensible limbBitLength being provided. * * If the result has fewer limbs than it would need for compatibiity with the dsl, it's padded to the left with '0' limbs. */ export const hexToFieldLimbs = (hexStr, limbBitLength, numberOfLimbs, silenceWarnings): string[] => { requireHex(hexStr); // we first convert to binary, so that we can split into limbs of specific bit-lengths: let bitsArr: string[] = []; bitsArr = splitHexToBits(hexStr, limbBitLength.toString()); // then we convert each limb into a decimal: let decArr: string[] = []; // decimal array decArr = bitsArr.map(item => binToDec(item.toString()) as string); // fit the output array to the desired numberOfLimbs: if (numberOfLimbs !== undefined) { if (numberOfLimbs < decArr.length) { const overflow = decArr.length - numberOfLimbs; if (!silenceWarnings) { throw new Error( `Field split into an array of ${decArr.length} limbs: ${decArr} , but this exceeds the requested number of limbs of ${numberOfLimbs}. Data would have been lost; possibly unexpectedly. To silence this warning, pass '1' or 'true' as the final parameter.`, ); } // remove extra limbs (dangerous!): for (let i = 0; i < overflow; i += 1) { decArr.shift(); } } else { const missing = numberOfLimbs - decArr.length; // if the number of limbs required is greater than the number so-far created, prefix any missing limbs to the array as '0' elements. for (let i = 0; i < missing; i += 1) { decArr.unshift('0'); } } } return decArr; }; // UTILITY FUNCTIONS: /* flattenDeep converts a nested array into a flattened array. We use this to pass our proofs and vks into the verifier contract. Example: A vk of the form: [ [ [ '1','2' ], [ '3','4' ] ], [ '5','6' ], [ [ '7','8' ], [ '9','10' ] ], [ [ '11','12' ], [ '13','14' ] ], [ '15','16' ], [ [ '17','18' ], [ '19','20' ] ], [ [ '21','22' ], [ '23','24' ] ], [ [ '25','26' ], [ '27','28' ], [ '29','30' ], [ '31','32' ] ] ] is converted to: ['1','2','3','4','5','6',...] */ export const flattenDeep = (arr) => { return arr.reduce( (acc, val) => (Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val)), [], ); }; export default { ensure0x, strip0x, rndHex, isHex, requireHex, utf8ToHex, hexToUtf8, asciiToHex, hexToAscii, hexToBinaryArray, hexToBinary, hexToBytes, hexToDec, hexToField, hexToFieldLimbs, binToDec, binToHex, decToHex, decToBin, add, parseToDigitsArray, convertBase, splitHexToBits, splitAndPadBits, leftPadBits, padHex, leftPadHex, flattenDeep, };
the_stack
import * as path from "path"; import * as fs from "fs-extra"; import { getCacheData, getFileMd5, writeCacheData, writeOrDeleteOutPutFiles } from "./file-utils"; import { Logger } from "./loger"; import { DefaultConvertHook } from "./default-convert-hook"; import fg from "fast-glob"; const defaultDir = ".excel2all"; const cacheFileName = ".e2aprmc"; const logFileName = "excel2all.log"; let startTime = 0; const defaultPattern = ["./**/*.xlsx", "./**/*.csv"]; const needIgnorePattern = ["!**/~$*.*", "!**/~.*.*", "!.git/**/*", "!.svn/**/*"]; /** * 转换 * @param converConfig 解析配置 */ export async function convert(converConfig: ITableConvertConfig) { //开始时间 startTime = new Date().getTime(); if (!converConfig.projRoot) { converConfig.projRoot = process.cwd(); } Logger.init(converConfig); const tableFileDir = converConfig.tableFileDir; if (!tableFileDir) { Logger.log(`配置表目录:tableFileDir为空`, "error"); return; } if (!fs.existsSync(tableFileDir)) { Logger.log(`配置表文件夹不存在:${tableFileDir}`, "error"); return; } if (!converConfig.pattern) { converConfig.pattern = defaultPattern; } converConfig.pattern = converConfig.pattern.concat(needIgnorePattern); let convertHook = new DefaultConvertHook(); const context: IConvertContext = { convertConfig: converConfig, utils: { fs: require("fs-extra"), xlsx: require("xlsx") } }; const customConvertHook = converConfig.customConvertHook; //开始 await new Promise<void>((res) => { customConvertHook && customConvertHook.onStart ? customConvertHook.onStart(context, res) : convertHook.onStart(context, res); }); const predoT1 = new Date().getTime(); getFileInfos(context); const { parseResultMapCacheFilePath, changedFileInfos } = context; const predoT2 = new Date().getTime(); Logger.systemLog(`[预处理数据时间:${predoT2 - predoT1}ms,${(predoT2 - predoT1) / 1000}]`); await new Promise<void>((res) => { customConvertHook && customConvertHook.onParseBefore ? customConvertHook.onParseBefore(context, res) : convertHook.onParseBefore(context, res); }); Logger.systemLog(`[开始解析]:数量[${changedFileInfos.length}]`); Logger.systemLog(`[解析]`); if (changedFileInfos.length > 0) { const t1 = new Date().getTime(); await new Promise<void>((res) => { customConvertHook && customConvertHook.onParse ? customConvertHook.onParse(context, res) : convertHook.onParse(context, res); }); const t2 = new Date().getTime(); Logger.systemLog(`[解析时间]:${t2 - t1}`); } onParseEnd(context, parseResultMapCacheFilePath, customConvertHook, convertHook); } /** * 解析结束 * @param parseConfig * @param parseResultMapCacheFilePath * @param convertHook * @param fileInfos * @param deleteFileInfos * @param parseResultMap * @param logStr */ async function onParseEnd( context: IConvertContext, parseResultMapCacheFilePath: string, customConvertHook: IConvertHook, convertHook: IConvertHook, logStr?: string ) { const convertConfig = context.convertConfig; //写入解析缓存 if (convertConfig.useCache) { writeCacheData(parseResultMapCacheFilePath, context.cacheData); } //解析结束,做导出处理 Logger.systemLog(`开始进行转换解析结果`); const parseAfterT1 = new Date().getTime(); await new Promise<void>((res) => { customConvertHook && customConvertHook.onParseAfter ? customConvertHook.onParseAfter(context, res) : convertHook.onParseAfter(context, res); }); const parseAfterT2 = new Date().getTime(); Logger.systemLog(`转换解析结果结束:${parseAfterT2 - parseAfterT1}ms,${(parseAfterT2 - parseAfterT1) / 1000}s`); if (context.outPutFileMap) { const outputFileMap = context.outPutFileMap; const outputFiles = Object.values(outputFileMap); //写入和删除文件处理 Logger.systemLog(`开始写入文件:0/${outputFiles.length}`); await new Promise<void>((res) => { writeOrDeleteOutPutFiles( outputFiles, (filePath, total, now, isOk) => { Logger.log(`[写入文件] 进度:(${now}/${total}) 路径:${filePath}`); }, () => { res(); } ); }); Logger.systemLog(`写入结束~`); } else { Logger.systemLog(`没有可写入文件~`); } //写入日志文件 if (!logStr) { logStr = Logger.logStr; } if (logStr.trim() !== "") { let logFileDirPath = context.convertConfig.outputLogDirPath as string; if (!logFileDirPath) logFileDirPath = defaultDir; if (!path.isAbsolute(logFileDirPath)) { logFileDirPath = path.join(context.convertConfig.projRoot, logFileDirPath); } const outputLogFileInfo: IOutPutFileInfo = { filePath: path.join(logFileDirPath, logFileName), data: logStr }; writeOrDeleteOutPutFiles([outputLogFileInfo]); } //写入结束 customConvertHook && customConvertHook.onConvertEnd ? customConvertHook.onConvertEnd(context) : convertHook.onConvertEnd(context); //结束时间 const endTime = new Date().getTime(); const useTime = endTime - startTime; Logger.log(`导表总时间:[${useTime}ms],[${useTime / 1000}s]`); } /** * 测试文件匹配 * @param convertConfig */ export function testFileMatch(convertConfig: ITableConvertConfig) { if (!convertConfig.projRoot) { convertConfig.projRoot = process.cwd(); } const tableFileDir = convertConfig.tableFileDir; if (!tableFileDir) { Logger.log(`配置表目录:tableFileDir为空`, "error"); return; } if (!fs.existsSync(tableFileDir)) { Logger.log(`配置表文件夹不存在:${tableFileDir}`, "error"); return; } if (!convertConfig.pattern) { convertConfig.pattern = defaultPattern; } const context: IConvertContext = { convertConfig: convertConfig } as any; let t1 = new Date().getTime(); getFileInfos(context); let t2 = new Date().getTime(); console.log(`执行时间:${(t2 - t1) / 1000}s`); if (convertConfig.useCache) { console.log(`----【缓存模式】----`); } console.log(`------------------------------匹配到的文件---------------------`); const filePaths = context.changedFileInfos.map((value) => { return value.filePath; }); console.log(filePaths); } /** * 使用fast-glob作为文件遍历 * 获取需要解析的文件信息 * @param context */ function getFileInfos(context: IConvertContext) { const converConfig = context.convertConfig; let changedFileInfos: IFileInfo[] = []; let deleteFileInfos: IFileInfo[] = []; const tableFileDir = converConfig.tableFileDir; const getFileInfo = (filePath: string, isDelete?: boolean) => { const filePathParse = path.parse(filePath); let fileData = !isDelete ? fs.readFileSync(filePath) : undefined; const fileInfo: IFileInfo = { filePath: filePath, fileName: filePathParse.name, fileExtName: filePathParse.ext, isDelete: isDelete, fileData: fileData }; return fileInfo; }; const matchPattern = converConfig.pattern; const filePaths: string[] = fg.sync(matchPattern, { absolute: true, onlyFiles: true, caseSensitiveMatch: false, cwd: tableFileDir }); let parseResultMap: TableParseResultMap = {}; let cacheData: ITableConvertCacheData; //缓存处理 let cacheFileDirPath: string = converConfig.cacheFileDirPath; let parseResultMapCacheFilePath: string; let fileInfo: IFileInfo; if (!converConfig.useCache) { for (let i = 0; i < filePaths.length; i++) { fileInfo = getFileInfo(filePaths[i]); changedFileInfos.push(fileInfo); } } else { let t1 = new Date().getTime(); if (!cacheFileDirPath) cacheFileDirPath = defaultDir; if (!path.isAbsolute(cacheFileDirPath)) { cacheFileDirPath = path.join(converConfig.projRoot, cacheFileDirPath); } parseResultMapCacheFilePath = path.join(cacheFileDirPath, cacheFileName); Logger.systemLog(`读取缓存数据`); cacheData = getCacheData(parseResultMapCacheFilePath); console.log(__dirname); const packageJson = getCacheData(path.join(__dirname, "../../../package.json")); if (!cacheData.version || cacheData.version !== packageJson.version) { Logger.systemLog( `工具版本不一致,缓存失效 => cacheVersion:${cacheData.version},toolVersion:${packageJson.version}` ); parseResultMap = {}; } else { parseResultMap = cacheData.parseResultMap; } if (!parseResultMap) { parseResultMap = {}; } cacheData.parseResultMap = parseResultMap; cacheData.version = packageJson.version; Logger.systemLog(`开始缓存处理...`); const oldFilePaths = Object.keys(parseResultMap); let oldFilePathIndex: number; let parseResult: ITableParseResult; let filePath: string; for (let i = 0; i < filePaths.length; i++) { filePath = filePaths[i]; fileInfo = getFileInfo(filePath); const fileData = fileInfo.fileData; parseResult = parseResultMap[filePath]; var md5str = getFileMd5(fileData); if (!parseResult || (parseResult && (parseResult.hasError || parseResult.md5hash !== md5str))) { parseResult = { filePath: filePath }; parseResultMap[filePath] = parseResult; parseResult.md5hash = md5str; changedFileInfos.push(fileInfo); } //判断文件是否还存在 oldFilePathIndex = oldFilePaths.indexOf(filePath); if (oldFilePathIndex > -1) { const endFilePath = oldFilePaths[oldFilePaths.length - 1]; oldFilePaths[oldFilePathIndex] = endFilePath; oldFilePaths.pop(); } } //删除旧文件 for (let i = 0; i < oldFilePaths.length; i++) { delete parseResultMap[oldFilePaths[i]]; let deleteFileInfo = getFileInfo(oldFilePaths[i], true); deleteFileInfos.push(deleteFileInfo); } let t2 = new Date().getTime(); Logger.systemLog(`缓存处理时间:${t2 - t1}ms,${(t2 - t1) / 1000}s`); } context.deleteFileInfos = deleteFileInfos; context.changedFileInfos = changedFileInfos; context.parseResultMap = parseResultMap; context.cacheData = cacheData; context.parseResultMapCacheFilePath = parseResultMapCacheFilePath; }
the_stack
'use strict'; import {IDisposable} from 'vs/base/common/lifecycle'; import {TPromise} from 'vs/base/common/winjs.base'; import * as modes from 'vs/editor/common/modes'; import {LineStream} from 'vs/editor/common/modes/lineStream'; import {NullMode, NullState, nullTokenize} from 'vs/editor/common/modes/nullMode'; import {Token} from 'vs/editor/common/core/token'; import {ModeTransition} from 'vs/editor/common/core/modeTransition'; export interface ILeavingNestedModeData { /** * The part of the line that will be tokenized by the nested mode */ nestedModeBuffer: string; /** * The part of the line that will be tokenized by the parent mode when it continues after the nested mode */ bufferAfterNestedMode: string; /** * The state that will be used for continuing tokenization by the parent mode after the nested mode */ stateAfterNestedMode: modes.IState; } export interface IEnteringNestedModeData { mode:modes.IMode; missingModePromise:TPromise<void>; } export interface ITokenizationCustomization { getInitialState():modes.IState; enterNestedMode?: (state:modes.IState) => boolean; getNestedMode?: (state:modes.IState) => IEnteringNestedModeData; getNestedModeInitialState?: (myState:modes.IState) => { state:modes.IState; missingModePromise:TPromise<void>; }; /** * Return null if the line does not leave the nested mode */ getLeavingNestedModeData?: (line:string, state:modes.IState) => ILeavingNestedModeData; /** * Callback for when leaving a nested mode and returning to the outer mode. * @param myStateAfterNestedMode The outer mode's state that will begin to tokenize * @param lastNestedModeState The nested mode's last state */ onReturningFromNestedMode?: (myStateAfterNestedMode:modes.IState, lastNestedModeState:modes.IState)=> void; } function isFunction(something) { return typeof something === 'function'; } export class TokenizationSupport implements modes.ITokenizationSupport, IDisposable { static MAX_EMBEDDED_LEVELS = 5; private customization:ITokenizationCustomization; private defaults: { enterNestedMode: boolean; getNestedMode: boolean; getNestedModeInitialState: boolean; getLeavingNestedModeData: boolean; onReturningFromNestedMode: boolean; }; public supportsNestedModes:boolean; private _mode:modes.IMode; private _modeId:string; private _embeddedModesListeners: { [modeId:string]: IDisposable; }; constructor(mode:modes.IMode, customization:ITokenizationCustomization, supportsNestedModes:boolean) { this._mode = mode; this._modeId = this._mode.getId(); this.customization = customization; this.supportsNestedModes = supportsNestedModes; this._embeddedModesListeners = {}; if (this.supportsNestedModes) { if (!this._mode.setTokenizationSupport) { throw new Error('Cannot be a mode with nested modes unless I can emit a tokenizationSupport changed event!'); } } this.defaults = { enterNestedMode: !isFunction(customization.enterNestedMode), getNestedMode: !isFunction(customization.getNestedMode), getNestedModeInitialState: !isFunction(customization.getNestedModeInitialState), getLeavingNestedModeData: !isFunction(customization.getLeavingNestedModeData), onReturningFromNestedMode: !isFunction(customization.onReturningFromNestedMode) }; } public dispose() : void { for (let listener in this._embeddedModesListeners) { this._embeddedModesListeners[listener].dispose(); delete this._embeddedModesListeners[listener]; } } public getInitialState(): modes.IState { return this.customization.getInitialState(); } public tokenize(line:string, state:modes.IState, deltaOffset:number = 0, stopAtOffset:number = deltaOffset + line.length):modes.ILineTokens { if (state.getMode() !== this._mode) { return this._nestedTokenize(line, state, deltaOffset, stopAtOffset, [], []); } else { return this._myTokenize(line, state, deltaOffset, stopAtOffset, [], []); } } /** * Precondition is: nestedModeState.getMode() !== this * This means we are in a nested mode when parsing starts on this line. */ private _nestedTokenize(buffer:string, nestedModeState:modes.IState, deltaOffset:number, stopAtOffset:number, prependTokens:Token[], prependModeTransitions:ModeTransition[]):modes.ILineTokens { let myStateBeforeNestedMode = nestedModeState.getStateData(); let leavingNestedModeData = this.getLeavingNestedModeData(buffer, myStateBeforeNestedMode); // Be sure to give every embedded mode the // opportunity to leave nested mode. // i.e. Don't go straight to the most nested mode let stepOnceNestedState = nestedModeState; while (stepOnceNestedState.getStateData() && stepOnceNestedState.getStateData().getMode() !== this._mode) { stepOnceNestedState = stepOnceNestedState.getStateData(); } let nestedMode = stepOnceNestedState.getMode(); if (!leavingNestedModeData) { // tokenization will not leave nested mode let result:modes.ILineTokens; if (nestedMode.tokenizationSupport) { result = nestedMode.tokenizationSupport.tokenize(buffer, nestedModeState, deltaOffset, stopAtOffset); } else { // The nested mode doesn't have tokenization support, // unfortunatelly this means we have to fake it result = nullTokenize(nestedMode.getId(), buffer, nestedModeState, deltaOffset); } result.tokens = prependTokens.concat(result.tokens); result.modeTransitions = prependModeTransitions.concat(result.modeTransitions); return result; } let nestedModeBuffer = leavingNestedModeData.nestedModeBuffer; if (nestedModeBuffer.length > 0) { // Tokenize with the nested mode let nestedModeLineTokens:modes.ILineTokens; if (nestedMode.tokenizationSupport) { nestedModeLineTokens = nestedMode.tokenizationSupport.tokenize(nestedModeBuffer, nestedModeState, deltaOffset, stopAtOffset); } else { // The nested mode doesn't have tokenization support, // unfortunatelly this means we have to fake it nestedModeLineTokens = nullTokenize(nestedMode.getId(), nestedModeBuffer, nestedModeState, deltaOffset); } // Save last state of nested mode nestedModeState = nestedModeLineTokens.endState; // Prepend nested mode's result to our result prependTokens = prependTokens.concat(nestedModeLineTokens.tokens); prependModeTransitions = prependModeTransitions.concat(nestedModeLineTokens.modeTransitions); } let bufferAfterNestedMode = leavingNestedModeData.bufferAfterNestedMode; let myStateAfterNestedMode = leavingNestedModeData.stateAfterNestedMode; myStateAfterNestedMode.setStateData(myStateBeforeNestedMode.getStateData()); this.onReturningFromNestedMode(myStateAfterNestedMode, nestedModeState); return this._myTokenize(bufferAfterNestedMode, myStateAfterNestedMode, deltaOffset + nestedModeBuffer.length, stopAtOffset, prependTokens, prependModeTransitions); } /** * Precondition is: state.getMode() === this * This means we are in the current mode when parsing starts on this line. */ private _myTokenize(buffer:string, myState:modes.IState, deltaOffset:number, stopAtOffset:number, prependTokens:Token[], prependModeTransitions:ModeTransition[]):modes.ILineTokens { let lineStream = new LineStream(buffer); let tokenResult:modes.ITokenizationResult, beforeTokenizeStreamPos:number; let previousType:string = null; let retokenize:TPromise<void> = null; myState = myState.clone(); if (prependModeTransitions.length <= 0 || prependModeTransitions[prependModeTransitions.length-1].modeId !== this._modeId) { // Avoid transitioning to the same mode (this can happen in case of empty embedded modes) prependModeTransitions.push(new ModeTransition(deltaOffset,this._modeId)); } let maxPos = Math.min(stopAtOffset - deltaOffset, buffer.length); while (lineStream.pos() < maxPos) { beforeTokenizeStreamPos = lineStream.pos(); do { tokenResult = myState.tokenize(lineStream); if (tokenResult === null || tokenResult === undefined || ((tokenResult.type === undefined || tokenResult.type === null) && (tokenResult.nextState === undefined || tokenResult.nextState === null))) { throw new Error('Tokenizer must return a valid state'); } if (tokenResult.nextState) { tokenResult.nextState.setStateData(myState.getStateData()); myState = tokenResult.nextState; } if (lineStream.pos() <= beforeTokenizeStreamPos) { throw new Error('Stream did not advance while tokenizing. Mode id is ' + this._modeId + ' (stuck at token type: "' + tokenResult.type + '", prepend tokens: "' + (prependTokens.map(t => t.type).join(',')) + '").'); } } while (!tokenResult.type && tokenResult.type !== ''); if (previousType !== tokenResult.type || tokenResult.dontMergeWithPrev || previousType === null) { prependTokens.push(new Token(beforeTokenizeStreamPos + deltaOffset, tokenResult.type)); } previousType = tokenResult.type; if (this.supportsNestedModes && this.enterNestedMode(myState)) { let currentEmbeddedLevels = this._getEmbeddedLevel(myState); if (currentEmbeddedLevels < TokenizationSupport.MAX_EMBEDDED_LEVELS) { let nestedModeState = this.getNestedModeInitialState(myState); // Re-emit tokenizationSupport change events from all modes that I ever embedded let embeddedMode = nestedModeState.state.getMode(); if (typeof embeddedMode.addSupportChangedListener === 'function' && !this._embeddedModesListeners.hasOwnProperty(embeddedMode.getId())) { let emitting = false; this._embeddedModesListeners[embeddedMode.getId()] = embeddedMode.addSupportChangedListener((e) => { if (emitting) { return; } if (e.tokenizationSupport) { emitting = true; this._mode.setTokenizationSupport((mode) => { return mode.tokenizationSupport; }); emitting = false; } }); } if (!lineStream.eos()) { // There is content from the embedded mode let restOfBuffer = buffer.substr(lineStream.pos()); let result = this._nestedTokenize(restOfBuffer, nestedModeState.state, deltaOffset + lineStream.pos(), stopAtOffset, prependTokens, prependModeTransitions); result.retokenize = result.retokenize || nestedModeState.missingModePromise; return result; } else { // Transition to the nested mode state myState = nestedModeState.state; retokenize = nestedModeState.missingModePromise; } } } } return { tokens: prependTokens, actualStopOffset: lineStream.pos() + deltaOffset, modeTransitions: prependModeTransitions, endState: myState, retokenize: retokenize }; } private _getEmbeddedLevel(state:modes.IState): number { let result = -1; while(state) { result++; state = state.getStateData(); } return result; } private enterNestedMode(state:modes.IState): boolean { if (this.defaults.enterNestedMode) { return false; } return this.customization.enterNestedMode(state); } private getNestedMode(state:modes.IState): IEnteringNestedModeData { if (this.defaults.getNestedMode) { return null; } return this.customization.getNestedMode(state); } private static _validatedNestedMode(input:IEnteringNestedModeData): IEnteringNestedModeData { let mode: modes.IMode = new NullMode(), missingModePromise: TPromise<void> = null; if (input && input.mode) { mode = input.mode; } if (input && input.missingModePromise) { missingModePromise = input.missingModePromise; } return { mode: mode, missingModePromise: missingModePromise }; } private getNestedModeInitialState(state:modes.IState): { state:modes.IState; missingModePromise:TPromise<void>; } { if (this.defaults.getNestedModeInitialState) { let nestedMode = TokenizationSupport._validatedNestedMode(this.getNestedMode(state)); let missingModePromise = nestedMode.missingModePromise; let nestedModeState: modes.IState; if (nestedMode.mode.tokenizationSupport) { nestedModeState = nestedMode.mode.tokenizationSupport.getInitialState(); } else { nestedModeState = new NullState(nestedMode.mode, null); } nestedModeState.setStateData(state); return { state: nestedModeState, missingModePromise: missingModePromise }; } return this.customization.getNestedModeInitialState(state); } private getLeavingNestedModeData(line:string, state:modes.IState): ILeavingNestedModeData { if (this.defaults.getLeavingNestedModeData) { return null; } return this.customization.getLeavingNestedModeData(line, state); } private onReturningFromNestedMode(myStateAfterNestedMode:modes.IState, lastNestedModeState:modes.IState): void { if (this.defaults.onReturningFromNestedMode) { return null; } return this.customization.onReturningFromNestedMode(myStateAfterNestedMode, lastNestedModeState); } }
the_stack
import { ByteArray } from './byte-array'; import { PdfStream } from './../../primitives/pdf-stream'; import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties'; import { PdfName } from './../../primitives/pdf-name'; import { PdfNumber } from './../../primitives/pdf-number'; import { PdfBoolean } from './../../primitives/pdf-boolean'; import { PdfDictionary } from './../../primitives/pdf-dictionary'; /** * Specifies the image `format`. * @private */ export enum ImageFormat { /** * Specifies the type of `Unknown`. * @hidden * @private */ Unknown, /** * Specifies the type of `Bmp`. * @hidden * @private */ Bmp, /** * Specifies the type of `Emf`. * @hidden * @private */ Emf, /** * Specifies the type of `Gif`. * @hidden * @private */ Gif, /** * Specifies the type of `Jpeg`. * @hidden * @private */ Jpeg, /** * Specifies the type of `Png`. * @hidden * @private */ Png, /** * Specifies the type of `Wmf`. * @hidden * @private */ Wmf, /** * Specifies the type of `Icon`. * @hidden * @private */ Icon } /** * `Decode the image stream`. * @private */ export class ImageDecoder { /** * Start of file markers. * @hidden * @private */ private sof1Marker : number = 0x00C1; private sof2Marker : number = 0x00C2; private sof3Marker : number = 0x00C3; private sof5Marker : number = 0x00C5; private sof6Marker : number = 0x00C6; private sof7Marker : number = 0x00C7; private sof9Marker : number = 0x00C9; private sof10Marker : number = 0x00CA; private sof11Marker : number = 0x00CB; private sof13Marker : number = 0x00CD; private sof14Marker : number = 0x00CE; private sof15Marker : number = 0x00CF; /** * Number array for `png header`. * @hidden * @private */ private static mPngHeader: number[] = [137, 80, 78, 71, 13, 10, 26, 10]; /** * Number Array for `jpeg header`. * @hidden * @private */ private static mJpegHeader: number[] = [255, 216]; /** * Number array for `gif header`. * @hidden * @private */ private static GIF_HEADER: string = 'G,I,F,8'; /** * Number array for `bmp header.` * @hidden * @private */ private static BMP_HEADER: string = 'B,M'; /** * `memory stream` to store image data. * @hidden * @private */ private mStream: ByteArray; /** * Specifies `format` of image. * @hidden * @private */ private mFormat: ImageFormat = ImageFormat.Unknown; /** * `height` of image. * @hidden * @private */ private mHeight: number; /** * `width` of image. * @hidden * @private */ private mWidth: number; /** * `Bits per component`. * @default 8 * @hidden * @private */ private mbitsPerComponent : number = 8; /** * ByteArray to store `image data`. * @hidden * @private */ private mImageData: ByteArray; /** * Store an instance of `PdfStream` for an image. * @hidden * @private */ private imageStream : PdfStream; /** * 'offset' of image. * @hidden * @private */ private offset : number; /** * Internal variable for accessing fields from `DictionryProperties` class. * @hidden * @private */ private dictionaryProperties : DictionaryProperties = new DictionaryProperties(); /** * Initialize the new instance for `image-decoder` class. * @private */ public constructor(stream: ByteArray) { this.mStream = stream; this.initialize(); } /** * Gets the `height` of image. * @hidden * @private */ public get height(): number { return this.mHeight; } /** * Gets the `width` of image. * @hidden * @private */ public get width(): number { return this.mWidth; } /** * Gets `bits per component`. * @hidden * @private */ public get bitsPerComponent() : number { return this.mbitsPerComponent; } /** * Gets the `size` of an image data. * @hidden * @private */ public get size(): number { return this.mImageData.count; } /** * Gets the value of an `image data`. * @hidden * @private */ public get imageData(): ByteArray { return this.mImageData; } /** * Gets the value of an `image data as number array`. * @hidden * @private */ public get imageDataAsNumberArray() : ArrayBuffer { return this.mImageData.internalBuffer.buffer; } /** * `Initialize` image data and image stream. * @hidden * @private */ private initialize(): void { if (this.mFormat === ImageFormat.Unknown && this.checkIfJpeg()) { this.mFormat = ImageFormat.Jpeg; this.parseJpegImage(); } this.reset(); this.mImageData = new ByteArray(this.mStream.count); this.mStream.read(this.mImageData, 0, this.mImageData.count); } /** * `Reset` stream position into 0. * @hidden * @private */ private reset(): void { this.mStream.position = 0; } /** * `Parse` Jpeg image. * @hidden * @private */ private parseJpegImage(): void { this.reset(); let imgData: ByteArray = new ByteArray(this.mStream.count); this.mStream.read(imgData, 0, imgData.count); let i: number = 4; let isLengthExceed : boolean = false; /* tslint:disable */ let length: number = imgData.getBuffer(i) * 256 + imgData.getBuffer(i + 1); while (i < imgData.count) { i += length; if (i < imgData.count) { if (imgData.getBuffer(i + 1) === 192) { this.mHeight = imgData.getBuffer(i + 5) * 256 + imgData.getBuffer(i + 6); this.mWidth = imgData.getBuffer(i + 7) * 256 + imgData.getBuffer(i + 8); return; } else { i += 2; length = imgData.getBuffer(i) * 256 + imgData.getBuffer(i + 1); } } else { isLengthExceed = true; break; } } if (isLengthExceed) { this.mStream.position = 0; this.skip(this.mStream, 2); this.readExceededJPGImage(this.mStream); } /* tslint:enable */ } /** * Gets the image `format`. * @private * @hidden */ public get format(): ImageFormat { return this.mFormat; } /** * `Checks if JPG`. * @private * @hidden */ private checkIfJpeg(): boolean { this.reset(); for (let i: number = 0; i < ImageDecoder.mJpegHeader.length; i++) { if (ImageDecoder.mJpegHeader[i] !== this.mStream.readByte(i)) { return false; } this.mStream.position++; } return true; } /** * Return image `dictionary`. * @hidden * @private */ public getImageDictionary() : PdfStream { if (this.mFormat === ImageFormat.Jpeg) { let tempArrayBuffer : number = this.imageData.internalBuffer.length; this.imageStream = new PdfStream(); this.imageStream.isImage = true; let tempString : string = ''; let decodedString : string = ''; for (let i : number = 0; i < this.imageDataAsNumberArray.byteLength; i++ ) { tempString += String.fromCharCode(null, this.mStream.readByte(i)); } for (let i : number = 0; i < tempString.length; i++) { if (i % 2 !== 0) { decodedString += tempString[i]; } } this.imageStream.data = [decodedString]; this.imageStream.compress = false; this.imageStream.items.setValue(this.dictionaryProperties.type, new PdfName(this.dictionaryProperties.xObject)); this.imageStream.items.setValue(this.dictionaryProperties.subtype, new PdfName(this.dictionaryProperties.image)); this.imageStream.items.setValue(this.dictionaryProperties.width, new PdfNumber(this.width)); this.imageStream.items.setValue(this.dictionaryProperties.height, new PdfNumber(this.height)); this.imageStream.items.setValue(this.dictionaryProperties.bitsPerComponent, new PdfNumber(this.bitsPerComponent)); this.imageStream.items.setValue(this.dictionaryProperties.filter, new PdfName(this.dictionaryProperties.dctdecode)); this.imageStream.items.setValue(this.dictionaryProperties.colorSpace, new PdfName(this.getColorSpace() as string)); this.imageStream.items.setValue(this.dictionaryProperties.decodeParms, this.getDecodeParams()); return this.imageStream; } else { return this.imageStream; } } /** * Return `colorSpace` of an image. * @hidden * @private */ private getColorSpace() : string { return this.dictionaryProperties.deviceRgb; } /** * Return `decode parameters` of an image. * @hidden * @private */ private getDecodeParams() : PdfDictionary { let decodeParams : PdfDictionary = new PdfDictionary(); decodeParams.items.setValue(this.dictionaryProperties.columns, new PdfNumber(this.width)); decodeParams.items.setValue(this.dictionaryProperties.blackIs1, new PdfBoolean(true)); decodeParams.items.setValue(this.dictionaryProperties.k, new PdfNumber(-1)); decodeParams.items.setValue(this.dictionaryProperties.predictor, new PdfNumber(15)); decodeParams.items.setValue(this.dictionaryProperties.bitsPerComponent, new PdfNumber(this.bitsPerComponent)); return decodeParams; } /** * 'readExceededJPGImage' stream * @hidden * @private */ private readExceededJPGImage(stream: ByteArray): void { this.mStream = stream; let isContinueReading : boolean = true; while (isContinueReading) { let marker : number = this.getMarker(stream); switch (marker) { case this.sof1Marker: case this.sof2Marker: case this.sof3Marker: case this.sof5Marker: case this.sof6Marker: case this.sof7Marker: case this.sof9Marker: case this.sof10Marker: case this.sof11Marker: case this.sof13Marker: case this.sof14Marker: case this.sof15Marker: stream.position += 3; this.mHeight = this.mStream.readNextTwoBytes(stream); this.mWidth = this.mStream.readNextTwoBytes(stream); isContinueReading = false; break; default: this.skipStream(stream); break; } } } /** * 'skip' stream * @hidden * @private */ private skip(stream: ByteArray, noOfBytes: number): void { this.mStream = stream; let temp : ByteArray = new ByteArray(noOfBytes); this.mStream.read(temp, 0, temp.count); } /** * 'getMarker' stream * @hidden * @private */ private getMarker(stream: ByteArray): number { let skippedByte : number = 0; let marker : number = 32; marker = stream.readByte(this.mStream.position); stream.position++; while (marker !== 255) { skippedByte++; marker = stream.readByte(this.mStream.position); stream.position++; } do { marker = stream.readByte(this.mStream.position); stream.position++; } while (marker === 255); return marker; } /** * 'skipStream' stream * @hidden * @private */ private skipStream(stream: ByteArray): void { let markerLength : number = this.mStream.readNextTwoBytes(stream) - 2; if (markerLength > 0) { stream.position += markerLength; } } }
the_stack
import * as FileSaver from "file-saver"; import { saveAs } from "file-saver"; import { Prototypes, deepClone, uniqueID } from "../../../core"; import { Actions } from "../../actions"; import { renderDataURLToPNG, stringToDataURL, convertColumns, } from "../../utils"; import { AppStore } from "../app_store"; import { Migrator } from "../migrator"; import { ActionHandlerRegistry } from "./registry"; import { getConfig } from "../../config"; import { ChartTemplateBuilder } from "../../template"; import { NestedEditorEventType, NestedEditorMessage, NestedEditorMessageType, } from "../../application"; /** Handlers for document-level actions such as Load, Save, Import, Export, Undo/Redo, Reset */ // eslint-disable-next-line export default function (REG: ActionHandlerRegistry<AppStore, Actions.Action>) { // eslint-disable-next-line REG.add(Actions.Export, function (action) { (async () => { // Export as vector graphics if (action.type == "svg") { const svg = await this.renderLocalSVG(); const blob = new Blob([svg], { type: "image/svg;charset=utf-8" }); saveAs(blob, "charticulator.svg", true); } // Export as bitmaps if (action.type == "png" || action.type == "jpeg") { const svgDataURL = stringToDataURL( "image/svg+xml", await this.renderLocalSVG() ); renderDataURLToPNG(svgDataURL, { mode: "scale", scale: action.options.scale || 2, background: "#ffffff", }).then((png) => { png.toBlob((blob) => { saveAs( blob, "charticulator." + (action.type == "png" ? "png" : "jpg"), true ); }, "image/" + action.type); }); } // Export as interactive HTML if (action.type == "html") { const containerScriptText = await ( await fetch(getConfig().ContainerURL) ).text(); const template = deepClone(this.buildChartTemplate()); const htmlString = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Charticulator HTML Export</title> <script type="text/javascript">${containerScriptText}</script> <style type="text/css"> #container { display: block; position: absolute; left: 0; right: 0; top: 0; bottom: 0; } </style> </head> <body> <div id="container"></div> <script type="text/javascript"> CharticulatorContainer.initialize().then(function() { const currentChart = ${JSON.stringify(this.chart)}; const chartState = ${JSON.stringify(this.chartState)}; const dataset = ${JSON.stringify(this.dataset)}; const template = ${JSON.stringify(template)}; const chartTemplate = new CharticulatorContainer.ChartTemplate( template ); chartTemplate.reset(); const defaultTable = dataset.tables[0]; const columns = defaultTable.columns; chartTemplate.assignTable(defaultTable.name, defaultTable.name); for (const column of columns) { chartTemplate.assignColumn( defaultTable.name, column.name, column.name ); } // links table const linksTable = dataset.tables[1]; const links = linksTable && (linksTable.columns); if (links) { chartTemplate.assignTable(linksTable.name, linksTable.name); for (const column of links) { chartTemplate.assignColumn( linksTable.name, column.name, column.name ); } } const instance = chartTemplate.instantiate(dataset); const { chart } = instance; for (const property of template.properties) { if (property.target.attribute) { CharticulatorContainer.ChartTemplate.SetChartAttributeMapping( chart, property.objectID, property.target.attribute, { type: "value", value: property.default, } ); } } const container = new CharticulatorContainer.ChartContainer({ chart: chart }, dataset); const width = document.getElementById("container").getBoundingClientRect().width; const height = document.getElementById("container").getBoundingClientRect().height; container.mount("container", width, height); window.addEventListener("resize", function() { container.resize( document.getElementById("container").getBoundingClientRect().width, document.getElementById("container").getBoundingClientRect().height ); }); }); </script> </body> </html> `; const blob = new Blob([htmlString]); saveAs(blob, "charticulator.html", true); } })(); }); REG.add(Actions.ExportTemplate, function (this, action) { action.target.generate(action.properties).then((base64) => { const byteCharacters = atob(base64); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: "application/x-binary", }); FileSaver.saveAs( blob, action.target.getFileName ? action.target.getFileName(action.properties) : "charticulator." + action.target.getFileExtension(action.properties) ); }); }); REG.add(Actions.Save, function (action) { this.backendSaveChart() .then(() => { if (action.onFinish) { action.onFinish(); } }) .catch((error: Error) => { if (action.onFinish) { action.onFinish(error); } }); }); REG.add(Actions.SaveAs, function (action) { this.backendSaveChartAs(action.saveAs) .then(() => { if (action.onFinish) { action.onFinish(); } }) .catch((error: Error) => { if (action.onFinish) { action.onFinish(error); } }); }); REG.add(Actions.Open, function (action) { this.backendOpenChart(action.id) .then(() => { if (action.onFinish) { action.onFinish(); } }) .catch((error: Error) => { if (action.onFinish) { action.onFinish(error); } }); }); REG.add(Actions.Load, function (action) { this.historyManager.clear(); const state = new Migrator().migrate( action.projectData, CHARTICULATOR_PACKAGE.version ); this.loadState(state); }); REG.add(Actions.ImportDataset, function (action) { this.currentChartID = null; this.dataset = action.dataset; this.originDataset = deepClone(this.dataset); this.historyManager.clear(); this.newChartEmpty(); this.emit(AppStore.EVENT_DATASET); this.solveConstraintsAndUpdateGraphics(); }); REG.add(Actions.ImportChartAndDataset, function (action) { this.currentChartID = null; this.currentSelection = null; this.dataset = action.dataset; this.originDataset = deepClone(this.dataset); this.chart = action.specification; this.chartManager = new Prototypes.ChartStateManager( this.chart, this.dataset, null, {}, {}, action.originSpecification ? deepClone(action.originSpecification) : this.chartManager.getOriginChart() ); this.chartManager.onUpdate(() => { this.solveConstraintsAndUpdateGraphics(); }); this.chartState = this.chartManager.chartState; this.emit(AppStore.EVENT_DATASET); this.emit(AppStore.EVENT_SELECTION); this.solveConstraintsAndUpdateGraphics(); }); REG.add(Actions.UpdatePlotSegments, function () { this.updatePlotSegments(); this.solveConstraintsAndUpdateGraphics(); this.emit(AppStore.EVENT_DATASET); this.emit(AppStore.EVENT_SELECTION); }); REG.add(Actions.UpdateDataAxis, function () { this.updateDataAxes(); this.solveConstraintsAndUpdateGraphics(); this.emit(AppStore.EVENT_DATASET); this.emit(AppStore.EVENT_SELECTION); }); REG.add(Actions.ReplaceDataset, function (action) { this.currentChartID = null; this.currentSelection = null; this.dataset = action.dataset; this.originDataset = deepClone(this.dataset); this.chartManager = new Prototypes.ChartStateManager( this.chart, this.dataset, null, {}, {}, action.keepState ? this.chartManager.getOriginChart() : null ); this.chartManager.onUpdate(() => { this.solveConstraintsAndUpdateGraphics(); }); this.chartState = this.chartManager.chartState; this.updatePlotSegments(); this.updateDataAxes(); this.updateScales(); this.solveConstraintsAndUpdateGraphics(); this.emit(AppStore.EVENT_DATASET); this.emit(AppStore.EVENT_SELECTION); }); REG.add(Actions.ConvertColumnDataType, function (action) { this.saveHistory(); const table = this.dataset.tables.find( (table) => table.name === action.tableName ); if (!table) { return; } const column = table.columns.find( (column) => column.name === action.column ); if (!column) { return; } const originTable = this.originDataset.tables.find( (table) => table.name === action.tableName ); let originColumn = originTable.columns.find( (column) => column.name === action.column ); if (originColumn.metadata.rawColumnName) { originColumn = originTable.columns.find( (column) => column.name === originColumn.metadata.rawColumnName ); } const result = convertColumns(table, column, originTable, action.type); if (result) { this.messageState.set("columnConvertError", result); } this.updatePlotSegments(); this.updateDataAxes(); this.updateScales(); this.solveConstraintsAndUpdateGraphics(); this.emit(AppStore.EVENT_DATASET); this.emit(AppStore.EVENT_SELECTION); }); REG.add(Actions.Undo, function () { const state = this.historyManager.undo(this.saveDecoupledState()); if (state) { const ss = this.saveSelectionState(); this.loadState(state); this.loadSelectionState(ss); } }); REG.add(Actions.Redo, function () { const state = this.historyManager.redo(this.saveDecoupledState()); if (state) { const ss = this.saveSelectionState(); this.loadState(state); this.loadSelectionState(ss); } }); REG.add(Actions.Reset, function () { this.saveHistory(); this.currentSelection = null; this.currentTool = null; this.emit(AppStore.EVENT_SELECTION); this.emit(AppStore.EVENT_CURRENT_TOOL); this.newChartEmpty(); this.solveConstraintsAndUpdateGraphics(); }); REG.add(Actions.OpenNestedEditor, function ({ options, object, property }) { this.emit(AppStore.EVENT_OPEN_NESTED_EDITOR, options, object, property); const editorID = uniqueID(); const newWindow = window.open( "index.html#!nestedEditor=" + editorID, "nested_chart_" + options.specification._id ); const listener = (e: MessageEvent) => { if (e.origin == document.location.origin) { const data = <NestedEditorMessage>e.data; if (data.id == editorID) { switch (data.type) { case NestedEditorMessageType.Initialized: { const builder = new ChartTemplateBuilder( options.specification, options.dataset, this.chartManager, CHARTICULATOR_PACKAGE.version ); const template = builder.build(); newWindow.postMessage( { id: editorID, type: NestedEditorEventType.Load, specification: options.specification, dataset: options.dataset, width: options.width, template, height: options.height, filterCondition: options.filterCondition, }, document.location.origin ); } break; case NestedEditorMessageType.Save: { this.setProperty({ object, property: property.property, field: property.field, value: data.specification, noUpdateState: property.noUpdateState, noComputeLayout: property.noComputeLayout, }); } break; } } } }; window.addEventListener("message", listener); }); }
the_stack
import { URI, UriComponents } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { Action2, IAction2Options, MenuId, MenuRegistry } from 'vs/platform/actions/common/actions'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { getNotebookEditorFromEditorPane, IActiveNotebookEditor, ICellViewModel, cellRangeToViewCells } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { NOTEBOOK_EDITOR_EDITABLE, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_IS_ACTIVE_EDITOR, NOTEBOOK_KERNEL_COUNT, NOTEBOOK_KERNEL_SOURCE_COUNT } from 'vs/workbench/contrib/notebook/common/notebookContextKeys'; import { ICellRange, isICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorCommandsContext } from 'vs/workbench/common/editor'; import { INotebookEditorService } from 'vs/workbench/contrib/notebook/browser/notebookEditorService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { WorkbenchActionExecutedClassification, WorkbenchActionExecutedEvent } from 'vs/base/common/actions'; import { TypeConstraint } from 'vs/base/common/types'; import { IJSONSchema } from 'vs/base/common/jsonSchema'; import { MarshalledId } from 'vs/base/common/marshallingIds'; // Kernel Command export const SELECT_KERNEL_ID = '_notebook.selectKernel'; export const NOTEBOOK_ACTIONS_CATEGORY = { value: localize('notebookActions.category', "Notebook"), original: 'Notebook' }; export const CELL_TITLE_CELL_GROUP_ID = 'inline/cell'; export const CELL_TITLE_OUTPUT_GROUP_ID = 'inline/output'; export const NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT = KeybindingWeight.EditorContrib; // smaller than Suggest Widget, etc export const enum CellToolbarOrder { EditCell, ExecuteAboveCells, ExecuteCellAndBelow, SaveCell, SplitCell, ClearCellOutput } export const enum CellOverflowToolbarGroups { Copy = '1_copy', Insert = '2_insert', Edit = '3_edit' } export interface INotebookActionContext { readonly cell?: ICellViewModel; readonly notebookEditor: IActiveNotebookEditor; readonly ui?: boolean; readonly selectedCells?: readonly ICellViewModel[]; readonly autoReveal?: boolean; } export interface INotebookCellToolbarActionContext extends INotebookActionContext { readonly ui: true; readonly cell: ICellViewModel; } export interface INotebookCommandContext extends INotebookActionContext { readonly ui: false; readonly selectedCells: readonly ICellViewModel[]; } export interface INotebookCellActionContext extends INotebookActionContext { cell: ICellViewModel; } export function getContextFromActiveEditor(editorService: IEditorService): INotebookActionContext | undefined { const editor = getNotebookEditorFromEditorPane(editorService.activeEditorPane); if (!editor || !editor.hasModel()) { return; } const activeCell = editor.getActiveCell(); const selectedCells = editor.getSelectionViewModels(); return { cell: activeCell, selectedCells, notebookEditor: editor }; } function getWidgetFromUri(accessor: ServicesAccessor, uri: URI) { const notebookEditorService = accessor.get(INotebookEditorService); const widget = notebookEditorService.listNotebookEditors().find(widget => widget.hasModel() && widget.textModel.uri.toString() === uri.toString()); if (widget && widget.hasModel()) { return widget; } return undefined; } export function getContextFromUri(accessor: ServicesAccessor, context?: any) { const uri = URI.revive(context); if (uri) { const widget = getWidgetFromUri(accessor, uri); if (widget) { return { notebookEditor: widget, }; } } return undefined; } export abstract class NotebookAction extends Action2 { constructor(desc: IAction2Options) { if (desc.f1 !== false) { desc.f1 = false; const f1Menu = { id: MenuId.CommandPalette, when: NOTEBOOK_IS_ACTIVE_EDITOR }; if (!desc.menu) { desc.menu = []; } else if (!Array.isArray(desc.menu)) { desc.menu = [desc.menu]; } desc.menu = [ ...desc.menu, f1Menu ]; } desc.category = NOTEBOOK_ACTIONS_CATEGORY; super(desc); } async run(accessor: ServicesAccessor, context?: any, ...additionalArgs: any[]): Promise<void> { const isFromUI = !!context; const from = isFromUI ? (this.isNotebookActionContext(context) ? 'notebookToolbar' : 'editorToolbar') : undefined; if (!this.isNotebookActionContext(context)) { context = this.getEditorContextFromArgsOrActive(accessor, context, ...additionalArgs); if (!context) { return; } } if (from !== undefined) { const telemetryService = accessor.get(ITelemetryService); telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: this.desc.id, from: from }); } return this.runWithContext(accessor, context); } abstract runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void>; private isNotebookActionContext(context?: unknown): context is INotebookActionContext { return !!context && !!(context as INotebookActionContext).notebookEditor; } protected getEditorContextFromArgsOrActive(accessor: ServicesAccessor, context?: any, ...additionalArgs: any[]): INotebookActionContext | undefined { return getContextFromActiveEditor(accessor.get(IEditorService)); } } // todo@rebornix, replace NotebookAction with this export abstract class NotebookMultiCellAction extends Action2 { constructor(desc: IAction2Options) { if (desc.f1 !== false) { desc.f1 = false; const f1Menu = { id: MenuId.CommandPalette, when: NOTEBOOK_IS_ACTIVE_EDITOR }; if (!desc.menu) { desc.menu = []; } else if (!Array.isArray(desc.menu)) { desc.menu = [desc.menu]; } desc.menu = [ ...desc.menu, f1Menu ]; } desc.category = NOTEBOOK_ACTIONS_CATEGORY; super(desc); } parseArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { return undefined; } abstract runWithContext(accessor: ServicesAccessor, context: INotebookCommandContext | INotebookCellToolbarActionContext): Promise<void>; private isCellToolbarContext(context?: unknown): context is INotebookCellToolbarActionContext { return !!context && !!(context as INotebookActionContext).notebookEditor && (context as any).$mid === MarshalledId.NotebookCellActionContext; } private isEditorContext(context?: unknown): boolean { return !!context && (context as IEditorCommandsContext).groupId !== undefined; } /** * The action/command args are resolved in following order * `run(accessor, cellToolbarContext)` from cell toolbar * `run(accessor, ...args)` from command service with arguments * `run(accessor, undefined)` from keyboard shortcuts, command palatte, etc */ async run(accessor: ServicesAccessor, ...additionalArgs: any[]): Promise<void> { const context = additionalArgs[0]; const isFromCellToolbar = this.isCellToolbarContext(context); const isFromEditorToolbar = this.isEditorContext(context); const from = isFromCellToolbar ? 'cellToolbar' : (isFromEditorToolbar ? 'editorToolbar' : 'other'); const telemetryService = accessor.get(ITelemetryService); if (isFromCellToolbar) { telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: this.desc.id, from: from }); return this.runWithContext(accessor, context); } // handle parsed args const parsedArgs = this.parseArgs(accessor, ...additionalArgs); if (parsedArgs) { telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: this.desc.id, from: from }); return this.runWithContext(accessor, parsedArgs); } // no parsed args, try handle active editor const editor = getEditorFromArgsOrActivePane(accessor); if (editor) { telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: this.desc.id, from: from }); return this.runWithContext(accessor, { ui: false, notebookEditor: editor, selectedCells: cellRangeToViewCells(editor, editor.getSelections()) }); } } } export abstract class NotebookCellAction<T = INotebookCellActionContext> extends NotebookAction { protected isCellActionContext(context?: unknown): context is INotebookCellActionContext { return !!context && !!(context as INotebookCellActionContext).notebookEditor && !!(context as INotebookCellActionContext).cell; } protected getCellContextFromArgs(accessor: ServicesAccessor, context?: T, ...additionalArgs: any[]): INotebookCellActionContext | undefined { return undefined; } override async run(accessor: ServicesAccessor, context?: INotebookCellActionContext, ...additionalArgs: any[]): Promise<void> { if (this.isCellActionContext(context)) { const telemetryService = accessor.get(ITelemetryService); telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: this.desc.id, from: 'cellToolbar' }); return this.runWithContext(accessor, context); } const contextFromArgs = this.getCellContextFromArgs(accessor, context, ...additionalArgs); if (contextFromArgs) { return this.runWithContext(accessor, contextFromArgs); } const activeEditorContext = this.getEditorContextFromArgsOrActive(accessor); if (this.isCellActionContext(activeEditorContext)) { return this.runWithContext(accessor, activeEditorContext); } } abstract override runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void>; } export const executeNotebookCondition = ContextKeyExpr.or(ContextKeyExpr.greater(NOTEBOOK_KERNEL_COUNT.key, 0), ContextKeyExpr.greater(NOTEBOOK_KERNEL_SOURCE_COUNT.key, 0)); interface IMultiCellArgs { ranges: ICellRange[]; document?: URI; autoReveal?: boolean; } function isMultiCellArgs(arg: unknown): arg is IMultiCellArgs { if (arg === undefined) { return false; } const ranges = (arg as IMultiCellArgs).ranges; if (!ranges) { return false; } if (!Array.isArray(ranges) || ranges.some(range => !isICellRange(range))) { return false; } if ((arg as IMultiCellArgs).document) { const uri = URI.revive((arg as IMultiCellArgs).document); if (!uri) { return false; } } return true; } export function getEditorFromArgsOrActivePane(accessor: ServicesAccessor, context?: UriComponents): IActiveNotebookEditor | undefined { const editorFromUri = getContextFromUri(accessor, context)?.notebookEditor; if (editorFromUri) { return editorFromUri; } const editor = getNotebookEditorFromEditorPane(accessor.get(IEditorService).activeEditorPane); if (!editor || !editor.hasModel()) { return; } return editor; } export function parseMultiCellExecutionArgs(accessor: ServicesAccessor, ...args: any[]): INotebookCommandContext | undefined { const firstArg = args[0]; if (isMultiCellArgs(firstArg)) { const editor = getEditorFromArgsOrActivePane(accessor, firstArg.document); if (!editor) { return; } const ranges = firstArg.ranges; const selectedCells = ranges.map(range => editor.getCellsInRange(range).slice(0)).flat(); const autoReveal = firstArg.autoReveal; return { ui: false, notebookEditor: editor, selectedCells, autoReveal }; } // handle legacy arguments if (isICellRange(firstArg)) { // cellRange, document const secondArg = args[1]; const editor = getEditorFromArgsOrActivePane(accessor, secondArg); if (!editor) { return; } return { ui: false, notebookEditor: editor, selectedCells: editor.getCellsInRange(firstArg) }; } // let's just execute the active cell const context = getContextFromActiveEditor(accessor.get(IEditorService)); return context ? { ui: false, notebookEditor: context.notebookEditor, selectedCells: context.selectedCells ?? [] } : undefined; } export const cellExecutionArgs: ReadonlyArray<{ readonly name: string; readonly isOptional?: boolean; readonly description?: string; readonly constraint?: TypeConstraint; readonly schema?: IJSONSchema; }> = [ { isOptional: true, name: 'options', description: 'The cell range options', schema: { 'type': 'object', 'required': ['ranges'], 'properties': { 'ranges': { 'type': 'array', items: [ { 'type': 'object', 'required': ['start', 'end'], 'properties': { 'start': { 'type': 'number' }, 'end': { 'type': 'number' } } } ] }, 'document': { 'type': 'object', 'description': 'The document uri', }, 'autoReveal': { 'type': 'boolean', 'description': 'Whether the cell should be revealed into view automatically' } } } } ]; MenuRegistry.appendMenuItem(MenuId.NotebookCellTitle, { submenu: MenuId.NotebookCellInsert, title: localize('notebookMenu.insertCell', "Insert Cell"), group: CellOverflowToolbarGroups.Insert, when: NOTEBOOK_EDITOR_EDITABLE.isEqualTo(true) }); MenuRegistry.appendMenuItem(MenuId.EditorContext, { submenu: MenuId.NotebookCellTitle, title: localize('notebookMenu.cellTitle', "Notebook Cell"), group: CellOverflowToolbarGroups.Insert, when: NOTEBOOK_EDITOR_FOCUSED });
the_stack
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /* * Configurable variables. You may need to tweak these to be compatible with * the server-side, but the defaults work in most cases. */ /* hex output format. 0 - lowercase; 1 - uppercase */ let hexcase: number = 0; /* base-64 pad character. "=" for strict RFC compliance */ let b64pad: string = ''; /* * These are the functions you'll usually want to call * They take string arguments and return either hex or base-64 encoded strings */ export const hex_md5 = (s: string) => rstr2hex(rstr_md5(str2rstr_utf8(s))); export default hex_md5; export const b64_md5 = (s: string) => rstr2b64(rstr_md5(str2rstr_utf8(s))); export const any_md5 = (s: string, e: string) => rstr2any(rstr_md5(str2rstr_utf8(s)), e); export const hex_hmac_md5 = (k: string, d: string) => rstr2hex(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); export const b64_hmac_md5 = (k: string, d: string) => rstr2b64(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d))); export const any_hmac_md5 = (k: string, d: string, e: string) => rstr2any(rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)), e); /* * Perform a simple self-test to see if the VM is working */ // eslint-disable-next-line @typescript-eslint/no-unused-vars const md5_vm_test = () => hex_md5('abc').toLowerCase() === '900150983cd24fb0d6963f7d28e17f72'; /* * Calculate the MD5 of a raw string */ const rstr_md5 = (s: string) => binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ const rstr_hmac_md5 = (key: string, data: string) => { var bkey = rstr2binl(key); if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } let ipad = Array(16); let opad = Array(16); for (var i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5c5c5c5c; } var hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); }; /* * Convert a raw string to a hex string */ const rstr2hex = (input: string) => { try { hexcase; } catch (e) { hexcase = 0; } var hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'; var output = ''; var x; for (var i = 0; i < input.length; i++) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0f) + hex_tab.charAt(x & 0x0f); } return output; }; /* * Convert a raw string to a base-64 string */ const rstr2b64 = (input: string) => { try { b64pad; } catch (e) { b64pad = ''; } var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var output = ''; var len = input.length; for (var i = 0; i < len; i += 3) { var triplet = (input.charCodeAt(i) << 16) | (i + 1 < len ? input.charCodeAt(i + 1) << 8 : 0) | (i + 2 < len ? input.charCodeAt(i + 2) : 0); for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 > input.length * 8) { output += b64pad; } else { output += tab.charAt((triplet >>> (6 * (3 - j))) & 0x3f); } } } return output; }; /* * Convert a raw string to an arbitrary string encoding */ const rstr2any = (input: string, encoding: string) => { var divisor = encoding.length; var i, j, q, x, quotient; /* Convert to an array of 16-bit big-endian values, forming the dividend */ var dividend = Array(Math.ceil(input.length / 2)); for (i = 0; i < dividend.length; i++) { dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1); } /* * Repeatedly perform a long division. The binary array forms the dividend, * the length of the encoding is the divisor. Once computed, the quotient * forms the dividend for the next step. All remainders are stored for later * use. */ var full_length = Math.ceil( (input.length * 8) / (Math.log(encoding.length) / Math.log(2)), ); var remainders = Array(full_length); for (j = 0; j < full_length; j++) { quotient = []; x = 0; for (i = 0; i < dividend.length; i++) { x = (x << 16) + dividend[i]; q = Math.floor(x / divisor); x -= q * divisor; if (quotient.length > 0 || q > 0) { quotient[quotient.length] = q; } } remainders[j] = x; dividend = quotient; } /* Convert the remainders to the output string */ var output = ''; for (i = remainders.length - 1; i >= 0; i--) { output += encoding.charAt(remainders[i]); } return output; }; /* * Encode a string as utf-8. * For efficiency, this assumes the input is valid utf-16. */ const str2rstr_utf8 = (input: string) => { var output = ''; var i = -1; var x, y; while (++i < input.length) { /* Decode utf-16 surrogate pairs */ x = input.charCodeAt(i); y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; if (x >= 0xd800 && x <= 0xdbff && y >= 0xdc00 && y <= 0xdfff) { x = 0x10000 + ((x & 0x03ff) << 10) + (y & 0x03ff); i++; } /* Encode output as utf-8 */ if (x <= 0x7f) { output += String.fromCharCode(x); } else if (x <= 0x7ff) { output += String.fromCharCode( 0xc0 | ((x >>> 6) & 0x1f), 0x80 | (x & 0x3f), ); } else if (x <= 0xffff) { output += String.fromCharCode( 0xe0 | ((x >>> 12) & 0x0f), 0x80 | ((x >>> 6) & 0x3f), 0x80 | (x & 0x3f), ); } else if (x <= 0x1fffff) { output += String.fromCharCode( 0xf0 | ((x >>> 18) & 0x07), 0x80 | ((x >>> 12) & 0x3f), 0x80 | ((x >>> 6) & 0x3f), 0x80 | (x & 0x3f), ); } } return output; }; /* * Encode a string as utf-16 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars const str2rstr_utf16le = (input: string) => { var output = ''; for (var i = 0; i < input.length; i++) { output += String.fromCharCode( input.charCodeAt(i) & 0xff, (input.charCodeAt(i) >>> 8) & 0xff, ); } return output; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars const str2rstr_utf16be = (input: string) => { var output = ''; for (var i = 0; i < input.length; i++) { output += String.fromCharCode( (input.charCodeAt(i) >>> 8) & 0xff, input.charCodeAt(i) & 0xff, ); } return output; }; /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ const rstr2binl = (input: string) => { let output: number[] = Array(input.length >> 2); for (var i = 0; i < output.length; i++) { output[i] = 0; } for (var i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xff) << i % 32; } return output; }; /* * Convert an array of little-endian words to a string */ const binl2rstr = (input: any[]): string => { var output = ''; for (var i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> i % 32) & 0xff); } return output; }; /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ const binl_md5 = (x: number[], len: number) => { /* append padding */ x[len >> 5] |= 0x80 << len % 32; x[(((len + 64) >>> 9) << 4) + 14] = len; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (var i = 0; i < x.length; i += 16) { var olda = a; var oldb = b; var oldc = c; var oldd = d; a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; }; /* * These functions implement the four basic operations the algorithm uses. */ const md5_cmn = ( q: number, a: number, b: number, x: number, s: number, t: number, ) => safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); const md5_ff = ( a: number, b: number, c: number, d: number, x: number, s: number, t: number, ) => md5_cmn((b & c) | (~b & d), a, b, x, s, t); const md5_gg = ( a: number, b: number, c: number, d: number, x: number, s: number, t: number, ) => md5_cmn((b & d) | (c & ~d), a, b, x, s, t); const md5_hh = ( a: number, b: number, c: number, d: number, x: number, s: number, t: number, ) => md5_cmn(b ^ c ^ d, a, b, x, s, t); const md5_ii = ( a: number, b: number, c: number, d: number, x: number, s: number, t: number, ) => md5_cmn(c ^ (b | ~d), a, b, x, s, t); /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ const safe_add = (x: number, y: number) => { var lsw = (x & 0xffff) + (y & 0xffff); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xffff); }; /* * Bitwise rotate a 32-bit number to the left. */ const bit_rol = (num: number, cnt: number) => (num << cnt) | (num >>> (32 - cnt));
the_stack
import * as assert from 'assert'; import { LineTokens } from 'vs/editor/common/tokens/lineTokens'; import { Range } from 'vs/editor/common/core/range'; import { computeIndentLevel } from 'vs/editor/common/model/utils'; import { MetadataConsts } from 'vs/editor/common/languages'; import { TestLineToken, TestLineTokenFactory } from 'vs/editor/test/common/core/testLineToken'; import { createTextModel } from 'vs/editor/test/common/testTextModel'; interface ILineEdit { startColumn: number; endColumn: number; text: string; } function assertLineTokens(__actual: LineTokens, _expected: TestToken[]): void { let tmp = TestToken.toTokens(_expected); LineTokens.convertToEndOffset(tmp, __actual.getLineContent().length); let expected = TestLineTokenFactory.inflateArr(tmp); let _actual = __actual.inflate(); interface ITestToken { endIndex: number; type: string; } let actual: ITestToken[] = []; for (let i = 0, len = _actual.getCount(); i < len; i++) { actual[i] = { endIndex: _actual.getEndOffset(i), type: _actual.getClassName(i) }; } let decode = (token: TestLineToken) => { return { endIndex: token.endIndex, type: token.getType() }; }; assert.deepStrictEqual(actual, expected.map(decode)); } suite('ModelLine - getIndentLevel', () => { function assertIndentLevel(text: string, expected: number, tabSize: number = 4): void { let actual = computeIndentLevel(text, tabSize); assert.strictEqual(actual, expected, text); } test('getIndentLevel', () => { assertIndentLevel('', -1); assertIndentLevel(' ', -1); assertIndentLevel(' \t', -1); assertIndentLevel('Hello', 0); assertIndentLevel(' Hello', 1); assertIndentLevel(' Hello', 3); assertIndentLevel('\tHello', 4); assertIndentLevel(' \tHello', 4); assertIndentLevel(' \tHello', 4); assertIndentLevel(' \tHello', 4); assertIndentLevel(' \tHello', 8); assertIndentLevel(' \tHello', 8); assertIndentLevel('\t Hello', 5); assertIndentLevel('\t \tHello', 8); }); }); class TestToken { public readonly startOffset: number; public readonly color: number; constructor(startOffset: number, color: number) { this.startOffset = startOffset; this.color = color; } public static toTokens(tokens: TestToken[]): Uint32Array; public static toTokens(tokens: TestToken[] | null): Uint32Array | null { if (tokens === null) { return null; } let tokensLen = tokens.length; let result = new Uint32Array((tokensLen << 1)); for (let i = 0; i < tokensLen; i++) { let token = tokens[i]; result[(i << 1)] = token.startOffset; result[(i << 1) + 1] = ( token.color << MetadataConsts.FOREGROUND_OFFSET ) >>> 0; } return result; } } suite('ModelLinesTokens', () => { interface IBufferLineState { text: string; tokens: TestToken[]; } interface IEdit { range: Range; text: string; } function testApplyEdits(initial: IBufferLineState[], edits: IEdit[], expected: IBufferLineState[]): void { const initialText = initial.map(el => el.text).join('\n'); const model = createTextModel(initialText, 'test'); for (let lineIndex = 0; lineIndex < initial.length; lineIndex++) { const lineTokens = initial[lineIndex].tokens; const lineTextLength = model.getLineMaxColumn(lineIndex + 1) - 1; const tokens = TestToken.toTokens(lineTokens); LineTokens.convertToEndOffset(tokens, lineTextLength); model.setLineTokens(lineIndex + 1, tokens); } model.applyEdits(edits.map((ed) => ({ identifier: null, range: ed.range, text: ed.text, forceMoveMarkers: false }))); for (let lineIndex = 0; lineIndex < expected.length; lineIndex++) { const actualLine = model.getLineContent(lineIndex + 1); const actualTokens = model.tokenization.getLineTokens(lineIndex + 1); assert.strictEqual(actualLine, expected[lineIndex].text); assertLineTokens(actualTokens, expected[lineIndex].tokens); } model.dispose(); } test('single delete 1', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 1, 1, 2), text: '' }], [{ text: 'ello world', tokens: [new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3)] }] ); }); test('single delete 2', () => { testApplyEdits( [{ text: 'helloworld', tokens: [new TestToken(0, 1), new TestToken(5, 2)] }], [{ range: new Range(1, 3, 1, 8), text: '' }], [{ text: 'herld', tokens: [new TestToken(0, 1), new TestToken(2, 2)] }] ); }); test('single delete 3', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 1, 1, 6), text: '' }], [{ text: ' world', tokens: [new TestToken(0, 2), new TestToken(1, 3)] }] ); }); test('single delete 4', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 2, 1, 7), text: '' }], [{ text: 'hworld', tokens: [new TestToken(0, 1), new TestToken(1, 3)] }] ); }); test('single delete 5', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 1, 1, 12), text: '' }], [{ text: '', tokens: [new TestToken(0, 1)] }] ); }); test('multi delete 6', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }, { text: 'hello world', tokens: [new TestToken(0, 7), new TestToken(5, 8), new TestToken(6, 9)] }], [{ range: new Range(1, 6, 3, 6), text: '' }], [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 8), new TestToken(6, 9)] }] ); }); test('multi delete 7', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }, { text: 'hello world', tokens: [new TestToken(0, 7), new TestToken(5, 8), new TestToken(6, 9)] }], [{ range: new Range(1, 12, 3, 12), text: '' }], [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }] ); }); test('multi delete 8', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }, { text: 'hello world', tokens: [new TestToken(0, 7), new TestToken(5, 8), new TestToken(6, 9)] }], [{ range: new Range(1, 1, 3, 1), text: '' }], [{ text: 'hello world', tokens: [new TestToken(0, 7), new TestToken(5, 8), new TestToken(6, 9)] }] ); }); test('multi delete 9', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }, { text: 'hello world', tokens: [new TestToken(0, 7), new TestToken(5, 8), new TestToken(6, 9)] }], [{ range: new Range(1, 12, 3, 1), text: '' }], [{ text: 'hello worldhello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3), new TestToken(11, 7), new TestToken(16, 8), new TestToken(17, 9)] }] ); }); test('single insert 1', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 1, 1, 1), text: 'xx' }], [{ text: 'xxhello world', tokens: [new TestToken(0, 1), new TestToken(7, 2), new TestToken(8, 3)] }] ); }); test('single insert 2', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 2, 1, 2), text: 'xx' }], [{ text: 'hxxello world', tokens: [new TestToken(0, 1), new TestToken(7, 2), new TestToken(8, 3)] }] ); }); test('single insert 3', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 6, 1, 6), text: 'xx' }], [{ text: 'helloxx world', tokens: [new TestToken(0, 1), new TestToken(7, 2), new TestToken(8, 3)] }] ); }); test('single insert 4', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 7, 1, 7), text: 'xx' }], [{ text: 'hello xxworld', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(8, 3)] }] ); }); test('single insert 5', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 12, 1, 12), text: 'xx' }], [{ text: 'hello worldxx', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }] ); }); test('multi insert 6', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 1, 1, 1), text: '\n' }], [{ text: '', tokens: [new TestToken(0, 1)] }, { text: 'hello world', tokens: [new TestToken(0, 1)] }] ); }); test('multi insert 7', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 12, 1, 12), text: '\n' }], [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: '', tokens: [new TestToken(0, 1)] }] ); }); test('multi insert 8', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }], [{ range: new Range(1, 7, 1, 7), text: '\n' }], [{ text: 'hello ', tokens: [new TestToken(0, 1), new TestToken(5, 2)] }, { text: 'world', tokens: [new TestToken(0, 1)] }] ); }); test('multi insert 9', () => { testApplyEdits( [{ text: 'hello world', tokens: [new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }], [{ range: new Range(1, 7, 1, 7), text: 'xx\nyy' }], [{ text: 'hello xx', tokens: [new TestToken(0, 1), new TestToken(5, 2)] }, { text: 'yyworld', tokens: [new TestToken(0, 1)] }, { text: 'hello world', tokens: [new TestToken(0, 4), new TestToken(5, 5), new TestToken(6, 6)] }] ); }); function testLineEditTokens(initialText: string, initialTokens: TestToken[], edits: ILineEdit[], expectedText: string, expectedTokens: TestToken[]): void { testApplyEdits( [{ text: initialText, tokens: initialTokens }], edits.map((ed) => ({ range: new Range(1, ed.startColumn, 1, ed.endColumn), text: ed.text })), [{ text: expectedText, tokens: expectedTokens }] ); } test('insertion on empty line', () => { const model = createTextModel('some text', 'test'); const tokens = TestToken.toTokens([new TestToken(0, 1)]); LineTokens.convertToEndOffset(tokens, model.getLineMaxColumn(1) - 1); model.setLineTokens(1, tokens); model.applyEdits([{ range: new Range(1, 1, 1, 10), text: '' }]); model.setLineTokens(1, new Uint32Array(0)); model.applyEdits([{ range: new Range(1, 1, 1, 1), text: 'a' }]); const actualTokens = model.tokenization.getLineTokens(1); assertLineTokens(actualTokens, [new TestToken(0, 1)]); model.dispose(); }); test('updates tokens on insertion 1', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 1, text: 'a', }], 'aabcd efgh', [ new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3) ] ); }); test('updates tokens on insertion 2', () => { testLineEditTokens( 'aabcd efgh', [ new TestToken(0, 1), new TestToken(5, 2), new TestToken(6, 3) ], [{ startColumn: 2, endColumn: 2, text: 'x', }], 'axabcd efgh', [ new TestToken(0, 1), new TestToken(6, 2), new TestToken(7, 3) ] ); }); test('updates tokens on insertion 3', () => { testLineEditTokens( 'axabcd efgh', [ new TestToken(0, 1), new TestToken(6, 2), new TestToken(7, 3) ], [{ startColumn: 3, endColumn: 3, text: 'stu', }], 'axstuabcd efgh', [ new TestToken(0, 1), new TestToken(9, 2), new TestToken(10, 3) ] ); }); test('updates tokens on insertion 4', () => { testLineEditTokens( 'axstuabcd efgh', [ new TestToken(0, 1), new TestToken(9, 2), new TestToken(10, 3) ], [{ startColumn: 10, endColumn: 10, text: '\t', }], 'axstuabcd\t efgh', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(11, 3) ] ); }); test('updates tokens on insertion 5', () => { testLineEditTokens( 'axstuabcd\t efgh', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(11, 3) ], [{ startColumn: 12, endColumn: 12, text: 'dd', }], 'axstuabcd\t ddefgh', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(13, 3) ] ); }); test('updates tokens on insertion 6', () => { testLineEditTokens( 'axstuabcd\t ddefgh', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(13, 3) ], [{ startColumn: 18, endColumn: 18, text: 'xyz', }], 'axstuabcd\t ddefghxyz', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(13, 3) ] ); }); test('updates tokens on insertion 7', () => { testLineEditTokens( 'axstuabcd\t ddefghxyz', [ new TestToken(0, 1), new TestToken(10, 2), new TestToken(13, 3) ], [{ startColumn: 1, endColumn: 1, text: 'x', }], 'xaxstuabcd\t ddefghxyz', [ new TestToken(0, 1), new TestToken(11, 2), new TestToken(14, 3) ] ); }); test('updates tokens on insertion 8', () => { testLineEditTokens( 'xaxstuabcd\t ddefghxyz', [ new TestToken(0, 1), new TestToken(11, 2), new TestToken(14, 3) ], [{ startColumn: 22, endColumn: 22, text: 'x', }], 'xaxstuabcd\t ddefghxyzx', [ new TestToken(0, 1), new TestToken(11, 2), new TestToken(14, 3) ] ); }); test('updates tokens on insertion 9', () => { testLineEditTokens( 'xaxstuabcd\t ddefghxyzx', [ new TestToken(0, 1), new TestToken(11, 2), new TestToken(14, 3) ], [{ startColumn: 2, endColumn: 2, text: '', }], 'xaxstuabcd\t ddefghxyzx', [ new TestToken(0, 1), new TestToken(11, 2), new TestToken(14, 3) ] ); }); test('updates tokens on insertion 10', () => { testLineEditTokens( '', [], [{ startColumn: 1, endColumn: 1, text: 'a', }], 'a', [ new TestToken(0, 1) ] ); }); test('delete second token 2', () => { testLineEditTokens( 'abcdefghij', [ new TestToken(0, 1), new TestToken(3, 2), new TestToken(6, 3) ], [{ startColumn: 4, endColumn: 7, text: '', }], 'abcghij', [ new TestToken(0, 1), new TestToken(3, 3) ] ); }); test('insert right before second token', () => { testLineEditTokens( 'abcdefghij', [ new TestToken(0, 1), new TestToken(3, 2), new TestToken(6, 3) ], [{ startColumn: 4, endColumn: 4, text: 'hello', }], 'abchellodefghij', [ new TestToken(0, 1), new TestToken(8, 2), new TestToken(11, 3) ] ); }); test('delete first char', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 2, text: '', }], 'bcd efgh', [ new TestToken(0, 1), new TestToken(3, 2), new TestToken(4, 3) ] ); }); test('delete 2nd and 3rd chars', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 2, endColumn: 4, text: '', }], 'ad efgh', [ new TestToken(0, 1), new TestToken(2, 2), new TestToken(3, 3) ] ); }); test('delete first token', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 5, text: '', }], ' efgh', [ new TestToken(0, 2), new TestToken(1, 3) ] ); }); test('delete second token', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 5, endColumn: 6, text: '', }], 'abcdefgh', [ new TestToken(0, 1), new TestToken(4, 3) ] ); }); test('delete second token + a bit of the third one', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 5, endColumn: 7, text: '', }], 'abcdfgh', [ new TestToken(0, 1), new TestToken(4, 3) ] ); }); test('delete second and third token', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 5, endColumn: 10, text: '', }], 'abcd', [ new TestToken(0, 1) ] ); }); test('delete everything', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 10, text: '', }], '', [ new TestToken(0, 1) ] ); }); test('noop', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 1, text: '', }], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); test('equivalent to deleting first two chars', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 1, endColumn: 3, text: '', }], 'cd efgh', [ new TestToken(0, 1), new TestToken(2, 2), new TestToken(3, 3) ] ); }); test('equivalent to deleting from 5 to the end', () => { testLineEditTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], [{ startColumn: 5, endColumn: 10, text: '', }], 'abcd', [ new TestToken(0, 1) ] ); }); test('updates tokens on replace 1', () => { testLineEditTokens( 'Hello world, ciao', [ new TestToken(0, 1), new TestToken(5, 0), new TestToken(6, 2), new TestToken(11, 0), new TestToken(13, 0) ], [{ startColumn: 1, endColumn: 6, text: 'Hi', }], 'Hi world, ciao', [ new TestToken(0, 0), new TestToken(3, 2), new TestToken(8, 0), new TestToken(10, 0), ] ); }); test('updates tokens on replace 2', () => { testLineEditTokens( 'Hello world, ciao', [ new TestToken(0, 1), new TestToken(5, 0), new TestToken(6, 2), new TestToken(11, 0), new TestToken(13, 0), ], [{ startColumn: 1, endColumn: 6, text: 'Hi', }, { startColumn: 8, endColumn: 12, text: 'my friends', }], 'Hi wmy friends, ciao', [ new TestToken(0, 0), new TestToken(3, 2), new TestToken(14, 0), new TestToken(16, 0), ] ); }); function testLineSplitTokens(initialText: string, initialTokens: TestToken[], splitColumn: number, expectedText1: string, expectedText2: string, expectedTokens: TestToken[]): void { testApplyEdits( [{ text: initialText, tokens: initialTokens }], [{ range: new Range(1, splitColumn, 1, splitColumn), text: '\n' }], [{ text: expectedText1, tokens: expectedTokens }, { text: expectedText2, tokens: [new TestToken(0, 1)] }] ); } test('split at the beginning', () => { testLineSplitTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 1, '', 'abcd efgh', [ new TestToken(0, 1), ] ); }); test('split at the end', () => { testLineSplitTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 10, 'abcd efgh', '', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); test('split inthe middle 1', () => { testLineSplitTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 5, 'abcd', ' efgh', [ new TestToken(0, 1) ] ); }); test('split inthe middle 2', () => { testLineSplitTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 6, 'abcd ', 'efgh', [ new TestToken(0, 1), new TestToken(4, 2) ] ); }); function testLineAppendTokens(aText: string, aTokens: TestToken[], bText: string, bTokens: TestToken[], expectedText: string, expectedTokens: TestToken[]): void { testApplyEdits( [{ text: aText, tokens: aTokens }, { text: bText, tokens: bTokens }], [{ range: new Range(1, aText.length + 1, 2, 1), text: '' }], [{ text: expectedText, tokens: expectedTokens }] ); } test('append empty 1', () => { testLineAppendTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], '', [], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); test('append empty 2', () => { testLineAppendTokens( '', [], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); test('append 1', () => { testLineAppendTokens( 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ], 'abcd efgh', [ new TestToken(0, 4), new TestToken(4, 5), new TestToken(5, 6) ], 'abcd efghabcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3), new TestToken(9, 4), new TestToken(13, 5), new TestToken(14, 6) ] ); }); test('append 2', () => { testLineAppendTokens( 'abcd ', [ new TestToken(0, 1), new TestToken(4, 2) ], 'efgh', [ new TestToken(0, 3) ], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); test('append 3', () => { testLineAppendTokens( 'abcd', [ new TestToken(0, 1), ], ' efgh', [ new TestToken(0, 2), new TestToken(1, 3) ], 'abcd efgh', [ new TestToken(0, 1), new TestToken(4, 2), new TestToken(5, 3) ] ); }); });
the_stack
import { TSNode } from './ts-nodes'; import { AST_NODE_TYPES } from './ast-node-types'; import { Node } from './ts-estree'; import * as ts from 'typescript'; export interface EstreeToTsNodeTypes { [AST_NODE_TYPES.ArrayExpression]: ts.ArrayLiteralExpression; [AST_NODE_TYPES.ArrayPattern]: ts.ArrayLiteralExpression | ts.ArrayBindingPattern; [AST_NODE_TYPES.ArrowFunctionExpression]: ts.ArrowFunction; [AST_NODE_TYPES.AssignmentExpression]: ts.BinaryExpression; [AST_NODE_TYPES.AssignmentPattern]: ts.ShorthandPropertyAssignment | ts.BindingElement | ts.BinaryExpression | ts.ParameterDeclaration; [AST_NODE_TYPES.AwaitExpression]: ts.AwaitExpression; [AST_NODE_TYPES.BinaryExpression]: ts.BinaryExpression; [AST_NODE_TYPES.BlockStatement]: ts.Block; [AST_NODE_TYPES.BreakStatement]: ts.BreakStatement; [AST_NODE_TYPES.CallExpression]: ts.CallExpression; [AST_NODE_TYPES.CatchClause]: ts.CatchClause; [AST_NODE_TYPES.ClassBody]: ts.ClassDeclaration | ts.ClassExpression; [AST_NODE_TYPES.ClassDeclaration]: ts.ClassDeclaration; [AST_NODE_TYPES.ClassExpression]: ts.ClassExpression; [AST_NODE_TYPES.ClassProperty]: ts.PropertyDeclaration; [AST_NODE_TYPES.ConditionalExpression]: ts.ConditionalExpression; [AST_NODE_TYPES.ContinueStatement]: ts.ContinueStatement; [AST_NODE_TYPES.DebuggerStatement]: ts.DebuggerStatement; [AST_NODE_TYPES.Decorator]: ts.Decorator; [AST_NODE_TYPES.DoWhileStatement]: ts.DoStatement; [AST_NODE_TYPES.EmptyStatement]: ts.EmptyStatement; [AST_NODE_TYPES.ExportAllDeclaration]: ts.ExportDeclaration; [AST_NODE_TYPES.ExportDefaultDeclaration]: ts.ExportAssignment | ts.FunctionDeclaration | ts.VariableStatement | ts.ClassDeclaration | ts.ClassExpression | ts.TypeAliasDeclaration | ts.InterfaceDeclaration | ts.EnumDeclaration | ts.ModuleDeclaration; [AST_NODE_TYPES.ExportNamedDeclaration]: ts.ExportDeclaration | ts.FunctionDeclaration | ts.VariableStatement | ts.ClassDeclaration | ts.ClassExpression | ts.TypeAliasDeclaration | ts.InterfaceDeclaration | ts.EnumDeclaration | ts.ModuleDeclaration; [AST_NODE_TYPES.ExportSpecifier]: ts.ExportSpecifier; [AST_NODE_TYPES.ExpressionStatement]: ts.ExpressionStatement; [AST_NODE_TYPES.ForInStatement]: ts.ForInStatement; [AST_NODE_TYPES.ForOfStatement]: ts.ForOfStatement; [AST_NODE_TYPES.ForStatement]: ts.ForStatement; [AST_NODE_TYPES.FunctionDeclaration]: ts.FunctionDeclaration; [AST_NODE_TYPES.FunctionExpression]: ts.FunctionExpression | ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration; [AST_NODE_TYPES.Identifier]: ts.Identifier | ts.ConstructorDeclaration | ts.Token<ts.SyntaxKind.NewKeyword | ts.SyntaxKind.ImportKeyword>; [AST_NODE_TYPES.IfStatement]: ts.IfStatement; [AST_NODE_TYPES.Import]: ts.ImportExpression; [AST_NODE_TYPES.ImportDeclaration]: ts.ImportDeclaration; [AST_NODE_TYPES.ImportDefaultSpecifier]: ts.ImportClause; [AST_NODE_TYPES.ImportExpression]: ts.CallExpression; [AST_NODE_TYPES.ImportNamespaceSpecifier]: ts.NamespaceImport; [AST_NODE_TYPES.ImportSpecifier]: ts.ImportSpecifier; [AST_NODE_TYPES.JSXAttribute]: ts.JsxAttribute; [AST_NODE_TYPES.JSXClosingElement]: ts.JsxClosingElement; [AST_NODE_TYPES.JSXClosingFragment]: ts.JsxClosingFragment; [AST_NODE_TYPES.JSXElement]: ts.JsxElement | ts.JsxSelfClosingElement; [AST_NODE_TYPES.JSXEmptyExpression]: ts.JsxExpression; [AST_NODE_TYPES.JSXExpressionContainer]: ts.JsxExpression; [AST_NODE_TYPES.JSXFragment]: ts.JsxFragment; [AST_NODE_TYPES.JSXIdentifier]: ts.Identifier | ts.ThisExpression; [AST_NODE_TYPES.JSXOpeningElement]: ts.JsxOpeningElement | ts.JsxSelfClosingElement; [AST_NODE_TYPES.JSXOpeningFragment]: ts.JsxOpeningFragment; [AST_NODE_TYPES.JSXSpreadAttribute]: ts.JsxSpreadAttribute; [AST_NODE_TYPES.JSXSpreadChild]: ts.JsxExpression; [AST_NODE_TYPES.JSXMemberExpression]: ts.PropertyAccessExpression; [AST_NODE_TYPES.JSXText]: ts.JsxText; [AST_NODE_TYPES.LabeledStatement]: ts.LabeledStatement; [AST_NODE_TYPES.Literal]: ts.StringLiteral | ts.NumericLiteral | ts.RegularExpressionLiteral | ts.JsxText | ts.NullLiteral | ts.BooleanLiteral | ts.BigIntLiteral; [AST_NODE_TYPES.LogicalExpression]: ts.BinaryExpression; [AST_NODE_TYPES.MemberExpression]: ts.PropertyAccessExpression | ts.ElementAccessExpression; [AST_NODE_TYPES.MetaProperty]: ts.MetaProperty; [AST_NODE_TYPES.MethodDefinition]: ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration | ts.ConstructorDeclaration; [AST_NODE_TYPES.NewExpression]: ts.NewExpression; [AST_NODE_TYPES.ObjectExpression]: ts.ObjectLiteralExpression; [AST_NODE_TYPES.ObjectPattern]: ts.ObjectLiteralExpression | ts.ObjectBindingPattern; [AST_NODE_TYPES.OptionalCallExpression]: ts.CallExpression; [AST_NODE_TYPES.OptionalMemberExpression]: ts.PropertyAccessExpression | ts.ElementAccessExpression; [AST_NODE_TYPES.Program]: ts.SourceFile; [AST_NODE_TYPES.Property]: ts.PropertyAssignment | ts.ShorthandPropertyAssignment | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration | ts.BindingElement; [AST_NODE_TYPES.RestElement]: ts.BindingElement | ts.SpreadAssignment | ts.SpreadElement | ts.ParameterDeclaration; [AST_NODE_TYPES.ReturnStatement]: ts.ReturnStatement; [AST_NODE_TYPES.SequenceExpression]: ts.BinaryExpression; [AST_NODE_TYPES.SpreadElement]: ts.SpreadElement | ts.SpreadAssignment; [AST_NODE_TYPES.Super]: ts.SuperExpression; [AST_NODE_TYPES.SwitchCase]: ts.CaseClause | ts.DefaultClause; [AST_NODE_TYPES.SwitchStatement]: ts.SwitchStatement; [AST_NODE_TYPES.TaggedTemplateExpression]: ts.TaggedTemplateExpression; [AST_NODE_TYPES.TemplateElement]: ts.NoSubstitutionTemplateLiteral | ts.TemplateHead | ts.TemplateMiddle | ts.TemplateTail; [AST_NODE_TYPES.TemplateLiteral]: ts.NoSubstitutionTemplateLiteral | ts.TemplateExpression; [AST_NODE_TYPES.ThisExpression]: ts.ThisExpression | ts.KeywordTypeNode; [AST_NODE_TYPES.ThrowStatement]: ts.ThrowStatement; [AST_NODE_TYPES.TryStatement]: ts.TryStatement; [AST_NODE_TYPES.TSAbstractClassProperty]: ts.PropertyDeclaration; [AST_NODE_TYPES.TSAbstractMethodDefinition]: ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration | ts.ConstructorDeclaration; [AST_NODE_TYPES.TSArrayType]: ts.ArrayTypeNode; [AST_NODE_TYPES.TSAsExpression]: ts.AsExpression; [AST_NODE_TYPES.TSCallSignatureDeclaration]: ts.PropertySignature; [AST_NODE_TYPES.TSClassImplements]: ts.ExpressionWithTypeArguments; [AST_NODE_TYPES.TSConditionalType]: ts.ConditionalTypeNode; [AST_NODE_TYPES.TSConstructorType]: ts.ConstructorTypeNode; [AST_NODE_TYPES.TSConstructSignatureDeclaration]: ts.ConstructorTypeNode | ts.FunctionTypeNode | ts.ConstructSignatureDeclaration | ts.CallSignatureDeclaration; [AST_NODE_TYPES.TSDeclareFunction]: ts.FunctionDeclaration; [AST_NODE_TYPES.TSEnumDeclaration]: ts.EnumDeclaration; [AST_NODE_TYPES.TSEnumMember]: ts.EnumMember; [AST_NODE_TYPES.TSExportAssignment]: ts.ExportAssignment; [AST_NODE_TYPES.TSExternalModuleReference]: ts.ExternalModuleReference; [AST_NODE_TYPES.TSFunctionType]: ts.FunctionTypeNode; [AST_NODE_TYPES.TSImportEqualsDeclaration]: ts.ImportEqualsDeclaration; [AST_NODE_TYPES.TSImportType]: ts.ImportTypeNode; [AST_NODE_TYPES.TSIndexedAccessType]: ts.IndexedAccessTypeNode; [AST_NODE_TYPES.TSIndexSignature]: ts.IndexSignatureDeclaration; [AST_NODE_TYPES.TSInferType]: ts.InferTypeNode; [AST_NODE_TYPES.TSInterfaceDeclaration]: ts.InterfaceDeclaration; [AST_NODE_TYPES.TSInterfaceBody]: ts.InterfaceDeclaration; [AST_NODE_TYPES.TSInterfaceHeritage]: ts.ExpressionWithTypeArguments; [AST_NODE_TYPES.TSIntersectionType]: ts.IntersectionTypeNode; [AST_NODE_TYPES.TSLiteralType]: ts.LiteralTypeNode; [AST_NODE_TYPES.TSMappedType]: ts.MappedTypeNode; [AST_NODE_TYPES.TSMethodSignature]: ts.MethodSignature; [AST_NODE_TYPES.TSModuleBlock]: ts.ModuleBlock; [AST_NODE_TYPES.TSModuleDeclaration]: ts.ModuleDeclaration; [AST_NODE_TYPES.TSNamespaceExportDeclaration]: ts.NamespaceExportDeclaration; [AST_NODE_TYPES.TSNonNullExpression]: ts.NonNullExpression; [AST_NODE_TYPES.TSOptionalType]: ts.OptionalTypeNode; [AST_NODE_TYPES.TSParameterProperty]: ts.ParameterDeclaration; [AST_NODE_TYPES.TSParenthesizedType]: ts.ParenthesizedTypeNode; [AST_NODE_TYPES.TSPropertySignature]: ts.PropertySignature; [AST_NODE_TYPES.TSQualifiedName]: ts.QualifiedName; [AST_NODE_TYPES.TSRestType]: ts.RestTypeNode; [AST_NODE_TYPES.TSThisType]: ts.ThisTypeNode; [AST_NODE_TYPES.TSTupleType]: ts.TupleTypeNode; [AST_NODE_TYPES.TSTypeAliasDeclaration]: ts.TypeAliasDeclaration; [AST_NODE_TYPES.TSTypeAnnotation]: undefined; [AST_NODE_TYPES.TSTypeAssertion]: ts.TypeAssertion; [AST_NODE_TYPES.TSTypeLiteral]: ts.TypeLiteralNode; [AST_NODE_TYPES.TSTypeOperator]: ts.TypeOperatorNode; [AST_NODE_TYPES.TSTypeParameter]: ts.TypeParameterDeclaration; [AST_NODE_TYPES.TSTypeParameterDeclaration]: undefined; [AST_NODE_TYPES.TSTypeParameterInstantiation]: ts.TaggedTemplateExpression | ts.ImportTypeNode | ts.ExpressionWithTypeArguments | ts.TypeReferenceNode | ts.JsxOpeningElement | ts.JsxSelfClosingElement | ts.NewExpression | ts.CallExpression; [AST_NODE_TYPES.TSTypePredicate]: ts.TypePredicateNode; [AST_NODE_TYPES.TSTypeQuery]: ts.TypeQueryNode; [AST_NODE_TYPES.TSTypeReference]: ts.TypeReferenceNode; [AST_NODE_TYPES.TSUnionType]: ts.UnionTypeNode; [AST_NODE_TYPES.UpdateExpression]: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression; [AST_NODE_TYPES.UnaryExpression]: ts.PrefixUnaryExpression | ts.PostfixUnaryExpression | ts.DeleteExpression | ts.VoidExpression | ts.TypeOfExpression; [AST_NODE_TYPES.VariableDeclaration]: ts.VariableDeclarationList | ts.VariableStatement; [AST_NODE_TYPES.VariableDeclarator]: ts.VariableDeclaration; [AST_NODE_TYPES.WhileStatement]: ts.WhileStatement; [AST_NODE_TYPES.WithStatement]: ts.WithStatement; [AST_NODE_TYPES.YieldExpression]: ts.YieldExpression; [AST_NODE_TYPES.TSEmptyBodyFunctionExpression]: ts.FunctionExpression | ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.SetAccessorDeclaration | ts.MethodDeclaration; [AST_NODE_TYPES.TSAbstractKeyword]: ts.Token<ts.SyntaxKind.AbstractKeyword>; [AST_NODE_TYPES.TSNullKeyword]: ts.NullLiteral | ts.KeywordTypeNode; [AST_NODE_TYPES.TSAnyKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSBigIntKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSBooleanKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSNeverKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSNumberKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSObjectKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSStringKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSSymbolKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSUnknownKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSVoidKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSUndefinedKeyword]: ts.KeywordTypeNode; [AST_NODE_TYPES.TSAsyncKeyword]: ts.Token<ts.SyntaxKind.AsyncKeyword>; [AST_NODE_TYPES.TSDeclareKeyword]: ts.Token<ts.SyntaxKind.DeclareKeyword>; [AST_NODE_TYPES.TSExportKeyword]: ts.Token<ts.SyntaxKind.ExportKeyword>; [AST_NODE_TYPES.TSStaticKeyword]: ts.Token<ts.SyntaxKind.StaticKeyword>; [AST_NODE_TYPES.TSPublicKeyword]: ts.Token<ts.SyntaxKind.PublicKeyword>; [AST_NODE_TYPES.TSPrivateKeyword]: ts.Token<ts.SyntaxKind.PrivateKeyword>; [AST_NODE_TYPES.TSProtectedKeyword]: ts.Token<ts.SyntaxKind.ProtectedKeyword>; [AST_NODE_TYPES.TSReadonlyKeyword]: ts.Token<ts.SyntaxKind.ReadonlyKeyword>; } /** * Maps TSESTree AST Node type to the expected TypeScript AST Node type(s). * This mapping is based on the internal logic of the parser. */ export declare type TSESTreeToTSNode<T extends Node = Node> = Extract<TSNode | ts.Token<ts.SyntaxKind.NewKeyword | ts.SyntaxKind.ImportKeyword>, EstreeToTsNodeTypes[T['type']]>; //# sourceMappingURL=estree-to-ts-node-types.d.ts.map
the_stack
import * as assert from 'assert'; import { suite, test } from 'mocha'; import { NodeType, QueryNode, Utils } from '../../src/extension/parser/nodes'; import { Parser } from '../../src/extension/parser/parser'; suite('Parser', function () { function assertNodeTypes(input: string, ...types: NodeType[]) { const parser = new Parser(); const nodes = parser.parse(input).nodes; assert.equal(nodes.length, 1); assert.equal(nodes[0]._type, NodeType.Query); (<QueryNode>nodes[0]).nodes.forEach((node, i) => { assert.equal(node._type, types[i], input.substring(node.start, node.end)); }); assert.equal((<QueryNode>nodes[0]).nodes.length, types.length); } function parseAndFlatten(input: string) { const parser = new Parser(); const query = parser.parse(input); const nodes: NodeType[] = []; Utils.walk(query, node => nodes.push(node._type)); return nodes.slice(1); } function assertNodeTypesDeep(input: string, ...types: NodeType[]) { const actual = parseAndFlatten(input); assert.deepEqual(actual, types, input); } function assertVariableValueNodeTypesDeep(input: string, ...types: NodeType[]) { const actual = parseAndFlatten(input); assert.deepEqual(actual.slice(0, 3), [NodeType.VariableDefinition, NodeType.VariableName, NodeType.Query]); assert.deepEqual(actual.slice(3), types, input); } test('QualifiedValue', function () { assertNodeTypes('label:foo', NodeType.QualifiedValue); assertNodeTypes('label:"foo bar"', NodeType.QualifiedValue); assertNodeTypes('-label:foo', NodeType.QualifiedValue); assertNodeTypes('label:foo,bar', NodeType.QualifiedValue); assertNodeTypes('label:"foo",bar,bazz', NodeType.QualifiedValue); assertNodeTypes('label:"foo",bar,"baz,z"', NodeType.QualifiedValue); assertNodeTypes('label:>=12', NodeType.QualifiedValue); assertNodeTypes('label:>12', NodeType.QualifiedValue); assertNodeTypes('label:<12', NodeType.QualifiedValue); assertNodeTypes('label:<=12', NodeType.QualifiedValue); assertNodeTypes('label:*..12', NodeType.QualifiedValue); assertNodeTypes('label:12..*', NodeType.QualifiedValue); assertNodeTypes('label:12..23', NodeType.QualifiedValue); }); test('VariableDefinition', function () { assertVariableValueNodeTypesDeep('$a=label:bug', NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); // Ignore any whitespace around '=' sign. assertVariableValueNodeTypesDeep('$a =value', NodeType.Literal); assertVariableValueNodeTypesDeep('$a= value', NodeType.Literal); assertVariableValueNodeTypesDeep('$a = value', NodeType.Literal); assertVariableValueNodeTypesDeep('$a\t=value', NodeType.Literal); assertVariableValueNodeTypesDeep('$a=\tvalue', NodeType.Literal); assertVariableValueNodeTypesDeep('$a\t=\tvalue', NodeType.Literal); assertVariableValueNodeTypesDeep('$a=foo bar', NodeType.Literal, NodeType.Literal); assertVariableValueNodeTypesDeep('$a=foo label:bar', NodeType.Literal, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertVariableValueNodeTypesDeep('$a=label:foo bar', NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal, NodeType.Literal); assertVariableValueNodeTypesDeep('$a=label:foo bar NOT buzz', NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal, NodeType.Literal, NodeType.Any, NodeType.Literal); assertVariableValueNodeTypesDeep('$a=label:foo label:bar', NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); }); test('Sequence', function () { assertNodeTypes('label: foo', NodeType.QualifiedValue, NodeType.Literal); assertNodeTypes('label:foo bar', NodeType.QualifiedValue, NodeType.Literal); assertNodeTypes('label:foo,bar bar', NodeType.QualifiedValue, NodeType.Literal); assertNodeTypes('label:foo bar NOT bazz', NodeType.QualifiedValue, NodeType.Literal, NodeType.Any, NodeType.Literal); assertNodeTypes('label:foo bar 0cafecafe bazz', NodeType.QualifiedValue, NodeType.Literal, NodeType.Any, NodeType.Literal); // assertNodeTypes('comments:>=10 \n$bar=label:bug', NodeType.QualifiedValue, NodeType.VariableDefinition); }); test('Sequence (deep)', function () { assertNodeTypesDeep('label: foo', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Missing, NodeType.Literal); assertNodeTypesDeep('label:foo', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('label:foo,bar', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.LiteralSequence, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('label:123', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Number); assertNodeTypesDeep('label:"123"', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('label:"foo bar"', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('"label":foo', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('-label:"foo"', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('label:foo bar NOT bazz', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal, NodeType.Literal, NodeType.Any, NodeType.Literal); assertNodeTypesDeep('label:cafecafe bazz', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Any, NodeType.Literal); assertNodeTypesDeep('label:"sss" dd"', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal, NodeType.Literal, NodeType.Any); assertNodeTypesDeep('$BUG=label:bug', NodeType.VariableDefinition, NodeType.VariableName, NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('$a=label:bug', NodeType.VariableDefinition, NodeType.VariableName, NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); assertNodeTypesDeep('foo OR BAR', NodeType.OrExpression, NodeType.Query, NodeType.Literal, NodeType.Query, NodeType.Literal); assertNodeTypesDeep('foo //nothing', NodeType.Query, NodeType.Literal); }); test('Query with sortby', function () { assertNodeTypes('label:foo sort:comments-asc', NodeType.QualifiedValue, NodeType.QualifiedValue); assertNodeTypes('label:foo sort:comments-asc sortby', NodeType.QualifiedValue, NodeType.QualifiedValue, NodeType.Literal); assertNodeTypesDeep('label:123 sort:comments-asc', NodeType.Query, NodeType.QualifiedValue, NodeType.Literal, NodeType.Number, NodeType.QualifiedValue, NodeType.Literal, NodeType.Literal); }); test('Bad diagnostics on my milestone query #35', function () { assertNodeTypes('milestone:4.7.0', NodeType.QualifiedValue); }); }); suite('Print Nodes', function () { function assertPrinted(text: string, expected: string[] = [text], values = new Map<string, string>()) { const query = new Parser().parse(text); const actual: string[] = []; Utils.walk(query, node => { if (node._type === NodeType.Query) { actual.push(Utils.print(node, text, name => values.get(name))); } }); assert.deepEqual(actual, expected); } test('simple', function () { assertPrinted('label:bug'); assertPrinted('label:bug,foo'); assertPrinted('-label:bug'); assertPrinted('-label:bug,bar'); assertPrinted('assignee:@me'); assertPrinted('comments:10..20'); assertPrinted('comments:10..*'); assertPrinted('comments:*..20'); assertPrinted('created:>=2020-03-22'); assertPrinted('foo NOT bar'); assertPrinted('foo NOT bar //comment', ['foo NOT bar']); }); test('print bogous nodes', function () { assertPrinted('label:bug'); assertPrinted('label:bug123'); assertPrinted('label=bug'); assertPrinted('label=bug foo=b#ar'); assertPrinted('label=bug foo=2020-04-19ar'); }); test('or-expression', function () { assertPrinted('label:bug OR label:foo', ['label:bug', 'label:foo']); assertPrinted('label:bug OR label:foo OR label:"123"', ['label:bug', 'label:foo', 'label:"123"']); assertPrinted('label:bug OR'); assertPrinted('OR label:bug'); assertPrinted('aaa OR bbb', ['aaa', 'bbb']); assertPrinted('aaa or bbb', ['aaa or bbb']); }); test('variables', function () { assertPrinted('label:$zzz', ['label:xxx'], new Map([['$zzz', 'xxx']])); assertPrinted('label:$zzz', ['label:$zzz'], new Map()); assertPrinted('label:$zzz OR foo $zzz', ['label:xxx', 'foo xxx'], new Map([['$zzz', 'xxx']])); }); test('GH Samples', function () { // all from https://help.github.com/en/github/searching-for-information-on-github/understanding-the-search-syntax assertPrinted('cats stars:>1000'); assertPrinted('cats topics:>=5'); assertPrinted('cats size:<10000'); assertPrinted('cats stars:<=50'); assertPrinted('cats stars:10..*'); assertPrinted('cats stars:*..10'); assertPrinted('cats stars:10..50'); assertPrinted('cats created:>2016-04-29'); assertPrinted('cats created:>=2017-04-01'); assertPrinted('cats pushed:<2012-07-05'); assertPrinted('cats created:<=2012-07-04'); assertPrinted('cats pushed:2016-04-30..2016-07-04'); assertPrinted('cats created:2012-04-30..*'); assertPrinted('cats created:*..2012-04-30'); assertPrinted('cats created:2017-01-01T01:00:00+07:00..2017-03-01T15:30:15+07:00'); assertPrinted('cats created:2016-03-21T14:11:00Z..2016-04-07T20:45:00Z'); assertPrinted('hello NOT world'); assertPrinted('cats stars:>10 -language:javascript'); assertPrinted('mentions:defunkt -org:github'); assertPrinted('cats NOT "hello world"'); assertPrinted('build label:"bug fix"'); assertPrinted('author:nat'); assertPrinted('is:issue assignee:@me'); }); test('GH Samples 2', function () { // https://help.github.com/en/github/searching-for-information-on-github/searching-issues-and-pull-requests // USE [...document.querySelectorAll('a[href*="https://github.com/search?"]')].map(a => a.textContent).join('\n') assertPrinted('cat type:pr'); assertPrinted('github commenter:defunkt type:issue'); assertPrinted('warning in:title'); assertPrinted('error in:title,body'); assertPrinted('shipit in:comments'); assertPrinted('user:defunkt ubuntu'); assertPrinted('org:github'); assertPrinted('repo:mozilla/shumway created:<2012-03-01'); assertPrinted('performance is:open is:issue'); assertPrinted('is:public'); assertPrinted('is:private cupcake'); assertPrinted('cool author:gjtorikian'); assertPrinted('bootstrap in:body author:mdo'); assertPrinted('author:app/robot'); assertPrinted('resque mentions:defunkt'); assertPrinted('involves:defunkt involves:jlord'); assertPrinted('NOT bootstrap in:body involves:mdo'); assertPrinted('repo:desktop/desktop is:open linked:pr'); assertPrinted('repo:desktop/desktop is:closed linked:issue'); assertPrinted('repo:desktop/desktop is:open -linked:pr'); assertPrinted('repo:desktop/desktop is:open -linked:issue'); assertPrinted('broken in:body -label:bug label:priority'); assertPrinted('e1109ab'); assertPrinted('0eff326d6213c is:merged'); assertPrinted('language:ruby state:open'); assertPrinted('state:closed comments:>100'); assertPrinted('comments:500..1000'); assertPrinted('interactions:>2000'); assertPrinted('interactions:500..1000'); assertPrinted('reactions:>1000'); assertPrinted('reactions:500..1000'); assertPrinted('draft:true'); assertPrinted('draft:false'); assertPrinted('type:pr team-review-requested:atom/design'); assertPrinted('language:c# created:<2011-01-01 state:open'); assertPrinted('weird in:body updated:>=2013-02-01'); assertPrinted('language:swift closed:>2014-06-11'); assertPrinted('language:javascript merged:<2011-01-01'); assertPrinted('fast in:title language:ruby merged:>=2014-05-01'); assertPrinted('archived:true GNOME'); assertPrinted('archived:false GNOME'); assertPrinted('code of conduct is:locked is:issue archived:false'); assertPrinted('code of conduct is:unlocked is:issue archived:false'); assertPrinted('priority no:label'); assertPrinted('sprint no:milestone type:issue'); assertPrinted('important no:assignee language:java type:issue'); }); test('Show Error/Warning when the query is invalid #24', function () { // https://github.com/microsoft/vscode-github-issue-notebooks/issues/24 assertPrinted('fooBar -assignee:@me sort:created-asc'); assertPrinted('fooBar sort asc by created -assignee:@me'); }); });
the_stack